{"version":3,"file":"vega-lite.min.js","sources":["../src/logical.ts","../src/util.ts","../src/channel.ts","../src/aggregate.ts","../src/bin.ts","../src/expr.ts","../src/title.ts","../src/vega.schema.ts","../src/compile/common.ts","../src/log/message.ts","../src/log/index.ts","../src/datetime.ts","../src/timeunit.ts","../src/predicate.ts","../src/type.ts","../src/scale.ts","../src/mark.ts","../src/compile/invalid/normalizeInvalidDataMode.ts","../src/compile/invalid/ScaleInvalidDataMode.ts","../src/compile/mark/encode/scaledZeroOrMinOrMax.ts","../src/compile/mark/encode/invalid.ts","../src/invalid.ts","../src/compile/mark/encode/valueref.ts","../src/compile/format.ts","../src/sort.ts","../src/spec/facet.ts","../src/channeldef.ts","../src/axis.ts","../src/spec/unit.ts","../src/compositemark/base.ts","../src/encoding.ts","../src/compositemark/common.ts","../src/compositemark/boxplot.ts","../src/compositemark/errorbar.ts","../src/compositemark/errorband.ts","../src/compositemark/index.ts","../src/guide.ts","../src/header.ts","../src/legend.ts","../src/selection.ts","../src/parameter.ts","../src/spec/concat.ts","../src/spec/base.ts","../src/config.ts","../src/spec/layer.ts","../src/spec/map.ts","../src/spec/repeat.ts","../src/stack.ts","../src/compile/mark/init.ts","../src/normalize/pathoverlay.ts","../src/normalize/repeater.ts","../src/normalize/ruleforrangedline.ts","../src/normalize/core.ts","../src/transform.ts","../src/normalize/selectioncompat.ts","../src/normalize/toplevelselection.ts","../src/normalize/index.ts","../src/spec/toplevel.ts","../src/compile/split.ts","../src/compile/data/index.ts","../src/data.ts","../src/compile/invalid/datasources.ts","../src/compile/selection/assemble.ts","../src/compile/data/dataflow.ts","../src/compile/data/timeunit.ts","../src/compile/selection/project.ts","../src/compile/selection/scales.ts","../src/compile/selection/interval.ts","../src/compile/selection/point.ts","../src/compile/mark/encode/conditional.ts","../src/compile/mark/encode/text.ts","../src/compile/mark/encode/tooltip.ts","../src/compile/mark/encode/aria.ts","../src/compile/mark/encode/nonposition.ts","../src/compile/mark/encode/color.ts","../src/compile/mark/encode/zindex.ts","../src/compile/mark/encode/offset.ts","../src/compile/mark/encode/position-point.ts","../src/compile/mark/encode/position-align.ts","../src/compile/mark/encode/position-range.ts","../src/compile/mark/encode/position-rect.ts","../src/compile/mark/encode/base.ts","../src/compile/mark/encode/defined.ts","../src/compile/selection/nearest.ts","../src/compile/selection/inputs.ts","../src/compile/selection/toggle.ts","../src/compile/selection/clear.ts","../src/compile/selection/legends.ts","../src/compile/selection/translate.ts","../src/compile/selection/zoom.ts","../src/compile/selection/index.ts","../src/compile/data/expressions.ts","../src/compile/data/filter.ts","../src/compile/selection/parse.ts","../src/compile/predicate.ts","../src/compile/axis/assemble.ts","../src/compile/axis/config.ts","../src/compile/axis/properties.ts","../src/compile/data/calculate.ts","../src/compile/header/common.ts","../src/compile/header/component.ts","../src/compile/header/assemble.ts","../src/compile/layoutsize/assemble.ts","../src/compile/layoutsize/component.ts","../src/compile/guide.ts","../src/compile/resolve.ts","../src/compile/legend/component.ts","../src/compile/legend/encode.ts","../src/compile/legend/properties.ts","../src/compile/legend/parse.ts","../src/compile/legend/assemble.ts","../src/compile/projection/assemble.ts","../src/projection.ts","../src/compile/projection/component.ts","../src/compile/projection/parse.ts","../src/compile/data/bin.ts","../src/compile/data/aggregate.ts","../src/compile/data/facet.ts","../src/compile/data/formatparse.ts","../src/compile/data/identifier.ts","../src/compile/data/graticule.ts","../src/compile/data/sequence.ts","../src/compile/data/source.ts","../src/compile/data/optimizer.ts","../src/compile/data/optimizers.ts","../src/compile/data/joinaggregate.ts","../src/compile/data/filterinvalid.ts","../src/compile/data/stack.ts","../src/compile/data/window.ts","../src/compile/data/subtree.ts","../src/compile/data/optimize.ts","../src/compile/signal.ts","../src/compile/scale/domain.ts","../src/compile/scale/assemble.ts","../src/compile/scale/component.ts","../src/compile/scale/range.ts","../src/compile/scale/properties.ts","../src/compile/scale/type.ts","../src/compile/scale/parse.ts","../src/compile/model.ts","../src/compile/data/density.ts","../src/compile/data/extent.ts","../src/compile/data/flatten.ts","../src/compile/data/fold.ts","../src/compile/data/geojson.ts","../src/compile/data/geopoint.ts","../src/compile/data/impute.ts","../src/compile/data/loess.ts","../src/compile/data/lookup.ts","../src/compile/data/quantile.ts","../src/compile/data/regression.ts","../src/compile/data/pivot.ts","../src/compile/data/sample.ts","../src/compile/data/assemble.ts","../src/compile/header/parse.ts","../src/compile/layoutsize/parse.ts","../src/compile/facet.ts","../src/compile/data/parse.ts","../src/compile/data/joinaggregatefacet.ts","../src/compile/concat.ts","../src/compile/axis/component.ts","../src/compile/axis/parse.ts","../src/compile/axis/encode.ts","../src/compile/mark/point.ts","../src/compile/mark/rule.ts","../src/compile/mark/text.ts","../src/compile/mark/tick.ts","../src/compile/mark/mark.ts","../src/compile/mark/arc.ts","../src/compile/mark/area.ts","../src/compile/mark/bar.ts","../src/compile/mark/geoshape.ts","../src/compile/mark/image.ts","../src/compile/mark/line.ts","../src/compile/mark/rect.ts","../src/compile/unit.ts","../src/compile/layoutsize/init.ts","../src/compile/layer.ts","../src/compile/buildmodel.ts","../src/index.ts","../src/compile/compile.ts"],"sourcesContent":["export type LogicalComposition = LogicalNot | LogicalAnd | LogicalOr | T;\n\nexport interface LogicalOr {\n or: LogicalComposition[];\n}\n\nexport interface LogicalAnd {\n and: LogicalComposition[];\n}\n\nexport interface LogicalNot {\n not: LogicalComposition;\n}\n\nexport function isLogicalOr(op: LogicalComposition): op is LogicalOr {\n return !!op.or;\n}\n\nexport function isLogicalAnd(op: LogicalComposition): op is LogicalAnd {\n return !!op.and;\n}\n\nexport function isLogicalNot(op: LogicalComposition): op is LogicalNot {\n return !!op.not;\n}\n\nexport function forEachLeaf(op: LogicalComposition, fn: (op: T) => void) {\n if (isLogicalNot(op)) {\n forEachLeaf(op.not, fn);\n } else if (isLogicalAnd(op)) {\n for (const subop of op.and) {\n forEachLeaf(subop, fn);\n }\n } else if (isLogicalOr(op)) {\n for (const subop of op.or) {\n forEachLeaf(subop, fn);\n }\n } else {\n fn(op);\n }\n}\n\nexport function normalizeLogicalComposition(\n op: LogicalComposition,\n normalizer: (o: T) => T\n): LogicalComposition {\n if (isLogicalNot(op)) {\n return {not: normalizeLogicalComposition(op.not, normalizer)};\n } else if (isLogicalAnd(op)) {\n return {and: op.and.map(o => normalizeLogicalComposition(o, normalizer))};\n } else if (isLogicalOr(op)) {\n return {or: op.or.map(o => normalizeLogicalComposition(o, normalizer))};\n } else {\n return normalizer(op);\n }\n}\n","import {hasOwnProperty, isNumber, isString, splitAccessPath, stringValue, writeConfig} from 'vega-util';\nimport {isLogicalAnd, isLogicalNot, isLogicalOr, LogicalComposition} from './logical';\n\nexport const duplicate = structuredClone;\n\nexport function never(message: string): never {\n throw new Error(message);\n}\n\n/**\n * Creates an object composed of the picked object properties.\n *\n * var object = {'a': 1, 'b': '2', 'c': 3};\n * pick(object, ['a', 'c']);\n * // → {'a': 1, 'c': 3}\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function pick(obj: T, props: readonly K[]): Pick {\n const copy: any = {};\n for (const prop of props) {\n if (hasOwnProperty(obj, prop)) {\n copy[prop] = obj[prop];\n }\n }\n return copy;\n}\n\n/**\n * The opposite of _.pick; this method creates an object composed of the own\n * and inherited enumerable string keyed properties of object that are not omitted.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function omit(obj: T, props: readonly K[]): Omit {\n const copy = {...(obj as any)};\n for (const prop of props) {\n delete copy[prop];\n }\n return copy;\n}\n\n/**\n * Monkey patch Set so that `stringify` produces a string representation of sets.\n */\nSet.prototype['toJSON'] = function () {\n return `Set(${[...this].map(x => stringify(x)).join(',')})`;\n};\n\n/**\n * Converts any object to a string of limited size, or a number.\n */\nexport function hash(a: any): string | number {\n if (isNumber(a)) {\n return a;\n }\n\n const str = isString(a) ? a : stringify(a);\n\n // short strings can be used as hash directly, longer strings are hashed to reduce memory usage\n if (str.length < 250) {\n return str;\n }\n\n // from http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/\n let h = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n h = (h << 5) - h + char;\n h = h & h; // Convert to 32bit integer\n }\n return h;\n}\n\nexport function isNullOrFalse(x: any): x is false | null {\n return x === false || x === null;\n}\n\nexport function contains(array: readonly T[], item: T) {\n return array.includes(item);\n}\n\n/**\n * Returns true if any item returns true.\n */\nexport function some(arr: readonly T[], f: (d: T, k?: any, i?: any) => boolean) {\n let i = 0;\n for (const [k, a] of arr.entries()) {\n if (f(a, k, i++)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Returns true if all items return true.\n */\nexport function every(arr: readonly T[], f: (d: T, k?: any, i?: any) => boolean) {\n let i = 0;\n for (const [k, a] of arr.entries()) {\n if (!f(a, k, i++)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Like TS Partial but applies recursively to all properties.\n */\nexport type DeepPartial = {[P in keyof T]?: DeepPartial};\n\n/**\n * recursively merges src into dest\n */\nexport function mergeDeep(dest: T, ...src: readonly DeepPartial[]): T {\n for (const s of src) {\n deepMerge_(dest, s ?? {});\n }\n return dest;\n}\n\nfunction deepMerge_(dest: any, src: any) {\n for (const property of keys(src)) {\n writeConfig(dest, property, src[property], true);\n }\n}\n\nexport function unique(values: readonly T[], f: (item: T) => string | number): T[] {\n const results: T[] = [];\n const u = {};\n let v: string | number;\n for (const val of values) {\n v = f(val);\n if (v in u) {\n continue;\n }\n u[v] = 1;\n results.push(val);\n }\n return results;\n}\n\nexport type Dict = Record;\n\n/**\n * Returns true if the two dictionaries agree. Applies only to defined values.\n */\nexport function isEqual(dict: Dict, other: Dict) {\n const dictKeys = keys(dict);\n const otherKeys = keys(other);\n if (dictKeys.length !== otherKeys.length) {\n return false;\n }\n for (const key of dictKeys) {\n if (dict[key] !== other[key]) {\n return false;\n }\n }\n return true;\n}\n\nexport function setEqual(a: Set, b: Set) {\n if (a.size !== b.size) {\n return false;\n }\n for (const e of a) {\n if (!b.has(e)) {\n return false;\n }\n }\n return true;\n}\n\nexport function hasIntersection(a: ReadonlySet, b: ReadonlySet) {\n for (const key of a) {\n if (b.has(key)) {\n return true;\n }\n }\n return false;\n}\n\nexport function prefixGenerator(a: ReadonlySet): ReadonlySet {\n const prefixes = new Set();\n for (const x of a) {\n const splitField = splitAccessPath(x);\n // Wrap every element other than the first in `[]`\n const wrappedWithAccessors = splitField.map((y, i) => (i === 0 ? y : `[${y}]`));\n const computedPrefixes = wrappedWithAccessors.map((_, i) => wrappedWithAccessors.slice(0, i + 1).join(''));\n for (const y of computedPrefixes) {\n prefixes.add(y);\n }\n }\n return prefixes;\n}\n\n/**\n * Returns true if a and b have an intersection. Also return true if a or b are undefined\n * since this means we don't know what fields a node produces or depends on.\n */\nexport function fieldIntersection(a: ReadonlySet, b: ReadonlySet): boolean {\n if (a === undefined || b === undefined) {\n return true;\n }\n return hasIntersection(prefixGenerator(a), prefixGenerator(b));\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isEmpty(obj: object) {\n return keys(obj).length === 0;\n}\n\n// This is a stricter version of Object.keys but with better types. See https://github.com/Microsoft/TypeScript/pull/12253#issuecomment-263132208\nexport const keys = Object.keys as (o: T) => Extract[];\n\nexport const vals = Object.values;\n\nexport const entries = Object.entries;\n\n// Using mapped type to declare a collect of flags for a string literal type S\n// https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types\nexport type Flag = {[K in S]: 1};\n\nexport function isBoolean(b: any): b is boolean {\n return b === true || b === false;\n}\n\n/**\n * Convert a string into a valid variable name\n */\nexport function varName(s: string): string {\n // Replace non-alphanumeric characters (anything besides a-zA-Z0-9_) with _\n const alphanumericS = s.replace(/\\W/g, '_');\n\n // Add _ if the string has leading numbers.\n return (s.match(/^\\d+/) ? '_' : '') + alphanumericS;\n}\n\nexport function logicalExpr(op: LogicalComposition, cb: (...args: readonly any[]) => string): string {\n if (isLogicalNot(op)) {\n return `!(${logicalExpr(op.not, cb)})`;\n } else if (isLogicalAnd(op)) {\n return `(${op.and.map((and: LogicalComposition) => logicalExpr(and, cb)).join(') && (')})`;\n } else if (isLogicalOr(op)) {\n return `(${op.or.map((or: LogicalComposition) => logicalExpr(or, cb)).join(') || (')})`;\n } else {\n return cb(op);\n }\n}\n\n/**\n * Delete nested property of an object, and delete the ancestors of the property if they become empty.\n */\nexport function deleteNestedProperty(obj: any, orderedProps: string[]) {\n if (orderedProps.length === 0) {\n return true;\n }\n const prop = orderedProps.shift()!; // eslint-disable-line @typescript-eslint/no-non-null-assertion\n if (prop in obj && deleteNestedProperty(obj[prop], orderedProps)) {\n delete obj[prop];\n }\n return isEmpty(obj);\n}\n\nexport function titleCase(s: string) {\n return s.charAt(0).toUpperCase() + s.substr(1);\n}\n\n/**\n * Converts a path to an access path with datum.\n * @param path The field name.\n * @param datum The string to use for `datum`.\n */\nexport function accessPathWithDatum(path: string, datum = 'datum') {\n const pieces = splitAccessPath(path);\n const prefixes = [];\n for (let i = 1; i <= pieces.length; i++) {\n const prefix = `[${pieces.slice(0, i).map(stringValue).join('][')}]`;\n prefixes.push(`${datum}${prefix}`);\n }\n return prefixes.join(' && ');\n}\n\n/**\n * Return access with datum to the flattened field.\n *\n * @param path The field name.\n * @param datum The string to use for `datum`.\n */\nexport function flatAccessWithDatum(path: string, datum: 'datum' | 'parent' | 'datum.datum' = 'datum') {\n return `${datum}[${stringValue(splitAccessPath(path).join('.'))}]`;\n}\n\nfunction escapePathAccess(string: string) {\n return string.replace(/(\\[|\\]|\\.|'|\")/g, '\\\\$1');\n}\n\n/**\n * Replaces path accesses with access to non-nested field.\n * For example, `foo[\"bar\"].baz` becomes `foo\\\\.bar\\\\.baz`.\n */\nexport function replacePathInField(path: string) {\n return `${splitAccessPath(path).map(escapePathAccess).join('\\\\.')}`;\n}\n\n/**\n * Replace all occurrences of a string with another string.\n *\n * @param string the string to replace in\n * @param find the string to replace\n * @param replacement the replacement\n */\nexport function replaceAll(string: string, find: string, replacement: string) {\n return string.replace(new RegExp(find.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'), 'g'), replacement);\n}\n\n/**\n * Remove path accesses with access from field.\n * For example, `foo[\"bar\"].baz` becomes `foo.bar.baz`.\n */\nexport function removePathFromField(path: string) {\n return `${splitAccessPath(path).join('.')}`;\n}\n\n/**\n * Count the depth of the path. Returns 1 for fields that are not nested.\n */\nexport function accessPathDepth(path: string) {\n if (!path) {\n return 0;\n }\n return splitAccessPath(path).length;\n}\n\n/**\n * This is a replacement for chained || for numeric properties or properties that respect null so that 0 will be included.\n */\nexport function getFirstDefined(...args: readonly T[]): T | undefined {\n for (const arg of args) {\n if (arg !== undefined) {\n return arg;\n }\n }\n return undefined;\n}\n\n// variable used to generate id\nlet idCounter = 42;\n\n/**\n * Returns a new random id every time it gets called.\n *\n * Has side effect!\n */\nexport function uniqueId(prefix?: string) {\n const id = ++idCounter;\n return prefix ? String(prefix) + id : id;\n}\n\n/**\n * Resets the id counter used in uniqueId. This can be useful for testing.\n */\nexport function resetIdCounter() {\n idCounter = 42;\n}\n\nexport function internalField(name: string) {\n return isInternalField(name) ? name : `__${name}`;\n}\n\nexport function isInternalField(name: string) {\n return name.startsWith('__');\n}\n\n/**\n * Normalize angle to be within [0,360).\n */\nexport function normalizeAngle(angle: number) {\n if (angle === undefined) {\n return undefined;\n }\n return ((angle % 360) + 360) % 360;\n}\n\n/**\n * Returns whether the passed in value is a valid number.\n */\nexport function isNumeric(value: number | string): boolean {\n if (isNumber(value)) {\n return true;\n }\n return !isNaN(value as any) && !isNaN(parseFloat(value));\n}\n\nconst clonedProto = Object.getPrototypeOf(structuredClone({}));\n\n/**\n * Compares two values for equality, including arrays and objects.\n *\n * Adapted from https://github.com/epoberezkin/fast-deep-equal.\n */\nexport function deepEqual(a: any, b: any) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n // compare names to avoid issues with structured clone\n if (a.constructor.name !== b.constructor.name) return false;\n\n let length;\n let i;\n\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0; ) if (!deepEqual(a[i], b[i])) return false;\n return true;\n }\n\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size) return false;\n for (i of a.entries()) if (!b.has(i[0])) return false;\n for (i of a.entries()) if (!deepEqual(i[1], b.get(i[0]))) return false;\n return true;\n }\n\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size) return false;\n for (i of a.entries()) if (!b.has(i[0])) return false;\n return true;\n }\n\n if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n length = (a as any).length;\n if (length != (b as any).length) return false;\n for (i = length; i-- !== 0; ) if (a[i] !== b[i]) return false;\n return true;\n }\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n // also compare to structured clone prototype\n if (a.valueOf !== Object.prototype.valueOf && a.valueOf !== clonedProto.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString && a.toString !== clonedProto.toString)\n return a.toString() === b.toString();\n\n const ks = Object.keys(a);\n length = ks.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b, ks[i])) return false;\n\n for (i = length; i-- !== 0; ) {\n const key = ks[i];\n\n if (!deepEqual(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a !== a && b !== b;\n}\n\n/**\n * Converts any object to a string representation that can be consumed by humans.\n *\n * Adapted from https://github.com/epoberezkin/fast-json-stable-stringify\n */\nexport function stringify(data: any) {\n const seen: any[] = [];\n\n return (function _stringify(node: any) {\n if (node && node.toJSON && typeof node.toJSON === 'function') {\n node = node.toJSON();\n }\n\n if (node === undefined) return undefined;\n if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';\n if (typeof node !== 'object') return JSON.stringify(node);\n\n let i, out;\n if (Array.isArray(node)) {\n out = '[';\n for (i = 0; i < node.length; i++) {\n if (i) out += ',';\n out += _stringify(node[i]) || 'null';\n }\n return out + ']';\n }\n\n if (node === null) return 'null';\n\n if (seen.includes(node)) {\n throw new TypeError('Converting circular structure to JSON');\n }\n\n const seenIndex = seen.push(node) - 1;\n const ks = Object.keys(node).sort();\n out = '';\n for (i = 0; i < ks.length; i++) {\n const key = ks[i];\n const value = _stringify(node[key]);\n\n if (!value) continue;\n if (out) out += ',';\n out += JSON.stringify(key) + ':' + value;\n }\n seen.splice(seenIndex, 1);\n return `{${out}}`;\n })(data);\n}\n","/*\n * Constants and utilities for encoding channels (Visual variables)\n * such as 'x', 'y', 'color'.\n */\n\nimport {RangeType} from './compile/scale/type';\nimport {Encoding} from './encoding';\nimport {Mark} from './mark';\nimport {EncodingFacetMapping} from './spec/facet';\nimport {Flag, keys} from './util';\n\nexport type Channel = keyof Encoding;\nexport type ExtendedChannel = Channel | FacetChannel;\n\n// Facet\nexport const ROW = 'row' as const;\nexport const COLUMN = 'column' as const;\n\nexport const FACET = 'facet' as const;\n\n// Position\nexport const X = 'x' as const;\nexport const Y = 'y' as const;\nexport const X2 = 'x2' as const;\nexport const Y2 = 'y2' as const;\n\n// Position Offset\nexport const XOFFSET = 'xOffset' as const;\nexport const YOFFSET = 'yOffset' as const;\n\n// Arc-Position\nexport const RADIUS = 'radius' as const;\nexport const RADIUS2 = 'radius2' as const;\nexport const THETA = 'theta' as const;\nexport const THETA2 = 'theta2' as const;\n\n// Geo Position\nexport const LATITUDE = 'latitude' as const;\nexport const LONGITUDE = 'longitude' as const;\nexport const LATITUDE2 = 'latitude2' as const;\nexport const LONGITUDE2 = 'longitude2' as const;\n\n// Mark property with scale\nexport const COLOR = 'color' as const;\n\nexport const FILL = 'fill' as const;\n\nexport const STROKE = 'stroke' as const;\n\nexport const SHAPE = 'shape' as const;\nexport const SIZE = 'size' as const;\n\nexport const ANGLE = 'angle' as const;\n\nexport const OPACITY = 'opacity' as const;\nexport const FILLOPACITY = 'fillOpacity' as const;\n\nexport const STROKEOPACITY = 'strokeOpacity' as const;\n\nexport const STROKEWIDTH = 'strokeWidth' as const;\nexport const STROKEDASH = 'strokeDash' as const;\n\n// Non-scale channel\nexport const TEXT = 'text' as const;\nexport const ORDER = 'order' as const;\nexport const DETAIL = 'detail' as const;\nexport const KEY = 'key' as const;\n\nexport const TOOLTIP = 'tooltip' as const;\nexport const HREF = 'href' as const;\n\nexport const URL = 'url' as const;\nexport const DESCRIPTION = 'description' as const;\n\nconst POSITION_CHANNEL_INDEX = {\n x: 1,\n y: 1,\n x2: 1,\n y2: 1\n} as const;\n\nexport type PositionChannel = keyof typeof POSITION_CHANNEL_INDEX;\n\nconst POLAR_POSITION_CHANNEL_INDEX = {\n theta: 1,\n theta2: 1,\n radius: 1,\n radius2: 1\n} as const;\n\nexport type PolarPositionChannel = keyof typeof POLAR_POSITION_CHANNEL_INDEX;\n\nexport function isPolarPositionChannel(c: Channel): c is PolarPositionChannel {\n return c in POLAR_POSITION_CHANNEL_INDEX;\n}\n\nconst GEO_POSIITON_CHANNEL_INDEX = {\n longitude: 1,\n longitude2: 1,\n latitude: 1,\n latitude2: 1\n} as const;\n\nexport type GeoPositionChannel = keyof typeof GEO_POSIITON_CHANNEL_INDEX;\n\nexport function getPositionChannelFromLatLong(channel: GeoPositionChannel): PositionChannel {\n switch (channel) {\n case LATITUDE:\n return 'y';\n case LATITUDE2:\n return 'y2';\n case LONGITUDE:\n return 'x';\n case LONGITUDE2:\n return 'x2';\n }\n}\n\nexport function isGeoPositionChannel(c: Channel): c is GeoPositionChannel {\n return c in GEO_POSIITON_CHANNEL_INDEX;\n}\n\nexport const GEOPOSITION_CHANNELS = keys(GEO_POSIITON_CHANNEL_INDEX);\n\nconst UNIT_CHANNEL_INDEX: Flag = {\n ...POSITION_CHANNEL_INDEX,\n ...POLAR_POSITION_CHANNEL_INDEX,\n\n ...GEO_POSIITON_CHANNEL_INDEX,\n xOffset: 1,\n yOffset: 1,\n\n // color\n color: 1,\n fill: 1,\n stroke: 1,\n\n // other non-position with scale\n opacity: 1,\n fillOpacity: 1,\n strokeOpacity: 1,\n\n strokeWidth: 1,\n strokeDash: 1,\n size: 1,\n angle: 1,\n shape: 1,\n\n // channels without scales\n order: 1,\n text: 1,\n detail: 1,\n key: 1,\n tooltip: 1,\n href: 1,\n url: 1,\n description: 1\n};\n\nexport type ColorChannel = 'color' | 'fill' | 'stroke';\n\nexport function isColorChannel(channel: Channel): channel is ColorChannel {\n return channel === COLOR || channel === FILL || channel === STROKE;\n}\n\nexport type FacetChannel = keyof EncodingFacetMapping;\n\nconst FACET_CHANNEL_INDEX: Flag> = {\n row: 1,\n column: 1,\n facet: 1\n};\n\nexport const FACET_CHANNELS = keys(FACET_CHANNEL_INDEX);\n\nconst CHANNEL_INDEX = {\n ...UNIT_CHANNEL_INDEX,\n ...FACET_CHANNEL_INDEX\n};\n\nexport const CHANNELS = keys(CHANNEL_INDEX);\n\nconst {order: _o, detail: _d, tooltip: _tt1, ...SINGLE_DEF_CHANNEL_INDEX} = CHANNEL_INDEX;\nconst {row: _r, column: _c, facet: _f, ...SINGLE_DEF_UNIT_CHANNEL_INDEX} = SINGLE_DEF_CHANNEL_INDEX;\n/**\n * Channels that cannot have an array of channelDef.\n * model.fieldDef, getFieldDef only work for these channels.\n *\n * (The only two channels that can have an array of channelDefs are \"detail\" and \"order\".\n * Since there can be multiple fieldDefs for detail and order, getFieldDef/model.fieldDef\n * are not applicable for them. Similarly, selection projection won't work with \"detail\" and \"order\".)\n */\n\nexport const SINGLE_DEF_CHANNELS = keys(SINGLE_DEF_CHANNEL_INDEX);\n\nexport type SingleDefChannel = (typeof SINGLE_DEF_CHANNELS)[number];\n\nexport const SINGLE_DEF_UNIT_CHANNELS = keys(SINGLE_DEF_UNIT_CHANNEL_INDEX);\n\nexport type SingleDefUnitChannel = (typeof SINGLE_DEF_UNIT_CHANNELS)[number];\n\nexport function isSingleDefUnitChannel(str: string): str is SingleDefUnitChannel {\n return !!SINGLE_DEF_UNIT_CHANNEL_INDEX[str];\n}\n\nexport function isChannel(str: string): str is Channel {\n return !!CHANNEL_INDEX[str];\n}\n\nexport type SecondaryRangeChannel = 'x2' | 'y2' | 'latitude2' | 'longitude2' | 'theta2' | 'radius2';\n\nexport const SECONDARY_RANGE_CHANNEL: SecondaryRangeChannel[] = [X2, Y2, LATITUDE2, LONGITUDE2, THETA2, RADIUS2];\n\nexport function isSecondaryRangeChannel(c: ExtendedChannel): c is SecondaryRangeChannel {\n const main = getMainRangeChannel(c);\n return main !== c;\n}\n\nexport type MainChannelOf = C extends 'x2'\n ? 'x'\n : C extends 'y2'\n ? 'y'\n : C extends 'latitude2'\n ? 'latitude'\n : C extends 'longitude2'\n ? 'longitude'\n : C extends 'theta2'\n ? 'theta'\n : C extends 'radius2'\n ? 'radius'\n : C;\n\n/**\n * Get the main channel for a range channel. E.g. `x` for `x2`.\n */\nexport function getMainRangeChannel(channel: C): MainChannelOf {\n switch (channel) {\n case X2:\n return X as MainChannelOf;\n case Y2:\n return Y as MainChannelOf;\n case LATITUDE2:\n return LATITUDE as MainChannelOf;\n case LONGITUDE2:\n return LONGITUDE as MainChannelOf;\n case THETA2:\n return THETA as MainChannelOf;\n case RADIUS2:\n return RADIUS as MainChannelOf;\n }\n return channel as MainChannelOf;\n}\n\nexport type SecondaryChannelOf = C extends 'x'\n ? 'x2'\n : C extends 'y'\n ? 'y2'\n : C extends 'latitude'\n ? 'latitude2'\n : C extends 'longitude'\n ? 'longitude2'\n : C extends 'theta'\n ? 'theta2'\n : C extends 'radius'\n ? 'radius2'\n : undefined;\n\nexport function getVgPositionChannel(channel: PolarPositionChannel | PositionChannel) {\n if (isPolarPositionChannel(channel)) {\n switch (channel) {\n case THETA:\n return 'startAngle';\n case THETA2:\n return 'endAngle';\n case RADIUS:\n return 'outerRadius';\n case RADIUS2:\n return 'innerRadius';\n }\n }\n return channel;\n}\n\n/**\n * Get the main channel for a range channel. E.g. `x` for `x2`.\n */\nexport function getSecondaryRangeChannel(channel: C): SecondaryChannelOf | undefined {\n switch (channel) {\n case X:\n return X2 as SecondaryChannelOf;\n case Y:\n return Y2 as SecondaryChannelOf;\n case LATITUDE:\n return LATITUDE2 as SecondaryChannelOf;\n case LONGITUDE:\n return LONGITUDE2 as SecondaryChannelOf;\n case THETA:\n return THETA2 as SecondaryChannelOf;\n case RADIUS:\n return RADIUS2 as SecondaryChannelOf;\n }\n return undefined;\n}\n\nexport function getSizeChannel(channel: PositionChannel): 'width' | 'height';\nexport function getSizeChannel(channel: Channel): 'width' | 'height' | undefined;\nexport function getSizeChannel(channel: Channel): 'width' | 'height' | undefined {\n switch (channel) {\n case X:\n case X2:\n return 'width';\n case Y:\n case Y2:\n return 'height';\n }\n return undefined;\n}\n\n/**\n * Get the main channel for a range channel. E.g. `x` for `x2`.\n */\nexport function getOffsetChannel(channel: Channel) {\n switch (channel) {\n case X:\n return 'xOffset';\n case Y:\n return 'yOffset';\n case X2:\n return 'x2Offset';\n case Y2:\n return 'y2Offset';\n case THETA:\n return 'thetaOffset';\n case RADIUS:\n return 'radiusOffset';\n case THETA2:\n return 'theta2Offset';\n case RADIUS2:\n return 'radius2Offset';\n }\n return undefined;\n}\n\n/**\n * Get the main channel for a range channel. E.g. `x` for `x2`.\n */\nexport function getOffsetScaleChannel(channel: Channel): OffsetScaleChannel {\n switch (channel) {\n case X:\n return 'xOffset';\n case Y:\n return 'yOffset';\n }\n return undefined;\n}\n\nexport function getMainChannelFromOffsetChannel(channel: OffsetScaleChannel): PositionScaleChannel {\n switch (channel) {\n case 'xOffset':\n return 'x';\n case 'yOffset':\n return 'y';\n }\n}\n\n// CHANNELS without COLUMN, ROW\nexport const UNIT_CHANNELS = keys(UNIT_CHANNEL_INDEX);\n\n// NONPOSITION_CHANNELS = UNIT_CHANNELS without X, Y, X2, Y2;\nconst {\n x: _x,\n y: _y,\n // x2 and y2 share the same scale as x and y\n x2: _x2,\n y2: _y2,\n //\n xOffset: _xo,\n yOffset: _yo,\n latitude: _latitude,\n longitude: _longitude,\n latitude2: _latitude2,\n longitude2: _longitude2,\n theta: _theta,\n theta2: _theta2,\n radius: _radius,\n radius2: _radius2,\n // The rest of unit channels then have scale\n ...NONPOSITION_CHANNEL_INDEX\n} = UNIT_CHANNEL_INDEX;\n\nexport const NONPOSITION_CHANNELS = keys(NONPOSITION_CHANNEL_INDEX);\nexport type NonPositionChannel = (typeof NONPOSITION_CHANNELS)[number];\n\nconst POSITION_SCALE_CHANNEL_INDEX = {\n x: 1,\n y: 1\n} as const;\nexport const POSITION_SCALE_CHANNELS = keys(POSITION_SCALE_CHANNEL_INDEX);\nexport type PositionScaleChannel = keyof typeof POSITION_SCALE_CHANNEL_INDEX;\n\nexport function isXorY(channel: ExtendedChannel): channel is PositionScaleChannel {\n return channel in POSITION_SCALE_CHANNEL_INDEX;\n}\n\nexport const POLAR_POSITION_SCALE_CHANNEL_INDEX = {\n theta: 1,\n radius: 1\n} as const;\n\nexport const POLAR_POSITION_SCALE_CHANNELS = keys(POLAR_POSITION_SCALE_CHANNEL_INDEX);\nexport type PolarPositionScaleChannel = keyof typeof POLAR_POSITION_SCALE_CHANNEL_INDEX;\n\nexport function getPositionScaleChannel(sizeType: 'width' | 'height'): PositionScaleChannel {\n return sizeType === 'width' ? X : Y;\n}\n\nconst OFFSET_SCALE_CHANNEL_INDEX: {xOffset: 1; yOffset: 1} = {xOffset: 1, yOffset: 1};\n\nexport const OFFSET_SCALE_CHANNELS = keys(OFFSET_SCALE_CHANNEL_INDEX);\n\nexport type OffsetScaleChannel = (typeof OFFSET_SCALE_CHANNELS)[0];\n\nexport function isXorYOffset(channel: Channel): channel is OffsetScaleChannel {\n return channel in OFFSET_SCALE_CHANNEL_INDEX;\n}\n\n// NON_POSITION_SCALE_CHANNEL = SCALE_CHANNELS without position / offset\nconst {\n // x2 and y2 share the same scale as x and y\n // text and tooltip have format instead of scale,\n // href has neither format, nor scale\n text: _t,\n tooltip: _tt,\n href: _hr,\n url: _u,\n description: _al,\n // detail and order have no scale\n detail: _dd,\n key: _k,\n order: _oo,\n ...NONPOSITION_SCALE_CHANNEL_INDEX\n} = NONPOSITION_CHANNEL_INDEX;\nexport const NONPOSITION_SCALE_CHANNELS = keys(NONPOSITION_SCALE_CHANNEL_INDEX);\nexport type NonPositionScaleChannel = (typeof NONPOSITION_SCALE_CHANNELS)[number];\n\nexport function isNonPositionScaleChannel(channel: Channel): channel is NonPositionScaleChannel {\n return !!NONPOSITION_CHANNEL_INDEX[channel];\n}\n\n/**\n * @returns whether Vega supports legends for a particular channel\n */\nexport function supportLegend(channel: NonPositionScaleChannel) {\n switch (channel) {\n case COLOR:\n case FILL:\n case STROKE:\n case SIZE:\n case SHAPE:\n case OPACITY:\n case STROKEWIDTH:\n case STROKEDASH:\n return true;\n case FILLOPACITY:\n case STROKEOPACITY:\n case ANGLE:\n return false;\n }\n}\n\n// Declare SCALE_CHANNEL_INDEX\nconst SCALE_CHANNEL_INDEX = {\n ...POSITION_SCALE_CHANNEL_INDEX,\n ...POLAR_POSITION_SCALE_CHANNEL_INDEX,\n ...OFFSET_SCALE_CHANNEL_INDEX,\n ...NONPOSITION_SCALE_CHANNEL_INDEX\n};\n\n/** List of channels with scales */\nexport const SCALE_CHANNELS = keys(SCALE_CHANNEL_INDEX);\nexport type ScaleChannel = (typeof SCALE_CHANNELS)[number];\n\nexport function isScaleChannel(channel: ExtendedChannel): channel is ScaleChannel {\n return !!SCALE_CHANNEL_INDEX[channel];\n}\n\nexport type SupportedMark = Partial>;\n\n/**\n * Return whether a channel supports a particular mark type.\n * @param channel channel name\n * @param mark the mark type\n * @return whether the mark supports the channel\n */\nexport function supportMark(channel: ExtendedChannel, mark: Mark) {\n return getSupportedMark(channel)[mark];\n}\n\nconst ALL_MARKS: Record = {\n // all marks\n arc: 'always',\n area: 'always',\n bar: 'always',\n circle: 'always',\n geoshape: 'always',\n image: 'always',\n line: 'always',\n rule: 'always',\n point: 'always',\n rect: 'always',\n square: 'always',\n trail: 'always',\n text: 'always',\n tick: 'always'\n};\n\nconst {geoshape: _g, ...ALL_MARKS_EXCEPT_GEOSHAPE} = ALL_MARKS;\n\n/**\n * Return a dictionary showing whether a channel supports mark type.\n * @param channel\n * @return A dictionary mapping mark types to 'always', 'binned', or undefined\n */\nfunction getSupportedMark(channel: ExtendedChannel): SupportedMark {\n switch (channel) {\n case COLOR:\n case FILL:\n case STROKE:\n // falls through\n\n case DESCRIPTION:\n case DETAIL:\n case KEY:\n case TOOLTIP:\n case HREF:\n case ORDER: // TODO: revise (order might not support rect, which is not stackable?)\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n case STROKEWIDTH:\n\n // falls through\n\n case FACET:\n case ROW: // falls through\n case COLUMN:\n return ALL_MARKS;\n case X:\n case Y:\n case XOFFSET:\n case YOFFSET:\n case LATITUDE:\n case LONGITUDE:\n // all marks except geoshape. geoshape does not use X, Y -- it uses a projection\n return ALL_MARKS_EXCEPT_GEOSHAPE;\n case X2:\n case Y2:\n case LATITUDE2:\n case LONGITUDE2:\n return {\n area: 'always',\n bar: 'always',\n image: 'always',\n rect: 'always',\n rule: 'always',\n circle: 'binned',\n point: 'binned',\n square: 'binned',\n tick: 'binned',\n line: 'binned',\n trail: 'binned'\n };\n case SIZE:\n return {\n point: 'always',\n tick: 'always',\n rule: 'always',\n circle: 'always',\n square: 'always',\n bar: 'always',\n text: 'always',\n line: 'always',\n trail: 'always'\n };\n case STROKEDASH:\n return {\n line: 'always',\n point: 'always',\n tick: 'always',\n rule: 'always',\n circle: 'always',\n square: 'always',\n bar: 'always',\n geoshape: 'always'\n };\n case SHAPE:\n return {point: 'always', geoshape: 'always'};\n case TEXT:\n return {text: 'always'};\n case ANGLE:\n return {point: 'always', square: 'always', text: 'always'};\n case URL:\n return {image: 'always'};\n case THETA:\n return {text: 'always', arc: 'always'};\n case RADIUS:\n return {text: 'always', arc: 'always'};\n case THETA2:\n case RADIUS2:\n return {arc: 'always'};\n }\n}\n\nexport function rangeType(channel: ExtendedChannel): RangeType {\n switch (channel) {\n case X:\n case Y:\n case THETA:\n case RADIUS:\n case XOFFSET:\n case YOFFSET:\n case SIZE:\n case ANGLE:\n case STROKEWIDTH:\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n\n // X2 and Y2 use X and Y scales, so they similarly have continuous range. [falls through]\n case X2:\n case Y2:\n case THETA2:\n case RADIUS2:\n return undefined;\n\n case FACET:\n case ROW:\n case COLUMN:\n case SHAPE:\n case STROKEDASH:\n // TEXT, TOOLTIP, URL, and HREF have no scale but have discrete output [falls through]\n case TEXT:\n case TOOLTIP:\n case HREF:\n case URL:\n case DESCRIPTION:\n return 'discrete';\n\n // Color can be either continuous or discrete, depending on scale type.\n case COLOR:\n case FILL:\n case STROKE:\n return 'flexible';\n\n // No scale, no range type.\n\n case LATITUDE:\n case LONGITUDE:\n case LATITUDE2:\n case LONGITUDE2:\n case DETAIL:\n case KEY:\n case ORDER:\n return undefined;\n }\n}\n","import {AggregateOp} from 'vega';\nimport {isString} from 'vega-util';\nimport {FieldName} from './channeldef';\nimport {contains, Flag} from './util';\n\nconst AGGREGATE_OP_INDEX: Flag = {\n argmax: 1,\n argmin: 1,\n average: 1,\n count: 1,\n distinct: 1,\n exponential: 1,\n exponentialb: 1,\n product: 1,\n max: 1,\n mean: 1,\n median: 1,\n min: 1,\n missing: 1,\n q1: 1,\n q3: 1,\n ci0: 1,\n ci1: 1,\n stderr: 1,\n stdev: 1,\n stdevp: 1,\n sum: 1,\n valid: 1,\n values: 1,\n variance: 1,\n variancep: 1\n};\n\nexport const MULTIDOMAIN_SORT_OP_INDEX = {\n count: 1,\n min: 1,\n max: 1\n};\n\nexport interface ArgminDef {\n argmin: FieldName;\n}\n\nexport interface ArgmaxDef {\n argmax: FieldName;\n}\n\nexport type NonArgAggregateOp = Exclude;\n\nexport type Aggregate = NonArgAggregateOp | ArgmaxDef | ArgminDef;\n\nexport function isArgminDef(a: Aggregate | string): a is ArgminDef {\n return !!a && !!a['argmin'];\n}\n\nexport function isArgmaxDef(a: Aggregate | string): a is ArgmaxDef {\n return !!a && !!a['argmax'];\n}\n\nexport function isAggregateOp(a: string | ArgminDef | ArgmaxDef): a is AggregateOp {\n return isString(a) && !!AGGREGATE_OP_INDEX[a];\n}\n\nexport const COUNTING_OPS = new Set([\n 'count',\n 'valid',\n 'missing',\n 'distinct'\n]) as ReadonlySet;\n\nexport function isCountingAggregateOp(aggregate?: string | Aggregate): boolean {\n return isString(aggregate) && COUNTING_OPS.has(aggregate as any);\n}\n\nexport function isMinMaxOp(aggregate?: Aggregate | string): boolean {\n return isString(aggregate) && contains(['min', 'max'], aggregate);\n}\n\n/** Additive-based aggregation operations. These can be applied to stack. */\nexport const SUM_OPS = new Set([\n 'count',\n 'sum',\n 'distinct',\n 'valid',\n 'missing'\n]) as ReadonlySet;\n\n/**\n * Aggregation operators that always produce values within the range [domainMin, domainMax].\n */\nexport const SHARED_DOMAIN_OPS = new Set([\n 'mean',\n 'average',\n 'median',\n 'q1',\n 'q3',\n 'min',\n 'max'\n]) as ReadonlySet;\n","import {isBoolean, isObject} from 'vega-util';\nimport {\n COLOR,\n COLUMN,\n ExtendedChannel,\n FILL,\n FILLOPACITY,\n OPACITY,\n ROW,\n SHAPE,\n SIZE,\n STROKE,\n STROKEDASH,\n STROKEOPACITY,\n STROKEWIDTH\n} from './channel';\nimport {normalizeBin} from './channeldef';\nimport {ParameterExtent} from './selection';\nimport {entries, keys, varName} from './util';\n\nexport interface BaseBin {\n /**\n * The number base to use for automatic bin determination (default is base 10).\n *\n * __Default value:__ `10`\n *\n */\n base?: number;\n /**\n * An exact step size to use between bins.\n *\n * __Note:__ If provided, options such as maxbins will be ignored.\n */\n step?: number;\n /**\n * An array of allowable step sizes to choose from.\n * @minItems 1\n */\n steps?: number[];\n /**\n * A minimum allowable step size (particularly useful for integer values).\n */\n minstep?: number;\n /**\n * Scale factors indicating allowable subdivisions. The default value is [5, 2], which indicates that for base 10 numbers (the default base), the method may consider dividing bin sizes by 5 and/or 2. For example, for an initial step size of 10, the method can check if bin sizes of 2 (= 10/5), 5 (= 10/2), or 1 (= 10/(5*2)) might also satisfy the given constraints.\n *\n * __Default value:__ `[5, 2]`\n *\n * @minItems 1\n */\n divide?: [number, number];\n /**\n * Maximum number of bins.\n *\n * __Default value:__ `6` for `row`, `column` and `shape` channels; `10` for other channels\n *\n * @minimum 2\n */\n maxbins?: number;\n /**\n * A value in the binned domain at which to anchor the bins, shifting the bin boundaries if necessary to ensure that a boundary aligns with the anchor value.\n *\n * __Default value:__ the minimum bin extent value\n */\n anchor?: number;\n /**\n * If true, attempts to make the bin boundaries use human-friendly boundaries, such as multiples of ten.\n *\n * __Default value:__ `true`\n */\n nice?: boolean;\n}\n\n/**\n * Binning properties or boolean flag for determining whether to bin data or not.\n */\nexport interface BinParams extends BaseBin {\n /**\n * A two-element (`[min, max]`) array indicating the range of desired bin values.\n */\n extent?: BinExtent; // VgBinTransform uses a different extent so we need to pull this out.\n\n /**\n * When set to `true`, Vega-Lite treats the input data as already binned.\n */\n binned?: boolean;\n}\n\nexport type Bin = boolean | BinParams | 'binned' | null;\n\nexport type BinExtent = [number, number] | ParameterExtent;\n\n/**\n * Create a key for the bin configuration. Not for prebinned bin.\n */\nexport function binToString(bin: BinParams | true) {\n if (isBoolean(bin)) {\n bin = normalizeBin(bin, undefined);\n }\n return (\n 'bin' +\n keys(bin)\n .map(p => (isParameterExtent(bin[p]) ? varName(`_${p}_${entries(bin[p])}`) : varName(`_${p}_${bin[p]}`)))\n .join('')\n );\n}\n\n/**\n * Vega-Lite should bin the data.\n */\nexport function isBinning(bin: BinParams | boolean | 'binned'): bin is BinParams | true {\n return bin === true || (isBinParams(bin) && !bin.binned);\n}\n\n/**\n * The data is already binned and so Vega-Lite should not bin it again.\n */\nexport function isBinned(bin: BinParams | boolean | 'binned'): bin is 'binned' | BinParams {\n return bin === 'binned' || (isBinParams(bin) && bin.binned === true);\n}\n\nexport function isBinParams(bin: BinParams | boolean | 'binned'): bin is BinParams {\n return isObject(bin);\n}\n\nexport function isParameterExtent(extent: unknown): extent is ParameterExtent {\n return extent?.['param'];\n}\n\nexport function autoMaxBins(channel?: ExtendedChannel): number {\n switch (channel) {\n case ROW:\n case COLUMN:\n case SIZE:\n case COLOR:\n case FILL:\n case STROKE:\n case STROKEWIDTH:\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n // Facets and Size shouldn't have too many bins\n // We choose 6 like shape to simplify the rule [falls through]\n case SHAPE:\n return 6; // Vega's \"shape\" has 6 distinct values\n case STROKEDASH:\n return 4; // We only provide 5 different stroke dash values (but 4 is more effective)\n default:\n return 10;\n }\n}\n","import {signalRefOrValue} from './compile/common';\nimport {Dict, keys} from './util';\nimport {MappedExclude} from './vega.schema';\n\nexport interface ExprRef {\n /**\n * Vega expression (which can refer to Vega-Lite parameters).\n */\n expr: string;\n}\n\nexport function isExprRef(o: any): o is ExprRef {\n return !!o?.expr;\n}\n\nexport function replaceExprRef>(index: T, {level}: {level: number} = {level: 0}) {\n const props = keys(index || {});\n const newIndex: Dict = {};\n for (const prop of props) {\n newIndex[prop] = level === 0 ? signalRefOrValue(index[prop]) : replaceExprRef(index[prop], {level: level - 1});\n }\n return newIndex as MappedExclude;\n}\n","import {BaseTitle, SignalRef, Text, TextEncodeEntry, TitleAnchor} from 'vega';\nimport {isArray, isString} from 'vega-util';\nimport {ExprRef} from './expr';\nimport {MarkConfig} from './mark';\nimport {pick} from './util';\nimport {MapExcludeValueRefAndReplaceSignalWith, MappedExcludeValueRef} from './vega.schema';\n\nexport type BaseTitleNoValueRefs = MapExcludeValueRefAndReplaceSignalWith<\n Omit,\n ES\n> &\n // Since some logic depends on align/baseline, Vega-Lite does NOT allow signal for them.\n MappedExcludeValueRef>;\n\nexport type TitleConfig = BaseTitleNoValueRefs;\n\nexport interface TitleBase extends BaseTitleNoValueRefs {\n /**\n * The anchor position for placing the title. One of `\"start\"`, `\"middle\"`, or `\"end\"`. For example, with an orientation of top these anchor positions map to a left-, center-, or right-aligned title.\n *\n * __Default value:__ `\"middle\"` for [single](https://vega.github.io/vega-lite/docs/spec.html) and [layered](https://vega.github.io/vega-lite/docs/layer.html) views.\n * `\"start\"` for other composite views.\n *\n * __Note:__ [For now](https://github.com/vega/vega-lite/issues/2875), `anchor` is only customizable only for [single](https://vega.github.io/vega-lite/docs/spec.html) and [layered](https://vega.github.io/vega-lite/docs/layer.html) views. For other composite views, `anchor` is always `\"start\"`.\n */\n anchor?: TitleAnchor;\n\n /**\n * A [mark style property](https://vega.github.io/vega-lite/docs/config.html#style) to apply to the title text mark.\n *\n * __Default value:__ `\"group-title\"`.\n */\n style?: string | string[];\n\n /**\n * \tThe integer z-index indicating the layering of the title group relative to other axis, mark and legend groups.\n *\n * __Default value:__ `0`.\n *\n * @TJS-type integer\n * @minimum 0\n */\n zindex?: number;\n\n /**\n * Mark definitions for custom encoding.\n *\n * @hidden\n */\n encoding?: TextEncodeEntry;\n}\n\nexport interface TitleParams extends TitleBase {\n /**\n * The title text.\n */\n text: Text | ES;\n\n /**\n * The subtitle Text.\n */\n subtitle?: Text;\n}\n\nexport function extractTitleConfig(titleConfig: TitleConfig): {\n titleMarkConfig: MarkConfig;\n subtitleMarkConfig: MarkConfig;\n /** These are non-mark title config that need to be hardcoded in the title directive. */\n nonMarkTitleProperties: BaseTitleNoValueRefs;\n subtitle: BaseTitleNoValueRefs;\n} {\n const {\n // These are non-mark title config that need to be hardcoded\n anchor,\n frame,\n offset,\n orient,\n angle,\n limit,\n\n // color needs to be redirect to fill\n color,\n\n // subtitle properties\n subtitleColor,\n subtitleFont,\n subtitleFontSize,\n subtitleFontStyle,\n subtitleFontWeight,\n subtitleLineHeight,\n subtitlePadding,\n\n // The rest are mark config.\n ...rest\n } = titleConfig;\n\n const titleMarkConfig: MarkConfig = {\n ...rest,\n ...(color ? {fill: color} : {})\n };\n\n // These are non-mark title config that need to be hardcoded\n const nonMarkTitleProperties: BaseTitleNoValueRefs = {\n ...(anchor ? {anchor} : {}),\n ...(frame ? {frame} : {}),\n ...(offset ? {offset} : {}),\n ...(orient ? {orient} : {}),\n ...(angle !== undefined ? {angle} : {}),\n ...(limit !== undefined ? {limit} : {})\n };\n\n // subtitle part can stay in config.title since header titles do not use subtitle\n const subtitle: BaseTitleNoValueRefs = {\n ...(subtitleColor ? {subtitleColor} : {}),\n ...(subtitleFont ? {subtitleFont} : {}),\n ...(subtitleFontSize ? {subtitleFontSize} : {}),\n ...(subtitleFontStyle ? {subtitleFontStyle} : {}),\n ...(subtitleFontWeight ? {subtitleFontWeight} : {}),\n ...(subtitleLineHeight ? {subtitleLineHeight} : {}),\n ...(subtitlePadding ? {subtitlePadding} : {})\n };\n\n const subtitleMarkConfig = pick(titleConfig, ['align', 'baseline', 'dx', 'dy', 'limit']);\n\n return {titleMarkConfig, subtitleMarkConfig, nonMarkTitleProperties, subtitle};\n}\n\nexport function isText(v: any): v is Text {\n return isString(v) || (isArray(v) && isString(v[0]));\n}\n","import type {\n AggregateOp,\n BandScale,\n BaseScale,\n BinOrdinalScale,\n ColorValueRef,\n Compare as VgCompare,\n ExprRef as VgExprRef,\n GeoShapeTransform as VgGeoShapeTransform,\n IdentityScale,\n LayoutAlign,\n LinearScale,\n LogScale,\n Mark,\n MarkConfig,\n NumericValueRef,\n OrdinalScale,\n PointScale,\n PowScale,\n ProjectionType,\n QuantileScale,\n QuantizeScale,\n RangeBand,\n RangeRaw,\n RangeScheme,\n ScaleData,\n ScaleDataRef,\n ScaledValueRef,\n ScaleMultiDataRef,\n ScaleMultiFieldsRef,\n SequentialScale,\n SignalRef,\n SortField as VgSortField,\n SqrtScale,\n SymLogScale,\n ThresholdScale,\n TimeInterval,\n TimeIntervalStep,\n TimeScale,\n Title as VgTitle,\n Transforms as VgTransform,\n UnionSortField as VgUnionSortField\n} from 'vega';\nimport {isArray} from 'vega-util';\nimport {Value} from './channeldef';\nimport {ExprRef} from './expr';\nimport {SortOrder} from './sort';\nimport {Dict, Flag, keys} from './util';\n\nexport type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef};\n\n// TODO: make recursive (e.g. with https://stackoverflow.com/a/64900252/214950 but needs https://github.com/vega/ts-json-schema-generator/issues/568)\nexport type MappedExclude = {\n [P in keyof T]: Exclude;\n};\n\nexport type MapExcludeAndKeepSignalAs = {\n [P in keyof T]: SignalRef extends T[P] ? Exclude | S : Exclude;\n};\n\n// Remove ValueRefs from mapped types\nexport type MappedExcludeValueRef = MappedExclude | NumericValueRef | ColorValueRef>;\n\nexport type MapExcludeValueRefAndReplaceSignalWith = MapExcludeAndKeepSignalAs<\n T,\n ScaledValueRef | NumericValueRef | ColorValueRef,\n S\n>;\n\nexport interface VgData {\n name: string;\n source?: string;\n values?: any;\n format?: {\n type?: string;\n parse?: string | Dict;\n property?: string;\n feature?: string;\n mesh?: string;\n };\n url?: string;\n transform?: VgTransform[];\n}\n\nexport type VgScaleDataRefWithSort = ScaleDataRef & {\n sort?: VgSortField;\n};\n\nexport function isSignalRef(o: any): o is SignalRef {\n return !!o?.signal;\n}\n\n// TODO: add type of value (Make it VgValueRef {value?:V ...})\nexport interface VgValueRef {\n value?: Value; // value should never be a signal so we use never\n field?:\n | string\n | {\n datum?: string;\n group?: string;\n parent?: string;\n };\n signal?: string;\n scale?: string; // TODO: object\n mult?: number;\n offset?: number | VgValueRef;\n band?: boolean | number | VgValueRef;\n test?: string;\n}\n\n// TODO: add vg prefix\nexport type VgScaleMultiDataRefWithSort = ScaleMultiDataRef & {\n fields: (any[] | VgScaleDataRefWithSort | SignalRef)[];\n sort?: VgUnionSortField;\n};\n\nexport type VgMultiFieldsRefWithSort = ScaleMultiFieldsRef & {\n sort?: VgUnionSortField;\n};\n\nexport type VgRange = RangeScheme | ScaleData | RangeBand | RangeRaw;\n\nexport function isVgRangeStep(range: VgRange): range is VgRangeStep {\n return !!range['step'];\n}\n\nexport interface VgRangeStep {\n step: number | SignalRef;\n}\n// Domains that are not a union of domains\nexport type VgNonUnionDomain = (null | string | number | boolean | SignalRef)[] | VgScaleDataRefWithSort | SignalRef;\n\nexport type VgDomain = BaseScale['domain'];\n\nexport type VgMarkGroup = any;\n\n/**\n * A combined type for any Vega scales that Vega-Lite can generate\n */\nexport type VgScale = Pick & {\n range?: RangeScheme | RangeBand | ScaleData; // different Vega scales have conflicting range, need to union them here\n nice?: boolean | number | TimeInterval | TimeIntervalStep | SignalRef; // different Vega scales have conflicting range, need to union them here\n zero?: boolean | SignalRef; // LogScale only allow false, making the intersection type overly strict\n} & Omit<\n // Continuous\n Omit &\n Omit &\n Omit &\n Omit, 'type'> & // use partial so exponent is not required\n Omit &\n Omit &\n Omit &\n // Discretizing\n Omit &\n Omit &\n Omit &\n Omit &\n // Sequential\n Omit &\n // Discrete\n Omit &\n Omit &\n Omit,\n 'range' | 'nice' | 'zero'\n >;\n\nexport interface RowCol {\n row?: T;\n column?: T;\n}\n\nexport interface VgLayout {\n center?: boolean | RowCol;\n padding?: number | RowCol;\n headerBand?: number | RowCol;\n footerBand?: number | RowCol;\n\n titleAnchor?: 'start' | 'end' | RowCol<'start' | 'end'>;\n offset?:\n | number\n | {\n rowHeader?: number;\n rowFooter?: number;\n rowTitle?: number;\n columnHeader?: number;\n columnFooter?: number;\n columnTitle?: number;\n };\n bounds?: 'full' | 'flush';\n columns?: number | {signal: string};\n align?: LayoutAlign | RowCol;\n}\n\nexport function isDataRefUnionedDomain(domain: VgDomain): domain is VgScaleMultiDataRefWithSort {\n if (!isArray(domain)) {\n return 'fields' in domain && !('data' in domain);\n }\n return false;\n}\n\nexport function isFieldRefUnionDomain(domain: VgDomain): domain is VgMultiFieldsRefWithSort {\n if (!isArray(domain)) {\n return 'fields' in domain && 'data' in domain;\n }\n return false;\n}\n\nexport function isDataRefDomain(domain: VgDomain | any): domain is VgScaleDataRefWithSort {\n if (!isArray(domain)) {\n return 'field' in domain && 'data' in domain;\n }\n return false;\n}\n\nexport type VgEncodeChannel =\n | 'x'\n | 'x2'\n | 'xc'\n | 'width'\n | 'y'\n | 'y2'\n | 'yc'\n | 'height'\n | 'opacity'\n | 'fill'\n | 'fillOpacity'\n | 'stroke'\n | 'strokeWidth'\n | 'strokeCap'\n | 'strokeOpacity'\n | 'strokeDash'\n | 'strokeDashOffset'\n | 'strokeMiterLimit'\n | 'strokeJoin'\n | 'strokeOffset'\n | 'strokeForeground'\n | 'cursor'\n | 'clip'\n | 'size'\n | 'shape'\n | 'path'\n | 'innerRadius'\n | 'outerRadius'\n | 'startAngle'\n | 'endAngle'\n | 'interpolate'\n | 'tension'\n | 'orient'\n | 'url'\n | 'align'\n | 'baseline'\n | 'text'\n | 'dir'\n | 'ellipsis'\n | 'limit'\n | 'dx'\n | 'dy'\n | 'radius'\n | 'theta'\n | 'angle'\n | 'font'\n | 'fontSize'\n | 'fontWeight'\n | 'fontStyle'\n | 'tooltip'\n | 'href'\n | 'cursor'\n | 'defined'\n | 'cornerRadius'\n | 'cornerRadiusTopLeft'\n | 'cornerRadiusTopRight'\n | 'cornerRadiusBottomRight'\n | 'cornerRadiusBottomLeft'\n | 'scaleX'\n | 'scaleY';\n\nexport type VgEncodeEntry = Partial>;\n\n// TODO: make export interface VgEncodeEntry {\n// x?: VgValueRef\n// y?: VgValueRef\n// ...\n// color?: VgValueRef\n// ...\n// }\n\nexport type VgPostEncodingTransform = VgGeoShapeTransform;\n\nconst VG_MARK_CONFIG_INDEX: Flag = {\n aria: 1,\n description: 1,\n ariaRole: 1,\n ariaRoleDescription: 1,\n blend: 1,\n opacity: 1,\n fill: 1,\n fillOpacity: 1,\n stroke: 1,\n strokeCap: 1,\n strokeWidth: 1,\n strokeOpacity: 1,\n strokeDash: 1,\n strokeDashOffset: 1,\n strokeJoin: 1,\n strokeOffset: 1,\n strokeMiterLimit: 1,\n startAngle: 1,\n endAngle: 1,\n padAngle: 1,\n innerRadius: 1,\n outerRadius: 1,\n size: 1,\n shape: 1,\n interpolate: 1,\n tension: 1,\n orient: 1,\n align: 1,\n baseline: 1,\n text: 1,\n dir: 1,\n dx: 1,\n dy: 1,\n ellipsis: 1,\n limit: 1,\n radius: 1,\n theta: 1,\n angle: 1,\n font: 1,\n fontSize: 1,\n fontWeight: 1,\n fontStyle: 1,\n lineBreak: 1,\n lineHeight: 1,\n cursor: 1,\n href: 1,\n tooltip: 1,\n cornerRadius: 1,\n cornerRadiusTopLeft: 1,\n cornerRadiusTopRight: 1,\n cornerRadiusBottomLeft: 1,\n cornerRadiusBottomRight: 1,\n aspect: 1,\n width: 1,\n height: 1,\n url: 1,\n smooth: 1\n\n // commented below are vg channel that do not have mark config.\n // x: 1,\n // y: 1,\n // x2: 1,\n // y2: 1,\n\n // xc'|'yc'\n // clip: 1,\n // path: 1,\n // url: 1,\n};\n\nexport const VG_MARK_CONFIGS = keys(VG_MARK_CONFIG_INDEX);\n\nexport const VG_MARK_INDEX: Flag = {\n arc: 1,\n area: 1,\n group: 1,\n image: 1,\n line: 1,\n path: 1,\n rect: 1,\n rule: 1,\n shape: 1,\n symbol: 1,\n text: 1,\n trail: 1\n};\n\n// Vega's cornerRadius channels.\nexport const VG_CORNERRADIUS_CHANNELS = [\n 'cornerRadius',\n 'cornerRadiusTopLeft',\n 'cornerRadiusTopRight',\n 'cornerRadiusBottomLeft',\n 'cornerRadiusBottomRight'\n] as const;\n\nexport interface VgComparator {\n field?: string | string[];\n order?: SortOrder | SortOrder[];\n}\n\nexport interface VgJoinAggregateTransform {\n type: 'joinaggregate';\n as?: string[];\n ops?: AggregateOp[];\n fields?: string[];\n groupby?: string[];\n}\n","import {ExprRef, SignalRef, Text} from 'vega';\nimport {array, isArray, stringValue} from 'vega-util';\nimport {AxisConfig, ConditionalAxisProperty} from '../axis';\nimport {\n ConditionalPredicate,\n DatumDef,\n FieldDef,\n FieldDefBase,\n FieldRefOption,\n OrderFieldDef,\n Value,\n ValueDef,\n vgField\n} from '../channeldef';\nimport {Config, StyleConfigIndex} from '../config';\nimport {isExprRef} from '../expr';\nimport {Mark, MarkConfig, MarkDef} from '../mark';\nimport {SortFields} from '../sort';\nimport {isText} from '../title';\nimport {deepEqual, getFirstDefined} from '../util';\nimport {isSignalRef, VgEncodeChannel, VgEncodeEntry, VgValueRef} from '../vega.schema';\nimport {AxisComponentProps} from './axis/component';\nimport {Explicit} from './split';\nimport {UnitModel} from './unit';\n\nexport const BIN_RANGE_DELIMITER = ' \\u2013 ';\n\nexport function signalOrValueRefWithCondition(\n val: ConditionalAxisProperty\n): ConditionalAxisProperty {\n const condition = isArray(val.condition)\n ? (val.condition as ConditionalPredicate | ExprRef | SignalRef>[]).map(conditionalSignalRefOrValue)\n : conditionalSignalRefOrValue(val.condition);\n\n return {\n ...signalRefOrValue>(val),\n condition\n };\n}\n\nexport function signalRefOrValue(value: T | SignalRef | ExprRef): T | SignalRef {\n if (isExprRef(value)) {\n const {expr, ...rest} = value;\n return {signal: expr, ...rest};\n }\n return value;\n}\n\nexport function conditionalSignalRefOrValue | DatumDef | ValueDef>(\n value: ConditionalPredicate\n): ConditionalPredicate {\n if (isExprRef(value)) {\n const {expr, ...rest} = value;\n return {signal: expr, ...rest};\n }\n return value;\n}\n\nexport function signalOrValueRef(value: T | SignalRef | ExprRef): {value: T} | SignalRef {\n if (isExprRef(value)) {\n const {expr, ...rest} = value;\n return {signal: expr, ...rest};\n }\n if (isSignalRef(value)) {\n return value;\n }\n return value !== undefined ? {value} : undefined;\n}\n\nexport function exprFromSignalRefOrValue(ref: Value | SignalRef): string {\n if (isSignalRef(ref)) {\n return ref.signal;\n }\n return stringValue(ref);\n}\nexport function exprFromValueRefOrSignalRef(ref: VgValueRef | SignalRef): string {\n if (isSignalRef(ref)) {\n return ref.signal;\n }\n return stringValue(ref.value);\n}\n\nexport function signalOrStringValue(v: SignalRef | any) {\n if (isSignalRef(v)) {\n return v.signal;\n }\n return v == null ? null : stringValue(v);\n}\n\nexport function applyMarkConfig(e: VgEncodeEntry, model: UnitModel, propsList: (keyof MarkConfig)[]) {\n for (const property of propsList) {\n const value = getMarkConfig(property, model.markDef, model.config);\n if (value !== undefined) {\n e[property] = signalOrValueRef(value);\n }\n }\n return e;\n}\n\nexport function getStyles(mark: MarkDef): string[] {\n return [].concat(mark.type, mark.style ?? []);\n}\n\nexport function getMarkPropOrConfig

(\n channel: P,\n mark: MarkDef,\n config: Config,\n opt: {\n vgChannel?: VgEncodeChannel;\n ignoreVgConfig?: boolean;\n } = {}\n): MarkDef[P] {\n const {vgChannel, ignoreVgConfig} = opt;\n if (vgChannel && mark[vgChannel] !== undefined) {\n return mark[vgChannel];\n } else if (mark[channel] !== undefined) {\n return mark[channel];\n } else if (ignoreVgConfig && (!vgChannel || vgChannel === channel)) {\n return undefined;\n }\n\n return getMarkConfig(channel, mark, config, opt);\n}\n\n/**\n * Return property value from style or mark specific config property if exists.\n * Otherwise, return general mark specific config.\n */\nexport function getMarkConfig

(\n channel: P,\n mark: MarkDef,\n config: Config,\n {vgChannel}: {vgChannel?: VgEncodeChannel} = {}\n): MarkDef[P] {\n return getFirstDefined[P]>(\n // style config has highest precedence\n vgChannel ? getMarkStyleConfig(channel, mark, config.style) : undefined,\n getMarkStyleConfig(channel, mark, config.style),\n // then mark-specific config\n vgChannel ? config[mark.type][vgChannel] : undefined,\n\n config[mark.type][channel as any], // 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\n\n // If there is vgChannel, skip vl channel.\n // For example, vl size for text is vg fontSize, but config.mark.size is only for point size.\n vgChannel ? config.mark[vgChannel] : config.mark[channel as any] // Need to cast for the same reason as above\n );\n}\n\nexport function getMarkStyleConfig

(\n prop: P,\n mark: MarkDef,\n styleConfigIndex: StyleConfigIndex\n) {\n return getStyleConfig(prop, getStyles(mark), styleConfigIndex);\n}\n\nexport function getStyleConfig

>(\n p: P,\n styles: string | string[],\n styleConfigIndex: StyleConfigIndex\n) {\n styles = array(styles);\n let value;\n for (const style of styles) {\n const styleConfig = styleConfigIndex[style];\n\n if (styleConfig && styleConfig[p as string] !== undefined) {\n value = styleConfig[p as string];\n }\n }\n return value;\n}\n\n/**\n * Return Vega sort parameters (tuple of field and order).\n */\nexport function sortParams(\n orderDef: OrderFieldDef | OrderFieldDef[],\n fieldRefOption?: FieldRefOption\n): SortFields {\n return array(orderDef).reduce(\n (s, orderChannelDef) => {\n s.field.push(vgField(orderChannelDef, fieldRefOption));\n s.order.push(orderChannelDef.sort ?? 'ascending');\n return s;\n },\n {field: [], order: []}\n );\n}\n\nexport type AxisTitleComponent = AxisComponentProps['title'];\n\nexport function mergeTitleFieldDefs(f1: readonly FieldDefBase[], f2: readonly FieldDefBase[]) {\n const merged = [...f1];\n\n f2.forEach(fdToMerge => {\n for (const fieldDef1 of merged) {\n // If already exists, no need to append to merged array\n if (deepEqual(fieldDef1, fdToMerge)) {\n return;\n }\n }\n merged.push(fdToMerge);\n });\n return merged;\n}\n\nexport function mergeTitle(title1: Text | SignalRef, title2: Text | SignalRef) {\n if (deepEqual(title1, title2) || !title2) {\n // if titles are the same or title2 is falsy\n return title1;\n } else if (!title1) {\n // if title1 is falsy\n return title2;\n } else {\n return [...array(title1), ...array(title2)].join(', ');\n }\n}\n\nexport function mergeTitleComponent(v1: Explicit, v2: Explicit) {\n const v1Val = v1.value;\n const v2Val = v2.value;\n\n if (v1Val == null || v2Val === null) {\n return {\n explicit: v1.explicit,\n value: null\n };\n } else if ((isText(v1Val) || isSignalRef(v1Val)) && (isText(v2Val) || isSignalRef(v2Val))) {\n return {\n explicit: v1.explicit,\n value: mergeTitle(v1Val, v2Val)\n };\n } else if (isText(v1Val) || isSignalRef(v1Val)) {\n return {\n explicit: v1.explicit,\n value: v1Val\n };\n } else if (isText(v2Val) || isSignalRef(v2Val)) {\n return {\n explicit: v1.explicit,\n value: v2Val\n };\n } else if (!isText(v1Val) && !isSignalRef(v1Val) && !isText(v2Val) && !isSignalRef(v2Val)) {\n return {\n explicit: v1.explicit,\n value: mergeTitleFieldDefs(v1Val, v2Val)\n };\n }\n /* istanbul ignore next: Condition should not happen -- only for warning in development. */\n throw new Error('It should never reach here');\n}\n","/**\n * Collection of all Vega-Lite Error Messages\n */\nimport {AggregateOp, SignalRef} from 'vega';\nimport {Aggregate} from '../aggregate';\nimport {\n Channel,\n ExtendedChannel,\n FacetChannel,\n getSizeChannel,\n OffsetScaleChannel,\n PositionScaleChannel,\n ScaleChannel\n} from '../channel';\nimport {HiddenCompositeAggregate, TypedFieldDef, Value} from '../channeldef';\nimport {SplitParentProperty} from '../compile/split';\nimport {CompositeMark} from '../compositemark';\nimport {ErrorBarCenter, ErrorBarExtent} from '../compositemark/errorbar';\nimport {DateTime, DateTimeExpr} from '../datetime';\nimport {ExprRef} from '../expr';\nimport {Mark} from '../mark';\nimport {Projection} from '../projection';\nimport {ScaleType} from '../scale';\nimport {GenericSpec} from '../spec';\nimport {Type} from '../type';\nimport {stringify} from '../util';\nimport {VgSortField} from '../vega.schema';\n\nexport function invalidSpec(spec: GenericSpec) {\n return `Invalid specification ${stringify(\n spec\n )}. Make sure the specification includes at least one of the following properties: \"mark\", \"layer\", \"facet\", \"hconcat\", \"vconcat\", \"concat\", or \"repeat\".`;\n}\n\n// FIT\nexport const FIT_NON_SINGLE = 'Autosize \"fit\" only works for single views and layered views.';\n\nexport function containerSizeNonSingle(name: 'width' | 'height') {\n const uName = name == 'width' ? 'Width' : 'Height';\n return `${uName} \"container\" only works for single views and layered views.`;\n}\n\nexport function containerSizeNotCompatibleWithAutosize(name: 'width' | 'height') {\n const uName = name == 'width' ? 'Width' : 'Height';\n const fitDirection = name == 'width' ? 'x' : 'y';\n return `${uName} \"container\" only works well with autosize \"fit\" or \"fit-${fitDirection}\".`;\n}\n\nexport function droppingFit(channel?: PositionScaleChannel) {\n return channel\n ? `Dropping \"fit-${channel}\" because spec has discrete ${getSizeChannel(channel)}.`\n : `Dropping \"fit\" because spec has discrete size.`;\n}\n\n// VIEW SIZE\n\nexport function unknownField(channel: Channel) {\n return `Unknown field for ${channel}. Cannot calculate view size.`;\n}\n\n// SELECTION\nexport function cannotProjectOnChannelWithoutField(channel: Channel) {\n return `Cannot project a selection on encoding channel \"${channel}\", which has no field.`;\n}\n\nexport function cannotProjectAggregate(channel: Channel, aggregate: Aggregate | HiddenCompositeAggregate) {\n return `Cannot project a selection on encoding channel \"${channel}\" as it uses an aggregate function (\"${aggregate}\").`;\n}\n\nexport function nearestNotSupportForContinuous(mark: string) {\n return `The \"nearest\" transform is not supported for ${mark} marks.`;\n}\n\nexport function selectionNotSupported(mark: CompositeMark) {\n return `Selection not supported for ${mark} yet.`;\n}\n\nexport function selectionNotFound(name: string) {\n return `Cannot find a selection named \"${name}\".`;\n}\n\nexport const SCALE_BINDINGS_CONTINUOUS =\n 'Scale bindings are currently only supported for scales with unbinned, continuous domains.';\n\nexport const SEQUENTIAL_SCALE_DEPRECATED =\n 'Sequntial scales are deprecated. The available quantitative scale type values are linear, log, pow, sqrt, symlog, time and utc';\n\nexport const LEGEND_BINDINGS_MUST_HAVE_PROJECTION =\n 'Legend bindings are only supported for selections over an individual field or encoding channel.';\nexport function cannotLookupVariableParameter(name: string) {\n return `Lookups can only be performed on selection parameters. \"${name}\" is a variable parameter.`;\n}\n\nexport function noSameUnitLookup(name: string) {\n return (\n `Cannot define and lookup the \"${name}\" selection in the same view. ` +\n `Try moving the lookup into a second, layered view?`\n );\n}\n\nexport const NEEDS_SAME_SELECTION = 'The same selection must be used to override scale domains in a layered view.';\n\nexport const INTERVAL_INITIALIZED_WITH_POS =\n 'Interval selections should be initialized using \"x\", \"y\", \"longitude\", or \"latitude\" keys.';\n\n// REPEAT\nexport function noSuchRepeatedValue(field: string) {\n return `Unknown repeated value \"${field}\".`;\n}\n\nexport function columnsNotSupportByRowCol(type: 'facet' | 'repeat') {\n return `The \"columns\" property cannot be used when \"${type}\" has nested row/column.`;\n}\n\n// CONCAT / REPEAT\nexport const CONCAT_CANNOT_SHARE_AXIS =\n 'Axes cannot be shared in concatenated or repeated views yet (https://github.com/vega/vega-lite/issues/2415).';\n\n// DATA\nexport function unrecognizedParse(p: string) {\n return `Unrecognized parse \"${p}\".`;\n}\n\nexport function differentParse(field: string, local: string, ancestor: string) {\n return `An ancestor parsed field \"${field}\" as ${ancestor} but a child wants to parse the field as ${local}.`;\n}\n\nexport const ADD_SAME_CHILD_TWICE = 'Attempt to add the same child twice.';\n\n// TRANSFORMS\nexport function invalidTransformIgnored(transform: any) {\n return `Ignoring an invalid transform: ${stringify(transform)}.`;\n}\n\nexport const NO_FIELDS_NEEDS_AS =\n '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.';\n\n// ENCODING & FACET\n\nexport function customFormatTypeNotAllowed(channel: ExtendedChannel) {\n return `Config.customFormatTypes is not true, thus custom format type and format for channel ${channel} are dropped.`;\n}\n\nexport function projectionOverridden(opt: {\n parentProjection: Projection;\n projection: Projection;\n}) {\n const {parentProjection, projection} = opt;\n return `Layer's shared projection ${stringify(parentProjection)} is overridden by a child projection ${stringify(\n projection\n )}.`;\n}\n\nexport const REPLACE_ANGLE_WITH_THETA = 'Arc marks uses theta channel rather than angle, replacing angle with theta.';\n\nexport function offsetNestedInsideContinuousPositionScaleDropped(mainChannel: PositionScaleChannel) {\n return `${mainChannel}Offset dropped because ${mainChannel} is continuous`;\n}\n\nexport function primitiveChannelDef(\n channel: ExtendedChannel,\n type: 'string' | 'number' | 'boolean',\n value: Exclude\n) {\n return `Channel ${channel} is a ${type}. Converted to {value: ${stringify(value)}}.`;\n}\n\nexport function invalidFieldType(type: Type) {\n return `Invalid field type \"${type}\".`;\n}\n\nexport function invalidFieldTypeForCountAggregate(type: Type, aggregate: Aggregate | string) {\n return `Invalid field type \"${type}\" for aggregate: \"${aggregate}\", using \"quantitative\" instead.`;\n}\n\nexport function invalidAggregate(aggregate: AggregateOp | string) {\n return `Invalid aggregation operator \"${aggregate}\".`;\n}\n\nexport function missingFieldType(channel: Channel, newType: Type) {\n return `Missing type for channel \"${channel}\", using \"${newType}\" instead.`;\n}\nexport function droppingColor(type: 'encoding' | 'property', opt: {fill?: boolean; stroke?: boolean}) {\n const {fill, stroke} = opt;\n return `Dropping color ${type} as the plot also has ${\n fill && stroke ? 'fill and stroke' : fill ? 'fill' : 'stroke'\n }.`;\n}\n\nexport function relativeBandSizeNotSupported(sizeChannel: 'width' | 'height') {\n return `Position range does not support relative band size for ${sizeChannel}.`;\n}\n\nexport function emptyFieldDef(fieldDef: unknown, channel: ExtendedChannel) {\n return `Dropping ${stringify(\n fieldDef\n )} from channel \"${channel}\" since it does not contain any data field, datum, value, or signal.`;\n}\n\nexport const LINE_WITH_VARYING_SIZE =\n 'Line marks cannot encode size with a non-groupby field. You may want to use trail marks instead.';\n\nexport function incompatibleChannel(\n channel: ExtendedChannel,\n markOrFacet: Mark | 'facet' | CompositeMark,\n when?: string\n) {\n return `${channel} dropped as it is incompatible with \"${markOrFacet}\"${when ? ` when ${when}` : ''}.`;\n}\n\nexport function offsetEncodingScaleIgnored(channel: OffsetScaleChannel) {\n return `${channel} encoding has no scale, so specified scale is ignored.`;\n}\n\nexport function invalidEncodingChannel(channel: ExtendedChannel) {\n return `${channel}-encoding is dropped as ${channel} is not a valid encoding channel.`;\n}\n\nexport function channelShouldBeDiscrete(channel: ExtendedChannel) {\n return `${channel} encoding should be discrete (ordinal / nominal / binned).`;\n}\n\nexport function channelShouldBeDiscreteOrDiscretizing(channel: ExtendedChannel) {\n return `${channel} encoding should be discrete (ordinal / nominal / binned) or use a discretizing scale (e.g. threshold).`;\n}\n\nexport function facetChannelDropped(channels: FacetChannel[]) {\n return `Facet encoding dropped as ${channels.join(' and ')} ${channels.length > 1 ? 'are' : 'is'} also specified.`;\n}\n\nexport function discreteChannelCannotEncode(channel: Channel, type: Type) {\n return `Using discrete channel \"${channel}\" to encode \"${type}\" field can be misleading as it does not encode ${\n type === 'ordinal' ? 'order' : 'magnitude'\n }.`;\n}\n\n// MARK\n\nexport function rangeMarkAlignmentCannotBeExpression(align: 'align' | 'baseline') {\n return `The ${align} for range marks cannot be an expression`;\n}\n\nexport function lineWithRange(hasX2: boolean, hasY2: boolean) {\n const channels = hasX2 && hasY2 ? 'x2 and y2' : hasX2 ? 'x2' : 'y2';\n return `Line mark is for continuous lines and thus cannot be used with ${channels}. We will use the rule mark (line segments) instead.`;\n}\n\nexport function orientOverridden(original: string, actual: string) {\n return `Specified orient \"${original}\" overridden with \"${actual}\".`;\n}\n\n// SCALE\nexport const CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN =\n 'Custom domain scale cannot be unioned with default field-based domain.';\n\nexport function cannotUseScalePropertyWithNonColor(prop: string) {\n return `Cannot use the scale property \"${prop}\" with non-color channel.`;\n}\n\nexport function cannotUseRelativeBandSizeWithNonBandScale(scaleType: ScaleType) {\n return `Cannot use the relative band size with ${scaleType} scale.`;\n}\n\nexport function unaggregateDomainHasNoEffectForRawField(fieldDef: TypedFieldDef) {\n return `Using unaggregated domain with raw field has no effect (${stringify(fieldDef)}).`;\n}\n\nexport function unaggregateDomainWithNonSharedDomainOp(aggregate: Aggregate | string) {\n return `Unaggregated domain not applicable for \"${aggregate}\" since it produces values outside the origin domain of the source data.`;\n}\n\nexport function unaggregatedDomainWithLogScale(fieldDef: TypedFieldDef) {\n return `Unaggregated domain is currently unsupported for log scale (${stringify(fieldDef)}).`;\n}\n\nexport function cannotApplySizeToNonOrientedMark(mark: Mark) {\n return `Cannot apply size to non-oriented mark \"${mark}\".`;\n}\n\nexport function scaleTypeNotWorkWithChannel(channel: Channel, scaleType: ScaleType, defaultScaleType: ScaleType) {\n return `Channel \"${channel}\" does not work with \"${scaleType}\" scale. We are using \"${defaultScaleType}\" scale instead.`;\n}\n\nexport function scaleTypeNotWorkWithFieldDef(scaleType: ScaleType, defaultScaleType: ScaleType) {\n return `FieldDef does not work with \"${scaleType}\" scale. We are using \"${defaultScaleType}\" scale instead.`;\n}\n\nexport function scalePropertyNotWorkWithScaleType(scaleType: ScaleType, propName: string, channel: Channel) {\n return `${channel}-scale's \"${propName}\" is dropped as it does not work with ${scaleType} scale.`;\n}\n\nexport function scaleTypeNotWorkWithMark(mark: Mark, scaleType: ScaleType) {\n return `Scale type \"${scaleType}\" does not work with mark \"${mark}\".`;\n}\n\nexport function stepDropped(channel: 'width' | 'height') {\n return `The step for \"${channel}\" is dropped because the ${channel === 'width' ? 'x' : 'y'} is continuous.`;\n}\n\nexport function mergeConflictingProperty(\n property: string | number | symbol,\n propertyOf: SplitParentProperty,\n v1: T,\n v2: T\n) {\n return `Conflicting ${propertyOf.toString()} property \"${property.toString()}\" (${stringify(v1)} and ${stringify(\n v2\n )}). Using ${stringify(v1)}.`;\n}\n\nexport function mergeConflictingDomainProperty(property: 'domains', propertyOf: SplitParentProperty, v1: T, v2: T) {\n return `Conflicting ${propertyOf.toString()} property \"${property.toString()}\" (${stringify(v1)} and ${stringify(\n v2\n )}). Using the union of the two domains.`;\n}\n\nexport function independentScaleMeansIndependentGuide(channel: Channel) {\n return `Setting the scale to be independent for \"${channel}\" means we also have to set the guide (axis or legend) to be independent.`;\n}\n\nexport function domainSortDropped(sort: VgSortField) {\n return `Dropping sort property ${stringify(\n sort\n )} as unioned domains only support boolean or op \"count\", \"min\", and \"max\".`;\n}\n\nexport const MORE_THAN_ONE_SORT =\n 'Domains that should be unioned has conflicting sort properties. Sort will be set to true.';\n\nexport const FACETED_INDEPENDENT_DIFFERENT_SOURCES =\n '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.';\n\nexport const FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES =\n '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.';\n\nexport const FACETED_INDEPENDENT_SAME_SOURCE =\n '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.';\n\n// AXIS\nexport const INVALID_CHANNEL_FOR_AXIS = 'Invalid channel for axis.';\n\n// STACK\nexport function cannotStackRangedMark(channel: Channel) {\n return `Cannot stack \"${channel}\" if there is already \"${channel}2\".`;\n}\n\nexport function stackNonLinearScale(scaleType: ScaleType) {\n return `Stack is applied to a non-linear scale (${scaleType}).`;\n}\n\nexport function stackNonSummativeAggregate(aggregate: Aggregate | string) {\n return `Stacking is applied even though the aggregate function is non-summative (\"${aggregate}\").`;\n}\n\n// TIMEUNIT\nexport function invalidTimeUnit(unitName: string, value: string | number) {\n return `Invalid ${unitName}: ${stringify(value)}.`;\n}\n\nexport function droppedDay(d: DateTime | DateTimeExpr) {\n return `Dropping day from datetime ${stringify(d)} as day cannot be combined with other units.`;\n}\n\nexport function errorBarCenterAndExtentAreNotNeeded(center: ErrorBarCenter, extent: ErrorBarExtent) {\n return `${extent ? 'extent ' : ''}${extent && center ? 'and ' : ''}${center ? 'center ' : ''}${\n extent && center ? 'are ' : 'is '\n }not needed when data are aggregated.`;\n}\n\nexport function errorBarCenterIsUsedWithWrongExtent(\n center: ErrorBarCenter,\n extent: ErrorBarExtent,\n mark: 'errorbar' | 'errorband'\n) {\n return `${center} is not usually used with ${extent} for ${mark}.`;\n}\n\nexport function errorBarContinuousAxisHasCustomizedAggregate(\n aggregate: Aggregate | string,\n compositeMark: CompositeMark\n) {\n return `Continuous axis should not have customized aggregation function ${aggregate}; ${compositeMark} already agregates the axis.`;\n}\n\nexport function errorBand1DNotSupport(property: 'interpolate' | 'tension') {\n return `1D error band does not support ${property}.`;\n}\n\n// CHANNEL\nexport function channelRequiredForBinned(channel: Channel) {\n return `Channel ${channel} is required for \"binned\" bin.`;\n}\n\nexport function channelShouldNotBeUsedForBinned(channel: ExtendedChannel) {\n return `Channel ${channel} should not be used with \"binned\" bin.`;\n}\n\nexport function domainRequiredForThresholdScale(channel: ScaleChannel) {\n return `Domain for ${channel} is required for threshold scale.`;\n}\n","/**\n * Vega-Lite's singleton logger utility.\n */\n\nimport {Debug, Error as ErrorLevel, Info, logger, LoggerInterface, Warn} from 'vega-util';\nexport * as message from './message';\n\n/**\n * Main (default) Vega Logger instance for Vega-Lite.\n */\nconst main = logger(Warn);\nlet current: LoggerInterface = main;\n\n/**\n * Logger tool for checking if the code throws correct warning.\n */\nexport class LocalLogger implements LoggerInterface {\n public warns: any[] = [];\n public infos: any[] = [];\n public debugs: any[] = [];\n\n #level: number = Warn;\n\n public level(): number;\n public level(_: number): this;\n public level(_?: number) {\n if (_) {\n this.#level = _;\n return this;\n }\n return this.#level;\n }\n\n public warn(...args: readonly any[]) {\n if (this.#level >= Warn) this.warns.push(...args);\n return this;\n }\n\n public info(...args: readonly any[]) {\n if (this.#level >= Info) this.infos.push(...args);\n return this;\n }\n\n public debug(...args: readonly any[]) {\n if (this.#level >= Debug) this.debugs.push(...args);\n return this;\n }\n\n public error(...args: readonly any[]): this {\n if (this.#level >= ErrorLevel) throw Error(...args);\n return this;\n }\n}\n\nexport function wrap(f: (logger: LocalLogger) => void) {\n return () => {\n current = new LocalLogger();\n f(current as LocalLogger);\n reset();\n };\n}\n\n/**\n * Set the singleton logger to be a custom logger.\n */\nexport function set(newLogger: LoggerInterface) {\n current = newLogger;\n return current;\n}\n\n/**\n * Reset the main logger to use the default Vega Logger.\n */\nexport function reset() {\n current = main;\n return current;\n}\n\nexport function error(...args: readonly any[]) {\n current.error(...args);\n}\n\nexport function warn(...args: readonly any[]) {\n current.warn(...args);\n}\n\nexport function info(...args: readonly any[]) {\n current.info(...args);\n}\n\nexport function debug(...args: readonly any[]) {\n current.debug(...args);\n}\n","// DateTime definition object\n\nimport {isNumber, isObject} from 'vega-util';\nimport * as log from './log';\nimport {TIMEUNIT_PARTS} from './timeunit';\nimport {duplicate, isNumeric, keys} from './util';\n\n/**\n * @minimum 1\n * @maximum 12\n * @TJS-type integer\n */\nexport type Month = number;\n\n/**\n * @minimum 1\n * @maximum 7\n */\nexport type Day = number;\n\n/**\n * Object for defining datetime in Vega-Lite Filter.\n * If both month and quarter are provided, month has higher precedence.\n * `day` cannot be combined with other date.\n * We accept string for month and day names.\n */\nexport interface DateTime {\n /**\n * Integer value representing the year.\n * @TJS-type integer\n */\n year?: number;\n\n /**\n * Integer value representing the quarter of the year (from 1-4).\n * @minimum 1\n * @maximum 4\n * @TJS-type integer\n */\n quarter?: number;\n\n /**\n * One of:\n * (1) integer value representing the month from `1`-`12`. `1` represents January;\n * (2) case-insensitive month name (e.g., `\"January\"`);\n * (3) case-insensitive, 3-character short month name (e.g., `\"Jan\"`).\n */\n month?: Month | string;\n\n /**\n * Integer value representing the date (day of the month) from 1-31.\n * @minimum 1\n * @maximum 31\n * @TJS-type integer\n */\n date?: number;\n\n /**\n * Value representing the day of a week. This can be one of:\n * (1) integer value -- `1` represents Monday;\n * (2) case-insensitive day name (e.g., `\"Monday\"`);\n * (3) case-insensitive, 3-character short day name (e.g., `\"Mon\"`).\n *\n * **Warning:** A DateTime definition object with `day`** should not be combined with `year`, `quarter`, `month`, or `date`.\n */\n day?: Day | string;\n\n /**\n * Integer value representing the hour of a day from 0-23.\n * @minimum 0\n * @maximum 24\n * @TJS-type integer\n */\n hours?: number;\n\n /**\n * Integer value representing the minute segment of time from 0-59.\n * @minimum 0\n * @maximum 60\n * @TJS-type integer\n */\n minutes?: number;\n\n /**\n * Integer value representing the second segment (0-59) of a time value\n * @minimum 0\n * @maximum 60\n * @TJS-type integer\n */\n seconds?: number;\n\n /**\n * Integer value representing the millisecond segment of time.\n * @minimum 0\n * @maximum 1000\n * @TJS-type integer\n */\n milliseconds?: number;\n\n /**\n * A boolean flag indicating if date time is in utc time. If false, the date time is in local time\n */\n utc?: boolean;\n}\n\n/**\n * Internal Object for defining datetime expressions.\n * This is an expression version of DateTime.\n * If both month and quarter are provided, month has higher precedence.\n * `day` cannot be combined with other date.\n */\nexport interface DateTimeExpr {\n year?: string;\n quarter?: string;\n month?: string;\n date?: string;\n day?: string;\n hours?: string;\n minutes?: string;\n seconds?: string;\n milliseconds?: string;\n utc?: boolean;\n}\n\nexport function isDateTime(o: any): o is DateTime {\n if (o && isObject(o)) {\n for (const part of TIMEUNIT_PARTS) {\n if (part in o) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport const MONTHS = [\n 'january',\n 'february',\n 'march',\n 'april',\n 'may',\n 'june',\n 'july',\n 'august',\n 'september',\n 'october',\n 'november',\n 'december'\n];\nexport const SHORT_MONTHS = MONTHS.map(m => m.substr(0, 3));\n\nexport const DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\nexport const SHORT_DAYS = DAYS.map(d => d.substr(0, 3));\n\nfunction normalizeQuarter(q: number | string): number {\n if (isNumeric(q)) {\n q = +q;\n }\n\n if (isNumber(q)) {\n if (q > 4) {\n log.warn(log.message.invalidTimeUnit('quarter', q));\n }\n // We accept 1-based quarter, so need to readjust to 0-based quarter\n return q - 1;\n } else {\n // Invalid quarter\n throw new Error(log.message.invalidTimeUnit('quarter', q));\n }\n}\n\nfunction normalizeMonth(m: string | number): number {\n if (isNumeric(m)) {\n m = +m;\n }\n\n if (isNumber(m)) {\n // We accept 1-based month, so need to readjust to 0-based month\n return m - 1;\n } else {\n const lowerM = m.toLowerCase();\n const monthIndex = MONTHS.indexOf(lowerM);\n if (monthIndex !== -1) {\n return monthIndex; // 0 for january, ...\n }\n const shortM = lowerM.substr(0, 3);\n const shortMonthIndex = SHORT_MONTHS.indexOf(shortM);\n if (shortMonthIndex !== -1) {\n return shortMonthIndex;\n }\n\n // Invalid month\n throw new Error(log.message.invalidTimeUnit('month', m));\n }\n}\n\nfunction normalizeDay(d: string | number): number {\n if (isNumeric(d)) {\n d = +d;\n }\n\n if (isNumber(d)) {\n // mod so that this can be both 0-based where 0 = sunday\n // and 1-based where 7=sunday\n return d % 7;\n } else {\n const lowerD = d.toLowerCase();\n const dayIndex = DAYS.indexOf(lowerD);\n if (dayIndex !== -1) {\n return dayIndex; // 0 for january, ...\n }\n const shortD = lowerD.substr(0, 3);\n const shortDayIndex = SHORT_DAYS.indexOf(shortD);\n if (shortDayIndex !== -1) {\n return shortDayIndex;\n }\n // Invalid day\n throw new Error(log.message.invalidTimeUnit('day', d));\n }\n}\n\n/**\n * @param d the date.\n * @param normalize whether to normalize quarter, month, day. This should probably be true if d is a DateTime.\n * @returns array of date time parts [year, month, day, hours, minutes, seconds, milliseconds]\n */\nfunction dateTimeParts(d: DateTime | DateTimeExpr, normalize: boolean) {\n const parts: (string | number)[] = [];\n\n if (normalize && d.day !== undefined) {\n if (keys(d).length > 1) {\n log.warn(log.message.droppedDay(d));\n d = duplicate(d);\n delete d.day;\n }\n }\n\n if (d.year !== undefined) {\n parts.push(d.year);\n } else {\n // Just like Vega's timeunit transform, set default year to 2012, so domain conversion will be compatible with Vega\n // Note: 2012 is a leap year (and so the date February 29 is respected) that begins on a Sunday (and so days of the week will order properly at the beginning of the year).\n parts.push(2012);\n }\n\n if (d.month !== undefined) {\n const month = normalize ? normalizeMonth(d.month) : d.month;\n parts.push(month);\n } else if (d.quarter !== undefined) {\n const quarter = normalize ? normalizeQuarter(d.quarter) : d.quarter;\n parts.push(isNumber(quarter) ? quarter * 3 : `${quarter}*3`);\n } else {\n parts.push(0); // months start at zero in JS\n }\n\n if (d.date !== undefined) {\n parts.push(d.date);\n } else if (d.day !== undefined) {\n // HACK: Day only works as a standalone unit\n // This is only correct because we always set year to 2006 for day\n const day = normalize ? normalizeDay(d.day) : d.day;\n parts.push(isNumber(day) ? day + 1 : `${day}+1`);\n } else {\n parts.push(1); // Date starts at 1 in JS\n }\n\n // Note: can't use TimeUnit enum here as importing it will create\n // circular dependency problem!\n for (const timeUnit of ['hours', 'minutes', 'seconds', 'milliseconds'] as const) {\n const unit = d[timeUnit];\n parts.push(typeof unit === 'undefined' ? 0 : unit);\n }\n\n return parts;\n}\n\n/**\n * Return Vega expression for a date time.\n *\n * @param d the date time.\n * @returns the Vega expression.\n */\nexport function dateTimeToExpr(d: DateTime) {\n const parts: (string | number)[] = dateTimeParts(d, true);\n\n const string = parts.join(', ');\n\n if (d.utc) {\n return `utc(${string})`;\n } else {\n return `datetime(${string})`;\n }\n}\n\n/**\n * Return Vega expression for a date time expression.\n *\n * @param d the internal date time object with expression.\n * @returns the Vega expression.\n */\nexport function dateTimeExprToExpr(d: DateTimeExpr) {\n const parts: (string | number)[] = dateTimeParts(d, false);\n\n const string = parts.join(', ');\n\n if (d.utc) {\n return `utc(${string})`;\n } else {\n return `datetime(${string})`;\n }\n}\n\n/**\n * @param d the date time.\n * @returns the timestamp.\n */\nexport function dateTimeToTimestamp(d: DateTime) {\n const parts: (string | number)[] = dateTimeParts(d, true);\n\n if (d.utc) {\n return +new Date(Date.UTC(...(parts as [any, any])));\n } else {\n return +new Date(...(parts as [any]));\n }\n}\n","import {isObject, isString} from 'vega-util';\nimport {DateTime, DateTimeExpr, dateTimeExprToExpr, dateTimeToExpr} from './datetime';\nimport {accessPathWithDatum, keys, stringify, varName} from './util';\n\n/** Time Unit that only corresponds to only one part of Date objects. */\nexport const LOCAL_SINGLE_TIMEUNIT_INDEX = {\n year: 1,\n quarter: 1,\n month: 1,\n week: 1,\n day: 1,\n dayofyear: 1,\n date: 1,\n hours: 1,\n minutes: 1,\n seconds: 1,\n milliseconds: 1\n} as const;\n\nexport type LocalSingleTimeUnit = keyof typeof LOCAL_SINGLE_TIMEUNIT_INDEX;\n\nexport const TIMEUNIT_PARTS = keys(LOCAL_SINGLE_TIMEUNIT_INDEX);\n\nexport function isLocalSingleTimeUnit(timeUnit: string): timeUnit is LocalSingleTimeUnit {\n return !!LOCAL_SINGLE_TIMEUNIT_INDEX[timeUnit];\n}\n\nexport const UTC_SINGLE_TIMEUNIT_INDEX = {\n utcyear: 1,\n utcquarter: 1,\n utcmonth: 1,\n utcweek: 1,\n utcday: 1,\n utcdayofyear: 1,\n utcdate: 1,\n utchours: 1,\n utcminutes: 1,\n utcseconds: 1,\n utcmilliseconds: 1\n} as const;\n\nexport type UtcSingleTimeUnit = keyof typeof UTC_SINGLE_TIMEUNIT_INDEX;\n\nexport type SingleTimeUnit = LocalSingleTimeUnit | UtcSingleTimeUnit;\n\nexport const LOCAL_MULTI_TIMEUNIT_INDEX = {\n yearquarter: 1,\n yearquartermonth: 1,\n\n yearmonth: 1,\n yearmonthdate: 1,\n yearmonthdatehours: 1,\n yearmonthdatehoursminutes: 1,\n yearmonthdatehoursminutesseconds: 1,\n\n yearweek: 1,\n yearweekday: 1,\n yearweekdayhours: 1,\n yearweekdayhoursminutes: 1,\n yearweekdayhoursminutesseconds: 1,\n\n yeardayofyear: 1,\n\n quartermonth: 1,\n\n monthdate: 1,\n monthdatehours: 1,\n monthdatehoursminutes: 1,\n monthdatehoursminutesseconds: 1,\n\n weekday: 1,\n weekdayhours: 1,\n weekdayhoursminutes: 1,\n weekdayhoursminutesseconds: 1,\n\n dayhours: 1,\n dayhoursminutes: 1,\n dayhoursminutesseconds: 1,\n\n hoursminutes: 1,\n hoursminutesseconds: 1,\n\n minutesseconds: 1,\n\n secondsmilliseconds: 1\n} as const;\n\nexport type LocalMultiTimeUnit = keyof typeof LOCAL_MULTI_TIMEUNIT_INDEX;\n\nconst BINNED_LOCAL_TIMEUNIT_INDEX = {\n binnedyear: 1,\n binnedyearquarter: 1,\n binnedyearquartermonth: 1,\n\n binnedyearmonth: 1,\n binnedyearmonthdate: 1,\n binnedyearmonthdatehours: 1,\n binnedyearmonthdatehoursminutes: 1,\n binnedyearmonthdatehoursminutesseconds: 1,\n\n binnedyearweek: 1,\n binnedyearweekday: 1,\n binnedyearweekdayhours: 1,\n binnedyearweekdayhoursminutes: 1,\n binnedyearweekdayhoursminutesseconds: 1,\n\n binnedyeardayofyear: 1\n} as const;\n\ntype BinnedLocalTimeUnit = keyof typeof BINNED_LOCAL_TIMEUNIT_INDEX;\n\nconst BINNED_UTC_TIMEUNIT_INDEX = {\n binnedutcyear: 1,\n binnedutcyearquarter: 1,\n binnedutcyearquartermonth: 1,\n\n binnedutcyearmonth: 1,\n binnedutcyearmonthdate: 1,\n binnedutcyearmonthdatehours: 1,\n binnedutcyearmonthdatehoursminutes: 1,\n binnedutcyearmonthdatehoursminutesseconds: 1,\n\n binnedutcyearweek: 1,\n binnedutcyearweekday: 1,\n binnedutcyearweekdayhours: 1,\n binnedutcyearweekdayhoursminutes: 1,\n binnedutcyearweekdayhoursminutesseconds: 1,\n\n binnedutcyeardayofyear: 1\n};\n\nexport const BINNED_TIMEUNIT_INDEX = {\n ...BINNED_LOCAL_TIMEUNIT_INDEX,\n ...BINNED_UTC_TIMEUNIT_INDEX\n};\n\ntype BinnedUtcTimeUnit = keyof typeof BINNED_UTC_TIMEUNIT_INDEX;\n\nexport type BinnedTimeUnit = BinnedLocalTimeUnit | BinnedUtcTimeUnit;\n\nexport function isBinnedTimeUnit(\n timeUnit: TimeUnit | BinnedTimeUnit | TimeUnitParams | undefined\n): timeUnit is BinnedTimeUnit | TimeUnitParams {\n if (isObject(timeUnit)) {\n return timeUnit.binned;\n }\n return isBinnedTimeUnitString(timeUnit);\n}\n\nexport function isBinnedTimeUnitString(timeUnit: TimeUnit | BinnedTimeUnit | undefined): timeUnit is BinnedTimeUnit {\n return timeUnit && timeUnit.startsWith('binned');\n}\n\nexport const UTC_MULTI_TIMEUNIT_INDEX = {\n utcyearquarter: 1,\n utcyearquartermonth: 1,\n\n utcyearmonth: 1,\n utcyearmonthdate: 1,\n utcyearmonthdatehours: 1,\n utcyearmonthdatehoursminutes: 1,\n utcyearmonthdatehoursminutesseconds: 1,\n\n utcyearweek: 1,\n utcyearweekday: 1,\n utcyearweekdayhours: 1,\n utcyearweekdayhoursminutes: 1,\n utcyearweekdayhoursminutesseconds: 1,\n\n utcyeardayofyear: 1,\n\n utcquartermonth: 1,\n\n utcmonthdate: 1,\n utcmonthdatehours: 1,\n utcmonthdatehoursminutes: 1,\n utcmonthdatehoursminutesseconds: 1,\n\n utcweekday: 1,\n utcweekdayhours: 1,\n utcweekdayhoursminutes: 1,\n utcweekdayhoursminutesseconds: 1,\n\n utcdayhours: 1,\n utcdayhoursminutes: 1,\n utcdayhoursminutesseconds: 1,\n\n utchoursminutes: 1,\n utchoursminutesseconds: 1,\n\n utcminutesseconds: 1,\n\n utcsecondsmilliseconds: 1\n} as const;\n\nexport type UtcMultiTimeUnit = keyof typeof UTC_MULTI_TIMEUNIT_INDEX;\n\nexport type MultiTimeUnit = LocalMultiTimeUnit | UtcMultiTimeUnit;\n\nexport type LocalTimeUnit = LocalSingleTimeUnit | LocalMultiTimeUnit;\nexport type UtcTimeUnit = UtcSingleTimeUnit | UtcMultiTimeUnit;\n\nexport function isUTCTimeUnit(t: string): t is UtcTimeUnit {\n return t.startsWith('utc');\n}\n\nexport function getLocalTimeUnitFromUTCTimeUnit(t: UtcTimeUnit): LocalTimeUnit {\n return t.substring(3) as LocalTimeUnit;\n}\n\nexport type TimeUnit = SingleTimeUnit | MultiTimeUnit;\n\nexport type TimeUnitFormat =\n | 'year'\n | 'year-month'\n | 'year-month-date'\n | 'quarter'\n | 'month'\n | 'date'\n | 'week'\n | 'day'\n | 'hours'\n | 'hours-minutes'\n | 'minutes'\n | 'seconds'\n | 'milliseconds';\n\nexport interface TimeUnitTransformParams {\n /**\n * Defines how date-time values should be binned.\n */\n unit?: TimeUnit;\n\n /**\n * If no `unit` is specified, maxbins is used to infer time units.\n */\n maxbins?: number;\n\n /**\n * The number of steps between bins, in terms of the least\n * significant unit provided.\n */\n step?: number;\n\n /**\n * True to use UTC timezone. Equivalent to using a `utc` prefixed `TimeUnit`.\n */\n utc?: boolean;\n}\n\n/**\n * Time Unit Params for encoding predicate, which can specified if the data is already \"binned\".\n */\nexport interface TimeUnitParams extends TimeUnitTransformParams {\n /**\n * Whether the data has already been binned to this time unit.\n * If true, Vega-Lite will only format the data, marks, and guides,\n * without applying the timeUnit transform to re-bin the data again.\n */\n binned?: boolean;\n}\n\n// matches vega time unit format specifier\nexport type TimeFormatConfig = Partial>;\n\n// In order of increasing specificity\nexport const VEGALITE_TIMEFORMAT: TimeFormatConfig = {\n 'year-month': '%b %Y ',\n 'year-month-date': '%b %d, %Y '\n};\n\nexport function getTimeUnitParts(timeUnit: TimeUnit): LocalSingleTimeUnit[] {\n return TIMEUNIT_PARTS.filter(part => containsTimeUnit(timeUnit, part));\n}\n\nexport function getSmallestTimeUnitPart(timeUnit: TimeUnit): LocalSingleTimeUnit {\n const parts = getTimeUnitParts(timeUnit);\n return parts[parts.length - 1];\n}\n\n/** Returns true if fullTimeUnit contains the timeUnit, false otherwise. */\nexport function containsTimeUnit(fullTimeUnit: TimeUnit, timeUnit: TimeUnit) {\n const index = fullTimeUnit.indexOf(timeUnit);\n\n if (index < 0) {\n return false;\n }\n\n // exclude milliseconds\n if (index > 0 && timeUnit === 'seconds' && fullTimeUnit.charAt(index - 1) === 'i') {\n return false;\n }\n\n // exclude dayofyear\n if (fullTimeUnit.length > index + 3 && timeUnit === 'day' && fullTimeUnit.charAt(index + 3) === 'o') {\n return false;\n }\n if (index > 0 && timeUnit === 'year' && fullTimeUnit.charAt(index - 1) === 'f') {\n return false;\n }\n\n return true;\n}\n\n/**\n * Returns Vega expression for a given timeUnit and fieldRef\n */\nexport function fieldExpr(fullTimeUnit: TimeUnit, field: string, {end}: {end: boolean} = {end: false}): string {\n const fieldRef = accessPathWithDatum(field);\n\n const utc = isUTCTimeUnit(fullTimeUnit) ? 'utc' : '';\n\n function func(timeUnit: TimeUnit) {\n if (timeUnit === 'quarter') {\n // quarter starting at 0 (0,3,6,9).\n return `(${utc}quarter(${fieldRef})-1)`;\n } else {\n return `${utc}${timeUnit}(${fieldRef})`;\n }\n }\n\n let lastTimeUnit: TimeUnit;\n\n const dateExpr: DateTimeExpr = {};\n\n for (const part of TIMEUNIT_PARTS) {\n if (containsTimeUnit(fullTimeUnit, part)) {\n dateExpr[part] = func(part);\n lastTimeUnit = part;\n }\n }\n\n if (end) {\n dateExpr[lastTimeUnit] += '+1';\n }\n\n return dateTimeExprToExpr(dateExpr);\n}\n\nexport function timeUnitSpecifierExpression(timeUnit: TimeUnit) {\n if (!timeUnit) {\n return undefined;\n }\n\n const timeUnitParts = getTimeUnitParts(timeUnit);\n return `timeUnitSpecifier(${stringify(timeUnitParts)}, ${stringify(VEGALITE_TIMEFORMAT)})`;\n}\n\n/**\n * Returns the signal expression used for axis labels for a time unit.\n */\nexport function formatExpression(timeUnit: TimeUnit, field: string, isUTCScale: boolean): string {\n if (!timeUnit) {\n return undefined;\n }\n\n const expr = timeUnitSpecifierExpression(timeUnit);\n\n // We only use utcFormat for utc scale\n // For utc time units, the data is already converted as a part of timeUnit transform.\n // Thus, utc time units should use timeFormat to avoid shifting the time twice.\n const utc = isUTCScale || isUTCTimeUnit(timeUnit);\n\n return `${utc ? 'utc' : 'time'}Format(${field}, ${expr})`;\n}\n\nexport function normalizeTimeUnit(timeUnit: TimeUnit | BinnedTimeUnit | TimeUnitParams): TimeUnitParams {\n if (!timeUnit) {\n return undefined;\n }\n\n let params: TimeUnitParams;\n if (isString(timeUnit)) {\n if (isBinnedTimeUnitString(timeUnit)) {\n params = {\n unit: timeUnit.substring(6) as TimeUnit,\n binned: true\n };\n } else {\n params = {\n unit: timeUnit\n };\n }\n } else if (isObject(timeUnit)) {\n params = {\n ...timeUnit,\n ...(timeUnit.unit ? {unit: timeUnit.unit} : {})\n };\n }\n\n if (isUTCTimeUnit(params.unit)) {\n params.utc = true;\n params.unit = getLocalTimeUnitFromUTCTimeUnit(params.unit);\n }\n\n return params;\n}\n\nexport function timeUnitToString(tu: TimeUnit | TimeUnitTransformParams) {\n const {utc, ...rest} = normalizeTimeUnit(tu);\n\n if (rest.unit) {\n return (\n (utc ? 'utc' : '') +\n keys(rest)\n .map(p => varName(`${p === 'unit' ? '' : `_${p}_`}${rest[p]}`))\n .join('')\n );\n } else {\n // when maxbins is specified instead of units\n return (\n (utc ? 'utc' : '') +\n 'timeunit' +\n keys(rest)\n .map(p => varName(`_${p}_${rest[p]}`))\n .join('')\n );\n }\n}\n\nexport function durationExpr(\n timeUnit: TimeUnit | BinnedTimeUnit | TimeUnitTransformParams,\n wrap: (x: string) => string = x => x\n) {\n const normalizedTimeUnit = normalizeTimeUnit(timeUnit);\n const smallestUnitPart = getSmallestTimeUnitPart(normalizedTimeUnit.unit);\n if (smallestUnitPart && smallestUnitPart !== 'day') {\n const startDate: DateTime = {\n year: 2001, // pick a non-leap year\n month: 1,\n date: 1,\n hours: 0,\n minutes: 0,\n seconds: 0,\n milliseconds: 0\n };\n const {step, part} = getDateTimePartAndStep(smallestUnitPart, normalizedTimeUnit.step);\n const endDate: DateTime = {\n ...startDate,\n [part]: +startDate[part] + step\n };\n\n // Calculate timestamp duration for the smallest unit listed\n return `${wrap(dateTimeToExpr(endDate))} - ${wrap(dateTimeToExpr(startDate))}`;\n }\n return undefined;\n}\n\nconst DATE_PARTS = {\n year: 1,\n month: 1,\n date: 1,\n hours: 1,\n minutes: 1,\n seconds: 1,\n milliseconds: 1\n} as const;\n\ntype DatePart = keyof typeof DATE_PARTS;\n\nexport function isDatePart(timeUnit: LocalSingleTimeUnit): timeUnit is DatePart {\n return !!DATE_PARTS[timeUnit];\n}\n\nexport function getDateTimePartAndStep(\n timeUnit: LocalSingleTimeUnit,\n step = 1\n): {\n part: keyof DateTime;\n step: number;\n} {\n if (isDatePart(timeUnit)) {\n return {part: timeUnit, step};\n }\n switch (timeUnit) {\n case 'day':\n case 'dayofyear':\n return {part: 'date', step};\n case 'quarter':\n return {part: 'month', step: step * 3};\n case 'week':\n return {part: 'date', step: step * 7};\n }\n}\n","import type {SignalRef} from 'vega';\nimport {isArray} from 'vega-util';\nimport {FieldName, valueExpr, vgField} from './channeldef';\nimport {DateTime} from './datetime';\nimport {ExprRef} from './expr';\nimport {LogicalComposition} from './logical';\nimport {ParameterName} from './parameter';\nimport {fieldExpr as timeUnitFieldExpr, normalizeTimeUnit, TimeUnit, TimeUnitParams, BinnedTimeUnit} from './timeunit';\nimport {stringify} from './util';\nimport {isSignalRef} from './vega.schema';\n\nexport type Predicate =\n // a) FieldPredicate (but we don't type FieldFilter here so the schema has no nesting\n // and thus the documentation shows all of the types clearly)\n | FieldEqualPredicate\n | FieldRangePredicate\n | FieldOneOfPredicate\n | FieldLTPredicate\n | FieldGTPredicate\n | FieldLTEPredicate\n | FieldGTEPredicate\n | FieldValidPredicate\n // b) Selection Predicate\n | ParameterPredicate\n // c) Vega Expression string\n | string;\n\nexport type FieldPredicate =\n | FieldEqualPredicate\n | FieldLTPredicate\n | FieldGTPredicate\n | FieldLTEPredicate\n | FieldGTEPredicate\n | FieldRangePredicate\n | FieldOneOfPredicate\n | FieldValidPredicate;\n\nexport interface ParameterPredicate {\n /**\n * Filter using a parameter name.\n */\n param: ParameterName;\n /**\n * For selection parameters, the predicate of empty selections returns true by default.\n * Override this behavior, by setting this property `empty: false`.\n */\n empty?: boolean;\n}\n\nexport function isSelectionPredicate(predicate: LogicalComposition): predicate is ParameterPredicate {\n return predicate?.['param'];\n}\n\nexport interface FieldPredicateBase {\n // TODO: support aggregate\n\n /**\n * Time unit for the field to be tested.\n */\n timeUnit?: TimeUnit | BinnedTimeUnit | TimeUnitParams;\n\n /**\n * Field to be tested.\n */\n field: FieldName;\n}\n\nexport interface FieldEqualPredicate extends FieldPredicateBase {\n /**\n * The value that the field should be equal to.\n */\n equal: string | number | boolean | DateTime | ExprRef | SignalRef;\n}\n\nexport function isFieldEqualPredicate(predicate: any): predicate is FieldEqualPredicate {\n return !!predicate?.field && predicate.equal !== undefined;\n}\n\nexport interface FieldLTPredicate extends FieldPredicateBase {\n /**\n * The value that the field should be less than.\n */\n lt: string | number | DateTime | ExprRef | SignalRef;\n}\n\nexport function isFieldLTPredicate(predicate: any): predicate is FieldLTPredicate {\n return !!predicate?.field && predicate.lt !== undefined;\n}\n\nexport interface FieldLTEPredicate extends FieldPredicateBase {\n /**\n * The value that the field should be less than or equals to.\n */\n lte: string | number | DateTime | ExprRef | SignalRef;\n}\n\nexport function isFieldLTEPredicate(predicate: any): predicate is FieldLTEPredicate {\n return !!predicate?.field && predicate.lte !== undefined;\n}\n\nexport interface FieldGTPredicate extends FieldPredicateBase {\n /**\n * The value that the field should be greater than.\n */\n gt: string | number | DateTime | ExprRef | SignalRef;\n}\n\nexport function isFieldGTPredicate(predicate: any): predicate is FieldGTPredicate {\n return !!predicate?.field && predicate.gt !== undefined;\n}\n\nexport interface FieldGTEPredicate extends FieldPredicateBase {\n /**\n * The value that the field should be greater than or equals to.\n */\n gte: string | number | DateTime | ExprRef | SignalRef;\n}\n\nexport function isFieldGTEPredicate(predicate: any): predicate is FieldGTEPredicate {\n return !!predicate?.field && predicate.gte !== undefined;\n}\n\nexport interface FieldRangePredicate extends FieldPredicateBase {\n /**\n * An array of inclusive minimum and maximum values\n * for a field value of a data item to be included in the filtered data.\n * @maxItems 2\n * @minItems 2\n */\n range: (number | DateTime | null | ExprRef | SignalRef)[] | ExprRef | SignalRef;\n}\n\nexport function isFieldRangePredicate(predicate: any): predicate is FieldRangePredicate {\n if (predicate?.field) {\n if (isArray(predicate.range) && predicate.range.length === 2) {\n return true;\n } else if (isSignalRef(predicate.range)) {\n return true;\n }\n }\n return false;\n}\n\nexport interface FieldOneOfPredicate extends FieldPredicateBase {\n /**\n * A set of values that the `field`'s value should be a member of,\n * for a data item included in the filtered data.\n */\n oneOf: string[] | number[] | boolean[] | DateTime[];\n}\n\nexport interface FieldValidPredicate extends FieldPredicateBase {\n /**\n * If set to true the field's value has to be valid, meaning both not `null` and not [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN).\n */\n valid: boolean;\n}\n\nexport function isFieldOneOfPredicate(predicate: any): predicate is FieldOneOfPredicate {\n return (\n !!predicate?.field && (isArray(predicate.oneOf) || isArray(predicate.in)) // backward compatibility\n );\n}\n\nexport function isFieldValidPredicate(predicate: any): predicate is FieldValidPredicate {\n return !!predicate?.field && predicate.valid !== undefined;\n}\n\nexport function isFieldPredicate(\n predicate: Predicate\n): predicate is\n | FieldOneOfPredicate\n | FieldEqualPredicate\n | FieldRangePredicate\n | FieldLTPredicate\n | FieldGTPredicate\n | FieldLTEPredicate\n | FieldGTEPredicate {\n return (\n isFieldOneOfPredicate(predicate) ||\n isFieldEqualPredicate(predicate) ||\n isFieldRangePredicate(predicate) ||\n isFieldLTPredicate(predicate) ||\n isFieldGTPredicate(predicate) ||\n isFieldLTEPredicate(predicate) ||\n isFieldGTEPredicate(predicate)\n );\n}\n\nfunction predicateValueExpr(v: number | string | boolean | DateTime | ExprRef | SignalRef, timeUnit: TimeUnit) {\n return valueExpr(v, {timeUnit, wrapTime: true});\n}\n\nfunction predicateValuesExpr(vals: (number | string | boolean | DateTime)[], timeUnit: TimeUnit) {\n return vals.map(v => predicateValueExpr(v, timeUnit));\n}\n\n// This method is used by Voyager. Do not change its behavior without changing Voyager.\nexport function fieldFilterExpression(predicate: FieldPredicate, useInRange = true) {\n const {field} = predicate;\n const normalizedTimeUnit = normalizeTimeUnit(predicate.timeUnit);\n const {unit, binned} = normalizedTimeUnit || {};\n const rawFieldExpr = vgField(predicate, {expr: 'datum'});\n const fieldExpr = unit\n ? // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly.\n // TODO: We calculate timeUnit on the fly here. Consider if we would like to consolidate this with timeUnit pipeline\n // TODO: support utc\n `time(${!binned ? timeUnitFieldExpr(unit, field) : rawFieldExpr})`\n : rawFieldExpr;\n\n if (isFieldEqualPredicate(predicate)) {\n return `${fieldExpr}===${predicateValueExpr(predicate.equal, unit)}`;\n } else if (isFieldLTPredicate(predicate)) {\n const upper = predicate.lt;\n return `${fieldExpr}<${predicateValueExpr(upper, unit)}`;\n } else if (isFieldGTPredicate(predicate)) {\n const lower = predicate.gt;\n return `${fieldExpr}>${predicateValueExpr(lower, unit)}`;\n } else if (isFieldLTEPredicate(predicate)) {\n const upper = predicate.lte;\n return `${fieldExpr}<=${predicateValueExpr(upper, unit)}`;\n } else if (isFieldGTEPredicate(predicate)) {\n const lower = predicate.gte;\n return `${fieldExpr}>=${predicateValueExpr(lower, unit)}`;\n } else if (isFieldOneOfPredicate(predicate)) {\n return `indexof([${predicateValuesExpr(predicate.oneOf, unit).join(',')}], ${fieldExpr}) !== -1`;\n } else if (isFieldValidPredicate(predicate)) {\n return fieldValidPredicate(fieldExpr, predicate.valid);\n } else if (isFieldRangePredicate(predicate)) {\n const {range} = predicate;\n const lower = isSignalRef(range) ? {signal: `${range.signal}[0]`} : range[0];\n const upper = isSignalRef(range) ? {signal: `${range.signal}[1]`} : range[1];\n\n if (lower !== null && upper !== null && useInRange) {\n return (\n 'inrange(' + fieldExpr + ', [' + predicateValueExpr(lower, unit) + ', ' + predicateValueExpr(upper, unit) + '])'\n );\n }\n\n const exprs = [];\n if (lower !== null) {\n exprs.push(`${fieldExpr} >= ${predicateValueExpr(lower, unit)}`);\n }\n if (upper !== null) {\n exprs.push(`${fieldExpr} <= ${predicateValueExpr(upper, unit)}`);\n }\n\n return exprs.length > 0 ? exprs.join(' && ') : 'true';\n }\n\n /* istanbul ignore next: it should never reach here */\n throw new Error(`Invalid field predicate: ${stringify(predicate)}`);\n}\n\nexport function fieldValidPredicate(fieldExpr: string, valid = true) {\n if (valid) {\n return `isValid(${fieldExpr}) && isFinite(+${fieldExpr})`;\n } else {\n return `!isValid(${fieldExpr}) || !isFinite(+${fieldExpr})`;\n }\n}\n\nexport function normalizePredicate(f: Predicate): Predicate {\n if (isFieldPredicate(f) && f.timeUnit) {\n return {\n ...f,\n timeUnit: normalizeTimeUnit(f.timeUnit)\n };\n }\n return f;\n}\n","import {keys} from './util';\n\n/**\n * Data type based on level of measurement\n */\nexport const Type = {\n quantitative: 'quantitative',\n ordinal: 'ordinal',\n temporal: 'temporal',\n nominal: 'nominal',\n geojson: 'geojson'\n} as const;\n\nexport type Type = keyof typeof Type;\n\nexport function isType(t: any): t is Type {\n return t in Type;\n}\n\nexport function isContinuous(type: Type): type is 'quantitative' | 'temporal' {\n return type === 'quantitative' || type === 'temporal';\n}\nexport function isDiscrete(type: Type): type is 'ordinal' | 'nominal' {\n return type === 'ordinal' || type === 'nominal';\n}\n\nexport const QUANTITATIVE = Type.quantitative;\nexport const ORDINAL = Type.ordinal;\nexport const TEMPORAL = Type.temporal;\nexport const NOMINAL = Type.nominal;\n\nexport const GEOJSON = Type.geojson;\n\nexport type StandardType = 'quantitative' | 'ordinal' | 'temporal' | 'nominal';\n\nexport const TYPES = keys(Type);\n\n/**\n * Get full, lowercase type name for a given type.\n * @param type\n * @return Full type name.\n */\nexport function getFullName(type: Type | string): Type | undefined {\n if (type) {\n type = type.toLowerCase();\n switch (type) {\n case 'q':\n case QUANTITATIVE:\n return 'quantitative';\n case 't':\n case TEMPORAL:\n return 'temporal';\n case 'o':\n case ORDINAL:\n return 'ordinal';\n case 'n':\n case NOMINAL:\n return 'nominal';\n case GEOJSON:\n return 'geojson';\n }\n }\n // If we get invalid input, return undefined type.\n return undefined;\n}\n","import {\n isObject,\n RangeEnum,\n ScaleBins,\n ScaleInterpolateEnum,\n ScaleInterpolateParams,\n SignalRef,\n TimeInterval,\n TimeIntervalStep\n} from 'vega';\nimport type {ColorScheme} from 'vega-typings';\nimport {isString} from 'vega-util';\nimport * as CHANNEL from './channel';\nimport {Channel, isColorChannel} from './channel';\nimport {DateTime} from './datetime';\nimport {ExprRef} from './expr';\nimport {ScaleInvalidDataConfigMixins} from './invalid';\nimport * as log from './log';\nimport {ParameterExtent} from './selection';\nimport {NOMINAL, ORDINAL, QUANTITATIVE, TEMPORAL, Type} from './type';\nimport {contains, Flag, keys} from './util';\n\nexport const ScaleType = {\n // Continuous - Quantitative\n LINEAR: 'linear',\n LOG: 'log',\n POW: 'pow',\n SQRT: 'sqrt',\n SYMLOG: 'symlog',\n\n IDENTITY: 'identity',\n SEQUENTIAL: 'sequential',\n\n // Continuous - Time\n TIME: 'time',\n UTC: 'utc',\n\n // Discretizing scales\n QUANTILE: 'quantile',\n QUANTIZE: 'quantize',\n THRESHOLD: 'threshold',\n BIN_ORDINAL: 'bin-ordinal',\n\n // Discrete scales\n ORDINAL: 'ordinal',\n POINT: 'point',\n BAND: 'band'\n} as const;\n\ntype ValueOf = T[keyof T];\nexport type ScaleType = ValueOf;\n\n/**\n * Index for scale categories -- only scale of the same categories can be merged together.\n * Current implementation is trying to be conservative and avoid merging scale type that might not work together\n */\nexport const SCALE_CATEGORY_INDEX: Record = {\n linear: 'numeric',\n log: 'numeric',\n pow: 'numeric',\n sqrt: 'numeric',\n symlog: 'numeric',\n identity: 'numeric',\n sequential: 'numeric',\n time: 'time',\n utc: 'time',\n ordinal: 'ordinal',\n 'bin-ordinal': 'bin-ordinal', // TODO: should bin-ordinal support merging with other\n point: 'ordinal-position',\n band: 'ordinal-position',\n quantile: 'discretizing',\n quantize: 'discretizing',\n threshold: 'discretizing'\n};\n\nexport const SCALE_TYPES: ScaleType[] = keys(SCALE_CATEGORY_INDEX);\n\n/**\n * Whether the two given scale types can be merged together.\n */\nexport function scaleCompatible(scaleType1: ScaleType, scaleType2: ScaleType) {\n const scaleCategory1 = SCALE_CATEGORY_INDEX[scaleType1];\n const scaleCategory2 = SCALE_CATEGORY_INDEX[scaleType2];\n return (\n scaleCategory1 === scaleCategory2 ||\n (scaleCategory1 === 'ordinal-position' && scaleCategory2 === 'time') ||\n (scaleCategory2 === 'ordinal-position' && scaleCategory1 === 'time')\n );\n}\n\n/**\n * Index for scale precedence -- high score = higher priority for merging.\n */\nconst SCALE_PRECEDENCE_INDEX: Record = {\n // numeric\n linear: 0,\n log: 1,\n pow: 1,\n sqrt: 1,\n symlog: 1,\n identity: 1,\n sequential: 1,\n // time\n time: 0,\n utc: 0,\n // ordinal-position -- these have higher precedence than continuous scales as they support more types of data\n point: 10,\n band: 11, // band has higher precedence as it is better for interaction\n // non grouped types\n ordinal: 0,\n 'bin-ordinal': 0,\n quantile: 0,\n quantize: 0,\n threshold: 0\n};\n\n/**\n * Return scale categories -- only scale of the same categories can be merged together.\n */\nexport function scaleTypePrecedence(scaleType: ScaleType): number {\n return SCALE_PRECEDENCE_INDEX[scaleType];\n}\n\nexport const QUANTITATIVE_SCALES = new Set([\n 'linear',\n 'log',\n 'pow',\n 'sqrt',\n 'symlog'\n]) as ReadonlySet;\n\nexport const CONTINUOUS_TO_CONTINUOUS_SCALES = new Set([\n ...QUANTITATIVE_SCALES,\n 'time',\n 'utc'\n]) as ReadonlySet;\n\nexport function isQuantitative(type: ScaleType): type is 'linear' | 'log' | 'pow' | 'sqrt' | 'symlog' {\n return QUANTITATIVE_SCALES.has(type);\n}\n\nexport const CONTINUOUS_TO_DISCRETE_SCALES = new Set([\n 'quantile',\n 'quantize',\n 'threshold'\n]) as ReadonlySet;\n\nexport const CONTINUOUS_DOMAIN_SCALES = new Set([\n ...CONTINUOUS_TO_CONTINUOUS_SCALES,\n ...CONTINUOUS_TO_DISCRETE_SCALES,\n 'sequential',\n 'identity'\n]) as ReadonlySet;\n\nexport const DISCRETE_DOMAIN_SCALES = new Set([\n 'ordinal',\n 'bin-ordinal',\n 'point',\n 'band'\n]) as ReadonlySet;\n\nexport const TIME_SCALE_TYPES = new Set(['time', 'utc']) as ReadonlySet;\n\nexport function hasDiscreteDomain(type: ScaleType): type is 'ordinal' | 'bin-ordinal' | 'point' | 'band' {\n return DISCRETE_DOMAIN_SCALES.has(type);\n}\n\nexport function hasContinuousDomain(\n type: ScaleType\n): type is 'linear' | 'log' | 'pow' | 'sqrt' | 'symlog' | 'time' | 'utc' | 'quantile' | 'quantize' | 'threshold' {\n return CONTINUOUS_DOMAIN_SCALES.has(type);\n}\n\nexport function isContinuousToContinuous(\n type: ScaleType\n): type is 'linear' | 'log' | 'pow' | 'sqrt' | 'symlog' | 'time' | 'utc' {\n return CONTINUOUS_TO_CONTINUOUS_SCALES.has(type);\n}\n\nexport function isContinuousToDiscrete(type: ScaleType): type is 'quantile' | 'quantize' | 'threshold' {\n return CONTINUOUS_TO_DISCRETE_SCALES.has(type);\n}\n\nexport interface ScaleConfig extends ScaleInvalidDataConfigMixins {\n /**\n * If true, rounds numeric output values to integers.\n * This can be helpful for snapping to the pixel grid.\n * (Only available for `x`, `y`, and `size` scales.)\n */\n round?: boolean | ES;\n\n /**\n * If true, values that exceed the data domain are clamped to either the minimum or maximum range value\n */\n clamp?: boolean | ES;\n\n /**\n * Default inner padding for `x` and `y` band scales with nested `xOffset` and `yOffset` encoding.\n *\n * __Default value:__ `0.2`\n *\n * @minimum 0\n * @maximum 1\n */\n bandWithNestedOffsetPaddingInner?: number | ES;\n\n /**\n * Default outer padding for `x` and `y` band scales with nested `xOffset` and `yOffset` encoding.\n *\n * __Default value:__ `0.2`\n *\n * @minimum 0\n * @maximum 1\n */\n // Note: nested offset always uses band scale, so we don't need \"band\" in the name for brevity.\n bandWithNestedOffsetPaddingOuter?: number | ES;\n\n /**\n * Default inner padding for `x` and `y` band scales.\n *\n * __Default value:__\n * - `nestedOffsetPaddingInner` for x/y scales with nested x/y offset scales.\n * - `barBandPaddingInner` for bar marks (`0.1` by default)\n * - `rectBandPaddingInner` for rect and other marks (`0` by default)\n *\n * @minimum 0\n * @maximum 1\n */\n bandPaddingInner?: number | ES;\n\n /**\n * Default outer padding for `x` and `y` band scales.\n *\n * __Default value:__ `paddingInner/2` (which makes _width/height = number of unique values * step_)\n *\n * @minimum 0\n * @maximum 1\n */\n bandPaddingOuter?: number | ES;\n\n /**\n * Default inner padding for `x` and `y` band-ordinal scales of `\"bar\"` marks.\n *\n * __Default value:__ `0.1`\n *\n * @minimum 0\n * @maximum 1\n */\n barBandPaddingInner?: number | ES;\n\n /**\n * Default inner padding for `x` and `y` band-ordinal scales of `\"rect\"` marks.\n *\n * __Default value:__ `0`\n *\n * @minimum 0\n * @maximum 1\n */\n rectBandPaddingInner?: number | ES;\n\n /**\n * Default inner padding for `x` and `y` band-ordinal scales of `\"tick\"` marks.\n *\n * __Default value:__ `0.25`\n *\n * @minimum 0\n * @maximum 1\n */\n tickBandPaddingInner?: number | ES;\n\n /**\n * Default padding inner for xOffset/yOffset's band scales.\n *\n * __Default Value:__ `0`\n */\n offsetBandPaddingInner?: number | ES;\n\n /**\n * Default padding outer for xOffset/yOffset's band scales.\n *\n * __Default Value:__ `0`\n */\n offsetBandPaddingOuter?: number | ES;\n\n /**\n * Default padding for continuous x/y scales.\n *\n * __Default:__ The bar width for continuous x-scale of a vertical bar and continuous y-scale of a horizontal bar.; `0` otherwise.\n *\n * @minimum 0\n */\n continuousPadding?: number | ES;\n\n /**\n * Default outer padding for `x` and `y` point-ordinal scales.\n *\n * __Default value:__ `0.5` (which makes _width/height = number of unique values * step_)\n *\n * @minimum 0\n * @maximum 1\n */\n pointPadding?: number | ES;\n\n /**\n * Use the source data range before aggregation as scale domain instead of aggregated data for aggregate axis.\n *\n * This is equivalent to setting `domain` to `\"unaggregate\"` for aggregated _quantitative_ fields by default.\n *\n * This property only works with aggregate functions that produce values within the raw data domain (`\"mean\"`, `\"average\"`, `\"median\"`, `\"q1\"`, `\"q3\"`, `\"min\"`, `\"max\"`). For other aggregations that produce values outside of the raw data domain (e.g. `\"count\"`, `\"sum\"`), this property is ignored.\n *\n * __Default value:__ `false`\n */\n useUnaggregatedDomain?: boolean;\n\n // nice should depends on type (quantitative or temporal), so\n // let's not make a config.\n\n // Configs for Range\n\n /**\n * The default max value for mapping quantitative fields to bar's size/bandSize.\n *\n * If undefined (default), we will use the axis's size (width or height) - 1.\n * @minimum 0\n */\n maxBandSize?: number;\n\n /**\n * The default min value for mapping quantitative fields to bar and tick's size/bandSize scale.\n *\n * __Default value:__ `2`\n *\n * @minimum 0\n */\n minBandSize?: number;\n\n /**\n * The default max value for mapping quantitative fields to text's size/fontSize scale.\n *\n * __Default value:__ `40`\n *\n * @minimum 0\n */\n maxFontSize?: number;\n\n /**\n * The default min value for mapping quantitative fields to text's size/fontSize scale.\n *\n * __Default value:__ `8`\n *\n * @minimum 0\n */\n minFontSize?: number;\n\n /**\n * Default minimum opacity for mapping a field to opacity.\n *\n * __Default value:__ `0.3`\n *\n * @minimum 0\n * @maximum 1\n */\n minOpacity?: number;\n\n /**\n * Default max opacity for mapping a field to opacity.\n *\n * __Default value:__ `0.8`\n *\n * @minimum 0\n * @maximum 1\n */\n maxOpacity?: number;\n\n /**\n * Default minimum value for point size scale.\n *\n * __Default value:__ `9`\n *\n * @minimum 0\n */\n minSize?: number;\n\n /**\n * Default max value for point size scale.\n * @minimum 0\n */\n maxSize?: number;\n\n /**\n * Default minimum strokeWidth for the scale of strokeWidth for rule and line marks and of size for trail marks.\n *\n * __Default value:__ `1`\n *\n * @minimum 0\n */\n minStrokeWidth?: number;\n\n /**\n * Default max strokeWidth for the scale of strokeWidth for rule and line marks and of size for trail marks.\n *\n * __Default value:__ `4`\n *\n * @minimum 0\n */\n maxStrokeWidth?: number;\n\n /**\n * Default range cardinality for [`quantile`](https://vega.github.io/vega-lite/docs/scale.html#quantile) scale.\n *\n * __Default value:__ `4`\n *\n * @minimum 0\n */\n quantileCount?: number;\n\n /**\n * Default range cardinality for [`quantize`](https://vega.github.io/vega-lite/docs/scale.html#quantize) scale.\n *\n * __Default value:__ `4`\n *\n * @minimum 0\n */\n quantizeCount?: number;\n\n /**\n * Reverse x-scale by default (useful for right-to-left charts).\n */\n xReverse?: boolean | ES;\n\n /**\n * Default `scale.zero` for [`continuous`](https://vega.github.io/vega-lite/docs/scale.html#continuous) scales except for (1) x/y-scales of non-ranged bar or area charts and (2) size scales.\n *\n * __Default value:__ `true`\n *\n */\n zero?: boolean;\n}\n\nexport const defaultScaleConfig: ScaleConfig = {\n pointPadding: 0.5,\n\n barBandPaddingInner: 0.1,\n rectBandPaddingInner: 0,\n tickBandPaddingInner: 0.25,\n\n bandWithNestedOffsetPaddingInner: 0.2,\n bandWithNestedOffsetPaddingOuter: 0.2,\n\n minBandSize: 2,\n\n minFontSize: 8,\n maxFontSize: 40,\n\n minOpacity: 0.3,\n maxOpacity: 0.8,\n\n // FIXME: revise if these *can* become ratios of width/height step\n minSize: 4, // Point size is area. For square point, 9 = 3 pixel ^ 2, not too small!\n\n minStrokeWidth: 1,\n maxStrokeWidth: 4,\n quantileCount: 4,\n quantizeCount: 4,\n\n zero: true\n};\n\nexport interface SchemeParams {\n /**\n * A color scheme name for ordinal scales (e.g., `\"category10\"` or `\"blues\"`).\n *\n * For the full list of supported schemes, please refer to the [Vega Scheme](https://vega.github.io/vega/docs/schemes/#reference) reference.\n */\n name: ColorScheme | SignalRef;\n\n /**\n * The extent of the color range to use. For example `[0.2, 1]` will rescale the color scheme such that color values in the range _[0, 0.2)_ are excluded from the scheme.\n */\n extent?: (number | SignalRef)[] | SignalRef;\n\n /**\n * The number of colors to use in the scheme. This can be useful for scale types such as `\"quantize\"`, which use the length of the scale range to determine the number of discrete bins for the scale domain.\n */\n count?: number | SignalRef;\n}\n\nexport type Domain =\n | (null | string | number | boolean | DateTime | SignalRef)[]\n | 'unaggregated'\n | ParameterExtent\n | SignalRef\n | DomainUnionWith;\n\nexport type Scheme = string | SchemeParams;\n\nexport function isExtendedScheme(scheme: Scheme | SignalRef): scheme is SchemeParams {\n return !isString(scheme) && !!scheme['name'];\n}\n\nexport function isParameterDomain(domain: Domain): domain is ParameterExtent {\n return domain?.['param'];\n}\n\nexport interface DomainUnionWith {\n /**\n * Customized domain values to be union with the field's values or explicitly defined domain.\n * Should be an array of valid scale domain values.\n */\n unionWith: (number | string | boolean | DateTime)[];\n}\n\nexport function isDomainUnionWith(domain: Domain): domain is DomainUnionWith {\n return domain?.['unionWith'];\n}\n\nexport interface FieldRange {\n field: string;\n}\n\nexport function isFieldRange(range: any): range is FieldRange {\n return isObject(range) && 'field' in range;\n}\n\nexport interface Scale {\n /**\n * The type of scale. Vega-Lite supports the following categories of scale types:\n *\n * 1) [**Continuous Scales**](https://vega.github.io/vega-lite/docs/scale.html#continuous) -- mapping continuous domains to continuous output ranges ([`\"linear\"`](https://vega.github.io/vega-lite/docs/scale.html#linear), [`\"pow\"`](https://vega.github.io/vega-lite/docs/scale.html#pow), [`\"sqrt\"`](https://vega.github.io/vega-lite/docs/scale.html#sqrt), [`\"symlog\"`](https://vega.github.io/vega-lite/docs/scale.html#symlog), [`\"log\"`](https://vega.github.io/vega-lite/docs/scale.html#log), [`\"time\"`](https://vega.github.io/vega-lite/docs/scale.html#time), [`\"utc\"`](https://vega.github.io/vega-lite/docs/scale.html#utc).\n *\n * 2) [**Discrete Scales**](https://vega.github.io/vega-lite/docs/scale.html#discrete) -- mapping discrete domains to discrete ([`\"ordinal\"`](https://vega.github.io/vega-lite/docs/scale.html#ordinal)) or continuous ([`\"band\"`](https://vega.github.io/vega-lite/docs/scale.html#band) and [`\"point\"`](https://vega.github.io/vega-lite/docs/scale.html#point)) output ranges.\n *\n * 3) [**Discretizing Scales**](https://vega.github.io/vega-lite/docs/scale.html#discretizing) -- mapping continuous domains to discrete output ranges [`\"bin-ordinal\"`](https://vega.github.io/vega-lite/docs/scale.html#bin-ordinal), [`\"quantile\"`](https://vega.github.io/vega-lite/docs/scale.html#quantile), [`\"quantize\"`](https://vega.github.io/vega-lite/docs/scale.html#quantize) and [`\"threshold\"`](https://vega.github.io/vega-lite/docs/scale.html#threshold).\n *\n * __Default value:__ please see the [scale type table](https://vega.github.io/vega-lite/docs/scale.html#type).\n */\n type?: ScaleType;\n\n /**\n * Customized domain values in the form of constant values or dynamic values driven by a parameter.\n *\n * 1) Constant `domain` for _quantitative_ fields can take one of the following forms:\n *\n * - A two-element array with minimum and maximum values. To create a diverging scale, this two-element array can be combined with the `domainMid` property.\n * - An array with more than two entries, for [Piecewise quantitative scales](https://vega.github.io/vega-lite/docs/scale.html#piecewise).\n * - A string value `\"unaggregated\"`, if the input field is aggregated, to indicate that the domain should include the raw data values prior to the aggregation.\n *\n * 2) Constant `domain` for _temporal_ fields can be a two-element array with minimum and maximum values, in the form of either timestamps or the [DateTime definition objects](https://vega.github.io/vega-lite/docs/types.html#datetime).\n *\n * 3) Constant `domain` for _ordinal_ and _nominal_ fields can be an array that lists valid input values.\n *\n * 4) To combine (union) specified constant domain with the field's values, `domain` can be an object with a `unionWith` property that specify constant domain to be combined. For example, `domain: {unionWith: [0, 100]}` for a quantitative scale means that the scale domain always includes `[0, 100]`, but will include other values in the fields beyond `[0, 100]`.\n *\n * 5) Domain can also takes an object defining a field or encoding of a parameter that [interactively determines](https://vega.github.io/vega-lite/docs/selection.html#scale-domains) the scale domain.\n */\n domain?:\n | (null | string | number | boolean | DateTime | ES)[]\n | 'unaggregated'\n | ParameterExtent\n | DomainUnionWith\n | ES;\n\n /**\n * An expression for an array of raw values that, if non-null, directly overrides the _domain_ property.\n * This is useful for supporting interactions such as panning or zooming a scale.\n * The scale may be initially determined using a data-driven domain, then modified in response to user input by setting the rawDomain value.\n */\n domainRaw?: ES;\n\n /**\n * Inserts a single mid-point value into a two-element domain. The mid-point value must lie between the domain minimum and maximum values. This property can be useful for setting a midpoint for [diverging color scales](https://vega.github.io/vega-lite/docs/scale.html#piecewise). The domainMid property is only intended for use with scales supporting continuous, piecewise domains.\n */\n domainMid?: number | ES;\n\n /**\n * Sets the maximum value in the scale domain, overriding the `domain` property. This property is only intended for use with scales having continuous domains.\n */\n domainMax?: number | DateTime | ES;\n\n /**\n * Sets the minimum value in the scale domain, overriding the domain property. This property is only intended for use with scales having continuous domains.\n */\n domainMin?: number | DateTime | ES;\n\n /**\n * If true, reverses the order of the scale range.\n * __Default value:__ `false`.\n */\n reverse?: boolean | ES;\n\n /**\n * The range of the scale. One of:\n *\n * - A string indicating a [pre-defined named scale range](https://vega.github.io/vega-lite/docs/scale.html#range-config) (e.g., example, `\"symbol\"`, or `\"diverging\"`).\n *\n * - For [continuous scales](https://vega.github.io/vega-lite/docs/scale.html#continuous), two-element array indicating minimum and maximum values, or an array with more than two entries for specifying a [piecewise scale](https://vega.github.io/vega-lite/docs/scale.html#piecewise).\n *\n * - For [discrete](https://vega.github.io/vega-lite/docs/scale.html#discrete) and [discretizing](https://vega.github.io/vega-lite/docs/scale.html#discretizing) scales, an array of desired output values or an object with a `field` property representing the range values. For example, if a field `color` contains CSS color names, we can set `range` to `{field: \"color\"}`.\n *\n * __Notes:__\n *\n * 1) For color scales you can also specify a color [`scheme`](https://vega.github.io/vega-lite/docs/scale.html#scheme) instead of `range`.\n *\n * 2) Any directly specified `range` for `x` and `y` channels will be ignored. Range can be customized via the view's corresponding [size](https://vega.github.io/vega-lite/docs/size.html) (`width` and `height`).\n */\n range?: RangeEnum | (number | string | number[] | ES)[] | FieldRange;\n\n /**\n * Sets the maximum value in the scale range, overriding the `range` property or the default range. This property is only intended for use with scales having continuous ranges.\n */\n rangeMax?: number | string | ES;\n\n /**\n * Sets the minimum value in the scale range, overriding the `range` property or the default range. This property is only intended for use with scales having continuous ranges.\n */\n rangeMin?: number | string | ES;\n\n // ordinal\n\n /**\n * A string indicating a color [scheme](https://vega.github.io/vega-lite/docs/scale.html#scheme) name (e.g., `\"category10\"` or `\"blues\"`) or a [scheme parameter object](https://vega.github.io/vega-lite/docs/scale.html#scheme-params).\n *\n * Discrete color schemes may be used with [discrete](https://vega.github.io/vega-lite/docs/scale.html#discrete) or [discretizing](https://vega.github.io/vega-lite/docs/scale.html#discretizing) scales. Continuous color schemes are intended for use with color scales.\n *\n * To set a custom scheme, instead set the list of values [as the scale range](https://vega.github.io/vega-lite/docs/scale.html#2-setting-the-range-property-to-an-array-of-valid-css-color-strings).\n *\n * For the full list of supported schemes, please refer to the [Vega Scheme](https://vega.github.io/vega/docs/schemes/#reference) reference.\n */\n scheme?: ColorScheme | SchemeParams | ES;\n\n /**\n * The alignment of the steps within the scale range.\n *\n * This value must lie in the range `[0,1]`. A value of `0.5` indicates that the steps should be centered within the range. A value of `0` or `1` may be used to shift the bands to one side, say to position them adjacent to an axis.\n *\n * __Default value:__ `0.5`\n */\n align?: number | ES;\n\n /**\n * Bin boundaries can be provided to scales as either an explicit array of bin boundaries or as a bin specification object. The legal values are:\n * - An [array](../types/#Array) literal of bin boundary values. For example, `[0, 5, 10, 15, 20]`. The array must include both starting and ending boundaries. The previous example uses five values to indicate a total of four bin intervals: [0-5), [5-10), [10-15), [15-20]. Array literals may include signal references as elements.\n * - A [bin specification object](https://vega.github.io/vega-lite/docs/scale.html#bins) that indicates the bin _step_ size, and optionally the _start_ and _stop_ boundaries.\n * - An array of bin boundaries over the scale domain. If provided, axes and legends will use the bin boundaries to inform the choice of tick marks and text labels.\n */\n // TODO: add - A [signal reference](../types/#Signal) that resolves to either an array or bin specification object.\n bins?: ScaleBins;\n\n /**\n * If `true`, rounds numeric output values to integers. This can be helpful for snapping to the pixel grid.\n *\n * __Default value:__ `false`.\n */\n round?: boolean | ES;\n\n /**\n * For _[continuous](https://vega.github.io/vega-lite/docs/scale.html#continuous)_ scales, expands the scale domain to accommodate the specified number of pixels on each of the scale range. The scale range must represent pixels for this parameter to function as intended. Padding adjustment is performed prior to all other adjustments, including the effects of the `zero`, `nice`, `domainMin`, and `domainMax` properties.\n *\n * For _[band](https://vega.github.io/vega-lite/docs/scale.html#band)_ scales, shortcut for setting `paddingInner` and `paddingOuter` to the same value.\n *\n * For _[point](https://vega.github.io/vega-lite/docs/scale.html#point)_ scales, alias for `paddingOuter`.\n *\n * __Default value:__ For _continuous_ scales, derived from the [scale config](https://vega.github.io/vega-lite/docs/scale.html#config)'s `continuousPadding`.\n * For _band and point_ scales, see `paddingInner` and `paddingOuter`. By default, Vega-Lite sets padding such that _width/height = number of unique values * step_.\n *\n * @minimum 0\n */\n padding?: number | ES;\n\n /**\n * The inner padding (spacing) within each band step of band scales, as a fraction of the step size. This value must lie in the range [0,1].\n *\n * For point scale, this property is invalid as point scales do not have internal band widths (only step sizes between bands).\n *\n * __Default value:__ derived from the [scale config](https://vega.github.io/vega-lite/docs/scale.html#config)'s `bandPaddingInner`.\n *\n * @minimum 0\n * @maximum 1\n */\n paddingInner?: number | ES;\n\n /**\n * The outer padding (spacing) at the ends of the range of band and point scales,\n * as a fraction of the step size. This value must lie in the range [0,1].\n *\n * __Default value:__ derived from the [scale config](https://vega.github.io/vega-lite/docs/scale.html#config)'s `bandPaddingOuter` for band scales and `pointPadding` for point scales.\n * By default, Vega-Lite sets outer padding such that _width/height = number of unique values * step_.\n *\n * @minimum 0\n * @maximum 1\n */\n paddingOuter?: number | ES;\n\n // typical\n /**\n * If `true`, values that exceed the data domain are clamped to either the minimum or maximum range value\n *\n * __Default value:__ derived from the [scale config](https://vega.github.io/vega-lite/docs/config.html#scale-config)'s `clamp` (`true` by default).\n */\n clamp?: boolean | ES;\n\n /**\n * Extending the domain so that it starts and ends on nice round values. This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. Nicing is useful if the domain is computed from data and may be irregular. For example, for a domain of _[0.201479…, 0.996679…]_, a nice domain might be _[0.2, 1.0]_.\n *\n * For quantitative scales such as linear, `nice` can be either a boolean flag or a number. If `nice` is a number, it will represent a desired tick count. This allows greater control over the step size used to extend the bounds, guaranteeing that the returned ticks will exactly cover the domain.\n *\n * For temporal fields with time and utc scales, the `nice` value can be a string indicating the desired time interval. Legal values are `\"millisecond\"`, `\"second\"`, `\"minute\"`, `\"hour\"`, `\"day\"`, `\"week\"`, `\"month\"`, and `\"year\"`. Alternatively, `time` and `utc` scales can accept an object-valued interval specifier of the form `{\"interval\": \"month\", \"step\": 3}`, which includes a desired number of interval steps. Here, the domain would snap to quarter (Jan, Apr, Jul, Oct) boundaries.\n *\n * __Default value:__ `true` for unbinned _quantitative_ fields without explicit domain bounds; `false` otherwise.\n *\n */\n nice?: boolean | number | TimeInterval | TimeIntervalStep | ES;\n\n /**\n * The logarithm base of the `log` scale (default `10`).\n */\n base?: number | ES;\n\n /**\n * The exponent of the `pow` scale.\n */\n exponent?: number | ES;\n\n /**\n * A constant determining the slope of the symlog function around zero. Only used for `symlog` scales.\n *\n * __Default value:__ `1`\n */\n constant?: number | ES;\n\n /**\n * If `true`, ensures that a zero baseline value is included in the scale domain.\n *\n * __Default value:__ `true` for x and y channels if the quantitative field is not binned and no custom `domain` is provided; `false` otherwise.\n *\n * __Note:__ Log, time, and utc scales do not support `zero`.\n */\n zero?: boolean | ES;\n\n /**\n * The interpolation method for range values. By default, a general interpolator for numbers, dates, strings and colors (in HCL space) is used. For color ranges, this property allows interpolation in alternative color spaces. Legal values include `rgb`, `hsl`, `hsl-long`, `lab`, `hcl`, `hcl-long`, `cubehelix` and `cubehelix-long` ('-long' variants use longer paths in polar coordinate spaces). If object-valued, this property accepts an object with a string-valued _type_ property and an optional numeric _gamma_ property applicable to rgb and cubehelix interpolators. For more, see the [d3-interpolate documentation](https://github.com/d3/d3-interpolate).\n *\n * * __Default value:__ `hcl`\n */\n interpolate?: ScaleInterpolateEnum | ES | ScaleInterpolateParams;\n}\n\nconst SCALE_PROPERTY_INDEX: Flag> = {\n type: 1,\n domain: 1,\n domainMax: 1,\n domainMin: 1,\n domainMid: 1,\n domainRaw: 1,\n align: 1,\n range: 1,\n rangeMax: 1,\n rangeMin: 1,\n scheme: 1,\n bins: 1,\n // Other properties\n reverse: 1,\n round: 1,\n // quantitative / time\n clamp: 1,\n nice: 1,\n // quantitative\n base: 1,\n exponent: 1,\n constant: 1,\n interpolate: 1,\n zero: 1, // zero depends on domain\n // band/point\n padding: 1,\n paddingInner: 1,\n paddingOuter: 1\n};\n\nexport const SCALE_PROPERTIES = keys(SCALE_PROPERTY_INDEX);\n\nconst {type, domain, range, rangeMax, rangeMin, scheme, ...NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX} =\n SCALE_PROPERTY_INDEX;\n\nexport const NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES = keys(NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX);\n\nexport function scaleTypeSupportProperty(scaleType: ScaleType, propName: keyof Scale): boolean {\n switch (propName) {\n case 'type':\n case 'domain':\n case 'reverse':\n case 'range':\n return true;\n case 'scheme':\n case 'interpolate':\n return !['point', 'band', 'identity'].includes(scaleType);\n case 'bins':\n return !['point', 'band', 'identity', 'ordinal'].includes(scaleType);\n case 'round':\n return isContinuousToContinuous(scaleType) || scaleType === 'band' || scaleType === 'point';\n case 'padding':\n case 'rangeMin':\n case 'rangeMax':\n return isContinuousToContinuous(scaleType) || ['point', 'band'].includes(scaleType);\n case 'paddingOuter':\n case 'align':\n return ['point', 'band'].includes(scaleType);\n case 'paddingInner':\n return scaleType === 'band';\n case 'domainMax':\n case 'domainMid':\n case 'domainMin':\n case 'domainRaw':\n case 'clamp':\n return isContinuousToContinuous(scaleType);\n case 'nice':\n return isContinuousToContinuous(scaleType) || scaleType === 'quantize' || scaleType === 'threshold';\n case 'exponent':\n return scaleType === 'pow';\n case 'base':\n return scaleType === 'log';\n case 'constant':\n return scaleType === 'symlog';\n case 'zero':\n return (\n hasContinuousDomain(scaleType) &&\n !contains(\n [\n 'log', // log scale cannot have zero value\n 'time',\n 'utc', // zero is not meaningful for time\n 'threshold', // threshold requires custom domain so zero does not matter\n 'quantile' // quantile depends on distribution so zero does not matter\n ],\n scaleType\n )\n );\n }\n}\n\n/**\n * Returns undefined if the input channel supports the input scale property name\n */\nexport function channelScalePropertyIncompatability(channel: Channel, propName: keyof Scale): string {\n switch (propName) {\n case 'interpolate':\n case 'scheme':\n case 'domainMid':\n if (!isColorChannel(channel)) {\n return log.message.cannotUseScalePropertyWithNonColor(propName);\n }\n return undefined;\n case 'align':\n case 'type':\n case 'bins':\n case 'domain':\n case 'domainMax':\n case 'domainMin':\n case 'domainRaw':\n case 'range':\n case 'base':\n case 'exponent':\n case 'constant':\n case 'nice':\n case 'padding':\n case 'paddingInner':\n case 'paddingOuter':\n case 'rangeMax':\n case 'rangeMin':\n case 'reverse':\n case 'round':\n case 'clamp':\n case 'zero':\n return undefined; // GOOD!\n }\n}\n\nexport function scaleTypeSupportDataType(specifiedType: ScaleType, fieldDefType: Type): boolean {\n if (contains([ORDINAL, NOMINAL], fieldDefType)) {\n return specifiedType === undefined || hasDiscreteDomain(specifiedType);\n } else if (fieldDefType === TEMPORAL) {\n return contains([ScaleType.TIME, ScaleType.UTC, undefined], specifiedType);\n } else if (fieldDefType === QUANTITATIVE) {\n return isQuantitative(specifiedType) || isContinuousToDiscrete(specifiedType) || specifiedType === undefined;\n }\n\n return true;\n}\n\nexport function channelSupportScaleType(channel: Channel, scaleType: ScaleType, hasNestedOffsetScale = false): boolean {\n if (!CHANNEL.isScaleChannel(channel)) {\n return false;\n }\n switch (channel) {\n case CHANNEL.X:\n case CHANNEL.Y:\n case CHANNEL.XOFFSET:\n case CHANNEL.YOFFSET:\n case CHANNEL.THETA:\n case CHANNEL.RADIUS:\n if (isContinuousToContinuous(scaleType)) {\n return true;\n } else if (scaleType === 'band') {\n return true;\n } else if (scaleType === 'point') {\n /*\n Point scale can't be use if the position has a nested offset scale\n because if there is a nested scale, then it's band.\n */\n return !hasNestedOffsetScale;\n }\n return false;\n case CHANNEL.SIZE: // TODO: size and opacity can support ordinal with more modification\n case CHANNEL.STROKEWIDTH:\n case CHANNEL.OPACITY:\n case CHANNEL.FILLOPACITY:\n case CHANNEL.STROKEOPACITY:\n case CHANNEL.ANGLE:\n // Although it generally doesn't make sense to use band with size and opacity,\n // it can also work since we use band: 0.5 to get midpoint.\n return (\n isContinuousToContinuous(scaleType) ||\n isContinuousToDiscrete(scaleType) ||\n contains(['band', 'point', 'ordinal'], scaleType)\n );\n case CHANNEL.COLOR:\n case CHANNEL.FILL:\n case CHANNEL.STROKE:\n return scaleType !== 'band'; // band does not make sense with color\n case CHANNEL.STROKEDASH:\n case CHANNEL.SHAPE:\n return scaleType === 'ordinal' || isContinuousToDiscrete(scaleType);\n }\n}\n","import {Align, Color, Gradient, MarkConfig as VgMarkConfig, Orientation, SignalRef, TextBaseline} from 'vega';\nimport {CompositeMark, CompositeMarkDef} from './compositemark';\nimport {ExprRef} from './expr';\nimport {Flag, keys} from './util';\nimport {MapExcludeValueRefAndReplaceSignalWith} from './vega.schema';\nimport {MarkInvalidMixins} from './invalid';\n\n/**\n * All types of primitive marks.\n */\nexport const Mark = {\n arc: 'arc',\n area: 'area',\n bar: 'bar',\n image: 'image',\n line: 'line',\n point: 'point',\n rect: 'rect',\n rule: 'rule',\n text: 'text',\n tick: 'tick',\n trail: 'trail',\n circle: 'circle',\n square: 'square',\n geoshape: 'geoshape'\n} as const;\n\nexport const ARC = Mark.arc;\nexport const AREA = Mark.area;\nexport const BAR = Mark.bar;\nexport const IMAGE = Mark.image;\nexport const LINE = Mark.line;\nexport const POINT = Mark.point;\nexport const RECT = Mark.rect;\nexport const RULE = Mark.rule;\nexport const TEXT = Mark.text;\nexport const TICK = Mark.tick;\nexport const TRAIL = Mark.trail;\nexport const CIRCLE = Mark.circle;\nexport const SQUARE = Mark.square;\nexport const GEOSHAPE = Mark.geoshape;\n\nexport type Mark = keyof typeof Mark;\n\nexport function isMark(m: string): m is Mark {\n return m in Mark;\n}\n\nexport const PATH_MARKS = ['line', 'area', 'trail'] as const;\n\nexport type PathMark = (typeof PATH_MARKS)[number];\n\nexport function isPathMark(m: Mark | CompositeMark): m is PathMark {\n return ['line', 'area', 'trail'].includes(m);\n}\n\nexport function isRectBasedMark(m: Mark | CompositeMark): m is 'rect' | 'bar' | 'image' | 'arc' {\n return ['rect', 'bar', 'image', 'arc' /* arc is rect/interval in polar coordinate */].includes(m);\n}\n\nexport const PRIMITIVE_MARKS = new Set(keys(Mark));\n\nexport interface ColorMixins {\n /**\n * Default color.\n *\n * __Default value:__ `\"#4682b4\"`\n *\n * __Note:__\n * - This property cannot be used in a [style config](https://vega.github.io/vega-lite/docs/mark.html#style-config).\n * - The `fill` and `stroke` properties have higher precedence than `color` and will override `color`.\n */\n color?: Color | Gradient | ES;\n}\n\nexport interface TooltipContent {\n content: 'encoding' | 'data';\n}\n\nexport interface VLOnlyMarkConfig extends ColorMixins, MarkInvalidMixins {\n /**\n * Whether the mark's color should be used as fill color instead of stroke color.\n *\n * __Default value:__ `false` for all `point`, `line`, and `rule` marks as well as `geoshape` marks for [`graticule`](https://vega.github.io/vega-lite/docs/data.html#graticule) data sources; otherwise, `true`.\n *\n * __Note:__ This property cannot be used in a [style config](https://vega.github.io/vega-lite/docs/mark.html#style-config).\n *\n */\n filled?: boolean;\n\n /**\n * For line and trail marks, this `order` property can be set to `null` or `false` to make the lines use the original order in the data sources.\n */\n order?: null | boolean;\n\n /**\n * Default relative band position for a time unit. If set to `0`, the marks will be positioned at the beginning of the time unit band step.\n * If set to `0.5`, the marks will be positioned in the middle of the time unit band step.\n */\n timeUnitBandPosition?: number;\n\n /**\n * Default relative band size for a time unit. If set to `1`, the bandwidth of the marks will be equal to the time unit band step.\n * If set to `0.5`, bandwidth of the marks will be half of the time unit band step.\n */\n timeUnitBandSize?: number;\n\n /**\n * The end angle of arc marks in radians. A value of 0 indicates up or “north”, increasing values proceed clockwise.\n */\n theta2?: number | ES; // In Vega, this is called endAngle\n\n /**\n * The secondary (inner) radius in pixels of arc marks.\n *\n * __Default value:__ `0`\n * @minimum 0\n */\n radius2?: number | ES; // In Vega, this is called innerRadius\n}\n\nexport interface MarkConfig\n extends VLOnlyMarkConfig,\n MapExcludeValueRefAndReplaceSignalWith, ES> {\n // ========== Overriding Vega ==========\n\n /**\n * The tooltip text string to show upon mouse hover or an object defining which fields should the tooltip be derived from.\n *\n * - If `tooltip` is `true` or `{\"content\": \"encoding\"}`, then all fields from `encoding` will be used.\n * - If `tooltip` is `{\"content\": \"data\"}`, then all fields that appear in the highlighted data point will be used.\n * - If set to `null` or `false`, then no tooltip will be used.\n *\n * See the [`tooltip`](https://vega.github.io/vega-lite/docs/tooltip.html) documentation for a detailed discussion about tooltip in Vega-Lite.\n *\n * __Default value:__ `null`\n */\n tooltip?: number | string | boolean | TooltipContent | ES | null; // VL has a special object form for tooltip content\n\n /**\n * Default size for marks.\n * - For `point`/`circle`/`square`, this represents the pixel area of the marks. Note that this value sets the area of the symbol; the side lengths will increase with the square root of this value.\n * - For `bar`, this represents the band size of the bar, in pixels.\n * - For `text`, this represents the font size, in pixels.\n *\n * __Default value:__\n * - `30` for point, circle, square marks; width/height's `step`\n * - `2` for bar marks with discrete dimensions;\n * - `5` for bar marks with continuous dimensions;\n * - `11` for text marks.\n *\n * @minimum 0\n */\n size?: number | ES; // size works beyond symbol marks in VL\n\n /**\n * X coordinates of the marks, or width of horizontal `\"bar\"` and `\"area\"` without specified `x2` or `width`.\n *\n * The `value` of this channel can be a number or a string `\"width\"` for the width of the plot.\n */\n x?: number | 'width' | ES; // Vega doesn't have 'width'\n\n /**\n * Y coordinates of the marks, or height of vertical `\"bar\"` and `\"area\"` without specified `y2` or `height`.\n *\n * The `value` of this channel can be a number or a string `\"height\"` for the height of the plot.\n */\n y?: number | 'height' | ES; // Vega doesn't have 'height'\n\n /**\n * X2 coordinates for ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n *\n * The `value` of this channel can be a number or a string `\"width\"` for the width of the plot.\n */\n x2?: number | 'width' | ES; // Vega doesn't have 'width'\n\n /**\n * Y2 coordinates for ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n *\n * The `value` of this channel can be a number or a string `\"height\"` for the height of the plot.\n */\n y2?: number | 'height' | ES; // Vega doesn't have 'height'\n\n /**\n * Default fill color. This property has higher precedence than `config.color`. Set to `null` to remove fill.\n *\n * __Default value:__ (None)\n *\n */\n fill?: Color | Gradient | null | ES; // docs: Vega doesn't have config.color\n\n /**\n * Default stroke color. This property has higher precedence than `config.color`. Set to `null` to remove stroke.\n *\n * __Default value:__ (None)\n *\n */\n stroke?: Color | Gradient | null | ES; // docs: Vega doesn't have config.color\n\n /**\n * The overall opacity (value between [0,1]).\n *\n * __Default value:__ `0.7` for non-aggregate plots with `point`, `tick`, `circle`, or `square` marks or layered `bar` charts and `1` otherwise.\n *\n * @minimum 0\n * @maximum 1\n */\n opacity?: number | ES; // docs (different defaults)\n\n /**\n * The orientation of a non-stacked bar, tick, area, and line charts.\n * The value is either horizontal (default) or vertical.\n * - For bar, rule and tick, this determines whether the size of the bar and tick\n * should be applied to x or y dimension.\n * - For area, this property determines the orient property of the Vega output.\n * - For line and trail marks, this property determines the sort order of the points in the line\n * if `config.sortLineBy` is not specified.\n * For stacked charts, this is always determined by the orientation of the stack;\n * therefore explicitly specified value will be ignored.\n */\n orient?: Orientation; // Vega orient doesn't apply to bar/tick/line. Since some logic depends on this property, Vega-Lite does NOT allow signal for orient.\n\n /**\n * The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). One of `\"left\"`, `\"right\"`, `\"center\"`.\n *\n * __Note:__ Expression reference is *not* supported for range marks.\n */\n align?: Align | ES;\n\n /**\n * For text marks, the vertical text baseline. One of `\"alphabetic\"` (default), `\"top\"`, `\"middle\"`, `\"bottom\"`, `\"line-top\"`, `\"line-bottom\"`, or an expression reference that provides one of the valid values.\n * The `\"line-top\"` and `\"line-bottom\"` values operate similarly to `\"top\"` and `\"bottom\"`,\n * but are calculated relative to the `lineHeight` rather than `fontSize` alone.\n *\n * For range marks, the vertical alignment of the marks. One of `\"top\"`, `\"middle\"`, `\"bottom\"`.\n *\n * __Note:__ Expression reference is *not* supported for range marks.\n *\n */\n baseline?: TextBaseline | ES;\n\n /**\n * - For arc marks, the arc length in radians if theta2 is not specified, otherwise the start arc angle. (A value of 0 indicates up or “north”, increasing values proceed clockwise.)\n *\n * - For text marks, polar coordinate angle in radians.\n *\n * @minimum 0\n * @maximum 360\n */\n theta?: number | ES; // overriding VG\n\n /**\n *\n * For arc mark, the primary (outer) radius in pixels.\n *\n * For text marks, polar coordinate radial offset, in pixels, of the text from the origin determined by the `x` and `y` properties.\n *\n * __Default value:__ `min(plot_width, plot_height)/2`\n * @minimum 0\n */\n radius?: number | ES; // overriding VG\n\n /**\n * The inner radius in pixels of arc marks. `innerRadius` is an alias for `radius2`.\n *\n * __Default value:__ `0`\n * @minimum 0\n */\n innerRadius?: number | ES;\n\n /**\n * The outer radius in pixels of arc marks. `outerRadius` is an alias for `radius`.\n *\n * __Default value:__ `0`\n * @minimum 0\n */\n outerRadius?: number | ES;\n}\n\nexport interface RectBinSpacingMixins {\n /**\n * Offset between bars for binned field. The ideal value for this is either 0 (preferred by statisticians) or 1 (Vega-Lite default, D3 example style).\n *\n * __Default value:__ `1`\n *\n * @minimum 0\n */\n binSpacing?: number;\n}\n\nexport type AnyMark = CompositeMark | CompositeMarkDef | Mark | MarkDef;\n\nexport function isMarkDef(mark: string | GenericMarkDef): mark is GenericMarkDef {\n return mark['type'];\n}\n\nexport function isPrimitiveMark(mark: AnyMark): mark is Mark {\n const markType = isMarkDef(mark) ? mark.type : mark;\n return (PRIMITIVE_MARKS as Set).has(markType);\n}\n\nexport const STROKE_CONFIG = [\n 'stroke',\n 'strokeWidth',\n 'strokeDash',\n 'strokeDashOffset',\n 'strokeOpacity',\n 'strokeJoin',\n 'strokeMiterLimit'\n] as const;\n\nexport const FILL_CONFIG = ['fill', 'fillOpacity'] as const;\n\nexport const FILL_STROKE_CONFIG = [...STROKE_CONFIG, ...FILL_CONFIG];\n\nconst VL_ONLY_MARK_CONFIG_INDEX: Flag> = {\n color: 1,\n filled: 1,\n invalid: 1,\n order: 1,\n radius2: 1,\n theta2: 1,\n timeUnitBandSize: 1,\n timeUnitBandPosition: 1\n};\n\nexport const VL_ONLY_MARK_CONFIG_PROPERTIES = keys(VL_ONLY_MARK_CONFIG_INDEX);\n\nexport const VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX: {\n [k in Mark]?: (keyof Required>[k])[];\n} = {\n area: ['line', 'point'],\n bar: ['binSpacing', 'continuousBandSize', 'discreteBandSize', 'minBandSize'],\n rect: ['binSpacing', 'continuousBandSize', 'discreteBandSize', 'minBandSize'],\n line: ['point'],\n tick: ['bandSize', 'thickness']\n};\n\nexport const defaultMarkConfig: MarkConfig = {\n color: '#4c78a8',\n invalid: 'break-paths-show-path-domains',\n timeUnitBandSize: 1\n};\n\n// TODO: replace with MarkConfigMixins[Mark] once https://github.com/vega/ts-json-schema-generator/issues/344 is fixed\nexport type AnyMarkConfig =\n | MarkConfig\n | AreaConfig\n | BarConfig\n | RectConfig\n | LineConfig\n | TickConfig;\n\nexport interface MarkConfigMixins {\n /** Mark Config */\n mark?: MarkConfig;\n\n // MARK-SPECIFIC CONFIGS\n\n /** Arc-specific Config */\n arc?: RectConfig;\n\n /** Area-Specific Config */\n area?: AreaConfig;\n\n /** Bar-Specific Config */\n bar?: BarConfig;\n\n /** Circle-Specific Config */\n circle?: MarkConfig;\n\n /** Image-specific Config */\n image?: RectConfig;\n\n /** Line-Specific Config */\n line?: LineConfig;\n\n /** Point-Specific Config */\n point?: MarkConfig;\n\n /** Rect-Specific Config */\n rect?: RectConfig;\n\n /** Rule-Specific Config */\n rule?: MarkConfig;\n\n /** Square-Specific Config */\n square?: MarkConfig;\n\n /** Text-Specific Config */\n text?: MarkConfig;\n\n /** Tick-Specific Config */\n tick?: TickConfig;\n\n /** Trail-Specific Config */\n trail?: LineConfig;\n\n /** Geoshape-Specific Config */\n geoshape?: MarkConfig;\n}\n\nconst MARK_CONFIG_INDEX: Flag> = {\n mark: 1,\n arc: 1,\n area: 1,\n bar: 1,\n circle: 1,\n image: 1,\n line: 1,\n point: 1,\n rect: 1,\n rule: 1,\n square: 1,\n text: 1,\n tick: 1,\n trail: 1,\n geoshape: 1\n};\n\nexport const MARK_CONFIGS = keys(MARK_CONFIG_INDEX);\n\nexport interface RectConfig extends RectBinSpacingMixins, MarkConfig {\n /**\n * The default size of the bars on continuous scales.\n *\n * __Default value:__ `5`\n *\n * @minimum 0\n */\n continuousBandSize?: number;\n\n /**\n * The default size of the bars with discrete dimensions. If unspecified, the default size is `step-2`, which provides 2 pixel offset between bars.\n * @minimum 0\n */\n discreteBandSize?: number | RelativeBandSize;\n\n /**\n * The minimum band size for bar and rectangle marks.\n * __Default value:__ `0.25`\n */\n minBandSize?: number | ES;\n}\n\nexport type BandSize = number | RelativeBandSize | SignalRef;\n\nexport interface RelativeBandSize {\n /**\n * The relative band size. For example `0.5` means half of the band scale's band width.\n */\n band: number;\n}\n\nexport function isRelativeBandSize(o: number | RelativeBandSize | ExprRef | SignalRef): o is RelativeBandSize {\n return o && o['band'] != undefined;\n}\n\nexport const BAR_CORNER_RADIUS_INDEX: Partial<\n Record<\n Orientation,\n ('cornerRadiusTopLeft' | 'cornerRadiusTopRight' | 'cornerRadiusBottomLeft' | 'cornerRadiusBottomRight')[]\n >\n> = {\n horizontal: ['cornerRadiusTopRight', 'cornerRadiusBottomRight'],\n vertical: ['cornerRadiusTopLeft', 'cornerRadiusTopRight']\n};\n\nexport interface BarCornerRadiusMixins {\n /**\n * - For vertical bars, top-left and top-right corner radius.\n *\n * - For horizontal bars, top-right and bottom-right corner radius.\n */\n cornerRadiusEnd?: number | ES;\n}\n\nexport type BarConfig = RectConfig & BarCornerRadiusMixins;\n\nexport type OverlayMarkDef = MarkConfig & MarkDefMixins;\n\nexport interface PointOverlayMixins {\n /**\n * A flag for overlaying points on top of line or area marks, or an object defining the properties of the overlayed points.\n *\n * - If this property is `\"transparent\"`, transparent points will be used (for enhancing tooltips and selections).\n *\n * - If this property is an empty object (`{}`) or `true`, filled points with default properties will be used.\n *\n * - If this property is `false`, no points would be automatically added to line or area marks.\n *\n * __Default value:__ `false`.\n */\n point?: boolean | OverlayMarkDef | 'transparent';\n}\n\nexport interface LineConfig extends MarkConfig, PointOverlayMixins {}\n\nexport interface LineOverlayMixins {\n /**\n * A flag for overlaying line on top of area marks, or an object defining the properties of the overlayed lines.\n *\n * - If this value is an empty object (`{}`) or `true`, lines with default properties will be used.\n *\n * - If this value is `false`, no lines would be automatically added to area marks.\n *\n * __Default value:__ `false`.\n */\n line?: boolean | OverlayMarkDef;\n}\n\nexport interface AreaConfig\n extends MarkConfig,\n PointOverlayMixins,\n LineOverlayMixins {}\n\nexport interface TickThicknessMixins {\n /**\n * Thickness of the tick mark.\n *\n * __Default value:__ `1`\n *\n * @minimum 0\n */\n thickness?: number | SignalRef;\n}\n\nexport interface GenericMarkDef {\n /**\n * The mark type. This could a primitive mark type\n * (one of `\"bar\"`, `\"circle\"`, `\"square\"`, `\"tick\"`, `\"line\"`,\n * `\"area\"`, `\"point\"`, `\"geoshape\"`, `\"rule\"`, and `\"text\"`)\n * or a composite mark type (`\"boxplot\"`, `\"errorband\"`, `\"errorbar\"`).\n */\n type: M;\n}\n\nexport interface MarkDefMixins {\n /**\n * A string or array of strings indicating the name of custom styles to apply to the mark. A style is a named collection of mark property defaults defined within the [style configuration](https://vega.github.io/vega-lite/docs/mark.html#style-config). If style is an array, later styles will override earlier styles. Any [mark properties](https://vega.github.io/vega-lite/docs/encoding.html#mark-prop) explicitly defined within the `encoding` will override a style default.\n *\n * __Default value:__ The mark's name. For example, a bar mark will have style `\"bar\"` by default.\n * __Note:__ Any specified style will augment the default style. For example, a bar mark with `\"style\": \"foo\"` will receive from `config.style.bar` and `config.style.foo` (the specified style `\"foo\"` has higher precedence).\n */\n style?: string | string[];\n\n /**\n * Whether a mark be clipped to the enclosing group’s width and height.\n */\n clip?: boolean | ES;\n\n // Offset properties should not be a part of config\n\n /**\n * Offset for x-position.\n */\n xOffset?: number | ES;\n\n /**\n * Offset for y-position.\n */\n yOffset?: number | ES;\n\n /**\n * Offset for x2-position.\n */\n x2Offset?: number | ES;\n\n /**\n * Offset for y2-position.\n */\n y2Offset?: number | ES;\n\n /**\n * Offset for theta.\n */\n thetaOffset?: number | ES;\n\n /**\n * Offset for theta2.\n */\n theta2Offset?: number | ES;\n\n /**\n * Offset for radius.\n */\n radiusOffset?: number | ES;\n\n /**\n * Offset for radius2.\n */\n radius2Offset?: number | ES;\n}\n\nexport interface RelativeBandSize {\n /**\n * The relative band size. For example `0.5` means half of the band scale's band width.\n */\n band: number;\n}\n\n// Point/Line OverlayMixins are only for area, line, and trail but we don't want to declare multiple types of MarkDef\nexport interface MarkDef\n extends GenericMarkDef,\n Omit<\n MarkConfig &\n AreaConfig &\n BarConfig & // always extends RectConfig\n LineConfig &\n TickConfig,\n 'startAngle' | 'endAngle' | 'width' | 'height'\n >,\n MarkDefMixins {\n // Omit startAngle/endAngle since we use theta/theta2 from Vega-Lite schema to avoid confusion\n // We still support start/endAngle only in config, just in case people use Vega config with Vega-Lite.\n\n /**\n * @hidden\n */\n startAngle?: number | ES;\n /**\n * @hidden\n */\n endAngle?: number | ES;\n\n // Replace width / height to include relative band size\n\n /**\n * Width of the marks. One of:\n *\n * - A number representing a fixed pixel width.\n *\n * - A relative band size definition. For example, `{band: 0.5}` represents half of the band.\n */\n width?: number | ES | RelativeBandSize;\n\n /**\n * Height of the marks. One of:\n *\n * - A number representing a fixed pixel height.\n *\n * - A relative band size definition. For example, `{band: 0.5}` represents half of the band\n */\n height?: number | ES | RelativeBandSize;\n}\n\nconst DEFAULT_RECT_BAND_SIZE = 5;\n\nexport const defaultBarConfig: RectConfig = {\n binSpacing: 1,\n continuousBandSize: DEFAULT_RECT_BAND_SIZE,\n minBandSize: 0.25,\n timeUnitBandPosition: 0.5\n};\n\nexport const defaultRectConfig: RectConfig = {\n binSpacing: 0,\n continuousBandSize: DEFAULT_RECT_BAND_SIZE,\n minBandSize: 0.25,\n timeUnitBandPosition: 0.5\n};\n\nexport interface TickConfig extends MarkConfig, TickThicknessMixins {\n /**\n * The width of the ticks.\n *\n * __Default value:__ 3/4 of step (width step for horizontal ticks and height step for vertical ticks).\n * @minimum 0\n */\n bandSize?: number;\n}\n\nexport const defaultTickConfig: TickConfig = {\n thickness: 1\n};\n\nexport function getMarkType(m: string | GenericMarkDef) {\n return isMarkDef(m) ? m.type : m;\n}\n","import {MarkInvalidDataMode} from '../../invalid';\n\ntype NormalizedMarkInvalidDataMode = Exclude;\n\nexport function normalizeInvalidDataMode(\n mode: MarkInvalidDataMode | null | undefined,\n {isPath}: {isPath: boolean}\n): NormalizedMarkInvalidDataMode {\n if (mode === undefined || mode === 'break-paths-show-path-domains') {\n return isPath ? 'break-paths-show-domains' : 'filter';\n } else if (mode === null) {\n return 'show';\n }\n return mode;\n}\n","import {SignalRef} from 'vega';\nimport {ScaleChannel} from '../../channel';\nimport {Config} from '../../config';\nimport {MarkInvalidDataMode} from '../../invalid';\nimport {MarkDef, isPathMark} from '../../mark';\nimport {ScaleType, hasContinuousDomain} from '../../scale';\nimport {getMarkPropOrConfig} from '../common';\nimport {normalizeInvalidDataMode} from './normalizeInvalidDataMode';\n\nexport type ScaleInvalidDataMode =\n // remove 'break-paths-show-path-domains' from MarkInvalidDataMode\n // because it is a macro for '\"filter\"' or `\"break-path-keep-domains`\n | Omit\n\n // Add always-valid because at scale level, categorical scales can handle any values and thus is always valid.\n | 'always-valid';\n\nexport function getScaleInvalidDataMode({\n markDef,\n config,\n scaleChannel,\n scaleType,\n isCountAggregate\n}: {\n markDef: MarkDef;\n config: Config;\n scaleChannel: C;\n scaleType: ScaleType;\n isCountAggregate: boolean;\n}): ScaleInvalidDataMode {\n if (!scaleType || !hasContinuousDomain(scaleType) || isCountAggregate) {\n // - Discrete scales can always display null as another category\n // - Count cannot output null values\n return 'always-valid';\n }\n\n const invalidMode = normalizeInvalidDataMode(getMarkPropOrConfig('invalid', markDef, config), {\n isPath: isPathMark(markDef.type)\n });\n\n const scaleOutputForInvalid = config.scale?.invalid?.[scaleChannel];\n if (scaleOutputForInvalid !== undefined) {\n // Regardless of the current invalid mode, if the channel has a default value, we consider the field valid.\n return 'show';\n }\n\n return invalidMode;\n}\nexport function shouldBreakPath(mode: ScaleInvalidDataMode): boolean {\n return mode === 'break-paths-filter-domains' || mode === 'break-paths-show-domains';\n}\n","import {VgValueRef} from '../../../vega.schema';\nimport {ScaleComponent} from '../../scale/component';\n\nexport interface ScaledZeroOrMinOrMaxProps {\n scaleName: string;\n scale: ScaleComponent;\n mode: 'zeroOrMin' | {zeroOrMax: {widthSignal: string; heightSignal: string}};\n}\n\nexport function scaledZeroOrMinOrMax({scaleName, scale, mode}: ScaledZeroOrMinOrMaxProps): VgValueRef | undefined {\n const domain = `domain('${scaleName}')`;\n\n if (!scale || !scaleName) {\n return undefined;\n }\n const min = `${domain}[0]`;\n const max = `peek(${domain})`; // peek = the last item of the array\n\n // If there is a scale (and hence its name)\n const domainHasZero = scale.domainHasZero();\n // zeroOrMin or zeroOrMax mode\n if (domainHasZero === 'definitely') {\n return {\n scale: scaleName,\n value: 0\n };\n } else if (domainHasZero === 'maybe') {\n const nonZeroValue = mode === 'zeroOrMin' ? min : max;\n return {signal: `scale('${scaleName}', inrange(0, ${domain}) ? 0 : ${nonZeroValue})`};\n } else {\n // domainHasZero === 'definitely-not'\n return {signal: `scale('${scaleName}', ${mode === 'zeroOrMin' ? min : max})`};\n }\n}\n","import {isCountingAggregateOp} from '../../../aggregate';\nimport {NonPositionScaleChannel, PolarPositionScaleChannel, PositionScaleChannel} from '../../../channel';\nimport {getFieldDef, vgField} from '../../../channeldef';\nimport {ScaleInvalidDataShowAs, isScaleInvalidDataIncludeAsValue} from '../../../invalid';\nimport {fieldValidPredicate} from '../../../predicate';\nimport {VgValueRef, isSignalRef} from '../../../vega.schema';\nimport {getScaleInvalidDataMode} from '../../invalid/ScaleInvalidDataMode';\nimport {ScaleComponent} from '../../scale/component';\nimport {scaledZeroOrMinOrMax} from './scaledZeroOrMinOrMax';\nimport {MidPointParams} from './valueref';\n\nexport function getConditionalValueRefForIncludingInvalidValue<\n C extends PositionScaleChannel | PolarPositionScaleChannel | NonPositionScaleChannel\n>({\n scaleChannel,\n channelDef,\n scale,\n scaleName,\n markDef,\n config\n}: {\n scaleChannel: C;\n} & Pick): VgValueRef | undefined {\n const scaleType = scale?.get('type');\n\n const fieldDef = getFieldDef(channelDef);\n const isCountAggregate = isCountingAggregateOp(fieldDef?.aggregate);\n\n const invalidDataMode = getScaleInvalidDataMode({\n scaleChannel,\n markDef,\n config,\n scaleType,\n isCountAggregate\n });\n\n if (fieldDef && invalidDataMode === 'show') {\n const includeAs: ScaleInvalidDataShowAs = config.scale.invalid?.[scaleChannel] ?? 'zero-or-min';\n return {\n test: fieldValidPredicate(vgField(fieldDef, {expr: 'datum'}), false),\n ...refForInvalidValues(includeAs, scale, scaleName)\n };\n }\n return undefined;\n}\n\nfunction refForInvalidValues(\n includeAs: ScaleInvalidDataShowAs,\n scale: ScaleComponent,\n scaleName: string\n): VgValueRef {\n if (isScaleInvalidDataIncludeAsValue(includeAs)) {\n const {value} = includeAs;\n return isSignalRef(value) ? {signal: value.signal} : {value};\n }\n\n return scaledZeroOrMinOrMax({\n scale,\n scaleName,\n mode: 'zeroOrMin'\n });\n}\n","import {SignalRef} from 'vega';\nimport {ScaleChannel} from './channel';\nimport {Mark, MarkDef} from './mark';\nimport {isObject} from 'vega-util';\n\n/**\n * Mixins for Vega-Lite Spec's Mark Definiton (to add mark.invalid)\n */\nexport interface MarkInvalidMixins {\n /**\n * Invalid data mode, which defines how the marks and corresponding scales should represent invalid values (`null` and `NaN` in continuous scales *without* defined output for invalid values).\n *\n * - `\"filter\"` — *Exclude* all invalid values from the visualization's *marks* and *scales*.\n * For path marks (for line, area, trail), this option will create paths that connect valid points, as if the data rows with invalid values do not exist.\n *\n * - `\"break-paths-filter-domains\"` —\n * Break path marks (for line, area, trail) at invalid values. For non-path marks, this is equivalent to `\"filter\"`.\n * All *scale* domains will *exclude* these filtered data points.\n *\n * - `\"break-paths-show-domains\"` —\n * Break paths (for line, area, trail) at invalid values. Hide invalid values for non-path marks.\n * All *scale* domains will *include* these filtered data points (for both path and non-path marks).\n *\n * - `\"show\"` or `null` —\n * Show all data points in the marks and scale domains. Each scale will use the output for invalid values defined in `config.scale.invalid`\n * or, if unspecified, by default invalid values will produce the same visual values as zero (if the scale includes zero) or the minimum value (if the scale does not include zero).\n *\n * - `\"break-paths-show-path-domains\"` (default) —\n * This is equivalent to `\"break-paths-show-domains\"` for path-based marks (line/area/trail)\n * and `\"filter\"` for non-path marks.\n *\n * __Note__: If any channel's scale has an output for invalid values defined in `config.scale.invalid`,\n * all values for the scales will be considered \"valid\" since they can produce a reasonable output for the scales.\n * Thus, fields for such channels will not be filtered and will not cause path breaks.\n */\n invalid?: MarkInvalidDataMode | null;\n}\n\nexport type MarkInvalidDataMode =\n | 'filter'\n | 'break-paths-filter-domains'\n | 'break-paths-show-domains'\n | 'break-paths-show-path-domains'\n | 'show';\n\n/**\n * Mixins for Vega-Lite Spec's config.scale\n */\nexport interface ScaleInvalidDataConfigMixins {\n /**\n * An object that defines scale outputs per channel for invalid values (nulls and NaNs on a continuous scale).\n * - The keys in this object are the scale channels.\n * - The values is either `\"zero-or-min\"` (use zero if the scale includes zero or min value otherwise) or a value definition `{value: ...}`.\n *\n * _Example:_ Setting this `config.scale.invalid` property to `{color: {value: '#aaa'}}`\n * will make the visualization color all invalid values with '#aaa'.\n *\n * See [https://vega.github.io/vega-lite/docs/invalid-data.html](Invalid Data Docs) for more details.\n */\n invalid?: ScaleInvalidDataConfig;\n}\n\nexport type ScaleInvalidDataConfig = {\n [c in ScaleChannel]?: ScaleInvalidDataShowAs;\n};\n\nexport type ScaleInvalidDataShowAs = ScaleInvalidDataShowAsValue | 'zero-or-min';\n\nexport type ScaleInvalidDataShowAsValue = {\n value: MarkDef[C];\n};\n\nexport function isScaleInvalidDataIncludeAsValue(\n invalidDataMode: ScaleInvalidDataShowAs\n): invalidDataMode is ScaleInvalidDataShowAsValue {\n return isObject(invalidDataMode) && 'value' in invalidDataMode;\n}\n","/**\n * Utility files for producing Vega ValueRef for marks\n */\nimport type {SignalRef} from 'vega';\nimport {isFunction} from 'vega-util';\nimport {isBinned, isBinning} from '../../../bin';\nimport {Channel, PolarPositionChannel, PositionChannel, X, X2, Y2, getMainRangeChannel} from '../../../channel';\nimport {\n ChannelDef,\n DatumDef,\n FieldDefBase,\n FieldRefOption,\n SecondaryChannelDef,\n SecondaryFieldDef,\n TypedFieldDef,\n Value,\n binRequiresRange,\n getBandPosition,\n isDatumDef,\n isFieldDef,\n isFieldOrDatumDef,\n isTypedFieldDef,\n isValueDef,\n vgField\n} from '../../../channeldef';\nimport {Config} from '../../../config';\nimport {dateTimeToExpr, isDateTime} from '../../../datetime';\nimport {isExprRef} from '../../../expr';\nimport * as log from '../../../log';\nimport {Mark, MarkDef} from '../../../mark';\nimport {hasDiscreteDomain} from '../../../scale';\nimport {StackProperties} from '../../../stack';\nimport {TEMPORAL} from '../../../type';\nimport {contains, stringify} from '../../../util';\nimport {VgValueRef, isSignalRef} from '../../../vega.schema';\nimport {signalOrValueRef} from '../../common';\nimport {ScaleComponent} from '../../scale/component';\nimport {getConditionalValueRefForIncludingInvalidValue} from './invalid';\n\nexport function midPointRefWithPositionInvalidTest(\n params: MidPointParams & {\n channel: PositionChannel | PolarPositionChannel;\n }\n): VgValueRef | VgValueRef[] {\n const {channel, channelDef, markDef, scale, scaleName, config} = params;\n const scaleChannel = getMainRangeChannel(channel);\n const mainRef = midPoint(params);\n\n const valueRefForIncludingInvalid = getConditionalValueRefForIncludingInvalidValue({\n scaleChannel,\n channelDef,\n scale,\n scaleName,\n markDef,\n config\n });\n\n return valueRefForIncludingInvalid !== undefined ? [valueRefForIncludingInvalid, mainRef] : mainRef;\n}\n\nexport function datumDefToExpr(datumDef: DatumDef) {\n const {datum} = datumDef;\n if (isDateTime(datum)) {\n return dateTimeToExpr(datum);\n }\n return `${stringify(datum)}`;\n}\n\nexport function valueRefForFieldOrDatumDef(\n fieldDef: FieldDefBase | DatumDef,\n scaleName: string,\n opt: FieldRefOption,\n encode: {offset?: number | VgValueRef; band?: number | boolean | SignalRef}\n): VgValueRef {\n const ref: VgValueRef = {};\n\n if (scaleName) {\n ref.scale = scaleName;\n }\n\n if (isDatumDef(fieldDef)) {\n const {datum} = fieldDef;\n if (isDateTime(datum)) {\n ref.signal = dateTimeToExpr(datum);\n } else if (isSignalRef(datum)) {\n ref.signal = datum.signal;\n } else if (isExprRef(datum)) {\n ref.signal = datum.expr;\n } else {\n ref.value = datum;\n }\n } else {\n ref.field = vgField(fieldDef, opt);\n }\n\n if (encode) {\n const {offset, band} = encode;\n if (offset) {\n ref.offset = offset;\n }\n if (band) {\n ref.band = band;\n }\n }\n return ref;\n}\n\n/**\n * Signal that returns the middle of a bin from start and end field. Should only be used with x and y.\n */\nexport function interpolatedSignalRef({\n scaleName,\n fieldOrDatumDef,\n fieldOrDatumDef2,\n offset,\n startSuffix,\n endSuffix = 'end',\n bandPosition = 0.5\n}: {\n scaleName: string;\n fieldOrDatumDef: TypedFieldDef;\n fieldOrDatumDef2?: SecondaryFieldDef;\n startSuffix?: string;\n endSuffix?: string;\n offset: number | SignalRef | VgValueRef;\n bandPosition: number | SignalRef;\n}): VgValueRef {\n const expr = !isSignalRef(bandPosition) && 0 < bandPosition && bandPosition < 1 ? 'datum' : undefined;\n const start = vgField(fieldOrDatumDef, {expr, suffix: startSuffix});\n const end =\n fieldOrDatumDef2 !== undefined\n ? vgField(fieldOrDatumDef2, {expr})\n : vgField(fieldOrDatumDef, {suffix: endSuffix, expr});\n\n const ref: VgValueRef = {};\n\n if (bandPosition === 0 || bandPosition === 1) {\n ref.scale = scaleName;\n const field = bandPosition === 0 ? start : end;\n ref.field = field;\n } else {\n const datum = isSignalRef(bandPosition)\n ? `(1-${bandPosition.signal}) * ${start} + ${bandPosition.signal} * ${end}`\n : `${1 - bandPosition} * ${start} + ${bandPosition} * ${end}`;\n ref.signal = `scale(\"${scaleName}\", ${datum})`;\n }\n\n if (offset) {\n ref.offset = offset;\n }\n return ref;\n}\n\nexport function binSizeExpr({scaleName, fieldDef}: {scaleName: string; fieldDef: TypedFieldDef}) {\n const start = vgField(fieldDef, {expr: 'datum'});\n const end = vgField(fieldDef, {expr: 'datum', suffix: 'end'});\n return `abs(scale(\"${scaleName}\", ${end}) - scale(\"${scaleName}\", ${start}))`;\n}\n\nexport interface MidPointParams {\n channel: Channel;\n channelDef: ChannelDef;\n channel2Def?: SecondaryChannelDef;\n\n markDef: MarkDef;\n config: Config;\n\n scaleName: string;\n scale: ScaleComponent;\n stack?: StackProperties;\n offset?: number | SignalRef | VgValueRef;\n defaultRef: VgValueRef | (() => VgValueRef);\n\n bandPosition?: number | SignalRef;\n}\n\n/**\n * @returns {VgValueRef} Value Ref for xc / yc or mid point for other channels.\n */\nexport function midPoint({\n channel,\n channelDef,\n channel2Def,\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef,\n bandPosition\n}: MidPointParams): VgValueRef {\n // TODO: datum support\n if (channelDef) {\n /* istanbul ignore else */\n\n if (isFieldOrDatumDef(channelDef)) {\n const scaleType = scale?.get('type');\n if (isTypedFieldDef(channelDef)) {\n bandPosition ??= getBandPosition({\n fieldDef: channelDef,\n fieldDef2: channel2Def,\n markDef,\n config\n });\n const {bin, timeUnit, type} = channelDef;\n\n if (isBinning(bin) || (bandPosition && timeUnit && type === TEMPORAL)) {\n // Use middle only for x an y to place marks in the center between start and end of the bin range.\n // We do not use the mid point for other channels (e.g. size) so that properties of legends and marks match.\n if (stack?.impute) {\n // For stack, we computed bin_mid so we can impute.\n return valueRefForFieldOrDatumDef(channelDef, scaleName, {binSuffix: 'mid'}, {offset});\n }\n\n if (bandPosition && !hasDiscreteDomain(scaleType)) {\n // if band = 0, no need to call interpolation\n // For non-stack, we can just calculate bin mid on the fly using signal.\n return interpolatedSignalRef({scaleName, fieldOrDatumDef: channelDef, bandPosition, offset});\n }\n return valueRefForFieldOrDatumDef(\n channelDef,\n scaleName,\n binRequiresRange(channelDef, channel) ? {binSuffix: 'range'} : {},\n {\n offset\n }\n );\n } else if (isBinned(bin)) {\n if (isFieldDef(channel2Def)) {\n return interpolatedSignalRef({\n scaleName,\n fieldOrDatumDef: channelDef,\n fieldOrDatumDef2: channel2Def,\n bandPosition,\n offset\n });\n } else {\n const channel2 = channel === X ? X2 : Y2;\n log.warn(log.message.channelRequiredForBinned(channel2));\n }\n }\n }\n\n return valueRefForFieldOrDatumDef(\n channelDef,\n scaleName,\n hasDiscreteDomain(scaleType) ? {binSuffix: 'range'} : {}, // no need for bin suffix if there is no scale\n {\n offset,\n // For band, to get mid point, need to offset by half of the band\n band: scaleType === 'band' ? bandPosition ?? channelDef.bandPosition ?? 0.5 : undefined\n }\n );\n } else if (isValueDef(channelDef)) {\n const value = channelDef.value;\n const offsetMixins = offset ? {offset} : {};\n\n return {...widthHeightValueOrSignalRef(channel, value), ...offsetMixins};\n }\n\n // If channelDef is neither field def or value def, it's a condition-only def.\n // In such case, we will use default ref.\n }\n\n if (isFunction(defaultRef)) {\n defaultRef = defaultRef();\n }\n\n if (defaultRef) {\n // for non-position, ref could be undefined.\n return {\n ...defaultRef,\n // only include offset when it is non-zero (zero = no offset)\n ...(offset ? {offset} : {})\n };\n }\n return defaultRef;\n}\n\n/**\n * Convert special \"width\" and \"height\" values in Vega-Lite into Vega value ref.\n */\nexport function widthHeightValueOrSignalRef(channel: Channel, value: Value | SignalRef) {\n if (contains(['x', 'x2'], channel) && value === 'width') {\n return {field: {group: 'width'}};\n } else if (contains(['y', 'y2'], channel) && value === 'height') {\n return {field: {group: 'height'}};\n }\n return signalOrValueRef(value);\n}\n","import type {SignalRef} from 'vega';\nimport {isString} from 'vega-util';\nimport {isBinning} from '../bin';\nimport {\n channelDefType,\n DatumDef,\n FieldDef,\n isFieldDef,\n isFieldOrDatumDefForTimeFormat,\n isPositionFieldOrDatumDef,\n isScaleFieldDef,\n vgField\n} from '../channeldef';\nimport {Config} from '../config';\nimport {fieldValidPredicate} from '../predicate';\nimport {ScaleType} from '../scale';\nimport {formatExpression, normalizeTimeUnit, timeUnitSpecifierExpression} from '../timeunit';\nimport {QUANTITATIVE, Type} from '../type';\nimport {Dict, stringify} from '../util';\nimport {isSignalRef} from '../vega.schema';\nimport {TimeUnit} from './../timeunit';\nimport {datumDefToExpr} from './mark/encode/valueref';\n\nexport function isCustomFormatType(formatType: string) {\n return formatType && formatType !== 'number' && formatType !== 'time';\n}\n\nfunction customFormatExpr(formatType: string, field: string, format: string | Dict) {\n return `${formatType}(${field}${format ? `, ${stringify(format)}` : ''})`;\n}\n\nexport const BIN_RANGE_DELIMITER = ' \\u2013 ';\n\nexport function formatSignalRef({\n fieldOrDatumDef,\n format,\n formatType,\n expr,\n normalizeStack,\n config\n}: {\n fieldOrDatumDef: FieldDef | DatumDef;\n format: string | Dict;\n formatType: string;\n expr?: 'datum' | 'parent' | 'datum.datum';\n normalizeStack?: boolean;\n config: Config;\n}) {\n if (isCustomFormatType(formatType)) {\n return formatCustomType({\n fieldOrDatumDef,\n format,\n formatType,\n expr,\n config\n });\n }\n\n const field = fieldToFormat(fieldOrDatumDef, expr, normalizeStack);\n const type = channelDefType(fieldOrDatumDef);\n\n if (format === undefined && formatType === undefined && config.customFormatTypes) {\n if (type === 'quantitative') {\n if (normalizeStack && config.normalizedNumberFormatType)\n return formatCustomType({\n fieldOrDatumDef,\n format: config.normalizedNumberFormat,\n formatType: config.normalizedNumberFormatType,\n expr,\n config\n });\n if (config.numberFormatType) {\n return formatCustomType({\n fieldOrDatumDef,\n format: config.numberFormat,\n formatType: config.numberFormatType,\n expr,\n config\n });\n }\n }\n if (\n type === 'temporal' &&\n config.timeFormatType &&\n isFieldDef(fieldOrDatumDef) &&\n fieldOrDatumDef.timeUnit === undefined\n ) {\n return formatCustomType({\n fieldOrDatumDef,\n format: config.timeFormat,\n formatType: config.timeFormatType,\n expr,\n config\n });\n }\n }\n\n if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {\n const signal = timeFormatExpression({\n field,\n timeUnit: isFieldDef(fieldOrDatumDef) ? normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : undefined,\n format,\n formatType: config.timeFormatType,\n rawTimeFormat: config.timeFormat,\n isUTCScale: isScaleFieldDef(fieldOrDatumDef) && fieldOrDatumDef.scale?.type === ScaleType.UTC\n });\n return signal ? {signal} : undefined;\n }\n\n format = numberFormat({type, specifiedFormat: format, config, normalizeStack});\n if (isFieldDef(fieldOrDatumDef) && isBinning(fieldOrDatumDef.bin)) {\n const endField = vgField(fieldOrDatumDef, {expr, binSuffix: 'end'});\n return {\n signal: binFormatExpression(field, endField, format, formatType, config)\n };\n } else if (format || channelDefType(fieldOrDatumDef) === 'quantitative') {\n return {\n signal: `${formatExpr(field, format)}`\n };\n } else {\n return {signal: `isValid(${field}) ? ${field} : \"\"+${field}`};\n }\n}\n\nfunction fieldToFormat(\n fieldOrDatumDef: FieldDef | DatumDef,\n expr: 'datum' | 'parent' | 'datum.datum',\n normalizeStack: boolean\n) {\n if (isFieldDef(fieldOrDatumDef)) {\n if (normalizeStack) {\n return `${vgField(fieldOrDatumDef, {expr, suffix: 'end'})}-${vgField(fieldOrDatumDef, {\n expr,\n suffix: 'start'\n })}`;\n } else {\n return vgField(fieldOrDatumDef, {expr});\n }\n } else {\n return datumDefToExpr(fieldOrDatumDef);\n }\n}\n\nexport function formatCustomType({\n fieldOrDatumDef,\n format,\n formatType,\n expr,\n normalizeStack,\n config,\n field\n}: {\n fieldOrDatumDef: FieldDef | DatumDef;\n format: string | Dict;\n formatType: string;\n expr?: 'datum' | 'parent' | 'datum.datum';\n normalizeStack?: boolean;\n config: Config;\n field?: string; // axis/legend \"use datum.value\"\n}) {\n field ??= fieldToFormat(fieldOrDatumDef, expr, normalizeStack);\n\n if (\n field !== 'datum.value' && // For axis/legend, we can't correctly know the end of the bin from `datum`\n isFieldDef(fieldOrDatumDef) &&\n isBinning(fieldOrDatumDef.bin)\n ) {\n const endField = vgField(fieldOrDatumDef, {expr, binSuffix: 'end'});\n return {\n signal: binFormatExpression(field, endField, format, formatType, config)\n };\n }\n return {signal: customFormatExpr(formatType, field, format)};\n}\n\nexport function guideFormat(\n fieldOrDatumDef: FieldDef | DatumDef,\n type: Type,\n format: string | Dict,\n formatType: string | SignalRef,\n config: Config,\n omitTimeFormatConfig: boolean // axis doesn't use config.timeFormat\n) {\n if (isString(formatType) && isCustomFormatType(formatType)) {\n return undefined; // handled in encode block\n } else if (format === undefined && formatType === undefined && config.customFormatTypes) {\n if (channelDefType(fieldOrDatumDef) === 'quantitative') {\n if (\n config.normalizedNumberFormatType &&\n isPositionFieldOrDatumDef(fieldOrDatumDef) &&\n fieldOrDatumDef.stack === 'normalize'\n ) {\n return undefined; // handled in encode block\n }\n if (config.numberFormatType) {\n return undefined; // handled in encode block\n }\n }\n }\n\n if (\n isPositionFieldOrDatumDef(fieldOrDatumDef) &&\n fieldOrDatumDef.stack === 'normalize' &&\n config.normalizedNumberFormat\n ) {\n return numberFormat({\n type: 'quantitative',\n config,\n normalizeStack: true\n });\n }\n\n if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {\n const timeUnit = isFieldDef(fieldOrDatumDef) ? normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : undefined;\n if (timeUnit === undefined && config.customFormatTypes && config.timeFormatType) {\n return undefined; // hanlded in encode block\n }\n\n return timeFormat({specifiedFormat: format as string, timeUnit, config, omitTimeFormatConfig});\n }\n\n return numberFormat({type, specifiedFormat: format, config});\n}\n\nexport function guideFormatType(\n formatType: string | SignalRef,\n fieldOrDatumDef: FieldDef | DatumDef,\n scaleType: ScaleType\n) {\n if (formatType && (isSignalRef(formatType) || formatType === 'number' || formatType === 'time')) {\n return formatType;\n }\n if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef) && scaleType !== 'time' && scaleType !== 'utc') {\n return isFieldDef(fieldOrDatumDef) && normalizeTimeUnit(fieldOrDatumDef?.timeUnit)?.utc ? 'utc' : 'time';\n }\n return undefined;\n}\n\n/**\n * Returns number format for a fieldDef.\n */\nexport function numberFormat({\n type,\n specifiedFormat,\n config,\n normalizeStack\n}: {\n type: Type;\n specifiedFormat?: string | Dict;\n config: Config;\n normalizeStack?: boolean;\n}) {\n // Specified format in axis/legend has higher precedence than fieldDef.format\n if (isString(specifiedFormat)) {\n return specifiedFormat;\n }\n\n if (type === QUANTITATIVE) {\n // we only apply the default if the field is quantitative\n return normalizeStack ? config.normalizedNumberFormat : config.numberFormat;\n }\n return undefined;\n}\n\n/**\n * Returns time format for a fieldDef for use in guides.\n */\nexport function timeFormat({\n specifiedFormat,\n timeUnit,\n config,\n omitTimeFormatConfig\n}: {\n specifiedFormat?: string;\n timeUnit?: TimeUnit;\n config: Config;\n omitTimeFormatConfig?: boolean;\n}) {\n if (specifiedFormat) {\n return specifiedFormat;\n }\n\n if (timeUnit) {\n return {\n signal: timeUnitSpecifierExpression(timeUnit)\n };\n }\n\n return omitTimeFormatConfig ? undefined : config.timeFormat;\n}\n\nfunction formatExpr(field: string, format: string) {\n return `format(${field}, \"${format || ''}\")`;\n}\n\nfunction binNumberFormatExpr(field: string, format: string | Dict, formatType: string, config: Config) {\n if (isCustomFormatType(formatType)) {\n return customFormatExpr(formatType, field, format);\n }\n\n return formatExpr(field, (isString(format) ? format : undefined) ?? config.numberFormat);\n}\n\nexport function binFormatExpression(\n startField: string,\n endField: string,\n format: string | Dict,\n formatType: string,\n config: Config\n): string {\n if (format === undefined && formatType === undefined && config.customFormatTypes && config.numberFormatType) {\n return binFormatExpression(startField, endField, config.numberFormat, config.numberFormatType, config);\n }\n const start = binNumberFormatExpr(startField, format, formatType, config);\n const end = binNumberFormatExpr(endField, format, formatType, config);\n return `${fieldValidPredicate(startField, false)} ? \"null\" : ${start} + \"${BIN_RANGE_DELIMITER}\" + ${end}`;\n}\n\n/**\n * Returns the time expression used for axis/legend labels or text mark for a temporal field\n */\nexport function timeFormatExpression({\n field,\n timeUnit,\n format,\n formatType,\n rawTimeFormat,\n isUTCScale\n}: {\n field: string;\n timeUnit?: TimeUnit;\n format?: string | Dict;\n formatType?: string;\n rawTimeFormat?: string; // should be provided only for actual text and headers, not axis/legend labels\n isUTCScale?: boolean;\n}): string {\n if (!timeUnit || format) {\n // If there is no time unit, or if user explicitly specifies format for axis/legend/text.\n if (!timeUnit && formatType) {\n return `${formatType}(${field}, '${format}')`;\n }\n format = isString(format) ? format : rawTimeFormat; // only use provided timeFormat if there is no timeUnit.\n return `${isUTCScale ? 'utc' : 'time'}Format(${field}, '${format}')`;\n } else {\n return formatExpression(timeUnit, field, isUTCScale);\n }\n}\n","import {isArray} from 'vega-util';\nimport {NonArgAggregateOp} from './aggregate';\nimport {FieldName} from './channeldef';\nimport {DateTime} from './datetime';\n\nexport type SortOrder = 'ascending' | 'descending';\n\n/**\n * A sort definition for transform\n */\nexport interface SortField {\n /**\n * The name of the field to sort.\n */\n field: FieldName;\n\n /**\n * Whether to sort the field in ascending or descending order. One of `\"ascending\"` (default), `\"descending\"`, or `null` (no not sort).\n */\n order?: SortOrder | null;\n}\n\nexport interface SortFields {\n field: FieldName[];\n order?: SortOrder[];\n}\n\nexport const DEFAULT_SORT_OP = 'min';\n\n/**\n * A sort definition for sorting a discrete scale in an encoding field definition.\n */\n\nexport interface EncodingSortField {\n /**\n * The data [field](https://vega.github.io/vega-lite/docs/field.html) to sort by.\n *\n * __Default value:__ If unspecified, defaults to the field specified in the outer data reference.\n */\n field?: F; // Field is optional because `\"op\": \"count\"` does not require a field.\n /**\n * An [aggregate operation](https://vega.github.io/vega-lite/docs/aggregate.html#ops) to perform on the field prior to sorting (e.g., `\"count\"`, `\"mean\"` and `\"median\"`).\n * An aggregation is required when there are multiple values of the sort field for each encoded data field.\n * The input data objects will be aggregated, grouped by the encoded data field.\n *\n * For a full list of operations, please see the documentation for [aggregate](https://vega.github.io/vega-lite/docs/aggregate.html#ops).\n *\n * __Default value:__ `\"sum\"` for stacked plots. Otherwise, `\"min\"`.\n */\n op?: NonArgAggregateOp;\n\n /**\n * The sort order. One of `\"ascending\"` (default), `\"descending\"`, or `null` (no not sort).\n */\n order?: SortOrder | null;\n}\n\nexport interface SortByEncoding {\n /**\n * The [encoding channel](https://vega.github.io/vega-lite/docs/encoding.html#channels) to sort by (e.g., `\"x\"`, `\"y\"`)\n */\n encoding: SortByChannel;\n\n /**\n * The sort order. One of `\"ascending\"` (default), `\"descending\"`, or `null` (no not sort).\n */\n order?: SortOrder | null;\n}\n\nexport type SortArray = number[] | string[] | boolean[] | DateTime[];\n\nconst SORT_BY_CHANNEL_INDEX = {\n x: 1,\n y: 1,\n color: 1,\n fill: 1,\n stroke: 1,\n strokeWidth: 1,\n size: 1,\n shape: 1,\n fillOpacity: 1,\n strokeOpacity: 1,\n opacity: 1,\n text: 1\n} as const;\n\nexport type SortByChannel = keyof typeof SORT_BY_CHANNEL_INDEX;\n\nexport function isSortByChannel(c: string): c is SortByChannel {\n return c in SORT_BY_CHANNEL_INDEX;\n}\n\nexport type SortByChannelDesc =\n | '-x'\n | '-y'\n | '-color'\n | '-fill'\n | '-stroke'\n | '-strokeWidth'\n | '-size'\n | '-shape'\n | '-fillOpacity'\n | '-strokeOpacity'\n | '-opacity'\n | '-text';\n\nexport type AllSortString = SortOrder | SortByChannel | SortByChannelDesc;\n\nexport type Sort = SortArray | AllSortString | EncodingSortField | SortByEncoding | null;\n\nexport function isSortByEncoding(sort: Sort): sort is SortByEncoding {\n return !!sort?.['encoding'];\n}\n\nexport function isSortField(sort: Sort): sort is EncodingSortField {\n return sort && (sort['op'] === 'count' || !!sort['field']);\n}\n\nexport function isSortArray(sort: Sort): sort is SortArray {\n return sort && isArray(sort);\n}\n","import {LayoutAlign, SignalRef} from 'vega';\nimport {BinParams} from '../bin';\nimport {ChannelDef, Field, FieldName, TypedFieldDef} from '../channeldef';\nimport {ExprRef} from '../expr';\nimport {Header} from '../header';\nimport {EncodingSortField, SortArray, SortOrder} from '../sort';\nimport {StandardType} from '../type';\nimport {BaseSpec, GenericCompositionLayoutWithColumns, ResolveMixins} from './base';\nimport {GenericLayerSpec, NormalizedLayerSpec} from './layer';\nimport {GenericUnitSpec, NormalizedUnitSpec} from './unit';\n\nexport interface FacetFieldDef\n extends TypedFieldDef {\n /**\n * An object defining properties of a facet's header.\n */\n header?: Header | null;\n\n // Note: `\"sort\"` for facet field def is different from encoding field def as it does not support `SortByEncoding`\n\n /**\n * Sort order for the encoded field.\n *\n * For continuous fields (quantitative or temporal), `sort` can be either `\"ascending\"` or `\"descending\"`.\n *\n * For discrete fields, `sort` can be one of the following:\n * - `\"ascending\"` or `\"descending\"` -- for sorting by the values' natural order in JavaScript.\n * - [A sort field definition](https://vega.github.io/vega-lite/docs/sort.html#sort-field) for sorting by another field.\n * - [An array specifying the field values in preferred order](https://vega.github.io/vega-lite/docs/sort.html#sort-array). In this case, the sort order will obey the values in the array, followed by any unspecified values in their original order. For discrete time field, values in the sort array can be [date-time definition objects](types#datetime). In addition, for time units `\"month\"` and `\"day\"`, the values can be the month or day names (case insensitive) or their 3-letter initials (e.g., `\"Mon\"`, `\"Tue\"`).\n * - `null` indicating no sort.\n *\n * __Default value:__ `\"ascending\"`\n *\n * __Note:__ `null` is not supported for `row` and `column`.\n */\n sort?: SortArray | SortOrder | EncodingSortField | null;\n}\n\nexport type FacetEncodingFieldDef<\n F extends Field,\n ES extends ExprRef | SignalRef = ExprRef | SignalRef\n> = FacetFieldDef & GenericCompositionLayoutWithColumns;\n\nexport interface RowColumnEncodingFieldDef\n extends FacetFieldDef {\n // Manually declarae this separated from GenericCompositionLayout as we don't support RowCol object in RowColumnEncodingFieldDef\n\n /**\n * The alignment to apply to row/column facet's subplot.\n * The supported string values are `\"all\"`, `\"each\"`, and `\"none\"`.\n *\n * - For `\"none\"`, a flow layout will be used, in which adjacent subviews are simply placed one after the other.\n * - For `\"each\"`, subviews will be aligned into a clean grid structure, but each row or column may be of variable size.\n * - For `\"all\"`, subviews will be aligned and each row or column will be sized identically based on the maximum observed size. String values for this property will be applied to both grid rows and columns.\n *\n * __Default value:__ `\"all\"`.\n */\n align?: LayoutAlign;\n\n /**\n * Boolean flag indicating if facet's subviews should be centered relative to their respective rows or columns.\n *\n * __Default value:__ `false`\n */\n center?: boolean;\n\n /**\n * The spacing in pixels between facet's sub-views.\n *\n * __Default value__: Depends on `\"spacing\"` property of [the view composition configuration](https://vega.github.io/vega-lite/docs/config.html#view-config) (`20` by default)\n */\n spacing?: number;\n}\n\nexport interface FacetMapping<\n F extends Field,\n FD extends FacetFieldDef = FacetFieldDef\n> {\n /**\n * A field definition for the vertical facet of trellis plots.\n */\n row?: FD;\n\n /**\n * A field definition for the horizontal facet of trellis plots.\n */\n column?: FD;\n}\n\nexport function isFacetMapping(\n f: FacetFieldDef | FacetMapping\n): f is FacetMapping {\n return 'row' in f || 'column' in f;\n}\n\n/**\n * Facet mapping for encoding macro\n */\nexport interface EncodingFacetMapping\n extends FacetMapping> {\n /**\n * A field definition for the (flexible) facet of trellis plots.\n *\n * If either `row` or `column` is specified, this channel will be ignored.\n */\n facet?: FacetEncodingFieldDef;\n}\n\nexport function isFacetFieldDef(channelDef: ChannelDef): channelDef is FacetFieldDef {\n return !!channelDef && 'header' in channelDef;\n}\n\n/**\n * Base interface for a facet specification.\n */\nexport interface GenericFacetSpec, L extends GenericLayerSpec, F extends Field>\n extends BaseSpec,\n GenericCompositionLayoutWithColumns,\n ResolveMixins {\n /**\n * Definition for how to facet the data. One of:\n * 1) [a field definition for faceting the plot by one field](https://vega.github.io/vega-lite/docs/facet.html#field-def)\n * 2) [An object that maps `row` and `column` channels to their field definitions](https://vega.github.io/vega-lite/docs/facet.html#mapping)\n */\n facet: FacetFieldDef | FacetMapping;\n\n /**\n * A specification of the view that gets faceted.\n */\n spec: L | U;\n // TODO: replace this with GenericSpec once we support all cases;\n}\n\n/**\n * A facet specification without any shortcut / expansion syntax\n */\nexport type NormalizedFacetSpec = GenericFacetSpec;\n\nexport function isFacetSpec(spec: BaseSpec): spec is GenericFacetSpec {\n return 'facet' in spec;\n}\n","import {Gradient, ScaleType, SignalRef, Text} from 'vega';\nimport {isArray, isBoolean, isNumber, isString} from 'vega-util';\nimport {Aggregate, isAggregateOp, isArgmaxDef, isArgminDef, isCountingAggregateOp} from './aggregate';\nimport {Axis} from './axis';\nimport {autoMaxBins, Bin, BinParams, binToString, isBinned, isBinning} from './bin';\nimport {\n ANGLE,\n Channel,\n COLOR,\n COLUMN,\n DESCRIPTION,\n DETAIL,\n ExtendedChannel,\n FACET,\n FILL,\n FILLOPACITY,\n getSizeChannel,\n HREF,\n isScaleChannel,\n isSecondaryRangeChannel,\n isXorY,\n KEY,\n LATITUDE,\n LATITUDE2,\n LONGITUDE,\n LONGITUDE2,\n OPACITY,\n ORDER,\n PolarPositionScaleChannel,\n PositionScaleChannel,\n RADIUS,\n RADIUS2,\n ROW,\n SHAPE,\n SIZE,\n STROKE,\n STROKEDASH,\n STROKEOPACITY,\n STROKEWIDTH,\n TEXT,\n THETA,\n THETA2,\n TOOLTIP,\n URL,\n X,\n X2,\n XOFFSET,\n Y,\n Y2,\n YOFFSET\n} from './channel';\nimport {getMarkConfig, getMarkPropOrConfig} from './compile/common';\nimport {isCustomFormatType} from './compile/format';\nimport {CompositeAggregate} from './compositemark';\nimport {Config} from './config';\nimport {DateTime, dateTimeToExpr, isDateTime} from './datetime';\nimport {Encoding} from './encoding';\nimport {ExprRef, isExprRef} from './expr';\nimport {Guide, GuideEncodingConditionalValueDef, TitleMixins} from './guide';\nimport {ImputeParams} from './impute';\nimport {Legend} from './legend';\nimport * as log from './log';\nimport {LogicalComposition} from './logical';\nimport {isRectBasedMark, Mark, MarkDef, RelativeBandSize} from './mark';\nimport {ParameterPredicate, Predicate} from './predicate';\nimport {hasDiscreteDomain, isContinuousToDiscrete, Scale, SCALE_CATEGORY_INDEX} from './scale';\nimport {isSortByChannel, Sort, SortOrder} from './sort';\nimport {isFacetFieldDef} from './spec/facet';\nimport {StackOffset} from './stack';\nimport {\n BinnedTimeUnit,\n getTimeUnitParts,\n isBinnedTimeUnit,\n isLocalSingleTimeUnit,\n normalizeTimeUnit,\n TimeUnit,\n TimeUnitParams,\n timeUnitToString\n} from './timeunit';\nimport {AggregatedFieldDef, WindowFieldDef} from './transform';\nimport {getFullName, QUANTITATIVE, StandardType, Type} from './type';\nimport {\n Dict,\n flatAccessWithDatum,\n getFirstDefined,\n internalField,\n omit,\n removePathFromField,\n replacePathInField,\n stringify,\n titleCase\n} from './util';\nimport {isSignalRef} from './vega.schema';\n\nexport type PrimitiveValue = number | string | boolean | null;\n\nexport type Value =\n | PrimitiveValue\n | number[]\n | Gradient\n | Text\n | ES;\n\n/**\n * Definition object for a constant value (primitive value or gradient definition) of an encoding channel.\n */\nexport interface ValueDef {\n /**\n * A constant value in visual domain (e.g., `\"red\"` / `\"#0099ff\"` / [gradient definition](https://vega.github.io/vega-lite/docs/types.html#gradient) for color, values between `0` to `1` for opacity).\n */\n value: V;\n}\n\nexport type PositionValueDef = ValueDef;\nexport type NumericValueDef = ValueDef;\n\n/**\n * A ValueDef with Condition where either the condition or the value are optional.\n * {\n * condition: {field: ...} | {value: ...},\n * value: ...,\n * }\n */\n\n/**\n * @minProperties 1\n */\nexport type ValueDefWithCondition | DatumDef, V extends Value = Value> = Partial<\n ValueDef\n> & {\n /**\n * A field definition or one or more value definition(s) with a parameter predicate.\n */\n condition?:\n | Conditional\n | Conditional>\n | Conditional>[];\n};\n\nexport type StringValueDefWithCondition = ValueDefWithCondition<\n MarkPropFieldOrDatumDef,\n string | null\n>;\nexport type TypeForShape = 'nominal' | 'ordinal' | 'geojson';\n\nexport type ConditionalTemplate = FieldDef | DatumDef | ValueDef | ExprRef | SignalRef;\n\nexport type Conditional = ConditionalPredicate | ConditionalParameter;\n\nexport type ConditionalPredicate = {\n /**\n * Predicate for triggering the condition\n */\n test: LogicalComposition;\n} & CD;\n\nexport type ConditionalParameter = ParameterPredicate & CD;\n\nexport function isConditionalParameter(c: Conditional): c is ConditionalParameter {\n return c['param'];\n}\n\nexport interface ConditionValueDefMixins {\n /**\n * One or more value definition(s) with [a parameter or a test predicate](https://vega.github.io/vega-lite/docs/condition.html).\n *\n * __Note:__ A field definition's `condition` property can only contain [conditional value definitions](https://vega.github.io/vega-lite/docs/condition.html#value)\n * since Vega-Lite only allows at most one encoded field per encoding channel.\n */\n condition?: Conditional> | Conditional>[];\n}\n\n/**\n * A FieldDef with Condition\n * {\n * condition: {value: ...},\n * field: ...,\n * ...\n * }\n */\n\nexport type FieldOrDatumDefWithCondition | DatumDef, V extends Value = Value> = F &\n ConditionValueDefMixins;\n\nexport type MarkPropDef =\n | FieldOrDatumDefWithCondition, V>\n | FieldOrDatumDefWithCondition, V>\n | ValueDefWithCondition, V>;\n\nexport type ColorDef = MarkPropDef;\nexport type NumericMarkPropDef = MarkPropDef;\n\nexport type NumericArrayMarkPropDef = MarkPropDef;\n\nexport type ShapeDef = MarkPropDef;\n\nexport type StringFieldDefWithCondition = FieldOrDatumDefWithCondition, string>;\nexport type TextDef =\n | FieldOrDatumDefWithCondition, Text>\n | FieldOrDatumDefWithCondition, Text>\n | ValueDefWithCondition, Text>;\n\n/**\n * A ValueDef with optional Condition\n * {\n * condition: {field: ...} | {value: ...},\n * value: ...,\n * }\n */\n\n/**\n * Reference to a repeated value.\n */\nexport interface RepeatRef {\n repeat: 'row' | 'column' | 'repeat' | 'layer';\n}\n\nexport type FieldName = string;\nexport type Field = FieldName | RepeatRef;\n\nexport function isRepeatRef(field: Field | any): field is RepeatRef {\n return field && !isString(field) && 'repeat' in field;\n}\n\n/** @@hidden */\nexport type HiddenCompositeAggregate = CompositeAggregate;\n\nexport interface FieldDefBase extends BandMixins {\n /**\n * __Required.__ A string defining the name of the field from which to pull a data value\n * or an object defining iterated values from the [`repeat`](https://vega.github.io/vega-lite/docs/repeat.html) operator.\n *\n * __See also:__ [`field`](https://vega.github.io/vega-lite/docs/field.html) documentation.\n *\n * __Notes:__\n * 1) Dots (`.`) and brackets (`[` and `]`) can be used to access nested objects (e.g., `\"field\": \"foo.bar\"` and `\"field\": \"foo['bar']\"`).\n * If field names contain dots or brackets but are not nested, you can use `\\\\` to escape dots and brackets (e.g., `\"a\\\\.b\"` and `\"a\\\\[0\\\\]\"`).\n * See more details about escaping in the [field documentation](https://vega.github.io/vega-lite/docs/field.html).\n * 2) `field` is not required if `aggregate` is `count`.\n */\n field?: F;\n\n // function\n\n /**\n * Time unit (e.g., `year`, `yearmonth`, `month`, `hours`) for a temporal field.\n * or [a temporal field that gets casted as ordinal](https://vega.github.io/vega-lite/docs/type.html#cast).\n *\n * __Default value:__ `undefined` (None)\n *\n * __See also:__ [`timeUnit`](https://vega.github.io/vega-lite/docs/timeunit.html) documentation.\n */\n timeUnit?: TimeUnit | BinnedTimeUnit | TimeUnitParams;\n\n /**\n * Aggregation function for the field\n * (e.g., `\"mean\"`, `\"sum\"`, `\"median\"`, `\"min\"`, `\"max\"`, `\"count\"`).\n *\n * __Default value:__ `undefined` (None)\n *\n * __See also:__ [`aggregate`](https://vega.github.io/vega-lite/docs/aggregate.html) documentation.\n */\n aggregate?: Aggregate | HiddenCompositeAggregate;\n\n /**\n * A flag for binning a `quantitative` field, [an object defining binning parameters](https://vega.github.io/vega-lite/docs/bin.html#bin-parameters), or indicating that the data for `x` or `y` channel are binned before they are imported into Vega-Lite (`\"binned\"`).\n *\n * - If `true`, default [binning parameters](https://vega.github.io/vega-lite/docs/bin.html#bin-parameters) will be applied.\n *\n * - If `\"binned\"`, this indicates that the data for the `x` (or `y`) channel are already binned. You can map the bin-start field to `x` (or `y`) and the bin-end field to `x2` (or `y2`). The scale and axis will be formatted similar to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also set the axis's [`tickMinStep`](https://vega.github.io/vega-lite/docs/axis.html#ticks) property.\n *\n * __Default value:__ `false`\n *\n * __See also:__ [`bin`](https://vega.github.io/vega-lite/docs/bin.html) documentation.\n */\n bin?: B;\n}\n\nexport function toFieldDefBase(fieldDef: FieldDef): FieldDefBase {\n const {field, timeUnit, bin, aggregate} = fieldDef;\n return {\n ...(timeUnit ? {timeUnit} : {}),\n ...(bin ? {bin} : {}),\n ...(aggregate ? {aggregate} : {}),\n field\n };\n}\n\nexport interface TypeMixins {\n /**\n * The type of measurement (`\"quantitative\"`, `\"temporal\"`, `\"ordinal\"`, or `\"nominal\"`) for the encoded field or constant value (`datum`).\n * It can also be a `\"geojson\"` type for encoding ['geoshape'](https://vega.github.io/vega-lite/docs/geoshape.html).\n *\n * Vega-Lite automatically infers data types in many cases as discussed below. However, type is required for a field if:\n * (1) the field is not nominal and the field encoding has no specified `aggregate` (except `argmin` and `argmax`), `bin`, scale type, custom `sort` order, nor `timeUnit`\n * or (2) if you wish to use an ordinal scale for a field with `bin` or `timeUnit`.\n *\n * __Default value:__\n *\n * 1) For a data `field`, `\"nominal\"` is the default data type unless the field encoding has `aggregate`, `channel`, `bin`, scale type, `sort`, or `timeUnit` that satisfies the following criteria:\n * - `\"quantitative\"` is the default type if (1) the encoded field contains `bin` or `aggregate` except `\"argmin\"` and `\"argmax\"`, (2) the encoding channel is `latitude` or `longitude` channel or (3) if the specified scale type is [a quantitative scale](https://vega.github.io/vega-lite/docs/scale.html#type).\n * - `\"temporal\"` is the default type if (1) the encoded field contains `timeUnit` or (2) the specified scale type is a time or utc scale\n * - `\"ordinal\"` is the default type if (1) the encoded field contains a [custom `sort` order](https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order), (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding channel is `order`.\n *\n * 2) For a constant value in data domain (`datum`):\n * - `\"quantitative\"` if the datum is a number\n * - `\"nominal\"` if the datum is a string\n * - `\"temporal\"` if the datum is [a date time object](https://vega.github.io/vega-lite/docs/datetime.html)\n *\n * __Note:__\n * - Data `type` describes the semantics of the data rather than the primitive data types (number, string, etc.). The same primitive data type can have different types of measurement. For example, numeric data can represent quantitative, ordinal, or nominal data.\n * - Data values for a temporal field can be either a date-time string (e.g., `\"2015-03-07 12:32:17\"`, `\"17:01\"`, `\"2015-03-16\"`. `\"2015\"`) or a timestamp number (e.g., `1552199579097`).\n * - When using with [`bin`](https://vega.github.io/vega-lite/docs/bin.html), the `type` property can be either `\"quantitative\"` (for using a linear bin scale) or [`\"ordinal\"` (for using an ordinal bin scale)](https://vega.github.io/vega-lite/docs/type.html#cast-bin).\n * - When using with [`timeUnit`](https://vega.github.io/vega-lite/docs/timeunit.html), the `type` property can be either `\"temporal\"` (default, for using a temporal scale) or [`\"ordinal\"` (for using an ordinal scale)](https://vega.github.io/vega-lite/docs/type.html#cast-bin).\n * - When using with [`aggregate`](https://vega.github.io/vega-lite/docs/aggregate.html), the `type` property refers to the post-aggregation data type. For example, we can calculate count `distinct` of a categorical field `\"cat\"` using `{\"aggregate\": \"distinct\", \"field\": \"cat\"}`. The `\"type\"` of the aggregate output is `\"quantitative\"`.\n * - Secondary channels (e.g., `x2`, `y2`, `xError`, `yError`) do not have `type` as they must have exactly the same type as their primary channels (e.g., `x`, `y`).\n *\n * __See also:__ [`type`](https://vega.github.io/vega-lite/docs/type.html) documentation.\n */\n type?: T;\n}\n\n/**\n * Definition object for a data field, its type and transformation of an encoding channel.\n */\nexport type TypedFieldDef<\n F extends Field,\n T extends Type = any,\n B extends Bin = boolean | BinParams | 'binned' | null // This is equivalent to Bin but we use the full form so the docs has detailed types\n> = FieldDefBase & TitleMixins & TypeMixins;\n\nexport interface SortableFieldDef<\n F extends Field,\n T extends Type = StandardType,\n B extends Bin = boolean | BinParams | null\n> extends TypedFieldDef {\n /**\n * Sort order for the encoded field.\n *\n * For continuous fields (quantitative or temporal), `sort` can be either `\"ascending\"` or `\"descending\"`.\n *\n * For discrete fields, `sort` can be one of the following:\n * - `\"ascending\"` or `\"descending\"` -- for sorting by the values' natural order in JavaScript.\n * - [A string indicating an encoding channel name to sort by](https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding) (e.g., `\"x\"` or `\"y\"`) with an optional minus prefix for descending sort (e.g., `\"-x\"` to sort by x-field, descending). This channel string is short-form of [a sort-by-encoding definition](https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding). For example, `\"sort\": \"-x\"` is equivalent to `\"sort\": {\"encoding\": \"x\", \"order\": \"descending\"}`.\n * - [A sort field definition](https://vega.github.io/vega-lite/docs/sort.html#sort-field) for sorting by another field.\n * - [An array specifying the field values in preferred order](https://vega.github.io/vega-lite/docs/sort.html#sort-array). In this case, the sort order will obey the values in the array, followed by any unspecified values in their original order. For discrete time field, values in the sort array can be [date-time definition objects](types#datetime). In addition, for time units `\"month\"` and `\"day\"`, the values can be the month or day names (case insensitive) or their 3-letter initials (e.g., `\"Mon\"`, `\"Tue\"`).\n * - `null` indicating no sort.\n *\n * __Default value:__ `\"ascending\"`\n *\n * __Note:__ `null` and sorting by another channel is not supported for `row` and `column`.\n *\n * __See also:__ [`sort`](https://vega.github.io/vega-lite/docs/sort.html) documentation.\n */\n sort?: Sort;\n}\n\nexport function isSortableFieldDef(fieldDef: FieldDef): fieldDef is SortableFieldDef {\n return 'sort' in fieldDef;\n}\n\nexport type ScaleFieldDef<\n F extends Field,\n T extends Type = StandardType,\n B extends Bin = boolean | BinParams | null\n> = SortableFieldDef & ScaleMixins;\n\nexport interface ScaleMixins {\n /**\n * An object defining properties of the channel's scale, which is the function that transforms values in the data domain (numbers, dates, strings, etc) to visual values (pixels, colors, sizes) of the encoding channels.\n *\n * If `null`, the scale will be [disabled and the data value will be directly encoded](https://vega.github.io/vega-lite/docs/scale.html#disable).\n *\n * __Default value:__ If undefined, default [scale properties](https://vega.github.io/vega-lite/docs/scale.html) are applied.\n *\n * __See also:__ [`scale`](https://vega.github.io/vega-lite/docs/scale.html) documentation.\n */\n scale?: Scale | null;\n}\n\nexport type OffsetDef =\n | ScaleFieldDef\n | ScaleDatumDef\n | ValueDef;\n\nexport interface DatumDef<\n F extends Field = string,\n V extends PrimitiveValue | DateTime | ExprRef | SignalRef = PrimitiveValue | DateTime | ExprRef | SignalRef\n> extends Partial>,\n BandMixins,\n TitleMixins {\n /**\n * A constant value in data domain.\n */\n datum?: F extends RepeatRef ? V | RepeatRef : V;\n // only apply Repeatref if field (F) can be RepeatRef\n // FIXME(https://github.com/microsoft/TypeScript/issues/37586):\n // `F extends RepeatRef` probably should be `RepeatRef extends F` but there is likely a bug in TS.\n}\n\nexport interface FormatMixins {\n /**\n * When used with the default `\"number\"` and `\"time\"` format type, the text formatting pattern for labels of guides (axes, legends, headers) and text marks.\n *\n * - If the format type is `\"number\"` (e.g., for quantitative fields), this is D3's [number format pattern](https://github.com/d3/d3-format#locale_format).\n * - If the format type is `\"time\"` (e.g., for temporal fields), this is D3's [time format pattern](https://github.com/d3/d3-time-format#locale_format).\n *\n * See the [format documentation](https://vega.github.io/vega-lite/docs/format.html) for more examples.\n *\n * When used with a [custom `formatType`](https://vega.github.io/vega-lite/docs/config.html#custom-format-type), this value will be passed as `format` alongside `datum.value` to the registered function.\n *\n * __Default value:__ Derived from [numberFormat](https://vega.github.io/vega-lite/docs/config.html#format) config for number format and from [timeFormat](https://vega.github.io/vega-lite/docs/config.html#format) config for time format.\n */\n format?: string | Dict;\n\n /**\n * The format type for labels. One of `\"number\"`, `\"time\"`, or a [registered custom format type](https://vega.github.io/vega-lite/docs/config.html#custom-format-type).\n *\n * __Default value:__\n * - `\"time\"` for temporal fields and ordinal and nominal fields with `timeUnit`.\n * - `\"number\"` for quantitative fields as well as ordinal and nominal fields without `timeUnit`.\n */\n formatType?: 'number' | 'time' | string;\n}\n\nexport type StringDatumDef = DatumDef & FormatMixins;\n\nexport type ScaleDatumDef = ScaleMixins & DatumDef;\n\n/**\n * A field definition of a secondary channel that shares a scale with another primary channel. For example, `x2`, `xError` and `xError2` share the same scale with `x`.\n */\nexport type SecondaryFieldDef = FieldDefBase & TitleMixins; // x2/y2 shouldn't have bin, but we keep bin property for simplicity of the codebase.\n\nexport type Position2Def = SecondaryFieldDef | DatumDef | PositionValueDef;\n\nexport type SecondaryChannelDef = Encoding['x2' | 'y2'];\n\n/**\n * Field Def without scale (and without bin: \"binned\" support).\n */\nexport type FieldDefWithoutScale = TypedFieldDef;\n\nexport type LatLongFieldDef = FieldDefBase &\n TitleMixins &\n Partial>; // Lat long shouldn't have bin, but we keep bin property for simplicity of the codebase.\n\nexport type LatLongDef = LatLongFieldDef | DatumDef;\n\nexport type PositionFieldDefBase = ScaleFieldDef<\n F,\n StandardType,\n boolean | BinParams | 'binned' | null // This is equivalent to Bin but we use the full form so the docs has detailed types\n> &\n PositionBaseMixins;\n\nexport type PositionDatumDefBase = ScaleDatumDef & PositionBaseMixins;\n\nexport interface PositionBaseMixins {\n /**\n * Type of stacking offset if the field should be stacked.\n * `stack` is only applicable for `x`, `y`, `theta`, and `radius` channels with continuous domains.\n * For example, `stack` of `y` can be used to customize stacking for a vertical bar chart.\n *\n * `stack` can be one of the following values:\n * - `\"zero\"` or `true`: stacking with baseline offset at zero value of the scale (for creating typical stacked [bar](https://vega.github.io/vega-lite/docs/stack.html#bar) and [area](https://vega.github.io/vega-lite/docs/stack.html#area) chart).\n * - `\"normalize\"` - stacking with normalized domain (for creating [normalized stacked bar and area charts](https://vega.github.io/vega-lite/docs/stack.html#normalized) and pie charts [with percentage tooltip](https://vega.github.io/vega-lite/docs/arc.html#tooltip)).
\n * -`\"center\"` - stacking with center baseline (for [streamgraph](https://vega.github.io/vega-lite/docs/stack.html#streamgraph)).\n * - `null` or `false` - No-stacking. This will produce layered [bar](https://vega.github.io/vega-lite/docs/stack.html#layered-bar-chart) and area chart.\n *\n * __Default value:__ `zero` for plots with all of the following conditions are true:\n * (1) the mark is `bar`, `area`, or `arc`;\n * (2) the stacked measure channel (x or y) has a linear scale;\n * (3) At least one of non-position channels mapped to an unaggregated field that is different from x and y. Otherwise, `null` by default.\n *\n * __See also:__ [`stack`](https://vega.github.io/vega-lite/docs/stack.html) documentation.\n */\n stack?: StackOffset | null | boolean;\n}\n\nexport interface BandMixins {\n /**\n * Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to `0`, and at the middle of the band if set to `0.5`.\n *\n * @minimum 0\n * @maximum 1\n */\n bandPosition?: number;\n}\n\nexport type PositionFieldDef = PositionFieldDefBase & PositionMixins;\n\nexport type PositionDatumDef = PositionDatumDefBase & PositionMixins;\n\nexport type PositionDef = PositionFieldDef | PositionDatumDef | PositionValueDef;\n\nexport interface PositionMixins {\n /**\n * An object defining properties of axis's gridlines, ticks and labels.\n * If `null`, the axis for the encoding channel will be removed.\n *\n * __Default value:__ If undefined, default [axis properties](https://vega.github.io/vega-lite/docs/axis.html) are applied.\n *\n * __See also:__ [`axis`](https://vega.github.io/vega-lite/docs/axis.html) documentation.\n */\n axis?: Axis | null;\n\n /**\n * An object defining the properties of the Impute Operation to be applied.\n * The field value of the other positional channel is taken as `key` of the `Impute` Operation.\n * The field of the `color` channel if specified is used as `groupby` of the `Impute` Operation.\n *\n * __See also:__ [`impute`](https://vega.github.io/vega-lite/docs/impute.html) documentation.\n */\n impute?: ImputeParams | null;\n}\n\nexport type PolarDef = PositionFieldDefBase | PositionDatumDefBase | PositionValueDef;\n\nexport function getBandPosition({\n fieldDef,\n fieldDef2,\n markDef: mark,\n config\n}: {\n fieldDef: FieldDef | DatumDef;\n fieldDef2?: SecondaryChannelDef;\n markDef: MarkDef;\n config: Config;\n}): number {\n if (isFieldOrDatumDef(fieldDef) && fieldDef.bandPosition !== undefined) {\n return fieldDef.bandPosition;\n }\n if (isFieldDef(fieldDef)) {\n const {timeUnit, bin} = fieldDef;\n if (timeUnit && !fieldDef2) {\n return getMarkConfig('timeUnitBandPosition', mark, config);\n } else if (isBinning(bin)) {\n return 0.5;\n }\n }\n\n return undefined;\n}\n\nexport function getBandSize({\n channel,\n fieldDef,\n fieldDef2,\n markDef: mark,\n config,\n scaleType,\n useVlSizeChannel\n}: {\n channel: PositionScaleChannel | PolarPositionScaleChannel;\n fieldDef: ChannelDef;\n fieldDef2?: SecondaryChannelDef;\n markDef: MarkDef;\n config: Config;\n scaleType: ScaleType;\n useVlSizeChannel?: boolean;\n}): number | RelativeBandSize | SignalRef {\n const sizeChannel = getSizeChannel(channel);\n const size = getMarkPropOrConfig(useVlSizeChannel ? 'size' : sizeChannel, mark, config, {\n vgChannel: sizeChannel\n });\n\n if (size !== undefined) {\n return size;\n }\n\n if (isFieldDef(fieldDef)) {\n const {timeUnit, bin} = fieldDef;\n\n if (timeUnit && !fieldDef2) {\n return {band: getMarkConfig('timeUnitBandSize', mark, config)};\n } else if (isBinning(bin) && !hasDiscreteDomain(scaleType)) {\n return {band: 1};\n }\n }\n\n if (isRectBasedMark(mark.type)) {\n if (scaleType) {\n if (hasDiscreteDomain(scaleType)) {\n return config[mark.type]?.discreteBandSize || {band: 1};\n } else {\n return config[mark.type]?.continuousBandSize;\n }\n }\n return config[mark.type]?.discreteBandSize;\n }\n\n return undefined;\n}\n\nexport function hasBandEnd(\n fieldDef: FieldDef,\n fieldDef2: SecondaryChannelDef,\n markDef: MarkDef,\n config: Config\n): boolean {\n if (isBinning(fieldDef.bin) || (fieldDef.timeUnit && isTypedFieldDef(fieldDef) && fieldDef.type === 'temporal')) {\n // Need to check bandPosition because non-rect marks (e.g., point) with timeUnit\n // doesn't have to use bandEnd if there is no bandPosition.\n return getBandPosition({fieldDef, fieldDef2, markDef, config}) !== undefined;\n }\n return false;\n}\n\n/**\n * Field definition of a mark property, which can contain a legend.\n */\nexport type MarkPropFieldDef = ScaleFieldDef &\n LegendMixins;\n\nexport type MarkPropDatumDef = LegendMixins & ScaleDatumDef;\n\nexport type MarkPropFieldOrDatumDef =\n | MarkPropFieldDef\n | MarkPropDatumDef;\n\nexport interface LegendMixins {\n /**\n * An object defining properties of the legend.\n * If `null`, the legend for the encoding channel will be removed.\n *\n * __Default value:__ If undefined, default [legend properties](https://vega.github.io/vega-lite/docs/legend.html) are applied.\n *\n * __See also:__ [`legend`](https://vega.github.io/vega-lite/docs/legend.html) documentation.\n */\n legend?: Legend | null;\n}\n\n// Detail\n\n// Order Path have no scale\n\nexport type OrderFieldDef = FieldDefWithoutScale & OrderOnlyDef;\n\nexport interface OrderOnlyDef {\n /**\n * The sort order. One of `\"ascending\"` (default) or `\"descending\"`.\n */\n sort?: SortOrder;\n}\n\nexport function isOrderOnlyDef(\n orderDef: OrderFieldDef | OrderFieldDef[] | OrderValueDef | OrderOnlyDef\n): orderDef is OrderOnlyDef {\n return orderDef && !!(orderDef as OrderOnlyDef).sort && !orderDef['field'];\n}\n\nexport type OrderValueDef = ConditionValueDefMixins & NumericValueDef;\n\nexport interface StringFieldDef extends FieldDefWithoutScale, FormatMixins {}\n\nexport type FieldDef = SecondaryFieldDef | TypedFieldDef;\nexport type ChannelDef = Encoding[keyof Encoding];\n\nexport function isConditionalDef | GuideEncodingConditionalValueDef | ExprRef | SignalRef>(\n channelDef: CD\n): channelDef is CD & {condition: Conditional} {\n return channelDef && 'condition' in channelDef;\n}\n\n/**\n * Return if a channelDef is a ConditionalValueDef with ConditionFieldDef\n */\nexport function hasConditionalFieldDef(\n channelDef: Partial>\n): channelDef is {condition: Conditional>} {\n const condition = channelDef?.['condition'];\n return !!condition && !isArray(condition) && isFieldDef(condition);\n}\n\nexport function hasConditionalFieldOrDatumDef(\n channelDef: ChannelDef\n): channelDef is {condition: Conditional>} {\n const condition = channelDef?.['condition'];\n return !!condition && !isArray(condition) && isFieldOrDatumDef(condition);\n}\n\nexport function hasConditionalValueDef(\n channelDef: ChannelDef\n): channelDef is ValueDef & {condition: Conditional> | Conditional>[]} {\n const condition = channelDef?.['condition'];\n return !!condition && (isArray(condition) || isValueDef(condition));\n}\n\nexport function isFieldDef(\n channelDef: Partial> | FieldDefBase | DatumDef\n): channelDef is FieldDefBase | TypedFieldDef | SecondaryFieldDef {\n // TODO: we can't use field in channelDef here as it's somehow failing runtime test\n return channelDef && (!!channelDef['field'] || channelDef['aggregate'] === 'count');\n}\n\nexport function channelDefType(channelDef: ChannelDef): Type | undefined {\n return channelDef?.['type'];\n}\n\nexport function isDatumDef(\n channelDef: Partial> | FieldDefBase | DatumDef\n): channelDef is DatumDef {\n return channelDef && 'datum' in channelDef;\n}\n\nexport function isContinuousFieldOrDatumDef(\n cd: ChannelDef\n): cd is TypedFieldDef | DatumDef {\n // TODO: make datum support DateTime object\n return (isTypedFieldDef(cd) && !isDiscrete(cd)) || isNumericDataDef(cd);\n}\n\nexport function isUnbinnedQuantitativeFieldOrDatumDef(cd: ChannelDef) {\n // TODO: make datum support DateTime object\n return (isTypedFieldDef(cd) && cd.type === 'quantitative' && !cd.bin) || isNumericDataDef(cd);\n}\n\nexport function isNumericDataDef(cd: ChannelDef): cd is DatumDef {\n return isDatumDef(cd) && isNumber(cd.datum);\n}\n\nexport function isFieldOrDatumDef(\n channelDef: Partial>\n): channelDef is FieldDef | DatumDef {\n return isFieldDef(channelDef) || isDatumDef(channelDef);\n}\n\nexport function isTypedFieldDef(channelDef: ChannelDef): channelDef is TypedFieldDef {\n return channelDef && ('field' in channelDef || channelDef['aggregate'] === 'count') && 'type' in channelDef;\n}\n\nexport function isValueDef(channelDef: Partial>): channelDef is ValueDef {\n return channelDef && 'value' in channelDef && 'value' in channelDef;\n}\n\nexport function isScaleFieldDef(channelDef: ChannelDef): channelDef is ScaleFieldDef {\n return channelDef && ('scale' in channelDef || 'sort' in channelDef);\n}\n\nexport function isPositionFieldOrDatumDef(\n channelDef: ChannelDef\n): channelDef is PositionFieldDef | PositionDatumDef {\n return channelDef && ('axis' in channelDef || 'stack' in channelDef || 'impute' in channelDef);\n}\n\nexport function isMarkPropFieldOrDatumDef(\n channelDef: ChannelDef\n): channelDef is MarkPropFieldDef | MarkPropDatumDef {\n return channelDef && 'legend' in channelDef;\n}\n\nexport function isStringFieldOrDatumDef(\n channelDef: ChannelDef\n): channelDef is StringFieldDef | StringDatumDef {\n return channelDef && ('format' in channelDef || 'formatType' in channelDef);\n}\n\nexport function toStringFieldDef(fieldDef: FieldDef): StringFieldDef {\n // omit properties that don't exist in string field defs\n return omit(fieldDef, ['legend', 'axis', 'header', 'scale'] as any[]);\n}\n\nexport interface FieldRefOption {\n /** Exclude bin, aggregate, timeUnit */\n nofn?: boolean;\n /** Wrap the field with datum, parent, or datum.datum (e.g., datum['...'] for Vega Expression */\n expr?: 'datum' | 'parent' | 'datum.datum';\n /** Prepend fn with custom function prefix */\n prefix?: string;\n /** Append suffix to the field ref for bin (default='start') */\n binSuffix?: 'end' | 'range' | 'mid';\n /** Append suffix to the field ref (general) */\n suffix?: string;\n /**\n * Use the field name for `as` in a transform.\n * We will not escape nested accesses because Vega transform outputs cannot be nested.\n */\n forAs?: boolean;\n}\n\nfunction isOpFieldDef(\n fieldDef: FieldDefBase | WindowFieldDef | AggregatedFieldDef\n): fieldDef is WindowFieldDef | AggregatedFieldDef {\n return 'op' in fieldDef;\n}\n\n/**\n * Get a Vega field reference from a Vega-Lite field def.\n */\nexport function vgField(\n fieldDef: FieldDefBase | WindowFieldDef | AggregatedFieldDef,\n opt: FieldRefOption = {}\n): string {\n let field = fieldDef.field;\n const prefix = opt.prefix;\n let suffix = opt.suffix;\n\n let argAccessor = ''; // for accessing argmin/argmax field at the end without getting escaped\n\n if (isCount(fieldDef)) {\n field = internalField('count');\n } else {\n let fn: string;\n\n if (!opt.nofn) {\n if (isOpFieldDef(fieldDef)) {\n fn = fieldDef.op;\n } else {\n const {bin, aggregate, timeUnit} = fieldDef;\n if (isBinning(bin)) {\n fn = binToString(bin);\n suffix = (opt.binSuffix ?? '') + (opt.suffix ?? '');\n } else if (aggregate) {\n if (isArgmaxDef(aggregate)) {\n argAccessor = `[\"${field}\"]`;\n field = `argmax_${aggregate.argmax}`;\n } else if (isArgminDef(aggregate)) {\n argAccessor = `[\"${field}\"]`;\n field = `argmin_${aggregate.argmin}`;\n } else {\n fn = String(aggregate);\n }\n } else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {\n fn = timeUnitToString(timeUnit);\n suffix = ((!['range', 'mid'].includes(opt.binSuffix) && opt.binSuffix) || '') + (opt.suffix ?? '');\n }\n }\n }\n\n if (fn) {\n field = field ? `${fn}_${field}` : fn;\n }\n }\n\n if (suffix) {\n field = `${field}_${suffix}`;\n }\n\n if (prefix) {\n field = `${prefix}_${field}`;\n }\n\n if (opt.forAs) {\n return removePathFromField(field);\n } else if (opt.expr) {\n // Expression to access flattened field. No need to escape dots.\n return flatAccessWithDatum(field, opt.expr) + argAccessor;\n } else {\n // We flattened all fields so paths should have become dot.\n return replacePathInField(field) + argAccessor;\n }\n}\n\nexport function isDiscrete(def: TypedFieldDef | DatumDef) {\n switch (def.type) {\n case 'nominal':\n case 'ordinal':\n case 'geojson':\n return true;\n case 'quantitative':\n return isFieldDef(def) && !!def.bin;\n case 'temporal':\n return false;\n }\n throw new Error(log.message.invalidFieldType(def.type));\n}\n\nexport function isDiscretizing(def: TypedFieldDef | DatumDef) {\n return isScaleFieldDef(def) && isContinuousToDiscrete(def.scale?.type);\n}\n\nexport function isCount(fieldDef: FieldDefBase) {\n return fieldDef.aggregate === 'count';\n}\n\nexport type FieldTitleFormatter = (fieldDef: FieldDefBase, config: Config) => string;\n\nexport function verbalTitleFormatter(fieldDef: FieldDefBase, config: Config) {\n const {field, bin, timeUnit, aggregate} = fieldDef;\n if (aggregate === 'count') {\n return config.countTitle;\n } else if (isBinning(bin)) {\n return `${field} (binned)`;\n } else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {\n const unit = normalizeTimeUnit(timeUnit)?.unit;\n if (unit) {\n return `${field} (${getTimeUnitParts(unit).join('-')})`;\n }\n } else if (aggregate) {\n if (isArgmaxDef(aggregate)) {\n return `${field} for max ${aggregate.argmax}`;\n } else if (isArgminDef(aggregate)) {\n return `${field} for min ${aggregate.argmin}`;\n } else {\n return `${titleCase(aggregate)} of ${field}`;\n }\n }\n return field;\n}\n\nexport function functionalTitleFormatter(fieldDef: FieldDefBase) {\n const {aggregate, bin, timeUnit, field} = fieldDef;\n if (isArgmaxDef(aggregate)) {\n return `${field} for argmax(${aggregate.argmax})`;\n } else if (isArgminDef(aggregate)) {\n return `${field} for argmin(${aggregate.argmin})`;\n }\n\n const timeUnitParams = timeUnit && !isBinnedTimeUnit(timeUnit) ? normalizeTimeUnit(timeUnit) : undefined;\n\n const fn = aggregate || timeUnitParams?.unit || (timeUnitParams?.maxbins && 'timeunit') || (isBinning(bin) && 'bin');\n if (fn) {\n return `${fn.toUpperCase()}(${field})`;\n } else {\n return field;\n }\n}\n\nexport const defaultTitleFormatter: FieldTitleFormatter = (fieldDef: FieldDefBase, config: Config) => {\n switch (config.fieldTitle) {\n case 'plain':\n return fieldDef.field;\n case 'functional':\n return functionalTitleFormatter(fieldDef);\n default:\n return verbalTitleFormatter(fieldDef, config);\n }\n};\n\nlet titleFormatter = defaultTitleFormatter;\n\nexport function setTitleFormatter(formatter: FieldTitleFormatter) {\n titleFormatter = formatter;\n}\n\nexport function resetTitleFormatter() {\n setTitleFormatter(defaultTitleFormatter);\n}\n\nexport function title(\n fieldOrDatumDef: TypedFieldDef | SecondaryFieldDef | DatumDef,\n config: Config,\n {allowDisabling, includeDefault = true}: {allowDisabling: boolean; includeDefault?: boolean}\n) {\n const guideTitle = getGuide(fieldOrDatumDef)?.title;\n\n if (!isFieldDef(fieldOrDatumDef)) {\n return guideTitle ?? fieldOrDatumDef.title;\n }\n const fieldDef = fieldOrDatumDef;\n\n const def = includeDefault ? defaultTitle(fieldDef, config) : undefined;\n\n if (allowDisabling) {\n return getFirstDefined(guideTitle, fieldDef.title, def);\n } else {\n return guideTitle ?? fieldDef.title ?? def;\n }\n}\n\nexport function getGuide(fieldDef: TypedFieldDef | SecondaryFieldDef | DatumDef): Guide {\n if (isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis) {\n return fieldDef.axis;\n } else if (isMarkPropFieldOrDatumDef(fieldDef) && fieldDef.legend) {\n return fieldDef.legend;\n } else if (isFacetFieldDef(fieldDef) && fieldDef.header) {\n return fieldDef.header;\n }\n return undefined;\n}\n\nexport function defaultTitle(fieldDef: FieldDefBase, config: Config) {\n return titleFormatter(fieldDef, config);\n}\n\nexport function getFormatMixins(fieldDef: TypedFieldDef | DatumDef) {\n if (isStringFieldOrDatumDef(fieldDef)) {\n const {format, formatType} = fieldDef;\n return {format, formatType};\n } else {\n const guide = getGuide(fieldDef) ?? {};\n const {format, formatType} = guide;\n return {format, formatType};\n }\n}\n\nexport function defaultType>(fieldDef: T, channel: ExtendedChannel): Type {\n switch (channel) {\n case 'latitude':\n case 'longitude':\n return 'quantitative';\n\n case 'row':\n case 'column':\n case 'facet':\n case 'shape':\n case 'strokeDash':\n return 'nominal';\n\n case 'order':\n return 'ordinal';\n }\n\n if (isSortableFieldDef(fieldDef) && isArray(fieldDef.sort)) {\n return 'ordinal';\n }\n\n const {aggregate, bin, timeUnit} = fieldDef;\n if (timeUnit) {\n return 'temporal';\n }\n\n if (bin || (aggregate && !isArgmaxDef(aggregate) && !isArgminDef(aggregate))) {\n return 'quantitative';\n }\n\n if (isScaleFieldDef(fieldDef) && fieldDef.scale?.type) {\n switch (SCALE_CATEGORY_INDEX[fieldDef.scale.type]) {\n case 'numeric':\n case 'discretizing':\n return 'quantitative';\n case 'time':\n return 'temporal';\n }\n }\n\n return 'nominal';\n}\n\n/**\n * Returns the fieldDef -- either from the outer channelDef or from the condition of channelDef.\n * @param channelDef\n */\n\nexport function getFieldDef(channelDef: ChannelDef): FieldDef {\n if (isFieldDef(channelDef)) {\n return channelDef;\n } else if (hasConditionalFieldDef(channelDef)) {\n return channelDef.condition;\n }\n return undefined;\n}\n\nexport function getFieldOrDatumDef = ChannelDef>(\n channelDef: CD\n): FieldDef | DatumDef {\n if (isFieldOrDatumDef(channelDef)) {\n return channelDef;\n } else if (hasConditionalFieldOrDatumDef(channelDef)) {\n return channelDef.condition;\n }\n return undefined;\n}\n\n/**\n * Convert type to full, lowercase type, or augment the fieldDef with a default type if missing.\n */\nexport function initChannelDef(\n channelDef: ChannelDef,\n channel: ExtendedChannel,\n config: Config,\n opt: {compositeMark?: boolean} = {}\n): ChannelDef {\n if (isString(channelDef) || isNumber(channelDef) || isBoolean(channelDef)) {\n const primitiveType = isString(channelDef) ? 'string' : isNumber(channelDef) ? 'number' : 'boolean';\n log.warn(log.message.primitiveChannelDef(channel, primitiveType, channelDef));\n return {value: channelDef} as ValueDef;\n }\n\n // If a fieldDef contains a field, we need type.\n if (isFieldOrDatumDef(channelDef)) {\n return initFieldOrDatumDef(channelDef, channel, config, opt);\n } else if (hasConditionalFieldOrDatumDef(channelDef)) {\n return {\n ...channelDef,\n // Need to cast as normalizeFieldDef normally return FieldDef, but here we know that it is definitely Condition\n condition: initFieldOrDatumDef(channelDef.condition, channel, config, opt) as Conditional>\n };\n }\n return channelDef;\n}\n\nexport function initFieldOrDatumDef(\n fd: FieldDef | DatumDef,\n channel: ExtendedChannel,\n config: Config,\n opt: {compositeMark?: boolean}\n): FieldDef | DatumDef {\n if (isStringFieldOrDatumDef(fd)) {\n const {format, formatType, ...rest} = fd;\n if (isCustomFormatType(formatType) && !config.customFormatTypes) {\n log.warn(log.message.customFormatTypeNotAllowed(channel));\n return initFieldOrDatumDef(rest, channel, config, opt);\n }\n } else {\n const guideType = isPositionFieldOrDatumDef(fd)\n ? 'axis'\n : isMarkPropFieldOrDatumDef(fd)\n ? 'legend'\n : isFacetFieldDef(fd)\n ? 'header'\n : null;\n if (guideType && fd[guideType]) {\n const {format, formatType, ...newGuide} = fd[guideType];\n if (isCustomFormatType(formatType) && !config.customFormatTypes) {\n log.warn(log.message.customFormatTypeNotAllowed(channel));\n return initFieldOrDatumDef({...fd, [guideType]: newGuide}, channel, config, opt);\n }\n }\n }\n\n if (isFieldDef(fd)) {\n return initFieldDef(fd, channel, opt);\n }\n return initDatumDef(fd);\n}\n\nfunction initDatumDef(datumDef: DatumDef): DatumDef {\n let type = datumDef['type'];\n if (type) {\n return datumDef;\n }\n const {datum} = datumDef;\n type = isNumber(datum) ? 'quantitative' : isString(datum) ? 'nominal' : isDateTime(datum) ? 'temporal' : undefined;\n\n return {...datumDef, type};\n}\n\nexport function initFieldDef(\n fd: FieldDef,\n channel: ExtendedChannel,\n {compositeMark = false}: {compositeMark?: boolean} = {}\n) {\n const {aggregate, timeUnit, bin, field} = fd;\n const fieldDef = {...fd};\n\n // Drop invalid aggregate\n if (!compositeMark && aggregate && !isAggregateOp(aggregate) && !isArgmaxDef(aggregate) && !isArgminDef(aggregate)) {\n log.warn(log.message.invalidAggregate(aggregate));\n delete fieldDef.aggregate;\n }\n\n // Normalize Time Unit\n if (timeUnit) {\n fieldDef.timeUnit = normalizeTimeUnit(timeUnit);\n }\n\n if (field) {\n fieldDef.field = `${field}`;\n }\n\n // Normalize bin\n if (isBinning(bin)) {\n fieldDef.bin = normalizeBin(bin, channel);\n }\n\n if (isBinned(bin) && !isXorY(channel)) {\n log.warn(log.message.channelShouldNotBeUsedForBinned(channel));\n }\n\n // Normalize Type\n if (isTypedFieldDef(fieldDef)) {\n const {type} = fieldDef;\n const fullType = getFullName(type);\n if (type !== fullType) {\n // convert short type to full type\n fieldDef.type = fullType;\n }\n if (type !== 'quantitative') {\n if (isCountingAggregateOp(aggregate)) {\n log.warn(log.message.invalidFieldTypeForCountAggregate(type, aggregate));\n fieldDef.type = 'quantitative';\n }\n }\n } else if (!isSecondaryRangeChannel(channel)) {\n // If type is empty / invalid, then augment with default type\n const newType = defaultType(fieldDef as TypedFieldDef, channel);\n fieldDef['type'] = newType;\n }\n\n if (isTypedFieldDef(fieldDef)) {\n const {compatible, warning} = channelCompatibility(fieldDef, channel) || {};\n if (compatible === false) {\n log.warn(warning);\n }\n }\n\n if (isSortableFieldDef(fieldDef) && isString(fieldDef.sort)) {\n const {sort} = fieldDef;\n if (isSortByChannel(sort)) {\n return {\n ...fieldDef,\n sort: {encoding: sort}\n };\n }\n const sub = sort.substr(1);\n if (sort.charAt(0) === '-' && isSortByChannel(sub)) {\n return {\n ...fieldDef,\n sort: {encoding: sub, order: 'descending'}\n };\n }\n }\n\n if (isFacetFieldDef(fieldDef)) {\n const {header} = fieldDef;\n if (header) {\n const {orient, ...rest} = header;\n if (orient) {\n return {\n ...fieldDef,\n header: {\n ...rest,\n labelOrient: header.labelOrient || orient,\n titleOrient: header.titleOrient || orient\n }\n };\n }\n }\n }\n\n return fieldDef;\n}\n\nexport function normalizeBin(bin: BinParams | boolean | 'binned', channel?: ExtendedChannel) {\n if (isBoolean(bin)) {\n return {maxbins: autoMaxBins(channel)};\n } else if (bin === 'binned') {\n return {\n binned: true\n };\n } else if (!bin.maxbins && !bin.step) {\n return {...bin, maxbins: autoMaxBins(channel)};\n } else {\n return bin;\n }\n}\n\nconst COMPATIBLE = {compatible: true};\nexport function channelCompatibility(\n fieldDef: TypedFieldDef,\n channel: ExtendedChannel\n): {compatible: boolean; warning?: string} {\n const type = fieldDef.type;\n\n if (type === 'geojson' && channel !== 'shape') {\n return {\n compatible: false,\n warning: `Channel ${channel} should not be used with a geojson data.`\n };\n }\n\n switch (channel) {\n case ROW:\n case COLUMN:\n case FACET:\n if (!isDiscrete(fieldDef)) {\n return {\n compatible: false,\n warning: log.message.channelShouldBeDiscrete(channel)\n };\n }\n return COMPATIBLE;\n\n case X:\n case Y:\n case XOFFSET:\n case YOFFSET:\n case COLOR:\n case FILL:\n case STROKE:\n case TEXT:\n case DETAIL:\n case KEY:\n case TOOLTIP:\n case HREF:\n case URL:\n case ANGLE:\n case THETA:\n case RADIUS:\n case DESCRIPTION:\n return COMPATIBLE;\n\n case LONGITUDE:\n case LONGITUDE2:\n case LATITUDE:\n case LATITUDE2:\n if (type !== QUANTITATIVE) {\n return {\n compatible: false,\n warning: `Channel ${channel} should be used with a quantitative field only, not ${fieldDef.type} field.`\n };\n }\n return COMPATIBLE;\n\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n case STROKEWIDTH:\n case SIZE:\n case THETA2:\n case RADIUS2:\n case X2:\n case Y2:\n if (type === 'nominal' && !fieldDef['sort']) {\n return {\n compatible: false,\n warning: `Channel ${channel} should not be used with an unsorted discrete field.`\n };\n }\n return COMPATIBLE;\n\n case SHAPE:\n case STROKEDASH:\n if (!isDiscrete(fieldDef) && !isDiscretizing(fieldDef)) {\n return {\n compatible: false,\n warning: log.message.channelShouldBeDiscreteOrDiscretizing(channel)\n };\n }\n return COMPATIBLE;\n\n case ORDER:\n if (fieldDef.type === 'nominal' && !('sort' in fieldDef)) {\n return {\n compatible: false,\n warning: `Channel order is inappropriate for nominal field, which has no inherent order.`\n };\n }\n return COMPATIBLE;\n }\n}\n\n/**\n * Check if the field def uses a time format or does not use any format but is temporal\n * (this does not cover field defs that are temporal but use a number format).\n */\nexport function isFieldOrDatumDefForTimeFormat(fieldOrDatumDef: FieldDef | DatumDef): boolean {\n const {formatType} = getFormatMixins(fieldOrDatumDef);\n return formatType === 'time' || (!formatType && isTimeFieldDef(fieldOrDatumDef));\n}\n\n/**\n * Check if field def has type `temporal`. If you want to also cover field defs that use a time format, use `isTimeFormatFieldDef`.\n */\nexport function isTimeFieldDef(def: FieldDef | DatumDef): boolean {\n return def && (def['type'] === 'temporal' || (isFieldDef(def) && !!def.timeUnit));\n}\n\n/**\n * Getting a value associated with a fielddef.\n * Convert the value to Vega expression if applicable (for datetime object, or string if the field def is temporal or has timeUnit)\n */\nexport function valueExpr(\n v: number | string | boolean | DateTime | ExprRef | SignalRef | number[],\n {\n timeUnit,\n type,\n wrapTime,\n undefinedIfExprNotRequired\n }: {\n timeUnit: TimeUnit | TimeUnitParams;\n type?: Type;\n wrapTime?: boolean;\n undefinedIfExprNotRequired?: boolean;\n }\n): string {\n const unit = timeUnit && normalizeTimeUnit(timeUnit)?.unit;\n let isTime = unit || type === 'temporal';\n\n let expr;\n if (isExprRef(v)) {\n expr = v.expr;\n } else if (isSignalRef(v)) {\n expr = v.signal;\n } else if (isDateTime(v)) {\n isTime = true;\n expr = dateTimeToExpr(v);\n } else if (isString(v) || isNumber(v)) {\n if (isTime) {\n expr = `datetime(${stringify(v)})`;\n\n if (isLocalSingleTimeUnit(unit)) {\n // for single timeUnit, we will use dateTimeToExpr to convert number/string to match the timeUnit\n if ((isNumber(v) && v < 10000) || (isString(v) && isNaN(Date.parse(v)))) {\n expr = dateTimeToExpr({[unit]: v});\n }\n }\n }\n }\n if (expr) {\n return wrapTime && isTime ? `time(${expr})` : expr;\n }\n // number or boolean or normal string\n return undefinedIfExprNotRequired ? undefined : stringify(v);\n}\n\n/**\n * Standardize value array -- convert each value to Vega expression if applicable\n */\nexport function valueArray(\n fieldOrDatumDef: TypedFieldDef | DatumDef,\n values: (number | string | boolean | DateTime)[]\n) {\n const {type} = fieldOrDatumDef;\n return values.map(v => {\n const timeUnit =\n isFieldDef(fieldOrDatumDef) && !isBinnedTimeUnit(fieldOrDatumDef.timeUnit) ? fieldOrDatumDef.timeUnit : undefined;\n const expr = valueExpr(v, {\n timeUnit,\n type,\n undefinedIfExprNotRequired: true\n });\n // return signal for the expression if we need an expression\n if (expr !== undefined) {\n return {signal: expr};\n }\n // otherwise just return the original value\n return v;\n });\n}\n\n/**\n * Checks whether a fieldDef for a particular channel requires a computed bin range.\n */\nexport function binRequiresRange(fieldDef: FieldDef, channel: Channel): boolean {\n if (!isBinning(fieldDef.bin)) {\n console.warn('Only call this method for binned field defs.');\n return false;\n }\n\n // We need the range only when the user explicitly forces a binned field to be use discrete scale. In this case, bin range is used in axis and legend labels.\n // We could check whether the axis or legend exists (not disabled) but that seems overkill.\n return isScaleChannel(channel) && ['ordinal', 'nominal'].includes((fieldDef as ScaleFieldDef).type);\n}\n","import {\n Align,\n Axis as VgAxis,\n AxisEncode,\n AxisOrient,\n BaseAxis,\n Color,\n FontStyle,\n FontWeight,\n LabelOverlap,\n SignalRef,\n TextBaseline,\n TimeInterval,\n TimeIntervalStep\n} from 'vega';\nimport {ConditionalPredicate, Value, ValueDef} from './channeldef';\nimport {DateTime} from './datetime';\nimport {ExprRef} from './expr';\nimport {Guide, GuideEncodingEntry, TitleMixins, VlOnlyGuideConfig} from './guide';\nimport {Flag, keys} from './util';\nimport {MapExcludeValueRefAndReplaceSignalWith, VgEncodeChannel} from './vega.schema';\n\nexport type BaseAxisNoValueRefs = AxisOverrideMixins &\n VLOnlyAxisMixins &\n Omit, 'labelOverlap'>;\n\ninterface AxisOverrideMixins {\n // Position and tickMinStep are not config in Vega, but are in Vega-Lite. So we just copy them here.\n\n /**\n * The anchor position of the axis in pixels. For x-axes with top or bottom orientation, this sets the axis group x coordinate. For y-axes with left or right orientation, this sets the axis group y coordinate.\n *\n * __Default value__: `0`\n */\n position?: number | ES;\n\n /**\n * The minimum desired step between axis ticks, in terms of scale domain values. For example, a value of `1` indicates that ticks should not be less than 1 unit apart. If `tickMinStep` is specified, the `tickCount` value will be adjusted, if necessary, to enforce the minimum step value.\n */\n tickMinStep?: number | ES;\n\n // ---------- Properties that do not support signal / expression ----------\n /**\n * A boolean flag indicating if the domain (the axis baseline) should be included as part of the axis.\n *\n * __Default value:__ `true`\n */\n domain?: boolean;\n\n /**\n * A boolean flag indicating if grid lines should be included as part of the axis\n *\n * __Default value:__ `true` for [continuous scales](https://vega.github.io/vega-lite/docs/scale.html#continuous) that are not binned; otherwise, `false`.\n */\n grid?: boolean;\n\n /**\n * A boolean flag indicating if labels should be included as part of the axis.\n *\n * __Default value:__ `true`.\n */\n labels?: boolean;\n\n /**\n * Boolean flag indicating if an extra axis tick should be added for the initial position of the axis. This flag is useful for styling axes for `band` scales such that ticks are placed on band boundaries rather in the middle of a band. Use in conjunction with `\"bandPosition\": 1` and an axis `\"padding\"` value of `0`.\n */\n tickExtra?: boolean;\n\n /**\n * Boolean flag indicating if pixel position values should be rounded to the nearest integer.\n *\n * __Default value:__ `true`\n */\n tickRound?: boolean;\n\n /**\n * Boolean value that determines whether the axis should include ticks.\n *\n * __Default value:__ `true`\n */\n ticks?: boolean;\n\n // Override comments to be Vega-Lite specific\n\n /**\n * Indicates if the first and last axis labels should be aligned flush with the scale range. Flush alignment for a horizontal axis will left-align the first label and right-align the last label. For vertical axes, bottom and top text baselines are applied instead. If this property is a number, it also indicates the number of pixels by which to offset the first and last labels; for example, a value of 2 will flush-align the first and last labels and also push them 2 pixels outward from the center of the axis. The additional adjustment can sometimes help the labels better visually group with corresponding axis ticks.\n *\n * __Default value:__ `true` for axis of a continuous x-scale. Otherwise, `false`.\n */\n labelFlush?: boolean | number;\n\n /**\n * The strategy to use for resolving overlap of axis labels. If `false` (the default), no overlap reduction is attempted. If set to `true` or `\"parity\"`, a strategy of removing every other label is used (this works well for standard linear axes). If set to `\"greedy\"`, a linear scan of the labels is performed, removing any labels that overlaps with the last visible label (this often works better for log-scaled axes).\n *\n * __Default value:__ `true` for non-nominal fields with non-log scales; `\"greedy\"` for log scales; otherwise `false`.\n */\n labelOverlap?: LabelOverlap | ES;\n\n /**\n * The offset, in pixels, by which to displace the axis from the edge of the enclosing group or data rectangle.\n *\n * __Default value:__ derived from the [axis config](https://vega.github.io/vega-lite/docs/config.html#facet-scale-config)'s `offset` (`0` by default)\n */\n offset?: number | ES;\n\n /**\n * The orientation of the axis. One of `\"top\"`, `\"bottom\"`, `\"left\"` or `\"right\"`. The orientation can be used to further specialize the axis type (e.g., a y-axis oriented towards the right edge of the chart).\n *\n * __Default value:__ `\"bottom\"` for x-axes and `\"left\"` for y-axes.\n */\n orient?: AxisOrient | ES;\n\n /**\n * A desired number of ticks, for axes visualizing quantitative scales. The resulting number may be different so that values are \"nice\" (multiples of 2, 5, 10) and lie within the underlying scale's range.\n *\n * For scales of type `\"time\"` or `\"utc\"`, the tick count can instead be a time interval specifier. Legal string values are `\"millisecond\"`, `\"second\"`, `\"minute\"`, `\"hour\"`, `\"day\"`, `\"week\"`, `\"month\"`, and `\"year\"`. Alternatively, an object-valued interval specifier of the form `{\"interval\": \"month\", \"step\": 3}` includes a desired number of interval steps. Here, ticks are generated for each quarter (Jan, Apr, Jul, Oct) boundary.\n *\n * __Default value__: Determine using a formula `ceil(width/40)` for x and `ceil(height/40)` for y.\n *\n * @minimum 0\n */\n tickCount?: number | TimeInterval | TimeIntervalStep | ES;\n\n /**\n * Explicitly set the visible axis tick values.\n */\n values?: number[] | string[] | boolean[] | DateTime[] | ES; // Vega already supports Signal -- we have to re-declare here since VL supports special Date Time object that's not valid in Vega.\n\n /**\n * A non-negative integer indicating the z-index of the axis.\n * If zindex is 0, axes should be drawn behind all chart elements.\n * To put them in front, set `zindex` to `1` or more.\n *\n * __Default value:__ `0` (behind the marks).\n *\n * @TJS-type integer\n * @minimum 0\n */\n zindex?: number;\n}\n\ninterface VLOnlyAxisMixins {\n /**\n * [Vega expression](https://vega.github.io/vega/docs/expressions/) for customizing labels.\n *\n * __Note:__ The label text and value can be assessed via the `label` and `value` properties of the axis's backing `datum` object.\n */\n labelExpr?: string;\n\n /**\n * A string or array of strings indicating the name of custom styles to apply to the axis. A style is a named collection of axis property defined within the [style configuration](https://vega.github.io/vega-lite/docs/mark.html#style-config). If style is an array, later styles will override earlier styles.\n *\n * __Default value:__ (none)\n * __Note:__ Any specified style will augment the default style. For example, an x-axis mark with `\"style\": \"foo\"` will use `config.axisX` and `config.style.foo` (the specified style `\"foo\"` has higher precedence).\n */\n style?: string | string[];\n}\n\nexport type ConditionalAxisProp =\n | 'labelAlign'\n | 'labelBaseline'\n | 'labelColor'\n | 'labelFont'\n | 'labelFontSize'\n | 'labelFontStyle'\n | 'labelFontWeight'\n | 'labelOpacity'\n | 'labelOffset'\n | 'labelPadding'\n | 'gridColor'\n | 'gridDash'\n | 'gridDashOffset'\n | 'gridOpacity'\n | 'gridWidth'\n | 'tickColor'\n | 'tickDash'\n | 'tickDashOffset'\n | 'tickOpacity'\n | 'tickSize'\n | 'tickWidth';\n\nexport const CONDITIONAL_AXIS_PROP_INDEX: Record<\n ConditionalAxisProp,\n {\n part: keyof AxisEncode;\n vgProp: VgEncodeChannel;\n } | null // null if we need to convert condition to signal\n> = {\n labelAlign: {\n part: 'labels',\n vgProp: 'align'\n },\n labelBaseline: {\n part: 'labels',\n vgProp: 'baseline'\n },\n labelColor: {\n part: 'labels',\n vgProp: 'fill'\n },\n labelFont: {\n part: 'labels',\n vgProp: 'font'\n },\n labelFontSize: {\n part: 'labels',\n vgProp: 'fontSize'\n },\n labelFontStyle: {\n part: 'labels',\n vgProp: 'fontStyle'\n },\n labelFontWeight: {\n part: 'labels',\n vgProp: 'fontWeight'\n },\n labelOpacity: {\n part: 'labels',\n vgProp: 'opacity'\n },\n labelOffset: null,\n labelPadding: null, // There is no fixed vgProp for tickSize, need to use signal.\n gridColor: {\n part: 'grid',\n vgProp: 'stroke'\n },\n gridDash: {\n part: 'grid',\n vgProp: 'strokeDash'\n },\n gridDashOffset: {\n part: 'grid',\n vgProp: 'strokeDashOffset'\n },\n gridOpacity: {\n part: 'grid',\n vgProp: 'opacity'\n },\n gridWidth: {\n part: 'grid',\n vgProp: 'strokeWidth'\n },\n tickColor: {\n part: 'ticks',\n vgProp: 'stroke'\n },\n tickDash: {\n part: 'ticks',\n vgProp: 'strokeDash'\n },\n tickDashOffset: {\n part: 'ticks',\n vgProp: 'strokeDashOffset'\n },\n tickOpacity: {\n part: 'ticks',\n vgProp: 'opacity'\n },\n tickSize: null, // There is no fixed vgProp for tickSize, need to use signal.\n tickWidth: {\n part: 'ticks',\n vgProp: 'strokeWidth'\n }\n};\n\nexport type ConditionalAxisProperty = (ValueDef | ES) & {\n condition: ConditionalPredicate | ES> | ConditionalPredicate | ES>[];\n};\n\nexport function isConditionalAxisValue(\n v: any\n): v is ConditionalAxisProperty {\n return v?.condition;\n}\n\nexport type ConditionalAxisNumber = ConditionalAxisProperty<\n number | null,\n ES\n>;\nexport type ConditionalAxisLabelAlign = ConditionalAxisProperty<\n Align | null,\n ES\n>;\nexport type ConditionalAxisLabelBaseline =\n ConditionalAxisProperty;\nexport type ConditionalAxisColor = ConditionalAxisProperty<\n Color | null,\n ES\n>;\nexport type ConditionalAxisString = ConditionalAxisProperty<\n string | null,\n ES\n>;\n\nexport type ConditionalAxisLabelFontStyle =\n ConditionalAxisProperty;\nexport type ConditionalAxisLabelFontWeight =\n ConditionalAxisProperty;\n\nexport type ConditionalAxisNumberArray = ConditionalAxisProperty<\n number[] | null,\n ES\n>;\n\n// Vega axis config is the same as Vega axis base. If this is not the case, add specific type.\nexport type AxisConfigBaseWithConditionalAndSignal = Omit<\n BaseAxisNoValueRefs,\n ConditionalAxisProp | 'title'\n> &\n AxisPropsWithCondition;\n\nexport interface AxisPropsWithCondition {\n labelAlign?: BaseAxisNoValueRefs['labelAlign'] | ConditionalAxisLabelAlign;\n labelBaseline?: BaseAxisNoValueRefs['labelBaseline'] | ConditionalAxisLabelBaseline;\n labelColor?: BaseAxisNoValueRefs['labelColor'] | ConditionalAxisColor;\n labelFont?: BaseAxisNoValueRefs['labelFont'] | ConditionalAxisString;\n labelFontSize?: BaseAxisNoValueRefs['labelFontSize'] | ConditionalAxisNumber;\n labelFontStyle?: BaseAxisNoValueRefs['labelFontStyle'] | ConditionalAxisLabelFontStyle;\n labelFontWeight?: BaseAxisNoValueRefs['labelFontWeight'] | ConditionalAxisLabelFontWeight;\n labelLineHeight?: BaseAxisNoValueRefs['labelLineHeight'] | ConditionalAxisNumber;\n labelOpacity?: BaseAxisNoValueRefs['labelOpacity'] | ConditionalAxisNumber;\n labelOffset?: BaseAxisNoValueRefs['labelOffset'] | ConditionalAxisNumber;\n labelPadding?: BaseAxisNoValueRefs['labelPadding'] | ConditionalAxisNumber;\n gridColor?: BaseAxisNoValueRefs['gridColor'] | ConditionalAxisColor;\n gridDash?: BaseAxisNoValueRefs['gridDash'] | ConditionalAxisNumberArray;\n gridDashOffset?: BaseAxisNoValueRefs['gridDashOffset'] | ConditionalAxisNumber;\n gridOpacity?: BaseAxisNoValueRefs['gridOpacity'] | ConditionalAxisNumber;\n gridWidth?: BaseAxisNoValueRefs['gridWidth'] | ConditionalAxisNumber;\n tickColor?: BaseAxisNoValueRefs['tickColor'] | ConditionalAxisColor;\n tickDash?: BaseAxisNoValueRefs['tickDash'] | ConditionalAxisNumberArray;\n tickDashOffset?: BaseAxisNoValueRefs['tickDashOffset'] | ConditionalAxisNumber;\n tickOpacity?: BaseAxisNoValueRefs['tickOpacity'] | ConditionalAxisNumber;\n tickSize?: BaseAxisNoValueRefs['tickSize'] | ConditionalAxisNumber;\n tickWidth?: BaseAxisNoValueRefs['tickWidth'] | ConditionalAxisNumber;\n title?: TitleMixins['title'];\n}\n\nexport type AxisConfig = Guide &\n VlOnlyGuideConfig &\n AxisConfigBaseWithConditionalAndSignal & {\n /**\n * Disable axis by default.\n */\n disable?: boolean;\n };\n\nexport interface Axis\n extends AxisConfigBaseWithConditionalAndSignal,\n Guide {\n /**\n * Mark definitions for custom axis encoding.\n *\n * @hidden\n */\n encoding?: AxisEncoding;\n}\n\nexport type AxisInternal = Axis;\n\nexport type AxisPart = keyof AxisEncoding;\nexport const AXIS_PARTS: AxisPart[] = ['domain', 'grid', 'labels', 'ticks', 'title'];\n\n/**\n * A dictionary listing whether a certain axis property is applicable for only main axes or only grid axes.\n */\nexport const AXIS_PROPERTY_TYPE: Record = {\n grid: 'grid',\n gridCap: 'grid',\n gridColor: 'grid',\n gridDash: 'grid',\n gridDashOffset: 'grid',\n gridOpacity: 'grid',\n gridScale: 'grid',\n gridWidth: 'grid',\n\n orient: 'main',\n\n bandPosition: 'both', // Need to be applied to grid axis too, so the grid will align with ticks.\n\n aria: 'main',\n description: 'main',\n domain: 'main',\n domainCap: 'main',\n domainColor: 'main',\n domainDash: 'main',\n domainDashOffset: 'main',\n domainOpacity: 'main',\n domainWidth: 'main',\n format: 'main',\n formatType: 'main',\n labelAlign: 'main',\n labelAngle: 'main',\n labelBaseline: 'main',\n labelBound: 'main',\n labelColor: 'main',\n labelFlush: 'main',\n labelFlushOffset: 'main',\n labelFont: 'main',\n labelFontSize: 'main',\n labelFontStyle: 'main',\n labelFontWeight: 'main',\n labelLimit: 'main',\n labelLineHeight: 'main',\n labelOffset: 'main',\n labelOpacity: 'main',\n labelOverlap: 'main',\n labelPadding: 'main',\n labels: 'main',\n labelSeparation: 'main',\n maxExtent: 'main',\n minExtent: 'main',\n offset: 'both',\n position: 'main',\n tickCap: 'main',\n tickColor: 'main',\n tickDash: 'main',\n tickDashOffset: 'main',\n tickMinStep: 'both',\n tickOffset: 'both', // Need to be applied to grid axis too, so the grid will align with ticks.\n tickOpacity: 'main',\n tickRound: 'both', // Apply rounding to grid and ticks so they are aligned.\n ticks: 'main',\n tickSize: 'main',\n tickWidth: 'both',\n title: 'main',\n titleAlign: 'main',\n titleAnchor: 'main',\n titleAngle: 'main',\n titleBaseline: 'main',\n titleColor: 'main',\n titleFont: 'main',\n titleFontSize: 'main',\n titleFontStyle: 'main',\n titleFontWeight: 'main',\n titleLimit: 'main',\n titleLineHeight: 'main',\n titleOpacity: 'main',\n titlePadding: 'main',\n titleX: 'main',\n titleY: 'main',\n\n encode: 'both', // we hide this in Vega-Lite\n scale: 'both',\n tickBand: 'both',\n tickCount: 'both',\n tickExtra: 'both',\n translate: 'both',\n values: 'both',\n zindex: 'both' // this is actually set afterward, so it doesn't matter\n};\n\nexport interface AxisEncoding {\n /**\n * Custom encoding for the axis container.\n */\n axis?: GuideEncodingEntry;\n\n /**\n * Custom encoding for the axis domain rule mark.\n */\n domain?: GuideEncodingEntry;\n\n /**\n * Custom encoding for axis gridline rule marks.\n */\n grid?: GuideEncodingEntry;\n\n /**\n * Custom encoding for axis label text marks.\n */\n labels?: GuideEncodingEntry;\n\n /**\n * Custom encoding for axis tick rule marks.\n */\n ticks?: GuideEncodingEntry;\n\n /**\n * Custom encoding for the axis title text mark.\n */\n title?: GuideEncodingEntry;\n}\n\nexport const COMMON_AXIS_PROPERTIES_INDEX: Flag)> = {\n orient: 1, // other things can depend on orient\n\n aria: 1,\n bandPosition: 1,\n description: 1,\n domain: 1,\n domainCap: 1,\n domainColor: 1,\n domainDash: 1,\n domainDashOffset: 1,\n domainOpacity: 1,\n domainWidth: 1,\n format: 1,\n formatType: 1,\n grid: 1,\n gridCap: 1,\n gridColor: 1,\n gridDash: 1,\n gridDashOffset: 1,\n gridOpacity: 1,\n gridWidth: 1,\n labelAlign: 1,\n labelAngle: 1,\n labelBaseline: 1,\n labelBound: 1,\n labelColor: 1,\n labelFlush: 1,\n labelFlushOffset: 1,\n labelFont: 1,\n labelFontSize: 1,\n labelFontStyle: 1,\n labelFontWeight: 1,\n labelLimit: 1,\n labelLineHeight: 1,\n labelOffset: 1,\n labelOpacity: 1,\n labelOverlap: 1,\n labelPadding: 1,\n labels: 1,\n labelSeparation: 1,\n maxExtent: 1,\n minExtent: 1,\n offset: 1,\n position: 1,\n tickBand: 1,\n tickCap: 1,\n tickColor: 1,\n tickCount: 1,\n tickDash: 1,\n tickDashOffset: 1,\n tickExtra: 1,\n tickMinStep: 1,\n tickOffset: 1,\n tickOpacity: 1,\n tickRound: 1,\n ticks: 1,\n tickSize: 1,\n tickWidth: 1,\n title: 1,\n titleAlign: 1,\n titleAnchor: 1,\n titleAngle: 1,\n titleBaseline: 1,\n titleColor: 1,\n titleFont: 1,\n titleFontSize: 1,\n titleFontStyle: 1,\n titleFontWeight: 1,\n titleLimit: 1,\n titleLineHeight: 1,\n titleOpacity: 1,\n titlePadding: 1,\n titleX: 1,\n titleY: 1,\n translate: 1,\n values: 1,\n zindex: 1\n};\n\nconst AXIS_PROPERTIES_INDEX: Flag> = {\n ...COMMON_AXIS_PROPERTIES_INDEX,\n style: 1,\n labelExpr: 1,\n encoding: 1\n};\n\nexport function isAxisProperty(prop: string): prop is keyof Axis {\n return !!AXIS_PROPERTIES_INDEX[prop];\n}\n\n// Export for dependent projects\nexport const AXIS_PROPERTIES = keys(AXIS_PROPERTIES_INDEX);\n\nexport interface AxisConfigMixins {\n /**\n * Axis configuration, which determines default properties for all `x` and `y` [axes](https://vega.github.io/vega-lite/docs/axis.html). For a full list of axis configuration options, please see the [corresponding section of the axis documentation](https://vega.github.io/vega-lite/docs/axis.html#config).\n */\n axis?: AxisConfig;\n\n /**\n * X-axis specific config.\n */\n axisX?: AxisConfig;\n\n /**\n * Y-axis specific config.\n */\n axisY?: AxisConfig;\n\n /**\n * Config for y-axis along the left edge of the chart.\n */\n axisLeft?: AxisConfig;\n\n /**\n * Config for y-axis along the right edge of the chart.\n */\n axisRight?: AxisConfig;\n\n /**\n * Config for x-axis along the top edge of the chart.\n */\n axisTop?: AxisConfig;\n\n /**\n * Config for x-axis along the bottom edge of the chart.\n */\n axisBottom?: AxisConfig;\n\n /**\n * Config for axes with \"band\" scales.\n */\n axisBand?: AxisConfig;\n\n /**\n * Config for axes with \"point\" scales.\n */\n axisPoint?: AxisConfig;\n\n /**\n * Config for axes with \"point\" or \"band\" scales.\n */\n axisDiscrete?: AxisConfig;\n\n /**\n * Config for quantitative axes.\n */\n axisQuantitative?: AxisConfig;\n\n /**\n * Config for temporal axes.\n */\n axisTemporal?: AxisConfig;\n\n /**\n * Config for x-axes with \"band\" scales.\n */\n axisXBand?: AxisConfig;\n\n /**\n * Config for x-axes with \"point\" scales.\n */\n axisXPoint?: AxisConfig;\n\n /**\n * Config for x-axes with \"point\" or \"band\" scales.\n */\n axisXDiscrete?: AxisConfig;\n\n /**\n * Config for x-quantitative axes.\n */\n axisXQuantitative?: AxisConfig;\n\n /**\n * Config for x-temporal axes.\n */\n axisXTemporal?: AxisConfig;\n\n /**\n * Config for y-axes with \"band\" scales.\n */\n axisYBand?: AxisConfig;\n\n /**\n * Config for y-axes with \"point\" scales.\n */\n axisYPoint?: AxisConfig;\n\n /**\n * Config for y-axes with \"point\" or \"band\" scales.\n */\n axisYDiscrete?: AxisConfig;\n\n /**\n * Config for y-quantitative axes.\n */\n axisYQuantitative?: AxisConfig;\n\n /**\n * Config for y-temporal axes.\n */\n axisYTemporal?: AxisConfig;\n}\n\nconst AXIS_CONFIGS_INDEX: Flag> = {\n axis: 1,\n axisBand: 1,\n axisBottom: 1,\n axisDiscrete: 1,\n axisLeft: 1,\n axisPoint: 1,\n axisQuantitative: 1,\n axisRight: 1,\n axisTemporal: 1,\n axisTop: 1,\n axisX: 1,\n axisXBand: 1,\n axisXDiscrete: 1,\n axisXPoint: 1,\n axisXQuantitative: 1,\n axisXTemporal: 1,\n axisY: 1,\n axisYBand: 1,\n axisYDiscrete: 1,\n axisYPoint: 1,\n axisYQuantitative: 1,\n axisYTemporal: 1\n};\n\nexport const AXIS_CONFIGS = keys(AXIS_CONFIGS_INDEX);\n","import {FieldName} from '../channeldef';\nimport {CompositeEncoding, FacetedCompositeEncoding} from '../compositemark';\nimport {Encoding} from '../encoding';\nimport {ExprRef} from '../expr';\nimport {AnyMark, Mark, MarkDef} from '../mark';\nimport {Projection} from '../projection';\nimport {SelectionParameter} from '../selection';\nimport {Field} from './../channeldef';\nimport {BaseSpec, DataMixins, FrameMixins, GenericCompositionLayout, ResolveMixins} from './base';\nimport {TopLevel, TopLevelParameter} from './toplevel';\n/**\n * Base interface for a unit (single-view) specification.\n */\nexport interface GenericUnitSpec, M, P = SelectionParameter> extends BaseSpec {\n /**\n * A string describing the mark type (one of `\"bar\"`, `\"circle\"`, `\"square\"`, `\"tick\"`, `\"line\"`,\n * `\"area\"`, `\"point\"`, `\"rule\"`, `\"geoshape\"`, and `\"text\"`) or a [mark definition object](https://vega.github.io/vega-lite/docs/mark.html#mark-def).\n */\n mark: M;\n\n /**\n * A key-value mapping between encoding channels and definition of fields.\n */\n encoding?: E;\n\n /**\n * An object defining properties of geographic projection, which will be applied to `shape` path for `\"geoshape\"` marks\n * and to `latitude` and `\"longitude\"` channels for other marks.\n */\n projection?: Projection;\n\n /**\n * An array of parameters that may either be simple variables, or more complex selections that map user input to data queries.\n */\n params?: P[];\n}\n\n/**\n * A unit specification without any shortcut/expansion syntax.\n */\nexport type NormalizedUnitSpec = GenericUnitSpec, Mark | MarkDef>;\n\n/**\n * A unit specification, which can contain either [primitive marks or composite marks](https://vega.github.io/vega-lite/docs/mark.html#types).\n */\nexport type UnitSpec = GenericUnitSpec, AnyMark>;\n\nexport type UnitSpecWithFrame = GenericUnitSpec, AnyMark> & FrameMixins;\n\n/**\n * Unit spec that can have a composite mark and row or column channels (shorthand for a facet spec).\n */\nexport type FacetedUnitSpec = GenericUnitSpec<\n FacetedCompositeEncoding,\n AnyMark,\n P\n> &\n ResolveMixins &\n GenericCompositionLayout &\n FrameMixins;\n\nexport type TopLevelUnitSpec = TopLevel> & DataMixins;\n\nexport function isUnitSpec(spec: BaseSpec): spec is FacetedUnitSpec | NormalizedUnitSpec {\n return 'mark' in spec;\n}\n","import {Encoding} from '../encoding';\nimport {GenericMarkDef, getMarkType} from '../mark';\nimport {NonFacetUnitNormalizer, Normalize, NormalizerParams} from '../normalize/base';\nimport {GenericSpec} from '../spec';\nimport {GenericLayerSpec, NormalizedLayerSpec} from '../spec/layer';\nimport {GenericUnitSpec, isUnitSpec, NormalizedUnitSpec} from '../spec/unit';\nimport {FieldName} from '../channeldef';\n\n// TODO: replace string with Mark\nexport type CompositeMarkUnitSpec = GenericUnitSpec>;\n\nexport class CompositeMarkNormalizer implements NonFacetUnitNormalizer> {\n constructor(\n public name: string,\n public run: (\n spec: CompositeMarkUnitSpec,\n params: NormalizerParams,\n normalize: Normalize<\n // Input of the normalize method\n GenericUnitSpec, M> | GenericLayerSpec,\n // Output of the normalize method\n NormalizedLayerSpec | NormalizedUnitSpec\n >\n ) => NormalizedLayerSpec | NormalizedUnitSpec\n ) {}\n\n public hasMatchingType(spec: GenericSpec): spec is CompositeMarkUnitSpec {\n if (isUnitSpec(spec)) {\n return getMarkType(spec.mark) === this.name;\n }\n return false;\n }\n}\n","import {AggregateOp} from 'vega';\nimport {array, isArray} from 'vega-util';\nimport {isArgmaxDef, isArgminDef} from './aggregate';\nimport {isBinned, isBinning} from './bin';\nimport {\n ANGLE,\n Channel,\n CHANNELS,\n COLOR,\n DESCRIPTION,\n DETAIL,\n FILL,\n FILLOPACITY,\n getMainChannelFromOffsetChannel,\n getOffsetScaleChannel,\n HREF,\n isChannel,\n isNonPositionScaleChannel,\n isSecondaryRangeChannel,\n isXorY,\n isXorYOffset,\n KEY,\n LATITUDE,\n LATITUDE2,\n LONGITUDE,\n LONGITUDE2,\n OPACITY,\n ORDER,\n RADIUS,\n RADIUS2,\n SHAPE,\n SIZE,\n STROKE,\n STROKEDASH,\n STROKEOPACITY,\n STROKEWIDTH,\n supportMark,\n TEXT,\n THETA,\n THETA2,\n TOOLTIP,\n UNIT_CHANNELS,\n URL,\n X,\n X2,\n XOFFSET,\n Y,\n Y2,\n YOFFSET\n} from './channel';\nimport {\n binRequiresRange,\n ChannelDef,\n ColorDef,\n Field,\n FieldDef,\n FieldDefWithoutScale,\n getFieldDef,\n getGuide,\n hasConditionalFieldDef,\n hasConditionalFieldOrDatumDef,\n initChannelDef,\n initFieldDef,\n isConditionalDef,\n isDatumDef,\n isFieldDef,\n isOrderOnlyDef,\n isTypedFieldDef,\n isValueDef,\n LatLongDef,\n NumericArrayMarkPropDef,\n NumericMarkPropDef,\n OffsetDef,\n OrderFieldDef,\n OrderOnlyDef,\n OrderValueDef,\n PolarDef,\n Position2Def,\n PositionDef,\n SecondaryFieldDef,\n ShapeDef,\n StringFieldDef,\n StringFieldDefWithCondition,\n StringValueDefWithCondition,\n TextDef,\n title,\n TypedFieldDef,\n vgField\n} from './channeldef';\nimport {Config} from './config';\nimport * as log from './log';\nimport {Mark} from './mark';\nimport {EncodingFacetMapping} from './spec/facet';\nimport {AggregatedFieldDef, BinTransform, TimeUnitTransform} from './transform';\nimport {isContinuous, isDiscrete, QUANTITATIVE, TEMPORAL} from './type';\nimport {keys, some} from './util';\nimport {isSignalRef} from './vega.schema';\nimport {isBinnedTimeUnit} from './timeunit';\n\nexport interface Encoding {\n /**\n * X coordinates of the marks, or width of horizontal `\"bar\"` and `\"area\"` without specified `x2` or `width`.\n *\n * The `value` of this channel can be a number or a string `\"width\"` for the width of the plot.\n */\n x?: PositionDef;\n\n /**\n * Y coordinates of the marks, or height of vertical `\"bar\"` and `\"area\"` without specified `y2` or `height`.\n *\n * The `value` of this channel can be a number or a string `\"height\"` for the height of the plot.\n */\n y?: PositionDef;\n\n /**\n * Offset of x-position of the marks\n */\n xOffset?: OffsetDef;\n\n /**\n * Offset of y-position of the marks\n */\n yOffset?: OffsetDef;\n\n /**\n * X2 coordinates for ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n *\n * The `value` of this channel can be a number or a string `\"width\"` for the width of the plot.\n */\n // TODO: Ham need to add default behavior\n // `x2` cannot have type as it should have the same type as `x`\n x2?: Position2Def;\n\n /**\n * Y2 coordinates for ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n *\n * The `value` of this channel can be a number or a string `\"height\"` for the height of the plot.\n */\n // TODO: Ham need to add default behavior\n // `y2` cannot have type as it should have the same type as `y`\n y2?: Position2Def;\n\n /**\n * Longitude position of geographically projected marks.\n */\n longitude?: LatLongDef;\n\n /**\n * Latitude position of geographically projected marks.\n */\n latitude?: LatLongDef;\n\n /**\n * Longitude-2 position for geographically projected ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n */\n // `longitude2` cannot have type as it should have the same type as `longitude`\n longitude2?: Position2Def;\n\n /**\n * Latitude-2 position for geographically projected ranged `\"area\"`, `\"bar\"`, `\"rect\"`, and `\"rule\"`.\n */\n // `latitude2` cannot have type as it should have the same type as `latitude`\n latitude2?: Position2Def;\n\n /**\n * - For arc marks, the arc length in radians if theta2 is not specified, otherwise the start arc angle. (A value of 0 indicates up or “north”, increasing values proceed clockwise.)\n *\n * - For text marks, polar coordinate angle in radians.\n */\n theta?: PolarDef;\n\n /**\n * The end angle of arc marks in radians. A value of 0 indicates up or “north”, increasing values proceed clockwise.\n */\n theta2?: Position2Def;\n\n /**\n * The outer radius in pixels of arc marks.\n */\n\n radius?: PolarDef;\n\n /**\n * The inner radius in pixels of arc marks.\n */\n radius2?: Position2Def;\n\n /**\n * Color of the marks – either fill or stroke color based on the `filled` property of mark definition.\n * By default, `color` represents fill color for `\"area\"`, `\"bar\"`, `\"tick\"`,\n * `\"text\"`, `\"trail\"`, `\"circle\"`, and `\"square\"` / stroke color for `\"line\"` and `\"point\"`.\n *\n * __Default value:__ If undefined, the default color depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#mark-config)'s `color` property.\n *\n * _Note:_\n * 1) For fine-grained control over both fill and stroke colors of the marks, please use the `fill` and `stroke` channels. The `fill` or `stroke` encodings have higher precedence than `color`, thus may override the `color` encoding if conflicting encodings are specified.\n * 2) See the scale documentation for more information about customizing [color scheme](https://vega.github.io/vega-lite/docs/scale.html#scheme).\n */\n color?: ColorDef;\n\n /**\n * Fill color of the marks.\n * __Default value:__ If undefined, the default color depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#mark-config)'s `color` property.\n *\n * _Note:_ The `fill` encoding has higher precedence than `color`, thus may override the `color` encoding if conflicting encodings are specified.\n */\n fill?: ColorDef;\n\n /**\n * Stroke color of the marks.\n * __Default value:__ If undefined, the default color depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#mark-config)'s `color` property.\n *\n * _Note:_ The `stroke` encoding has higher precedence than `color`, thus may override the `color` encoding if conflicting encodings are specified.\n */\n\n stroke?: ColorDef;\n\n /**\n * Opacity of the marks.\n *\n * __Default value:__ If undefined, the default opacity depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#mark-config)'s `opacity` property.\n */\n opacity?: NumericMarkPropDef;\n\n /**\n * Fill opacity of the marks.\n *\n * __Default value:__ If undefined, the default opacity depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#mark-config)'s `fillOpacity` property.\n */\n fillOpacity?: NumericMarkPropDef;\n\n /**\n * Stroke opacity of the marks.\n *\n * __Default value:__ If undefined, the default opacity depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#mark-config)'s `strokeOpacity` property.\n */\n strokeOpacity?: NumericMarkPropDef;\n\n /**\n * Stroke width of the marks.\n *\n * __Default value:__ If undefined, the default stroke width depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#mark-config)'s `strokeWidth` property.\n */\n strokeWidth?: NumericMarkPropDef;\n\n /**\n * Stroke dash of the marks.\n *\n * __Default value:__ `[1,0]` (No dash).\n */\n strokeDash?: NumericArrayMarkPropDef;\n\n /**\n * Size of the mark.\n * - For `\"point\"`, `\"square\"` and `\"circle\"`, – the symbol size, or pixel area of the mark.\n * - For `\"bar\"` and `\"tick\"` – the bar and tick's size.\n * - For `\"text\"` – the text's font size.\n * - Size is unsupported for `\"line\"`, `\"area\"`, and `\"rect\"`. (Use `\"trail\"` instead of line with varying size)\n */\n size?: NumericMarkPropDef;\n\n /**\n * Rotation angle of point and text marks.\n */\n angle?: NumericMarkPropDef;\n\n /**\n * Shape of the mark.\n *\n * 1. For `point` marks the supported values include:\n * - plotting shapes: `\"circle\"`, `\"square\"`, `\"cross\"`, `\"diamond\"`, `\"triangle-up\"`, `\"triangle-down\"`, `\"triangle-right\"`, or `\"triangle-left\"`.\n * - the line symbol `\"stroke\"`\n * - centered directional shapes `\"arrow\"`, `\"wedge\"`, or `\"triangle\"`\n * - a custom [SVG path string](https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths) (For correct sizing, custom shape paths should be defined within a square bounding box with coordinates ranging from -1 to 1 along both the x and y dimensions.)\n *\n * 2. For `geoshape` marks it should be a field definition of the geojson data\n *\n * __Default value:__ If undefined, the default shape depends on [mark config](https://vega.github.io/vega-lite/docs/config.html#point-config)'s `shape` property. (`\"circle\"` if unset.)\n */\n shape?: ShapeDef;\n /**\n * Additional levels of detail for grouping data in aggregate views and\n * in line, trail, and area marks without mapping data to a specific visual channel.\n */\n detail?: FieldDefWithoutScale | FieldDefWithoutScale[];\n\n /**\n * A data field to use as a unique key for data binding. When a visualization’s data is updated, the key value will be used to match data elements to existing mark instances. Use a key channel to enable object constancy for transitions over dynamic data.\n */\n key?: FieldDefWithoutScale;\n\n /**\n * Text of the `text` mark.\n */\n text?: TextDef;\n\n /**\n * The tooltip text to show upon mouse hover. Specifying `tooltip` encoding overrides [the `tooltip` property in the mark definition](https://vega.github.io/vega-lite/docs/mark.html#mark-def).\n *\n * See the [`tooltip`](https://vega.github.io/vega-lite/docs/tooltip.html) documentation for a detailed discussion about tooltip in Vega-Lite.\n */\n tooltip?: StringFieldDefWithCondition | StringValueDefWithCondition | StringFieldDef[] | null;\n\n /**\n * A URL to load upon mouse click.\n */\n href?: StringFieldDefWithCondition | StringValueDefWithCondition;\n\n /**\n * The URL of an image mark.\n */\n url?: StringFieldDefWithCondition | StringValueDefWithCondition;\n\n /**\n * A text description of this mark for ARIA accessibility (SVG output only). For SVG output the `\"aria-label\"` attribute will be set to this description.\n */\n description?: StringFieldDefWithCondition | StringValueDefWithCondition;\n\n /**\n * Order of the marks.\n * - For stacked marks, this `order` channel encodes [stack order](https://vega.github.io/vega-lite/docs/stack.html#order).\n * - For line and trail marks, this `order` channel encodes order of data points in the lines. This can be useful for creating [a connected scatterplot](https://vega.github.io/vega-lite/examples/connected_scatterplot.html). Setting `order` to `{\"value\": null}` makes the line marks use the original order in the data sources.\n * - Otherwise, this `order` channel encodes layer order of the marks.\n *\n * __Note__: In aggregate plots, `order` field should be `aggregate`d to avoid creating additional aggregation grouping.\n */\n order?: OrderFieldDef | OrderFieldDef[] | OrderValueDef | OrderOnlyDef;\n}\n\nexport interface EncodingWithFacet extends Encoding, EncodingFacetMapping {}\n\nexport function channelHasField(\n encoding: EncodingWithFacet,\n channel: keyof EncodingWithFacet\n): boolean {\n const channelDef = encoding && encoding[channel];\n if (channelDef) {\n if (isArray(channelDef)) {\n return some(channelDef, fieldDef => !!fieldDef.field);\n } else {\n return isFieldDef(channelDef) || hasConditionalFieldDef(channelDef);\n }\n }\n return false;\n}\n\nexport function channelHasFieldOrDatum(\n encoding: EncodingWithFacet,\n channel: keyof EncodingWithFacet\n): boolean {\n const channelDef = encoding && encoding[channel];\n if (channelDef) {\n if (isArray(channelDef)) {\n return some(channelDef, fieldDef => !!fieldDef.field);\n } else {\n return isFieldDef(channelDef) || isDatumDef(channelDef) || hasConditionalFieldOrDatumDef(channelDef);\n }\n }\n return false;\n}\n\nexport function channelHasNestedOffsetScale(\n encoding: EncodingWithFacet,\n channel: keyof EncodingWithFacet\n): boolean {\n if (isXorY(channel)) {\n const fieldDef = encoding[channel];\n if (\n (isFieldDef(fieldDef) || isDatumDef(fieldDef)) &&\n (isDiscrete(fieldDef.type) || (isFieldDef(fieldDef) && fieldDef.timeUnit))\n ) {\n const offsetChannel = getOffsetScaleChannel(channel);\n return channelHasFieldOrDatum(encoding, offsetChannel);\n }\n }\n return false;\n}\n\nexport function isAggregate(encoding: EncodingWithFacet) {\n return some(CHANNELS, channel => {\n if (channelHasField(encoding, channel)) {\n const channelDef = encoding[channel];\n if (isArray(channelDef)) {\n return some(channelDef, fieldDef => !!fieldDef.aggregate);\n } else {\n const fieldDef = getFieldDef(channelDef);\n return fieldDef && !!fieldDef.aggregate;\n }\n }\n return false;\n });\n}\n\nexport function extractTransformsFromEncoding(oldEncoding: Encoding, config: Config) {\n const groupby: string[] = [];\n const bins: BinTransform[] = [];\n const timeUnits: TimeUnitTransform[] = [];\n const aggregate: AggregatedFieldDef[] = [];\n const encoding: Encoding = {};\n\n forEach(oldEncoding, (channelDef, channel) => {\n // Extract potential embedded transformations along with remaining properties\n if (isFieldDef(channelDef)) {\n const {field, aggregate: aggOp, bin, timeUnit, ...remaining} = channelDef;\n if (aggOp || timeUnit || bin) {\n const guide = getGuide(channelDef);\n const isTitleDefined = guide?.title;\n let newField = vgField(channelDef, {forAs: true});\n const newFieldDef: FieldDef = {\n // Only add title if it doesn't exist\n ...(isTitleDefined ? [] : {title: title(channelDef, config, {allowDisabling: true})}),\n ...remaining,\n // Always overwrite field\n field: newField\n };\n\n if (aggOp) {\n let op: AggregateOp;\n\n if (isArgmaxDef(aggOp)) {\n op = 'argmax';\n newField = vgField({op: 'argmax', field: aggOp.argmax}, {forAs: true});\n newFieldDef.field = `${newField}.${field}`;\n } else if (isArgminDef(aggOp)) {\n op = 'argmin';\n newField = vgField({op: 'argmin', field: aggOp.argmin}, {forAs: true});\n newFieldDef.field = `${newField}.${field}`;\n } else if (aggOp !== 'boxplot' && aggOp !== 'errorbar' && aggOp !== 'errorband') {\n op = aggOp;\n }\n\n if (op) {\n const aggregateEntry: AggregatedFieldDef = {\n op,\n as: newField\n };\n if (field) {\n aggregateEntry.field = field;\n }\n aggregate.push(aggregateEntry);\n }\n } else {\n groupby.push(newField);\n if (isTypedFieldDef(channelDef) && isBinning(bin)) {\n bins.push({bin, field, as: newField});\n // Add additional groupbys for range and end of bins\n groupby.push(vgField(channelDef, {binSuffix: 'end'}));\n if (binRequiresRange(channelDef, channel)) {\n groupby.push(vgField(channelDef, {binSuffix: 'range'}));\n }\n // Create accompanying 'x2' or 'y2' field if channel is 'x' or 'y' respectively\n if (isXorY(channel)) {\n const secondaryChannel: SecondaryFieldDef = {\n field: `${newField}_end`\n };\n encoding[`${channel}2`] = secondaryChannel;\n }\n newFieldDef.bin = 'binned';\n if (!isSecondaryRangeChannel(channel)) {\n newFieldDef['type'] = QUANTITATIVE;\n }\n } else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {\n timeUnits.push({\n timeUnit,\n field,\n as: newField\n });\n\n // define the format type for later compilation\n const formatType = isTypedFieldDef(channelDef) && channelDef.type !== TEMPORAL && 'time';\n if (formatType) {\n if (channel === TEXT || channel === TOOLTIP) {\n newFieldDef['formatType'] = formatType;\n } else if (isNonPositionScaleChannel(channel)) {\n newFieldDef['legend'] = {\n formatType,\n ...newFieldDef['legend']\n };\n } else if (isXorY(channel)) {\n newFieldDef['axis'] = {\n formatType,\n ...newFieldDef['axis']\n };\n }\n }\n }\n }\n\n // now the field should refer to post-transformed field instead\n encoding[channel as any] = newFieldDef;\n } else {\n groupby.push(field);\n encoding[channel as any] = oldEncoding[channel];\n }\n } else {\n // For value def / signal ref / datum def, just copy\n encoding[channel as any] = oldEncoding[channel];\n }\n });\n\n return {\n bins,\n timeUnits,\n aggregate,\n groupby,\n encoding\n };\n}\n\nexport function markChannelCompatible(encoding: Encoding, channel: Channel, mark: Mark) {\n const markSupported = supportMark(channel, mark);\n if (!markSupported) {\n return false;\n } else if (markSupported === 'binned') {\n const primaryFieldDef = encoding[channel === X2 ? X : Y];\n\n // circle, point, square and tick only support x2/y2 when their corresponding x/y fieldDef\n // has \"binned\" data and thus need x2/y2 to specify the bin-end field.\n if (isFieldDef(primaryFieldDef) && isFieldDef(encoding[channel]) && isBinned(primaryFieldDef.bin)) {\n return true;\n } else {\n return false;\n }\n }\n return true;\n}\n\nexport function initEncoding(\n encoding: Encoding,\n mark: Mark,\n filled: boolean,\n config: Config\n): Encoding {\n const normalizedEncoding: Encoding = {};\n for (const key of keys(encoding)) {\n if (!isChannel(key)) {\n // Drop invalid channel\n log.warn(log.message.invalidEncodingChannel(key));\n }\n }\n\n for (let channel of UNIT_CHANNELS) {\n if (!encoding[channel]) {\n continue;\n }\n\n const channelDef = encoding[channel];\n if (isXorYOffset(channel)) {\n const mainChannel = getMainChannelFromOffsetChannel(channel);\n\n const positionDef = normalizedEncoding[mainChannel];\n if (isFieldDef(positionDef)) {\n if (isContinuous(positionDef.type)) {\n if (isFieldDef(channelDef) && !positionDef.timeUnit) {\n // TODO: nesting continuous field instead continuous field should\n // behave like offsetting the data in data domain\n log.warn(log.message.offsetNestedInsideContinuousPositionScaleDropped(mainChannel));\n continue;\n }\n }\n }\n }\n\n if (channel === 'angle' && mark === 'arc' && !encoding.theta) {\n log.warn(log.message.REPLACE_ANGLE_WITH_THETA);\n channel = THETA;\n }\n\n if (!markChannelCompatible(encoding, channel, mark)) {\n // Drop unsupported channel\n log.warn(log.message.incompatibleChannel(channel, mark));\n continue;\n }\n\n // Drop line's size if the field is aggregated.\n if (channel === SIZE && mark === 'line') {\n const fieldDef = getFieldDef(encoding[channel]);\n if (fieldDef?.aggregate) {\n log.warn(log.message.LINE_WITH_VARYING_SIZE);\n continue;\n }\n }\n // Drop color if either fill or stroke is specified\n\n if (channel === COLOR && (filled ? 'fill' in encoding : 'stroke' in encoding)) {\n log.warn(log.message.droppingColor('encoding', {fill: 'fill' in encoding, stroke: 'stroke' in encoding}));\n continue;\n }\n\n if (\n channel === DETAIL ||\n (channel === ORDER && !isArray(channelDef) && !isValueDef(channelDef)) ||\n (channel === TOOLTIP && isArray(channelDef))\n ) {\n if (channelDef) {\n if (channel === ORDER) {\n const def = encoding[channel];\n if (isOrderOnlyDef(def)) {\n normalizedEncoding[channel] = def;\n continue;\n }\n }\n // Array of fieldDefs for detail channel (or production rule)\n (normalizedEncoding[channel] as any) = array(channelDef).reduce(\n (defs: FieldDef[], fieldDef: FieldDef) => {\n if (!isFieldDef(fieldDef)) {\n log.warn(log.message.emptyFieldDef(fieldDef, channel));\n } else {\n defs.push(initFieldDef(fieldDef, channel));\n }\n return defs;\n },\n []\n );\n }\n } else {\n if (channel === TOOLTIP && channelDef === null) {\n // Preserve null so we can use it to disable tooltip\n normalizedEncoding[channel] = null;\n } else if (\n !isFieldDef(channelDef) &&\n !isDatumDef(channelDef) &&\n !isValueDef(channelDef) &&\n !isConditionalDef(channelDef) &&\n !isSignalRef(channelDef)\n ) {\n log.warn(log.message.emptyFieldDef(channelDef, channel));\n continue;\n }\n\n normalizedEncoding[channel as any] = initChannelDef(channelDef as ChannelDef, channel, config);\n }\n }\n return normalizedEncoding;\n}\n\n/**\n * For composite marks, we have to call initChannelDef during init so we can infer types earlier.\n */\nexport function normalizeEncoding(encoding: Encoding, config: Config): Encoding {\n const normalizedEncoding: Encoding = {};\n\n for (const channel of keys(encoding)) {\n const newChannelDef = initChannelDef(encoding[channel], channel, config, {compositeMark: true});\n normalizedEncoding[channel as any] = newChannelDef;\n }\n\n return normalizedEncoding;\n}\n\nexport function fieldDefs(encoding: EncodingWithFacet): FieldDef[] {\n const arr: FieldDef[] = [];\n for (const channel of keys(encoding)) {\n if (channelHasField(encoding, channel)) {\n const channelDef = encoding[channel];\n const channelDefArray = array(channelDef);\n for (const def of channelDefArray) {\n if (isFieldDef(def)) {\n arr.push(def);\n } else if (hasConditionalFieldDef(def)) {\n arr.push(def.condition);\n }\n }\n }\n }\n return arr;\n}\n\nexport function forEach>(\n mapping: U,\n f: (cd: ChannelDef, c: keyof U) => void,\n thisArg?: any\n) {\n if (!mapping) {\n return;\n }\n\n for (const channel of keys(mapping)) {\n const el = mapping[channel];\n if (isArray(el)) {\n for (const channelDef of el as unknown[]) {\n f.call(thisArg, channelDef, channel);\n }\n } else {\n f.call(thisArg, el, channel);\n }\n }\n}\n\nexport function reduce>(\n mapping: U,\n f: (acc: any, fd: TypedFieldDef, c: keyof U) => U,\n init: T,\n thisArg?: any\n) {\n if (!mapping) {\n return init;\n }\n\n return keys(mapping).reduce((r, channel) => {\n const map = mapping[channel];\n if (isArray(map)) {\n return map.reduce((r1: T, channelDef: ChannelDef) => {\n return f.call(thisArg, r1, channelDef, channel);\n }, r);\n } else {\n return f.call(thisArg, r, map, channel);\n }\n }, init);\n}\n\n/**\n * Returns list of path grouping fields for the given encoding\n */\nexport function pathGroupingFields(mark: Mark, encoding: Encoding): string[] {\n return keys(encoding).reduce((details, channel) => {\n switch (channel) {\n // x, y, x2, y2, lat, long, lat1, long2, order, tooltip, href, aria label, cursor should not cause lines to group\n case X:\n case Y:\n case HREF:\n case DESCRIPTION:\n case URL:\n case X2:\n case Y2:\n case XOFFSET:\n case YOFFSET:\n case THETA:\n case THETA2:\n case RADIUS:\n case RADIUS2:\n // falls through\n\n case LATITUDE:\n case LONGITUDE:\n case LATITUDE2:\n case LONGITUDE2:\n // TODO: case 'cursor':\n\n // text, shape, shouldn't be a part of line/trail/area [falls through]\n case TEXT:\n case SHAPE:\n case ANGLE:\n // falls through\n\n // tooltip fields should not be added to group by [falls through]\n case TOOLTIP:\n return details;\n\n case ORDER:\n // order should not group line / trail\n if (mark === 'line' || mark === 'trail') {\n return details;\n }\n // but order should group area for stacking (falls through)\n\n case DETAIL:\n case KEY: {\n const channelDef = encoding[channel];\n if (isArray(channelDef) || isFieldDef(channelDef)) {\n for (const fieldDef of array(channelDef)) {\n if (!fieldDef.aggregate) {\n details.push(vgField(fieldDef, {}));\n }\n }\n }\n return details;\n }\n\n case SIZE:\n if (mark === 'trail') {\n // For trail, size should not group trail lines.\n return details;\n }\n // For line, size should group lines.\n\n // falls through\n case COLOR:\n case FILL:\n case STROKE:\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n case STROKEDASH:\n case STROKEWIDTH: {\n // TODO strokeDashOffset:\n // falls through\n\n const fieldDef = getFieldDef(encoding[channel]);\n if (fieldDef && !fieldDef.aggregate) {\n details.push(vgField(fieldDef, {}));\n }\n return details;\n }\n }\n }, []);\n}\n","import {Orientation, SignalRef, Text} from 'vega';\nimport {isArray, isBoolean, isString} from 'vega-util';\nimport {CompositeMark, CompositeMarkDef} from '.';\nimport {\n Field,\n FieldDefBase,\n isContinuousFieldOrDatumDef,\n isFieldDef,\n isFieldOrDatumDefForTimeFormat,\n PositionFieldDef,\n SecondaryFieldDef,\n StringFieldDef,\n StringFieldDefWithCondition,\n StringValueDefWithCondition\n} from '../channeldef';\nimport {Encoding, fieldDefs} from '../encoding';\nimport {ExprRef} from '../expr';\nimport * as log from '../log';\nimport {ColorMixins, GenericMarkDef, isMarkDef, Mark, AnyMarkConfig, MarkDef} from '../mark';\nimport {GenericUnitSpec, NormalizedUnitSpec} from '../spec';\nimport {getFirstDefined, hash, unique} from '../util';\nimport {isSignalRef} from '../vega.schema';\nimport {toStringFieldDef} from './../channeldef';\n\n// Parts mixins can be any mark type. We could make a more specific type for each part.\nexport type PartsMixins

= Partial>>;\n\nexport type GenericCompositeMarkDef = GenericMarkDef &\n ColorMixins & {\n /**\n * The opacity (value between [0,1]) of the mark.\n *\n * @minimum 0\n * @maximum 1\n */\n opacity?: number;\n\n /**\n * Whether a composite mark be clipped to the enclosing group’s width and height.\n */\n clip?: boolean;\n };\n\nexport interface CompositeMarkTooltipSummary {\n /**\n * The prefix of the field to be shown in tooltip\n */\n fieldPrefix: string;\n\n /**\n * The title prefix to show, corresponding to the field with field prefix `fieldPrefix`\n */\n titlePrefix: Text | SignalRef;\n}\n\nexport function filterTooltipWithAggregatedField(\n oldEncoding: Encoding\n): {\n customTooltipWithoutAggregatedField?:\n | StringFieldDefWithCondition\n | StringValueDefWithCondition\n | StringFieldDef[];\n filteredEncoding: Encoding;\n} {\n const {tooltip, ...filteredEncoding} = oldEncoding;\n if (!tooltip) {\n return {filteredEncoding};\n }\n\n let customTooltipWithAggregatedField:\n | StringFieldDefWithCondition\n | StringValueDefWithCondition\n | StringFieldDef[];\n let customTooltipWithoutAggregatedField:\n | StringFieldDefWithCondition\n | StringValueDefWithCondition\n | StringFieldDef[];\n\n if (isArray(tooltip)) {\n for (const t of tooltip) {\n if (t.aggregate) {\n if (!customTooltipWithAggregatedField) {\n customTooltipWithAggregatedField = [];\n }\n (customTooltipWithAggregatedField as StringFieldDef[]).push(t);\n } else {\n if (!customTooltipWithoutAggregatedField) {\n customTooltipWithoutAggregatedField = [];\n }\n (customTooltipWithoutAggregatedField as StringFieldDef[]).push(t);\n }\n }\n\n if (customTooltipWithAggregatedField) {\n (filteredEncoding as Encoding).tooltip = customTooltipWithAggregatedField;\n }\n } else {\n if (tooltip['aggregate']) {\n (filteredEncoding as Encoding).tooltip = tooltip;\n } else {\n customTooltipWithoutAggregatedField = tooltip;\n }\n }\n\n if (isArray(customTooltipWithoutAggregatedField) && customTooltipWithoutAggregatedField.length === 1) {\n customTooltipWithoutAggregatedField = customTooltipWithoutAggregatedField[0];\n }\n return {customTooltipWithoutAggregatedField, filteredEncoding};\n}\n\nexport function getCompositeMarkTooltip(\n tooltipSummary: CompositeMarkTooltipSummary[],\n continuousAxisChannelDef: PositionFieldDef,\n encodingWithoutContinuousAxis: Encoding,\n withFieldName = true\n): Encoding {\n if ('tooltip' in encodingWithoutContinuousAxis) {\n return {tooltip: encodingWithoutContinuousAxis.tooltip};\n }\n\n const fiveSummaryTooltip: StringFieldDef[] = tooltipSummary.map(\n ({fieldPrefix, titlePrefix}): StringFieldDef => {\n const mainTitle = withFieldName ? ` of ${getTitle(continuousAxisChannelDef)}` : '';\n return {\n field: fieldPrefix + continuousAxisChannelDef.field,\n type: continuousAxisChannelDef.type,\n title: isSignalRef(titlePrefix) ? {signal: `${titlePrefix}\"${escape(mainTitle)}\"`} : titlePrefix + mainTitle\n };\n }\n );\n\n const tooltipFieldDefs = fieldDefs(encodingWithoutContinuousAxis).map(toStringFieldDef);\n\n return {\n tooltip: [\n ...fiveSummaryTooltip,\n // need to cast because TextFieldDef supports fewer types of bin\n ...unique(tooltipFieldDefs, hash)\n ]\n };\n}\n\nexport function getTitle(continuousAxisChannelDef: PositionFieldDef) {\n const {title, field} = continuousAxisChannelDef;\n return getFirstDefined(title, field);\n}\n\nexport function makeCompositeAggregatePartFactory

>(\n compositeMarkDef: GenericCompositeMarkDef & P,\n continuousAxis: 'x' | 'y',\n continuousAxisChannelDef: PositionFieldDef,\n sharedEncoding: Encoding,\n compositeMarkConfig: P\n) {\n const {scale, axis} = continuousAxisChannelDef;\n\n return ({\n partName,\n mark,\n positionPrefix,\n endPositionPrefix = undefined,\n extraEncoding = {}\n }: {\n partName: keyof P;\n mark: Mark | MarkDef;\n positionPrefix: string;\n endPositionPrefix?: string;\n extraEncoding?: Encoding;\n }) => {\n const title = getTitle(continuousAxisChannelDef);\n\n return partLayerMixins

(compositeMarkDef, partName, compositeMarkConfig, {\n mark, // TODO better remove this method and just have mark as a parameter of the method\n encoding: {\n [continuousAxis]: {\n field: `${positionPrefix}_${continuousAxisChannelDef.field}`,\n type: continuousAxisChannelDef.type,\n ...(title !== undefined ? {title} : {}),\n ...(scale !== undefined ? {scale} : {}),\n ...(axis !== undefined ? {axis} : {})\n },\n ...(isString(endPositionPrefix)\n ? {\n [`${continuousAxis}2`]: {\n field: `${endPositionPrefix}_${continuousAxisChannelDef.field}`\n }\n }\n : {}),\n ...sharedEncoding,\n ...extraEncoding\n }\n });\n };\n}\n\nexport function partLayerMixins

>(\n markDef: GenericCompositeMarkDef & P,\n part: keyof P,\n compositeMarkConfig: P,\n partBaseSpec: NormalizedUnitSpec\n): NormalizedUnitSpec[] {\n const {clip, color, opacity} = markDef;\n\n const mark = markDef.type;\n\n if (markDef[part] || (markDef[part] === undefined && compositeMarkConfig[part])) {\n return [\n {\n ...partBaseSpec,\n mark: {\n ...(compositeMarkConfig[part] as AnyMarkConfig),\n ...(clip ? {clip} : {}),\n ...(color ? {color} : {}),\n ...(opacity ? {opacity} : {}),\n ...(isMarkDef(partBaseSpec.mark) ? partBaseSpec.mark : {type: partBaseSpec.mark}),\n style: `${mark}-${String(part)}`,\n ...(isBoolean(markDef[part]) ? {} : (markDef[part] as AnyMarkConfig))\n }\n }\n ];\n }\n return [];\n}\n\nexport function compositeMarkContinuousAxis(\n spec: GenericUnitSpec, CompositeMark | CompositeMarkDef>,\n orient: Orientation,\n compositeMark: M\n): {\n continuousAxisChannelDef: PositionFieldDef;\n continuousAxisChannelDef2: SecondaryFieldDef;\n continuousAxisChannelDefError: SecondaryFieldDef;\n continuousAxisChannelDefError2: SecondaryFieldDef;\n continuousAxis: 'x' | 'y';\n} {\n const {encoding} = spec;\n const continuousAxis: 'x' | 'y' = orient === 'vertical' ? 'y' : 'x';\n\n const continuousAxisChannelDef = encoding[continuousAxis] as PositionFieldDef; // Safe to cast because if x is not continuous fielddef, the orient would not be horizontal.\n const continuousAxisChannelDef2 = encoding[`${continuousAxis}2`] as SecondaryFieldDef;\n const continuousAxisChannelDefError = encoding[`${continuousAxis}Error`] as SecondaryFieldDef;\n const continuousAxisChannelDefError2 = encoding[`${continuousAxis}Error2`] as SecondaryFieldDef;\n\n return {\n continuousAxisChannelDef: filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark),\n continuousAxisChannelDef2: filterAggregateFromChannelDef(continuousAxisChannelDef2, compositeMark),\n continuousAxisChannelDefError: filterAggregateFromChannelDef(continuousAxisChannelDefError, compositeMark),\n continuousAxisChannelDefError2: filterAggregateFromChannelDef(continuousAxisChannelDefError2, compositeMark),\n continuousAxis\n };\n}\n\nfunction filterAggregateFromChannelDef>(\n continuousAxisChannelDef: F,\n compositeMark: M\n): F {\n if (continuousAxisChannelDef?.aggregate) {\n const {aggregate, ...continuousAxisWithoutAggregate} = continuousAxisChannelDef;\n if (aggregate !== compositeMark) {\n log.warn(log.message.errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark));\n }\n return continuousAxisWithoutAggregate as F;\n } else {\n return continuousAxisChannelDef;\n }\n}\n\nexport function compositeMarkOrient(\n spec: GenericUnitSpec, CompositeMark | CompositeMarkDef>,\n compositeMark: M\n): Orientation {\n const {mark, encoding} = spec;\n const {x, y} = encoding;\n\n if (isMarkDef(mark) && mark.orient) {\n return mark.orient;\n }\n\n if (isContinuousFieldOrDatumDef(x)) {\n // x is continuous\n if (isContinuousFieldOrDatumDef(y)) {\n // both x and y are continuous\n const xAggregate = isFieldDef(x) && x.aggregate;\n const yAggregate = isFieldDef(y) && y.aggregate;\n\n if (!xAggregate && yAggregate === compositeMark) {\n return 'vertical';\n } else if (!yAggregate && xAggregate === compositeMark) {\n return 'horizontal';\n } else if (xAggregate === compositeMark && yAggregate === compositeMark) {\n throw new Error('Both x and y cannot have aggregate');\n } else {\n if (isFieldOrDatumDefForTimeFormat(y) && !isFieldOrDatumDefForTimeFormat(x)) {\n // y is temporal but x is not\n return 'horizontal';\n }\n\n // default orientation for two continuous\n return 'vertical';\n }\n }\n\n return 'horizontal';\n } else if (isContinuousFieldOrDatumDef(y)) {\n // y is continuous but x is not\n return 'vertical';\n } else {\n // Neither x nor y is continuous.\n throw new Error(`Need a valid continuous axis for ${compositeMark}s`);\n }\n}\n","import {Orientation} from 'vega';\nimport {isNumber, isObject} from 'vega-util';\nimport {getMarkPropOrConfig} from '../compile/common';\nimport {Config} from '../config';\nimport {Encoding, extractTransformsFromEncoding, normalizeEncoding} from '../encoding';\nimport * as log from '../log';\nimport {isMarkDef, MarkDef} from '../mark';\nimport {MarkInvalidMixins} from '../invalid';\nimport {NormalizerParams} from '../normalize';\nimport {GenericUnitSpec, NormalizedLayerSpec, NormalizedUnitSpec} from '../spec';\nimport {AggregatedFieldDef, CalculateTransform, JoinAggregateTransform, Transform} from '../transform';\nimport {isEmpty, omit, removePathFromField} from '../util';\nimport {CompositeMarkNormalizer} from './base';\nimport {\n compositeMarkContinuousAxis,\n compositeMarkOrient,\n filterTooltipWithAggregatedField,\n GenericCompositeMarkDef,\n getCompositeMarkTooltip,\n getTitle,\n makeCompositeAggregatePartFactory,\n partLayerMixins,\n PartsMixins\n} from './common';\n\nexport const BOXPLOT = 'boxplot' as const;\nexport type BoxPlot = typeof BOXPLOT;\n\nexport const BOXPLOT_PARTS = ['box', 'median', 'outliers', 'rule', 'ticks'] as const;\n\ntype BoxPlotPart = (typeof BOXPLOT_PARTS)[number];\n\nexport type BoxPlotPartsMixins = PartsMixins;\n\nexport interface BoxPlotConfig extends BoxPlotPartsMixins {\n /** Size of the box and median tick of a box plot */\n size?: number;\n\n /**\n * The extent of the whiskers. Available options include:\n * - `\"min-max\"`: min and max are the lower and upper whiskers respectively.\n * - A number representing multiple of the interquartile range. This number will be multiplied by the IQR to determine whisker boundary, which spans from the smallest data to the largest data within the range _[Q1 - k * IQR, Q3 + k * IQR]_ where _Q1_ and _Q3_ are the first and third quartiles while _IQR_ is the interquartile range (_Q3-Q1_).\n *\n * __Default value:__ `1.5`.\n */\n extent?: 'min-max' | number;\n}\n\nexport type BoxPlotDef = GenericCompositeMarkDef &\n BoxPlotConfig &\n MarkInvalidMixins & {\n /**\n * Type of the mark. For box plots, this should always be `\"boxplot\"`.\n * [boxplot](https://vega.github.io/vega-lite/docs/boxplot.html)\n */\n type: BoxPlot;\n\n /**\n * Orientation of the box plot. This is normally automatically determined based on types of fields on x and y channels. However, an explicit `orient` be specified when the orientation is ambiguous.\n *\n * __Default value:__ `\"vertical\"`.\n */\n orient?: Orientation;\n };\n\nexport interface BoxPlotConfigMixins {\n /**\n * Box Config\n */\n boxplot?: BoxPlotConfig;\n}\n\nexport const boxPlotNormalizer = new CompositeMarkNormalizer(BOXPLOT, normalizeBoxPlot);\n\nexport function getBoxPlotType(extent: number | 'min-max') {\n if (isNumber(extent)) {\n return 'tukey';\n }\n // 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.\n return extent;\n}\n\nexport function normalizeBoxPlot(\n spec: GenericUnitSpec, BoxPlot | BoxPlotDef>,\n {config}: NormalizerParams\n): NormalizedLayerSpec {\n // Need to initEncoding first so we can infer type\n spec = {\n ...spec,\n encoding: normalizeEncoding(spec.encoding, config)\n };\n const {mark, encoding: _encoding, params, projection: _p, ...outerSpec} = spec;\n const markDef: BoxPlotDef = isMarkDef(mark) ? mark : {type: mark};\n\n // TODO(https://github.com/vega/vega-lite/issues/3702): add selection support\n if (params) {\n log.warn(log.message.selectionNotSupported('boxplot'));\n }\n\n const extent = markDef.extent ?? config.boxplot.extent;\n const sizeValue = getMarkPropOrConfig(\n 'size',\n markDef as any, // TODO: https://github.com/vega/vega-lite/issues/6245\n config\n );\n\n const invalid = markDef.invalid;\n\n const boxPlotType = getBoxPlotType(extent);\n const {\n bins,\n timeUnits,\n transform,\n continuousAxisChannelDef,\n continuousAxis,\n groupby,\n aggregate,\n encodingWithoutContinuousAxis,\n ticksOrient,\n boxOrient,\n customTooltipWithoutAggregatedField\n } = boxParams(spec, extent, config);\n\n const aliasedFieldName = removePathFromField(continuousAxisChannelDef.field);\n\n const {color, size, ...encodingWithoutSizeColorAndContinuousAxis} = encodingWithoutContinuousAxis;\n\n const makeBoxPlotPart = (sharedEncoding: Encoding) => {\n return makeCompositeAggregatePartFactory(\n markDef,\n continuousAxis,\n continuousAxisChannelDef,\n sharedEncoding,\n config.boxplot\n );\n };\n\n const makeBoxPlotExtent = makeBoxPlotPart(encodingWithoutSizeColorAndContinuousAxis);\n const makeBoxPlotBox = makeBoxPlotPart(encodingWithoutContinuousAxis);\n const defaultBoxColor = (isObject(config.boxplot.box) ? config.boxplot.box.color : config.mark.color) || '#4c78a8';\n const makeBoxPlotMidTick = makeBoxPlotPart({\n ...encodingWithoutSizeColorAndContinuousAxis,\n ...(size ? {size} : {}),\n color: {\n condition: {\n test: `datum['lower_box_${continuousAxisChannelDef.field}'] >= datum['upper_box_${continuousAxisChannelDef.field}']`,\n ...(color || {value: defaultBoxColor})\n }\n }\n });\n\n const fiveSummaryTooltipEncoding: Encoding = getCompositeMarkTooltip(\n [\n {fieldPrefix: boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_', titlePrefix: 'Max'},\n {fieldPrefix: 'upper_box_', titlePrefix: 'Q3'},\n {fieldPrefix: 'mid_box_', titlePrefix: 'Median'},\n {fieldPrefix: 'lower_box_', titlePrefix: 'Q1'},\n {fieldPrefix: boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_', titlePrefix: 'Min'}\n ],\n continuousAxisChannelDef,\n encodingWithoutContinuousAxis\n );\n\n // ## Whisker Layers\n\n const endTick: MarkDef = {type: 'tick', color: 'black', opacity: 1, orient: ticksOrient, invalid, aria: false};\n const whiskerTooltipEncoding: Encoding =\n boxPlotType === 'min-max'\n ? fiveSummaryTooltipEncoding // for min-max, show five-summary tooltip for whisker\n : // for tukey / k-IQR, just show upper/lower-whisker\n getCompositeMarkTooltip(\n [\n {fieldPrefix: 'upper_whisker_', titlePrefix: 'Upper Whisker'},\n {fieldPrefix: 'lower_whisker_', titlePrefix: 'Lower Whisker'}\n ],\n continuousAxisChannelDef,\n encodingWithoutContinuousAxis\n );\n\n const whiskerLayers = [\n ...makeBoxPlotExtent({\n partName: 'rule',\n mark: {type: 'rule', invalid, aria: false},\n positionPrefix: 'lower_whisker',\n endPositionPrefix: 'lower_box',\n extraEncoding: whiskerTooltipEncoding\n }),\n ...makeBoxPlotExtent({\n partName: 'rule',\n mark: {type: 'rule', invalid, aria: false},\n positionPrefix: 'upper_box',\n endPositionPrefix: 'upper_whisker',\n extraEncoding: whiskerTooltipEncoding\n }),\n ...makeBoxPlotExtent({\n partName: 'ticks',\n mark: endTick,\n positionPrefix: 'lower_whisker',\n extraEncoding: whiskerTooltipEncoding\n }),\n ...makeBoxPlotExtent({\n partName: 'ticks',\n mark: endTick,\n positionPrefix: 'upper_whisker',\n extraEncoding: whiskerTooltipEncoding\n })\n ];\n\n // ## Box Layers\n\n // TODO: support hiding certain mark parts\n const boxLayers: NormalizedUnitSpec[] = [\n ...(boxPlotType !== 'tukey' ? whiskerLayers : []),\n ...makeBoxPlotBox({\n partName: 'box',\n mark: {\n type: 'bar',\n ...(sizeValue ? {size: sizeValue} : {}),\n orient: boxOrient,\n invalid,\n ariaRoleDescription: 'box'\n },\n positionPrefix: 'lower_box',\n endPositionPrefix: 'upper_box',\n extraEncoding: fiveSummaryTooltipEncoding\n }),\n ...makeBoxPlotMidTick({\n partName: 'median',\n mark: {\n type: 'tick',\n invalid,\n ...(isObject(config.boxplot.median) && config.boxplot.median.color ? {color: config.boxplot.median.color} : {}),\n ...(sizeValue ? {size: sizeValue} : {}),\n orient: ticksOrient,\n aria: false\n },\n positionPrefix: 'mid_box',\n extraEncoding: fiveSummaryTooltipEncoding\n })\n ];\n\n if (boxPlotType === 'min-max') {\n return {\n ...outerSpec,\n transform: (outerSpec.transform ?? []).concat(transform),\n layer: boxLayers\n };\n }\n\n // Tukey Box Plot\n\n const lowerBoxExpr = `datum[\"lower_box_${continuousAxisChannelDef.field}\"]`;\n const upperBoxExpr = `datum[\"upper_box_${continuousAxisChannelDef.field}\"]`;\n const iqrExpr = `(${upperBoxExpr} - ${lowerBoxExpr})`;\n const lowerWhiskerExpr = `${lowerBoxExpr} - ${extent} * ${iqrExpr}`;\n const upperWhiskerExpr = `${upperBoxExpr} + ${extent} * ${iqrExpr}`;\n const fieldExpr = `datum[\"${continuousAxisChannelDef.field}\"]`;\n\n const joinaggregateTransform: JoinAggregateTransform = {\n joinaggregate: boxParamsQuartiles(continuousAxisChannelDef.field),\n groupby\n };\n\n const filteredWhiskerSpec: NormalizedLayerSpec = {\n transform: [\n {\n filter: `(${lowerWhiskerExpr} <= ${fieldExpr}) && (${fieldExpr} <= ${upperWhiskerExpr})`\n },\n {\n aggregate: [\n {\n op: 'min',\n field: continuousAxisChannelDef.field,\n as: `lower_whisker_${aliasedFieldName}`\n },\n {\n op: 'max',\n field: continuousAxisChannelDef.field,\n as: `upper_whisker_${aliasedFieldName}`\n },\n // preserve lower_box / upper_box\n {\n op: 'min',\n field: `lower_box_${continuousAxisChannelDef.field}`,\n as: `lower_box_${aliasedFieldName}`\n },\n {\n op: 'max',\n field: `upper_box_${continuousAxisChannelDef.field}`,\n as: `upper_box_${aliasedFieldName}`\n },\n ...aggregate\n ],\n groupby\n }\n ],\n layer: whiskerLayers\n };\n\n const {tooltip, ...encodingWithoutSizeColorContinuousAxisAndTooltip} = encodingWithoutSizeColorAndContinuousAxis;\n\n const {scale, axis} = continuousAxisChannelDef;\n const title = getTitle(continuousAxisChannelDef);\n const axisWithoutTitle = omit(axis, ['title']);\n\n const outlierLayersMixins = partLayerMixins(markDef, 'outliers', config.boxplot, {\n transform: [{filter: `(${fieldExpr} < ${lowerWhiskerExpr}) || (${fieldExpr} > ${upperWhiskerExpr})`}],\n mark: 'point',\n encoding: {\n [continuousAxis]: {\n field: continuousAxisChannelDef.field,\n type: continuousAxisChannelDef.type,\n ...(title !== undefined ? {title} : {}),\n ...(scale !== undefined ? {scale} : {}),\n // add axis without title since we already added the title above\n ...(isEmpty(axisWithoutTitle) ? {} : {axis: axisWithoutTitle})\n },\n ...encodingWithoutSizeColorContinuousAxisAndTooltip,\n ...(color ? {color} : {}),\n ...(customTooltipWithoutAggregatedField ? {tooltip: customTooltipWithoutAggregatedField} : {})\n }\n })[0];\n\n let filteredLayersMixins: NormalizedLayerSpec;\n const filteredLayersMixinsTransforms = [...bins, ...timeUnits, joinaggregateTransform];\n if (outlierLayersMixins) {\n filteredLayersMixins = {\n transform: filteredLayersMixinsTransforms,\n layer: [outlierLayersMixins, filteredWhiskerSpec]\n };\n } else {\n filteredLayersMixins = filteredWhiskerSpec;\n filteredLayersMixins.transform.unshift(...filteredLayersMixinsTransforms);\n }\n\n return {\n ...outerSpec,\n layer: [\n filteredLayersMixins,\n {\n // boxplot\n transform,\n layer: boxLayers\n }\n ]\n };\n}\n\nfunction boxParamsQuartiles(continousAxisField: string): AggregatedFieldDef[] {\n const aliasedFieldName = removePathFromField(continousAxisField);\n return [\n {\n op: 'q1',\n field: continousAxisField,\n as: `lower_box_${aliasedFieldName}`\n },\n {\n op: 'q3',\n field: continousAxisField,\n as: `upper_box_${aliasedFieldName}`\n }\n ];\n}\n\nfunction boxParams(\n spec: GenericUnitSpec, BoxPlot | BoxPlotDef>,\n extent: 'min-max' | number,\n config: Config\n) {\n const orient = compositeMarkOrient(spec, BOXPLOT);\n const {continuousAxisChannelDef, continuousAxis} = compositeMarkContinuousAxis(spec, orient, BOXPLOT);\n const continuousFieldName: string = continuousAxisChannelDef.field;\n const aliasedFieldName = removePathFromField(continuousFieldName);\n\n const boxPlotType = getBoxPlotType(extent);\n\n const boxplotSpecificAggregate: AggregatedFieldDef[] = [\n ...boxParamsQuartiles(continuousFieldName),\n {\n op: 'median',\n field: continuousFieldName,\n as: `mid_box_${aliasedFieldName}`\n },\n {\n op: 'min',\n field: continuousFieldName,\n as: (boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_') + aliasedFieldName\n },\n {\n op: 'max',\n field: continuousFieldName,\n as: (boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_') + aliasedFieldName\n }\n ];\n\n const postAggregateCalculates: CalculateTransform[] =\n boxPlotType === 'min-max' || boxPlotType === 'tukey'\n ? []\n : [\n // This is for the original k-IQR, which we do not expose\n {\n calculate: `datum[\"upper_box_${aliasedFieldName}\"] - datum[\"lower_box_${aliasedFieldName}\"]`,\n as: `iqr_${aliasedFieldName}`\n },\n {\n calculate: `min(datum[\"upper_box_${aliasedFieldName}\"] + datum[\"iqr_${aliasedFieldName}\"] * ${extent}, datum[\"max_${aliasedFieldName}\"])`,\n as: `upper_whisker_${aliasedFieldName}`\n },\n {\n calculate: `max(datum[\"lower_box_${aliasedFieldName}\"] - datum[\"iqr_${aliasedFieldName}\"] * ${extent}, datum[\"min_${aliasedFieldName}\"])`,\n as: `lower_whisker_${aliasedFieldName}`\n }\n ];\n\n const {[continuousAxis]: oldContinuousAxisChannelDef, ...oldEncodingWithoutContinuousAxis} = spec.encoding;\n const {customTooltipWithoutAggregatedField, filteredEncoding} = filterTooltipWithAggregatedField(\n oldEncodingWithoutContinuousAxis\n );\n\n const {\n bins,\n timeUnits,\n aggregate,\n groupby,\n encoding: encodingWithoutContinuousAxis\n } = extractTransformsFromEncoding(filteredEncoding, config);\n\n const ticksOrient: Orientation = orient === 'vertical' ? 'horizontal' : 'vertical';\n const boxOrient: Orientation = orient;\n\n const transform: Transform[] = [\n ...bins,\n ...timeUnits,\n {\n aggregate: [...aggregate, ...boxplotSpecificAggregate],\n groupby\n },\n ...postAggregateCalculates\n ];\n\n return {\n bins,\n timeUnits,\n transform,\n groupby,\n aggregate,\n continuousAxisChannelDef,\n continuousAxis,\n encodingWithoutContinuousAxis,\n ticksOrient,\n boxOrient,\n customTooltipWithoutAggregatedField\n };\n}\n","import {AggregateOp, Orientation, SignalRef, Text} from 'vega';\nimport {PositionChannel} from '../channel';\nimport {\n Field,\n isContinuousFieldOrDatumDef,\n isFieldOrDatumDef,\n PositionFieldDef,\n SecondaryFieldDef,\n title,\n ValueDef\n} from '../channeldef';\nimport {Config} from '../config';\nimport {Data} from '../data';\nimport {Encoding, extractTransformsFromEncoding, normalizeEncoding} from '../encoding';\nimport {ExprRef} from '../expr';\nimport * as log from '../log';\nimport {isMarkDef, MarkDef} from '../mark';\nimport {NormalizerParams} from '../normalize';\nimport {GenericUnitSpec, NormalizedLayerSpec} from '../spec';\nimport {Step} from '../spec/base';\nimport {NormalizedUnitSpec} from '../spec/unit';\nimport {TitleParams} from '../title';\nimport {AggregatedFieldDef, CalculateTransform, Transform} from '../transform';\nimport {replaceAll, titleCase} from '../util';\nimport {CompositeMarkNormalizer} from './base';\nimport {\n compositeMarkContinuousAxis,\n compositeMarkOrient,\n CompositeMarkTooltipSummary,\n GenericCompositeMarkDef,\n getCompositeMarkTooltip,\n makeCompositeAggregatePartFactory,\n PartsMixins\n} from './common';\nimport {ErrorBand, ErrorBandDef} from './errorband';\n\nexport const ERRORBAR = 'errorbar' as const;\nexport type ErrorBar = typeof ERRORBAR;\n\nexport type ErrorBarExtent = 'ci' | 'iqr' | 'stderr' | 'stdev';\nexport type ErrorBarCenter = 'mean' | 'median';\n\nexport type ErrorInputType = 'raw' | 'aggregated-upper-lower' | 'aggregated-error';\n\nexport const ERRORBAR_PARTS = ['ticks', 'rule'] as const;\n\nexport type ErrorBarPart = (typeof ERRORBAR_PARTS)[number];\n\nexport interface ErrorExtraEncoding {\n /**\n * Error value of x coordinates for error specified `\"errorbar\"` and `\"errorband\"`.\n */\n xError?: SecondaryFieldDef | ValueDef;\n\n /**\n * Secondary error value of x coordinates for error specified `\"errorbar\"` and `\"errorband\"`.\n */\n // `xError2` cannot have type as it should have the same type as `xError`\n xError2?: SecondaryFieldDef | ValueDef;\n\n /**\n * Error value of y coordinates for error specified `\"errorbar\"` and `\"errorband\"`.\n */\n yError?: SecondaryFieldDef | ValueDef;\n\n /**\n * Secondary error value of y coordinates for error specified `\"errorbar\"` and `\"errorband\"`.\n */\n // `yError2` cannot have type as it should have the same type as `yError`\n yError2?: SecondaryFieldDef | ValueDef;\n}\n\nexport type ErrorEncoding = Pick, PositionChannel | 'color' | 'detail' | 'opacity'> &\n ErrorExtraEncoding;\n\nexport type ErrorBarPartsMixins = PartsMixins;\n\nexport interface ErrorBarConfig extends ErrorBarPartsMixins {\n /** Size of the ticks of an error bar */\n size?: number;\n\n /** Thickness of the ticks and the bar of an error bar */\n thickness?: number;\n\n /**\n * The center of the errorbar. Available options include:\n * - `\"mean\"`: the mean of the data points.\n * - `\"median\"`: the median of the data points.\n *\n * __Default value:__ `\"mean\"`.\n * @hidden\n */\n\n // center is not needed right now but will be added back to the schema if future features require it.\n center?: ErrorBarCenter;\n\n /**\n * The extent of the rule. Available options include:\n * - `\"ci\"`: Extend the rule to the confidence interval of the mean.\n * - `\"stderr\"`: The size of rule are set to the value of standard error, extending from the mean.\n * - `\"stdev\"`: The size of rule are set to the value of standard deviation, extending from the mean.\n * - `\"iqr\"`: Extend the rule to the q1 and q3.\n *\n * __Default value:__ `\"stderr\"`.\n */\n extent?: ErrorBarExtent;\n}\n\nexport type ErrorBarDef = GenericCompositeMarkDef &\n ErrorBarConfig & {\n /**\n * Orientation of the error bar. This is normally automatically determined, but can be specified when the orientation is ambiguous and cannot be automatically determined.\n */\n orient?: Orientation;\n };\n\nexport interface ErrorBarConfigMixins {\n /**\n * ErrorBar Config\n */\n errorbar?: ErrorBarConfig;\n}\n\nexport const errorBarNormalizer = new CompositeMarkNormalizer(ERRORBAR, normalizeErrorBar);\n\nexport function normalizeErrorBar(\n spec: GenericUnitSpec, ErrorBar | ErrorBarDef>,\n {config}: NormalizerParams\n): NormalizedLayerSpec | NormalizedUnitSpec {\n // Need to initEncoding first so we can infer type\n spec = {\n ...spec,\n encoding: normalizeEncoding(spec.encoding, config)\n };\n\n const {\n transform,\n continuousAxisChannelDef,\n continuousAxis,\n encodingWithoutContinuousAxis,\n ticksOrient,\n markDef,\n outerSpec,\n tooltipEncoding\n } = errorBarParams(spec, ERRORBAR, config);\n delete encodingWithoutContinuousAxis['size'];\n\n const makeErrorBarPart = makeCompositeAggregatePartFactory(\n markDef,\n continuousAxis,\n continuousAxisChannelDef,\n encodingWithoutContinuousAxis,\n config.errorbar\n );\n\n const thickness = markDef.thickness;\n const size = markDef.size;\n const tick: MarkDef = {\n type: 'tick',\n orient: ticksOrient,\n aria: false,\n ...(thickness !== undefined ? {thickness} : {}),\n ...(size !== undefined ? {size} : {})\n };\n\n const layer = [\n ...makeErrorBarPart({\n partName: 'ticks',\n mark: tick,\n positionPrefix: 'lower',\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBarPart({\n partName: 'ticks',\n mark: tick,\n positionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBarPart({\n partName: 'rule',\n mark: {\n type: 'rule',\n ariaRoleDescription: 'errorbar',\n ...(thickness !== undefined ? {size: thickness} : {})\n },\n positionPrefix: 'lower',\n endPositionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n })\n ];\n\n return {\n ...outerSpec,\n transform,\n ...(layer.length > 1 ? {layer} : {...layer[0]})\n };\n}\n\nfunction errorBarOrientAndInputType(\n spec: GenericUnitSpec, ErrorBar | ErrorBand | ErrorBarDef | ErrorBandDef>,\n compositeMark: ErrorBar | ErrorBand\n): {\n orient: Orientation;\n inputType: ErrorInputType;\n} {\n const {encoding} = spec;\n\n if (errorBarIsInputTypeRaw(encoding)) {\n return {\n orient: compositeMarkOrient(spec, compositeMark),\n inputType: 'raw'\n };\n }\n\n const isTypeAggregatedUpperLower: boolean = errorBarIsInputTypeAggregatedUpperLower(encoding);\n const isTypeAggregatedError: boolean = errorBarIsInputTypeAggregatedError(encoding);\n const x = encoding.x;\n const y = encoding.y;\n\n if (isTypeAggregatedUpperLower) {\n // type is aggregated-upper-lower\n\n if (isTypeAggregatedError) {\n throw new Error(`${compositeMark} cannot be both type aggregated-upper-lower and aggregated-error`);\n }\n\n const x2 = encoding.x2;\n const y2 = encoding.y2;\n\n if (isFieldOrDatumDef(x2) && isFieldOrDatumDef(y2)) {\n // having both x, x2 and y, y2\n throw new Error(`${compositeMark} cannot have both x2 and y2`);\n } else if (isFieldOrDatumDef(x2)) {\n if (isContinuousFieldOrDatumDef(x)) {\n // having x, x2 quantitative and field y, y2 are not specified\n return {orient: 'horizontal', inputType: 'aggregated-upper-lower'};\n } else {\n // having x, x2 that are not both quantitative\n throw new Error(`Both x and x2 have to be quantitative in ${compositeMark}`);\n }\n } else if (isFieldOrDatumDef(y2)) {\n // y2 is a FieldDef\n if (isContinuousFieldOrDatumDef(y)) {\n // having y, y2 quantitative and field x, x2 are not specified\n return {orient: 'vertical', inputType: 'aggregated-upper-lower'};\n } else {\n // having y, y2 that are not both quantitative\n throw new Error(`Both y and y2 have to be quantitative in ${compositeMark}`);\n }\n }\n throw new Error('No ranged axis');\n } else {\n // type is aggregated-error\n\n const xError = encoding.xError;\n const xError2 = encoding.xError2;\n const yError = encoding.yError;\n const yError2 = encoding.yError2;\n\n if (isFieldOrDatumDef(xError2) && !isFieldOrDatumDef(xError)) {\n // having xError2 without xError\n throw new Error(`${compositeMark} cannot have xError2 without xError`);\n }\n\n if (isFieldOrDatumDef(yError2) && !isFieldOrDatumDef(yError)) {\n // having yError2 without yError\n throw new Error(`${compositeMark} cannot have yError2 without yError`);\n }\n\n if (isFieldOrDatumDef(xError) && isFieldOrDatumDef(yError)) {\n // having both xError and yError\n throw new Error(`${compositeMark} cannot have both xError and yError with both are quantiative`);\n } else if (isFieldOrDatumDef(xError)) {\n if (isContinuousFieldOrDatumDef(x)) {\n // having x and xError that are all quantitative\n return {orient: 'horizontal', inputType: 'aggregated-error'};\n } else {\n // having x, xError, and xError2 that are not all quantitative\n throw new Error('All x, xError, and xError2 (if exist) have to be quantitative');\n }\n } else if (isFieldOrDatumDef(yError)) {\n if (isContinuousFieldOrDatumDef(y)) {\n // having y and yError that are all quantitative\n return {orient: 'vertical', inputType: 'aggregated-error'};\n } else {\n // having y, yError, and yError2 that are not all quantitative\n throw new Error('All y, yError, and yError2 (if exist) have to be quantitative');\n }\n }\n throw new Error('No ranged axis');\n }\n}\n\nfunction errorBarIsInputTypeRaw(encoding: ErrorEncoding): boolean {\n return (\n (isFieldOrDatumDef(encoding.x) || isFieldOrDatumDef(encoding.y)) &&\n !isFieldOrDatumDef(encoding.x2) &&\n !isFieldOrDatumDef(encoding.y2) &&\n !isFieldOrDatumDef(encoding.xError) &&\n !isFieldOrDatumDef(encoding.xError2) &&\n !isFieldOrDatumDef(encoding.yError) &&\n !isFieldOrDatumDef(encoding.yError2)\n );\n}\n\nfunction errorBarIsInputTypeAggregatedUpperLower(encoding: ErrorEncoding): boolean {\n return isFieldOrDatumDef(encoding.x2) || isFieldOrDatumDef(encoding.y2);\n}\n\nfunction errorBarIsInputTypeAggregatedError(encoding: ErrorEncoding): boolean {\n return (\n isFieldOrDatumDef(encoding.xError) ||\n isFieldOrDatumDef(encoding.xError2) ||\n isFieldOrDatumDef(encoding.yError) ||\n isFieldOrDatumDef(encoding.yError2)\n );\n}\n\nexport function errorBarParams<\n M extends ErrorBar | ErrorBand,\n MD extends GenericCompositeMarkDef & (ErrorBarDef | ErrorBandDef)\n>(\n spec: GenericUnitSpec, M | MD>,\n compositeMark: M,\n config: Config\n): {\n transform: Transform[];\n groupby: string[];\n continuousAxisChannelDef: PositionFieldDef;\n continuousAxis: 'x' | 'y';\n encodingWithoutContinuousAxis: ErrorEncoding;\n ticksOrient: Orientation;\n markDef: MD;\n outerSpec: {\n data?: Data;\n title?: Text | TitleParams;\n name?: string;\n description?: string;\n transform?: Transform[];\n width?: number | 'container' | Step;\n height?: number | 'container' | Step;\n };\n tooltipEncoding: ErrorEncoding;\n} {\n // TODO: use selection\n const {mark, encoding, params, projection: _p, ...outerSpec} = spec;\n const markDef: MD = isMarkDef(mark) ? mark : ({type: mark} as MD);\n\n // TODO(https://github.com/vega/vega-lite/issues/3702): add selection support\n if (params) {\n log.warn(log.message.selectionNotSupported(compositeMark));\n }\n\n const {orient, inputType} = errorBarOrientAndInputType(spec, compositeMark);\n const {\n continuousAxisChannelDef,\n continuousAxisChannelDef2,\n continuousAxisChannelDefError,\n continuousAxisChannelDefError2,\n continuousAxis\n } = compositeMarkContinuousAxis(spec, orient, compositeMark);\n\n const {errorBarSpecificAggregate, postAggregateCalculates, tooltipSummary, tooltipTitleWithFieldName} =\n errorBarAggregationAndCalculation(\n markDef,\n continuousAxisChannelDef,\n continuousAxisChannelDef2,\n continuousAxisChannelDefError,\n continuousAxisChannelDefError2,\n inputType,\n compositeMark,\n config\n );\n\n const {\n [continuousAxis]: oldContinuousAxisChannelDef,\n [continuousAxis === 'x' ? 'x2' : 'y2']: oldContinuousAxisChannelDef2,\n [continuousAxis === 'x' ? 'xError' : 'yError']: oldContinuousAxisChannelDefError,\n [continuousAxis === 'x' ? 'xError2' : 'yError2']: oldContinuousAxisChannelDefError2,\n ...oldEncodingWithoutContinuousAxis\n } = encoding;\n\n const {\n bins,\n timeUnits,\n aggregate: oldAggregate,\n groupby: oldGroupBy,\n encoding: encodingWithoutContinuousAxis\n } = extractTransformsFromEncoding(oldEncodingWithoutContinuousAxis, config);\n\n const aggregate: AggregatedFieldDef[] = [...oldAggregate, ...errorBarSpecificAggregate];\n const groupby: string[] = inputType !== 'raw' ? [] : oldGroupBy;\n\n const tooltipEncoding: ErrorEncoding = getCompositeMarkTooltip(\n tooltipSummary,\n continuousAxisChannelDef,\n encodingWithoutContinuousAxis,\n tooltipTitleWithFieldName\n );\n\n return {\n transform: [\n ...(outerSpec.transform ?? []),\n ...bins,\n ...timeUnits,\n ...(aggregate.length === 0 ? [] : [{aggregate, groupby}]),\n ...postAggregateCalculates\n ],\n groupby,\n continuousAxisChannelDef,\n continuousAxis,\n encodingWithoutContinuousAxis,\n ticksOrient: orient === 'vertical' ? 'horizontal' : 'vertical',\n markDef,\n outerSpec,\n tooltipEncoding\n };\n}\n\nfunction errorBarAggregationAndCalculation<\n M extends ErrorBar | ErrorBand,\n MD extends GenericCompositeMarkDef & (ErrorBarDef | ErrorBandDef)\n>(\n markDef: MD,\n continuousAxisChannelDef: PositionFieldDef,\n continuousAxisChannelDef2: SecondaryFieldDef,\n continuousAxisChannelDefError: SecondaryFieldDef,\n continuousAxisChannelDefError2: SecondaryFieldDef,\n inputType: ErrorInputType,\n compositeMark: M,\n config: Config\n): {\n postAggregateCalculates: CalculateTransform[];\n errorBarSpecificAggregate: AggregatedFieldDef[];\n tooltipSummary: CompositeMarkTooltipSummary[];\n tooltipTitleWithFieldName: boolean;\n} {\n let errorBarSpecificAggregate: AggregatedFieldDef[] = [];\n let postAggregateCalculates: CalculateTransform[] = [];\n const continuousFieldName: string = continuousAxisChannelDef.field;\n\n let tooltipSummary: CompositeMarkTooltipSummary[];\n let tooltipTitleWithFieldName = false;\n\n if (inputType === 'raw') {\n const center: ErrorBarCenter = markDef.center\n ? markDef.center\n : markDef.extent\n ? markDef.extent === 'iqr'\n ? 'median'\n : 'mean'\n : config.errorbar.center;\n const extent: ErrorBarExtent = markDef.extent ? markDef.extent : center === 'mean' ? 'stderr' : 'iqr';\n\n if ((center === 'median') !== (extent === 'iqr')) {\n log.warn(log.message.errorBarCenterIsUsedWithWrongExtent(center, extent, compositeMark));\n }\n\n if (extent === 'stderr' || extent === 'stdev') {\n errorBarSpecificAggregate = [\n {op: extent, field: continuousFieldName, as: `extent_${continuousFieldName}`},\n {op: center, field: continuousFieldName, as: `center_${continuousFieldName}`}\n ];\n\n postAggregateCalculates = [\n {\n calculate: `datum[\"center_${continuousFieldName}\"] + datum[\"extent_${continuousFieldName}\"]`,\n as: `upper_${continuousFieldName}`\n },\n {\n calculate: `datum[\"center_${continuousFieldName}\"] - datum[\"extent_${continuousFieldName}\"]`,\n as: `lower_${continuousFieldName}`\n }\n ];\n\n tooltipSummary = [\n {fieldPrefix: 'center_', titlePrefix: titleCase(center)},\n {fieldPrefix: 'upper_', titlePrefix: getTitlePrefix(center, extent, '+')},\n {fieldPrefix: 'lower_', titlePrefix: getTitlePrefix(center, extent, '-')}\n ];\n tooltipTitleWithFieldName = true;\n } else {\n let centerOp: AggregateOp;\n let lowerExtentOp: AggregateOp;\n let upperExtentOp: AggregateOp;\n if (extent === 'ci') {\n centerOp = 'mean';\n lowerExtentOp = 'ci0';\n upperExtentOp = 'ci1';\n } else {\n centerOp = 'median';\n lowerExtentOp = 'q1';\n upperExtentOp = 'q3';\n }\n\n errorBarSpecificAggregate = [\n {op: lowerExtentOp, field: continuousFieldName, as: `lower_${continuousFieldName}`},\n {op: upperExtentOp, field: continuousFieldName, as: `upper_${continuousFieldName}`},\n {op: centerOp, field: continuousFieldName, as: `center_${continuousFieldName}`}\n ];\n\n tooltipSummary = [\n {\n fieldPrefix: 'upper_',\n titlePrefix: title({field: continuousFieldName, aggregate: upperExtentOp, type: 'quantitative'}, config, {\n allowDisabling: false\n })\n },\n {\n fieldPrefix: 'lower_',\n titlePrefix: title({field: continuousFieldName, aggregate: lowerExtentOp, type: 'quantitative'}, config, {\n allowDisabling: false\n })\n },\n {\n fieldPrefix: 'center_',\n titlePrefix: title({field: continuousFieldName, aggregate: centerOp, type: 'quantitative'}, config, {\n allowDisabling: false\n })\n }\n ];\n }\n } else {\n if (markDef.center || markDef.extent) {\n log.warn(log.message.errorBarCenterAndExtentAreNotNeeded(markDef.center, markDef.extent));\n }\n\n if (inputType === 'aggregated-upper-lower') {\n tooltipSummary = [];\n postAggregateCalculates = [\n {calculate: `datum[\"${continuousAxisChannelDef2.field}\"]`, as: `upper_${continuousFieldName}`},\n {calculate: `datum[\"${continuousFieldName}\"]`, as: `lower_${continuousFieldName}`}\n ];\n } else if (inputType === 'aggregated-error') {\n tooltipSummary = [{fieldPrefix: '', titlePrefix: continuousFieldName}];\n postAggregateCalculates = [\n {\n calculate: `datum[\"${continuousFieldName}\"] + datum[\"${continuousAxisChannelDefError.field}\"]`,\n as: `upper_${continuousFieldName}`\n }\n ];\n\n if (continuousAxisChannelDefError2) {\n postAggregateCalculates.push({\n calculate: `datum[\"${continuousFieldName}\"] + datum[\"${continuousAxisChannelDefError2.field}\"]`,\n as: `lower_${continuousFieldName}`\n });\n } else {\n postAggregateCalculates.push({\n calculate: `datum[\"${continuousFieldName}\"] - datum[\"${continuousAxisChannelDefError.field}\"]`,\n as: `lower_${continuousFieldName}`\n });\n }\n }\n\n for (const postAggregateCalculate of postAggregateCalculates) {\n tooltipSummary.push({\n fieldPrefix: postAggregateCalculate.as.substring(0, 6),\n titlePrefix: replaceAll(replaceAll(postAggregateCalculate.calculate, 'datum[\"', ''), '\"]', '')\n });\n }\n }\n return {postAggregateCalculates, errorBarSpecificAggregate, tooltipSummary, tooltipTitleWithFieldName};\n}\n\nfunction getTitlePrefix(center: ErrorBarCenter, extent: ErrorBarExtent, operation: '+' | '-'): string {\n return `${titleCase(center)} ${operation} ${extent}`;\n}\n","import {Interpolate, Orientation} from 'vega';\nimport {Field} from '../channeldef';\nimport {Encoding, normalizeEncoding} from '../encoding';\nimport * as log from '../log';\nimport {MarkDef} from '../mark';\nimport {NormalizerParams} from '../normalize';\nimport {GenericUnitSpec, NormalizedLayerSpec} from '../spec';\nimport {CompositeMarkNormalizer} from './base';\nimport {GenericCompositeMarkDef, makeCompositeAggregatePartFactory, PartsMixins} from './common';\nimport {ErrorBarCenter, ErrorBarExtent, errorBarParams, ErrorEncoding} from './errorbar';\n\nexport type ErrorBandUnitSpec<\n EE = undefined // extra encoding parameter (for faceted composite unit spec)\n> = GenericUnitSpec & EE, ErrorBand | ErrorBandDef>;\n\nexport const ERRORBAND = 'errorband' as const;\nexport type ErrorBand = typeof ERRORBAND;\n\nexport const ERRORBAND_PARTS = ['band', 'borders'] as const;\n\ntype ErrorBandPart = (typeof ERRORBAND_PARTS)[number];\n\nexport type ErrorBandPartsMixins = PartsMixins;\n\nexport interface ErrorBandConfig extends ErrorBandPartsMixins {\n /**\n * The center of the error band. Available options include:\n * - `\"mean\"`: the mean of the data points.\n * - `\"median\"`: the median of the data points.\n *\n * __Default value:__ `\"mean\"`.\n * @hidden\n */\n\n // center is not needed right now but will be added back to the schema if future features require it.\n center?: ErrorBarCenter;\n\n /**\n * The extent of the band. Available options include:\n * - `\"ci\"`: Extend the band to the confidence interval of the mean.\n * - `\"stderr\"`: The size of band are set to the value of standard error, extending from the mean.\n * - `\"stdev\"`: The size of band are set to the value of standard deviation, extending from the mean.\n * - `\"iqr\"`: Extend the band to the q1 and q3.\n *\n * __Default value:__ `\"stderr\"`.\n */\n extent?: ErrorBarExtent;\n\n /**\n * The line interpolation method for the error band. One of the following:\n * - `\"linear\"`: piecewise linear segments, as in a polyline.\n * - `\"linear-closed\"`: close the linear segments to form a polygon.\n * - `\"step\"`: a piecewise constant function (a step function) consisting of alternating horizontal and vertical lines. The y-value changes at the midpoint of each pair of adjacent x-values.\n * - `\"step-before\"`: a piecewise constant function (a step function) consisting of alternating horizontal and vertical lines. The y-value changes before the x-value.\n * - `\"step-after\"`: a piecewise constant function (a step function) consisting of alternating horizontal and vertical lines. The y-value changes after the x-value.\n * - `\"basis\"`: a B-spline, with control point duplication on the ends.\n * - `\"basis-open\"`: an open B-spline; may not intersect the start or end.\n * - `\"basis-closed\"`: a closed B-spline, as in a loop.\n * - `\"cardinal\"`: a Cardinal spline, with control point duplication on the ends.\n * - `\"cardinal-open\"`: an open Cardinal spline; may not intersect the start or end, but will intersect other control points.\n * - `\"cardinal-closed\"`: a closed Cardinal spline, as in a loop.\n * - `\"bundle\"`: equivalent to basis, except the tension parameter is used to straighten the spline.\n * - `\"monotone\"`: cubic interpolation that preserves monotonicity in y.\n */\n interpolate?: Interpolate;\n\n /**\n * The tension parameter for the interpolation type of the error band.\n *\n * @minimum 0\n * @maximum 1\n */\n tension?: number;\n}\n\nexport type ErrorBandDef = GenericCompositeMarkDef &\n ErrorBandConfig & {\n /**\n * Orientation of the error band. This is normally automatically determined, but can be specified when the orientation is ambiguous and cannot be automatically determined.\n */\n orient?: Orientation;\n };\n\nexport interface ErrorBandConfigMixins {\n /**\n * ErrorBand Config\n */\n errorband?: ErrorBandConfig;\n}\n\nexport const errorBandNormalizer = new CompositeMarkNormalizer(ERRORBAND, normalizeErrorBand);\n\nexport function normalizeErrorBand(\n spec: GenericUnitSpec, ErrorBand | ErrorBandDef>,\n {config}: NormalizerParams\n): NormalizedLayerSpec {\n // Need to initEncoding first so we can infer type\n spec = {\n ...spec,\n encoding: normalizeEncoding(spec.encoding, config)\n };\n\n const {\n transform,\n continuousAxisChannelDef,\n continuousAxis,\n encodingWithoutContinuousAxis,\n markDef,\n outerSpec,\n tooltipEncoding\n } = errorBarParams(spec, ERRORBAND, config);\n const errorBandDef: ErrorBandDef = markDef;\n\n const makeErrorBandPart = makeCompositeAggregatePartFactory(\n errorBandDef,\n continuousAxis,\n continuousAxisChannelDef,\n encodingWithoutContinuousAxis,\n config.errorband\n );\n\n const is2D = spec.encoding.x !== undefined && spec.encoding.y !== undefined;\n\n let bandMark: MarkDef = {type: is2D ? 'area' : 'rect'};\n let bordersMark: MarkDef = {type: is2D ? 'line' : 'rule'};\n const interpolate = {\n ...(errorBandDef.interpolate ? {interpolate: errorBandDef.interpolate} : {}),\n ...(errorBandDef.tension && errorBandDef.interpolate ? {tension: errorBandDef.tension} : {})\n };\n\n if (is2D) {\n bandMark = {\n ...bandMark,\n ...interpolate,\n ariaRoleDescription: 'errorband'\n };\n bordersMark = {\n ...bordersMark,\n ...interpolate,\n aria: false\n };\n } else if (errorBandDef.interpolate) {\n log.warn(log.message.errorBand1DNotSupport('interpolate'));\n } else if (errorBandDef.tension) {\n log.warn(log.message.errorBand1DNotSupport('tension'));\n }\n\n return {\n ...outerSpec,\n transform,\n layer: [\n ...makeErrorBandPart({\n partName: 'band',\n mark: bandMark,\n positionPrefix: 'lower',\n endPositionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBandPart({\n partName: 'borders',\n mark: bordersMark,\n positionPrefix: 'lower',\n\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBandPart({\n partName: 'borders',\n mark: bordersMark,\n positionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n })\n ]\n };\n}\n","import {Field} from '../channeldef';\nimport {Encoding} from '../encoding';\nimport {NormalizerParams} from '../normalize';\nimport {GenericUnitSpec, NormalizedLayerSpec} from '../spec';\nimport {EncodingFacetMapping} from '../spec/facet';\nimport {NormalizedUnitSpec} from '../spec/unit';\nimport {keys} from '../util';\nimport {CompositeMarkNormalizer} from './base';\nimport {BOXPLOT, BoxPlot, BoxPlotConfigMixins, BoxPlotDef, BOXPLOT_PARTS, normalizeBoxPlot} from './boxplot';\nimport {\n ERRORBAND,\n ErrorBand,\n ErrorBandConfigMixins,\n ErrorBandDef,\n ERRORBAND_PARTS,\n normalizeErrorBand\n} from './errorband';\nimport {\n ERRORBAR,\n ErrorBar,\n ErrorBarConfigMixins,\n ErrorBarDef,\n ERRORBAR_PARTS,\n ErrorExtraEncoding,\n normalizeErrorBar\n} from './errorbar';\n\nexport type {BoxPlotConfig} from './boxplot';\nexport type {ErrorBandConfigMixins} from './errorband';\nexport type {ErrorBarConfigMixins} from './errorbar';\n\nexport type CompositeMarkNormalizerRun = (\n spec: GenericUnitSpec,\n params: NormalizerParams\n) => NormalizedLayerSpec | NormalizedUnitSpec;\n\n/**\n * Registry index for all composite mark's normalizer\n */\nconst compositeMarkRegistry: {\n [mark: string]: {\n normalizer: CompositeMarkNormalizer;\n parts: readonly string[];\n };\n} = {};\n\nexport function add(mark: string, run: CompositeMarkNormalizerRun, parts: readonly string[]) {\n const normalizer = new CompositeMarkNormalizer(mark, run);\n compositeMarkRegistry[mark] = {normalizer, parts};\n}\n\nexport function remove(mark: string) {\n delete compositeMarkRegistry[mark];\n}\n\nexport type CompositeEncoding = Encoding & ErrorExtraEncoding;\n\nexport type PartialIndex> = {\n [t in keyof T]?: Partial;\n};\n\nexport type SharedCompositeEncoding = PartialIndex<\n Omit, 'detail' | 'order' | 'tooltip'> // need to omit and cherry pick detail / order / tooltip since they allow array\n> &\n Pick, 'detail' | 'order' | 'tooltip'>;\n\nexport type FacetedCompositeEncoding = Encoding & ErrorExtraEncoding & EncodingFacetMapping;\n\nexport type CompositeMark = BoxPlot | ErrorBar | ErrorBand;\n\nexport function getAllCompositeMarks() {\n return keys(compositeMarkRegistry);\n}\n\nexport type CompositeMarkDef = BoxPlotDef | ErrorBarDef | ErrorBandDef;\n\nexport type CompositeAggregate = BoxPlot | ErrorBar | ErrorBand;\n\nexport interface CompositeMarkConfigMixins extends BoxPlotConfigMixins, ErrorBarConfigMixins, ErrorBandConfigMixins {}\n\nadd(BOXPLOT, normalizeBoxPlot, BOXPLOT_PARTS);\nadd(ERRORBAR, normalizeErrorBar, ERRORBAR_PARTS);\nadd(ERRORBAND, normalizeErrorBand, ERRORBAND_PARTS);\n","import {SignalRef, Text} from 'vega';\nimport {ConditionValueDefMixins, FormatMixins, ValueDef} from './channeldef';\nimport {LegendConfig} from './legend';\nimport {VgEncodeChannel} from './vega.schema';\n\nexport interface TitleMixins {\n /**\n * A title for the field. If `null`, the title will be removed.\n *\n * __Default value:__ derived from the field's name and transformation function (`aggregate`, `bin` and `timeUnit`). If the field has an aggregate function, the function is displayed as part of the title (e.g., `\"Sum of Profit\"`). If the field is binned or has a time unit applied, the applied function is shown in parentheses (e.g., `\"Profit (binned)\"`, `\"Transaction Date (year-month)\"`). Otherwise, the title is simply the field name.\n *\n * __Notes__:\n *\n * 1) You can customize the default field title format by providing the [`fieldTitle`](https://vega.github.io/vega-lite/docs/config.html#top-level-config) property in the [config](https://vega.github.io/vega-lite/docs/config.html) or [`fieldTitle` function via the `compile` function's options](https://vega.github.io/vega-lite/usage/compile.html#field-title).\n *\n * 2) If both field definition's `title` and axis, header, or legend `title` are defined, axis/header/legend title will be used.\n */\n title?: Text | null | SignalRef;\n}\n\nexport interface Guide extends TitleMixins, FormatMixins {}\n\nexport interface VlOnlyGuideConfig {\n /**\n * Set to null to disable title for the axis, legend, or header.\n */\n title?: null;\n}\n\nexport type GuideEncodingConditionalValueDef = ValueDef & ConditionValueDefMixins;\n\nexport type GuideEncodingEntry = Partial>;\n\nexport const VL_ONLY_LEGEND_CONFIG: (keyof LegendConfig)[] = [\n 'gradientHorizontalMaxLength',\n 'gradientHorizontalMinLength',\n 'gradientVerticalMaxLength',\n 'gradientVerticalMinLength',\n 'unselectedOpacity'\n];\n","import {Align, Color, FontStyle, FontWeight, Orient, SignalRef, TextBaseline, TitleAnchor, TitleConfig} from 'vega';\nimport {FormatMixins} from './channeldef';\nimport {ExprRef} from './expr';\nimport {Guide, VlOnlyGuideConfig} from './guide';\nimport {Flag, keys} from './util';\n\nexport const HEADER_TITLE_PROPERTIES_MAP: Partial, keyof TitleConfig>> = {\n titleAlign: 'align',\n titleAnchor: 'anchor',\n titleAngle: 'angle',\n titleBaseline: 'baseline',\n titleColor: 'color',\n titleFont: 'font',\n titleFontSize: 'fontSize',\n titleFontStyle: 'fontStyle',\n titleFontWeight: 'fontWeight',\n titleLimit: 'limit',\n titleLineHeight: 'lineHeight',\n titleOrient: 'orient',\n titlePadding: 'offset'\n};\n\nexport const HEADER_LABEL_PROPERTIES_MAP: Partial, keyof TitleConfig>> = {\n labelAlign: 'align',\n labelAnchor: 'anchor',\n labelAngle: 'angle',\n labelBaseline: 'baseline',\n labelColor: 'color',\n labelFont: 'font',\n labelFontSize: 'fontSize',\n labelFontStyle: 'fontStyle',\n labelFontWeight: 'fontWeight',\n labelLimit: 'limit',\n labelLineHeight: 'lineHeight',\n labelOrient: 'orient',\n labelPadding: 'offset'\n};\n\nexport const HEADER_TITLE_PROPERTIES = keys(HEADER_TITLE_PROPERTIES_MAP);\n\nexport const HEADER_LABEL_PROPERTIES = keys(HEADER_LABEL_PROPERTIES_MAP);\n\nexport interface CoreHeader extends FormatMixins {\n // ---------- Title ----------\n /**\n * The anchor position for placing the title. One of `\"start\"`, `\"middle\"`, or `\"end\"`. For example, with an orientation of top these anchor positions map to a left-, center-, or right-aligned title.\n */\n titleAnchor?: TitleAnchor; // We don't allow signal for titleAnchor since there is a dependent logic\n\n /**\n * Horizontal text alignment (to the anchor) of header titles.\n */\n titleAlign?: Align | ES;\n\n /**\n * The rotation angle of the header title.\n *\n * __Default value:__ `0`.\n *\n * @minimum -360\n * @maximum 360\n */\n titleAngle?: number; // We don't allow signal for titleAngle since there is a dependent logic\n\n /**\n * The vertical text baseline for the header title. One of `\"alphabetic\"` (default), `\"top\"`, `\"middle\"`, `\"bottom\"`, `\"line-top\"`, or `\"line-bottom\"`.\n * The `\"line-top\"` and `\"line-bottom\"` values operate similarly to `\"top\"` and `\"bottom\"`, but are calculated relative to the `titleLineHeight` rather than `titleFontSize` alone.\n *\n * __Default value:__ `\"middle\"`\n */\n titleBaseline?: TextBaseline | ES;\n\n /**\n * Color of the header title, can be in hex color code or regular color name.\n */\n titleColor?: Color | ES;\n\n /**\n * Font of the header title. (e.g., `\"Helvetica Neue\"`).\n */\n titleFont?: string | ES;\n\n /**\n * Font size of the header title.\n *\n * @minimum 0\n */\n titleFontSize?: number | ES;\n\n /**\n * The font style of the header title.\n */\n titleFontStyle?: FontStyle | ES;\n\n /**\n * Font weight of the header title.\n * This can be either a string (e.g `\"bold\"`, `\"normal\"`) or a number (`100`, `200`, `300`, ..., `900` where `\"normal\"` = `400` and `\"bold\"` = `700`).\n */\n titleFontWeight?: FontWeight | ES;\n\n /**\n * The maximum length of the header title in pixels. The text value will be automatically truncated if the rendered size exceeds the limit.\n *\n * __Default value:__ `0`, indicating no limit\n */\n titleLimit?: number | ES;\n\n /**\n * Line height in pixels for multi-line header title text or title text with `\"line-top\"` or `\"line-bottom\"` baseline.\n */\n titleLineHeight?: number | ES;\n\n /**\n * The orientation of the header title. One of `\"top\"`, `\"bottom\"`, `\"left\"` or `\"right\"`.\n */\n titleOrient?: Orient; // no signal ref since there is a dependent logic\n\n /**\n * The padding, in pixel, between facet header's title and the label.\n *\n * __Default value:__ `10`\n */\n titlePadding?: number | ES;\n\n // ---------- Label ----------\n\n /**\n * A boolean flag indicating if labels should be included as part of the header.\n *\n * __Default value:__ `true`.\n */\n labels?: boolean;\n\n /**\n * Horizontal text alignment of header labels. One of `\"left\"`, `\"center\"`, or `\"right\"`.\n */\n labelAlign?: Align | ES;\n\n /**\n * The vertical text baseline for the header labels. One of `\"alphabetic\"` (default), `\"top\"`, `\"middle\"`, `\"bottom\"`, `\"line-top\"`, or `\"line-bottom\"`.\n * The `\"line-top\"` and `\"line-bottom\"` values operate similarly to `\"top\"` and `\"bottom\"`, but are calculated relative to the `titleLineHeight` rather than `titleFontSize` alone.\n *\n */\n labelBaseline?: TextBaseline | ES;\n\n /**\n * The anchor position for placing the labels. One of `\"start\"`, `\"middle\"`, or `\"end\"`. For example, with a label orientation of top these anchor positions map to a left-, center-, or right-aligned label.\n */\n labelAnchor?: TitleAnchor;\n\n /**\n * [Vega expression](https://vega.github.io/vega/docs/expressions/) for customizing labels.\n *\n * __Note:__ The label text and value can be assessed via the `label` and `value` properties of the header's backing `datum` object.\n */\n labelExpr?: string;\n\n /**\n * The rotation angle of the header labels.\n *\n * __Default value:__ `0` for column header, `-90` for row header.\n *\n * @minimum -360\n * @maximum 360\n */\n labelAngle?: number; // no signal ref since there is a dependent logic\n\n /**\n * The color of the header label, can be in hex color code or regular color name.\n */\n labelColor?: Color | ES;\n\n /**\n * The font of the header label.\n */\n labelFont?: string | ES;\n\n /**\n * The font size of the header label, in pixels.\n *\n * @minimum 0\n */\n labelFontSize?: number | ES;\n\n /**\n * The font style of the header label.\n */\n labelFontStyle?: FontStyle | ES;\n\n /**\n * The font weight of the header label.\n */\n labelFontWeight?: FontWeight | ES;\n\n /**\n * The maximum length of the header label in pixels. The text value will be automatically truncated if the rendered size exceeds the limit.\n *\n * __Default value:__ `0`, indicating no limit\n */\n labelLimit?: number | ES;\n\n /**\n * Line height in pixels for multi-line header labels or title text with `\"line-top\"` or `\"line-bottom\"` baseline.\n */\n labelLineHeight?: number | ES;\n\n /**\n * The orientation of the header label. One of `\"top\"`, `\"bottom\"`, `\"left\"` or `\"right\"`.\n */\n labelOrient?: Orient; // no signal ref since there is a dependent logic\n\n /**\n * The padding, in pixel, between facet header's label and the plot.\n *\n * __Default value:__ `10`\n */\n labelPadding?: number | ES;\n\n /**\n * Shortcut for setting both labelOrient and titleOrient.\n */\n orient?: Orient; // no signal ref since there is a dependent logic\n}\n\nexport interface HeaderConfig extends CoreHeader, VlOnlyGuideConfig {}\n\n/**\n * Headers of row / column channels for faceted plots.\n */\nexport interface Header extends CoreHeader, Guide {}\n\nexport interface HeaderConfigMixins {\n /**\n * Header configuration, which determines default properties for all [headers](https://vega.github.io/vega-lite/docs/header.html).\n *\n * For a full list of header configuration options, please see the [corresponding section of in the header documentation](https://vega.github.io/vega-lite/docs/header.html#config).\n */\n header?: HeaderConfig;\n\n /**\n * Header configuration, which determines default properties for row [headers](https://vega.github.io/vega-lite/docs/header.html).\n *\n * For a full list of header configuration options, please see the [corresponding section of in the header documentation](https://vega.github.io/vega-lite/docs/header.html#config).\n */\n headerRow?: HeaderConfig;\n\n /**\n * Header configuration, which determines default properties for column [headers](https://vega.github.io/vega-lite/docs/header.html).\n *\n * For a full list of header configuration options, please see the [corresponding section of in the header documentation](https://vega.github.io/vega-lite/docs/header.html#config).\n */\n headerColumn?: HeaderConfig;\n\n /**\n * Header configuration, which determines default properties for non-row/column facet [headers](https://vega.github.io/vega-lite/docs/header.html).\n *\n * For a full list of header configuration options, please see the [corresponding section of in the header documentation](https://vega.github.io/vega-lite/docs/header.html#config).\n */\n headerFacet?: HeaderConfig;\n}\n\nconst HEADER_CONFIGS_INDEX: Flag> = {\n header: 1,\n headerRow: 1,\n headerColumn: 1,\n headerFacet: 1\n};\n\nexport const HEADER_CONFIGS = keys(HEADER_CONFIGS_INDEX);\n","import {\n BaseLegend,\n LabelOverlap,\n Legend as VgLegend,\n LegendConfig as VgLegendConfig,\n LegendOrient,\n Orientation,\n SignalRef\n} from 'vega';\nimport {DateTime} from './datetime';\nimport {ExprRef} from './expr';\nimport {Guide, GuideEncodingEntry, VlOnlyGuideConfig} from './guide';\nimport {Flag, keys} from './util';\nimport {MapExcludeValueRefAndReplaceSignalWith} from './vega.schema';\n\nexport const LEGEND_SCALE_CHANNELS = [\n 'size',\n 'shape',\n 'fill',\n 'stroke',\n 'strokeDash',\n 'strokeWidth',\n 'opacity'\n] as const;\n\ntype BaseLegendNoValueRefs = MapExcludeValueRefAndReplaceSignalWith;\n\nexport type LegendConfig = LegendMixins &\n VlOnlyGuideConfig &\n MapExcludeValueRefAndReplaceSignalWith & {\n /**\n * Max legend length for a vertical gradient when `config.legend.gradientLength` is undefined.\n *\n * __Default value:__ `200`\n */\n gradientVerticalMaxLength?: number;\n\n /**\n * Min legend length for a vertical gradient when `config.legend.gradientLength` is undefined.\n *\n * __Default value:__ `100`\n */\n gradientVerticalMinLength?: number;\n\n /**\n * Max legend length for a horizontal gradient when `config.legend.gradientLength` is undefined.\n *\n * __Default value:__ `200`\n */\n gradientHorizontalMaxLength?: number;\n\n /**\n * Min legend length for a horizontal gradient when `config.legend.gradientLength` is undefined.\n *\n * __Default value:__ `100`\n */\n gradientHorizontalMinLength?: number;\n\n /**\n * The length in pixels of the primary axis of a color gradient. This value corresponds to the height of a vertical gradient or the width of a horizontal gradient.\n *\n * __Default value:__ `undefined`. If `undefined`, the default gradient will be determined based on the following rules:\n * - For vertical gradients, `clamp(plot_height, gradientVerticalMinLength, gradientVerticalMaxLength)`\n * - For top-`orient`ed or bottom-`orient`ed horizontal gradients, `clamp(plot_width, gradientHorizontalMinLength, gradientHorizontalMaxLength)`\n * - For other horizontal gradients, `gradientHorizontalMinLength`\n *\n * where `clamp(value, min, max)` restricts _value_ to be between the specified _min_ and _max_.\n * @minimum 0\n */\n gradientLength?: number;\n\n /**\n * The opacity of unselected legend entries.\n *\n * __Default value:__ 0.35.\n */\n unselectedOpacity?: number;\n\n /**\n * Disable legend by default\n */\n disable?: boolean;\n };\n\n/**\n * Properties of a legend or boolean flag for determining whether to show it.\n */\nexport interface Legend\n extends Omit, 'orient'>,\n LegendMixins,\n Guide {\n /**\n * Mark definitions for custom legend encoding.\n *\n * @hidden\n */\n encoding?: LegendEncoding;\n\n /**\n * [Vega expression](https://vega.github.io/vega/docs/expressions/) for customizing labels.\n *\n * __Note:__ The label text and value can be assessed via the `label` and `value` properties of the legend's backing `datum` object.\n */\n labelExpr?: string;\n\n /**\n * The minimum desired step between legend ticks, in terms of scale domain values. For example, a value of `1` indicates that ticks should not be less than 1 unit apart. If `tickMinStep` is specified, the `tickCount` value will be adjusted, if necessary, to enforce the minimum step value.\n *\n * __Default value__: `undefined`\n */\n tickMinStep?: number | ES;\n\n /**\n * Explicitly set the visible legend values.\n */\n values?: number[] | string[] | boolean[] | DateTime[] | ES; // Vega already supports Signal -- we have to re-declare here since VL supports special Date Time object that's not valid in Vega.\n\n /**\n * The type of the legend. Use `\"symbol\"` to create a discrete legend and `\"gradient\"` for a continuous color gradient.\n *\n * __Default value:__ `\"gradient\"` for non-binned quantitative fields and temporal fields; `\"symbol\"` otherwise.\n */\n type?: 'symbol' | 'gradient';\n\n /**\n * A non-negative integer indicating the z-index of the legend.\n * If zindex is 0, legend should be drawn behind all chart elements.\n * To put them in front, use zindex = 1.\n *\n * @TJS-type integer\n * @minimum 0\n */\n zindex?: number;\n}\n\n// Change comments to be Vega-Lite specific\ninterface LegendMixins {\n /**\n * The strategy to use for resolving overlap of labels in gradient legends. If `false`, no overlap reduction is attempted. If set to `true` or `\"parity\"`, a strategy of removing every other label is used. If set to `\"greedy\"`, a linear scan of the labels is performed, removing any label that overlaps with the last visible label (this often works better for log-scaled axes).\n *\n * __Default value:__ `\"greedy\"` for `log scales otherwise `true`.\n */\n labelOverlap?: LabelOverlap | ES; // override comment since our default differs from Vega\n\n /**\n * The direction of the legend, one of `\"vertical\"` or `\"horizontal\"`.\n *\n * __Default value:__\n * - For top-/bottom-`orient`ed legends, `\"horizontal\"`\n * - For left-/right-`orient`ed legends, `\"vertical\"`\n * - For top/bottom-left/right-`orient`ed legends, `\"horizontal\"` for gradient legends and `\"vertical\"` for symbol legends.\n */\n direction?: Orientation; // Omit SignalRef\n\n /**\n * The orientation of the legend, which determines how the legend is positioned within the scene. One of `\"left\"`, `\"right\"`, `\"top\"`, `\"bottom\"`, `\"top-left\"`, `\"top-right\"`, `\"bottom-left\"`, `\"bottom-right\"`, `\"none\"`.\n *\n * __Default value:__ `\"right\"`\n */\n orient?: LegendOrient; // Omit SignalRef\n}\n\nexport type LegendInternal = Legend;\n\nexport interface LegendEncoding {\n /**\n * Custom encoding for the legend container.\n * This can be useful for creating legend with custom x, y position.\n */\n legend?: GuideEncodingEntry;\n\n /**\n * Custom encoding for the legend title text mark.\n */\n title?: GuideEncodingEntry;\n\n /**\n * Custom encoding for legend label text marks.\n */\n labels?: GuideEncodingEntry;\n\n /**\n * Custom encoding for legend symbol marks.\n */\n symbols?: GuideEncodingEntry;\n\n /**\n * Custom encoding for legend gradient filled rect marks.\n */\n gradient?: GuideEncodingEntry;\n}\n\nexport const defaultLegendConfig: LegendConfig = {\n gradientHorizontalMaxLength: 200,\n gradientHorizontalMinLength: 100,\n gradientVerticalMaxLength: 200,\n gradientVerticalMinLength: 64, // This is Vega's minimum.\n unselectedOpacity: 0.35\n};\n\nexport const COMMON_LEGEND_PROPERTY_INDEX: Flag)> = {\n aria: 1,\n clipHeight: 1,\n columnPadding: 1,\n columns: 1,\n cornerRadius: 1,\n description: 1,\n direction: 1,\n fillColor: 1,\n format: 1,\n formatType: 1,\n gradientLength: 1,\n gradientOpacity: 1,\n gradientStrokeColor: 1,\n gradientStrokeWidth: 1,\n gradientThickness: 1,\n gridAlign: 1,\n labelAlign: 1,\n labelBaseline: 1,\n labelColor: 1,\n labelFont: 1,\n labelFontSize: 1,\n labelFontStyle: 1,\n labelFontWeight: 1,\n labelLimit: 1,\n labelOffset: 1,\n labelOpacity: 1,\n labelOverlap: 1,\n labelPadding: 1,\n labelSeparation: 1,\n legendX: 1,\n legendY: 1,\n offset: 1,\n orient: 1,\n padding: 1,\n rowPadding: 1,\n strokeColor: 1,\n symbolDash: 1,\n symbolDashOffset: 1,\n symbolFillColor: 1,\n symbolLimit: 1,\n symbolOffset: 1,\n symbolOpacity: 1,\n symbolSize: 1,\n symbolStrokeColor: 1,\n symbolStrokeWidth: 1,\n symbolType: 1,\n tickCount: 1,\n tickMinStep: 1,\n title: 1,\n titleAlign: 1,\n titleAnchor: 1,\n titleBaseline: 1,\n titleColor: 1,\n titleFont: 1,\n titleFontSize: 1,\n titleFontStyle: 1,\n titleFontWeight: 1,\n titleLimit: 1,\n titleLineHeight: 1,\n titleOpacity: 1,\n titleOrient: 1,\n titlePadding: 1,\n type: 1,\n values: 1,\n zindex: 1\n};\n\nexport const LEGEND_PROPERTIES = keys(COMMON_LEGEND_PROPERTY_INDEX);\n","import {Binding, Color, Cursor, Stream, Vector2} from 'vega';\nimport {isObject} from 'vega-util';\nimport {SingleDefUnitChannel} from './channel';\nimport {FieldName, PrimitiveValue} from './channeldef';\nimport {DateTime} from './datetime';\nimport {ParameterName} from './parameter';\nimport {Dict} from './util';\n\nexport const SELECTION_ID = '_vgsid_';\nexport type SelectionType = 'point' | 'interval';\nexport type SelectionResolution = 'global' | 'union' | 'intersect';\n\nexport type SelectionInit = PrimitiveValue | DateTime;\nexport type SelectionInitInterval = Vector2 | Vector2 | Vector2 | Vector2;\n\nexport type SelectionInitMapping = Dict;\nexport type SelectionInitIntervalMapping = Dict;\n\nexport type LegendStreamBinding = {legend: string | Stream};\nexport type LegendBinding = 'legend' | LegendStreamBinding;\n\nexport interface BaseSelectionConfig {\n /**\n * Determines the default event processing and data query for the selection. Vega-Lite currently supports two selection types:\n *\n * - `\"point\"` -- to select multiple discrete data values; the first value is selected on `click` and additional values toggled on shift-click.\n * - `\"interval\"` -- to select a continuous range of data values on `drag`.\n */\n type: T;\n\n /**\n * Clears the selection, emptying it of all values. This property can be a\n * [Event Stream](https://vega.github.io/vega/docs/event-streams/) or `false` to disable clear.\n *\n * __Default value:__ `dblclick`.\n *\n * __See also:__ [`clear` examples ](https://vega.github.io/vega-lite/docs/selection.html#clear) in the documentation.\n */\n clear?: Stream | string | boolean;\n\n /**\n * A [Vega event stream](https://vega.github.io/vega/docs/event-streams/) (object or selector) that triggers the selection.\n * For interval selections, the event stream must specify a [start and end](https://vega.github.io/vega/docs/event-streams/#between-filters).\n *\n * __See also:__ [`on` examples](https://vega.github.io/vega-lite/docs/selection.html#on) in the documentation.\n */\n on?: Stream | string;\n\n /**\n * With layered and multi-view displays, a strategy that determines how\n * selections' data queries are resolved when applied in a filter transform,\n * conditional encoding rule, or scale domain.\n *\n * One of:\n * - `\"global\"` -- only one brush exists for the entire SPLOM. When the user begins to drag, any previous brushes are cleared, and a new one is constructed.\n * - `\"union\"` -- each cell contains its own brush, and points are highlighted if they lie within _any_ of these individual brushes.\n * - `\"intersect\"` -- each cell contains its own brush, and points are highlighted only if they fall within _all_ of these individual brushes.\n *\n * __Default value:__ `global`.\n *\n * __See also:__ [`resolve` examples](https://vega.github.io/vega-lite/docs/selection.html#resolve) in the documentation.\n */\n resolve?: SelectionResolution;\n\n // TODO(https://github.com/vega/vega-lite/issues/2596).\n // predicate?: string;\n // domain?: SelectionDomain;\n\n /**\n * An array of encoding channels. The corresponding data field values\n * must match for a data tuple to fall within the selection.\n *\n * __See also:__ The [projection with `encodings` and `fields` section](https://vega.github.io/vega-lite/docs/selection.html#project) in the documentation.\n */\n encodings?: SingleDefUnitChannel[];\n\n /**\n * An array of field names whose values must match for a data tuple to\n * fall within the selection.\n *\n * __See also:__ The [projection with `encodings` and `fields` section](https://vega.github.io/vega-lite/docs/selection.html#project) in the documentation.\n */\n fields?: FieldName[];\n}\n\nexport interface PointSelectionConfig extends BaseSelectionConfig<'point'> {\n /**\n * Controls whether data values should be toggled (inserted or removed from a point selection)\n * or only ever inserted into point selections.\n *\n * One of:\n * - `true` -- the default behavior, which corresponds to `\"event.shiftKey\"`. As a result, data values are toggled when the user interacts with the shift-key pressed.\n * - `false` -- disables toggling behaviour; the selection will only ever contain a single data value corresponding to the most recent interaction.\n * - A [Vega expression](https://vega.github.io/vega/docs/expressions/) which is re-evaluated as the user interacts. If the expression evaluates to `true`, the data value is toggled into or out of the point selection. If the expression evaluates to `false`, the point selection is first cleared, and the data value is then inserted. For example, setting the value to the Vega expression `\"true\"` will toggle data values\n * without the user pressing the shift-key.\n *\n * __Default value:__ `true`\n *\n * __See also:__ [`toggle` examples](https://vega.github.io/vega-lite/docs/selection.html#toggle) in the documentation.\n */\n toggle?: string | boolean;\n\n /**\n * When true, an invisible voronoi diagram is computed to accelerate discrete\n * selection. The data value _nearest_ the mouse cursor is added to the selection.\n *\n * __Default value:__ `false`, which means that data values must be interacted with directly (e.g., clicked on) to be added to the selection.\n *\n * __See also:__ [`nearest` examples](https://vega.github.io/vega-lite/docs/selection.html#nearest) documentation.\n */\n nearest?: boolean;\n}\n\n// Similar to BaseMarkConfig but the field documentations are specificly for an interval mark.\nexport interface BrushConfig {\n /**\n * The fill color of the interval mark.\n *\n * __Default value:__ `\"#333333\"`\n *\n */\n fill?: Color;\n\n /**\n * The fill opacity of the interval mark (a value between `0` and `1`).\n *\n * __Default value:__ `0.125`\n */\n fillOpacity?: number;\n\n /**\n * The stroke color of the interval mark.\n *\n * __Default value:__ `\"#ffffff\"`\n */\n stroke?: Color;\n\n /**\n * The stroke opacity of the interval mark (a value between `0` and `1`).\n */\n strokeOpacity?: number;\n\n /**\n * The stroke width of the interval mark.\n */\n strokeWidth?: number;\n\n /**\n * An array of alternating stroke and space lengths, for creating dashed or dotted lines.\n */\n strokeDash?: number[];\n\n /**\n * The offset (in pixels) with which to begin drawing the stroke dash array.\n */\n strokeDashOffset?: number;\n\n /**\n * The mouse cursor used over the interval mark. Any valid [CSS cursor type](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values) can be used.\n */\n cursor?: Cursor;\n}\n\nexport interface IntervalSelectionConfig extends BaseSelectionConfig<'interval'> {\n /**\n * When truthy, allows a user to interactively move an interval selection\n * back-and-forth. Can be `true`, `false` (to disable panning), or a\n * [Vega event stream definition](https://vega.github.io/vega/docs/event-streams/)\n * which must include a start and end event to trigger continuous panning.\n * Discrete panning (e.g., pressing the left/right arrow keys) will be supported in future versions.\n *\n * __Default value:__ `true`, which corresponds to `[pointerdown, window:pointerup] > window:pointermove!`.\n * This default allows users to clicks and drags within an interval selection to reposition it.\n *\n * __See also:__ [`translate` examples](https://vega.github.io/vega-lite/docs/selection.html#translate) in the documentation.\n */\n translate?: string | boolean;\n\n /**\n * When truthy, allows a user to interactively resize an interval selection.\n * Can be `true`, `false` (to disable zooming), or a [Vega event stream\n * definition](https://vega.github.io/vega/docs/event-streams/). Currently,\n * only `wheel` events are supported,\n * but custom event streams can still be used to specify filters, debouncing, and throttling.\n * Future versions will expand the set of events that can trigger this transformation.\n *\n * __Default value:__ `true`, which corresponds to `wheel!`. This default allows users to use the mouse wheel to resize an interval selection.\n *\n * __See also:__ [`zoom` examples](https://vega.github.io/vega-lite/docs/selection.html#zoom) in the documentation.\n */\n zoom?: string | boolean;\n\n /**\n * An interval selection also adds a rectangle mark to depict the\n * extents of the interval. The `mark` property can be used to customize the\n * appearance of the mark.\n *\n * __See also:__ [`mark` examples](https://vega.github.io/vega-lite/docs/selection.html#mark) in the documentation.\n */\n mark?: BrushConfig;\n}\n\nexport interface SelectionParameter {\n /**\n * Required. A unique name for the selection parameter. Selection names should be valid JavaScript identifiers: they should contain only alphanumeric characters (or \"$\", or \"_\") and may not start with a digit. Reserved keywords that may not be used as parameter names are \"datum\", \"event\", \"item\", and \"parent\".\n */\n name: ParameterName;\n\n /**\n * Determines the default event processing and data query for the selection. Vega-Lite currently supports two selection types:\n *\n * - `\"point\"` -- to select multiple discrete data values; the first value is selected on `click` and additional values toggled on shift-click.\n * - `\"interval\"` -- to select a continuous range of data values on `drag`.\n */\n select: T | (T extends 'point' ? PointSelectionConfig : T extends 'interval' ? IntervalSelectionConfig : never);\n\n /**\n * Initialize the selection with a mapping between [projected channels or field names](https://vega.github.io/vega-lite/docs/selection.html#project) and initial values.\n *\n * __See also:__ [`init`](https://vega.github.io/vega-lite/docs/value.html) documentation.\n */\n value?: T extends 'point'\n ? SelectionInit | SelectionInitMapping[]\n : T extends 'interval'\n ? SelectionInitIntervalMapping\n : never;\n\n /**\n * When set, a selection is populated by input elements (also known as dynamic query widgets)\n * or by interacting with the corresponding legend. Direct manipulation interaction is disabled by default;\n * to re-enable it, set the selection's [`on`](https://vega.github.io/vega-lite/docs/selection.html#common-selection-properties) property.\n *\n * Legend bindings are restricted to selections that only specify a single field or encoding.\n *\n * Query widget binding takes the form of Vega's [input element binding definition](https://vega.github.io/vega/docs/signals/#bind)\n * or can be a mapping between projected field/encodings and binding definitions.\n *\n * __See also:__ [`bind`](https://vega.github.io/vega-lite/docs/bind.html) documentation.\n */\n bind?: T extends 'point'\n ? Binding | Record | LegendBinding\n : T extends 'interval'\n ? 'scales'\n : never;\n}\n\nexport type TopLevelSelectionParameter = SelectionParameter & {\n /**\n * By default, top-level selections are applied to every view in the visualization.\n * If this property is specified, selections will only be applied to views with the given names.\n */\n views?: string[];\n};\n\nexport type ParameterExtent =\n | {\n /**\n * The name of a parameter.\n */\n param: ParameterName;\n\n /**\n * If a selection parameter is specified, the field name to extract selected values for\n * when the selection is [projected](https://vega.github.io/vega-lite/docs/selection.html#project) over multiple fields or encodings.\n */\n field?: FieldName;\n }\n | {\n /**\n * The name of a parameter.\n */\n param: ParameterName;\n\n /**\n * If a selection parameter is specified, the encoding channel to extract selected values for\n * when a selection is [projected](https://vega.github.io/vega-lite/docs/selection.html#project) over multiple fields or encodings.\n */\n encoding?: SingleDefUnitChannel;\n };\n\nexport type PointSelectionConfigWithoutType = Omit;\n\nexport type IntervalSelectionConfigWithoutType = Omit;\n\nexport interface SelectionConfig {\n /**\n * The default definition for a [`point`](https://vega.github.io/vega-lite/docs/parameter.html#select) selection. All properties and transformations\n * for a point selection definition (except `type`) may be specified here.\n *\n * For instance, setting `point` to `{\"on\": \"dblclick\"}` populates point selections on double-click by default.\n */\n point?: PointSelectionConfigWithoutType;\n\n /**\n * The default definition for an [`interval`](https://vega.github.io/vega-lite/docs/parameter.html#select) selection. All properties and transformations\n * for an interval selection definition (except `type`) may be specified here.\n *\n * For instance, setting `interval` to `{\"translate\": false}` disables the ability to move\n * interval selections by default.\n */\n interval?: IntervalSelectionConfigWithoutType;\n}\n\nexport const defaultConfig: SelectionConfig = {\n point: {\n on: 'click',\n fields: [SELECTION_ID],\n toggle: 'event.shiftKey',\n resolve: 'global',\n clear: 'dblclick'\n },\n interval: {\n on: '[pointerdown, window:pointerup] > window:pointermove!',\n encodings: ['x', 'y'],\n translate: '[pointerdown, window:pointerup] > window:pointermove!',\n zoom: 'wheel!',\n mark: {fill: '#333', fillOpacity: 0.125, stroke: 'white'},\n resolve: 'global',\n clear: 'dblclick'\n }\n};\n\nexport function isLegendBinding(bind: any): bind is LegendBinding {\n return bind === 'legend' || !!bind?.legend;\n}\n\nexport function isLegendStreamBinding(bind: any): bind is LegendStreamBinding {\n return isLegendBinding(bind) && isObject(bind);\n}\n\nexport function isSelectionParameter(param: any): param is SelectionParameter {\n return !!param?.['select'];\n}\n","import {Binding, Expr, InitSignal, NewSignal} from 'vega';\nimport {isSelectionParameter, TopLevelSelectionParameter} from './selection';\n\nexport type ParameterName = string;\n\nexport interface VariableParameter {\n /**\n * A unique name for the variable parameter. Parameter names should be valid JavaScript identifiers: they should contain only alphanumeric characters (or \"$\", or \"_\") and may not start with a digit. Reserved keywords that may not be used as parameter names are \"datum\", \"event\", \"item\", and \"parent\".\n */\n name: ParameterName;\n\n /**\n * The [initial value](http://vega.github.io/vega-lite/docs/value.html) of the parameter.\n *\n * __Default value:__ `undefined`\n */\n value?: any;\n\n /**\n * An expression for the value of the parameter. This expression may include other parameters, in which case the parameter will automatically update in response to upstream parameter changes.\n */\n expr?: Expr;\n\n /**\n * Binds the parameter to an external input element such as a slider, selection list or radio button group.\n */\n bind?: Binding;\n\n /**\n *A boolean flag (default `true`) indicating if the update expression should be automatically re-evaluated when any upstream signal dependencies update. If `false`, the update expression will not register any dependencies on other signals, even for initialization.\n *\n * __Default value:__ `true`\n */\n react?: boolean;\n}\n\nexport function assembleParameterSignals(params: (VariableParameter | TopLevelSelectionParameter)[]) {\n const signals: (NewSignal | InitSignal)[] = [];\n for (const param of params || []) {\n // Selection parameters are handled separately via assembleSelectionTopLevelSignals\n // and assembleSignals methods registered on the Model.\n if (isSelectionParameter(param)) continue;\n const {expr, bind, ...rest} = param;\n\n if (bind && expr) {\n // Vega's InitSignal -- apply expr to \"init\"\n const signal: InitSignal = {\n ...rest,\n bind,\n init: expr\n };\n signals.push(signal);\n } else {\n const signal: NewSignal = {\n ...rest,\n ...(expr ? {update: expr} : {}),\n ...(bind ? {bind} : {})\n };\n signals.push(signal);\n }\n }\n return signals;\n}\n","import {GenericSpec, NormalizedSpec} from '.';\nimport {BaseSpec, BoundsMixins, GenericCompositionLayoutWithColumns, ResolveMixins} from './base';\n\n/**\n * Base layout mixins for V/HConcatSpec, which should not have RowCol generic fo its property.\n */\nexport interface OneDirectionalConcatLayout extends BoundsMixins, ResolveMixins {\n /**\n * Boolean flag indicating if subviews should be centered relative to their respective rows or columns.\n *\n * __Default value:__ `false`\n */\n center?: boolean;\n\n /**\n * The spacing in pixels between sub-views of the concat operator.\n *\n * __Default value__: `10`\n */\n spacing?: number;\n}\n\n/**\n * Base interface for a generalized concatenation specification.\n */\nexport interface GenericConcatSpec>\n extends BaseSpec,\n GenericCompositionLayoutWithColumns,\n ResolveMixins {\n /**\n * A list of views to be concatenated.\n */\n concat: S[];\n}\n\n/**\n * Base interface for a vertical concatenation specification.\n */\nexport interface GenericVConcatSpec>\n extends BaseSpec,\n OneDirectionalConcatLayout {\n /**\n * A list of views to be concatenated and put into a column.\n */\n vconcat: S[];\n}\n\n/**\n * Base interface for a horizontal concatenation specification.\n */\nexport interface GenericHConcatSpec>\n extends BaseSpec,\n OneDirectionalConcatLayout {\n /**\n * A list of views to be concatenated and put into a row.\n */\n hconcat: S[];\n}\n\n/** A concat spec without any shortcut/expansion syntax */\nexport type NormalizedConcatSpec =\n | GenericConcatSpec\n | GenericVConcatSpec\n | GenericHConcatSpec;\n\nexport function isAnyConcatSpec(spec: BaseSpec): spec is GenericVConcatSpec | GenericHConcatSpec {\n return isVConcatSpec(spec) || isHConcatSpec(spec) || isConcatSpec(spec);\n}\n\nexport function isConcatSpec(spec: BaseSpec): spec is GenericConcatSpec {\n return 'concat' in spec;\n}\n\nexport function isVConcatSpec(spec: BaseSpec): spec is GenericVConcatSpec {\n return 'vconcat' in spec;\n}\n\nexport function isHConcatSpec(spec: BaseSpec): spec is GenericHConcatSpec {\n return 'hconcat' in spec;\n}\n","import {Color, Cursor, SignalRef, Text} from 'vega';\nimport {isNumber, isObject} from 'vega-util';\nimport {NormalizedSpec} from '.';\nimport {Data} from '../data';\nimport {ExprRef} from '../expr';\nimport {MarkConfig} from '../mark';\nimport {Resolve} from '../resolve';\nimport {TitleParams} from '../title';\nimport {Transform} from '../transform';\nimport {Flag, keys} from '../util';\nimport {LayoutAlign, RowCol} from '../vega.schema';\nimport {isConcatSpec, isVConcatSpec} from './concat';\nimport {isFacetMapping, isFacetSpec} from './facet';\n\nexport type {TopLevel} from './toplevel';\n\n/**\n * Common properties for all types of specification\n */\nexport interface BaseSpec {\n /**\n * Title for the plot.\n */\n title?: Text | TitleParams;\n\n /**\n * Name of the visualization for later reference.\n */\n name?: string;\n\n /**\n * Description of this mark for commenting purpose.\n */\n description?: string;\n\n /**\n * An object describing the data source. Set to `null` to ignore the parent's data source. If no data is set, it is derived from the parent.\n */\n data?: Data | null;\n\n /**\n * An array of data transformations such as filter and new field calculation.\n */\n transform?: Transform[];\n}\n\nexport interface DataMixins {\n /**\n * An object describing the data source.\n */\n data: Data;\n}\n\nexport type StepFor = 'position' | 'offset';\n\nexport interface Step {\n /**\n * The size (width/height) per discrete step.\n */\n step: number;\n\n /**\n * Whether to apply the step to position scale or offset scale when there are both `x` and `xOffset` or both `y` and `yOffset` encodings.\n */\n for?: StepFor;\n}\n\nexport function getStepFor({step, offsetIsDiscrete}: {step: Step; offsetIsDiscrete: boolean}): StepFor {\n if (offsetIsDiscrete) {\n return step.for ?? 'offset';\n } else {\n return 'position';\n }\n}\n\nexport function isStep(size: number | Step | 'container' | 'merged'): size is Step {\n return isObject(size) && size['step'] !== undefined;\n}\n\n// TODO(https://github.com/vega/vega-lite/issues/2503): Make this generic so we can support some form of top-down sizing.\n/**\n * Common properties for specifying width and height of unit and layer specifications.\n */\nexport interface LayoutSizeMixins {\n /**\n * The width of a visualization.\n *\n * - For a plot with a continuous x-field, width should be a number.\n * - For a plot with either a discrete x-field or no x-field, width can be either a number indicating a fixed width or an object in the form of `{step: number}` defining the width per discrete step. (No x-field is equivalent to having one discrete step.)\n * - To enable responsive sizing on width, it should be set to `\"container\"`.\n *\n * __Default value:__\n * Based on `config.view.continuousWidth` for a plot with a continuous x-field and `config.view.discreteWidth` otherwise.\n *\n * __Note:__ For plots with [`row` and `column` channels](https://vega.github.io/vega-lite/docs/encoding.html#facet), this represents the width of a single view and the `\"container\"` option cannot be used.\n *\n * __See also:__ [`width`](https://vega.github.io/vega-lite/docs/size.html) documentation.\n */\n width?: number | 'container' | Step; // Vega also supports SignalRef for width and height. However, we need to know if width is a step or not in VL and it's very difficult to check this at runtime, so we intentionally do not support SignalRef here.\n\n /**\n * The height of a visualization.\n *\n * - For a plot with a continuous y-field, height should be a number.\n * - For a plot with either a discrete y-field or no y-field, height can be either a number indicating a fixed height or an object in the form of `{step: number}` defining the height per discrete step. (No y-field is equivalent to having one discrete step.)\n * - To enable responsive sizing on height, it should be set to `\"container\"`.\n *\n * __Default value:__ Based on `config.view.continuousHeight` for a plot with a continuous y-field and `config.view.discreteHeight` otherwise.\n *\n * __Note:__ For plots with [`row` and `column` channels](https://vega.github.io/vega-lite/docs/encoding.html#facet), this represents the height of a single view and the `\"container\"` option cannot be used.\n *\n * __See also:__ [`height`](https://vega.github.io/vega-lite/docs/size.html) documentation.\n */\n height?: number | 'container' | Step; // Vega also supports SignalRef for width and height. However, we need to know if width is a step or not in VL and it's very difficult to check this at runtime, so we intentionally do not support SignalRef here.\n}\n\nexport function isFrameMixins(o: any): o is FrameMixins {\n return o['view'] || o['width'] || o['height'];\n}\n\nexport interface FrameMixins extends LayoutSizeMixins {\n /**\n * An object defining the view background's fill and stroke.\n *\n * __Default value:__ none (transparent)\n */\n view?: ViewBackground;\n}\n\nexport interface ResolveMixins {\n /**\n * Scale, axis, and legend resolutions for view composition specifications.\n */\n resolve?: Resolve;\n}\n\nexport interface BaseViewBackground\n extends Partial<\n Pick<\n MarkConfig,\n | 'cornerRadius'\n | 'fillOpacity'\n | 'opacity'\n | 'strokeCap'\n | 'strokeDash'\n | 'strokeDashOffset'\n | 'strokeJoin'\n | 'strokeMiterLimit'\n | 'strokeOpacity'\n | 'strokeWidth'\n >\n > {\n // Override documentations for fill, stroke, and cursor\n /**\n * The fill color.\n *\n * __Default value:__ `undefined`\n */\n fill?: Color | null | ES;\n\n /**\n * The stroke color.\n *\n * __Default value:__ `\"#ddd\"`\n */\n stroke?: Color | null | ES;\n\n /**\n * The mouse cursor used over the view. Any valid [CSS cursor type](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values) can be used.\n */\n cursor?: Cursor;\n}\n\nexport interface ViewBackground extends BaseViewBackground {\n /**\n * A string or array of strings indicating the name of custom styles to apply to the view background. A style is a named collection of mark property defaults defined within the [style configuration](https://vega.github.io/vega-lite/docs/mark.html#style-config). If style is an array, later styles will override earlier styles.\n *\n * __Default value:__ `\"cell\"`\n * __Note:__ Any specified view background properties will augment the default style.\n */\n style?: string | string[];\n}\n\nexport interface BoundsMixins {\n /**\n * The bounds calculation method to use for determining the extent of a sub-plot. One of `full` (the default) or `flush`.\n *\n * - If set to `full`, the entire calculated bounds (including axes, title, and legend) will be used.\n * - If set to `flush`, only the specified width and height values for the sub-view will be used. The `flush` setting can be useful when attempting to place sub-plots without axes or legends into a uniform grid structure.\n *\n * __Default value:__ `\"full\"`\n */\n\n bounds?: 'full' | 'flush';\n}\n\n/**\n * Base layout for FacetSpec and RepeatSpec.\n * This is named \"GenericComposition\" layout as ConcatLayout is a GenericCompositionLayout too\n * (but _not_ vice versa).\n */\nexport interface GenericCompositionLayout extends BoundsMixins {\n /**\n * The alignment to apply to grid rows and columns.\n * The supported string values are `\"all\"`, `\"each\"`, and `\"none\"`.\n *\n * - For `\"none\"`, a flow layout will be used, in which adjacent subviews are simply placed one after the other.\n * - For `\"each\"`, subviews will be aligned into a clean grid structure, but each row or column may be of variable size.\n * - For `\"all\"`, subviews will be aligned and each row or column will be sized identically based on the maximum observed size. String values for this property will be applied to both grid rows and columns.\n *\n * Alternatively, an object value of the form `{\"row\": string, \"column\": string}` can be used to supply different alignments for rows and columns.\n *\n * __Default value:__ `\"all\"`.\n */\n align?: LayoutAlign | RowCol;\n\n /**\n * Boolean flag indicating if subviews should be centered relative to their respective rows or columns.\n *\n * An object value of the form `{\"row\": boolean, \"column\": boolean}` can be used to supply different centering values for rows and columns.\n *\n * __Default value:__ `false`\n */\n center?: boolean | RowCol;\n\n /**\n * The spacing in pixels between sub-views of the composition operator.\n * An object of the form `{\"row\": number, \"column\": number}` can be used to set\n * different spacing values for rows and columns.\n *\n * __Default value__: Depends on `\"spacing\"` property of [the view composition configuration](https://vega.github.io/vega-lite/docs/config.html#view-config) (`20` by default)\n */\n spacing?: number | RowCol;\n}\n\nexport const DEFAULT_SPACING = 20;\n\nexport interface ColumnMixins {\n /**\n * The number of columns to include in the view composition layout.\n *\n * __Default value__: `undefined` -- An infinite number of columns (a single row) will be assumed. This is equivalent to\n * `hconcat` (for `concat`) and to using the `column` channel (for `facet` and `repeat`).\n *\n * __Note__:\n *\n * 1) This property is only for:\n * - the general (wrappable) `concat` operator (not `hconcat`/`vconcat`)\n * - the `facet` and `repeat` operator with one field/repetition definition (without row/column nesting)\n *\n * 2) Setting the `columns` to `1` is equivalent to `vconcat` (for `concat`) and to using the `row` channel (for `facet` and `repeat`).\n */\n columns?: number;\n}\n\nexport type GenericCompositionLayoutWithColumns = GenericCompositionLayout & ColumnMixins;\n\nexport type CompositionConfig = ColumnMixins & {\n /**\n * The default spacing in pixels between composed sub-views.\n *\n * __Default value__: `20`\n */\n spacing?: number;\n};\n\nexport interface CompositionConfigMixins {\n /** Default configuration for the `facet` view composition operator */\n facet?: CompositionConfig;\n\n /** Default configuration for all concatenation and repeat view composition operators (`concat`, `hconcat`, `vconcat`, and `repeat`) */\n concat?: CompositionConfig;\n}\n\nconst COMPOSITION_LAYOUT_INDEX: Flag = {\n align: 1,\n bounds: 1,\n center: 1,\n columns: 1,\n spacing: 1\n};\n\nconst COMPOSITION_LAYOUT_PROPERTIES = keys(COMPOSITION_LAYOUT_INDEX);\n\nexport type SpecType = 'unit' | 'facet' | 'layer' | 'concat';\n\nexport function extractCompositionLayout(\n spec: NormalizedSpec,\n specType: keyof CompositionConfigMixins,\n config: CompositionConfigMixins\n): GenericCompositionLayoutWithColumns {\n const compositionConfig = config[specType];\n const layout: GenericCompositionLayoutWithColumns = {};\n\n // Apply config first\n const {spacing: spacingConfig, columns} = compositionConfig;\n if (spacingConfig !== undefined) {\n layout.spacing = spacingConfig;\n }\n\n if (columns !== undefined) {\n if ((isFacetSpec(spec) && !isFacetMapping(spec.facet)) || isConcatSpec(spec)) {\n layout.columns = columns;\n }\n }\n\n if (isVConcatSpec(spec)) {\n layout.columns = 1;\n }\n\n // Then copy properties from the spec\n for (const prop of COMPOSITION_LAYOUT_PROPERTIES) {\n if (spec[prop] !== undefined) {\n if (prop === 'spacing') {\n const spacing: number | RowCol = spec[prop];\n\n layout[prop] = isNumber(spacing)\n ? spacing\n : {\n row: spacing.row ?? spacingConfig,\n column: spacing.column ?? spacingConfig\n };\n } else {\n (layout[prop] as any) = spec[prop];\n }\n }\n }\n\n return layout;\n}\n","import {Color, InitSignal, Locale, NewSignal, RangeConfig, RangeScheme, SignalRef, writeConfig} from 'vega';\nimport {isObject, mergeConfig} from 'vega-util';\nimport {Axis, AxisConfig, AxisConfigMixins, AXIS_CONFIGS, isConditionalAxisValue} from './axis';\nimport {signalOrValueRefWithCondition, signalRefOrValue} from './compile/common';\nimport {CompositeMarkConfigMixins, getAllCompositeMarks} from './compositemark';\nimport {ExprRef, replaceExprRef} from './expr';\nimport {VL_ONLY_LEGEND_CONFIG} from './guide';\nimport {HeaderConfigMixins, HEADER_CONFIGS} from './header';\nimport {defaultLegendConfig, LegendConfig} from './legend';\nimport * as mark from './mark';\nimport {\n AnyMarkConfig,\n Mark,\n MarkConfig,\n MarkConfigMixins,\n MARK_CONFIGS,\n PRIMITIVE_MARKS,\n VL_ONLY_MARK_CONFIG_PROPERTIES,\n VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX\n} from './mark';\nimport {assembleParameterSignals} from './parameter';\nimport {ProjectionConfig} from './projection';\nimport {defaultScaleConfig, ScaleConfig} from './scale';\nimport {defaultConfig as defaultSelectionConfig, SelectionConfig} from './selection';\nimport {BaseViewBackground, CompositionConfigMixins, DEFAULT_SPACING, isStep} from './spec/base';\nimport {TopLevelProperties} from './spec/toplevel';\nimport {extractTitleConfig, TitleConfig} from './title';\nimport {duplicate, getFirstDefined, isEmpty, keys, omit} from './util';\n\nexport interface ViewConfig extends BaseViewBackground {\n /**\n * The default width when the plot has a continuous field for x or longitude, or has arc marks.\n *\n * __Default value:__ `200`\n */\n continuousWidth?: number;\n\n /**\n * The default width when the plot has non-arc marks and either a discrete x-field or no x-field.\n * The width can be either a number indicating a fixed width or an object in the form of `{step: number}` defining the width per discrete step.\n *\n * __Default value:__ a step size based on `config.view.step`.\n */\n discreteWidth?: number | {step: number};\n /**\n * The default height when the plot has a continuous y-field for x or latitude, or has arc marks.\n *\n * __Default value:__ `200`\n */\n continuousHeight?: number;\n\n /**\n * The default height when the plot has non arc marks and either a discrete y-field or no y-field.\n * The height can be either a number indicating a fixed height or an object in the form of `{step: number}` defining the height per discrete step.\n *\n * __Default value:__ a step size based on `config.view.step`.\n */\n discreteHeight?: number | {step: number};\n\n /**\n * Default step size for x-/y- discrete fields.\n */\n step?: number;\n\n /**\n * Whether the view should be clipped.\n */\n clip?: boolean;\n}\n\nexport function getViewConfigContinuousSize(\n viewConfig: ViewConfig,\n channel: 'width' | 'height'\n) {\n return viewConfig[channel] ?? viewConfig[channel === 'width' ? 'continuousWidth' : 'continuousHeight']; // get width/height for backwards compatibility\n}\n\nexport function getViewConfigDiscreteStep(\n viewConfig: ViewConfig,\n channel: 'width' | 'height'\n) {\n const size = getViewConfigDiscreteSize(viewConfig, channel);\n return isStep(size) ? size.step : DEFAULT_STEP;\n}\n\nexport function getViewConfigDiscreteSize(\n viewConfig: ViewConfig,\n channel: 'width' | 'height'\n) {\n const size = viewConfig[channel] ?? viewConfig[channel === 'width' ? 'discreteWidth' : 'discreteHeight']; // get width/height for backwards compatibility\n return getFirstDefined(size, {step: viewConfig.step});\n}\n\nexport const DEFAULT_STEP = 20;\n\nexport const defaultViewConfig: ViewConfig = {\n continuousWidth: 200,\n continuousHeight: 200,\n step: DEFAULT_STEP\n};\n\nexport function isVgScheme(rangeScheme: string[] | RangeScheme): rangeScheme is RangeScheme {\n return rangeScheme && !!rangeScheme['scheme'];\n}\n\nexport type ColorConfig = Record;\n\nexport type FontSizeConfig = Record;\n\nexport interface FormatConfig {\n /**\n * If numberFormatType is not specified,\n * D3 number format for guide labels, text marks, and tooltips of non-normalized fields (fields *without* `stack: \"normalize\"`). For example `\"s\"` for SI units.\n * Use [D3's number format pattern](https://github.com/d3/d3-format#locale_format).\n *\n * If `config.numberFormatType` is specified and `config.customFormatTypes` is `true`, this value will be passed as `format` alongside `datum.value` to the `config.numberFormatType` function.\n */\n numberFormat?: string;\n\n /**\n * [Custom format type](https://vega.github.io/vega-lite/docs/config.html#custom-format-type)\n * for `config.numberFormat`.\n *\n * __Default value:__ `undefined` -- This is equilvalent to call D3-format, which is exposed as [`format` in Vega-Expression](https://vega.github.io/vega/docs/expressions/#format).\n * __Note:__ You must also set `customFormatTypes` to `true` to use this feature.\n */\n numberFormatType?: string;\n\n /**\n * If normalizedNumberFormatType is not specified,\n * D3 number format for axis labels, text marks, and tooltips of normalized stacked fields (fields with `stack: \"normalize\"`). For example `\"s\"` for SI units.\n * Use [D3's number format pattern](https://github.com/d3/d3-format#locale_format).\n *\n * If `config.normalizedNumberFormatType` is specified and `config.customFormatTypes` is `true`, this value will be passed as `format` alongside `datum.value` to the `config.numberFormatType` function.\n * __Default value:__ `%`\n */\n normalizedNumberFormat?: string;\n\n /**\n * [Custom format type](https://vega.github.io/vega-lite/docs/config.html#custom-format-type)\n * for `config.normalizedNumberFormat`.\n *\n * __Default value:__ `undefined` -- This is equilvalent to call D3-format, which is exposed as [`format` in Vega-Expression](https://vega.github.io/vega/docs/expressions/#format).\n * __Note:__ You must also set `customFormatTypes` to `true` to use this feature.\n */\n normalizedNumberFormatType?: string;\n\n /**\n * Default time format for raw time values (without time units) in text marks, legend labels and header labels.\n *\n * __Default value:__ `\"%b %d, %Y\"`\n * __Note:__ Axes automatically determine the format for each label automatically so this config does not affect axes.\n */\n timeFormat?: string;\n\n /**\n * [Custom format type](https://vega.github.io/vega-lite/docs/config.html#custom-format-type)\n * for `config.timeFormat`.\n *\n * __Default value:__ `undefined` -- This is equilvalent to call D3-time-format, which is exposed as [`timeFormat` in Vega-Expression](https://vega.github.io/vega/docs/expressions/#timeFormat).\n * __Note:__ You must also set `customFormatTypes` to `true` and there must *not* be a `timeUnit` defined to use this feature.\n */\n timeFormatType?: string;\n}\n\nexport interface VLOnlyConfig extends FormatConfig {\n /**\n * Default font for all text marks, titles, and labels.\n */\n font?: string;\n\n /**\n * Default color signals.\n *\n * @hidden\n */\n color?: boolean | ColorConfig;\n\n /**\n * Default font size signals.\n *\n * @hidden\n */\n fontSize?: boolean | FontSizeConfig;\n\n /**\n * Default axis and legend title for count fields.\n *\n * __Default value:__ `'Count of Records`.\n *\n * @type {string}\n */\n countTitle?: string;\n\n /**\n * Defines how Vega-Lite generates title for fields. There are three possible styles:\n * - `\"verbal\"` (Default) - displays function in a verbal style (e.g., \"Sum of field\", \"Year-month of date\", \"field (binned)\").\n * - `\"function\"` - displays function using parentheses and capitalized texts (e.g., \"SUM(field)\", \"YEARMONTH(date)\", \"BIN(field)\").\n * - `\"plain\"` - displays only the field name without functions (e.g., \"field\", \"date\", \"field\").\n */\n fieldTitle?: 'verbal' | 'functional' | 'plain';\n\n /**\n * Allow the `formatType` property for text marks and guides to accept a custom formatter function [registered as a Vega expression](https://vega.github.io/vega-lite/usage/compile.html#format-type).\n */\n customFormatTypes?: boolean;\n\n /**\n * Define [custom format configuration](https://vega.github.io/vega-lite/docs/config.html#format) for tooltips. If unspecified, default format config will be applied.\n */\n tooltipFormat?: FormatConfig;\n\n /** Default properties for [single view plots](https://vega.github.io/vega-lite/docs/spec.html#single). */\n view?: ViewConfig;\n\n /**\n * Scale configuration determines default properties for all [scales](https://vega.github.io/vega-lite/docs/scale.html). For a full list of scale configuration options, please see the [corresponding section of the scale documentation](https://vega.github.io/vega-lite/docs/scale.html#config).\n */\n scale?: ScaleConfig;\n\n /** An object hash for defining default properties for each type of selections. */\n selection?: SelectionConfig;\n}\n\nexport type StyleConfigIndex = Partial | Axis>> &\n MarkConfigMixins & {\n /**\n * Default style for axis, legend, and header titles.\n */\n 'guide-title'?: MarkConfig;\n\n /**\n * Default style for axis, legend, and header labels.\n */\n 'guide-label'?: MarkConfig;\n\n /**\n * Default style for chart titles\n */\n 'group-title'?: MarkConfig;\n\n /**\n * Default style for chart subtitles\n */\n 'group-subtitle'?: MarkConfig;\n };\n\nexport interface Config\n extends TopLevelProperties,\n VLOnlyConfig,\n MarkConfigMixins,\n CompositeMarkConfigMixins,\n AxisConfigMixins,\n HeaderConfigMixins,\n CompositionConfigMixins {\n /**\n * An object hash that defines default range arrays or schemes for using with scales.\n * For a full list of scale range configuration options, please see the [corresponding section of the scale documentation](https://vega.github.io/vega-lite/docs/scale.html#config).\n */\n range?: RangeConfig;\n\n /**\n * Legend configuration, which determines default properties for all [legends](https://vega.github.io/vega-lite/docs/legend.html). For a full list of legend configuration options, please see the [corresponding section of in the legend documentation](https://vega.github.io/vega-lite/docs/legend.html#config).\n */\n legend?: LegendConfig;\n\n /**\n * Title configuration, which determines default properties for all [titles](https://vega.github.io/vega-lite/docs/title.html). For a full list of title configuration options, please see the [corresponding section of the title documentation](https://vega.github.io/vega-lite/docs/title.html#config).\n */\n title?: TitleConfig;\n\n /**\n * Projection configuration, which determines default properties for all [projections](https://vega.github.io/vega-lite/docs/projection.html). For a full list of projection configuration options, please see the [corresponding section of the projection documentation](https://vega.github.io/vega-lite/docs/projection.html#config).\n */\n projection?: ProjectionConfig;\n\n /** An object hash that defines key-value mappings to determine default properties for marks with a given [style](https://vega.github.io/vega-lite/docs/mark.html#mark-def). The keys represent styles names; the values have to be valid [mark configuration objects](https://vega.github.io/vega-lite/docs/mark.html#config). */\n style?: StyleConfigIndex;\n\n /**\n * A delimiter, such as a newline character, upon which to break text strings into multiple lines. This property provides a global default for text marks, which is overridden by mark or style config settings, and by the lineBreak mark encoding channel. If signal-valued, either string or regular expression (regexp) values are valid.\n */\n lineBreak?: string | ES;\n\n /**\n * A boolean flag indicating if ARIA default attributes should be included for marks and guides (SVG output only). If false, the `\"aria-hidden\"` attribute will be set for all guides, removing them from the ARIA accessibility tree and Vega-Lite will not generate default descriptions for marks.\n *\n * __Default value:__ `true`.\n */\n aria?: boolean;\n\n /**\n * Locale definitions for string parsing and formatting of number and date values. The locale object should contain `number` and/or `time` properties with [locale definitions](https://vega.github.io/vega/docs/api/locale/). Locale definitions provided in the config block may be overridden by the View constructor locale option.\n */\n locale?: Locale;\n\n /**\n * @hidden\n */\n signals?: (InitSignal | NewSignal)[];\n}\n\nexport const defaultConfig: Config = {\n background: 'white',\n\n padding: 5,\n timeFormat: '%b %d, %Y',\n countTitle: 'Count of Records',\n\n view: defaultViewConfig,\n\n mark: mark.defaultMarkConfig,\n\n arc: {},\n area: {},\n bar: mark.defaultBarConfig,\n circle: {},\n geoshape: {},\n image: {},\n line: {},\n point: {},\n rect: mark.defaultRectConfig,\n rule: {color: 'black'}, // Need this to override default color in mark config\n square: {},\n text: {color: 'black'}, // Need this to override default color in mark config\n tick: mark.defaultTickConfig,\n trail: {},\n\n boxplot: {\n size: 14,\n extent: 1.5,\n box: {},\n median: {color: 'white'},\n outliers: {},\n rule: {},\n ticks: null\n },\n\n errorbar: {\n center: 'mean',\n rule: true,\n ticks: false\n },\n\n errorband: {\n band: {\n opacity: 0.3\n },\n borders: false\n },\n\n scale: defaultScaleConfig,\n\n projection: {},\n\n legend: defaultLegendConfig,\n header: {titlePadding: 10, labelPadding: 10},\n headerColumn: {},\n headerRow: {},\n headerFacet: {},\n\n selection: defaultSelectionConfig,\n style: {},\n\n title: {},\n\n facet: {spacing: DEFAULT_SPACING},\n concat: {spacing: DEFAULT_SPACING},\n\n normalizedNumberFormat: '.0%'\n};\n\n// Tableau10 color palette, copied from `vegaScale.scheme('tableau10')`\nconst tab10 = [\n '#4c78a8',\n '#f58518',\n '#e45756',\n '#72b7b2',\n '#54a24b',\n '#eeca3b',\n '#b279a2',\n '#ff9da6',\n '#9d755d',\n '#bab0ac'\n];\n\nexport const DEFAULT_FONT_SIZE = {\n text: 11,\n guideLabel: 10,\n guideTitle: 11,\n groupTitle: 13,\n groupSubtitle: 12\n};\n\nexport const DEFAULT_COLOR = {\n blue: tab10[0],\n orange: tab10[1],\n red: tab10[2],\n teal: tab10[3],\n green: tab10[4],\n yellow: tab10[5],\n purple: tab10[6],\n pink: tab10[7],\n brown: tab10[8],\n gray0: '#000',\n gray1: '#111',\n gray2: '#222',\n gray3: '#333',\n gray4: '#444',\n gray5: '#555',\n gray6: '#666',\n gray7: '#777',\n gray8: '#888',\n gray9: '#999',\n gray10: '#aaa',\n gray11: '#bbb',\n gray12: '#ccc',\n gray13: '#ddd',\n gray14: '#eee',\n gray15: '#fff'\n};\n\nexport function colorSignalConfig(color: boolean | ColorConfig = {}): Config {\n return {\n signals: [\n {\n name: 'color',\n value: isObject(color) ? {...DEFAULT_COLOR, ...color} : DEFAULT_COLOR\n }\n ],\n mark: {color: {signal: 'color.blue'}},\n rule: {color: {signal: 'color.gray0'}},\n text: {\n color: {signal: 'color.gray0'}\n },\n style: {\n 'guide-label': {\n fill: {signal: 'color.gray0'}\n },\n 'guide-title': {\n fill: {signal: 'color.gray0'}\n },\n 'group-title': {\n fill: {signal: 'color.gray0'}\n },\n 'group-subtitle': {\n fill: {signal: 'color.gray0'}\n },\n cell: {\n stroke: {signal: 'color.gray8'}\n }\n },\n axis: {\n domainColor: {signal: 'color.gray13'},\n gridColor: {signal: 'color.gray8'},\n tickColor: {signal: 'color.gray13'}\n },\n range: {\n category: [\n {signal: 'color.blue'},\n {signal: 'color.orange'},\n {signal: 'color.red'},\n {signal: 'color.teal'},\n {signal: 'color.green'},\n {signal: 'color.yellow'},\n {signal: 'color.purple'},\n {signal: 'color.pink'},\n {signal: 'color.brown'},\n {signal: 'color.grey8'}\n ]\n }\n };\n}\n\nexport function fontSizeSignalConfig(fontSize: boolean | FontSizeConfig): Config {\n return {\n signals: [\n {\n name: 'fontSize',\n value: isObject(fontSize) ? {...DEFAULT_FONT_SIZE, ...fontSize} : DEFAULT_FONT_SIZE\n }\n ],\n text: {\n fontSize: {signal: 'fontSize.text'}\n },\n style: {\n 'guide-label': {\n fontSize: {signal: 'fontSize.guideLabel'}\n },\n 'guide-title': {\n fontSize: {signal: 'fontSize.guideTitle'}\n },\n 'group-title': {\n fontSize: {signal: 'fontSize.groupTitle'}\n },\n 'group-subtitle': {\n fontSize: {signal: 'fontSize.groupSubtitle'}\n }\n }\n };\n}\n\nexport function fontConfig(font: string): Config {\n return {\n text: {font},\n style: {\n 'guide-label': {font},\n 'guide-title': {font},\n 'group-title': {font},\n 'group-subtitle': {font}\n }\n };\n}\n\nfunction getAxisConfigInternal(axisConfig: AxisConfig) {\n const props = keys(axisConfig || {});\n const axisConfigInternal: AxisConfig = {};\n for (const prop of props) {\n const val = axisConfig[prop];\n axisConfigInternal[prop as any] = isConditionalAxisValue(val)\n ? signalOrValueRefWithCondition(val)\n : signalRefOrValue(val);\n }\n return axisConfigInternal;\n}\n\nfunction getStyleConfigInternal(styleConfig: StyleConfigIndex) {\n const props = keys(styleConfig);\n\n const styleConfigInternal: StyleConfigIndex = {};\n for (const prop of props) {\n // We need to cast to cheat a bit here since styleConfig can be either mark config or axis config\n styleConfigInternal[prop as any] = getAxisConfigInternal(styleConfig[prop] as any);\n }\n return styleConfigInternal;\n}\n\nconst configPropsWithExpr = [\n ...MARK_CONFIGS,\n ...AXIS_CONFIGS,\n ...HEADER_CONFIGS,\n 'background',\n 'padding',\n 'legend',\n 'lineBreak',\n 'scale',\n 'style',\n 'title',\n 'view'\n] as const;\n\n/**\n * Merge specified config with default config and config for the `color` flag,\n * then replace all expressions with signals\n */\nexport function initConfig(specifiedConfig: Config = {}): Config {\n const {color, font, fontSize, selection, ...restConfig} = specifiedConfig;\n const mergedConfig = mergeConfig(\n {},\n duplicate(defaultConfig),\n font ? fontConfig(font) : {},\n color ? colorSignalConfig(color) : {},\n fontSize ? fontSizeSignalConfig(fontSize) : {},\n restConfig || {}\n );\n\n // mergeConfig doesn't recurse and overrides object values.\n if (selection) {\n writeConfig(mergedConfig, 'selection', selection, true);\n }\n\n const outputConfig: Config = omit(mergedConfig, configPropsWithExpr);\n\n for (const prop of ['background', 'lineBreak', 'padding']) {\n if (mergedConfig[prop]) {\n outputConfig[prop] = signalRefOrValue(mergedConfig[prop]);\n }\n }\n\n for (const markConfigType of mark.MARK_CONFIGS) {\n if (mergedConfig[markConfigType]) {\n // FIXME: outputConfig[markConfigType] expects that types are replaced recursively but replaceExprRef only replaces one level deep\n outputConfig[markConfigType] = replaceExprRef(mergedConfig[markConfigType]) as any;\n }\n }\n\n for (const axisConfigType of AXIS_CONFIGS) {\n if (mergedConfig[axisConfigType]) {\n outputConfig[axisConfigType] = getAxisConfigInternal(mergedConfig[axisConfigType]);\n }\n }\n\n for (const headerConfigType of HEADER_CONFIGS) {\n if (mergedConfig[headerConfigType]) {\n outputConfig[headerConfigType] = replaceExprRef(mergedConfig[headerConfigType]);\n }\n }\n\n if (mergedConfig.legend) {\n outputConfig.legend = replaceExprRef(mergedConfig.legend);\n }\n\n if (mergedConfig.scale) {\n const {invalid, ...otherScaleConfig} = mergedConfig.scale;\n const newScaleInvalid = replaceExprRef(invalid, {level: 1});\n outputConfig.scale = {\n ...replaceExprRef(otherScaleConfig),\n ...(keys(newScaleInvalid).length > 0 ? {invalid: newScaleInvalid} : {})\n };\n }\n\n if (mergedConfig.style) {\n outputConfig.style = getStyleConfigInternal(mergedConfig.style);\n }\n\n if (mergedConfig.title) {\n outputConfig.title = replaceExprRef(mergedConfig.title);\n }\n\n if (mergedConfig.view) {\n outputConfig.view = replaceExprRef(mergedConfig.view);\n }\n\n return outputConfig;\n}\n\nconst MARK_STYLES = new Set(['view', ...PRIMITIVE_MARKS]) as ReadonlySet<'view' | Mark>;\n\nconst VL_ONLY_CONFIG_PROPERTIES: (keyof Config)[] = [\n 'color',\n 'fontSize',\n 'background', // We apply background to the spec directly.\n 'padding',\n 'facet',\n 'concat',\n 'numberFormat',\n 'numberFormatType',\n 'normalizedNumberFormat',\n 'normalizedNumberFormatType',\n 'timeFormat',\n 'countTitle',\n 'header',\n\n 'axisQuantitative',\n 'axisTemporal',\n 'axisDiscrete',\n 'axisPoint',\n\n 'axisXBand',\n 'axisXPoint',\n 'axisXDiscrete',\n 'axisXQuantitative',\n 'axisXTemporal',\n\n 'axisYBand',\n 'axisYPoint',\n 'axisYDiscrete',\n 'axisYQuantitative',\n 'axisYTemporal',\n\n 'scale',\n 'selection',\n 'overlay' as keyof Config // FIXME: Redesign and unhide this\n];\n\nconst VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {\n view: ['continuousWidth', 'continuousHeight', 'discreteWidth', 'discreteHeight', 'step'],\n ...VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX\n};\n\nexport function stripAndRedirectConfig(config: Config) {\n config = duplicate(config);\n\n for (const prop of VL_ONLY_CONFIG_PROPERTIES) {\n delete config[prop];\n }\n\n if (config.axis) {\n // delete condition axis config\n for (const prop in config.axis) {\n if (isConditionalAxisValue(config.axis[prop])) {\n delete config.axis[prop];\n }\n }\n }\n\n if (config.legend) {\n for (const prop of VL_ONLY_LEGEND_CONFIG) {\n delete config.legend[prop];\n }\n }\n\n // Remove Vega-Lite only generic mark config\n if (config.mark) {\n for (const prop of VL_ONLY_MARK_CONFIG_PROPERTIES) {\n delete config.mark[prop];\n }\n\n if (config.mark.tooltip && isObject(config.mark.tooltip)) {\n delete config.mark.tooltip;\n }\n }\n\n if (config.params) {\n config.signals = (config.signals || []).concat(assembleParameterSignals(config.params));\n delete config.params;\n }\n\n for (const markType of MARK_STYLES) {\n // Remove Vega-Lite-only mark config\n for (const prop of VL_ONLY_MARK_CONFIG_PROPERTIES) {\n delete config[markType][prop];\n }\n\n // Remove Vega-Lite only mark-specific config\n const vlOnlyMarkSpecificConfigs = VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX[markType];\n if (vlOnlyMarkSpecificConfigs) {\n for (const prop of vlOnlyMarkSpecificConfigs) {\n delete config[markType][prop];\n }\n }\n\n // Redirect mark config to config.style so that mark config only affect its own mark type\n // without affecting other marks that share the same underlying Vega marks.\n // For example, config.rect should not affect bar marks.\n redirectConfigToStyleConfig(config, markType);\n }\n\n for (const m of getAllCompositeMarks()) {\n // Clean up the composite mark config as we don't need them in the output specs anymore\n delete config[m];\n }\n\n redirectTitleConfig(config);\n\n // Remove empty config objects.\n for (const prop in config) {\n if (isObject(config[prop]) && isEmpty(config[prop])) {\n delete config[prop];\n }\n }\n\n return isEmpty(config) ? undefined : config;\n}\n\n/**\n *\n * Redirect config.title -- so that title config do not affect header labels,\n * which also uses `title` directive to implement.\n *\n * For subtitle configs in config.title, keep them in config.title as header titles never have subtitles.\n */\nfunction redirectTitleConfig(config: Config) {\n const {titleMarkConfig, subtitleMarkConfig, subtitle} = extractTitleConfig(config.title);\n\n // set config.style if title/subtitleMarkConfig is not an empty object\n if (!isEmpty(titleMarkConfig)) {\n config.style['group-title'] = {\n ...config.style['group-title'],\n ...titleMarkConfig // config.title has higher precedence than config.style.group-title in Vega\n };\n }\n if (!isEmpty(subtitleMarkConfig)) {\n config.style['group-subtitle'] = {\n ...config.style['group-subtitle'],\n ...subtitleMarkConfig\n };\n }\n\n // subtitle part can stay in config.title since header titles do not use subtitle\n if (!isEmpty(subtitle)) {\n config.title = subtitle;\n } else {\n delete config.title;\n }\n}\n\nfunction redirectConfigToStyleConfig(\n config: Config,\n prop: Mark | 'view' | string, // string = composite mark\n toProp?: string,\n compositeMarkPart?: string\n) {\n const propConfig: MarkConfig = compositeMarkPart ? config[prop][compositeMarkPart] : config[prop];\n\n if (prop === 'view') {\n toProp = 'cell'; // View's default style is \"cell\"\n }\n\n const style: MarkConfig = {\n ...propConfig,\n ...(config.style[toProp ?? prop] as MarkConfig)\n };\n\n // set config.style if it is not an empty object\n if (!isEmpty(style)) {\n config.style[toProp ?? prop] = style;\n }\n\n if (!compositeMarkPart) {\n // For composite mark, so don't delete the whole config yet as we have to do multiple redirections.\n delete config[prop];\n }\n}\n","import {Field} from '../channeldef';\nimport {SharedCompositeEncoding} from '../compositemark';\nimport {ExprRef} from '../expr';\nimport {Projection} from '../projection';\nimport {BaseSpec, FrameMixins, ResolveMixins} from './base';\nimport {GenericUnitSpec, NormalizedUnitSpec, UnitSpec} from './unit';\n\n/**\n * Base interface for a layer specification.\n */\nexport interface GenericLayerSpec> extends BaseSpec, FrameMixins, ResolveMixins {\n /**\n * Layer or single view specifications to be layered.\n *\n * __Note__: Specifications inside `layer` cannot use `row` and `column` channels as layering facet specifications is not allowed. Instead, use the [facet operator](https://vega.github.io/vega-lite/docs/facet.html) and place a layer inside a facet.\n */\n layer: (GenericLayerSpec | U)[];\n}\n\n/**\n * A full layered plot specification, which may contains `encoding` and `projection` properties that will be applied to underlying unit (single-view) specifications.\n */\nexport interface LayerSpec extends BaseSpec, FrameMixins, ResolveMixins {\n /**\n * Layer or single view specifications to be layered.\n *\n * __Note__: Specifications inside `layer` cannot use `row` and `column` channels as layering facet specifications is not allowed. Instead, use the [facet operator](https://vega.github.io/vega-lite/docs/facet.html) and place a layer inside a facet.\n */\n layer: (LayerSpec | UnitSpec)[];\n\n /**\n * A shared key-value mapping between encoding channels and definition of fields in the underlying layers.\n */\n encoding?: SharedCompositeEncoding;\n\n /**\n * An object defining properties of the geographic projection shared by underlying layers.\n */\n projection?: Projection;\n}\n\n/**\n * A layered specification without any shortcut/expansion syntax.\n */\nexport type NormalizedLayerSpec = GenericLayerSpec;\n\nexport function isLayerSpec(spec: BaseSpec): spec is GenericLayerSpec {\n return 'layer' in spec;\n}\n","import {GenericSpec} from '.';\nimport * as log from '../log';\nimport {Field, FieldName} from '../channeldef';\nimport {\n GenericConcatSpec,\n GenericHConcatSpec,\n GenericVConcatSpec,\n isConcatSpec,\n isHConcatSpec,\n isVConcatSpec\n} from './concat';\nimport {GenericFacetSpec, isFacetSpec} from './facet';\nimport {GenericLayerSpec, isLayerSpec} from './layer';\nimport {isRepeatSpec, RepeatSpec} from './repeat';\nimport {GenericUnitSpec, isUnitSpec, NormalizedUnitSpec} from './unit';\n\nexport abstract class SpecMapper<\n P,\n UI extends GenericUnitSpec,\n LI extends GenericLayerSpec = GenericLayerSpec,\n UO extends GenericUnitSpec = NormalizedUnitSpec,\n RO extends RepeatSpec = never,\n FO extends Field = FieldName\n> {\n public map(spec: GenericSpec, params: P): GenericSpec, RO, FO> {\n if (isFacetSpec(spec)) {\n return this.mapFacet(spec, params);\n } else if (isRepeatSpec(spec)) {\n return this.mapRepeat(spec, params);\n } else if (isHConcatSpec(spec)) {\n return this.mapHConcat(spec, params);\n } else if (isVConcatSpec(spec)) {\n return this.mapVConcat(spec, params);\n } else if (isConcatSpec(spec)) {\n return this.mapConcat(spec, params);\n } else {\n return this.mapLayerOrUnit(spec, params);\n }\n }\n\n public mapLayerOrUnit(spec: UI | LI, params: P): UO | GenericLayerSpec {\n if (isLayerSpec(spec)) {\n return this.mapLayer(spec, params);\n } else if (isUnitSpec(spec)) {\n return this.mapUnit(spec, params);\n }\n throw new Error(log.message.invalidSpec(spec));\n }\n\n public abstract mapUnit(spec: UI, params: P): UO | GenericLayerSpec;\n\n protected mapLayer(spec: LI, params: P): GenericLayerSpec {\n return {\n ...spec,\n layer: spec.layer.map(subspec => this.mapLayerOrUnit(subspec, params))\n };\n }\n\n protected mapHConcat(\n spec: GenericHConcatSpec>,\n params: P\n ): GenericHConcatSpec, RO, FO>> {\n return {\n ...spec,\n hconcat: spec.hconcat.map(subspec => this.map(subspec, params))\n };\n }\n\n protected mapVConcat(\n spec: GenericVConcatSpec>,\n params: P\n ): GenericVConcatSpec, RO, FO>> {\n return {\n ...spec,\n vconcat: spec.vconcat.map(subspec => this.map(subspec, params))\n };\n }\n\n protected mapConcat(\n spec: GenericConcatSpec>,\n params: P\n ): GenericConcatSpec, RO, FO>> {\n const {concat, ...rest} = spec;\n\n return {\n ...rest,\n concat: concat.map(subspec => this.map(subspec, params))\n };\n }\n\n protected mapFacet(spec: GenericFacetSpec, params: P): GenericFacetSpec, FO> {\n return {\n // as any is required here since TS cannot infer that FO may only be FieldName or Field, but not RepeatRef\n ...(spec as any),\n // TODO: remove \"any\" once we support all facet listed in https://github.com/vega/vega-lite/issues/2760\n spec: this.map(spec.spec, params) as any\n };\n }\n\n protected mapRepeat(spec: RepeatSpec, params: P): GenericSpec {\n return {\n ...spec,\n // as any is required here since TS cannot infer that the output type satisfies the input type\n spec: this.map(spec.spec as any, params)\n };\n }\n}\n","import {isArray} from 'vega-util';\nimport {LayerSpec, NonNormalizedSpec} from '.';\nimport {Field} from '../channeldef';\nimport {BaseSpec, GenericCompositionLayoutWithColumns, ResolveMixins} from './base';\nimport {UnitSpecWithFrame} from './unit';\n\nexport interface RepeatMapping {\n /**\n * An array of fields to be repeated vertically.\n */\n row?: string[];\n\n /**\n * An array of fields to be repeated horizontally.\n */\n column?: string[];\n}\n\nexport interface LayerRepeatMapping extends RepeatMapping {\n /**\n * An array of fields to be repeated as layers.\n */\n layer: string[];\n}\n\nexport type RepeatSpec = NonLayerRepeatSpec | LayerRepeatSpec;\n\n/**\n * Base interface for a repeat specification.\n */\nexport interface NonLayerRepeatSpec extends BaseSpec, GenericCompositionLayoutWithColumns, ResolveMixins {\n /**\n * Definition for fields to be repeated. One of:\n * 1) An array of fields to be repeated. If `\"repeat\"` is an array, the field can be referred to as `{\"repeat\": \"repeat\"}`. The repeated views are laid out in a wrapped row. You can set the number of columns to control the wrapping.\n * 2) An object that maps `\"row\"` and/or `\"column\"` to the listed fields to be repeated along the particular orientations. The objects `{\"repeat\": \"row\"}` and `{\"repeat\": \"column\"}` can be used to refer to the repeated field respectively.\n */\n repeat: string[] | RepeatMapping;\n\n /**\n * A specification of the view that gets repeated.\n */\n spec: NonNormalizedSpec;\n}\n\nexport interface LayerRepeatSpec extends BaseSpec, GenericCompositionLayoutWithColumns, ResolveMixins {\n /**\n * Definition for fields to be repeated. One of:\n * 1) An array of fields to be repeated. If `\"repeat\"` is an array, the field can be referred to as `{\"repeat\": \"repeat\"}`. The repeated views are laid out in a wrapped row. You can set the number of columns to control the wrapping.\n * 2) An object that maps `\"row\"` and/or `\"column\"` to the listed fields to be repeated along the particular orientations. The objects `{\"repeat\": \"row\"}` and `{\"repeat\": \"column\"}` can be used to refer to the repeated field respectively.\n */\n repeat: LayerRepeatMapping;\n\n /**\n * A specification of the view that gets repeated.\n */\n spec: LayerSpec | UnitSpecWithFrame;\n}\n\nexport function isRepeatSpec(spec: BaseSpec): spec is RepeatSpec {\n return 'repeat' in spec;\n}\n\nexport function isLayerRepeatSpec(spec: RepeatSpec): spec is LayerRepeatSpec {\n return !isArray(spec.repeat) && spec.repeat['layer'];\n}\n","import {array, isBoolean} from 'vega-util';\nimport {Aggregate, SUM_OPS} from './aggregate';\nimport {getSecondaryRangeChannel, NonPositionChannel, NONPOSITION_CHANNELS} from './channel';\nimport {\n channelDefType,\n FieldName,\n getFieldDef,\n isFieldDef,\n isFieldOrDatumDef,\n PositionDatumDef,\n PositionDef,\n PositionFieldDef,\n TypedFieldDef,\n vgField\n} from './channeldef';\nimport {CompositeAggregate} from './compositemark';\nimport {channelHasField, Encoding, isAggregate} from './encoding';\nimport * as log from './log';\nimport {\n ARC,\n AREA,\n BAR,\n CIRCLE,\n isMarkDef,\n isPathMark,\n LINE,\n Mark,\n MarkDef,\n POINT,\n RULE,\n SQUARE,\n TEXT,\n TICK\n} from './mark';\nimport {ScaleType} from './scale';\n\nconst STACK_OFFSET_INDEX = {\n zero: 1,\n center: 1,\n normalize: 1\n} as const;\n\nexport type StackOffset = keyof typeof STACK_OFFSET_INDEX;\n\nexport function isStackOffset(s: string): s is StackOffset {\n return s in STACK_OFFSET_INDEX;\n}\n\nexport interface StackProperties {\n /** Dimension axis of the stack. */\n groupbyChannels: ('x' | 'y' | 'theta' | 'radius' | 'xOffset' | 'yOffset')[];\n\n /** Field for groupbyChannel. */\n groupbyFields: Set;\n\n /** Measure axis of the stack. */\n fieldChannel: 'x' | 'y' | 'theta' | 'radius';\n\n /** Stack-by fields e.g., color, detail */\n stackBy: {\n fieldDef: TypedFieldDef;\n channel: NonPositionChannel;\n }[];\n\n /**\n * See `stack` property of Position Field Def.\n */\n offset: StackOffset;\n\n /**\n * Whether this stack will produce impute transform\n */\n impute: boolean;\n}\n\nexport const STACKABLE_MARKS = new Set([ARC, BAR, AREA, RULE, POINT, CIRCLE, SQUARE, LINE, TEXT, TICK]);\nexport const STACK_BY_DEFAULT_MARKS = new Set([BAR, AREA, ARC]);\n\nfunction isUnbinnedQuantitative(channelDef: PositionDef) {\n return isFieldDef(channelDef) && channelDefType(channelDef) === 'quantitative' && !channelDef.bin;\n}\n\nfunction potentialStackedChannel(\n encoding: Encoding,\n x: 'x' | 'theta',\n {orient, type: mark}: MarkDef\n): 'x' | 'y' | 'theta' | 'radius' | undefined {\n const y = x === 'x' ? 'y' : 'radius';\n\n const isCartesianBarOrArea = x === 'x' && ['bar', 'area'].includes(mark);\n\n const xDef = encoding[x];\n const yDef = encoding[y];\n\n if (isFieldDef(xDef) && isFieldDef(yDef)) {\n if (isUnbinnedQuantitative(xDef) && isUnbinnedQuantitative(yDef)) {\n if (xDef.stack) {\n return x;\n } else if (yDef.stack) {\n return y;\n }\n const xAggregate = isFieldDef(xDef) && !!xDef.aggregate;\n const yAggregate = isFieldDef(yDef) && !!yDef.aggregate;\n // if there is no explicit stacking, only apply stack if there is only one aggregate for x or y\n if (xAggregate !== yAggregate) {\n return xAggregate ? x : y;\n }\n\n if (isCartesianBarOrArea) {\n if (orient === 'vertical') {\n return y;\n } else if (orient === 'horizontal') {\n return x;\n }\n }\n } else if (isUnbinnedQuantitative(xDef)) {\n return x;\n } else if (isUnbinnedQuantitative(yDef)) {\n return y;\n }\n } else if (isUnbinnedQuantitative(xDef)) {\n if (isCartesianBarOrArea && orient === 'vertical') {\n return undefined;\n }\n return x;\n } else if (isUnbinnedQuantitative(yDef)) {\n if (isCartesianBarOrArea && orient === 'horizontal') {\n return undefined;\n }\n return y;\n }\n return undefined;\n}\n\nfunction getDimensionChannel(channel: 'x' | 'y' | 'theta' | 'radius') {\n switch (channel) {\n case 'x':\n return 'y';\n case 'y':\n return 'x';\n case 'theta':\n return 'radius';\n case 'radius':\n return 'theta';\n }\n}\n\nexport function stack(m: Mark | MarkDef, encoding: Encoding): StackProperties {\n const markDef = isMarkDef(m) ? m : {type: m};\n const mark = markDef.type;\n\n // Should have stackable mark\n if (!STACKABLE_MARKS.has(mark)) {\n return null;\n }\n\n // Run potential stacked twice, one for Cartesian and another for Polar,\n // so text marks can be stacked in any of the coordinates.\n\n // Note: The logic here is not perfectly correct. If we want to support stacked dot plots where each dot is a pie chart with label, we have to change the stack logic here to separate Cartesian stacking for polar stacking.\n // However, since we probably never want to do that, let's just note the limitation here.\n const fieldChannel =\n potentialStackedChannel(encoding, 'x', markDef) || potentialStackedChannel(encoding, 'theta', markDef);\n\n if (!fieldChannel) {\n return null;\n }\n\n const stackedFieldDef = encoding[fieldChannel] as PositionFieldDef | PositionDatumDef;\n const stackedField = isFieldDef(stackedFieldDef) ? vgField(stackedFieldDef, {}) : undefined;\n\n const dimensionChannel: 'x' | 'y' | 'theta' | 'radius' = getDimensionChannel(fieldChannel);\n const groupbyChannels: StackProperties['groupbyChannels'] = [];\n const groupbyFields: Set = new Set();\n\n if (encoding[dimensionChannel]) {\n const dimensionDef = encoding[dimensionChannel];\n const dimensionField = isFieldDef(dimensionDef) ? vgField(dimensionDef, {}) : undefined;\n\n if (dimensionField && dimensionField !== stackedField) {\n // avoid grouping by the stacked field\n groupbyChannels.push(dimensionChannel);\n groupbyFields.add(dimensionField);\n }\n }\n\n const dimensionOffsetChannel = dimensionChannel === 'x' ? 'xOffset' : 'yOffset';\n const dimensionOffsetDef = encoding[dimensionOffsetChannel];\n const dimensionOffsetField = isFieldDef(dimensionOffsetDef) ? vgField(dimensionOffsetDef, {}) : undefined;\n\n if (dimensionOffsetField && dimensionOffsetField !== stackedField) {\n // avoid grouping by the stacked field\n groupbyChannels.push(dimensionOffsetChannel);\n groupbyFields.add(dimensionOffsetField);\n }\n\n // If the dimension has offset, don't stack anymore\n\n // Should have grouping level of detail that is different from the dimension field\n const stackBy = NONPOSITION_CHANNELS.reduce((sc, channel) => {\n // Ignore tooltip in stackBy (https://github.com/vega/vega-lite/issues/4001)\n if (channel !== 'tooltip' && channelHasField(encoding, channel)) {\n const channelDef = encoding[channel];\n for (const cDef of array(channelDef)) {\n const fieldDef = getFieldDef(cDef);\n if (fieldDef.aggregate) {\n continue;\n }\n\n // Check whether the channel's field is identical to x/y's field or if the channel is a repeat\n const f = vgField(fieldDef, {});\n if (\n // if fielddef is a repeat, just include it in the stack by\n !f ||\n // otherwise, the field must be different from the groupBy fields.\n !groupbyFields.has(f)\n ) {\n sc.push({channel, fieldDef});\n }\n }\n }\n return sc;\n }, []);\n\n // Automatically determine offset\n let offset: StackOffset;\n if (stackedFieldDef.stack !== undefined) {\n if (isBoolean(stackedFieldDef.stack)) {\n offset = stackedFieldDef.stack ? 'zero' : null;\n } else {\n offset = stackedFieldDef.stack;\n }\n } else if (STACK_BY_DEFAULT_MARKS.has(mark)) {\n offset = 'zero';\n }\n\n if (!offset || !isStackOffset(offset)) {\n return null;\n }\n\n if (isAggregate(encoding) && stackBy.length === 0) {\n return null;\n }\n\n // warn when stacking non-linear\n if (stackedFieldDef?.scale?.type && stackedFieldDef?.scale?.type !== ScaleType.LINEAR) {\n if (stackedFieldDef?.stack) {\n log.warn(log.message.stackNonLinearScale(stackedFieldDef.scale.type));\n }\n }\n\n // Check if it is a ranged mark\n if (isFieldOrDatumDef(encoding[getSecondaryRangeChannel(fieldChannel)])) {\n if (stackedFieldDef.stack !== undefined) {\n log.warn(log.message.cannotStackRangedMark(fieldChannel));\n }\n return null;\n }\n\n // Warn if stacking non-summative aggregate\n if (\n isFieldDef(stackedFieldDef) &&\n stackedFieldDef.aggregate &&\n !(SUM_OPS as Set).has(stackedFieldDef.aggregate)\n ) {\n log.warn(log.message.stackNonSummativeAggregate(stackedFieldDef.aggregate));\n }\n\n return {\n groupbyChannels,\n groupbyFields,\n fieldChannel,\n impute: stackedFieldDef.impute === null ? false : isPathMark(mark),\n stackBy,\n offset\n };\n}\n","import {Orientation, SignalRef} from 'vega';\nimport {isBinned, isBinning} from '../../bin';\nimport {isFieldDef, isNumericDataDef, isUnbinnedQuantitativeFieldOrDatumDef, isTypedFieldDef} from '../../channeldef';\nimport {Config} from '../../config';\nimport {Encoding, isAggregate} from '../../encoding';\nimport {replaceExprRef} from '../../expr';\nimport * as log from '../../log';\nimport {\n AREA,\n BAR,\n BAR_CORNER_RADIUS_INDEX as BAR_CORNER_RADIUS_END_INDEX,\n CIRCLE,\n IMAGE,\n LINE,\n Mark,\n MarkDef,\n POINT,\n RECT,\n RULE,\n SQUARE,\n TEXT,\n TICK\n} from '../../mark';\nimport {QUANTITATIVE, TEMPORAL} from '../../type';\nimport {contains, getFirstDefined} from '../../util';\nimport {getMarkConfig, getMarkPropOrConfig} from '../common';\n\nexport function initMarkdef(originalMarkDef: MarkDef, encoding: Encoding, config: Config) {\n // FIXME: markDef expects that exprRefs are replaced recursively but replaceExprRef only replaces the top level\n const markDef: MarkDef = replaceExprRef(originalMarkDef) as any;\n\n // set orient, which can be overridden by rules as sometimes the specified orient is invalid.\n const specifiedOrient = getMarkPropOrConfig('orient', markDef, config);\n markDef.orient = orient(markDef.type, encoding, specifiedOrient);\n if (specifiedOrient !== undefined && specifiedOrient !== markDef.orient) {\n log.warn(log.message.orientOverridden(markDef.orient, specifiedOrient));\n }\n\n if (markDef.type === 'bar' && markDef.orient) {\n const cornerRadiusEnd = getMarkPropOrConfig('cornerRadiusEnd', markDef, config);\n if (cornerRadiusEnd !== undefined) {\n const newProps =\n (markDef.orient === 'horizontal' && encoding.x2) || (markDef.orient === 'vertical' && encoding.y2)\n ? ['cornerRadius']\n : BAR_CORNER_RADIUS_END_INDEX[markDef.orient];\n\n for (const newProp of newProps) {\n markDef[newProp] = cornerRadiusEnd;\n }\n\n if (markDef.cornerRadiusEnd !== undefined) {\n delete markDef.cornerRadiusEnd; // no need to keep the original cap cornerRadius\n }\n }\n }\n\n // set opacity and filled if not specified in mark config\n const specifiedOpacity = getMarkPropOrConfig('opacity', markDef, config);\n const specifiedfillOpacity = getMarkPropOrConfig('fillOpacity', markDef, config);\n if (specifiedOpacity === undefined && specifiedfillOpacity === undefined) {\n markDef.opacity = opacity(markDef.type, encoding);\n }\n\n // set cursor, which should be pointer if href channel is present unless otherwise specified\n const specifiedCursor = getMarkPropOrConfig('cursor', markDef, config);\n if (specifiedCursor === undefined) {\n markDef.cursor = cursor(markDef, encoding, config);\n }\n\n return markDef;\n}\n\nfunction cursor(markDef: MarkDef, encoding: Encoding, config: Config) {\n if (encoding.href || markDef.href || getMarkPropOrConfig('href', markDef, config)) {\n return 'pointer';\n }\n return markDef.cursor;\n}\n\nfunction opacity(mark: Mark, encoding: Encoding) {\n if (contains([POINT, TICK, CIRCLE, SQUARE], mark)) {\n // point-based marks\n if (!isAggregate(encoding)) {\n return 0.7;\n }\n }\n return undefined;\n}\n\nexport function defaultFilled(markDef: MarkDef, config: Config, {graticule}: {graticule: boolean}) {\n if (graticule) {\n return false;\n }\n const filledConfig = getMarkConfig('filled', markDef, config);\n const mark = markDef.type;\n return getFirstDefined(filledConfig, mark !== POINT && mark !== LINE && mark !== RULE);\n}\n\nfunction orient(mark: Mark, encoding: Encoding, specifiedOrient: Orientation): Orientation {\n switch (mark) {\n case POINT:\n case CIRCLE:\n case SQUARE:\n case TEXT:\n case RECT:\n case IMAGE:\n // orient is meaningless for these marks.\n return undefined;\n }\n\n const {x, y, x2, y2} = encoding;\n\n switch (mark) {\n case BAR:\n if (isFieldDef(x) && (isBinned(x.bin) || (isFieldDef(y) && y.aggregate && !x.aggregate))) {\n return 'vertical';\n }\n if (isFieldDef(y) && (isBinned(y.bin) || (isFieldDef(x) && x.aggregate && !y.aggregate))) {\n return 'horizontal';\n }\n if (y2 || x2) {\n // Ranged bar does not always have clear orientation, so we allow overriding\n if (specifiedOrient) {\n return specifiedOrient;\n }\n\n // If y is range and x is non-range, non-bin Q\n if (!x2) {\n if ((isFieldDef(x) && x.type === QUANTITATIVE && !isBinning(x.bin)) || isNumericDataDef(x)) {\n if (isFieldDef(y) && isBinned(y.bin)) {\n return 'horizontal';\n }\n }\n return 'vertical';\n }\n\n // If x is range and y is non-range, non-bin Q\n if (!y2) {\n if ((isFieldDef(y) && y.type === QUANTITATIVE && !isBinning(y.bin)) || isNumericDataDef(y)) {\n if (isFieldDef(x) && isBinned(x.bin)) {\n return 'vertical';\n }\n }\n return 'horizontal';\n }\n }\n\n // falls through\n case RULE:\n // return undefined for line segment rule and bar with both axis ranged\n // we have to ignore the case that the data are already binned\n if (x2 && !(isFieldDef(x) && isBinned(x.bin)) && y2 && !(isFieldDef(y) && isBinned(y.bin))) {\n return undefined;\n }\n\n // falls through\n case AREA:\n // If there are range for both x and y, y (vertical) has higher precedence.\n if (y2) {\n if (isFieldDef(y) && isBinned(y.bin)) {\n return 'horizontal';\n } else {\n return 'vertical';\n }\n } else if (x2) {\n if (isFieldDef(x) && isBinned(x.bin)) {\n return 'vertical';\n } else {\n return 'horizontal';\n }\n } else if (mark === RULE) {\n if (x && !y) {\n return 'vertical';\n } else if (y && !x) {\n return 'horizontal';\n }\n }\n\n // falls through\n case LINE:\n case TICK: {\n const xIsMeasure = isUnbinnedQuantitativeFieldOrDatumDef(x);\n const yIsMeasure = isUnbinnedQuantitativeFieldOrDatumDef(y);\n\n if (specifiedOrient) {\n return specifiedOrient;\n } else if (xIsMeasure && !yIsMeasure) {\n // Tick is opposite to bar, line, area\n return mark !== 'tick' ? 'horizontal' : 'vertical';\n } else if (!xIsMeasure && yIsMeasure) {\n // Tick is opposite to bar, line, area\n return mark !== 'tick' ? 'vertical' : 'horizontal';\n } else if (xIsMeasure && yIsMeasure) {\n return 'vertical';\n } else {\n const xIsTemporal = isTypedFieldDef(x) && x.type === TEMPORAL;\n const yIsTemporal = isTypedFieldDef(y) && y.type === TEMPORAL;\n\n // x: T, y: N --> vertical tick\n if (xIsTemporal && !yIsTemporal) {\n return 'vertical';\n } else if (!xIsTemporal && yIsTemporal) {\n return 'horizontal';\n }\n }\n return undefined;\n }\n }\n return 'vertical';\n}\n","import type {SignalRef} from 'vega';\nimport {isObject} from 'vega-util';\nimport {Config} from '../config';\nimport {Encoding, normalizeEncoding} from '../encoding';\nimport {ExprRef} from '../expr';\nimport {AreaConfig, isMarkDef, LineConfig, Mark, MarkConfig, MarkDef} from '../mark';\nimport {GenericUnitSpec, NormalizedUnitSpec} from '../spec';\nimport {isUnitSpec} from '../spec/unit';\nimport {stack} from '../stack';\nimport {keys, omit, pick} from '../util';\nimport {NonFacetUnitNormalizer, NormalizeLayerOrUnit, NormalizerParams} from './base';\nimport {initMarkdef} from '../compile/mark/init';\n\ntype UnitSpecWithPathOverlay = GenericUnitSpec, Mark | MarkDef<'line' | 'area' | 'rule' | 'trail'>>;\n\nfunction dropLineAndPoint(markDef: MarkDef): MarkDef | Mark {\n const {point: _point, line: _line, ...mark} = markDef;\n\n return keys(mark).length > 1 ? mark : mark.type;\n}\n\nfunction dropLineAndPointFromConfig(config: Config) {\n for (const mark of ['line', 'area', 'rule', 'trail'] as const) {\n if (config[mark]) {\n config = {\n ...config,\n // TODO: remove as any\n [mark]: omit(config[mark], ['point', 'line'] as any)\n };\n }\n }\n return config;\n}\n\nfunction getPointOverlay(\n markDef: MarkDef,\n markConfig: LineConfig = {},\n encoding: Encoding\n): MarkConfig {\n if (markDef.point === 'transparent') {\n return {opacity: 0};\n } else if (markDef.point) {\n // truthy : true or object\n return isObject(markDef.point) ? markDef.point : {};\n } else if (markDef.point !== undefined) {\n // false or null\n return null;\n } else {\n // undefined (not disabled)\n if (markConfig.point || encoding.shape) {\n // enable point overlay if config[mark].point is truthy or if encoding.shape is provided\n return isObject(markConfig.point) ? markConfig.point : {};\n }\n // markDef.point is defined as falsy\n return undefined;\n }\n}\n\nfunction getLineOverlay(\n markDef: MarkDef,\n markConfig: AreaConfig = {}\n): MarkConfig {\n if (markDef.line) {\n // true or object\n return markDef.line === true ? {} : markDef.line;\n } else if (markDef.line !== undefined) {\n // false or null\n return null;\n } else {\n // undefined (not disabled)\n if (markConfig.line) {\n // enable line overlay if config[mark].line is truthy\n return markConfig.line === true ? {} : markConfig.line;\n }\n // markDef.point is defined as falsy\n return undefined;\n }\n}\n\nexport class PathOverlayNormalizer implements NonFacetUnitNormalizer {\n public name = 'path-overlay';\n\n public hasMatchingType(spec: GenericUnitSpec, config: Config): spec is UnitSpecWithPathOverlay {\n if (isUnitSpec(spec)) {\n const {mark, encoding} = spec;\n const markDef = isMarkDef(mark) ? mark : {type: mark};\n switch (markDef.type) {\n case 'line':\n case 'rule':\n case 'trail':\n return !!getPointOverlay(markDef, config[markDef.type], encoding);\n case 'area':\n return (\n // false / null are also included as we want to remove the properties\n !!getPointOverlay(markDef, config[markDef.type], encoding) ||\n !!getLineOverlay(markDef, config[markDef.type])\n );\n }\n }\n return false;\n }\n\n public run(spec: UnitSpecWithPathOverlay, normParams: NormalizerParams, normalize: NormalizeLayerOrUnit) {\n const {config} = normParams;\n const {params, projection, mark, name, encoding: e, ...outerSpec} = spec;\n\n // Need to call normalizeEncoding because we need the inferred types to correctly determine stack\n const encoding = normalizeEncoding(e, config);\n\n const markDef: MarkDef = isMarkDef(mark) ? mark : {type: mark};\n\n const pointOverlay = getPointOverlay(markDef, config[markDef.type], encoding);\n\n const lineOverlay = markDef.type === 'area' && getLineOverlay(markDef, config[markDef.type]);\n\n const layer: NormalizedUnitSpec[] = [\n {\n name,\n ...(params ? {params} : {}),\n mark: dropLineAndPoint({\n // TODO: extract this 0.7 to be shared with default opacity for point/tick/...\n ...(markDef.type === 'area' && markDef.opacity === undefined && markDef.fillOpacity === undefined\n ? {opacity: 0.7}\n : {}),\n ...markDef\n }),\n // drop shape from encoding as this might be used to trigger point overlay\n encoding: omit(encoding, ['shape'])\n }\n ];\n\n // FIXME: determine rules for applying selections.\n\n // Need to copy stack config to overlayed layer\n // FIXME: normalizer shouldn't call `initMarkdef`, a method from an init phase.\n const stackProps = stack(initMarkdef(markDef, encoding, config), encoding);\n\n let overlayEncoding = encoding;\n if (stackProps) {\n const {fieldChannel: stackFieldChannel, offset} = stackProps;\n overlayEncoding = {\n ...encoding,\n [stackFieldChannel]: {\n ...encoding[stackFieldChannel],\n ...(offset ? {stack: offset} : {})\n }\n };\n }\n\n // overlay line layer should be on the edge of area but passing y2/x2 makes\n // it as \"rule\" mark so that it draws unwanted vertical/horizontal lines.\n // point overlay also should not have y2/x2 as it does not support.\n overlayEncoding = omit(overlayEncoding, ['y2', 'x2']);\n\n if (lineOverlay) {\n layer.push({\n ...(projection ? {projection} : {}),\n mark: {\n type: 'line',\n ...pick(markDef, ['clip', 'interpolate', 'tension', 'tooltip']),\n ...lineOverlay\n },\n encoding: overlayEncoding\n });\n }\n if (pointOverlay) {\n layer.push({\n ...(projection ? {projection} : {}),\n mark: {\n type: 'point',\n opacity: 1,\n filled: true,\n ...pick(markDef, ['clip', 'tooltip']),\n ...pointOverlay\n },\n encoding: overlayEncoding\n });\n }\n\n return normalize(\n {\n ...outerSpec,\n layer\n },\n {\n ...normParams,\n config: dropLineAndPointFromConfig(config)\n }\n );\n }\n}\n","import {hasOwnProperty, isArray} from 'vega-util';\nimport {\n ChannelDef,\n DatumDef,\n Field,\n FieldDef,\n FieldName,\n hasConditionalFieldOrDatumDef,\n isConditionalDef,\n isFieldDef,\n isFieldOrDatumDef,\n isRepeatRef,\n isSortableFieldDef,\n ScaleFieldDef,\n ValueDef\n} from '../channeldef';\nimport {Encoding} from '../encoding';\nimport * as log from '../log';\nimport {isSortField} from '../sort';\nimport {FacetFieldDef, FacetMapping, isFacetMapping} from '../spec/facet';\n\nexport interface RepeaterValue {\n row?: string;\n column?: string;\n\n repeat?: string;\n\n layer?: string;\n}\n\nexport function replaceRepeaterInFacet(\n facet: FacetFieldDef | FacetMapping,\n repeater: RepeaterValue\n): FacetFieldDef | FacetMapping {\n if (!repeater) {\n return facet as FacetFieldDef;\n }\n\n if (isFacetMapping(facet)) {\n return replaceRepeaterInMapping(facet, repeater) as FacetMapping;\n }\n return replaceRepeaterInFieldDef(facet, repeater) as FacetFieldDef;\n}\n\nexport function replaceRepeaterInEncoding>(\n encoding: E,\n repeater: RepeaterValue\n): Encoding {\n if (!repeater) {\n return encoding as Encoding;\n }\n\n return replaceRepeaterInMapping(encoding, repeater) as Encoding;\n}\n\n/**\n * Replaces repeated value and returns if the repeated value is valid.\n */\nfunction replaceRepeatInProp(prop: keyof T, o: T, repeater: RepeaterValue): T {\n const val = o[prop];\n if (isRepeatRef(val)) {\n if (val.repeat in repeater) {\n return {...o, [prop]: repeater[val.repeat]};\n } else {\n log.warn(log.message.noSuchRepeatedValue(val.repeat));\n return undefined;\n }\n }\n return o;\n}\n\n/**\n * Replace repeater values in a field def with the concrete field name.\n */\n\nfunction replaceRepeaterInFieldDef(fieldDef: FieldDef, repeater: RepeaterValue) {\n fieldDef = replaceRepeatInProp('field', fieldDef, repeater);\n\n if (fieldDef === undefined) {\n // the field def should be ignored\n return undefined;\n } else if (fieldDef === null) {\n return null;\n }\n\n if (isSortableFieldDef(fieldDef) && isSortField(fieldDef.sort)) {\n const sort = replaceRepeatInProp('field', fieldDef.sort, repeater);\n fieldDef = {\n ...fieldDef,\n ...(sort ? {sort} : {})\n };\n }\n\n return fieldDef as ScaleFieldDef;\n}\n\nfunction replaceRepeaterInFieldOrDatumDef(def: FieldDef | DatumDef, repeater: RepeaterValue) {\n if (isFieldDef(def)) {\n return replaceRepeaterInFieldDef(def, repeater);\n } else {\n const datumDef = replaceRepeatInProp('datum', def, repeater);\n if (datumDef !== def && !datumDef.type) {\n datumDef.type = 'nominal';\n }\n return datumDef;\n }\n}\n\nfunction replaceRepeaterInChannelDef(channelDef: ChannelDef, repeater: RepeaterValue) {\n if (isFieldOrDatumDef(channelDef)) {\n const fd = replaceRepeaterInFieldOrDatumDef(channelDef, repeater);\n if (fd) {\n return fd;\n } else if (isConditionalDef>(channelDef)) {\n return {condition: channelDef.condition};\n }\n } else {\n if (hasConditionalFieldOrDatumDef(channelDef)) {\n const fd = replaceRepeaterInFieldOrDatumDef(channelDef.condition, repeater);\n if (fd) {\n return {\n ...channelDef,\n condition: fd\n } as ChannelDef;\n } else {\n const {condition, ...channelDefWithoutCondition} = channelDef;\n return channelDefWithoutCondition as ChannelDef;\n }\n }\n return channelDef as ValueDef;\n }\n return undefined;\n}\n\ntype EncodingOrFacet = Encoding | FacetMapping;\n\nfunction replaceRepeaterInMapping(\n mapping: EncodingOrFacet,\n repeater: RepeaterValue\n): EncodingOrFacet {\n const out: EncodingOrFacet = {};\n for (const channel in mapping) {\n if (hasOwnProperty(mapping, channel)) {\n const channelDef: ChannelDef | ChannelDef[] = mapping[channel];\n\n if (isArray(channelDef)) {\n // array cannot have condition\n out[channel] = (channelDef as ChannelDef[]) // somehow we need to cast it here\n .map(cd => replaceRepeaterInChannelDef(cd, repeater))\n .filter(cd => cd);\n } else {\n const cd = replaceRepeaterInChannelDef(channelDef, repeater);\n if (cd !== undefined) {\n out[channel] = cd;\n }\n }\n }\n }\n return out;\n}\n","import {isObject} from 'vega-util';\nimport {isBinned} from '../bin';\nimport {getMainRangeChannel, SECONDARY_RANGE_CHANNEL} from '../channel';\nimport {Field, isDatumDef, isFieldDef} from '../channeldef';\nimport {Encoding} from '../encoding';\nimport * as log from '../log';\nimport {isMarkDef} from '../mark';\nimport {GenericSpec} from '../spec';\nimport {GenericUnitSpec, isUnitSpec} from '../spec/unit';\nimport {NonFacetUnitNormalizer, NormalizeLayerOrUnit, NormalizerParams} from './base';\n\ninterface EncodingX2Mixins {\n x2: Encoding['x2'];\n}\n\ninterface EncodingY2Mixins {\n y2: Encoding['y2'];\n}\n\ntype RangedLineSpec = GenericUnitSpec & (EncodingX2Mixins | EncodingY2Mixins), 'line' | {mark: 'line'}>;\n\nexport class RuleForRangedLineNormalizer implements NonFacetUnitNormalizer {\n public name = 'RuleForRangedLine';\n\n public hasMatchingType(spec: GenericSpec): spec is RangedLineSpec {\n if (isUnitSpec(spec)) {\n const {encoding, mark} = spec;\n if (mark === 'line' || (isMarkDef(mark) && mark.type === 'line')) {\n for (const channel of SECONDARY_RANGE_CHANNEL) {\n const mainChannel = getMainRangeChannel(channel);\n const mainChannelDef = encoding[mainChannel];\n\n if (encoding[channel]) {\n if ((isFieldDef(mainChannelDef) && !isBinned(mainChannelDef.bin)) || isDatumDef(mainChannelDef)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n\n public run(spec: RangedLineSpec, params: NormalizerParams, normalize: NormalizeLayerOrUnit) {\n const {encoding, mark} = spec;\n log.warn(log.message.lineWithRange(!!encoding.x2, !!encoding.y2));\n\n return normalize(\n {\n ...spec,\n mark: isObject(mark) ? {...mark, type: 'rule'} : 'rule'\n },\n params\n );\n }\n}\n","import type {SignalRef} from 'vega';\nimport {isArray} from 'vega-util';\nimport {COLUMN, FACET, ROW} from '../channel';\nimport {Field, FieldName, hasConditionalFieldOrDatumDef, isFieldOrDatumDef, isValueDef} from '../channeldef';\nimport {SharedCompositeEncoding} from '../compositemark';\nimport {boxPlotNormalizer} from '../compositemark/boxplot';\nimport {errorBandNormalizer} from '../compositemark/errorband';\nimport {errorBarNormalizer} from '../compositemark/errorbar';\nimport {channelHasField, Encoding} from '../encoding';\nimport {ExprRef} from '../expr';\nimport * as log from '../log';\nimport {Projection} from '../projection';\nimport {FacetedUnitSpec, GenericSpec, LayerSpec, UnitSpec} from '../spec';\nimport {GenericCompositionLayoutWithColumns} from '../spec/base';\nimport {GenericConcatSpec} from '../spec/concat';\nimport {\n FacetEncodingFieldDef,\n FacetFieldDef,\n FacetMapping,\n GenericFacetSpec,\n isFacetMapping,\n NormalizedFacetSpec\n} from '../spec/facet';\nimport {NormalizedSpec} from '../spec/index';\nimport {NormalizedLayerSpec} from '../spec/layer';\nimport {SpecMapper} from '../spec/map';\nimport {isLayerRepeatSpec, LayerRepeatSpec, NonLayerRepeatSpec, RepeatSpec} from '../spec/repeat';\nimport {isUnitSpec, NormalizedUnitSpec} from '../spec/unit';\nimport {isEmpty, keys, omit, varName} from '../util';\nimport {isSignalRef} from '../vega.schema';\nimport {NonFacetUnitNormalizer, NormalizerParams} from './base';\nimport {PathOverlayNormalizer} from './pathoverlay';\nimport {replaceRepeaterInEncoding, replaceRepeaterInFacet} from './repeater';\nimport {RuleForRangedLineNormalizer} from './ruleforrangedline';\n\nexport class CoreNormalizer extends SpecMapper, LayerSpec> {\n private nonFacetUnitNormalizers: NonFacetUnitNormalizer[] = [\n boxPlotNormalizer,\n errorBarNormalizer,\n errorBandNormalizer,\n new PathOverlayNormalizer(),\n new RuleForRangedLineNormalizer()\n ];\n\n public map(spec: GenericSpec, LayerSpec, RepeatSpec, Field>, params: NormalizerParams) {\n // Special handling for a faceted unit spec as it can return a facet spec, not just a layer or unit spec like a normal unit spec.\n if (isUnitSpec(spec)) {\n const hasRow = channelHasField(spec.encoding, ROW);\n const hasColumn = channelHasField(spec.encoding, COLUMN);\n const hasFacet = channelHasField(spec.encoding, FACET);\n\n if (hasRow || hasColumn || hasFacet) {\n return this.mapFacetedUnit(spec, params);\n }\n }\n\n return super.map(spec, params);\n }\n\n // This is for normalizing non-facet unit\n public mapUnit(spec: UnitSpec, params: NormalizerParams): NormalizedUnitSpec | NormalizedLayerSpec {\n const {parentEncoding, parentProjection} = params;\n\n const encoding = replaceRepeaterInEncoding(spec.encoding, params.repeater);\n\n const specWithReplacedEncoding = {\n ...spec,\n ...(spec.name ? {name: [params.repeaterPrefix, spec.name].filter(n => n).join('_')} : {}),\n ...(encoding ? {encoding} : {})\n };\n\n if (parentEncoding || parentProjection) {\n return this.mapUnitWithParentEncodingOrProjection(specWithReplacedEncoding, params);\n }\n\n const normalizeLayerOrUnit = this.mapLayerOrUnit.bind(this);\n\n for (const unitNormalizer of this.nonFacetUnitNormalizers) {\n if (unitNormalizer.hasMatchingType(specWithReplacedEncoding, params.config)) {\n return unitNormalizer.run(specWithReplacedEncoding, params, normalizeLayerOrUnit);\n }\n }\n\n return specWithReplacedEncoding as NormalizedUnitSpec;\n }\n\n protected mapRepeat(\n spec: RepeatSpec,\n params: NormalizerParams\n ): GenericConcatSpec | NormalizedLayerSpec {\n if (isLayerRepeatSpec(spec)) {\n return this.mapLayerRepeat(spec, params);\n } else {\n return this.mapNonLayerRepeat(spec, params);\n }\n }\n\n private mapLayerRepeat(\n spec: LayerRepeatSpec,\n params: NormalizerParams\n ): GenericConcatSpec | NormalizedLayerSpec {\n const {repeat, spec: childSpec, ...rest} = spec;\n const {row, column, layer} = repeat;\n\n const {repeater = {}, repeaterPrefix = ''} = params;\n\n if (row || column) {\n return this.mapRepeat(\n {\n ...spec,\n repeat: {\n ...(row ? {row} : {}),\n ...(column ? {column} : {})\n },\n spec: {\n repeat: {layer},\n spec: childSpec\n }\n },\n params\n );\n } else {\n return {\n ...rest,\n layer: layer.map(layerValue => {\n const childRepeater = {\n ...repeater,\n layer: layerValue\n };\n\n const childName = `${(childSpec.name ? `${childSpec.name}_` : '') + repeaterPrefix}child__layer_${varName(\n layerValue\n )}`;\n\n const child = this.mapLayerOrUnit(childSpec, {...params, repeater: childRepeater, repeaterPrefix: childName});\n child.name = childName;\n\n return child;\n })\n };\n }\n }\n\n private mapNonLayerRepeat(spec: NonLayerRepeatSpec, params: NormalizerParams): GenericConcatSpec {\n const {repeat, spec: childSpec, data, ...remainingProperties} = spec;\n\n if (!isArray(repeat) && spec.columns) {\n // is repeat with row/column\n spec = omit(spec, ['columns']);\n log.warn(log.message.columnsNotSupportByRowCol('repeat'));\n }\n\n const concat: NormalizedSpec[] = [];\n\n const {repeater = {}, repeaterPrefix = ''} = params;\n\n const row = (!isArray(repeat) && repeat.row) || [repeater ? repeater.row : null];\n const column = (!isArray(repeat) && repeat.column) || [repeater ? repeater.column : null];\n\n const repeatValues = (isArray(repeat) && repeat) || [repeater ? repeater.repeat : null];\n\n // cross product\n for (const repeatValue of repeatValues) {\n for (const rowValue of row) {\n for (const columnValue of column) {\n const childRepeater = {\n repeat: repeatValue,\n row: rowValue,\n column: columnValue,\n layer: repeater.layer\n };\n\n const childName =\n (childSpec.name ? `${childSpec.name}_` : '') +\n repeaterPrefix +\n 'child__' +\n (isArray(repeat)\n ? `${varName(repeatValue)}`\n : (repeat.row ? `row_${varName(rowValue)}` : '') +\n (repeat.column ? `column_${varName(columnValue)}` : ''));\n\n const child = this.map(childSpec, {...params, repeater: childRepeater, repeaterPrefix: childName});\n child.name = childName;\n\n // we move data up\n concat.push(omit(child, ['data']) as NormalizedSpec);\n }\n }\n }\n\n const columns = isArray(repeat) ? spec.columns : repeat.column ? repeat.column.length : 1;\n return {\n data: childSpec.data ?? data, // data from child spec should have precedence\n align: 'all',\n ...remainingProperties,\n columns,\n concat\n };\n }\n\n protected mapFacet(\n spec: GenericFacetSpec, LayerSpec, Field>,\n params: NormalizerParams\n ): GenericFacetSpec {\n const {facet} = spec;\n\n if (isFacetMapping(facet) && spec.columns) {\n // is facet with row/column\n spec = omit(spec, ['columns']);\n log.warn(log.message.columnsNotSupportByRowCol('facet'));\n }\n\n return super.mapFacet(spec, params);\n }\n\n private mapUnitWithParentEncodingOrProjection(\n spec: FacetedUnitSpec,\n params: NormalizerParams\n ): NormalizedUnitSpec | NormalizedLayerSpec {\n const {encoding, projection} = spec;\n const {parentEncoding, parentProjection, config} = params;\n const mergedProjection = mergeProjection({parentProjection, projection});\n const mergedEncoding = mergeEncoding({\n parentEncoding,\n encoding: replaceRepeaterInEncoding(encoding, params.repeater)\n });\n\n return this.mapUnit(\n {\n ...spec,\n ...(mergedProjection ? {projection: mergedProjection} : {}),\n ...(mergedEncoding ? {encoding: mergedEncoding} : {})\n },\n {config}\n );\n }\n\n private mapFacetedUnit(spec: FacetedUnitSpec, normParams: NormalizerParams): NormalizedFacetSpec {\n // New encoding in the inside spec should not contain row / column\n // as row/column should be moved to facet\n const {row, column, facet, ...encoding} = spec.encoding;\n\n // Mark and encoding should be moved into the inner spec\n const {mark, width, projection, height, view, params, encoding: _, ...outerSpec} = spec;\n\n const {facetMapping, layout} = this.getFacetMappingAndLayout({row, column, facet}, normParams);\n\n const newEncoding = replaceRepeaterInEncoding(encoding, normParams.repeater);\n\n return this.mapFacet(\n {\n ...outerSpec,\n ...layout,\n\n // row / column has higher precedence than facet\n facet: facetMapping,\n spec: {\n ...(width ? {width} : {}),\n ...(height ? {height} : {}),\n ...(view ? {view} : {}),\n ...(projection ? {projection} : {}),\n mark,\n encoding: newEncoding,\n ...(params ? {params} : {})\n }\n },\n normParams\n );\n }\n\n private getFacetMappingAndLayout(\n facets: {\n row: FacetEncodingFieldDef;\n column: FacetEncodingFieldDef;\n facet: FacetEncodingFieldDef;\n },\n params: NormalizerParams\n ): {facetMapping: FacetMapping | FacetFieldDef; layout: GenericCompositionLayoutWithColumns} {\n const {row, column, facet} = facets;\n\n if (row || column) {\n if (facet) {\n log.warn(log.message.facetChannelDropped([...(row ? [ROW] : []), ...(column ? [COLUMN] : [])]));\n }\n\n const facetMapping = {};\n const layout = {};\n\n for (const channel of [ROW, COLUMN]) {\n const def = facets[channel];\n if (def) {\n const {align, center, spacing, columns, ...defWithoutLayout} = def;\n facetMapping[channel] = defWithoutLayout;\n\n for (const prop of ['align', 'center', 'spacing'] as const) {\n if (def[prop] !== undefined) {\n layout[prop] ??= {};\n layout[prop][channel] = def[prop];\n }\n }\n }\n }\n\n return {facetMapping, layout};\n } else {\n const {align, center, spacing, columns, ...facetMapping} = facet;\n return {\n facetMapping: replaceRepeaterInFacet(facetMapping, params.repeater),\n layout: {\n ...(align ? {align} : {}),\n ...(center ? {center} : {}),\n ...(spacing ? {spacing} : {}),\n ...(columns ? {columns} : {})\n }\n };\n }\n }\n\n public mapLayer(\n spec: LayerSpec,\n {parentEncoding, parentProjection, ...otherParams}: NormalizerParams\n ): NormalizedLayerSpec {\n // Special handling for extended layer spec\n\n const {encoding, projection, ...rest} = spec;\n const params: NormalizerParams = {\n ...otherParams,\n parentEncoding: mergeEncoding({parentEncoding, encoding, layer: true}),\n parentProjection: mergeProjection({parentProjection, projection})\n };\n return super.mapLayer(\n {\n ...rest,\n ...(spec.name ? {name: [params.repeaterPrefix, spec.name].filter(n => n).join('_')} : {})\n },\n params\n );\n }\n}\n\nfunction mergeEncoding({\n parentEncoding,\n encoding = {},\n layer\n}: {\n parentEncoding: SharedCompositeEncoding;\n encoding: SharedCompositeEncoding | Encoding;\n layer?: boolean;\n}): Encoding {\n let merged: any = {};\n if (parentEncoding) {\n const channels = new Set([...keys(parentEncoding), ...keys(encoding)]);\n for (const channel of channels) {\n const channelDef = encoding[channel];\n const parentChannelDef = parentEncoding[channel];\n\n if (isFieldOrDatumDef(channelDef)) {\n // Field/Datum Def can inherit properties from its parent\n // Note that parentChannelDef doesn't have to be a field/datum def if the channelDef is already one.\n const mergedChannelDef = {\n ...parentChannelDef,\n ...channelDef\n };\n merged[channel] = mergedChannelDef;\n } else if (hasConditionalFieldOrDatumDef(channelDef)) {\n merged[channel] = {\n ...channelDef,\n condition: {\n ...parentChannelDef,\n ...channelDef.condition\n }\n };\n } else if (channelDef || channelDef === null) {\n merged[channel] = channelDef;\n } else if (\n layer ||\n isValueDef(parentChannelDef) ||\n isSignalRef(parentChannelDef) ||\n isFieldOrDatumDef(parentChannelDef) ||\n isArray(parentChannelDef)\n ) {\n merged[channel] = parentChannelDef;\n }\n }\n } else {\n merged = encoding;\n }\n return !merged || isEmpty(merged) ? undefined : merged;\n}\n\nfunction mergeProjection(opt: {\n parentProjection: Projection;\n projection: Projection;\n}) {\n const {parentProjection, projection} = opt;\n if (parentProjection && projection) {\n log.warn(log.message.projectionOverridden({parentProjection, projection}));\n }\n return projection ?? parentProjection;\n}\n","import {AggregateOp} from 'vega';\nimport {BinParams} from './bin';\nimport {FieldName} from './channeldef';\nimport {Data} from './data';\nimport {ImputeParams} from './impute';\nimport {LogicalComposition, normalizeLogicalComposition} from './logical';\nimport {ParameterName} from './parameter';\nimport {normalizePredicate, Predicate} from './predicate';\nimport {SortField} from './sort';\nimport {TimeUnit, TimeUnitTransformParams} from './timeunit';\n\nexport interface FilterTransform {\n /**\n * The `filter` property must be a predication definition, which can take one of the following forms:\n *\n * 1) an [expression](https://vega.github.io/vega-lite/docs/types.html#expression) string,\n * where `datum` can be used to refer to the current data object.\n * For example, `{filter: \"datum.b2 > 60\"}` would make the output data includes only items that have values in the field `b2` over 60.\n *\n * 2) one of the [field predicates](https://vega.github.io/vega-lite/docs/predicate.html#field-predicate):\n * [`equal`](https://vega.github.io/vega-lite/docs/predicate.html#field-equal-predicate),\n * [`lt`](https://vega.github.io/vega-lite/docs/predicate.html#lt-predicate),\n * [`lte`](https://vega.github.io/vega-lite/docs/predicate.html#lte-predicate),\n * [`gt`](https://vega.github.io/vega-lite/docs/predicate.html#gt-predicate),\n * [`gte`](https://vega.github.io/vega-lite/docs/predicate.html#gte-predicate),\n * [`range`](https://vega.github.io/vega-lite/docs/predicate.html#range-predicate),\n * [`oneOf`](https://vega.github.io/vega-lite/docs/predicate.html#one-of-predicate),\n * or [`valid`](https://vega.github.io/vega-lite/docs/predicate.html#valid-predicate),\n\n * 3) a [selection predicate](https://vega.github.io/vega-lite/docs/predicate.html#selection-predicate), which define the names of a selection that the data point should belong to (or a logical composition of selections).\n *\n * 4) a [logical composition](https://vega.github.io/vega-lite/docs/predicate.html#composition) of (1), (2), or (3).\n */\n filter: LogicalComposition;\n}\n\nexport function isFilter(t: Transform): t is FilterTransform {\n return 'filter' in t;\n}\n\nexport interface CalculateTransform {\n /**\n * A [expression](https://vega.github.io/vega-lite/docs/types.html#expression) string. Use the variable `datum` to refer to the current data object.\n */\n calculate: string;\n\n /**\n * The field for storing the computed formula value.\n */\n as: FieldName;\n}\n\nexport interface BinTransform {\n /**\n * An object indicating bin properties, or simply `true` for using default bin parameters.\n */\n bin: true | BinParams;\n\n /**\n * The data field to bin.\n */\n field: FieldName;\n\n /**\n * The output fields at which to write the start and end bin values.\n * This can be either a string or an array of strings with two elements denoting the name for the fields for bin start and bin end respectively.\n * If a single string (e.g., `\"val\"`) is provided, the end field will be `\"val_end\"`.\n */\n as: FieldName | FieldName[];\n}\n\nexport interface TimeUnitTransform {\n /**\n * The timeUnit.\n */\n timeUnit: TimeUnit | TimeUnitTransformParams;\n\n /**\n * The data field to apply time unit.\n */\n field: FieldName;\n\n /**\n * The output field to write the timeUnit value.\n */\n as: FieldName;\n}\n\nexport interface AggregateTransform {\n /**\n * Array of objects that define fields to aggregate.\n */\n aggregate: AggregatedFieldDef[];\n\n /**\n * The data fields to group by. If not specified, a single group containing all data objects will be used.\n */\n groupby?: FieldName[];\n}\n\nexport interface AggregatedFieldDef {\n /**\n * The aggregation operation to apply to the fields (e.g., `\"sum\"`, `\"average\"`, or `\"count\"`).\n * See the [full list of supported aggregation operations](https://vega.github.io/vega-lite/docs/aggregate.html#ops)\n * for more information.\n */\n op: AggregateOp;\n\n /**\n * The data field for which to compute aggregate function. This is required for all aggregation operations except `\"count\"`.\n */\n field?: FieldName;\n\n /**\n * The output field names to use for each aggregated field.\n */\n as: FieldName;\n}\n\nexport interface StackTransform {\n /**\n * The field which is stacked.\n */\n stack: FieldName;\n /**\n * The data fields to group by.\n */\n groupby: FieldName[];\n /**\n * Mode for stacking marks. One of `\"zero\"` (default), `\"center\"`, or `\"normalize\"`.\n * The `\"zero\"` offset will stack starting at `0`. The `\"center\"` offset will center the stacks. The `\"normalize\"` offset will compute percentage values for each stack point, with output values in the range `[0,1]`.\n *\n * __Default value:__ `\"zero\"`\n */\n offset?: 'zero' | 'center' | 'normalize';\n /**\n * Field that determines the order of leaves in the stacked charts.\n */\n sort?: SortField[];\n /**\n * Output field names. This can be either a string or an array of strings with two elements denoting the name for the fields for stack start and stack end respectively.\n * If a single string(e.g., `\"val\"`) is provided, the end field will be `\"val_end\"`.\n */\n as: FieldName | [FieldName, FieldName];\n}\n\nexport type WindowOnlyOp =\n | 'row_number'\n | 'rank'\n | 'dense_rank'\n | 'percent_rank'\n | 'cume_dist'\n | 'ntile'\n | 'lag'\n | 'lead'\n | 'first_value'\n | 'last_value'\n | 'nth_value';\n\nexport interface WindowFieldDef {\n /**\n * The window or aggregation operation to apply within a window (e.g., `\"rank\"`, `\"lead\"`, `\"sum\"`, `\"average\"` or `\"count\"`). See the list of all supported operations [here](https://vega.github.io/vega-lite/docs/window.html#ops).\n */\n op: AggregateOp | WindowOnlyOp;\n\n /**\n * Parameter values for the window functions. Parameter values can be omitted for operations that do not accept a parameter.\n *\n * See the list of all supported operations and their parameters [here](https://vega.github.io/vega-lite/docs/transforms/window.html).\n */\n param?: number;\n\n /**\n * The data field for which to compute the aggregate or window function. This can be omitted for window functions that do not operate over a field such as `\"count\"`, `\"rank\"`, `\"dense_rank\"`.\n */\n field?: FieldName;\n\n /**\n * The output name for the window operation.\n */\n as: FieldName;\n}\n\nexport interface WindowTransform {\n /**\n * The definition of the fields in the window, and what calculations to use.\n */\n window: WindowFieldDef[];\n\n /**\n * A frame specification as a two-element array indicating how the sliding window should proceed. The array entries should either be a number indicating the offset from the current data object, or null to indicate unbounded rows preceding or following the current data object. The default value is `[null, 0]`, indicating that the sliding window includes the current object and all preceding objects. The value `[-5, 5]` indicates that the window should include five objects preceding and five objects following the current object. Finally, `[null, null]` indicates that the window frame should always include all data objects. If you this frame and want to assign the same value to add objects, you can use the simpler [join aggregate transform](https://vega.github.io/vega-lite/docs/joinaggregate.html). The only operators affected are the aggregation operations and the `first_value`, `last_value`, and `nth_value` window operations. The other window operations are not affected by this.\n *\n * __Default value:__: `[null, 0]` (includes the current object and all preceding objects)\n */\n frame?: (null | number)[];\n\n /**\n * Indicates if the sliding window frame should ignore peer values (data that are considered identical by the sort criteria). The default is false, causing the window frame to expand to include all peer values. If set to true, the window frame will be defined by offset values only. This setting only affects those operations that depend on the window frame, namely aggregation operations and the first_value, last_value, and nth_value window operations.\n *\n * __Default value:__ `false`\n */\n ignorePeers?: boolean;\n\n /**\n * The data fields for partitioning the data objects into separate windows. If unspecified, all data points will be in a single window.\n */\n groupby?: FieldName[];\n\n /**\n * A sort field definition for sorting data objects within a window. If two data objects are considered equal by the comparator, they are considered \"peer\" values of equal rank. If sort is not specified, the order is undefined: data objects are processed in the order they are observed and none are considered peers (the ignorePeers parameter is ignored and treated as if set to `true`).\n */\n sort?: SortField[];\n}\n\nexport interface JoinAggregateFieldDef {\n /**\n * The aggregation operation to apply (e.g., `\"sum\"`, `\"average\"` or `\"count\"`). See the list of all supported operations [here](https://vega.github.io/vega-lite/docs/aggregate.html#ops).\n */\n op: AggregateOp;\n\n /**\n * The data field for which to compute the aggregate function. This can be omitted for functions that do not operate over a field such as `\"count\"`.\n */\n field?: FieldName;\n\n /**\n * The output name for the join aggregate operation.\n */\n as: FieldName;\n}\n\nexport interface JoinAggregateTransform {\n /**\n * The definition of the fields in the join aggregate, and what calculations to use.\n */\n joinaggregate: JoinAggregateFieldDef[];\n\n /**\n * The data fields for partitioning the data objects into separate groups. If unspecified, all data points will be in a single group.\n */\n groupby?: FieldName[];\n}\n\nexport interface ImputeSequence {\n /**\n * The starting value of the sequence.\n * __Default value:__ `0`\n */\n start?: number;\n /**\n * The ending value(exclusive) of the sequence.\n */\n stop: number;\n /**\n * The step value between sequence entries.\n * __Default value:__ `1` or `-1` if `stop < start`\n */\n step?: number;\n}\n\nexport function isImputeSequence(t: ImputeSequence | any[] | undefined): t is ImputeSequence {\n return t?.['stop'] !== undefined;\n}\n\nexport interface ImputeTransform extends ImputeParams {\n /**\n * The data field for which the missing values should be imputed.\n */\n impute: FieldName;\n\n /**\n * A key field that uniquely identifies data objects within a group.\n * Missing key values (those occurring in the data but not in the current group) will be imputed.\n */\n key: FieldName;\n\n /**\n * An optional array of fields by which to group the values.\n * Imputation will then be performed on a per-group basis.\n */\n groupby?: FieldName[];\n}\n\nexport interface FlattenTransform {\n /**\n * An array of one or more data fields containing arrays to flatten.\n * If multiple fields are specified, their array values should have a parallel structure, ideally with the same length.\n * If the lengths of parallel arrays do not match,\n * the longest array will be used with `null` values added for missing entries.\n */\n flatten: FieldName[];\n\n /**\n * The output field names for extracted array values.\n *\n * __Default value:__ The field name of the corresponding array field\n */\n as?: FieldName[];\n}\n\nexport interface SampleTransform {\n /**\n * The maximum number of data objects to include in the sample.\n *\n * __Default value:__ `1000`\n */\n sample: number;\n}\n\nexport interface LookupBase {\n /**\n * Key in data to lookup.\n */\n key: FieldName;\n /**\n * Fields in foreign data or selection to lookup.\n * If not specified, the entire object is queried.\n */\n fields?: FieldName[];\n}\n\nexport interface LookupData extends LookupBase {\n /**\n * Secondary data source to lookup in.\n */\n data: Data;\n}\n\nexport interface LookupSelection extends LookupBase {\n /**\n * Selection parameter name to look up.\n */\n param: ParameterName;\n}\n\nexport interface LookupTransform {\n /**\n * Key in primary data source.\n */\n lookup: string;\n\n /**\n * The output fields on which to store the looked up data values.\n *\n * For data lookups, this property may be left blank if `from.fields`\n * has been specified (those field names will be used); if `from.fields`\n * has not been specified, `as` must be a string.\n *\n * For selection lookups, this property is optional: if unspecified,\n * looked up values will be stored under a property named for the selection;\n * and if specified, it must correspond to `from.fields`.\n */\n as?: FieldName | FieldName[];\n\n /**\n * The default value to use if lookup fails.\n *\n * __Default value:__ `null`\n */\n default?: any;\n\n /**\n * Data source or selection for secondary data reference.\n */\n from: LookupData | LookupSelection;\n}\n\nexport function isLookup(t: Transform): t is LookupTransform {\n return 'lookup' in t;\n}\n\nexport function isLookupData(from: LookupData | LookupSelection): from is LookupData {\n return 'data' in from;\n}\n\nexport function isLookupSelection(from: LookupData | LookupSelection): from is LookupSelection {\n return 'param' in from;\n}\n\nexport interface FoldTransform {\n /**\n * An array of data fields indicating the properties to fold.\n */\n fold: FieldName[];\n\n /**\n * The output field names for the key and value properties produced by the fold transform.\n * __Default value:__ `[\"key\", \"value\"]`\n */\n as?: [FieldName, FieldName];\n}\n\nexport interface ExtentTransform {\n /**\n * The field of which to get the extent.\n */\n extent: FieldName;\n\n /**\n * The output parameter produced by the extent transform.\n */\n param: ParameterName;\n}\n\nexport interface PivotTransform {\n /**\n * The data field to pivot on. The unique values of this field become new field names in the output stream.\n */\n pivot: FieldName;\n\n /**\n * The data field to populate pivoted fields. The aggregate values of this field become the values of the new pivoted fields.\n */\n value: FieldName;\n\n /**\n * The optional data fields to group by. If not specified, a single group containing all data objects will be used.\n */\n groupby?: FieldName[];\n\n /**\n * An optional parameter indicating the maximum number of pivoted fields to generate.\n * The default (`0`) applies no limit. The pivoted `pivot` names are sorted in ascending order prior to enforcing the limit.\n * __Default value:__ `0`\n */\n limit?: number;\n\n /**\n * The aggregation operation to apply to grouped `value` field values.\n * __Default value:__ `sum`\n */\n op?: AggregateOp;\n}\n\nexport function isPivot(t: Transform): t is PivotTransform {\n return 'pivot' in t;\n}\n\nexport interface DensityTransform {\n /**\n * The data field for which to perform density estimation.\n */\n density: FieldName;\n\n /**\n * The data fields to group by. If not specified, a single group containing all data objects will be used.\n */\n groupby?: FieldName[];\n\n /**\n * A boolean flag indicating whether to produce density estimates (false) or cumulative density estimates (true).\n *\n * __Default value:__ `false`\n */\n cumulative?: boolean;\n\n /**\n * A boolean flag indicating if the output values should be probability estimates (false) or smoothed counts (true).\n *\n * __Default value:__ `false`\n */\n counts?: boolean;\n\n /**\n * The bandwidth (standard deviation) of the Gaussian kernel. If unspecified or set to zero, the bandwidth value is automatically estimated from the input data using Scott’s rule.\n */\n bandwidth?: number;\n\n /**\n * A [min, max] domain from which to sample the distribution. If unspecified, the extent will be determined by the observed minimum and maximum values of the density value field.\n */\n extent?: [number, number];\n\n /**\n * The minimum number of samples to take along the extent domain for plotting the density.\n *\n * __Default value:__ `25`\n */\n minsteps?: number;\n\n /**\n * The maximum number of samples to take along the extent domain for plotting the density.\n *\n * __Default value:__ `200`\n */\n maxsteps?: number;\n\n /**\n * The exact number of samples to take along the extent domain for plotting the density. If specified, overrides both minsteps and maxsteps to set an exact number of uniform samples. Potentially useful in conjunction with a fixed extent to ensure consistent sample points for stacked densities.\n */\n steps?: number;\n\n /**\n * The output fields for the sample value and corresponding density estimate.\n *\n * __Default value:__ `[\"value\", \"density\"]`\n */\n as?: [FieldName, FieldName];\n /**\n * Indicates how parameters for multiple densities should be resolved.\n * If `\"independent\"`, each density may have its own domain extent and dynamic number of curve sample steps.\n * If `\"shared\"`, the KDE transform will ensure that all densities are defined over a shared domain and curve steps, enabling stacking.\n *\n * __Default value:__ `\"shared\"`\n */\n resolve?: 'independent' | 'shared';\n}\n\nexport function isDensity(t: Transform): t is DensityTransform {\n return 'density' in t;\n}\n\nexport interface QuantileTransform {\n /**\n * The data field for which to perform quantile estimation.\n */\n quantile: FieldName;\n\n /**\n * The data fields to group by. If not specified, a single group containing all data objects will be used.\n */\n groupby?: FieldName[];\n\n /**\n * An array of probabilities in the range (0, 1) for which to compute quantile values. If not specified, the *step* parameter will be used.\n */\n probs?: number[];\n\n /**\n * A probability step size (default 0.01) for sampling quantile values. All values from one-half the step size up to 1 (exclusive) will be sampled. This parameter is only used if the *probs* parameter is not provided.\n */\n step?: number;\n\n /**\n * The output field names for the probability and quantile values.\n *\n * __Default value:__ `[\"prob\", \"value\"]`\n */\n as?: [FieldName, FieldName];\n}\n\nexport function isQuantile(t: Transform): t is QuantileTransform {\n return 'quantile' in t;\n}\n\nexport interface RegressionTransform {\n /**\n * The data field of the dependent variable to predict.\n */\n regression: FieldName;\n\n /**\n * The data field of the independent variable to use a predictor.\n */\n on: FieldName;\n\n /**\n * The data fields to group by. If not specified, a single group containing all data objects will be used.\n */\n groupby?: FieldName[];\n\n /**\n * The functional form of the regression model. One of `\"linear\"`, `\"log\"`, `\"exp\"`, `\"pow\"`, `\"quad\"`, or `\"poly\"`.\n *\n * __Default value:__ `\"linear\"`\n */\n method?: 'linear' | 'log' | 'exp' | 'pow' | 'quad' | 'poly';\n\n /**\n * The polynomial order (number of coefficients) for the 'poly' method.\n *\n * __Default value:__ `3`\n */\n order?: number;\n\n /**\n * A [min, max] domain over the independent (x) field for the starting and ending points of the generated trend line.\n */\n extent?: [number, number];\n\n /**\n * A boolean flag indicating if the transform should return the regression model parameters (one object per group), rather than trend line points.\n * The resulting objects include a `coef` array of fitted coefficient values (starting with the intercept term and then including terms of increasing order)\n * and an `rSquared` value (indicating the total variance explained by the model).\n *\n * __Default value:__ `false`\n */\n params?: boolean;\n\n /**\n * The output field names for the smoothed points generated by the regression transform.\n *\n * __Default value:__ The field names of the input x and y values.\n */\n as?: [FieldName, FieldName];\n}\n\nexport function isRegression(t: Transform): t is RegressionTransform {\n return 'regression' in t;\n}\n\nexport interface LoessTransform {\n /**\n * The data field of the dependent variable to smooth.\n */\n loess: FieldName;\n\n /**\n * The data field of the independent variable to use a predictor.\n */\n on: FieldName;\n\n /**\n * The data fields to group by. If not specified, a single group containing all data objects will be used.\n */\n groupby?: FieldName[];\n\n /**\n * A bandwidth parameter in the range `[0, 1]` that determines the amount of smoothing.\n *\n * __Default value:__ `0.3`\n */\n bandwidth?: number;\n\n /**\n * The output field names for the smoothed points generated by the loess transform.\n *\n * __Default value:__ The field names of the input x and y values.\n */\n as?: [FieldName, FieldName];\n}\n\nexport function isLoess(t: Transform): t is LoessTransform {\n return 'loess' in t;\n}\n\nexport function isSample(t: Transform): t is SampleTransform {\n return 'sample' in t;\n}\n\nexport function isWindow(t: Transform): t is WindowTransform {\n return 'window' in t;\n}\n\nexport function isJoinAggregate(t: Transform): t is JoinAggregateTransform {\n return 'joinaggregate' in t;\n}\n\nexport function isFlatten(t: Transform): t is FlattenTransform {\n return 'flatten' in t;\n}\nexport function isCalculate(t: Transform): t is CalculateTransform {\n return 'calculate' in t;\n}\n\nexport function isBin(t: Transform): t is BinTransform {\n return 'bin' in t;\n}\n\nexport function isImpute(t: Transform): t is ImputeTransform {\n return 'impute' in t;\n}\n\nexport function isTimeUnit(t: Transform): t is TimeUnitTransform {\n return 'timeUnit' in t;\n}\n\nexport function isAggregate(t: Transform): t is AggregateTransform {\n return 'aggregate' in t;\n}\n\nexport function isStack(t: Transform): t is StackTransform {\n return 'stack' in t;\n}\n\nexport function isFold(t: Transform): t is FoldTransform {\n return 'fold' in t;\n}\n\nexport function isExtent(t: Transform): t is ExtentTransform {\n return 'extent' in t && !('density' in t) && !('regression' in t);\n}\nexport type Transform =\n | AggregateTransform\n | BinTransform\n | CalculateTransform\n | DensityTransform\n | ExtentTransform\n | FilterTransform\n | FlattenTransform\n | FoldTransform\n | ImputeTransform\n | JoinAggregateTransform\n | LoessTransform\n | LookupTransform\n | QuantileTransform\n | RegressionTransform\n | TimeUnitTransform\n | SampleTransform\n | StackTransform\n | WindowTransform\n | PivotTransform;\n\nexport function normalizeTransform(transform: Transform[]) {\n return transform.map(t => {\n if (isFilter(t)) {\n return {\n filter: normalizeLogicalComposition(t.filter, normalizePredicate)\n };\n }\n return t;\n });\n}\n","import {isArray} from 'vega';\nimport {BinParams, isBinParams} from '../bin';\nimport {ChannelDef, Field, isConditionalDef, isFieldDef, isScaleFieldDef} from '../channeldef';\nimport {LogicalComposition, normalizeLogicalComposition} from '../logical';\nimport {FacetedUnitSpec, GenericSpec, LayerSpec, RepeatSpec, UnitSpec} from '../spec';\nimport {SpecMapper} from '../spec/map';\nimport {isBin, isFilter, isLookup} from '../transform';\nimport {duplicate, entries, vals} from '../util';\nimport {NormalizerParams} from './base';\n\nexport class SelectionCompatibilityNormalizer extends SpecMapper<\n NormalizerParams,\n FacetedUnitSpec,\n LayerSpec,\n UnitSpec\n> {\n public map(\n spec: GenericSpec, LayerSpec, RepeatSpec, Field>,\n normParams: NormalizerParams\n ) {\n normParams.emptySelections ??= {};\n normParams.selectionPredicates ??= {};\n spec = normalizeTransforms(spec, normParams);\n return super.map(spec, normParams);\n }\n\n public mapLayerOrUnit(spec: FacetedUnitSpec | LayerSpec, normParams: NormalizerParams) {\n spec = normalizeTransforms(spec, normParams);\n\n if (spec.encoding) {\n const encoding = {};\n for (const [channel, enc] of entries(spec.encoding)) {\n encoding[channel] = normalizeChannelDef(enc, normParams);\n }\n\n spec = {...spec, encoding};\n }\n\n return super.mapLayerOrUnit(spec, normParams);\n }\n\n public mapUnit(spec: UnitSpec, normParams: NormalizerParams) {\n const {selection, ...rest} = spec as any;\n if (selection) {\n return {\n ...rest,\n params: entries(selection).map(([name, selDef]) => {\n const {init: value, bind, empty, ...select} = selDef as any;\n if (select.type === 'single') {\n select.type = 'point';\n select.toggle = false;\n } else if (select.type === 'multi') {\n select.type = 'point';\n }\n\n // Propagate emptiness forwards and backwards\n normParams.emptySelections[name] = empty !== 'none';\n for (const pred of vals(normParams.selectionPredicates[name] ?? {})) {\n pred.empty = empty !== 'none';\n }\n\n return {name, value, select, bind};\n })\n };\n }\n\n return spec;\n }\n}\n\nfunction normalizeTransforms(spec: any, normParams: NormalizerParams) {\n const {transform: tx, ...rest} = spec;\n if (tx) {\n const transform = tx.map((t: any) => {\n if (isFilter(t)) {\n return {filter: normalizePredicate(t, normParams)};\n } else if (isBin(t) && isBinParams(t.bin)) {\n return {\n ...t,\n bin: normalizeBinExtent(t.bin)\n };\n } else if (isLookup(t)) {\n const {selection: param, ...from} = t.from as any;\n return param\n ? {\n ...t,\n from: {param, ...from}\n }\n : t;\n }\n return t;\n });\n\n return {...rest, transform};\n }\n\n return spec;\n}\n\nfunction normalizeChannelDef(obj: any, normParams: NormalizerParams): ChannelDef {\n const enc = duplicate(obj);\n\n if (isFieldDef(enc) && isBinParams(enc.bin)) {\n enc.bin = normalizeBinExtent(enc.bin);\n }\n\n if (isScaleFieldDef(enc) && (enc.scale?.domain as any)?.selection) {\n const {selection: param, ...domain} = enc.scale.domain as any;\n enc.scale.domain = {...domain, ...(param ? {param} : {})};\n }\n\n if (isConditionalDef(enc)) {\n if (isArray(enc.condition)) {\n enc.condition = enc.condition.map((c: any) => {\n const {selection, param, test, ...cond} = c;\n return param ? c : {...cond, test: normalizePredicate(c, normParams)};\n });\n } else {\n const {selection, param, test, ...cond} = normalizeChannelDef(enc.condition, normParams) as any;\n enc.condition = param\n ? enc.condition\n : {\n ...cond,\n test: normalizePredicate(enc.condition, normParams)\n };\n }\n }\n\n return enc;\n}\n\nfunction normalizeBinExtent(bin: BinParams): BinParams {\n const ext = bin.extent as any;\n if (ext?.selection) {\n const {selection: param, ...rest} = ext;\n return {...bin, extent: {...rest, param}};\n }\n\n return bin;\n}\n\nfunction normalizePredicate(op: any, normParams: NormalizerParams) {\n // Normalize old compositions of selection names (e.g., selection: {and: [\"one\", \"two\"]})\n const normalizeSelectionComposition = (o: LogicalComposition) => {\n return normalizeLogicalComposition(o, param => {\n const empty = normParams.emptySelections[param] ?? true;\n const pred = {param, empty};\n normParams.selectionPredicates[param] ??= [];\n normParams.selectionPredicates[param].push(pred);\n return pred as any;\n });\n };\n\n return op.selection\n ? normalizeSelectionComposition(op.selection)\n : normalizeLogicalComposition(op.test || op.filter, o =>\n o.selection ? normalizeSelectionComposition(o.selection) : o\n );\n}\n","import {isArray, isString} from 'vega';\nimport {Field} from '../channeldef';\nimport {VariableParameter} from '../parameter';\nimport {isSelectionParameter, SelectionParameter} from '../selection';\nimport {\n BaseSpec,\n isUnitSpec,\n NormalizedLayerSpec,\n NormalizedSpec,\n NormalizedUnitSpec,\n TopLevel,\n UnitSpec\n} from '../spec';\nimport {SpecMapper} from '../spec/map';\nimport {NormalizerParams} from './base';\n\nexport class TopLevelSelectionsNormalizer extends SpecMapper {\n public map(spec: TopLevel, normParams: NormalizerParams): TopLevel {\n const selections = normParams.selections ?? [];\n if (spec.params && !isUnitSpec(spec)) {\n const params: VariableParameter[] = [];\n for (const param of spec.params) {\n if (isSelectionParameter(param)) {\n selections.push(param);\n } else {\n params.push(param);\n }\n }\n\n spec.params = params;\n }\n\n normParams.selections = selections;\n return super.map(spec, normParams);\n }\n\n public mapUnit(spec: UnitSpec, normParams: NormalizerParams): NormalizedUnitSpec | NormalizedLayerSpec {\n const selections = normParams.selections;\n if (!selections || !selections.length) return spec as NormalizedUnitSpec;\n\n const path = (normParams.path ?? []).concat(spec.name);\n const params: SelectionParameter[] = [];\n\n for (const selection of selections) {\n // By default, apply selections to all unit views.\n if (!selection.views || !selection.views.length) {\n params.push(selection);\n } else {\n for (const view of selection.views) {\n // view is either a specific unit name, or a partial path through the spec tree.\n if (\n (isString(view) && (view === spec.name || path.includes(view))) ||\n (isArray(view) &&\n // logic for backwards compatibility with view paths before we had unique names\n // @ts-ignore\n view.map(v => path.indexOf(v)).every((v, i, arr) => v !== -1 && (i === 0 || v > arr[i - 1])))\n ) {\n params.push(selection);\n }\n }\n }\n }\n\n if (params.length) spec.params = params;\n return spec as NormalizedUnitSpec;\n }\n}\n\nfor (const method of ['mapFacet', 'mapRepeat', 'mapHConcat', 'mapVConcat', 'mapLayer']) {\n const proto = TopLevelSelectionsNormalizer.prototype[method];\n TopLevelSelectionsNormalizer.prototype[method] = function (spec: BaseSpec, params: NormalizerParams) {\n return proto.call(this, spec, addSpecNameToParams(spec, params));\n };\n}\n\nfunction addSpecNameToParams(spec: BaseSpec, params: NormalizerParams) {\n return spec.name\n ? {\n ...params,\n path: (params.path ?? []).concat(spec.name)\n }\n : params;\n}\n","import type {SignalRef} from 'vega';\nimport {isString} from 'vega-util';\nimport {Field} from '../channeldef';\nimport {Config, initConfig} from '../config';\nimport * as log from '../log';\nimport {\n FacetedUnitSpec,\n isLayerSpec,\n isUnitSpec,\n LayoutSizeMixins,\n NonNormalizedSpec,\n NormalizedSpec,\n RepeatSpec,\n TopLevelSpec\n} from '../spec';\nimport {AutoSizeParams, AutosizeType, TopLevel} from '../spec/toplevel';\nimport {deepEqual} from '../util';\nimport {NormalizerParams} from './base';\nimport {CoreNormalizer} from './core';\nimport {SelectionCompatibilityNormalizer} from './selectioncompat';\nimport {TopLevelSelectionsNormalizer} from './toplevelselection';\n\nexport function normalize(\n spec: TopLevelSpec & LayoutSizeMixins,\n config?: Config\n): TopLevel & LayoutSizeMixins {\n if (config === undefined) {\n config = initConfig(spec.config);\n }\n\n const normalizedSpec = normalizeGenericSpec(spec, config);\n\n const {width, height} = spec;\n const autosize = normalizeAutoSize(normalizedSpec, {width, height, autosize: spec.autosize}, config);\n\n return {\n ...normalizedSpec,\n ...(autosize ? {autosize} : {})\n };\n}\n\nconst coreNormalizer = new CoreNormalizer();\nconst selectionCompatNormalizer = new SelectionCompatibilityNormalizer();\nconst topLevelSelectionNormalizer = new TopLevelSelectionsNormalizer();\n\n/**\n * Decompose extended unit specs into composition of pure unit specs.\n * And push top-level selection definitions down to unit specs.\n */\nfunction normalizeGenericSpec(\n spec: NonNormalizedSpec | FacetedUnitSpec | RepeatSpec,\n config: Config = {}\n) {\n const normParams = {config};\n return topLevelSelectionNormalizer.map(\n coreNormalizer.map(selectionCompatNormalizer.map(spec, normParams), normParams),\n normParams\n );\n}\n\nfunction _normalizeAutoSize(autosize: AutosizeType | AutoSizeParams) {\n return isString(autosize) ? {type: autosize} : autosize ?? {};\n}\n\n/**\n * Normalize autosize and deal with width or height == \"container\".\n */\nexport function normalizeAutoSize(\n spec: TopLevel,\n sizeInfo: {autosize: AutosizeType | AutoSizeParams} & LayoutSizeMixins,\n config?: Config\n) {\n let {width, height} = sizeInfo;\n\n const isFitCompatible = isUnitSpec(spec) || isLayerSpec(spec);\n const autosizeDefault: AutoSizeParams = {};\n\n if (!isFitCompatible) {\n // If spec is not compatible with autosize == \"fit\", discard width/height == container\n if (width == 'container') {\n log.warn(log.message.containerSizeNonSingle('width'));\n width = undefined;\n }\n if (height == 'container') {\n log.warn(log.message.containerSizeNonSingle('height'));\n height = undefined;\n }\n } else {\n // Default autosize parameters to fit when width/height is \"container\"\n if (width == 'container' && height == 'container') {\n autosizeDefault.type = 'fit';\n autosizeDefault.contains = 'padding';\n } else if (width == 'container') {\n autosizeDefault.type = 'fit-x';\n autosizeDefault.contains = 'padding';\n } else if (height == 'container') {\n autosizeDefault.type = 'fit-y';\n autosizeDefault.contains = 'padding';\n }\n }\n\n const autosize: AutoSizeParams = {\n type: 'pad',\n ...autosizeDefault,\n ...(config ? _normalizeAutoSize(config.autosize) : {}),\n ..._normalizeAutoSize(spec.autosize)\n };\n\n if (autosize.type === 'fit' && !isFitCompatible) {\n log.warn(log.message.FIT_NON_SINGLE);\n autosize.type = 'pad';\n }\n\n if (width == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-x')) {\n log.warn(log.message.containerSizeNotCompatibleWithAutosize('width'));\n }\n if (height == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-y')) {\n log.warn(log.message.containerSizeNotCompatibleWithAutosize('height'));\n }\n\n // Delete autosize property if it's Vega's default\n if (deepEqual(autosize, {type: 'pad'})) {\n return undefined;\n }\n\n return autosize;\n}\n\nexport type {NormalizerParams};\n","import {Color, SignalRef} from 'vega';\nimport {BaseSpec} from '.';\nimport {getPositionScaleChannel} from '../channel';\nimport {signalRefOrValue} from '../compile/common';\nimport {Config} from '../config';\nimport {InlineDataset} from '../data';\nimport {ExprRef} from '../expr';\nimport {VariableParameter} from '../parameter';\nimport {TopLevelSelectionParameter} from '../selection';\nimport {Dict} from '../util';\n\n/**\n * @minimum 0\n */\nexport type Padding = number | {top?: number; bottom?: number; left?: number; right?: number};\n\nexport type Datasets = Dict;\n\nexport type TopLevelParameter = VariableParameter | TopLevelSelectionParameter;\n\nexport type TopLevel = S &\n TopLevelProperties & {\n /**\n * URL to [JSON schema](http://json-schema.org/) for a Vega-Lite specification. Unless you have a reason to change this, use `https://vega.github.io/schema/vega-lite/v5.json`. Setting the `$schema` property allows automatic validation and autocomplete in editors that support JSON schema.\n * @format uri\n */\n $schema?: string;\n\n /**\n * Vega-Lite configuration object. This property can only be defined at the top-level of a specification.\n */\n config?: Config;\n\n /**\n * A global data store for named datasets. This is a mapping from names to inline datasets.\n * This can be an array of objects or primitive values or a string. Arrays of primitive values are ingested as objects with a `data` property.\n */\n datasets?: Datasets;\n\n /**\n * Optional metadata that will be passed to Vega.\n * This object is completely ignored by Vega and Vega-Lite and can be used for custom metadata.\n */\n usermeta?: Dict;\n };\n\n/**\n * Shared properties between Top-Level specs and Config\n */\nexport interface TopLevelProperties {\n /**\n * CSS color property to use as the background of the entire view.\n *\n * __Default value:__ `\"white\"`\n */\n background?: Color | ES;\n\n /**\n * The default visualization padding, in pixels, from the edge of the visualization canvas to the data rectangle. If a number, specifies padding for all sides.\n * If an object, the value should have the format `{\"left\": 5, \"top\": 5, \"right\": 5, \"bottom\": 5}` to specify padding for each side of the visualization.\n *\n * __Default value__: `5`\n */\n padding?: Padding | ES;\n\n /**\n * How the visualization size should be determined. If a string, should be one of `\"pad\"`, `\"fit\"` or `\"none\"`.\n * Object values can additionally specify parameters for content sizing and automatic resizing.\n *\n * __Default value__: `pad`\n */\n autosize?: AutosizeType | AutoSizeParams; // Vega actually supports signal for autosize. However, we need to check autosize at compile time to infer the rest of the spec. Thus VL's autosize won't support SignalRef for now.\n\n /**\n * Dynamic variables or selections that parameterize a visualization.\n */\n params?: TopLevelParameter[];\n}\n\nexport type FitType = 'fit' | 'fit-x' | 'fit-y';\n\nexport function isFitType(autoSizeType: AutosizeType): autoSizeType is FitType {\n return autoSizeType === 'fit' || autoSizeType === 'fit-x' || autoSizeType === 'fit-y';\n}\n\nexport function getFitType(sizeType?: 'width' | 'height'): FitType {\n return sizeType ? (`fit-${getPositionScaleChannel(sizeType)}` as FitType) : 'fit';\n}\n\nexport type AutosizeType = 'pad' | 'none' | 'fit' | 'fit-x' | 'fit-y';\n\nexport interface AutoSizeParams {\n /**\n * The sizing format type. One of `\"pad\"`, `\"fit\"`, `\"fit-x\"`, `\"fit-y\"`, or `\"none\"`. See the [autosize type](https://vega.github.io/vega-lite/docs/size.html#autosize) documentation for descriptions of each.\n *\n * __Default value__: `\"pad\"`\n */\n type?: AutosizeType;\n\n /**\n * A boolean flag indicating if autosize layout should be re-calculated on every view update.\n *\n * __Default value__: `false`\n */\n resize?: boolean;\n\n /**\n * Determines how size calculation should be performed, one of `\"content\"` or `\"padding\"`. The default setting (`\"content\"`) interprets the width and height settings as the data rectangle (plotting) dimensions, to which padding is then added. In contrast, the `\"padding\"` setting includes the padding within the view size calculations, such that the width and height settings indicate the **total** intended size of the view.\n *\n * __Default value__: `\"content\"`\n */\n contains?: 'content' | 'padding';\n}\n\nconst TOP_LEVEL_PROPERTIES: (keyof TopLevelProperties)[] = [\n 'background',\n 'padding'\n // We do not include \"autosize\" here as it is supported by only unit and layer specs and thus need to be normalized\n];\n\nexport function extractTopLevelProperties(t: TopLevelProperties, includeParams: boolean) {\n const o: TopLevelProperties = {};\n for (const p of TOP_LEVEL_PROPERTIES) {\n if (t && t[p] !== undefined) {\n o[p as any] = signalRefOrValue(t[p]);\n }\n }\n if (includeParams) {\n o.params = t.params;\n }\n return o;\n}\n","import * as log from '../log';\nimport {deepEqual, duplicate, getFirstDefined, keys} from '../util';\n\n/**\n * Generic class for storing properties that are explicitly specified\n * and implicitly determined by the compiler.\n * This is important for scale/axis/legend merging as\n * we want to prioritize properties that users explicitly specified.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport class Split {\n constructor(\n public readonly explicit: Partial = {},\n public readonly implicit: Partial = {}\n ) {}\n\n public clone() {\n return new Split(duplicate(this.explicit), duplicate(this.implicit));\n }\n\n public combine(): Partial {\n return {\n ...this.explicit, // Explicit properties comes first\n ...this.implicit\n };\n }\n\n public get(key: K): T[K] {\n // Explicit has higher precedence\n return getFirstDefined(this.explicit[key], this.implicit[key]);\n }\n\n public getWithExplicit(key: K): Explicit {\n // Explicit has higher precedence\n if (this.explicit[key] !== undefined) {\n return {explicit: true, value: this.explicit[key]};\n } else if (this.implicit[key] !== undefined) {\n return {explicit: false, value: this.implicit[key]};\n }\n return {explicit: false, value: undefined};\n }\n\n public setWithExplicit(key: K, {value, explicit}: Explicit) {\n if (value !== undefined) {\n this.set(key, value, explicit);\n }\n }\n\n public set(key: K, value: T[K], explicit: boolean) {\n delete this[explicit ? 'implicit' : 'explicit'][key];\n this[explicit ? 'explicit' : 'implicit'][key] = value;\n return this;\n }\n\n public copyKeyFromSplit(key: keyof T, {explicit, implicit}: Split) {\n // Explicit has higher precedence\n if (explicit[key] !== undefined) {\n this.set(key, explicit[key], true);\n } else if (implicit[key] !== undefined) {\n this.set(key, implicit[key], false);\n }\n }\n public copyKeyFromObject(key: keyof T, s: Partial) {\n // Explicit has higher precedence\n if (s[key] !== undefined) {\n this.set(key, s[key], true);\n }\n }\n\n /**\n * Merge split object into this split object. Properties from the other split\n * overwrite properties from this split.\n */\n public copyAll(other: Split) {\n for (const key of keys(other.combine())) {\n const val = other.getWithExplicit(key);\n this.setWithExplicit(key, val);\n }\n }\n}\n\nexport interface Explicit {\n explicit: boolean;\n value: T;\n}\n\nexport function makeExplicit(value: T): Explicit {\n return {\n explicit: true,\n value\n };\n}\n\nexport function makeImplicit(value: T): Explicit {\n return {\n explicit: false,\n value\n };\n}\n\nexport type SplitParentProperty = 'scale' | 'axis' | 'legend' | '';\n\nexport function tieBreakByComparing(compare: (v1: T, v2: T) => number) {\n return (\n v1: Explicit,\n v2: Explicit,\n property: keyof S | never,\n propertyOf: SplitParentProperty\n ): Explicit => {\n const diff = compare(v1.value, v2.value);\n if (diff > 0) {\n return v1;\n } else if (diff < 0) {\n return v2;\n }\n return defaultTieBreaker(v1, v2, property, propertyOf);\n };\n}\n\nexport function defaultTieBreaker(\n v1: Explicit,\n v2: Explicit,\n property: keyof S,\n propertyOf: SplitParentProperty\n) {\n if (v1.explicit && v2.explicit) {\n log.warn(log.message.mergeConflictingProperty(property, propertyOf, v1.value, v2.value));\n }\n // If equal score, prefer v1.\n return v1;\n}\n\nexport function mergeValuesWithExplicit(\n v1: Explicit,\n v2: Explicit,\n property: keyof S,\n propertyOf: SplitParentProperty,\n tieBreaker: (\n v1: Explicit,\n v2: Explicit,\n property: keyof S,\n propertyOf: string\n ) => Explicit = defaultTieBreaker\n) {\n if (v1 === undefined || v1.value === undefined) {\n // For first run\n return v2;\n }\n\n if (v1.explicit && !v2.explicit) {\n return v1;\n } else if (v2.explicit && !v1.explicit) {\n return v2;\n } else if (deepEqual(v1.value, v2.value)) {\n return v1;\n } else {\n return tieBreaker(v1, v2, property, propertyOf);\n }\n}\n","import {Parse} from '../../data';\nimport {Dict} from '../../util';\nimport {Split} from '../split';\nimport {OutputNode} from './dataflow';\nimport {FacetNode} from './facet';\nimport {SourceNode} from './source';\n\nexport interface DataComponent {\n /**\n * A list of unique sources.\n */\n sources: SourceNode[];\n\n /**\n * Registry of output nodes.\n */\n outputNodes: Dict;\n\n /**\n * How often is an output node used. If it is not used, we don't need to\n * instantiate it in the assemble step.\n */\n outputNodeRefCounts: Dict;\n\n /**\n * The output node before aggregation.\n */\n raw?: OutputNode;\n\n /**\n * The output node for scale domain before filter invalid.\n */\n preFilterInvalid?: OutputNode;\n\n /**\n * The output node for scale domain after filter invalid.\n */\n postFilterInvalid?: OutputNode;\n\n /**\n * The main output node.\n */\n main?: OutputNode;\n\n /**\n * For facets, we store the reference to the root node.\n */\n facetRoot?: FacetNode;\n\n /**\n * True if the data for this model is faceted.\n * A dataset is faceted if a parent model is a facet and no new dataset is\n * defined (which would make the data unfaceted again).\n */\n isFaceted: boolean;\n\n /**\n * Parse properties passed down from ancestors. Helps us to keep track of what has been parsed or is derived.\n */\n ancestorParse?: AncestorParse;\n}\n\n/**\n * Class to track interesting properties (see https://15721.courses.cs.cmu.edu/spring2016/papers/graefe-ieee1995.pdf)\n * about how fields have been parsed or whether they have been derived in a transform. We use this to not parse the\n * same field again (or differently).\n */\nexport class AncestorParse extends Split {\n constructor(\n public readonly explicit: Partial = {},\n public readonly implicit: Partial = {},\n public parseNothing = false\n ) {\n super(explicit, implicit);\n }\n\n public clone(): AncestorParse {\n const clone = super.clone() as AncestorParse;\n clone.parseNothing = this.parseNothing;\n return clone;\n }\n}\n","/*\n * Constants and utilities for data.\n */\nimport {Vector2} from 'vega';\nimport {FieldName} from './channeldef';\nimport {VgData} from './vega.schema';\n\nexport type ParseValue = null | string | 'string' | 'boolean' | 'date' | 'number';\n\nexport interface Parse {\n [field: string]: ParseValue;\n}\n\nexport interface DataFormatBase {\n /**\n * If set to `null`, disable type inference based on the spec and only use type inference based on the data.\n * Alternatively, a parsing directive object can be provided for explicit data types. Each property of the object corresponds to a field name, and the value to the desired data type (one of `\"number\"`, `\"boolean\"`, `\"date\"`, or null (do not parse the field)).\n * For example, `\"parse\": {\"modified_on\": \"date\"}` parses the `modified_on` field in each input record a Date value.\n *\n * For `\"date\"`, we parse data based using JavaScript's [`Date.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse).\n * For Specific date formats can be provided (e.g., `{foo: \"date:'%m%d%Y'\"}`), using the [d3-time-format syntax](https://github.com/d3/d3-time-format#locale_format). UTC date format parsing is supported similarly (e.g., `{foo: \"utc:'%m%d%Y'\"}`). See more about [UTC time](https://vega.github.io/vega-lite/docs/timeunit.html#utc)\n */\n parse?: Parse | null;\n\n /**\n * Type of input data: `\"json\"`, `\"csv\"`, `\"tsv\"`, `\"dsv\"`.\n *\n * __Default value:__ The default format type is determined by the extension of the file URL.\n * If no extension is detected, `\"json\"` will be used by default.\n */\n type?: 'csv' | 'tsv' | 'dsv' | 'json' | 'topojson';\n}\n\nexport interface CsvDataFormat extends DataFormatBase {\n type?: 'csv' | 'tsv';\n}\n\nexport interface DsvDataFormat extends DataFormatBase {\n type?: 'dsv';\n\n /**\n * The delimiter between records. The delimiter must be a single character (i.e., a single 16-bit code unit); so, ASCII delimiters are fine, but emoji delimiters are not.\n *\n * @minLength 1\n * @maxLength 1\n */\n delimiter: string;\n}\n\nexport interface JsonDataFormat extends DataFormatBase {\n type?: 'json';\n /**\n * The JSON property containing the desired data.\n * This parameter can be used when the loaded JSON file may have surrounding structure or meta-data.\n * For example `\"property\": \"values.features\"` is equivalent to retrieving `json.values.features`\n * from the loaded JSON object.\n */\n property?: string;\n}\n\nexport interface TopoDataFormat extends DataFormatBase {\n type?: 'topojson';\n /**\n * The name of the TopoJSON object set to convert to a GeoJSON feature collection.\n * For example, in a map of the world, there may be an object set named `\"countries\"`.\n * Using the feature property, we can extract this set and generate a GeoJSON feature object for each country.\n */\n feature?: string;\n /**\n * The name of the TopoJSON object set to convert to mesh.\n * Similar to the `feature` option, `mesh` extracts a named TopoJSON object set.\n * Unlike the `feature` option, the corresponding geo data is returned as a single, unified mesh instance, not as individual GeoJSON features.\n * Extracting a mesh is useful for more efficiently drawing borders or other geographic elements that you do not need to associate with specific regions such as individual countries, states or counties.\n */\n mesh?: string;\n}\n\nexport type DataFormat = CsvDataFormat | DsvDataFormat | JsonDataFormat | TopoDataFormat;\n\nexport type DataFormatType = 'json' | 'csv' | 'tsv' | 'dsv' | 'topojson';\n\nexport type DataSource = UrlData | InlineData | NamedData;\n\nexport type Data = DataSource | Generator;\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport type InlineDataset = number[] | string[] | boolean[] | object[] | string | object;\n\nexport interface DataBase {\n /**\n * An object that specifies the format for parsing the data.\n */\n format?: DataFormat;\n /**\n * Provide a placeholder name and bind data at runtime.\n */\n name?: string;\n}\n\nexport interface UrlData extends DataBase {\n /**\n * An URL from which to load the data set. Use the `format.type` property\n * to ensure the loaded data is correctly parsed.\n */\n url: string;\n}\n\nexport interface InlineData extends DataBase {\n /**\n * The full data set, included inline. This can be an array of objects or primitive values, an object, or a string.\n * Arrays of primitive values are ingested as objects with a `data` property. Strings are parsed according to the specified format type.\n */\n values: InlineDataset;\n}\n\nexport interface NamedData extends DataBase {\n /**\n * Provide a placeholder name and bind data at runtime.\n *\n * New data may change the layout but Vega does not always resize the chart. To update the layout when the data updates, set [autosize](https://vega.github.io/vega-lite/docs/size.html#autosize) or explicitly use [view.resize](https://vega.github.io/vega/docs/api/view/#view_resize).\n */\n name: string;\n}\n\nexport function isUrlData(data: Partial | Partial): data is UrlData {\n return 'url' in data;\n}\n\nexport function isInlineData(data: Partial | Partial): data is InlineData {\n return 'values' in data;\n}\n\nexport function isNamedData(data: Partial | Partial): data is NamedData {\n return 'name' in data && !isUrlData(data) && !isInlineData(data) && !isGenerator(data);\n}\n\nexport function isGenerator(data: Partial | Partial): data is Generator {\n return data && (isSequenceGenerator(data) || isSphereGenerator(data) || isGraticuleGenerator(data));\n}\n\nexport function isSequenceGenerator(data: Partial | Partial): data is SequenceGenerator {\n return 'sequence' in data;\n}\n\nexport function isSphereGenerator(data: Partial | Partial): data is SphereGenerator {\n return 'sphere' in data;\n}\n\nexport function isGraticuleGenerator(data: Partial | Partial): data is GraticuleGenerator {\n return 'graticule' in data;\n}\n\nexport enum DataSourceType {\n Raw,\n /** Main data source for marks */\n Main,\n Row,\n Column,\n Lookup,\n /** Pre-filter-invalid data source for scale domains */\n PreFilterInvalid,\n\n /** Post-filter-invalid data source for scale domains */\n PostFilterInvalid\n}\n\nexport type Generator = SequenceGenerator | SphereGenerator | GraticuleGenerator;\n\nexport interface GeneratorBase {\n /**\n * Provide a placeholder name and bind data at runtime.\n */\n name?: string;\n}\n\nexport interface SequenceGenerator extends GeneratorBase {\n /**\n * Generate a sequence of numbers.\n */\n sequence: SequenceParams;\n}\n\nexport interface SequenceParams {\n /**\n * The starting value of the sequence (inclusive).\n */\n start: number;\n /**\n * The ending value of the sequence (exclusive).\n */\n stop: number;\n /**\n * The step value between sequence entries.\n *\n * __Default value:__ `1`\n */\n step?: number;\n\n /**\n * The name of the generated sequence field.\n *\n * __Default value:__ `\"data\"`\n */\n as?: FieldName;\n}\n\nexport interface SphereGenerator extends GeneratorBase {\n /**\n * Generate sphere GeoJSON data for the full globe.\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n sphere: true | {};\n}\n\nexport interface GraticuleGenerator extends GeneratorBase {\n /**\n * Generate graticule GeoJSON data for geographic reference lines.\n */\n graticule: true | GraticuleParams;\n}\n\nexport interface GraticuleParams {\n /**\n * The major extent of the graticule as a two-element array of coordinates.\n */\n extentMajor?: Vector2>;\n\n /**\n * The minor extent of the graticule as a two-element array of coordinates.\n */\n extentMinor?: Vector2>;\n\n /**\n * Sets both the major and minor extents to the same values.\n */\n extent?: Vector2>;\n\n /**\n * The major step angles of the graticule.\n *\n *\n * __Default value:__ `[90, 360]`\n */\n stepMajor?: Vector2;\n\n /**\n * The minor step angles of the graticule.\n *\n * __Default value:__ `[10, 10]`\n */\n stepMinor?: Vector2;\n\n /**\n * Sets both the major and minor step angles to the same values.\n */\n step?: Vector2;\n\n /**\n * The precision of the graticule in degrees.\n *\n * __Default value:__ `2.5`\n */\n precision?: number;\n}\n","import {MarkInvalidDataMode} from '../../invalid';\n\nimport {DataSourceType} from '../../data';\nimport {normalizeInvalidDataMode} from './normalizeInvalidDataMode';\n\ntype PreOrPostFilteringInvalidValues = 'include-invalid-values' | 'exclude-invalid-values';\n\nexport interface DataSourcesForHandlingInvalidValues {\n marks: PreOrPostFilteringInvalidValues;\n scales: PreOrPostFilteringInvalidValues;\n}\ninterface GetDataSourcesForHandlingInvalidValuesProps {\n invalid: MarkInvalidDataMode | null | undefined;\n isPath: boolean;\n}\n\nexport function getDataSourcesForHandlingInvalidValues({\n invalid,\n isPath\n}: GetDataSourcesForHandlingInvalidValuesProps): DataSourcesForHandlingInvalidValues {\n const normalizedInvalid = normalizeInvalidDataMode(invalid, {isPath});\n\n switch (normalizedInvalid) {\n case 'filter':\n // Both marks and scales use post-filter data\n return {\n marks: 'exclude-invalid-values',\n scales: 'exclude-invalid-values'\n };\n case 'break-paths-show-domains':\n return {\n // Path-based marks use pre-filter data so we know to skip these invalid points in the path.\n // For non-path based marks, we skip by not showing them at all.\n marks: isPath ? 'include-invalid-values' : 'exclude-invalid-values',\n scales: 'include-invalid-values'\n };\n case 'break-paths-filter-domains':\n // For path marks, the marks will use unfiltered data (and skip points). But we need a separate data sources to feed the domain.\n // For non-path marks, we can use the filtered data for both marks and scales.\n return {\n marks: isPath ? 'include-invalid-values' : 'exclude-invalid-values',\n // Unlike 'break-paths-show-domains', 'break-paths-filter-domains' uses post-filter data to feed scale.\n scales: 'exclude-invalid-values'\n };\n case 'show':\n return {\n marks: 'include-invalid-values',\n scales: 'include-invalid-values'\n };\n }\n}\n\nexport function getScaleDataSourceForHandlingInvalidValues(\n props: GetDataSourcesForHandlingInvalidValuesProps\n): DataSourceType {\n const {marks, scales} = getDataSourcesForHandlingInvalidValues(props);\n if (marks === scales) {\n // If both marks and scales use the same data, there is only the main data source.\n return DataSourceType.Main;\n }\n // If marks and scales use differetnt data, return the pre/post-filter data source accordingly.\n return scales === 'include-invalid-values' ? DataSourceType.PreFilterInvalid : DataSourceType.PostFilterInvalid;\n}\n","import {Signal, SignalRef} from 'vega';\nimport {parseSelector} from 'vega-event-selector';\nimport {identity, isArray, stringValue} from 'vega-util';\nimport {MODIFY, STORE, unitName, VL_SELECTION_RESOLVE, TUPLE, selectionCompilers} from '.';\nimport {dateTimeToExpr, isDateTime, dateTimeToTimestamp} from '../../datetime';\nimport {hasContinuousDomain} from '../../scale';\nimport {SelectionInit, SelectionInitInterval, ParameterExtent, SELECTION_ID} from '../../selection';\nimport {keys, replacePathInField, stringify, vals} from '../../util';\nimport {VgData, VgDomain} from '../../vega.schema';\nimport {FacetModel} from '../facet';\nimport {LayerModel} from '../layer';\nimport {isUnitModel, Model} from '../model';\nimport {ScaleComponent} from '../scale/component';\nimport {UnitModel} from '../unit';\nimport {parseSelectionExtent} from './parse';\nimport {SelectionProjection} from './project';\n\nexport function assembleProjection(proj: SelectionProjection) {\n const {signals, hasLegend, index, ...rest} = proj;\n rest.field = replacePathInField(rest.field);\n return rest;\n}\n\nexport function assembleInit(\n init: readonly (SelectionInit | readonly SelectionInit[] | SelectionInitInterval)[] | SelectionInit,\n isExpr = true,\n wrap: (str: string | number) => string | number = identity\n): any {\n if (isArray(init)) {\n const assembled = init.map(v => assembleInit(v, isExpr, wrap));\n return isExpr ? `[${assembled.join(', ')}]` : assembled;\n } else if (isDateTime(init)) {\n if (isExpr) {\n return wrap(dateTimeToExpr(init));\n } else {\n return wrap(dateTimeToTimestamp(init));\n }\n }\n return isExpr ? wrap(stringify(init)) : init;\n}\n\nexport function assembleUnitSelectionSignals(model: UnitModel, signals: Signal[]) {\n for (const selCmpt of vals(model.component.selection ?? {})) {\n const name = selCmpt.name;\n let modifyExpr = `${name}${TUPLE}, ${selCmpt.resolve === 'global' ? 'true' : `{unit: ${unitName(model)}}`}`;\n\n for (const c of selectionCompilers) {\n if (!c.defined(selCmpt)) continue;\n if (c.signals) signals = c.signals(model, selCmpt, signals);\n if (c.modifyExpr) modifyExpr = c.modifyExpr(model, selCmpt, modifyExpr);\n }\n\n signals.push({\n name: name + MODIFY,\n on: [\n {\n events: {signal: selCmpt.name + TUPLE},\n update: `modify(${stringValue(selCmpt.name + STORE)}, ${modifyExpr})`\n }\n ]\n });\n }\n\n return cleanupEmptyOnArray(signals);\n}\n\nexport function assembleFacetSignals(model: FacetModel, signals: Signal[]) {\n if (model.component.selection && keys(model.component.selection).length) {\n const name = stringValue(model.getName('cell'));\n signals.unshift({\n name: 'facet',\n value: {},\n on: [\n {\n events: parseSelector('pointermove', 'scope'),\n update: `isTuple(facet) ? facet : group(${name}).datum`\n }\n ]\n });\n }\n\n return cleanupEmptyOnArray(signals);\n}\n\nexport function assembleTopLevelSignals(model: UnitModel, signals: Signal[]) {\n let hasSelections = false;\n for (const selCmpt of vals(model.component.selection ?? {})) {\n const name = selCmpt.name;\n const store = stringValue(name + STORE);\n const hasSg = signals.filter(s => s.name === name);\n if (hasSg.length === 0) {\n const resolve = selCmpt.resolve === 'global' ? 'union' : selCmpt.resolve;\n const isPoint = selCmpt.type === 'point' ? ', true, true)' : ')';\n signals.push({\n name: selCmpt.name,\n update: `${VL_SELECTION_RESOLVE}(${store}, ${stringValue(resolve)}${isPoint}`\n });\n }\n hasSelections = true;\n\n for (const c of selectionCompilers) {\n if (c.defined(selCmpt) && c.topLevelSignals) {\n signals = c.topLevelSignals(model, selCmpt, signals);\n }\n }\n }\n\n if (hasSelections) {\n const hasUnit = signals.filter(s => s.name === 'unit');\n if (hasUnit.length === 0) {\n signals.unshift({\n name: 'unit',\n value: {},\n on: [{events: 'pointermove', update: 'isTuple(group()) ? group() : unit'}]\n });\n }\n }\n\n return cleanupEmptyOnArray(signals);\n}\n\nexport function assembleUnitSelectionData(model: UnitModel, data: readonly VgData[]): VgData[] {\n const dataCopy = [...data];\n const unit = unitName(model, {escape: false});\n\n for (const selCmpt of vals(model.component.selection ?? {})) {\n const store: VgData = {name: selCmpt.name + STORE};\n\n if (selCmpt.project.hasSelectionId) {\n store.transform = [{type: 'collect', sort: {field: SELECTION_ID}}];\n }\n\n if (selCmpt.init) {\n const fields = selCmpt.project.items.map(assembleProjection);\n\n store.values = selCmpt.project.hasSelectionId\n ? selCmpt.init.map(i => ({unit, [SELECTION_ID]: assembleInit(i, false)[0]}))\n : selCmpt.init.map(i => ({unit, fields, values: assembleInit(i, false)}));\n }\n\n const contains = dataCopy.filter(d => d.name === selCmpt.name + STORE);\n if (!contains.length) {\n dataCopy.push(store);\n }\n }\n\n return dataCopy;\n}\n\nexport function assembleUnitSelectionMarks(model: UnitModel, marks: any[]): any[] {\n for (const selCmpt of vals(model.component.selection ?? {})) {\n for (const c of selectionCompilers) {\n if (c.defined(selCmpt) && c.marks) {\n marks = c.marks(model, selCmpt, marks);\n }\n }\n }\n\n return marks;\n}\n\nexport function assembleLayerSelectionMarks(model: LayerModel, marks: any[]): any[] {\n for (const child of model.children) {\n if (isUnitModel(child)) {\n marks = assembleUnitSelectionMarks(child, marks);\n }\n }\n\n return marks;\n}\n\nexport function assembleSelectionScaleDomain(\n model: Model,\n extent: ParameterExtent,\n scaleCmpt: ScaleComponent,\n domain: VgDomain\n): SignalRef {\n const parsedExtent = parseSelectionExtent(model, extent.param, extent);\n\n return {\n signal:\n hasContinuousDomain(scaleCmpt.get('type')) && isArray(domain) && domain[0] > domain[1]\n ? `isValid(${parsedExtent}) && reverse(${parsedExtent})`\n : parsedExtent\n };\n}\n\nfunction cleanupEmptyOnArray(signals: Signal[]) {\n return signals.map(s => {\n if (s.on && !s.on.length) delete s.on;\n return s;\n });\n}\n","import {DataSourceType} from '../../data';\nimport * as log from '../../log';\nimport {Dict, uniqueId} from '../../util';\n\n/**\n * A node in the dataflow tree.\n */\nexport abstract class DataFlowNode {\n private _children: DataFlowNode[] = [];\n\n private _parent: DataFlowNode = null;\n\n protected _hash: string | number;\n\n constructor(\n parent: DataFlowNode,\n public readonly debugName?: string\n ) {\n if (parent) {\n this.parent = parent;\n }\n }\n\n /**\n * Clone this node with a deep copy but don't clone links to children or parents.\n */\n public clone(): DataFlowNode {\n throw new Error('Cannot clone node');\n }\n\n /**\n * Return a hash of the node.\n */\n public abstract hash(): string | number;\n\n /**\n * Set of fields that this node depends on.\n */\n public abstract dependentFields(): Set;\n\n /**\n * Set of fields that are being created by this node.\n */\n public abstract producedFields(): Set;\n\n get parent() {\n return this._parent;\n }\n\n /**\n * Set the parent of the node and also add this node to the parent's children.\n */\n set parent(parent: DataFlowNode) {\n this._parent = parent;\n if (parent) {\n parent.addChild(this);\n }\n }\n\n get children() {\n return this._children;\n }\n\n public numChildren() {\n return this._children.length;\n }\n\n public addChild(child: DataFlowNode, loc?: number) {\n // do not add the same child twice\n if (this._children.includes(child)) {\n log.warn(log.message.ADD_SAME_CHILD_TWICE);\n return;\n }\n\n if (loc !== undefined) {\n this._children.splice(loc, 0, child);\n } else {\n this._children.push(child);\n }\n }\n\n public removeChild(oldChild: DataFlowNode) {\n const loc = this._children.indexOf(oldChild);\n this._children.splice(loc, 1);\n return loc;\n }\n\n /**\n * Remove node from the dataflow.\n */\n public remove() {\n let loc = this._parent.removeChild(this);\n for (const child of this._children) {\n // do not use the set method because we want to insert at a particular location\n child._parent = this._parent;\n this._parent.addChild(child, loc++);\n }\n }\n\n /**\n * Insert another node as a parent of this node.\n */\n public insertAsParentOf(other: DataFlowNode) {\n const parent = other.parent;\n parent.removeChild(this);\n this.parent = parent;\n other.parent = this;\n }\n\n public swapWithParent() {\n const parent = this._parent;\n const newParent = parent.parent;\n\n // reconnect the children\n for (const child of this._children) {\n child.parent = parent;\n }\n\n // remove old links\n this._children = []; // equivalent to removing every child link one by one\n parent.removeChild(this);\n const loc = parent.parent.removeChild(parent);\n\n // swap two nodes but maintain order in children\n this._parent = newParent;\n newParent.addChild(this, loc);\n\n parent.parent = this;\n }\n}\n\nexport class OutputNode extends DataFlowNode {\n private _source: string;\n\n private _name: string;\n\n public clone(): this {\n const cloneObj = new (this.constructor as any)();\n cloneObj.debugName = `clone_${this.debugName}`;\n cloneObj._source = this._source;\n cloneObj._name = `clone_${this._name}`;\n cloneObj.type = this.type;\n cloneObj.refCounts = this.refCounts;\n cloneObj.refCounts[cloneObj._name] = 0;\n return cloneObj;\n }\n\n /**\n * @param source The name of the source. Will change in assemble.\n * @param type The type of the output node.\n * @param refCounts A global ref counter map.\n */\n constructor(\n parent: DataFlowNode,\n source: string,\n public readonly type: DataSourceType,\n private readonly refCounts: Dict\n ) {\n super(parent, source);\n\n this._source = this._name = source;\n\n if (this.refCounts && !(this._name in this.refCounts)) {\n this.refCounts[this._name] = 0;\n }\n }\n\n public dependentFields() {\n return new Set();\n }\n\n public producedFields() {\n return new Set();\n }\n\n public hash() {\n if (this._hash === undefined) {\n this._hash = `Output ${uniqueId()}`;\n }\n return this._hash;\n }\n\n /**\n * Request the datasource name and increase the ref counter.\n *\n * During the parsing phase, this will return the simple name such as 'main' or 'raw'.\n * It is crucial to request the name from an output node to mark it as a required node.\n * If nobody ever requests the name, this datasource will not be instantiated in the assemble phase.\n *\n * In the assemble phase, this will return the correct name.\n */\n public getSource() {\n this.refCounts[this._name]++;\n return this._source;\n }\n\n public isRequired(): boolean {\n return !!this.refCounts[this._name];\n }\n\n public setSource(source: string) {\n this._source = source;\n }\n}\n","import {TimeUnitTransform as VgTimeUnitTransform} from 'vega';\nimport {FormulaTransform as VgFormulaTransform} from 'vega';\nimport {FieldName, getBandPosition, vgField} from '../../channeldef';\nimport {\n TimeUnitParams,\n getDateTimePartAndStep,\n getSmallestTimeUnitPart,\n getTimeUnitParts,\n isBinnedTimeUnit,\n normalizeTimeUnit\n} from '../../timeunit';\nimport {TimeUnitTransform} from '../../transform';\nimport {Dict, duplicate, entries, hash, isEmpty, replacePathInField, vals} from '../../util';\nimport {ModelWithField, isUnitModel} from '../model';\nimport {DataFlowNode} from './dataflow';\nimport {isRectBasedMark} from '../../mark';\nimport {isXorY} from '../../channel';\n\nexport type TimeUnitComponent = (TimeUnitTransform | BinnedTimeUnitOffset) & {\n rectBandPosition?: number;\n};\n\nexport interface BinnedTimeUnitOffset {\n timeUnit: TimeUnitParams;\n field: FieldName;\n}\n\nfunction isTimeUnitTransformComponent(timeUnitComponent: TimeUnitComponent): timeUnitComponent is TimeUnitTransform {\n return (timeUnitComponent as TimeUnitTransform).as !== undefined;\n}\n\nfunction offsetAs(field: FieldName) {\n return `${field}_end`;\n}\n\nexport class TimeUnitNode extends DataFlowNode {\n public clone() {\n return new TimeUnitNode(null, duplicate(this.timeUnits));\n }\n\n constructor(\n parent: DataFlowNode,\n private timeUnits: Dict\n ) {\n super(parent);\n }\n\n public static makeFromEncoding(parent: DataFlowNode, model: ModelWithField) {\n const formula = model.reduceFieldDef((timeUnitComponent: TimeUnitComponent, fieldDef, channel) => {\n const {field, timeUnit} = fieldDef;\n\n if (timeUnit) {\n let component: TimeUnitComponent | undefined;\n\n if (isBinnedTimeUnit(timeUnit)) {\n // For binned time unit, only produce end if the mark is a rect-based mark (rect, bar, image, arc), which needs \"range\".\n\n if (isUnitModel(model)) {\n const {mark, markDef, config} = model;\n const bandPosition = getBandPosition({fieldDef, markDef, config});\n if (isRectBasedMark(mark) || !!bandPosition) {\n component = {\n timeUnit: normalizeTimeUnit(timeUnit),\n field\n };\n }\n }\n } else {\n component = {\n as: vgField(fieldDef, {forAs: true}),\n field,\n timeUnit\n };\n }\n\n if (isUnitModel(model)) {\n const {mark, markDef, config} = model;\n const bandPosition = getBandPosition({fieldDef, markDef, config});\n if (isRectBasedMark(mark) && isXorY(channel) && bandPosition !== 0.5) {\n component.rectBandPosition = bandPosition;\n }\n }\n\n if (component) {\n timeUnitComponent[hash(component)] = component;\n }\n }\n return timeUnitComponent;\n }, {} as Dict);\n\n if (isEmpty(formula)) {\n return null;\n }\n\n return new TimeUnitNode(parent, formula);\n }\n\n public static makeFromTransform(parent: DataFlowNode, t: TimeUnitTransform) {\n const {timeUnit, ...other} = {...t};\n\n const normalizedTimeUnit = normalizeTimeUnit(timeUnit);\n\n const component = {\n ...other,\n timeUnit: normalizedTimeUnit\n };\n\n return new TimeUnitNode(parent, {\n [hash(component)]: component\n });\n }\n\n /**\n * Merge together TimeUnitNodes assigning the children of `other` to `this`\n * and removing `other`.\n */\n public merge(other: TimeUnitNode) {\n this.timeUnits = {...this.timeUnits};\n\n // if the same hash happen twice, merge\n for (const key in other.timeUnits) {\n if (!this.timeUnits[key]) {\n // copy if it's not a duplicate\n this.timeUnits[key] = other.timeUnits[key];\n }\n }\n\n for (const child of other.children) {\n other.removeChild(child);\n child.parent = this;\n }\n\n other.remove();\n }\n\n /**\n * Remove time units coming from the other node.\n */\n public removeFormulas(fields: Set) {\n const newFormula = {};\n\n for (const [key, timeUnitComponent] of entries(this.timeUnits)) {\n const fieldAs = isTimeUnitTransformComponent(timeUnitComponent)\n ? timeUnitComponent.as\n : `${timeUnitComponent.field}_end`;\n if (!fields.has(fieldAs)) {\n newFormula[key] = timeUnitComponent;\n }\n }\n\n this.timeUnits = newFormula;\n }\n\n public producedFields() {\n return new Set(\n vals(this.timeUnits).map(f => {\n return isTimeUnitTransformComponent(f) ? f.as : offsetAs(f.field);\n })\n );\n }\n\n public dependentFields() {\n return new Set(vals(this.timeUnits).map(f => f.field));\n }\n\n public hash() {\n return `TimeUnit ${hash(this.timeUnits)}`;\n }\n\n public assemble() {\n const transforms: (VgTimeUnitTransform | VgFormulaTransform)[] = [];\n\n for (const f of vals(this.timeUnits)) {\n const {rectBandPosition} = f;\n const normalizedTimeUnit = normalizeTimeUnit(f.timeUnit);\n\n if (isTimeUnitTransformComponent(f)) {\n const {field, as} = f;\n const {unit, utc, ...params} = normalizedTimeUnit;\n\n const startEnd: [string, string] = [as, `${as}_end`];\n\n transforms.push({\n field: replacePathInField(field),\n type: 'timeunit',\n ...(unit ? {units: getTimeUnitParts(unit)} : {}),\n ...(utc ? {timezone: 'utc'} : {}),\n ...params,\n as: startEnd\n });\n\n transforms.push(...offsetedRectFormulas(startEnd, rectBandPosition, normalizedTimeUnit));\n } else if (f) {\n const {field: escapedField} = f;\n // since this is a expression, we want the unescaped field name\n const field = escapedField.replaceAll('\\\\.', '.');\n const expr = offsetExpr({timeUnit: normalizedTimeUnit, field});\n const endAs = offsetAs(field);\n transforms.push({\n type: 'formula',\n expr,\n as: endAs\n });\n\n transforms.push(...offsetedRectFormulas([field, endAs], rectBandPosition, normalizedTimeUnit));\n }\n }\n\n return transforms;\n }\n}\n\nexport const OFFSETTED_RECT_START_SUFFIX = 'offsetted_rect_start';\nexport const OFFSETTED_RECT_END_SUFFIX = 'offsetted_rect_end';\n\nfunction offsetExpr({timeUnit, field, reverse}: {timeUnit: TimeUnitParams; field: string; reverse?: boolean}) {\n const {unit, utc} = timeUnit;\n const smallestUnit = getSmallestTimeUnitPart(unit);\n const {part, step} = getDateTimePartAndStep(smallestUnit, timeUnit.step);\n const offsetFn = utc ? 'utcOffset' : 'timeOffset';\n const expr = `${offsetFn}('${part}', datum['${field}'], ${reverse ? -step : step})`;\n return expr;\n}\n\nfunction offsetedRectFormulas(\n [startField, endField]: [string, string],\n rectBandPosition: number | undefined,\n timeUnit: TimeUnitParams\n): VgFormulaTransform[] {\n if (rectBandPosition !== undefined && rectBandPosition !== 0.5) {\n const startExpr = `datum['${startField}']`;\n const endExpr = `datum['${endField}']`;\n return [\n {\n type: 'formula',\n expr: interpolateExpr(\n [\n offsetExpr({\n timeUnit,\n field: startField,\n reverse: true\n }),\n startExpr\n ],\n rectBandPosition + 0.5\n ),\n as: `${startField}_${OFFSETTED_RECT_START_SUFFIX}`\n },\n {\n type: 'formula',\n expr: interpolateExpr([startExpr, endExpr], rectBandPosition + 0.5),\n as: `${startField}_${OFFSETTED_RECT_END_SUFFIX}`\n }\n ];\n }\n return [];\n}\n\nfunction interpolateExpr([start, end]: [string, string], fraction: number) {\n return `${1 - fraction} * ${start} + ${fraction} * ${end}`;\n}\n","import {array, isObject} from 'vega-util';\nimport {\n GeoPositionChannel,\n getPositionChannelFromLatLong,\n isGeoPositionChannel,\n isScaleChannel,\n isSingleDefUnitChannel,\n SingleDefUnitChannel\n} from '../../channel';\nimport * as log from '../../log';\nimport {hasContinuousDomain} from '../../scale';\nimport {PointSelectionConfig, SelectionInitIntervalMapping, SelectionInitMapping, SELECTION_ID} from '../../selection';\nimport {Dict, hash, keys, varName, isEmpty} from '../../util';\nimport {TimeUnitComponent, TimeUnitNode} from '../data/timeunit';\nimport {SelectionCompiler} from '.';\nimport {assembleProjection} from './assemble';\nimport {isBinnedTimeUnit} from '../../timeunit';\nexport const TUPLE_FIELDS = '_tuple_fields';\n\n/**\n * Whether the selection tuples hold enumerated or ranged values for a field.\n */\nexport type TupleStoreType =\n // enumerated\n | 'E'\n // ranged, exclusive, left-right inclusive\n | 'R'\n // ranged, left-inclusive, right-exclusive\n | 'R-RE';\n\nexport interface SelectionProjection {\n type: TupleStoreType;\n field: string;\n index: number;\n channel?: SingleDefUnitChannel;\n geoChannel?: GeoPositionChannel;\n signals?: {data?: string; visual?: string};\n hasLegend?: boolean;\n}\n\nexport class SelectionProjectionComponent {\n public hasChannel: Partial>;\n public hasField: Record;\n public hasSelectionId: boolean;\n public timeUnit?: TimeUnitNode;\n public items: SelectionProjection[];\n\n constructor(...items: SelectionProjection[]) {\n this.items = items;\n this.hasChannel = {};\n this.hasField = {};\n this.hasSelectionId = false;\n }\n}\n\nconst project: SelectionCompiler = {\n defined: () => {\n return true; // This transform handles its own defaults, so always run parse.\n },\n\n parse: (model, selCmpt, selDef) => {\n const name = selCmpt.name;\n const proj = (selCmpt.project ??= new SelectionProjectionComponent());\n const parsed: Dict = {};\n const timeUnits: Dict = {};\n\n const signals = new Set();\n const signalName = (p: SelectionProjection, range: 'data' | 'visual') => {\n const suffix = range === 'visual' ? p.channel : p.field;\n let sg = varName(`${name}_${suffix}`);\n for (let counter = 1; signals.has(sg); counter++) {\n sg = varName(`${name}_${suffix}_${counter}`);\n }\n signals.add(sg);\n return {[range]: sg};\n };\n\n const type = selCmpt.type;\n const cfg = model.config.selection[type];\n const init =\n selDef.value !== undefined\n ? (array(selDef.value as any) as SelectionInitMapping[] | SelectionInitIntervalMapping[])\n : null;\n\n // If no explicit projection (either fields or encodings) is specified, set some defaults.\n // If an initial value is set, try to infer projections.\n let {fields, encodings} = (isObject(selDef.select) ? selDef.select : {}) as PointSelectionConfig;\n if (!fields && !encodings && init) {\n for (const initVal of init) {\n // initVal may be a scalar value to smoothen varParam -> pointSelection gradient.\n if (!isObject(initVal)) {\n continue;\n }\n\n for (const key of keys(initVal)) {\n if (isSingleDefUnitChannel(key)) {\n (encodings || (encodings = [])).push(key as SingleDefUnitChannel);\n } else {\n if (type === 'interval') {\n log.warn(log.message.INTERVAL_INITIALIZED_WITH_POS);\n encodings = cfg.encodings;\n } else {\n (fields ??= []).push(key);\n }\n }\n }\n }\n }\n\n // If no initial value is specified, use the default configuration.\n // We break this out as a separate if block (instead of an else condition)\n // to account for unprojected point selections that have scalar initial values\n if (!fields && !encodings) {\n encodings = cfg.encodings;\n if ('fields' in cfg) {\n fields = cfg.fields;\n }\n }\n\n for (const channel of encodings ?? []) {\n const fieldDef = model.fieldDef(channel);\n if (fieldDef) {\n let field = fieldDef.field;\n\n if (fieldDef.aggregate) {\n log.warn(log.message.cannotProjectAggregate(channel, fieldDef.aggregate));\n continue;\n } else if (!field) {\n log.warn(log.message.cannotProjectOnChannelWithoutField(channel));\n continue;\n }\n\n if (fieldDef.timeUnit && !isBinnedTimeUnit(fieldDef.timeUnit)) {\n field = model.vgField(channel);\n // Construct TimeUnitComponents which will be combined into a\n // TimeUnitNode. This node may need to be inserted into the\n // dataflow if the selection is used across views that do not\n // have these time units defined.\n const component = {\n timeUnit: fieldDef.timeUnit,\n as: field,\n field: fieldDef.field\n };\n\n timeUnits[hash(component)] = component;\n }\n\n // Prevent duplicate projections on the same field.\n // TODO: what if the same field is bound to multiple channels (e.g., SPLOM diag).\n if (!parsed[field]) {\n // Determine whether the tuple will store enumerated or ranged values.\n // Interval selections store ranges for continuous scales, and enumerations otherwise.\n // Single/multi selections store ranges for binned fields, and enumerations otherwise.\n const tplType: TupleStoreType =\n type === 'interval' &&\n isScaleChannel(channel) &&\n hasContinuousDomain(model.getScaleComponent(channel).get('type'))\n ? 'R'\n : fieldDef.bin\n ? 'R-RE'\n : 'E';\n\n const p: SelectionProjection = {field, channel, type: tplType, index: proj.items.length};\n p.signals = {...signalName(p, 'data'), ...signalName(p, 'visual')};\n proj.items.push((parsed[field] = p));\n proj.hasField[field] = parsed[field];\n proj.hasSelectionId = proj.hasSelectionId || field === SELECTION_ID;\n\n if (isGeoPositionChannel(channel)) {\n p.geoChannel = channel;\n p.channel = getPositionChannelFromLatLong(channel);\n proj.hasChannel[p.channel] = parsed[field];\n } else {\n proj.hasChannel[channel] = parsed[field];\n }\n }\n } else {\n log.warn(log.message.cannotProjectOnChannelWithoutField(channel));\n }\n }\n\n for (const field of fields ?? []) {\n if (proj.hasField[field]) continue;\n const p: SelectionProjection = {type: 'E', field, index: proj.items.length};\n p.signals = {...signalName(p, 'data')};\n proj.items.push(p);\n proj.hasField[field] = p;\n proj.hasSelectionId = proj.hasSelectionId || field === SELECTION_ID;\n }\n\n if (init) {\n selCmpt.init = (init as any).map((v: SelectionInitMapping | SelectionInitIntervalMapping) => {\n // Selections can be initialized either with a full object that maps projections to values\n // or scalar values to smoothen the abstraction gradient from variable params to point selections.\n return proj.items.map(p =>\n isObject(v) ? (v[p.geoChannel || p.channel] !== undefined ? v[p.geoChannel || p.channel] : v[p.field]) : v\n );\n });\n }\n\n if (!isEmpty(timeUnits)) {\n proj.timeUnit = new TimeUnitNode(null, timeUnits);\n }\n },\n\n signals: (model, selCmpt, allSignals) => {\n const name = selCmpt.name + TUPLE_FIELDS;\n const hasSignal = allSignals.filter(s => s.name === name);\n return hasSignal.length > 0 || selCmpt.project.hasSelectionId\n ? allSignals\n : allSignals.concat({\n name,\n value: selCmpt.project.items.map(assembleProjection)\n });\n }\n};\n\nexport default project;\n","import {stringValue} from 'vega-util';\nimport {VL_SELECTION_RESOLVE} from '.';\nimport {isScaleChannel, ScaleChannel} from '../../channel';\nimport * as log from '../../log';\nimport {hasContinuousDomain} from '../../scale';\nimport {isLayerModel, Model} from '../model';\nimport {UnitModel} from '../unit';\nimport {SelectionProjection} from './project';\nimport {SelectionCompiler} from '.';\nimport {replacePathInField} from '../../util';\nimport {NewSignal} from 'vega';\n\nconst scaleBindings: SelectionCompiler<'interval'> = {\n defined: selCmpt => {\n return selCmpt.type === 'interval' && selCmpt.resolve === 'global' && selCmpt.bind && selCmpt.bind === 'scales';\n },\n\n parse: (model, selCmpt) => {\n const bound: SelectionProjection[] = (selCmpt.scales = []);\n\n for (const proj of selCmpt.project.items) {\n const channel = proj.channel;\n\n if (!isScaleChannel(channel)) {\n continue;\n }\n\n const scale = model.getScaleComponent(channel);\n const scaleType = scale ? scale.get('type') : undefined;\n\n if (scaleType == 'sequential') {\n log.warn(log.message.SEQUENTIAL_SCALE_DEPRECATED);\n }\n\n if (!scale || !hasContinuousDomain(scaleType)) {\n log.warn(log.message.SCALE_BINDINGS_CONTINUOUS);\n continue;\n }\n\n scale.set('selectionExtent', {param: selCmpt.name, field: proj.field}, true);\n bound.push(proj);\n }\n },\n\n topLevelSignals: (model, selCmpt, signals) => {\n const bound = selCmpt.scales.filter(proj => signals.filter(s => s.name === proj.signals.data).length === 0);\n\n // Top-level signals are only needed for multiview displays and if this\n // view's top-level signals haven't already been generated.\n if (!model.parent || isTopLevelLayer(model) || bound.length === 0) {\n return signals;\n }\n\n // vlSelectionResolve does not account for the behavior of bound scales in\n // multiview displays. Each unit view adds a tuple to the store, but the\n // state of the selection is the unit selection most recently updated. This\n // state is captured by the top-level signals that we insert and \"push\n // outer\" to from within the units. We need to reassemble this state into\n // the top-level named signal, except no single selCmpt has a global view.\n const namedSg: NewSignal = signals.filter(s => s.name === selCmpt.name)[0];\n let update = namedSg.update;\n if (update.indexOf(VL_SELECTION_RESOLVE) >= 0) {\n namedSg.update = `{${bound\n .map(proj => `${stringValue(replacePathInField(proj.field))}: ${proj.signals.data}`)\n .join(', ')}}`;\n } else {\n for (const proj of bound) {\n const mapping = `${stringValue(replacePathInField(proj.field))}: ${proj.signals.data}`;\n if (!update.includes(mapping)) {\n update = `${update.substring(0, update.length - 1)}, ${mapping}}`;\n }\n }\n namedSg.update = update;\n }\n\n return signals.concat(bound.map(proj => ({name: proj.signals.data})));\n },\n\n signals: (model, selCmpt, signals) => {\n // Nested signals need only push to top-level signals with multiview displays.\n if (model.parent && !isTopLevelLayer(model)) {\n for (const proj of selCmpt.scales) {\n const signal: any = signals.find(s => s.name === proj.signals.data);\n signal.push = 'outer';\n delete signal.value;\n delete signal.update;\n }\n }\n\n return signals;\n }\n};\n\nexport default scaleBindings;\n\nexport function domain(model: UnitModel, channel: ScaleChannel) {\n const scale = stringValue(model.scaleName(channel));\n return `domain(${scale})`;\n}\n\nfunction isTopLevelLayer(model: Model): boolean {\n return model.parent && isLayerModel(model.parent) && (!model.parent.parent ?? isTopLevelLayer(model.parent.parent));\n}\n","import {isObject, NewSignal, OnEvent, SignalValue, Stream} from 'vega';\nimport {array, stringValue} from 'vega-util';\nimport {SelectionCompiler, SelectionComponent, STORE, TUPLE, unitName} from '.';\nimport {GeoPositionChannel, LATITUDE, LONGITUDE, ScaleChannel, X, Y} from '../../channel';\nimport {FieldName} from '../../channeldef';\nimport {warn} from '../../log';\nimport {hasContinuousDomain} from '../../scale';\nimport {IntervalSelectionConfigWithoutType, SelectionInitInterval, SELECTION_ID} from '../../selection';\nimport {keys, vals} from '../../util';\nimport {LayoutSizeIndex} from '../layoutsize/component';\nimport {isUnitModel} from '../model';\nimport {UnitModel} from '../unit';\nimport {assembleInit} from './assemble';\nimport {SelectionProjection, TUPLE_FIELDS} from './project';\nimport scales from './scales';\n\nexport const BRUSH = '_brush';\nexport const SCALE_TRIGGER = '_scale_trigger';\nexport const GEO_INIT_TICK = 'geo_interval_init_tick'; // Workaround for https://github.com/vega/vega/issues/3481\nconst INIT = '_init';\nconst CENTER = '_center';\n\n// Separate type because the \"fields\" property is only used internally and we don't want to leak it to the schema.\nexport type IntervalSelectionConfigWithField = IntervalSelectionConfigWithoutType & {fields?: FieldName[]};\n\nconst interval: SelectionCompiler<'interval'> = {\n defined: selCmpt => selCmpt.type === 'interval',\n\n parse: (model, selCmpt, selDef) => {\n if (model.hasProjection) {\n const def: IntervalSelectionConfigWithField = {...(isObject(selDef.select) ? selDef.select : {})};\n def.fields = [SELECTION_ID];\n if (!def.encodings) {\n // Remap default x/y projection\n def.encodings = selDef.value ? (keys(selDef.value) as GeoPositionChannel[]) : [LONGITUDE, LATITUDE];\n }\n\n selDef.select = {type: 'interval', ...def};\n }\n\n if (selCmpt.translate && !scales.defined(selCmpt)) {\n const filterExpr = `!event.item || event.item.mark.name !== ${stringValue(selCmpt.name + BRUSH)}`;\n for (const evt of selCmpt.events) {\n if (!evt.between) {\n warn(`${evt} is not an ordered event stream for interval selections.`);\n continue;\n }\n\n const filters = array((evt.between[0].filter ??= []));\n if (filters.indexOf(filterExpr) < 0) {\n filters.push(filterExpr);\n }\n }\n }\n },\n\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const tupleSg = name + TUPLE;\n const channels = vals(selCmpt.project.hasChannel).filter(p => p.channel === X || p.channel === Y);\n const init = selCmpt.init ? selCmpt.init[0] : null;\n\n signals.push(\n ...channels.reduce((arr, proj) => arr.concat(channelSignals(model, selCmpt, proj, init && init[proj.index])), [])\n );\n\n if (!model.hasProjection) {\n // Proxy scale reactions to ensure that an infinite loop doesn't occur\n // when an interval selection filter touches the scale.\n if (!scales.defined(selCmpt)) {\n const triggerSg = name + SCALE_TRIGGER;\n const scaleTriggers = channels.map(proj => {\n const channel = proj.channel as 'x' | 'y';\n const {data: dname, visual: vname} = proj.signals;\n const scaleName = stringValue(model.scaleName(channel));\n const scaleType = model.getScaleComponent(channel).get('type');\n const toNum = hasContinuousDomain(scaleType) ? '+' : '';\n return (\n `(!isArray(${dname}) || ` +\n `(${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ` +\n `${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))`\n );\n });\n\n if (scaleTriggers.length) {\n signals.push({\n name: triggerSg,\n value: {},\n on: [\n {\n events: channels.map(proj => ({scale: model.scaleName(proj.channel)})),\n update: scaleTriggers.join(' && ') + ` ? ${triggerSg} : {}`\n }\n ]\n });\n }\n }\n\n // Only add an interval to the store if it has valid data extents. Data extents\n // are set to null if pixel extents are equal to account for intervals over\n // ordinal/nominal domains which, when inverted, will still produce a valid datum.\n const dataSignals = channels.map(proj => proj.signals.data);\n const update = `unit: ${unitName(model)}, fields: ${name + TUPLE_FIELDS}, values`;\n return signals.concat({\n name: tupleSg,\n ...(init ? {init: `{${update}: ${assembleInit(init)}}`} : {}),\n ...(dataSignals.length\n ? {\n on: [\n {\n events: [{signal: dataSignals.join(' || ')}], // Prevents double invocation, see https://github.com/vega/vega/issues/1672.\n update: `${dataSignals.join(' && ')} ? {${update}: [${dataSignals}]} : null`\n }\n ]\n }\n : {})\n });\n } else {\n const projection = stringValue(model.projectionName());\n const centerSg = model.projectionName() + CENTER;\n const {x, y} = selCmpt.project.hasChannel;\n const xvname = x && x.signals.visual;\n const yvname = y && y.signals.visual;\n const xinit = x ? init && init[x.index] : `${centerSg}[0]`;\n const yinit = y ? init && init[y.index] : `${centerSg}[1]`;\n const sizeSg = (layout: keyof LayoutSizeIndex) => model.getSizeSignalRef(layout).signal;\n const bbox =\n `[` +\n `[${xvname ? xvname + '[0]' : '0'}, ${yvname ? yvname + '[0]' : '0'}],` +\n `[${xvname ? xvname + '[1]' : sizeSg('width')}, ` +\n `${yvname ? yvname + '[1]' : sizeSg('height')}]` +\n `]`;\n\n if (init) {\n signals.unshift({\n name: name + INIT,\n init:\n `[scale(${projection}, [${x ? xinit[0] : xinit}, ${y ? yinit[0] : yinit}]), ` +\n `scale(${projection}, [${x ? xinit[1] : xinit}, ${y ? yinit[1] : yinit}])]`\n });\n\n if (!x || !y) {\n // If initializing a uni-dimensional brush, use the center of the view to determine the other coord\n const hasCenterSg = signals.find(s => s.name === centerSg);\n if (!hasCenterSg) {\n signals.unshift({\n name: centerSg,\n update: `invert(${projection}, [${sizeSg('width')}/2, ${sizeSg('height')}/2])`\n });\n }\n }\n }\n\n const intersect = `intersect(${bbox}, {markname: ${stringValue(model.getName('marks'))}}, unit.mark)`;\n const base = `{unit: ${unitName(model)}}`;\n const update = `vlSelectionTuples(${intersect}, ${base})`;\n const visualSignals = channels.map(proj => proj.signals.visual);\n\n return signals.concat({\n name: tupleSg,\n on: [\n {\n events: [\n ...(visualSignals.length ? [{signal: visualSignals.join(' || ')}] : []),\n ...(init ? [{signal: GEO_INIT_TICK}] : [])\n ],\n update\n }\n ]\n });\n }\n },\n\n topLevelSignals: (model, selCmpt, signals) => {\n if (isUnitModel(model) && model.hasProjection && selCmpt.init) {\n // Workaround for https://github.com/vega/vega/issues/3481\n // The scenegraph isn't populated on the first pulse. So we use a timer signal\n // to re-pulse the dataflow as soon as possible. We return an object to ensure\n // this only occurs once.\n const hasTick = signals.filter(s => s.name === GEO_INIT_TICK);\n if (!hasTick.length) {\n signals.unshift({\n name: GEO_INIT_TICK,\n value: null,\n on: [\n {\n events: 'timer{1}',\n update: `${GEO_INIT_TICK} === null ? {} : ${GEO_INIT_TICK}`\n }\n ]\n });\n }\n }\n\n return signals;\n },\n\n marks: (model, selCmpt, marks) => {\n const name = selCmpt.name;\n const {x, y} = selCmpt.project.hasChannel;\n const xvname = x?.signals.visual;\n const yvname = y?.signals.visual;\n const store = `data(${stringValue(selCmpt.name + STORE)})`;\n\n // Do not add a brush if we're binding to scales\n // or we don't have a valid interval projection\n if (scales.defined(selCmpt) || (!x && !y)) {\n return marks;\n }\n\n const update: any = {\n x: x !== undefined ? {signal: `${xvname}[0]`} : {value: 0},\n y: y !== undefined ? {signal: `${yvname}[0]`} : {value: 0},\n x2: x !== undefined ? {signal: `${xvname}[1]`} : {field: {group: 'width'}},\n y2: y !== undefined ? {signal: `${yvname}[1]`} : {field: {group: 'height'}}\n };\n\n // If the selection is resolved to global, only a single interval is in\n // the store. Wrap brush mark's encodings with a production rule to test\n // this based on the `unit` property. Hide the brush mark if it corresponds\n // to a unit different from the one in the store.\n if (selCmpt.resolve === 'global') {\n for (const key of keys(update)) {\n update[key] = [\n {\n test: `${store}.length && ${store}[0].unit === ${unitName(model)}`,\n ...update[key]\n },\n {value: 0}\n ];\n }\n }\n\n // Two brush marks ensure that fill colors and other aesthetic choices do\n // not interefere with the core marks, but that the brushed region can still\n // be interacted with (e.g., dragging it around).\n const {fill, fillOpacity, cursor, ...stroke} = selCmpt.mark;\n const vgStroke = keys(stroke).reduce((def, k) => {\n def[k] = [\n {\n test: [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`]\n .filter(t => t)\n .join(' && '),\n value: stroke[k]\n },\n {value: null}\n ];\n return def;\n }, {});\n\n // Set cursor to move unless the brush cannot be translated\n const vgCursor = cursor ?? (selCmpt.translate ? 'move' : null);\n\n return [\n {\n name: `${name + BRUSH}_bg`,\n type: 'rect',\n clip: true,\n encode: {\n enter: {\n fill: {value: fill},\n fillOpacity: {value: fillOpacity}\n },\n update\n }\n },\n ...marks,\n {\n name: name + BRUSH,\n type: 'rect',\n clip: true,\n encode: {\n enter: {\n ...(vgCursor ? {cursor: {value: vgCursor}} : {}),\n fill: {value: 'transparent'}\n },\n update: {...update, ...vgStroke}\n }\n }\n ];\n }\n};\nexport default interval;\n\n/**\n * Returns the visual and data signals for an interval selection.\n */\nfunction channelSignals(\n model: UnitModel,\n selCmpt: SelectionComponent<'interval'>,\n proj: SelectionProjection,\n init: SelectionInitInterval\n): NewSignal[] {\n const scaledInterval = !model.hasProjection;\n const channel = proj.channel;\n const vname = proj.signals.visual;\n\n const scaleName = stringValue(scaledInterval ? model.scaleName(channel) : model.projectionName());\n const scaled = (str: string) => `scale(${scaleName}, ${str})`;\n\n const size = model.getSizeSignalRef(channel === X ? 'width' : 'height').signal;\n const coord = `${channel}(unit)`;\n const von = selCmpt.events.reduce((def: OnEvent[], evt: Stream) => {\n return [\n ...def,\n {events: evt.between[0], update: `[${coord}, ${coord}]`}, // Brush Start\n {events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]`} // Brush End\n ];\n }, []);\n\n if (scaledInterval) {\n const dname = proj.signals.data;\n const hasScales = scales.defined(selCmpt);\n const scale = model.getScaleComponent(channel as ScaleChannel);\n const scaleType = scale ? scale.get('type') : undefined;\n const vinit: SignalValue = init ? {init: assembleInit(init, true, scaled)} : {value: []};\n\n // React to pan/zooms of continuous scales. Non-continuous scales\n // (band, point) cannot be pan/zoomed and any other changes\n // to their domains (e.g., filtering) should clear the brushes.\n von.push({\n events: {signal: selCmpt.name + SCALE_TRIGGER},\n update: hasContinuousDomain(scaleType) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]`\n });\n\n return hasScales\n ? [{name: dname, on: []}]\n : [\n {name: vname, ...vinit, on: von},\n {\n name: dname,\n ...(init ? {init: assembleInit(init)} : {}), // Cannot be `value` as `init` may require datetime exprs.\n on: [\n {\n events: {signal: vname},\n update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})`\n }\n ]\n }\n ];\n } else {\n const initIdx = channel === X ? 0 : 1;\n const initSg = selCmpt.name + INIT;\n const vinit: SignalValue = init ? {init: `[${initSg}[0][${initIdx}], ${initSg}[1][${initIdx}]]`} : {value: []};\n return [{name: vname, ...vinit, on: von}];\n }\n}\n","import {Stream} from 'vega';\nimport {stringValue} from 'vega-util';\nimport {SelectionCompiler, TUPLE, unitName} from '.';\nimport {SELECTION_ID} from '../../selection';\nimport {vals} from '../../util';\nimport {BRUSH} from './interval';\nimport {TUPLE_FIELDS} from './project';\n\nconst point: SelectionCompiler<'point'> = {\n defined: selCmpt => selCmpt.type === 'point',\n\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const fieldsSg = name + TUPLE_FIELDS;\n const project = selCmpt.project;\n const datum = '(item().isVoronoi ? datum.datum : datum)';\n\n // Only add a discrete selection to the store if a datum is present _and_\n // the interaction isn't occurring on a group mark. This guards against\n // polluting interactive state with invalid values in faceted displays\n // as the group marks are also data-driven. We force the update to account\n // for constant null states but varying toggles (e.g., shift-click in\n // whitespace followed by a click in whitespace; the store should only\n // be cleared on the second click).\n const brushes = vals(model.component.selection ?? {})\n .reduce((acc, cmpt) => {\n return cmpt.type === 'interval' ? acc.concat(cmpt.name + BRUSH) : acc;\n }, [])\n .map(b => `indexof(item().mark.name, '${b}') < 0`)\n .join(' && ');\n\n const test = `datum && item().mark.marktype !== 'group' && indexof(item().mark.role, 'legend') < 0${\n brushes ? ` && ${brushes}` : ''\n }`;\n\n let update = `unit: ${unitName(model)}, `;\n\n if (selCmpt.project.hasSelectionId) {\n update += `${SELECTION_ID}: ${datum}[${stringValue(SELECTION_ID)}]`;\n } else {\n const values = project.items\n .map(p => {\n const fieldDef = model.fieldDef(p.channel);\n // Binned fields should capture extents, for a range test against the raw field.\n return fieldDef?.bin\n ? `[${datum}[${stringValue(model.vgField(p.channel, {}))}], ` +\n `${datum}[${stringValue(model.vgField(p.channel, {binSuffix: 'end'}))}]]`\n : `${datum}[${stringValue(p.field)}]`;\n })\n .join(', ');\n\n update += `fields: ${fieldsSg}, values: [${values}]`;\n }\n\n const events: Stream[] = selCmpt.events;\n return signals.concat([\n {\n name: name + TUPLE,\n on: events\n ? [\n {\n events,\n update: `${test} ? {${update}} : null`,\n force: true\n }\n ]\n : []\n }\n ]);\n }\n};\n\nexport default point;\n","import {array} from 'vega-util';\nimport {ChannelDef, ConditionalPredicate, isConditionalDef, isConditionalParameter} from '../../../channeldef';\nimport {GuideEncodingConditionalValueDef} from '../../../guide';\nimport {VgEncodeEntry, VgValueRef} from '../../../vega.schema';\nimport {expression} from '../../predicate';\nimport {parseSelectionPredicate} from '../../selection/parse';\nimport {UnitModel} from '../../unit';\n\n/**\n * Return a VgEncodeEntry that includes a Vega production rule for a scale channel's encoding or guide encoding, which includes:\n * (1) the conditional rules (if provided as part of channelDef)\n * (2) invalidValueRef for handling invalid values (if provided as a parameter of this method)\n * (3) main reference for the encoded data.\n */\nexport function wrapCondition({\n model,\n channelDef,\n vgChannel,\n invalidValueRef,\n mainRefFn\n}: {\n model: UnitModel;\n channelDef: CD;\n vgChannel: string;\n\n /**\n * invalidValue for a scale channel if the invalidDataMode is include for the channel.\n * For scale channel with other invalidDataMode or non-scale channel, this value should be undefined.\n */\n invalidValueRef: VgValueRef | undefined;\n mainRefFn: (cDef: CD) => VgValueRef;\n}): VgEncodeEntry {\n const condition = isConditionalDef(channelDef) && channelDef.condition;\n\n let valueRefs: VgValueRef[] = [];\n\n if (condition) {\n const conditions = array(condition);\n valueRefs = conditions.map(c => {\n const conditionValueRef = mainRefFn(c);\n if (isConditionalParameter(c)) {\n const {param, empty} = c;\n const test = parseSelectionPredicate(model, {param, empty});\n return {test, ...conditionValueRef};\n } else {\n const test = expression(model, (c as ConditionalPredicate).test); // FIXME: remove casting once TS is no longer dumb about it\n return {test, ...conditionValueRef};\n }\n });\n }\n\n if (invalidValueRef !== undefined) {\n valueRefs.push(invalidValueRef);\n }\n\n const mainValueRef = mainRefFn(channelDef);\n if (mainValueRef !== undefined) {\n valueRefs.push(mainValueRef);\n }\n\n if (\n valueRefs.length > 1 ||\n (valueRefs.length === 1 && Boolean(valueRefs[0].test)) // We must use array form valueRefs if test exists, otherwise Vega won't execute the test.\n ) {\n return {[vgChannel]: valueRefs};\n } else if (valueRefs.length === 1) {\n return {[vgChannel]: valueRefs[0]};\n }\n return {};\n}\n","import {getFormatMixins, isFieldOrDatumDef, isValueDef} from '../../../channeldef';\nimport {Config} from '../../../config';\nimport {Encoding} from '../../../encoding';\nimport {VgValueRef} from '../../../vega.schema';\nimport {signalOrValueRef} from '../../common';\nimport {formatSignalRef} from '../../format';\nimport {UnitModel} from '../../unit';\nimport {wrapCondition} from './conditional';\n\nexport function text(model: UnitModel, channel: 'text' | 'href' | 'url' | 'description' = 'text') {\n const channelDef = model.encoding[channel];\n return wrapCondition({\n model,\n channelDef,\n vgChannel: channel,\n mainRefFn: cDef => textRef(cDef, model.config),\n invalidValueRef: undefined // text encoding doesn't have continuous scales and thus can't have invalid values\n });\n}\n\nexport function textRef(\n channelDef: Encoding['text' | 'tooltip'],\n config: Config,\n expr: 'datum' | 'datum.datum' = 'datum'\n): VgValueRef {\n // text\n if (channelDef) {\n if (isValueDef(channelDef)) {\n return signalOrValueRef(channelDef.value);\n }\n if (isFieldOrDatumDef(channelDef)) {\n const {format, formatType} = getFormatMixins(channelDef);\n return formatSignalRef({fieldOrDatumDef: channelDef, format, formatType, expr, config});\n }\n }\n return undefined;\n}\n","import {array, isArray, isObject, isString} from 'vega-util';\nimport {isBinned} from '../../../bin';\nimport {getMainRangeChannel, isXorY, Channel, THETA, RADIUS} from '../../../channel';\nimport {\n defaultTitle,\n getFieldDef,\n getFormatMixins,\n hasConditionalFieldDef,\n isFieldDef,\n isTypedFieldDef,\n SecondaryFieldDef,\n TypedFieldDef,\n vgField\n} from '../../../channeldef';\nimport {Config} from '../../../config';\nimport {Encoding, forEach} from '../../../encoding';\nimport {StackProperties} from '../../../stack';\nimport {entries} from '../../../util';\nimport {isSignalRef} from '../../../vega.schema';\nimport {getMarkPropOrConfig} from '../../common';\nimport {binFormatExpression, formatSignalRef} from '../../format';\nimport {UnitModel} from '../../unit';\nimport {wrapCondition} from './conditional';\nimport {textRef} from './text';\n\nexport function tooltip(model: UnitModel, opt: {reactiveGeom?: boolean} = {}) {\n const {encoding, markDef, config, stack} = model;\n const channelDef = encoding.tooltip;\n if (isArray(channelDef)) {\n return {tooltip: tooltipRefForEncoding({tooltip: channelDef}, stack, config, opt)};\n } else {\n const datum = opt.reactiveGeom ? 'datum.datum' : 'datum';\n const mainRefFn = (cDef: Encoding['tooltip']) => {\n // use valueRef based on channelDef first\n const tooltipRefFromChannelDef = textRef(cDef, config, datum);\n if (tooltipRefFromChannelDef) {\n return tooltipRefFromChannelDef;\n }\n\n if (cDef === null) {\n // Allow using encoding.tooltip = null to disable tooltip\n return undefined;\n }\n\n let markTooltip = getMarkPropOrConfig('tooltip', markDef, config);\n\n if (markTooltip === true) {\n markTooltip = {content: 'encoding'};\n }\n\n if (isString(markTooltip)) {\n return {value: markTooltip};\n } else if (isObject(markTooltip)) {\n // `tooltip` is `{fields: 'encodings' | 'fields'}`\n if (isSignalRef(markTooltip)) {\n return markTooltip;\n } else if (markTooltip.content === 'encoding') {\n return tooltipRefForEncoding(encoding, stack, config, opt);\n } else {\n return {signal: datum};\n }\n }\n\n return undefined;\n };\n\n return wrapCondition({\n model,\n channelDef,\n vgChannel: 'tooltip',\n mainRefFn,\n invalidValueRef: undefined // tooltip encoding doesn't have continuous scales and thus can't have invalid values\n });\n }\n}\n\nexport function tooltipData(\n encoding: Encoding,\n stack: StackProperties,\n config: Config,\n {reactiveGeom}: {reactiveGeom?: boolean} = {}\n) {\n const formatConfig = {...config, ...config.tooltipFormat};\n const toSkip = {};\n const expr = reactiveGeom ? 'datum.datum' : 'datum';\n const tuples: {channel: Channel; key: string; value: string}[] = [];\n\n function add(fDef: TypedFieldDef | SecondaryFieldDef, channel: Channel) {\n const mainChannel = getMainRangeChannel(channel);\n\n const fieldDef: TypedFieldDef = isTypedFieldDef(fDef)\n ? fDef\n : {\n ...fDef,\n type: (encoding[mainChannel] as TypedFieldDef).type // for secondary field def, copy type from main channel\n };\n\n const title = fieldDef.title || defaultTitle(fieldDef, formatConfig);\n const key = array(title).join(', ').replaceAll(/\"/g, '\\\\\"');\n\n let value: string;\n\n if (isXorY(channel)) {\n const channel2 = channel === 'x' ? 'x2' : 'y2';\n const fieldDef2 = getFieldDef(encoding[channel2]);\n\n if (isBinned(fieldDef.bin) && fieldDef2) {\n const startField = vgField(fieldDef, {expr});\n const endField = vgField(fieldDef2, {expr});\n const {format, formatType} = getFormatMixins(fieldDef);\n value = binFormatExpression(startField, endField, format, formatType, formatConfig);\n toSkip[channel2] = true;\n }\n }\n\n if (\n (isXorY(channel) || channel === THETA || channel === RADIUS) &&\n stack &&\n stack.fieldChannel === channel &&\n stack.offset === 'normalize'\n ) {\n const {format, formatType} = getFormatMixins(fieldDef);\n value = formatSignalRef({\n fieldOrDatumDef: fieldDef,\n format,\n formatType,\n expr,\n config: formatConfig,\n normalizeStack: true\n }).signal;\n }\n\n value ??= textRef(fieldDef, formatConfig, expr).signal;\n\n tuples.push({channel, key, value});\n }\n\n forEach(encoding, (channelDef, channel) => {\n if (isFieldDef(channelDef)) {\n add(channelDef, channel);\n } else if (hasConditionalFieldDef(channelDef)) {\n add(channelDef.condition, channel);\n }\n });\n\n const out = {};\n for (const {channel, key, value} of tuples) {\n if (!toSkip[channel] && !out[key]) {\n out[key] = value;\n }\n }\n\n return out;\n}\n\nexport function tooltipRefForEncoding(\n encoding: Encoding,\n stack: StackProperties,\n config: Config,\n {reactiveGeom}: {reactiveGeom?: boolean} = {}\n) {\n const data = tooltipData(encoding, stack, config, {reactiveGeom});\n\n const keyValues = entries(data).map(([key, value]) => `\"${key}\": ${value}`);\n return keyValues.length > 0 ? {signal: `{${keyValues.join(', ')}}`} : undefined;\n}\n","import {entries, isEmpty} from '../../../util';\nimport {getMarkPropOrConfig, signalOrValueRef} from '../../common';\nimport {VG_MARK_INDEX} from './../../../vega.schema';\nimport {UnitModel} from './../../unit';\nimport {wrapCondition} from './conditional';\nimport {textRef} from './text';\nimport {tooltipData} from './tooltip';\n\nexport function aria(model: UnitModel) {\n const {markDef, config} = model;\n\n const enableAria = getMarkPropOrConfig('aria', markDef, config);\n\n // We can ignore other aria properties if ariaHidden is true.\n if (enableAria === false) {\n // getMarkGroups sets aria to false already so we don't have to set it in the encode block\n return {};\n }\n\n return {\n ...(enableAria ? {aria: enableAria} : {}),\n ...ariaRoleDescription(model),\n ...description(model)\n };\n}\n\nfunction ariaRoleDescription(model: UnitModel) {\n const {mark, markDef, config} = model;\n\n if (config.aria === false) {\n return {};\n }\n\n const ariaRoleDesc = getMarkPropOrConfig('ariaRoleDescription', markDef, config);\n\n if (ariaRoleDesc != null) {\n return {ariaRoleDescription: {value: ariaRoleDesc}};\n }\n\n return mark in VG_MARK_INDEX ? {} : {ariaRoleDescription: {value: mark}};\n}\n\nexport function description(model: UnitModel) {\n const {encoding, markDef, config, stack} = model;\n const channelDef = encoding.description;\n\n if (channelDef) {\n return wrapCondition({\n model,\n channelDef,\n vgChannel: 'description',\n mainRefFn: cDef => textRef(cDef, model.config),\n invalidValueRef: undefined // aria encoding doesn't have continuous scales and thus can't have invalid values\n });\n }\n\n // Use default from mark def or config if defined.\n // Functions in encode usually just return undefined but since we are defining a default below, we need to check the default here.\n const descriptionValue = getMarkPropOrConfig('description', markDef, config);\n if (descriptionValue != null) {\n return {\n description: signalOrValueRef(descriptionValue)\n };\n }\n\n if (config.aria === false) {\n return {};\n }\n\n const data = tooltipData(encoding, stack, config);\n\n if (isEmpty(data)) {\n return undefined;\n }\n\n return {\n description: {\n signal: entries(data)\n .map(([key, value], index) => `\"${index > 0 ? '; ' : ''}${key}: \" + (${value})`)\n .join(' + ')\n }\n };\n}\n","import type {SignalRef} from 'vega';\nimport {NonPositionScaleChannel} from '../../../channel';\nimport {Value} from '../../../channeldef';\nimport {VgEncodeChannel, VgEncodeEntry, VgValueRef} from '../../../vega.schema';\nimport {getMarkPropOrConfig, signalOrValueRef} from '../../common';\nimport {UnitModel} from '../../unit';\nimport {wrapCondition} from './conditional';\nimport * as ref from './valueref';\nimport {getConditionalValueRefForIncludingInvalidValue} from './invalid';\n\n/**\n * Return encode for non-positional channels with scales. (Text doesn't have scale.)\n */\nexport function nonPosition(\n channel: NonPositionScaleChannel,\n model: UnitModel,\n opt: {\n defaultValue?: Value | SignalRef;\n vgChannel?: VgEncodeChannel;\n defaultRef?: VgValueRef;\n } = {}\n): VgEncodeEntry {\n const {markDef, encoding, config} = model;\n const {vgChannel} = opt;\n let {defaultRef, defaultValue} = opt;\n\n if (defaultRef === undefined) {\n // prettier-ignore\n defaultValue ??= getMarkPropOrConfig(channel, markDef, config, {vgChannel, ignoreVgConfig: true});\n\n if (defaultValue !== undefined) {\n defaultRef = signalOrValueRef(defaultValue);\n }\n }\n\n const channelDef = encoding[channel];\n const commonProps = {\n markDef,\n config,\n scaleName: model.scaleName(channel),\n scale: model.getScaleComponent(channel)\n };\n\n const invalidValueRef = getConditionalValueRefForIncludingInvalidValue({\n ...commonProps,\n scaleChannel: channel,\n channelDef\n });\n\n const mainRefFn = (cDef: typeof channelDef) => {\n return ref.midPoint({\n ...commonProps,\n channel,\n channelDef: cDef,\n stack: null, // No need to provide stack for non-position as it does not affect mid point\n defaultRef\n });\n };\n\n return wrapCondition({\n model,\n channelDef,\n vgChannel: vgChannel ?? channel,\n invalidValueRef,\n mainRefFn\n });\n}\n","import * as log from '../../../log';\nimport {contains} from '../../../util';\nimport {VgEncodeEntry} from '../../../vega.schema';\nimport {getMarkPropOrConfig, signalOrValueRef} from '../../common';\nimport {UnitModel} from '../../unit';\nimport {nonPosition} from './nonposition';\n\nexport function color(model: UnitModel, opt: {filled: boolean | undefined} = {filled: undefined}): VgEncodeEntry {\n const {markDef, encoding, config} = model;\n const {type: markType} = markDef;\n\n // Allow filled to be overridden (for trail's \"filled\")\n const filled = opt.filled ?? getMarkPropOrConfig('filled', markDef, config);\n\n const transparentIfNeeded = contains(['bar', 'point', 'circle', 'square', 'geoshape'], markType)\n ? 'transparent'\n : undefined;\n\n const defaultFill =\n getMarkPropOrConfig(filled === true ? 'color' : undefined, markDef, config, {vgChannel: 'fill'}) ??\n // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified\n config.mark[filled === true && 'color'] ??\n // If there is no fill, always fill symbols, bar, geoshape\n // with transparent fills https://github.com/vega/vega-lite/issues/1316\n transparentIfNeeded;\n\n const defaultStroke =\n getMarkPropOrConfig(filled === false ? 'color' : undefined, markDef, config, {vgChannel: 'stroke'}) ??\n // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified\n config.mark[filled === false && 'color'];\n\n const colorVgChannel = filled ? 'fill' : 'stroke';\n\n const fillStrokeMarkDefAndConfig: VgEncodeEntry = {\n ...(defaultFill ? {fill: signalOrValueRef(defaultFill)} : {}),\n ...(defaultStroke ? {stroke: signalOrValueRef(defaultStroke)} : {})\n };\n\n if (markDef.color && (filled ? markDef.fill : markDef.stroke)) {\n log.warn(log.message.droppingColor('property', {fill: 'fill' in markDef, stroke: 'stroke' in markDef}));\n }\n\n return {\n ...fillStrokeMarkDefAndConfig,\n ...nonPosition('color', model, {\n vgChannel: colorVgChannel,\n defaultValue: filled ? defaultFill : defaultStroke\n }),\n ...nonPosition('fill', model, {\n // if there is encoding.fill, include default fill just in case we have conditional-only fill encoding\n defaultValue: encoding.fill ? defaultFill : undefined\n }),\n ...nonPosition('stroke', model, {\n // if there is encoding.stroke, include default fill just in case we have conditional-only stroke encoding\n defaultValue: encoding.stroke ? defaultStroke : undefined\n })\n };\n}\n","import {isValueDef} from '../../../channeldef';\nimport {isPathMark} from '../../../mark';\nimport {signalOrValueRef} from '../../common';\nimport {UnitModel} from '../../unit';\nimport {wrapCondition} from './conditional';\n\nexport function zindex(model: UnitModel) {\n const {encoding, mark} = model;\n const order = encoding.order;\n\n if (!isPathMark(mark) && isValueDef(order)) {\n return wrapCondition({\n model,\n channelDef: order,\n vgChannel: 'zindex',\n mainRefFn: cd => signalOrValueRef(cd.value),\n invalidValueRef: undefined // zindex encoding doesn't have continuous scales and thus can't have invalid values\n });\n }\n return {};\n}\n","/**\n * Utility files for producing Vega ValueRef for marks\n */\nimport type {SignalRef} from 'vega';\nimport {PolarPositionChannel, PositionChannel} from '../../../channel';\nimport {Encoding} from '../../../encoding';\nimport {Mark, MarkDef} from '../../../mark';\nimport {VgValueRef} from '../../../vega.schema';\nimport {signalOrValueRef} from '../../common';\nimport {UnitModel} from '../../unit';\nimport {midPoint} from './valueref';\n\nexport interface Offset {\n offsetType?: 'visual' | 'encoding';\n offset?: number | VgValueRef;\n}\n\nexport function positionOffset({\n channel: baseChannel,\n markDef,\n encoding = {},\n model,\n bandPosition\n}: {\n channel: PositionChannel | PolarPositionChannel;\n markDef: MarkDef;\n encoding?: Encoding;\n model?: UnitModel;\n bandPosition?: number;\n}): Offset {\n const channel = `${baseChannel}Offset` as\n | 'xOffset'\n | 'yOffset'\n | 'x2Offset'\n | 'y2Offset'\n | 'thetaOffset'\n | 'radiusOffset'\n | 'theta2Offset'\n | 'radius2Offset'; // Need to cast as the type can't be inferred automatically\n\n const defaultValue = markDef[channel];\n const channelDef = encoding[channel];\n\n if ((channel === 'xOffset' || channel === 'yOffset') && channelDef) {\n const ref = midPoint({\n channel: channel,\n channelDef,\n markDef,\n config: model?.config,\n scaleName: model.scaleName(channel),\n scale: model.getScaleComponent(channel),\n stack: null,\n defaultRef: signalOrValueRef(defaultValue),\n bandPosition\n });\n return {offsetType: 'encoding', offset: ref};\n }\n\n const markDefOffsetValue = markDef[channel];\n if (markDefOffsetValue) {\n return {offsetType: 'visual', offset: markDefOffsetValue};\n }\n\n return {};\n}\n","import {\n getMainRangeChannel,\n getSecondaryRangeChannel,\n getSizeChannel,\n getVgPositionChannel,\n isXorY,\n PolarPositionChannel,\n PolarPositionScaleChannel,\n PositionChannel,\n PositionScaleChannel\n} from '../../../channel';\nimport {isFieldDef, isFieldOrDatumDef, TypedFieldDef} from '../../../channeldef';\nimport {Config} from '../../../config';\nimport {VgValueRef} from '../../../vega.schema';\nimport {getMarkPropOrConfig} from '../../common';\nimport {ScaleComponent} from '../../scale/component';\nimport {UnitModel} from '../../unit';\nimport {positionOffset} from './offset';\nimport * as ref from './valueref';\nimport {scaledZeroOrMinOrMax, ScaledZeroOrMinOrMaxProps} from './scaledZeroOrMinOrMax';\n\n/**\n * Return encode for point (non-band) position channels.\n */\nexport function pointPosition(\n channel: 'x' | 'y' | 'theta' | 'radius',\n model: UnitModel,\n {\n defaultPos,\n vgChannel\n }: {\n defaultPos: 'mid' | 'zeroOrMin' | 'zeroOrMax' | null;\n vgChannel?: 'x' | 'y' | 'xc' | 'yc';\n }\n) {\n const {encoding, markDef, config, stack} = model;\n\n const channelDef = encoding[channel];\n const channel2Def = encoding[getSecondaryRangeChannel(channel)];\n const scaleName = model.scaleName(channel);\n const scale = model.getScaleComponent(channel);\n\n const {offset, offsetType} = positionOffset({\n channel,\n markDef,\n encoding,\n model,\n bandPosition: 0.5\n });\n\n // Get default position or position from mark def\n const defaultRef = pointPositionDefaultRef({\n model,\n defaultPos,\n channel,\n scaleName,\n scale\n });\n\n const valueRef =\n !channelDef && isXorY(channel) && (encoding.latitude || encoding.longitude)\n ? // use geopoint output if there are lat/long and there is no point position overriding lat/long.\n {field: model.getName(channel)}\n : positionRef({\n channel,\n channelDef,\n channel2Def,\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef,\n bandPosition: offsetType === 'encoding' ? 0 : undefined\n });\n\n return valueRef ? {[vgChannel || channel]: valueRef} : undefined;\n}\n\n// TODO: we need to find a way to refactor these so that scaleName is a part of scale\n// but that's complicated. For now, this is a huge step moving forward.\n\n/**\n * @return Vega ValueRef for normal x- or y-position without projection\n */\nexport function positionRef(\n params: ref.MidPointParams & {\n channel: 'x' | 'y' | 'radius' | 'theta';\n }\n): VgValueRef | VgValueRef[] {\n const {channel, channelDef, scaleName, stack, offset, markDef} = params;\n\n // This isn't a part of midPoint because we use midPoint for non-position too\n if (isFieldOrDatumDef(channelDef) && stack && channel === stack.fieldChannel) {\n if (isFieldDef(channelDef)) {\n let bandPosition = channelDef.bandPosition;\n\n if (bandPosition === undefined && markDef.type === 'text' && (channel === 'radius' || channel === 'theta')) {\n // theta and radius of text mark should use bandPosition = 0.5 by default\n // so that labels for arc marks are centered automatically\n bandPosition = 0.5;\n }\n\n if (bandPosition !== undefined) {\n return ref.interpolatedSignalRef({\n scaleName,\n fieldOrDatumDef: channelDef as TypedFieldDef, // positionRef always have type\n startSuffix: 'start',\n bandPosition,\n offset\n });\n }\n }\n // x or y use stack_end so that stacked line's point mark use stack_end too.\n return ref.valueRefForFieldOrDatumDef(channelDef, scaleName, {suffix: 'end'}, {offset});\n }\n\n return ref.midPointRefWithPositionInvalidTest(params);\n}\n\nexport function pointPositionDefaultRef({\n model,\n defaultPos,\n channel,\n scaleName,\n scale\n}: {\n model: UnitModel;\n defaultPos: 'mid' | 'zeroOrMin' | 'zeroOrMax' | null;\n channel: PositionChannel | PolarPositionChannel;\n scaleName: string;\n scale: ScaleComponent;\n}): () => VgValueRef {\n const {markDef, config} = model;\n return () => {\n const mainChannel = getMainRangeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n\n const definedValueOrConfig = getMarkPropOrConfig(channel, markDef, config, {vgChannel});\n if (definedValueOrConfig !== undefined) {\n return ref.widthHeightValueOrSignalRef(channel, definedValueOrConfig);\n }\n\n switch (defaultPos) {\n case 'zeroOrMin':\n return zeroOrMinOrMaxPosition({scaleName, scale, mode: 'zeroOrMin', mainChannel, config});\n case 'zeroOrMax':\n return zeroOrMinOrMaxPosition({\n scaleName,\n scale,\n mode: {zeroOrMax: {widthSignal: model.width.signal, heightSignal: model.height.signal}},\n mainChannel,\n config\n });\n case 'mid': {\n const sizeRef = model[getSizeChannel(channel)];\n return {...sizeRef, mult: 0.5};\n }\n }\n // defaultPos === null\n return undefined;\n };\n}\n\nfunction zeroOrMinOrMaxPosition({\n mainChannel,\n config,\n ...otherProps\n}: ScaledZeroOrMinOrMaxProps & {\n mainChannel: PositionScaleChannel | PolarPositionScaleChannel;\n config: Config;\n}): VgValueRef {\n const scaledValueRef = scaledZeroOrMinOrMax(otherProps);\n const {mode} = otherProps;\n\n if (scaledValueRef) {\n return scaledValueRef;\n }\n\n switch (mainChannel) {\n case 'radius': {\n if (mode === 'zeroOrMin') {\n return {value: 0}; // min value\n }\n const {widthSignal, heightSignal} = mode.zeroOrMax;\n // max of radius is min(width, height) / 2\n return {\n signal: `min(${widthSignal},${heightSignal})/2`\n };\n }\n case 'theta':\n return mode === 'zeroOrMin' ? {value: 0} : {signal: '2*PI'};\n case 'x':\n return mode === 'zeroOrMin' ? {value: 0} : {field: {group: 'width'}};\n case 'y':\n return mode === 'zeroOrMin' ? {field: {group: 'height'}} : {value: 0};\n }\n}\n","import {Align, SignalRef, TextBaseline} from 'vega';\nimport {getVgPositionChannel} from '../../../channel';\nimport {Config} from '../../../config';\nimport * as log from '../../../log';\nimport {Mark, MarkDef} from '../../../mark';\nimport {isSignalRef, VgEncodeChannel} from '../../../vega.schema';\nimport {getMarkPropOrConfig} from '../../common';\n\nconst ALIGNED_X_CHANNEL: Record = {\n left: 'x',\n center: 'xc',\n right: 'x2'\n};\n\nconst BASELINED_Y_CHANNEL = {\n top: 'y',\n middle: 'yc',\n bottom: 'y2'\n};\n\nexport function vgAlignedPositionChannel(\n channel: 'x' | 'y' | 'radius' | 'theta',\n markDef: MarkDef,\n config: Config,\n defaultAlign: 'top' | 'middle' = 'middle'\n) {\n if (channel === 'radius' || channel === 'theta') {\n return getVgPositionChannel(channel);\n }\n const alignChannel = channel === 'x' ? 'align' : 'baseline';\n const align = getMarkPropOrConfig(alignChannel, markDef, config);\n\n let alignExcludingSignal: Align | TextBaseline;\n\n if (isSignalRef(align)) {\n log.warn(log.message.rangeMarkAlignmentCannotBeExpression(alignChannel));\n alignExcludingSignal = undefined;\n } else {\n alignExcludingSignal = align;\n }\n\n if (channel === 'x') {\n return ALIGNED_X_CHANNEL[alignExcludingSignal || (defaultAlign === 'top' ? 'left' : 'center')];\n } else {\n return BASELINED_Y_CHANNEL[alignExcludingSignal || defaultAlign];\n }\n}\n","import type {SignalRef} from 'vega';\nimport {getMainRangeChannel, getSecondaryRangeChannel, getSizeChannel, getVgPositionChannel} from '../../../channel';\nimport {isFieldOrDatumDef} from '../../../channeldef';\nimport * as log from '../../../log';\nimport {isRelativeBandSize, Mark, MarkConfig, MarkDef} from '../../../mark';\nimport {VgEncodeEntry, VgValueRef} from '../../../vega.schema';\nimport {getMarkStyleConfig} from '../../common';\nimport {UnitModel} from '../../unit';\nimport {positionOffset} from './offset';\nimport {vgAlignedPositionChannel} from './position-align';\nimport {pointPosition, pointPositionDefaultRef} from './position-point';\nimport * as ref from './valueref';\n\n/**\n * Utility for area/rule position, which can be either point or range.\n * (One of the axes should be point and the other should be range.)\n */\nexport function pointOrRangePosition(\n channel: 'x' | 'y',\n model: UnitModel,\n {\n defaultPos,\n defaultPos2,\n range\n }: {\n defaultPos: 'zeroOrMin' | 'zeroOrMax' | 'mid';\n defaultPos2: 'zeroOrMin' | 'zeroOrMax';\n range: boolean;\n }\n) {\n if (range) {\n return rangePosition(channel, model, {defaultPos, defaultPos2});\n }\n return pointPosition(channel, model, {defaultPos});\n}\n\nexport function rangePosition(\n channel: 'x' | 'y' | 'theta' | 'radius',\n model: UnitModel,\n {\n defaultPos,\n defaultPos2\n }: {\n defaultPos: 'zeroOrMin' | 'zeroOrMax' | 'mid';\n defaultPos2: 'zeroOrMin' | 'zeroOrMax';\n }\n): VgEncodeEntry {\n const {markDef, config} = model;\n const channel2 = getSecondaryRangeChannel(channel);\n const sizeChannel = getSizeChannel(channel);\n\n const pos2Mixins = pointPosition2OrSize(model, defaultPos2, channel2);\n\n const vgChannel = pos2Mixins[sizeChannel]\n ? // If there is width/height, we need to position the marks based on the alignment.\n vgAlignedPositionChannel(channel, markDef, config)\n : // Otherwise, make sure to apply to the right Vg Channel (for arc mark)\n getVgPositionChannel(channel);\n\n return {\n ...pointPosition(channel, model, {defaultPos, vgChannel}),\n ...pos2Mixins\n };\n}\n\n/**\n * Return encode for x2, y2.\n * If channel is not specified, return one channel based on orientation.\n */\nfunction pointPosition2OrSize(\n model: UnitModel,\n defaultPos: 'zeroOrMin' | 'zeroOrMax',\n channel: 'x2' | 'y2' | 'radius2' | 'theta2'\n) {\n const {encoding, mark, markDef, stack, config} = model;\n\n const baseChannel = getMainRangeChannel(channel);\n const sizeChannel = getSizeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n\n const channelDef = encoding[baseChannel];\n const scaleName = model.scaleName(baseChannel);\n const scale = model.getScaleComponent(baseChannel);\n\n const {offset} =\n channel in encoding || channel in markDef\n ? positionOffset({channel, markDef, encoding, model})\n : positionOffset({channel: baseChannel, markDef, encoding, model});\n\n if (!channelDef && (channel === 'x2' || channel === 'y2') && (encoding.latitude || encoding.longitude)) {\n const vgSizeChannel = getSizeChannel(channel);\n\n const size = model.markDef[vgSizeChannel];\n if (size != null) {\n return {\n [vgSizeChannel]: {value: size}\n };\n } else {\n return {\n [vgChannel]: {field: model.getName(channel)}\n };\n }\n }\n\n const valueRef = position2Ref({\n channel,\n channelDef,\n channel2Def: encoding[channel],\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef: undefined\n });\n\n if (valueRef !== undefined) {\n return {[vgChannel]: valueRef};\n }\n\n // TODO: check width/height encoding here once we add them\n\n // no x2/y2 encoding, then try to read x2/y2 or width/height based on precedence:\n // markDef > config.style > mark-specific config (config[mark]) > general mark config (config.mark)\n\n return (\n position2orSize(channel, markDef) ||\n position2orSize(channel, {\n [channel]: getMarkStyleConfig(channel, markDef, config.style),\n [sizeChannel]: getMarkStyleConfig(sizeChannel, markDef, config.style)\n }) ||\n position2orSize(channel, config[mark]) ||\n position2orSize(channel, config.mark) || {\n [vgChannel]: pointPositionDefaultRef({\n model,\n defaultPos,\n channel,\n scaleName,\n scale\n })()\n }\n );\n}\n\nexport function position2Ref({\n channel,\n channelDef,\n channel2Def,\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef\n}: ref.MidPointParams & {\n channel: 'x2' | 'y2' | 'radius2' | 'theta2';\n}): VgValueRef | VgValueRef[] {\n if (\n isFieldOrDatumDef(channelDef) &&\n stack &&\n // If fieldChannel is X and channel is X2 (or Y and Y2)\n channel.charAt(0) === stack.fieldChannel.charAt(0)\n ) {\n return ref.valueRefForFieldOrDatumDef(channelDef, scaleName, {suffix: 'start'}, {offset});\n }\n return ref.midPointRefWithPositionInvalidTest({\n channel,\n channelDef: channel2Def,\n scaleName,\n scale,\n stack,\n markDef,\n config,\n offset,\n defaultRef\n });\n}\n\nfunction position2orSize(\n channel: 'x2' | 'y2' | 'radius2' | 'theta2',\n markDef: MarkConfig | MarkDef\n) {\n const sizeChannel = getSizeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n if (markDef[vgChannel] !== undefined) {\n return {[vgChannel]: ref.widthHeightValueOrSignalRef(channel, markDef[vgChannel])};\n } else if (markDef[channel] !== undefined) {\n return {[vgChannel]: ref.widthHeightValueOrSignalRef(channel, markDef[channel])};\n } else if (markDef[sizeChannel]) {\n const dimensionSize = markDef[sizeChannel];\n if (isRelativeBandSize(dimensionSize)) {\n log.warn(log.message.relativeBandSizeNotSupported(sizeChannel));\n } else {\n return {[sizeChannel]: ref.widthHeightValueOrSignalRef(channel, dimensionSize)};\n }\n }\n return undefined;\n}\n","import type {SignalRef} from 'vega';\nimport {isArray, isNumber} from 'vega-util';\nimport {isBinned, isBinning, isBinParams} from '../../../bin';\nimport {\n getOffsetChannel,\n getSecondaryRangeChannel,\n getSizeChannel,\n getVgPositionChannel,\n isPolarPositionChannel,\n isXorY,\n PolarPositionChannel,\n PositionChannel\n} from '../../../channel';\nimport {getBandPosition, getBandSize, isFieldDef, isFieldOrDatumDef, TypedFieldDef, vgField} from '../../../channeldef';\nimport {Config, getViewConfigDiscreteStep} from '../../../config';\nimport {Encoding} from '../../../encoding';\nimport * as log from '../../../log';\nimport {BandSize, isRelativeBandSize} from '../../../mark';\nimport {hasDiscreteDomain} from '../../../scale';\nimport {isSignalRef, isVgRangeStep, VgEncodeEntry, VgValueRef} from '../../../vega.schema';\nimport {getMarkConfig, getMarkPropOrConfig, signalOrStringValue, signalOrValueRef} from '../../common';\nimport {ScaleComponent} from '../../scale/component';\nimport {UnitModel} from '../../unit';\nimport {nonPosition} from './nonposition';\nimport {positionOffset} from './offset';\nimport {vgAlignedPositionChannel} from './position-align';\nimport {pointPositionDefaultRef} from './position-point';\nimport {rangePosition} from './position-range';\nimport * as ref from './valueref';\nimport {getOffsetScaleChannel} from '../../../channel';\nimport {getFirstDefined} from '../../../util';\nimport {Mark} from '../../../mark';\nimport {OFFSETTED_RECT_END_SUFFIX, OFFSETTED_RECT_START_SUFFIX} from '../../data/timeunit';\n\nexport function rectPosition(model: UnitModel, channel: 'x' | 'y' | 'theta' | 'radius'): VgEncodeEntry {\n const {config, encoding, markDef} = model;\n const mark = markDef.type;\n\n const channel2 = getSecondaryRangeChannel(channel);\n const sizeChannel = getSizeChannel(channel);\n const channelDef = encoding[channel];\n const channelDef2 = encoding[channel2];\n\n const scale = model.getScaleComponent(channel);\n const scaleType = scale ? scale.get('type') : undefined;\n\n const orient = markDef.orient;\n const hasSizeDef =\n encoding[sizeChannel] ?? encoding.size ?? getMarkPropOrConfig('size', markDef, config, {vgChannel: sizeChannel});\n\n const offsetScaleChannel = getOffsetChannel(channel);\n\n const isBarBand = mark === 'bar' && (channel === 'x' ? orient === 'vertical' : orient === 'horizontal');\n\n // x, x2, and width -- we must specify two of these in all conditions\n if (\n isFieldDef(channelDef) &&\n (isBinning(channelDef.bin) || isBinned(channelDef.bin) || (channelDef.timeUnit && !channelDef2)) &&\n !(hasSizeDef && !isRelativeBandSize(hasSizeDef)) &&\n !encoding[offsetScaleChannel] &&\n !hasDiscreteDomain(scaleType)\n ) {\n return rectBinPosition({\n fieldDef: channelDef,\n fieldDef2: channelDef2,\n channel,\n model\n });\n } else if (((isFieldOrDatumDef(channelDef) && hasDiscreteDomain(scaleType)) || isBarBand) && !channelDef2) {\n return positionAndSize(channelDef, channel, model);\n } else {\n return rangePosition(channel, model, {defaultPos: 'zeroOrMax', defaultPos2: 'zeroOrMin'});\n }\n}\n\nfunction defaultSizeRef(\n sizeChannel: 'width' | 'height',\n scaleName: string,\n scale: ScaleComponent,\n config: Config,\n bandSize: BandSize,\n hasFieldDef: boolean,\n mark: Mark\n): VgValueRef {\n if (isRelativeBandSize(bandSize)) {\n if (scale) {\n const scaleType = scale.get('type');\n if (scaleType === 'band') {\n let bandWidth = `bandwidth('${scaleName}')`;\n if (bandSize.band !== 1) {\n bandWidth = `${bandSize.band} * ${bandWidth}`;\n }\n const minBandSize = getMarkConfig('minBandSize', {type: mark}, config);\n return {signal: minBandSize ? `max(${signalOrStringValue(minBandSize)}, ${bandWidth})` : bandWidth};\n } else if (bandSize.band !== 1) {\n log.warn(log.message.cannotUseRelativeBandSizeWithNonBandScale(scaleType));\n bandSize = undefined;\n }\n } else {\n return {\n mult: bandSize.band,\n field: {group: sizeChannel}\n };\n }\n } else if (isSignalRef(bandSize)) {\n return bandSize;\n } else if (bandSize) {\n return {value: bandSize};\n }\n\n // no valid band size\n if (scale) {\n const scaleRange = scale.get('range');\n if (isVgRangeStep(scaleRange) && isNumber(scaleRange.step)) {\n return {value: scaleRange.step - 2};\n }\n }\n if (!hasFieldDef) {\n const {bandPaddingInner, barBandPaddingInner, rectBandPaddingInner} = config.scale;\n const padding = getFirstDefined(bandPaddingInner, mark === 'bar' ? barBandPaddingInner : rectBandPaddingInner); // this part is like paddingInner in scale.ts\n if (isSignalRef(padding)) {\n return {signal: `(1 - (${padding.signal})) * ${sizeChannel}`};\n } else if (isNumber(padding)) {\n return {signal: `${1 - padding} * ${sizeChannel}`};\n }\n }\n const defaultStep = getViewConfigDiscreteStep(config.view, sizeChannel);\n return {value: defaultStep - 2};\n}\n\n/**\n * Output position encoding and its size encoding for continuous, point, and band scales.\n */\nfunction positionAndSize(\n fieldDef: Encoding['x' | 'y' | 'theta' | 'radius'],\n channel: 'x' | 'y' | 'theta' | 'radius',\n model: UnitModel\n) {\n const {markDef, encoding, config, stack} = model;\n const orient = markDef.orient;\n\n const scaleName = model.scaleName(channel);\n const scale = model.getScaleComponent(channel);\n const vgSizeChannel = getSizeChannel(channel);\n const channel2 = getSecondaryRangeChannel(channel);\n\n const offsetScaleChannel = getOffsetChannel(channel);\n const offsetScaleName = model.scaleName(offsetScaleChannel);\n const offsetScale = model.getScaleComponent(getOffsetScaleChannel(channel));\n\n // use \"size\" channel for bars, if there is orient and the channel matches the right orientation\n const useVlSizeChannel = (orient === 'horizontal' && channel === 'y') || (orient === 'vertical' && channel === 'x');\n\n // Use size encoding / mark property / config if it exists\n let sizeMixins;\n if (encoding.size || markDef.size) {\n if (useVlSizeChannel) {\n sizeMixins = nonPosition('size', model, {\n vgChannel: vgSizeChannel,\n defaultRef: signalOrValueRef(markDef.size)\n });\n } else {\n log.warn(log.message.cannotApplySizeToNonOrientedMark(markDef.type));\n }\n }\n const hasSizeFromMarkOrEncoding = !!sizeMixins;\n\n // Otherwise, apply default value\n const bandSize = getBandSize({\n channel,\n fieldDef,\n markDef,\n config,\n scaleType: (scale || offsetScale)?.get('type'),\n useVlSizeChannel\n });\n\n sizeMixins = sizeMixins || {\n [vgSizeChannel]: defaultSizeRef(\n vgSizeChannel,\n offsetScaleName || scaleName,\n offsetScale || scale,\n config,\n bandSize,\n !!fieldDef,\n markDef.type\n )\n };\n\n /*\n Band scales with size value and all point scales, use xc/yc + band=0.5\n\n Otherwise (band scales that has size based on a band ref), use x/y with position band = (1 - size_band) / 2.\n In this case, size_band is the band specified in the x/y-encoding.\n By default band is 1, so `(1 - band) / 2` = 0.\n If band is 0.6, the the x/y position in such case should be `(1 - band) / 2` = 0.2\n */\n\n const defaultBandAlign =\n (scale || offsetScale)?.get('type') === 'band' && isRelativeBandSize(bandSize) && !hasSizeFromMarkOrEncoding\n ? 'top'\n : 'middle';\n\n const vgChannel = vgAlignedPositionChannel(channel, markDef, config, defaultBandAlign);\n const center = vgChannel === 'xc' || vgChannel === 'yc';\n const {offset, offsetType} = positionOffset({channel, markDef, encoding, model, bandPosition: center ? 0.5 : 0});\n\n const posRef = ref.midPointRefWithPositionInvalidTest({\n channel,\n channelDef: fieldDef,\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef: pointPositionDefaultRef({model, defaultPos: 'mid', channel, scaleName, scale}),\n bandPosition: center\n ? offsetType === 'encoding'\n ? 0\n : 0.5\n : isSignalRef(bandSize)\n ? {signal: `(1-${bandSize})/2`}\n : isRelativeBandSize(bandSize)\n ? (1 - bandSize.band) / 2\n : 0\n });\n\n if (vgSizeChannel) {\n return {[vgChannel]: posRef, ...sizeMixins};\n } else {\n // otherwise, we must simulate size by setting position2 = position + size\n // (for theta/radius since Vega doesn't have thetaWidth/radiusWidth)\n const vgChannel2 = getVgPositionChannel(channel2);\n const sizeRef = sizeMixins[vgSizeChannel];\n const sizeOffset = offset ? {...sizeRef, offset} : sizeRef;\n return {\n [vgChannel]: posRef,\n\n // posRef might be an array that wraps position invalid test\n [vgChannel2]: isArray(posRef)\n ? [posRef[0], {...posRef[1], offset: sizeOffset}]\n : {\n ...posRef,\n offset: sizeOffset\n }\n };\n }\n}\n\nfunction getBinSpacing(\n channel: PositionChannel | PolarPositionChannel,\n spacing: number,\n reverse: boolean | SignalRef,\n axisTranslate: number | SignalRef,\n offset: number | VgValueRef,\n minBandSize: number | SignalRef,\n bandSizeExpr: string\n) {\n if (isPolarPositionChannel(channel)) {\n return 0;\n }\n\n const isEnd = channel === 'x' || channel === 'y2';\n\n const spacingOffset = isEnd ? -spacing / 2 : spacing / 2;\n\n if (isSignalRef(reverse) || isSignalRef(offset) || isSignalRef(axisTranslate) || minBandSize) {\n const reverseExpr = signalOrStringValue(reverse);\n const offsetExpr = signalOrStringValue(offset);\n const axisTranslateExpr = signalOrStringValue(axisTranslate);\n const minBandSizeExpr = signalOrStringValue(minBandSize);\n\n const sign = isEnd ? '' : '-';\n\n const spacingAndSizeOffset = minBandSize\n ? `(${bandSizeExpr} < ${minBandSizeExpr} ? ${sign}0.5 * (${minBandSizeExpr} - (${bandSizeExpr})) : ${spacingOffset})`\n : spacingOffset;\n\n const t = axisTranslateExpr ? `${axisTranslateExpr} + ` : '';\n const r = reverseExpr ? `(${reverseExpr} ? -1 : 1) * ` : '';\n const o = offsetExpr ? `(${offsetExpr} + ${spacingAndSizeOffset})` : spacingAndSizeOffset;\n\n return {\n signal: t + r + o\n };\n } else {\n offset = offset || 0;\n return axisTranslate + (reverse ? -offset - spacingOffset : +offset + spacingOffset);\n }\n}\n\nfunction rectBinPosition({\n fieldDef,\n fieldDef2,\n channel,\n model\n}: {\n fieldDef: TypedFieldDef;\n fieldDef2?: Encoding['x2' | 'y2'];\n channel: 'x' | 'y' | 'theta' | 'radius';\n model: UnitModel;\n}) {\n const {config, markDef, encoding} = model;\n\n const scale = model.getScaleComponent(channel);\n const scaleName = model.scaleName(channel);\n const scaleType = scale ? scale.get('type') : undefined;\n const reverse = scale.get('reverse');\n\n const bandSize = getBandSize({channel, fieldDef, markDef, config, scaleType});\n\n const axis = model.component.axes[channel]?.[0];\n const axisTranslate = axis?.get('translate') ?? 0.5; // vega default is 0.5\n\n const spacing = isXorY(channel) ? getMarkPropOrConfig('binSpacing', markDef, config) ?? 0 : 0;\n\n const channel2 = getSecondaryRangeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n const vgChannel2 = getVgPositionChannel(channel2);\n const minBandSize = getMarkConfig('minBandSize', markDef, config);\n\n const {offset} = positionOffset({channel, markDef, encoding, model, bandPosition: 0});\n const {offset: offset2} = positionOffset({channel: channel2, markDef, encoding, model, bandPosition: 0});\n\n const bandSizeExpr = ref.binSizeExpr({fieldDef, scaleName});\n const binSpacingOffset = getBinSpacing(channel, spacing, reverse, axisTranslate, offset, minBandSize, bandSizeExpr);\n const binSpacingOffset2 = getBinSpacing(\n channel2,\n spacing,\n reverse,\n axisTranslate,\n offset2 ?? offset,\n minBandSize,\n bandSizeExpr\n );\n\n const bandPositionForBandSize = isSignalRef(bandSize)\n ? {signal: `(1-${bandSize.signal})/2`}\n : isRelativeBandSize(bandSize)\n ? (1 - bandSize.band) / 2\n : 0.5;\n\n const bandPosition = getBandPosition({fieldDef, fieldDef2, markDef, config});\n\n if (isBinning(fieldDef.bin) || fieldDef.timeUnit) {\n const useRectOffsetField = fieldDef.timeUnit && bandPosition !== 0.5;\n\n return {\n [vgChannel2]: rectBinRef({\n fieldDef,\n scaleName,\n bandPosition: bandPositionForBandSize,\n offset: binSpacingOffset2,\n useRectOffsetField\n }),\n [vgChannel]: rectBinRef({\n fieldDef,\n scaleName,\n bandPosition: isSignalRef(bandPositionForBandSize)\n ? {signal: `1-${bandPositionForBandSize.signal}`}\n : 1 - bandPositionForBandSize,\n offset: binSpacingOffset,\n useRectOffsetField\n })\n };\n } else if (isBinned(fieldDef.bin)) {\n const startRef = ref.valueRefForFieldOrDatumDef(fieldDef, scaleName, {}, {offset: binSpacingOffset2});\n\n if (isFieldDef(fieldDef2)) {\n return {\n [vgChannel2]: startRef,\n [vgChannel]: ref.valueRefForFieldOrDatumDef(fieldDef2, scaleName, {}, {offset: binSpacingOffset})\n };\n } else if (isBinParams(fieldDef.bin) && fieldDef.bin.step) {\n return {\n [vgChannel2]: startRef,\n [vgChannel]: {\n signal: `scale(\"${scaleName}\", ${vgField(fieldDef, {expr: 'datum'})} + ${fieldDef.bin.step})`,\n offset: binSpacingOffset\n }\n };\n }\n }\n log.warn(log.message.channelRequiredForBinned(channel2));\n return undefined;\n}\n\n/**\n * Value Ref for binned fields\n */\nfunction rectBinRef({\n fieldDef,\n scaleName,\n bandPosition,\n offset,\n useRectOffsetField\n}: {\n fieldDef: TypedFieldDef;\n scaleName: string;\n bandPosition: number | SignalRef;\n offset?: number | SignalRef;\n useRectOffsetField: boolean;\n}) {\n return ref.interpolatedSignalRef({\n scaleName,\n fieldOrDatumDef: fieldDef,\n bandPosition,\n offset,\n ...(useRectOffsetField\n ? {\n startSuffix: OFFSETTED_RECT_START_SUFFIX,\n endSuffix: OFFSETTED_RECT_END_SUFFIX\n }\n : {})\n });\n}\n","import {MarkDef} from '../../../mark';\nimport {VG_MARK_CONFIGS, VgEncodeEntry, VgValueRef} from '../../../vega.schema';\nimport {signalOrValueRef} from '../../common';\nimport {UnitModel} from '../../unit';\nimport {aria} from './aria';\nimport {color} from './color';\nimport {nonPosition} from './nonposition';\nimport {text} from './text';\nimport {tooltip} from './tooltip';\nimport {zindex} from './zindex';\n\nexport {color} from './color';\nexport {nonPosition} from './nonposition';\nexport {pointPosition} from './position-point';\nexport {pointOrRangePosition, rangePosition} from './position-range';\nexport {rectPosition} from './position-rect';\nexport {text} from './text';\nexport {tooltip} from './tooltip';\n\nexport type Ignore = Record<'color' | 'size' | 'orient' | 'align' | 'baseline' | 'theta', 'ignore' | 'include'>;\n\nconst ALWAYS_IGNORE = new Set(['aria', 'width', 'height']);\n\nexport function baseEncodeEntry(model: UnitModel, ignore: Ignore) {\n const {fill = undefined, stroke = undefined} = ignore.color === 'include' ? color(model) : {};\n return {\n ...markDefProperties(model.markDef, ignore),\n ...colorRef('fill', fill),\n ...colorRef('stroke', stroke),\n ...nonPosition('opacity', model),\n ...nonPosition('fillOpacity', model),\n ...nonPosition('strokeOpacity', model),\n ...nonPosition('strokeWidth', model),\n ...nonPosition('strokeDash', model),\n ...zindex(model),\n ...tooltip(model),\n ...text(model, 'href'),\n ...aria(model)\n };\n}\n\nfunction colorRef(channel: 'fill' | 'stroke', valueRef: VgValueRef | VgValueRef[]): VgEncodeEntry {\n return valueRef ? {[channel]: valueRef} : {};\n}\n\nfunction markDefProperties(mark: MarkDef, ignore: Ignore) {\n return VG_MARK_CONFIGS.reduce((m, prop) => {\n if (!ALWAYS_IGNORE.has(prop) && mark[prop] !== undefined && ignore[prop] !== 'ignore') {\n m[prop] = signalOrValueRef(mark[prop]);\n }\n return m;\n }, {});\n}\n","import {isCountingAggregateOp} from '../../../aggregate';\nimport {isScaleChannel} from '../../../channel';\nimport {Value} from '../../../channeldef';\nimport {fieldValidPredicate} from '../../../predicate';\nimport {VgEncodeEntry} from '../../../vega.schema';\nimport {signalOrValueRef} from '../../common';\nimport {getScaleInvalidDataMode, shouldBreakPath} from '../../invalid/ScaleInvalidDataMode';\nimport {UnitModel} from '../../unit';\n\n/**\n * Create Vega's \"defined\" encoding to break paths in a path mark for invalid values.\n */\nexport function defined(model: UnitModel): VgEncodeEntry {\n const {config, markDef} = model;\n\n // For each channel (x/y), add fields to break path to a set first.\n const fieldsToBreakPath = new Set();\n\n model.forEachFieldDef((fieldDef, channel) => {\n let scaleType;\n if (!isScaleChannel(channel) || !(scaleType = model.getScaleType(channel))) {\n // Skip if the channel is not a scale channel or does not have a scale\n return;\n }\n\n const isCountAggregate = isCountingAggregateOp(fieldDef.aggregate);\n const invalidDataMode = getScaleInvalidDataMode({\n scaleChannel: channel,\n markDef,\n config,\n scaleType,\n isCountAggregate\n });\n if (shouldBreakPath(invalidDataMode)) {\n const field = model.vgField(channel, {expr: 'datum', binSuffix: model.stack?.impute ? 'mid' : undefined});\n if (field) {\n fieldsToBreakPath.add(field);\n }\n }\n });\n\n // If the set is not empty, return a defined signal.\n if (fieldsToBreakPath.size > 0) {\n const signal = [...fieldsToBreakPath].map(field => fieldValidPredicate(field, true)).join(' && ');\n return {defined: {signal}};\n }\n return undefined;\n}\n\nexport function valueIfDefined(prop: string, value: Value): VgEncodeEntry {\n if (value !== undefined) {\n return {[prop]: signalOrValueRef(value)};\n }\n return undefined;\n}\n","import * as log from '../../log';\nimport {isPathMark} from '../../mark';\nimport {tooltip} from '../mark/encode';\nimport {SelectionCompiler} from '.';\n\nconst VORONOI = 'voronoi';\n\nconst nearest: SelectionCompiler<'point'> = {\n defined: selCmpt => {\n return selCmpt.type === 'point' && selCmpt.nearest;\n },\n\n parse: (model, selCmpt) => {\n // Scope selection events to the voronoi mark to prevent capturing\n // events that occur on the group mark (https://github.com/vega/vega/issues/2112).\n if (selCmpt.events) {\n for (const s of selCmpt.events) {\n s.markname = model.getName(VORONOI);\n }\n }\n },\n\n marks: (model, selCmpt, marks) => {\n const {x, y} = selCmpt.project.hasChannel;\n const markType = model.mark;\n if (isPathMark(markType)) {\n log.warn(log.message.nearestNotSupportForContinuous(markType));\n return marks;\n }\n\n const cellDef = {\n name: model.getName(VORONOI),\n type: 'path',\n interactive: true,\n from: {data: model.getName('marks')},\n encode: {\n update: {\n fill: {value: 'transparent'},\n strokeWidth: {value: 0.35},\n stroke: {value: 'transparent'},\n isVoronoi: {value: true},\n ...tooltip(model, {reactiveGeom: true})\n }\n },\n transform: [\n {\n type: 'voronoi',\n x: {expr: x || !y ? 'datum.datum.x || 0' : '0'},\n y: {expr: y || !x ? 'datum.datum.y || 0' : '0'},\n size: [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')]\n }\n ]\n };\n\n let index = 0;\n let exists = false;\n marks.forEach((mark, i) => {\n const name = mark.name ?? '';\n if (name === model.component.mark[0].name) {\n index = i;\n } else if (name.indexOf(VORONOI) >= 0) {\n exists = true;\n }\n });\n\n if (!exists) {\n marks.splice(index + 1, 0, cellDef);\n }\n\n return marks;\n }\n};\n\nexport default nearest;\n","import {stringValue} from 'vega-util';\nimport {disableDirectManipulation, TUPLE} from '.';\nimport {varName} from '../../util';\nimport {assembleInit} from './assemble';\nimport nearest from './nearest';\nimport {TUPLE_FIELDS} from './project';\nimport {SelectionCompiler} from '.';\nimport {isLegendBinding} from '../../selection';\nimport {NewSignal} from 'vega';\n\nconst inputBindings: SelectionCompiler<'point'> = {\n defined: selCmpt => {\n return (\n selCmpt.type === 'point' &&\n selCmpt.resolve === 'global' &&\n selCmpt.bind &&\n selCmpt.bind !== 'scales' &&\n !isLegendBinding(selCmpt.bind)\n );\n },\n\n parse: (model, selCmpt, selDef) => disableDirectManipulation(selCmpt, selDef),\n\n topLevelSignals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const proj = selCmpt.project;\n const bind = selCmpt.bind;\n const init = selCmpt.init && selCmpt.init[0]; // Can only exist on single selections (one initial value).\n const datum = nearest.defined(selCmpt) ? '(item().isVoronoi ? datum.datum : datum)' : 'datum';\n\n proj.items.forEach((p, i) => {\n const sgname = varName(`${name}_${p.field}`);\n const hasSignal = signals.filter(s => s.name === sgname);\n\n if (!hasSignal.length) {\n signals.unshift({\n name: sgname,\n ...(init ? {init: assembleInit(init[i])} : {value: null}),\n on: selCmpt.events\n ? [\n {\n events: selCmpt.events,\n update: `datum && item().mark.marktype !== 'group' ? ${datum}[${stringValue(p.field)}] : null`\n }\n ]\n : [],\n bind: bind[p.field] ?? bind[p.channel] ?? bind\n });\n }\n });\n\n return signals;\n },\n\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const proj = selCmpt.project;\n const signal: NewSignal = signals.filter(s => s.name === name + TUPLE)[0];\n const fields = name + TUPLE_FIELDS;\n const values = proj.items.map(p => varName(`${name}_${p.field}`));\n const valid = values.map(v => `${v} !== null`).join(' && ');\n\n if (values.length) {\n signal.update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;\n }\n\n delete signal.value;\n delete signal.on;\n\n return signals;\n }\n};\n\nexport default inputBindings;\n","import {TUPLE, unitName} from '.';\nimport {SelectionCompiler} from '.';\n\nexport const TOGGLE = '_toggle';\n\nconst toggle: SelectionCompiler<'point'> = {\n defined: selCmpt => {\n return selCmpt.type === 'point' && !!selCmpt.toggle;\n },\n\n signals: (model, selCmpt, signals) => {\n return signals.concat({\n name: selCmpt.name + TOGGLE,\n value: false,\n on: [{events: selCmpt.events, update: selCmpt.toggle}]\n });\n },\n\n modifyExpr: (model, selCmpt) => {\n const tpl = selCmpt.name + TUPLE;\n const signal = selCmpt.name + TOGGLE;\n\n return (\n `${signal} ? null : ${tpl}, ` +\n (selCmpt.resolve === 'global' ? `${signal} ? null : true, ` : `${signal} ? null : {unit: ${unitName(model)}}, `) +\n `${signal} ? ${tpl} : null`\n );\n }\n};\n\nexport default toggle;\n","import {Update} from 'vega';\nimport {parseSelector} from 'vega-event-selector';\nimport {isString} from 'vega-util';\nimport {TUPLE} from '.';\nimport {varName} from '../../util';\nimport inputBindings from './inputs';\nimport toggle, {TOGGLE} from './toggle';\nimport {SelectionCompiler} from '.';\n\nconst clear: SelectionCompiler = {\n defined: selCmpt => {\n return selCmpt.clear !== undefined && selCmpt.clear !== false;\n },\n\n parse: (model, selCmpt) => {\n if (selCmpt.clear) {\n selCmpt.clear = isString(selCmpt.clear) ? parseSelector(selCmpt.clear, 'view') : selCmpt.clear;\n }\n },\n\n topLevelSignals: (model, selCmpt, signals) => {\n if (inputBindings.defined(selCmpt)) {\n for (const proj of selCmpt.project.items) {\n const idx = signals.findIndex(n => n.name === varName(`${selCmpt.name}_${proj.field}`));\n if (idx !== -1) {\n signals[idx].on.push({events: selCmpt.clear, update: 'null'});\n }\n }\n }\n\n return signals;\n },\n\n signals: (model, selCmpt, signals) => {\n function addClear(idx: number, update: Update) {\n if (idx !== -1 && signals[idx].on) {\n signals[idx].on.push({events: selCmpt.clear, update});\n }\n }\n\n // Be as minimalist as possible when adding clear triggers to minimize dataflow execution.\n if (selCmpt.type === 'interval') {\n for (const proj of selCmpt.project.items) {\n const vIdx = signals.findIndex(n => n.name === proj.signals.visual);\n addClear(vIdx, '[0, 0]');\n\n if (vIdx === -1) {\n const dIdx = signals.findIndex(n => n.name === proj.signals.data);\n addClear(dIdx, 'null');\n }\n }\n } else {\n let tIdx = signals.findIndex(n => n.name === selCmpt.name + TUPLE);\n addClear(tIdx, 'null');\n\n if (toggle.defined(selCmpt)) {\n tIdx = signals.findIndex(n => n.name === selCmpt.name + TOGGLE);\n addClear(tIdx, 'false');\n }\n }\n\n return signals;\n }\n};\n\nexport default clear;\n","import {isObject, MergedStream, NewSignal, Stream} from 'vega';\nimport {parseSelector} from 'vega-event-selector';\nimport {array, isString} from 'vega-util';\nimport {disableDirectManipulation, TUPLE} from '.';\nimport {NonPositionScaleChannel} from '../../channel';\nimport * as log from '../../log';\nimport {isLegendBinding, isLegendStreamBinding, SELECTION_ID} from '../../selection';\nimport {duplicate, vals, varName} from '../../util';\nimport {LegendComponent} from '../legend/component';\nimport {UnitModel} from '../unit';\nimport {TUPLE_FIELDS} from './project';\nimport {TOGGLE} from './toggle';\nimport {SelectionCompiler} from '.';\n\nconst legendBindings: SelectionCompiler<'point'> = {\n defined: selCmpt => {\n const spec = selCmpt.resolve === 'global' && selCmpt.bind && isLegendBinding(selCmpt.bind);\n const projLen = selCmpt.project.items.length === 1 && selCmpt.project.items[0].field !== SELECTION_ID;\n if (spec && !projLen) {\n log.warn(log.message.LEGEND_BINDINGS_MUST_HAVE_PROJECTION);\n }\n\n return spec && projLen;\n },\n\n parse: (model, selCmpt, selDef) => {\n // Allow legend items to be toggleable by default even though direct manipulation is disabled.\n const selDef_ = duplicate(selDef);\n selDef_.select = isString(selDef_.select)\n ? {type: selDef_.select, toggle: selCmpt.toggle}\n : {...selDef_.select, toggle: selCmpt.toggle};\n disableDirectManipulation(selCmpt, selDef_);\n\n if (isObject(selDef.select) && (selDef.select.on || selDef.select.clear)) {\n const legendFilter = 'event.item && indexof(event.item.mark.role, \"legend\") < 0';\n for (const evt of selCmpt.events) {\n evt.filter = array(evt.filter ?? []);\n if (!evt.filter.includes(legendFilter)) {\n evt.filter.push(legendFilter);\n }\n }\n }\n\n const evt = isLegendStreamBinding(selCmpt.bind) ? selCmpt.bind.legend : 'click';\n const stream: Stream[] = isString(evt) ? parseSelector(evt, 'view') : array(evt);\n selCmpt.bind = {legend: {merge: stream}};\n },\n\n topLevelSignals: (model, selCmpt, signals) => {\n const selName = selCmpt.name;\n const stream = isLegendStreamBinding(selCmpt.bind) && (selCmpt.bind.legend as MergedStream);\n const markName = (name: string) => (s: Stream) => {\n const ds = duplicate(s);\n ds.markname = name;\n return ds;\n };\n\n for (const proj of selCmpt.project.items) {\n if (!proj.hasLegend) continue;\n const prefix = `${varName(proj.field)}_legend`;\n const sgName = `${selName}_${prefix}`;\n const hasSignal = signals.filter(s => s.name === sgName);\n\n if (hasSignal.length === 0) {\n const events = stream.merge\n .map(markName(`${prefix}_symbols`))\n .concat(stream.merge.map(markName(`${prefix}_labels`)))\n .concat(stream.merge.map(markName(`${prefix}_entries`)));\n\n signals.unshift({\n name: sgName,\n ...(!selCmpt.init ? {value: null} : {}),\n on: [\n // Legend entries do not store values, so we need to walk the scenegraph to the symbol datum.\n {\n events,\n update: 'isDefined(datum.value) ? datum.value : item().items[0].items[0].datum.value',\n force: true\n },\n {events: stream.merge, update: `!event.item || !datum ? null : ${sgName}`, force: true}\n ]\n });\n }\n }\n\n return signals;\n },\n\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const proj = selCmpt.project;\n const tuple: NewSignal = signals.find(s => s.name === name + TUPLE);\n const fields = name + TUPLE_FIELDS;\n const values = proj.items.filter(p => p.hasLegend).map(p => varName(`${name}_${varName(p.field)}_legend`));\n const valid = values.map(v => `${v} !== null`).join(' && ');\n const update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;\n\n if (selCmpt.events && values.length > 0) {\n tuple.on.push({\n events: values.map(signal => ({signal})),\n update\n });\n } else if (values.length > 0) {\n tuple.update = update;\n delete tuple.value;\n delete tuple.on;\n }\n\n const toggle = signals.find(s => s.name === name + TOGGLE);\n const events = isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;\n if (toggle) {\n if (!selCmpt.events) toggle.on[0].events = events;\n else toggle.on.push({...toggle.on[0], events});\n }\n\n return signals;\n }\n};\n\nexport default legendBindings;\n\nexport function parseInteractiveLegend(\n model: UnitModel,\n channel: NonPositionScaleChannel,\n legendCmpt: LegendComponent\n) {\n const field = model.fieldDef(channel)?.field;\n for (const selCmpt of vals(model.component.selection ?? {})) {\n const proj = selCmpt.project.hasField[field] ?? selCmpt.project.hasChannel[channel];\n if (proj && legendBindings.defined(selCmpt)) {\n const legendSelections = legendCmpt.get('selections') ?? [];\n legendSelections.push(selCmpt.name);\n legendCmpt.set('selections', legendSelections, false);\n proj.hasLegend = true;\n }\n }\n}\n","import {NewSignal} from 'vega';\nimport {parseSelector} from 'vega-event-selector';\nimport {SelectionComponent} from '.';\nimport {ScaleChannel, X, Y} from '../../channel';\nimport {UnitModel} from '../unit';\nimport {BRUSH as INTERVAL_BRUSH} from './interval';\nimport {SelectionProjection} from './project';\nimport scalesCompiler, {domain} from './scales';\nimport {SelectionCompiler} from '.';\n\nconst ANCHOR = '_translate_anchor';\nconst DELTA = '_translate_delta';\n\nconst translate: SelectionCompiler<'interval'> = {\n defined: selCmpt => {\n return selCmpt.type === 'interval' && selCmpt.translate;\n },\n\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const boundScales = scalesCompiler.defined(selCmpt);\n const anchor = name + ANCHOR;\n const {x, y} = selCmpt.project.hasChannel;\n let events = parseSelector(selCmpt.translate, 'scope');\n\n if (!boundScales) {\n events = events.map(e => ((e.between[0].markname = name + INTERVAL_BRUSH), e));\n }\n\n signals.push(\n {\n name: anchor,\n value: {},\n on: [\n {\n events: events.map(e => e.between[0]),\n update:\n '{x: x(unit), y: y(unit)' +\n (x !== undefined ? `, extent_x: ${boundScales ? domain(model, X) : `slice(${x.signals.visual})`}` : '') +\n (y !== undefined ? `, extent_y: ${boundScales ? domain(model, Y) : `slice(${y.signals.visual})`}` : '') +\n '}'\n }\n ]\n },\n {\n name: name + DELTA,\n value: {},\n on: [\n {\n events,\n update: `{x: ${anchor}.x - x(unit), y: ${anchor}.y - y(unit)}`\n }\n ]\n }\n );\n\n if (x !== undefined) {\n onDelta(model, selCmpt, x, 'width', signals);\n }\n\n if (y !== undefined) {\n onDelta(model, selCmpt, y, 'height', signals);\n }\n\n return signals;\n }\n};\n\nexport default translate;\n\nfunction onDelta(\n model: UnitModel,\n selCmpt: SelectionComponent,\n proj: SelectionProjection,\n size: 'width' | 'height',\n signals: NewSignal[]\n) {\n const name = selCmpt.name;\n const anchor = name + ANCHOR;\n const delta = name + DELTA;\n const channel = proj.channel as ScaleChannel;\n const boundScales = scalesCompiler.defined(selCmpt);\n const signal = signals.filter(s => s.name === proj.signals[boundScales ? 'data' : 'visual'])[0];\n const sizeSg = model.getSizeSignalRef(size).signal;\n const scaleCmpt = model.getScaleComponent(channel);\n const scaleType = scaleCmpt && scaleCmpt.get('type');\n const reversed = scaleCmpt && scaleCmpt.get('reverse'); // scale parsing sets this flag for fieldDef.sort\n const sign = !boundScales ? '' : channel === X ? (reversed ? '' : '-') : reversed ? '-' : '';\n const extent = `${anchor}.extent_${channel}`;\n const offset = `${sign}${delta}.${channel} / ${boundScales ? `${sizeSg}` : `span(${extent})`}`;\n const panFn =\n !boundScales || !scaleCmpt\n ? 'panLinear'\n : scaleType === 'log'\n ? 'panLog'\n : scaleType === 'symlog'\n ? 'panSymlog'\n : scaleType === 'pow'\n ? 'panPow'\n : 'panLinear';\n const arg = !boundScales\n ? ''\n : scaleType === 'pow'\n ? `, ${scaleCmpt.get('exponent') ?? 1}`\n : scaleType === 'symlog'\n ? `, ${scaleCmpt.get('constant') ?? 1}`\n : '';\n const update = `${panFn}(${extent}, ${offset}${arg})`;\n\n signal.on.push({\n events: {signal: delta},\n update: boundScales ? update : `clampRange(${update}, 0, ${sizeSg})`\n });\n}\n","import {NewSignal} from 'vega';\nimport {parseSelector} from 'vega-event-selector';\nimport {stringValue} from 'vega-util';\nimport {SelectionComponent} from '.';\nimport {ScaleChannel, X, Y} from '../../channel';\nimport {UnitModel} from '../unit';\nimport {BRUSH as INTERVAL_BRUSH} from './interval';\nimport {SelectionProjection} from './project';\nimport {default as scalesCompiler, domain} from './scales';\nimport {SelectionCompiler} from '.';\n\nconst ANCHOR = '_zoom_anchor';\nconst DELTA = '_zoom_delta';\n\nconst zoom: SelectionCompiler<'interval'> = {\n defined: selCmpt => {\n return selCmpt.type === 'interval' && selCmpt.zoom;\n },\n\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const boundScales = scalesCompiler.defined(selCmpt);\n const delta = name + DELTA;\n const {x, y} = selCmpt.project.hasChannel;\n const sx = stringValue(model.scaleName(X));\n const sy = stringValue(model.scaleName(Y));\n let events = parseSelector(selCmpt.zoom, 'scope');\n\n if (!boundScales) {\n events = events.map(e => ((e.markname = name + INTERVAL_BRUSH), e));\n }\n\n signals.push(\n {\n name: name + ANCHOR,\n on: [\n {\n events,\n update: !boundScales\n ? `{x: x(unit), y: y(unit)}`\n : '{' +\n [sx ? `x: invert(${sx}, x(unit))` : '', sy ? `y: invert(${sy}, y(unit))` : '']\n .filter(expr => expr)\n .join(', ') +\n '}'\n }\n ]\n },\n {\n name: delta,\n on: [\n {\n events,\n force: true,\n update: 'pow(1.001, event.deltaY * pow(16, event.deltaMode))'\n }\n ]\n }\n );\n\n if (x !== undefined) {\n onDelta(model, selCmpt, x, 'width', signals);\n }\n\n if (y !== undefined) {\n onDelta(model, selCmpt, y, 'height', signals);\n }\n\n return signals;\n }\n};\n\nexport default zoom;\n\nfunction onDelta(\n model: UnitModel,\n selCmpt: SelectionComponent,\n proj: SelectionProjection,\n size: 'width' | 'height',\n signals: NewSignal[]\n) {\n const name = selCmpt.name;\n const channel = proj.channel as ScaleChannel;\n const boundScales = scalesCompiler.defined(selCmpt);\n const signal = signals.filter(s => s.name === proj.signals[boundScales ? 'data' : 'visual'])[0];\n const sizeSg = model.getSizeSignalRef(size).signal;\n const scaleCmpt = model.getScaleComponent(channel);\n const scaleType = scaleCmpt && scaleCmpt.get('type');\n const base = boundScales ? domain(model, channel) : signal.name;\n const delta = name + DELTA;\n const anchor = `${name}${ANCHOR}.${channel}`;\n const zoomFn =\n !boundScales || !scaleCmpt\n ? 'zoomLinear'\n : scaleType === 'log'\n ? 'zoomLog'\n : scaleType === 'symlog'\n ? 'zoomSymlog'\n : scaleType === 'pow'\n ? 'zoomPow'\n : 'zoomLinear';\n const arg = !boundScales\n ? ''\n : scaleType === 'pow'\n ? `, ${scaleCmpt.get('exponent') ?? 1}`\n : scaleType === 'symlog'\n ? `, ${scaleCmpt.get('constant') ?? 1}`\n : '';\n const update = `${zoomFn}(${base}, ${anchor}, ${delta}${arg})`;\n\n signal.on.push({\n events: {signal: delta},\n update: boundScales ? update : `clampRange(${update}, 0, ${sizeSg})`\n });\n}\n","import {Binding, isString, Signal, Stream} from 'vega';\nimport {stringValue} from 'vega-util';\nimport {FACET_CHANNELS} from '../../channel';\nimport {\n BrushConfig,\n LegendBinding,\n SelectionInit,\n SelectionInitInterval,\n SelectionResolution,\n SelectionType\n} from '../../selection';\nimport {Dict, vals} from '../../util';\nimport {OutputNode} from '../data/dataflow';\nimport {FacetModel} from '../facet';\nimport {isFacetModel, Model} from '../model';\nimport {UnitModel} from '../unit';\nimport interval from './interval';\nimport point from './point';\nimport {SelectionProjection, SelectionProjectionComponent} from './project';\nimport {SelectionParameter} from '../../selection';\nimport clear from './clear';\nimport inputs from './inputs';\nimport nearest from './nearest';\nimport project from './project';\nimport scales from './scales';\nimport legends from './legends';\nimport toggle from './toggle';\nimport translate from './translate';\nimport zoom from './zoom';\nimport {ParameterName} from '../../parameter';\n\nexport const STORE = '_store';\nexport const TUPLE = '_tuple';\nexport const MODIFY = '_modify';\nexport const SELECTION_DOMAIN = '_selection_domain_';\nexport const VL_SELECTION_RESOLVE = 'vlSelectionResolve';\n\nexport interface SelectionComponent {\n name: ParameterName;\n type: T;\n // Use conditional types for stricter type of init (as the type of init depends on selection type).\n init?: (T extends 'interval' ? SelectionInitInterval : T extends 'point' ? SelectionInit : never)[][];\n events: Stream[];\n materialized: OutputNode;\n bind?: 'scales' | Binding | Dict | LegendBinding;\n resolve: SelectionResolution;\n mark?: BrushConfig;\n project: SelectionProjectionComponent;\n scales?: SelectionProjection[];\n toggle?: string;\n translate?: any;\n zoom?: any;\n nearest?: any;\n clear?: any;\n}\n\nexport interface SelectionCompiler {\n defined: (selCmpt: SelectionComponent) => boolean;\n parse?: (model: UnitModel, selCmpt: SelectionComponent, def: SelectionParameter) => void;\n signals?: (model: UnitModel, selCmpt: SelectionComponent, signals: Signal[]) => Signal[];\n topLevelSignals?: (model: Model, selCmpt: SelectionComponent, signals: Signal[]) => Signal[];\n modifyExpr?: (model: UnitModel, selCmpt: SelectionComponent, expr: string) => string;\n marks?: (model: UnitModel, selCmpt: SelectionComponent, marks: any[]) => any[];\n}\n\n// Order matters for parsing and assembly.\nexport const selectionCompilers: SelectionCompiler[] = [\n point,\n interval,\n project,\n toggle,\n\n // Bindings may disable direct manipulation.\n inputs,\n scales,\n legends,\n\n clear,\n translate,\n zoom,\n nearest\n];\n\nfunction getFacetModel(model: Model): FacetModel {\n let parent = model.parent;\n while (parent) {\n if (isFacetModel(parent)) break;\n parent = parent.parent;\n }\n\n return parent as FacetModel;\n}\n\nexport function unitName(model: Model, {escape} = {escape: true}) {\n let name = escape ? stringValue(model.name) : model.name;\n const facetModel = getFacetModel(model);\n if (facetModel) {\n const {facet} = facetModel;\n for (const channel of FACET_CHANNELS) {\n if (facet[channel]) {\n name += ` + '__facet_${channel}_' + (facet[${stringValue(facetModel.vgField(channel))}])`;\n }\n }\n }\n return name;\n}\n\nexport function requiresSelectionId(model: Model) {\n return vals(model.component.selection ?? {}).reduce((identifier, selCmpt) => {\n return identifier || selCmpt.project.hasSelectionId;\n }, false);\n}\n\n// Binding a point selection to query widgets or legends disables default direct manipulation interaction.\n// A user can choose to re-enable it by explicitly specifying triggering input events.\nexport function disableDirectManipulation(selCmpt: SelectionComponent, selDef: SelectionParameter<'point'>) {\n if (isString(selDef.select) || !selDef.select.on) delete selCmpt.events;\n if (isString(selDef.select) || !selDef.select.clear) delete selCmpt.clear;\n if (isString(selDef.select) || !selDef.select.toggle) delete selCmpt.toggle;\n}\n","import {parseExpression} from 'vega-expression';\n\nfunction getName(node: any) {\n const name: string[] = [];\n\n if (node.type === 'Identifier') {\n return [node.name];\n }\n\n if (node.type === 'Literal') {\n return [node.value];\n }\n\n if (node.type === 'MemberExpression') {\n name.push(...getName(node.object));\n name.push(...getName(node.property));\n }\n\n return name;\n}\n\nfunction startsWithDatum(node: any): boolean {\n if (node.object.type === 'MemberExpression') {\n return startsWithDatum(node.object);\n }\n return node.object.name === 'datum';\n}\n\nexport function getDependentFields(expression: string) {\n const ast = parseExpression(expression);\n const dependents = new Set();\n // visit is missing in types https://github.com/vega/vega/issues/3298\n (ast as any).visit((node: any) => {\n if (node.type === 'MemberExpression' && startsWithDatum(node)) {\n dependents.add(getName(node).slice(1).join('.'));\n }\n });\n\n return dependents;\n}\n","import {FilterTransform as VgFilterTransform} from 'vega';\nimport {LogicalComposition} from '../../logical';\nimport {Predicate} from '../../predicate';\nimport {duplicate} from '../../util';\nimport {Model} from '../model';\nimport {expression} from '../predicate';\nimport {DataFlowNode} from './dataflow';\nimport {getDependentFields} from './expressions';\n\nexport class FilterNode extends DataFlowNode {\n private expr: string;\n private _dependentFields: Set;\n public clone() {\n return new FilterNode(null, this.model, duplicate(this.filter));\n }\n\n constructor(\n parent: DataFlowNode,\n private readonly model: Model,\n private readonly filter: LogicalComposition\n ) {\n super(parent);\n\n // TODO: refactor this to not take a node and\n // then add a static function makeFromOperand and make the constructor take only an expression\n this.expr = expression(this.model, this.filter, this);\n\n this._dependentFields = getDependentFields(this.expr);\n }\n\n public dependentFields() {\n return this._dependentFields;\n }\n\n public producedFields() {\n return new Set(); // filter does not produce any new fields\n }\n\n public assemble(): VgFilterTransform {\n return {\n type: 'filter',\n expr: this.expr\n };\n }\n\n public hash() {\n return `Filter ${this.expr}`;\n }\n}\n","import {parseSelector} from 'vega-event-selector';\nimport {array, isObject, isString, stringValue} from 'vega-util';\nimport {selectionCompilers, SelectionComponent, STORE} from '.';\nimport {warn} from '../../log';\nimport {BaseSelectionConfig, SelectionParameter, ParameterExtent} from '../../selection';\nimport {Dict, duplicate, entries, replacePathInField, varName} from '../../util';\nimport {DataFlowNode, OutputNode} from '../data/dataflow';\nimport {FilterNode} from '../data/filter';\nimport {Model} from '../model';\nimport {UnitModel} from '../unit';\nimport {DataSourceType} from '../../data';\nimport {ParameterPredicate} from '../../predicate';\n\nexport function parseUnitSelection(model: UnitModel, selDefs: SelectionParameter[]) {\n const selCmpts: Dict> = {};\n const selectionConfig = model.config.selection;\n\n if (!selDefs || !selDefs.length) return selCmpts;\n\n for (const def of selDefs) {\n const name = varName(def.name);\n const selDef = def.select;\n const type = isString(selDef) ? selDef : selDef.type;\n const defaults: BaseSelectionConfig = isObject(selDef) ? duplicate(selDef) : {type};\n\n // Set default values from config if a property hasn't been specified,\n // or if it is true. E.g., \"translate\": true should use the default\n // event handlers for translate. However, true may be a valid value for\n // a property (e.g., \"nearest\": true).\n const cfg = selectionConfig[type];\n for (const key in cfg) {\n // Project transform applies its defaults.\n if (key === 'fields' || key === 'encodings') {\n continue;\n }\n\n if (key === 'mark') {\n defaults[key] = {...cfg[key], ...defaults[key]};\n }\n\n if (defaults[key] === undefined || defaults[key] === true) {\n defaults[key] = duplicate(cfg[key] ?? defaults[key]);\n }\n }\n\n const selCmpt: SelectionComponent = (selCmpts[name] = {\n ...defaults,\n name,\n type,\n init: def.value,\n bind: def.bind,\n events: isString(defaults.on) ? parseSelector(defaults.on, 'scope') : array(duplicate(defaults.on))\n } as any);\n\n const def_ = duplicate(def); // defensive copy to prevent compilers from causing side effects\n for (const c of selectionCompilers) {\n if (c.defined(selCmpt) && c.parse) {\n c.parse(model, selCmpt, def_);\n }\n }\n }\n\n return selCmpts;\n}\n\nexport function parseSelectionPredicate(\n model: Model,\n pred: ParameterPredicate,\n dfnode?: DataFlowNode,\n datum = 'datum'\n): string {\n const name = isString(pred) ? pred : pred.param;\n const vname = varName(name);\n const store = stringValue(vname + STORE);\n let selCmpt;\n\n try {\n selCmpt = model.getSelectionComponent(vname, name);\n } catch (e) {\n // If a selection isn't found, treat as a variable parameter and coerce to boolean.\n return `!!${vname}`;\n }\n\n if (selCmpt.project.timeUnit) {\n const child = dfnode ?? model.component.data.raw;\n const tunode = selCmpt.project.timeUnit.clone();\n if (child.parent) {\n tunode.insertAsParentOf(child);\n } else {\n child.parent = tunode;\n }\n }\n\n const fn = selCmpt.project.hasSelectionId ? 'vlSelectionIdTest(' : 'vlSelectionTest(';\n const resolve = selCmpt.resolve === 'global' ? ')' : `, ${stringValue(selCmpt.resolve)})`;\n const test = `${fn}${store}, ${datum}${resolve}`;\n const length = `length(data(${store}))`;\n\n return pred.empty === false ? `${length} && ${test}` : `!${length} || ${test}`;\n}\n\nexport function parseSelectionExtent(model: Model, name: string, extent: ParameterExtent) {\n const vname = varName(name);\n const encoding = extent['encoding'];\n let field = extent['field'];\n let selCmpt;\n\n try {\n selCmpt = model.getSelectionComponent(vname, name);\n } catch (e) {\n // If a selection isn't found, treat it as a variable parameter.\n return vname;\n }\n\n if (!encoding && !field) {\n field = selCmpt.project.items[0].field;\n if (selCmpt.project.items.length > 1) {\n warn(\n 'A \"field\" or \"encoding\" must be specified when using a selection as a scale domain. ' +\n `Using \"field\": ${stringValue(field)}.`\n );\n }\n } else if (encoding && !field) {\n const encodings = selCmpt.project.items.filter(p => p.channel === encoding);\n if (!encodings.length || encodings.length > 1) {\n field = selCmpt.project.items[0].field;\n warn(\n (!encodings.length ? 'No ' : 'Multiple ') +\n `matching ${stringValue(encoding)} encoding found for selection ${stringValue(extent.param)}. ` +\n `Using \"field\": ${stringValue(field)}.`\n );\n } else {\n field = encodings[0].field;\n }\n }\n\n return `${selCmpt.name}[${stringValue(replacePathInField(field))}]`;\n}\n\nexport function materializeSelections(model: UnitModel, main: OutputNode) {\n for (const [selection, selCmpt] of entries(model.component.selection ?? {})) {\n const lookupName = model.getName(`lookup_${selection}`);\n model.component.data.outputNodes[lookupName] = selCmpt.materialized = new OutputNode(\n new FilterNode(main, model, {param: selection}),\n lookupName,\n DataSourceType.Lookup,\n model.component.data.outputNodeRefCounts\n );\n }\n}\n","import {isString} from 'vega-util';\nimport {LogicalComposition} from '../logical';\nimport {fieldFilterExpression, isSelectionPredicate, Predicate} from '../predicate';\nimport {logicalExpr} from '../util';\nimport {DataFlowNode} from './data/dataflow';\nimport {Model} from './model';\nimport {parseSelectionPredicate} from './selection/parse';\n\n/**\n * Converts a predicate into an expression.\n */\n// model is only used for selection filters.\nexport function expression(model: Model, filterOp: LogicalComposition, node?: DataFlowNode): string {\n return logicalExpr(filterOp, (predicate: Predicate) => {\n if (isString(predicate)) {\n return predicate;\n } else if (isSelectionPredicate(predicate)) {\n return parseSelectionPredicate(model, predicate, node);\n } else {\n // Filter Object\n return fieldFilterExpression(predicate);\n }\n });\n}\n","import {Axis as VgAxis, AxisEncode, NewSignal, SignalRef, Text} from 'vega';\nimport {array, isArray} from 'vega-util';\nimport {AXIS_PARTS, AXIS_PROPERTY_TYPE, CONDITIONAL_AXIS_PROP_INDEX, isConditionalAxisValue} from '../../axis';\nimport {POSITION_SCALE_CHANNELS} from '../../channel';\nimport {defaultTitle, FieldDefBase} from '../../channeldef';\nimport {Config} from '../../config';\nimport {isText} from '../../title';\nimport {contains, getFirstDefined, isEmpty, replaceAll} from '../../util';\nimport {isSignalRef, VgEncodeChannel, VgValueRef} from '../../vega.schema';\nimport {exprFromValueRefOrSignalRef} from '../common';\nimport {Model} from '../model';\nimport {expression} from '../predicate';\nimport {AxisComponent, AxisComponentIndex} from './component';\n\nfunction assembleTitle(title: Text | FieldDefBase[] | SignalRef, config: Config): Text | SignalRef {\n if (!title) {\n return undefined;\n }\n if (isArray(title) && !isText(title)) {\n return title.map(fieldDef => defaultTitle(fieldDef, config)).join(', ');\n }\n return title;\n}\n\nfunction setAxisEncode(\n axis: Omit,\n part: keyof AxisEncode,\n vgProp: VgEncodeChannel,\n vgRef: VgValueRef | readonly VgValueRef[]\n) {\n axis.encode ??= {};\n axis.encode[part] ??= {};\n axis.encode[part].update ??= {};\n // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291\n (axis.encode[part].update[vgProp] as any) = vgRef;\n}\n\nexport function assembleAxis(\n axisCmpt: AxisComponent,\n kind: 'main' | 'grid',\n config: Config,\n opt: {\n header: boolean; // whether this is called via a header\n } = {header: false}\n): VgAxis {\n const {disable, orient, scale, labelExpr, title, zindex, ...axis} = axisCmpt.combine();\n\n if (disable) {\n return undefined;\n }\n\n for (const prop in axis) {\n const propType = AXIS_PROPERTY_TYPE[prop];\n const propValue = axis[prop];\n\n if (propType && propType !== kind && propType !== 'both') {\n // Remove properties that are not valid for this kind of axis\n delete axis[prop];\n } else if (isConditionalAxisValue(propValue)) {\n // deal with conditional axis value\n\n const {condition, ...valueOrSignalRef} = propValue;\n const conditions = array(condition);\n\n const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];\n if (propIndex) {\n const {vgProp, part} = propIndex;\n // If there is a corresponding Vega property for the channel,\n // use Vega's custom axis encoding and delete the original axis property to avoid conflicts\n\n const vgRef = [\n ...conditions.map(c => {\n const {test, ...valueOrSignalCRef} = c;\n return {\n test: expression(null, test),\n ...valueOrSignalCRef\n };\n }),\n valueOrSignalRef\n ];\n setAxisEncode(axis, part, vgProp, vgRef);\n delete axis[prop];\n } else if (propIndex === null) {\n // If propIndex is null, this means we support conditional axis property by converting the condition to signal instead.\n const signalRef: SignalRef = {\n signal:\n conditions\n .map(c => {\n const {test, ...valueOrSignalCRef} = c;\n return `${expression(null, test)} ? ${exprFromValueRefOrSignalRef(valueOrSignalCRef)} : `;\n })\n .join('') + exprFromValueRefOrSignalRef(valueOrSignalRef)\n };\n axis[prop] = signalRef;\n }\n } else if (isSignalRef(propValue)) {\n const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];\n if (propIndex) {\n const {vgProp, part} = propIndex;\n setAxisEncode(axis, part, vgProp, propValue);\n delete axis[prop];\n } // else do nothing since the property already supports signal\n }\n\n // Do not pass labelAlign/Baseline = null to Vega since it won't pass the schema\n // Note that we need to use null so the default labelAlign is preserved.\n if (contains(['labelAlign', 'labelBaseline'], prop) && axis[prop] === null) {\n delete axis[prop];\n }\n }\n\n if (kind === 'grid') {\n if (!axis.grid) {\n return undefined;\n }\n\n // Remove unnecessary encode block\n if (axis.encode) {\n // Only need to keep encode block for grid\n const {grid} = axis.encode;\n axis.encode = {\n ...(grid ? {grid} : {})\n };\n\n if (isEmpty(axis.encode)) {\n delete axis.encode;\n }\n }\n\n return {\n scale,\n orient,\n ...axis,\n domain: false,\n labels: false,\n aria: false, // always hide grid axis\n\n // Always set min/maxExtent to 0 to ensure that `config.axis*.minExtent` and `config.axis*.maxExtent`\n // would not affect gridAxis\n maxExtent: 0,\n minExtent: 0,\n ticks: false,\n zindex: getFirstDefined(zindex, 0) // put grid behind marks by default\n };\n } else {\n // kind === 'main'\n\n if (!opt.header && axisCmpt.mainExtracted) {\n // if mainExtracted has been extracted to a separate facet\n return undefined;\n }\n\n if (labelExpr !== undefined) {\n let expr = labelExpr;\n if (axis.encode?.labels?.update && isSignalRef(axis.encode.labels.update.text)) {\n expr = replaceAll(labelExpr, 'datum.label', axis.encode.labels.update.text.signal);\n }\n setAxisEncode(axis, 'labels', 'text', {signal: expr});\n }\n\n if (axis.labelAlign === null) {\n delete axis.labelAlign;\n }\n\n // Remove unnecessary encode block\n if (axis.encode) {\n for (const part of AXIS_PARTS) {\n if (!axisCmpt.hasAxisPart(part)) {\n delete axis.encode[part];\n }\n }\n if (isEmpty(axis.encode)) {\n delete axis.encode;\n }\n }\n\n const titleString = assembleTitle(title, config);\n\n return {\n scale,\n orient,\n grid: false,\n ...(titleString ? {title: titleString} : {}),\n ...axis,\n ...(config.aria === false ? {aria: false} : {}),\n zindex: getFirstDefined(zindex, 0) // put axis line above marks by default\n };\n }\n}\n\n/**\n * Add axis signals so grid line works correctly\n * (Fix https://github.com/vega/vega-lite/issues/4226)\n */\nexport function assembleAxisSignals(model: Model): NewSignal[] {\n const {axes} = model.component;\n const signals: NewSignal[] = [];\n\n for (const channel of POSITION_SCALE_CHANNELS) {\n if (axes[channel]) {\n for (const axis of axes[channel]) {\n if (!axis.get('disable') && !axis.get('gridScale')) {\n // If there is x-axis but no y-scale for gridScale, need to set height/width so x-axis can draw the grid with the right height. Same for y-axis and width.\n\n const sizeType = channel === 'x' ? 'height' : 'width';\n const update = model.getSizeSignalRef(sizeType).signal;\n\n if (sizeType !== update) {\n signals.push({\n name: sizeType,\n update\n });\n }\n }\n }\n }\n }\n return signals;\n}\n\nexport function assembleAxes(axisComponents: AxisComponentIndex, config: Config): VgAxis[] {\n const {x = [], y = []} = axisComponents;\n return [\n ...x.map(a => assembleAxis(a, 'grid', config)),\n ...y.map(a => assembleAxis(a, 'grid', config)),\n ...x.map(a => assembleAxis(a, 'main', config)),\n ...y.map(a => assembleAxis(a, 'main', config))\n ].filter(a => a); // filter undefined\n}\n","import {ScaleType, SignalRef} from 'vega';\nimport {array} from 'vega-util';\nimport {AxisConfig} from '../../axis';\nimport {PositionScaleChannel} from '../../channel';\nimport {Config, StyleConfigIndex} from '../../config';\nimport {isQuantitative} from '../../scale';\nimport {keys, titleCase} from '../../util';\nimport {isSignalRef} from '../../vega.schema';\nimport {getStyleConfig, signalOrStringValue} from '../common';\n\nfunction getAxisConfigFromConfigTypes(\n configTypes: string[],\n config: Config,\n channel: 'x' | 'y',\n orient: string | SignalRef\n) {\n // TODO: add special casing to add conditional value based on orient signal\n return Object.assign.apply(null, [\n {},\n ...configTypes.map(configType => {\n if (configType === 'axisOrient') {\n const orient1 = channel === 'x' ? 'bottom' : 'left';\n const orientConfig1 = config[channel === 'x' ? 'axisBottom' : 'axisLeft'] || {};\n const orientConfig2 = config[channel === 'x' ? 'axisTop' : 'axisRight'] || {};\n\n const props = new Set([...keys(orientConfig1), ...keys(orientConfig2)]);\n\n const conditionalOrientAxisConfig = {};\n for (const prop of props.values()) {\n conditionalOrientAxisConfig[prop] = {\n // orient is surely signal in this case\n signal: `${orient['signal']} === \"${orient1}\" ? ${signalOrStringValue(\n orientConfig1[prop]\n )} : ${signalOrStringValue(orientConfig2[prop])}`\n };\n }\n\n return conditionalOrientAxisConfig;\n }\n\n return config[configType];\n })\n ]);\n}\n\nexport type AxisConfigs = ReturnType;\n\nexport function getAxisConfigs(\n channel: PositionScaleChannel,\n scaleType: ScaleType,\n orient: string | SignalRef,\n config: Config\n) {\n const typeBasedConfigTypes =\n scaleType === 'band'\n ? ['axisDiscrete', 'axisBand']\n : scaleType === 'point'\n ? ['axisDiscrete', 'axisPoint']\n : isQuantitative(scaleType)\n ? ['axisQuantitative']\n : scaleType === 'time' || scaleType === 'utc'\n ? ['axisTemporal']\n : [];\n\n const axisChannel = channel === 'x' ? 'axisX' : 'axisY';\n const axisOrient = isSignalRef(orient) ? 'axisOrient' : `axis${titleCase(orient)}`; // axisTop, axisBottom, ...\n\n const vlOnlyConfigTypes = [\n // technically Vega does have axisBand, but if we make another separation here,\n // it will further introduce complexity in the code\n ...typeBasedConfigTypes,\n ...typeBasedConfigTypes.map(c => axisChannel + c.substr(4))\n ];\n\n const vgConfigTypes = ['axis', axisOrient, axisChannel];\n\n return {\n vlOnlyAxisConfig: getAxisConfigFromConfigTypes(vlOnlyConfigTypes, config, channel, orient),\n vgAxisConfig: getAxisConfigFromConfigTypes(vgConfigTypes, config, channel, orient),\n axisConfigStyle: getAxisConfigStyle([...vgConfigTypes, ...vlOnlyConfigTypes], config)\n };\n}\n\nexport function getAxisConfigStyle(axisConfigTypes: string[], config: Config) {\n const toMerge = [{}];\n for (const configType of axisConfigTypes) {\n // TODO: add special casing to add conditional value based on orient signal\n let style = config[configType]?.style;\n if (style) {\n style = array(style);\n for (const s of style) {\n toMerge.push(config.style[s]);\n }\n }\n }\n return Object.assign.apply(null, toMerge);\n}\nexport function getAxisConfig(\n property: keyof AxisConfig,\n styleConfigIndex: StyleConfigIndex,\n style: string | string[],\n axisConfigs: Partial = {}\n): {configFrom?: string; configValue?: any} {\n const styleConfig = getStyleConfig(property, style, styleConfigIndex);\n\n if (styleConfig !== undefined) {\n return {\n configFrom: 'style',\n configValue: styleConfig\n };\n }\n\n for (const configFrom of ['vlOnlyAxisConfig', 'vgAxisConfig', 'axisConfigStyle']) {\n if (axisConfigs[configFrom]?.[property] !== undefined) {\n return {configFrom, configValue: axisConfigs[configFrom][property]};\n }\n }\n return {};\n}\n","import {Align, AxisOrient, Orient, SignalRef} from 'vega';\nimport {isArray, isObject} from 'vega-util';\nimport {AxisInternal} from '../../axis';\nimport {isBinned, isBinning} from '../../bin';\nimport {PositionScaleChannel, X} from '../../channel';\nimport {\n DatumDef,\n isDiscrete,\n isFieldDef,\n PositionDatumDef,\n PositionFieldDef,\n toFieldDefBase,\n TypedFieldDef,\n valueArray\n} from '../../channeldef';\nimport {Config, StyleConfigIndex} from '../../config';\nimport {Mark} from '../../mark';\nimport {hasDiscreteDomain} from '../../scale';\nimport {Sort} from '../../sort';\nimport {durationExpr, normalizeTimeUnit} from '../../timeunit';\nimport {NOMINAL, ORDINAL, Type} from '../../type';\nimport {contains, normalizeAngle} from '../../util';\nimport {isSignalRef} from '../../vega.schema';\nimport {mergeTitle, mergeTitleFieldDefs} from '../common';\nimport {guideFormatType} from '../format';\nimport {UnitModel} from '../unit';\nimport {ScaleType} from './../../scale';\nimport {AxisComponentProps} from './component';\nimport {AxisConfigs, getAxisConfig} from './config';\n\nexport interface AxisRuleParams {\n fieldOrDatumDef: PositionFieldDef | PositionDatumDef;\n axis: AxisInternal;\n channel: PositionScaleChannel;\n model: UnitModel;\n\n mark: Mark;\n scaleType: ScaleType;\n orient: Orient | SignalRef;\n labelAngle: number | SignalRef;\n format: string | SignalRef;\n formatType: ReturnType;\n config: Config;\n}\n\nexport const axisRules: {\n [k in keyof AxisComponentProps]?: (params: AxisRuleParams) => AxisComponentProps[k];\n} = {\n scale: ({model, channel}) => model.scaleName(channel),\n\n format: ({format}) => format, // we already calculate this in parse\n\n formatType: ({formatType}) => formatType, // we already calculate this in parse\n\n grid: ({fieldOrDatumDef, axis, scaleType}) => axis.grid ?? defaultGrid(scaleType, fieldOrDatumDef),\n\n gridScale: ({model, channel}) => gridScale(model, channel),\n\n labelAlign: ({axis, labelAngle, orient, channel}) =>\n axis.labelAlign || defaultLabelAlign(labelAngle, orient, channel),\n\n labelAngle: ({labelAngle}) => labelAngle, // we already calculate this in parse\n\n labelBaseline: ({axis, labelAngle, orient, channel}) =>\n axis.labelBaseline || defaultLabelBaseline(labelAngle, orient, channel),\n\n labelFlush: ({axis, fieldOrDatumDef, channel}) => axis.labelFlush ?? defaultLabelFlush(fieldOrDatumDef.type, channel),\n\n labelOverlap: ({axis, fieldOrDatumDef, scaleType}) =>\n axis.labelOverlap ??\n defaultLabelOverlap(\n fieldOrDatumDef.type,\n scaleType,\n isFieldDef(fieldOrDatumDef) && !!fieldOrDatumDef.timeUnit,\n isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined\n ),\n\n // we already calculate orient in parse\n orient: ({orient}) => orient as AxisOrient, // Need to cast until Vega supports signal\n\n tickCount: ({channel, model, axis, fieldOrDatumDef, scaleType}) => {\n const sizeType = channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;\n const size = sizeType ? model.getSizeSignalRef(sizeType) : undefined;\n return axis.tickCount ?? defaultTickCount({fieldOrDatumDef, scaleType, size, values: axis.values});\n },\n\n tickMinStep: defaultTickMinStep,\n\n title: ({axis, model, channel}) => {\n if (axis.title !== undefined) {\n return axis.title;\n }\n const fieldDefTitle = getFieldDefTitle(model, channel);\n if (fieldDefTitle !== undefined) {\n return fieldDefTitle;\n }\n const fieldDef = model.typedFieldDef(channel);\n const channel2 = channel === 'x' ? 'x2' : 'y2';\n const fieldDef2 = model.fieldDef(channel2);\n\n // If title not specified, store base parts of fieldDef (and fieldDef2 if exists)\n return mergeTitleFieldDefs(\n fieldDef ? [toFieldDefBase(fieldDef)] : [],\n isFieldDef(fieldDef2) ? [toFieldDefBase(fieldDef2)] : []\n );\n },\n\n values: ({axis, fieldOrDatumDef}) => values(axis, fieldOrDatumDef),\n\n zindex: ({axis, fieldOrDatumDef, mark}) => axis.zindex ?? defaultZindex(mark, fieldOrDatumDef)\n};\n\n// TODO: we need to refactor this method after we take care of config refactoring\n/**\n * Default rules for whether to show a grid should be shown for a channel.\n * If `grid` is unspecified, the default value is `true` for ordinal scales that are not binned\n */\n\nexport function defaultGrid(scaleType: ScaleType, fieldDef: TypedFieldDef | DatumDef) {\n return !hasDiscreteDomain(scaleType) && isFieldDef(fieldDef) && !isBinning(fieldDef?.bin) && !isBinned(fieldDef?.bin);\n}\n\nexport function gridScale(model: UnitModel, channel: PositionScaleChannel) {\n const gridChannel: PositionScaleChannel = channel === 'x' ? 'y' : 'x';\n if (model.getScaleComponent(gridChannel)) {\n return model.scaleName(gridChannel);\n }\n return undefined;\n}\n\nexport function getLabelAngle(\n fieldOrDatumDef: PositionFieldDef | PositionDatumDef,\n axis: AxisInternal,\n channel: PositionScaleChannel,\n styleConfig: StyleConfigIndex,\n axisConfigs?: AxisConfigs\n) {\n const labelAngle = axis?.labelAngle;\n // try axis value\n if (labelAngle !== undefined) {\n return isSignalRef(labelAngle) ? labelAngle : normalizeAngle(labelAngle);\n } else {\n // try axis config value\n const {configValue: angle} = getAxisConfig('labelAngle', styleConfig, axis?.style, axisConfigs);\n if (angle !== undefined) {\n return normalizeAngle(angle);\n } else {\n // get default value\n if (\n channel === X &&\n contains([NOMINAL, ORDINAL], fieldOrDatumDef.type) &&\n !(isFieldDef(fieldOrDatumDef) && fieldOrDatumDef.timeUnit)\n ) {\n return 270;\n }\n // no default\n return undefined;\n }\n }\n}\n\nexport function normalizeAngleExpr(angle: SignalRef) {\n return `(((${angle.signal} % 360) + 360) % 360)`;\n}\n\nexport function defaultLabelBaseline(\n angle: number | SignalRef,\n orient: AxisOrient | SignalRef,\n channel: 'x' | 'y',\n alwaysIncludeMiddle?: boolean\n) {\n if (angle !== undefined) {\n if (channel === 'x') {\n if (isSignalRef(angle)) {\n const a = normalizeAngleExpr(angle);\n const orientIsTop = isSignalRef(orient) ? `(${orient.signal} === \"top\")` : orient === 'top';\n return {\n signal:\n `(45 < ${a} && ${a} < 135) || (225 < ${a} && ${a} < 315) ? \"middle\" :` +\n `(${a} <= 45 || 315 <= ${a}) === ${orientIsTop} ? \"bottom\" : \"top\"`\n };\n }\n\n if ((45 < angle && angle < 135) || (225 < angle && angle < 315)) {\n return 'middle';\n }\n\n if (isSignalRef(orient)) {\n const op = angle <= 45 || 315 <= angle ? '===' : '!==';\n return {signal: `${orient.signal} ${op} \"top\" ? \"bottom\" : \"top\"`};\n }\n\n return (angle <= 45 || 315 <= angle) === (orient === 'top') ? 'bottom' : 'top';\n } else {\n if (isSignalRef(angle)) {\n const a = normalizeAngleExpr(angle);\n const orientIsLeft = isSignalRef(orient) ? `(${orient.signal} === \"left\")` : orient === 'left';\n const middle = alwaysIncludeMiddle ? '\"middle\"' : 'null';\n return {\n signal: `${a} <= 45 || 315 <= ${a} || (135 <= ${a} && ${a} <= 225) ? ${middle} : (45 <= ${a} && ${a} <= 135) === ${orientIsLeft} ? \"top\" : \"bottom\"`\n };\n }\n\n if (angle <= 45 || 315 <= angle || (135 <= angle && angle <= 225)) {\n return alwaysIncludeMiddle ? 'middle' : null;\n }\n\n if (isSignalRef(orient)) {\n const op = 45 <= angle && angle <= 135 ? '===' : '!==';\n return {signal: `${orient.signal} ${op} \"left\" ? \"top\" : \"bottom\"`};\n }\n\n return (45 <= angle && angle <= 135) === (orient === 'left') ? 'top' : 'bottom';\n }\n }\n return undefined;\n}\n\nexport function defaultLabelAlign(\n angle: number | SignalRef,\n orient: AxisOrient | SignalRef,\n channel: 'x' | 'y'\n): Align | SignalRef {\n if (angle === undefined) {\n return undefined;\n }\n\n const isX = channel === 'x';\n const startAngle = isX ? 0 : 90;\n const mainOrient = isX ? 'bottom' : 'left';\n\n if (isSignalRef(angle)) {\n const a = normalizeAngleExpr(angle);\n const orientIsMain = isSignalRef(orient) ? `(${orient.signal} === \"${mainOrient}\")` : orient === mainOrient;\n return {\n signal:\n `(${startAngle ? `(${a} + 90)` : a} % 180 === 0) ? ${isX ? null : '\"center\"'} :` +\n `(${startAngle} < ${a} && ${a} < ${180 + startAngle}) === ${orientIsMain} ? \"left\" : \"right\"`\n };\n }\n\n if ((angle + startAngle) % 180 === 0) {\n // For bottom, use default label align so label flush still works\n return isX ? null : 'center';\n }\n\n if (isSignalRef(orient)) {\n const op = startAngle < angle && angle < 180 + startAngle ? '===' : '!==';\n const orientIsMain = `${orient.signal} ${op} \"${mainOrient}\"`;\n return {\n signal: `${orientIsMain} ? \"left\" : \"right\"`\n };\n }\n\n if ((startAngle < angle && angle < 180 + startAngle) === (orient === mainOrient)) {\n return 'left';\n }\n\n return 'right';\n}\n\nexport function defaultLabelFlush(type: Type, channel: PositionScaleChannel) {\n if (channel === 'x' && contains(['quantitative', 'temporal'], type)) {\n return true;\n }\n return undefined;\n}\n\nexport function defaultLabelOverlap(type: Type, scaleType: ScaleType, hasTimeUnit: boolean, sort?: Sort) {\n // do not prevent overlap for nominal data because there is no way to infer what the missing labels are\n if ((hasTimeUnit && !isObject(sort)) || (type !== 'nominal' && type !== 'ordinal')) {\n if (scaleType === 'log' || scaleType === 'symlog') {\n return 'greedy';\n }\n return true;\n }\n return undefined;\n}\n\nexport function defaultOrient(channel: PositionScaleChannel) {\n return channel === 'x' ? 'bottom' : 'left';\n}\n\nexport function defaultTickCount({\n fieldOrDatumDef,\n scaleType,\n size,\n values: vals\n}: {\n fieldOrDatumDef: TypedFieldDef | DatumDef;\n scaleType: ScaleType;\n size?: SignalRef;\n values?: AxisInternal['values'];\n}) {\n if (!vals && !hasDiscreteDomain(scaleType) && scaleType !== 'log') {\n if (isFieldDef(fieldOrDatumDef)) {\n if (isBinning(fieldOrDatumDef.bin)) {\n // for binned data, we don't want more ticks than maxbins\n return {signal: `ceil(${size.signal}/10)`};\n }\n\n if (\n fieldOrDatumDef.timeUnit &&\n contains(['month', 'hours', 'day', 'quarter'], normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit)\n ) {\n return undefined;\n }\n }\n\n return {signal: `ceil(${size.signal}/40)`};\n }\n\n return undefined;\n}\n\nexport function defaultTickMinStep({format, fieldOrDatumDef}: Pick) {\n if (format === 'd') {\n return 1;\n }\n\n if (isFieldDef(fieldOrDatumDef)) {\n const {timeUnit} = fieldOrDatumDef;\n if (timeUnit) {\n const signal = durationExpr(timeUnit);\n if (signal) {\n return {signal};\n }\n }\n }\n return undefined;\n}\n\nexport function getFieldDefTitle(model: UnitModel, channel: 'x' | 'y') {\n const channel2 = channel === 'x' ? 'x2' : 'y2';\n const fieldDef = model.fieldDef(channel);\n const fieldDef2 = model.fieldDef(channel2);\n\n const title1 = fieldDef ? fieldDef.title : undefined;\n const title2 = fieldDef2 ? fieldDef2.title : undefined;\n\n if (title1 && title2) {\n return mergeTitle(title1, title2);\n } else if (title1) {\n return title1;\n } else if (title2) {\n return title2;\n } else if (title1 !== undefined) {\n // falsy value to disable config\n return title1;\n } else if (title2 !== undefined) {\n // falsy value to disable config\n return title2;\n }\n\n return undefined;\n}\n\nexport function values(axis: AxisInternal, fieldOrDatumDef: TypedFieldDef | DatumDef) {\n const vals = axis.values;\n\n if (isArray(vals)) {\n return valueArray(fieldOrDatumDef, vals);\n } else if (isSignalRef(vals)) {\n return vals;\n }\n\n return undefined;\n}\n\nexport function defaultZindex(mark: Mark, fieldDef: TypedFieldDef | DatumDef) {\n if (mark === 'rect' && isDiscrete(fieldDef)) {\n return 1;\n }\n return 0;\n}\n","import {FormulaTransform as VgFormulaTransform} from 'vega';\nimport {SingleDefChannel} from '../../channel';\nimport {FieldRefOption, isScaleFieldDef, TypedFieldDef, vgField} from '../../channeldef';\nimport {DateTime} from '../../datetime';\nimport {fieldFilterExpression} from '../../predicate';\nimport {isSortArray} from '../../sort';\nimport {CalculateTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {ModelWithField} from '../model';\nimport {DataFlowNode} from './dataflow';\nimport {getDependentFields} from './expressions';\n\nexport class CalculateNode extends DataFlowNode {\n private _dependentFields: Set;\n\n public clone() {\n return new CalculateNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private readonly transform: CalculateTransform\n ) {\n super(parent);\n\n this._dependentFields = getDependentFields(this.transform.calculate);\n }\n\n public static parseAllForSortIndex(parent: DataFlowNode, model: ModelWithField) {\n // get all the encoding with sort fields from model\n model.forEachFieldDef((fieldDef: TypedFieldDef, channel: SingleDefChannel) => {\n if (!isScaleFieldDef(fieldDef)) {\n return;\n }\n if (isSortArray(fieldDef.sort)) {\n const {field, timeUnit} = fieldDef;\n const sort: (number | string | boolean | DateTime)[] = fieldDef.sort;\n // generate `datum[\"a\"] === val0 ? 0 : datum[\"a\"] === val1 ? 1 : ... : n` via FieldEqualPredicate\n const calculate =\n sort\n .map((sortValue, i) => {\n return `${fieldFilterExpression({field, timeUnit, equal: sortValue})} ? ${i} : `;\n })\n .join('') + sort.length;\n\n parent = new CalculateNode(parent, {\n calculate,\n as: sortArrayIndexField(fieldDef, channel, {forAs: true})\n });\n }\n });\n return parent;\n }\n\n public producedFields() {\n return new Set([this.transform.as]);\n }\n\n public dependentFields() {\n return this._dependentFields;\n }\n\n public assemble(): VgFormulaTransform {\n return {\n type: 'formula',\n expr: this.transform.calculate,\n as: this.transform.as\n };\n }\n\n public hash() {\n return `Calculate ${hash(this.transform)}`;\n }\n}\n\nexport function sortArrayIndexField(fieldDef: TypedFieldDef, channel: SingleDefChannel, opt?: FieldRefOption) {\n return vgField(fieldDef, {prefix: channel, suffix: 'sort_index', ...opt});\n}\n","import {Orient, SignalRef} from 'vega';\nimport {FacetChannel} from '../../channel';\nimport {Config} from '../../config';\nimport {Header} from '../../header';\nimport {contains, getFirstDefined} from '../../util';\nimport {HeaderChannel} from './component';\n\n/**\n * Get header channel, which can be different from facet channel when orient is specified or when the facet channel is facet.\n */\nexport function getHeaderChannel(channel: FacetChannel, orient: Orient): HeaderChannel {\n if (contains(['top', 'bottom'], orient)) {\n return 'column';\n } else if (contains(['left', 'right'], orient)) {\n return 'row';\n }\n return channel === 'row' ? 'row' : 'column';\n}\n\nexport function getHeaderProperty

>(\n prop: P,\n header: Header,\n config: Config,\n channel: FacetChannel\n): Header[P] {\n const headerSpecificConfig =\n channel === 'row' ? config.headerRow : channel === 'column' ? config.headerColumn : config.headerFacet;\n\n return getFirstDefined((header || {})[prop], headerSpecificConfig[prop], config.header[prop]);\n}\n\nexport function getHeaderProperties(\n properties: (keyof Header)[],\n header: Header,\n config: Config,\n channel: FacetChannel\n): Header {\n const props = {};\n for (const prop of properties) {\n const value = getHeaderProperty(prop, header || {}, config, channel);\n if (value !== undefined) {\n props[prop] = value;\n }\n }\n return props;\n}\n","/**\n * Utility for generating row / column headers\n */\nimport {Axis as VgAxis, SignalRef, Text} from 'vega';\nimport {FacetFieldDef} from '../../spec/facet';\n\nexport type HeaderChannel = 'row' | 'column';\nexport const HEADER_CHANNELS: HeaderChannel[] = ['row', 'column'];\n\nexport type HeaderType = 'header' | 'footer';\nexport const HEADER_TYPES: HeaderType[] = ['header', 'footer'];\n\nexport interface LayoutHeaderComponentIndex {\n row?: LayoutHeaderComponent;\n column?: LayoutHeaderComponent;\n facet?: LayoutHeaderComponent;\n}\n\n/**\n * A component that represents all header, footers and title of a Vega group with layout directive.\n */\nexport interface LayoutHeaderComponent {\n title?: Text | SignalRef;\n\n // TODO: concat can have multiple header / footer.\n // Need to redesign this part a bit.\n\n facetFieldDef?: FacetFieldDef;\n\n /**\n * An array of header components for headers.\n * For facet, there should be only one header component, which is data-driven.\n * For concat, there can be multiple header components that explicitly list different axes.\n */\n header?: HeaderComponent[];\n\n /**\n * An array of header components for footers.\n * For facet, there should be only one header component, which is data-driven.\n * For concat, there can be multiple header components that explicitly list different axes.\n */\n footer?: HeaderComponent[];\n}\n\n/**\n * A component that represents one group of row/column-header/footer.\n */\nexport interface HeaderComponent {\n labels: boolean;\n\n sizeSignal: {signal: string};\n\n axes: VgAxis[];\n}\n","/**\n * Utility for generating row / column headers\n */\n\nimport {SignalRef, TitleAnchor, TitleConfig} from 'vega';\nimport {isArray} from 'vega-util';\nimport {FacetChannel, FACET_CHANNELS} from '../../channel';\nimport {vgField} from '../../channeldef';\nimport {Config} from '../../config';\nimport {\n CoreHeader,\n HEADER_LABEL_PROPERTIES,\n HEADER_LABEL_PROPERTIES_MAP,\n HEADER_TITLE_PROPERTIES,\n HEADER_TITLE_PROPERTIES_MAP\n} from '../../header';\nimport {isSortField} from '../../sort';\nimport {FacetFieldDef, isFacetMapping} from '../../spec/facet';\nimport {contains, isEmpty, normalizeAngle, replaceAll} from '../../util';\nimport {RowCol, VgComparator, VgMarkGroup, VgTitle} from '../../vega.schema';\nimport {defaultLabelAlign, defaultLabelBaseline} from '../axis/properties';\nimport {sortArrayIndexField} from '../data/calculate';\nimport {formatSignalRef} from '../format';\nimport {isFacetModel, Model} from '../model';\nimport {getHeaderChannel, getHeaderProperties, getHeaderProperty} from './common';\nimport {\n HeaderChannel,\n HeaderComponent,\n HeaderType,\n HEADER_TYPES,\n LayoutHeaderComponent,\n LayoutHeaderComponentIndex\n} from './component';\n\n// TODO: rename to assembleHeaderTitleGroup\nexport function assembleTitleGroup(model: Model, channel: FacetChannel) {\n const title = model.component.layoutHeaders[channel].title;\n const config = model.config ? model.config : undefined;\n const facetFieldDef = model.component.layoutHeaders[channel].facetFieldDef\n ? model.component.layoutHeaders[channel].facetFieldDef\n : undefined;\n\n const {\n titleAnchor,\n titleAngle: ta,\n titleOrient\n } = getHeaderProperties(['titleAnchor', 'titleAngle', 'titleOrient'], facetFieldDef.header, config, channel);\n const headerChannel = getHeaderChannel(channel, titleOrient);\n\n const titleAngle = normalizeAngle(ta);\n\n return {\n name: `${channel}-title`,\n type: 'group',\n role: `${headerChannel}-title`,\n title: {\n text: title,\n ...(channel === 'row' ? {orient: 'left'} : {}),\n style: 'guide-title',\n ...defaultHeaderGuideBaseline(titleAngle, headerChannel),\n ...defaultHeaderGuideAlign(headerChannel, titleAngle, titleAnchor),\n ...assembleHeaderProperties(config, facetFieldDef, channel, HEADER_TITLE_PROPERTIES, HEADER_TITLE_PROPERTIES_MAP)\n }\n };\n}\n\nexport function defaultHeaderGuideAlign(headerChannel: HeaderChannel, angle: number, anchor: TitleAnchor = 'middle') {\n switch (anchor) {\n case 'start':\n return {align: 'left'};\n case 'end':\n return {align: 'right'};\n }\n\n const align = defaultLabelAlign(angle, headerChannel === 'row' ? 'left' : 'top', headerChannel === 'row' ? 'y' : 'x');\n return align ? {align} : {};\n}\n\nexport function defaultHeaderGuideBaseline(angle: number, channel: FacetChannel) {\n const baseline = defaultLabelBaseline(angle, channel === 'row' ? 'left' : 'top', channel === 'row' ? 'y' : 'x', true);\n return baseline ? {baseline} : {};\n}\n\nexport function assembleHeaderGroups(model: Model, channel: HeaderChannel): VgMarkGroup[] {\n const layoutHeader = model.component.layoutHeaders[channel];\n const groups = [];\n for (const headerType of HEADER_TYPES) {\n if (layoutHeader[headerType]) {\n for (const headerComponent of layoutHeader[headerType]) {\n const group = assembleHeaderGroup(model, channel, headerType, layoutHeader, headerComponent);\n if (group != null) {\n groups.push(group);\n }\n }\n }\n }\n return groups;\n}\n\nfunction getSort(facetFieldDef: FacetFieldDef, channel: HeaderChannel): VgComparator {\n const {sort} = facetFieldDef;\n if (isSortField(sort)) {\n return {\n field: vgField(sort, {expr: 'datum'}),\n order: sort.order ?? 'ascending'\n };\n } else if (isArray(sort)) {\n return {\n field: sortArrayIndexField(facetFieldDef, channel, {expr: 'datum'}),\n order: 'ascending'\n };\n } else {\n return {\n field: vgField(facetFieldDef, {expr: 'datum'}),\n order: sort ?? 'ascending'\n };\n }\n}\n\nexport function assembleLabelTitle(\n facetFieldDef: FacetFieldDef,\n channel: FacetChannel,\n config: Config\n) {\n const {format, formatType, labelAngle, labelAnchor, labelOrient, labelExpr} = getHeaderProperties(\n ['format', 'formatType', 'labelAngle', 'labelAnchor', 'labelOrient', 'labelExpr'],\n facetFieldDef.header,\n config,\n channel\n );\n\n const titleTextExpr = formatSignalRef({\n fieldOrDatumDef: facetFieldDef,\n format,\n formatType,\n expr: 'parent',\n config\n }).signal;\n const headerChannel = getHeaderChannel(channel, labelOrient);\n\n return {\n text: {\n signal: labelExpr\n ? replaceAll(\n replaceAll(labelExpr, 'datum.label', titleTextExpr),\n 'datum.value',\n vgField(facetFieldDef, {expr: 'parent'})\n )\n : titleTextExpr\n },\n ...(channel === 'row' ? {orient: 'left'} : {}),\n style: 'guide-label',\n frame: 'group',\n ...defaultHeaderGuideBaseline(labelAngle, headerChannel),\n ...defaultHeaderGuideAlign(headerChannel, labelAngle, labelAnchor),\n ...assembleHeaderProperties(config, facetFieldDef, channel, HEADER_LABEL_PROPERTIES, HEADER_LABEL_PROPERTIES_MAP)\n };\n}\n\nexport function assembleHeaderGroup(\n model: Model,\n channel: HeaderChannel,\n headerType: HeaderType,\n layoutHeader: LayoutHeaderComponent,\n headerComponent: HeaderComponent\n) {\n if (headerComponent) {\n let title = null;\n const {facetFieldDef} = layoutHeader;\n const config = model.config ? model.config : undefined;\n if (facetFieldDef && headerComponent.labels) {\n const {labelOrient} = getHeaderProperties(['labelOrient'], facetFieldDef.header, config, channel);\n\n // Include label title in the header if orient aligns with the channel\n if (\n (channel === 'row' && !contains(['top', 'bottom'], labelOrient)) ||\n (channel === 'column' && !contains(['left', 'right'], labelOrient))\n ) {\n title = assembleLabelTitle(facetFieldDef, channel, config);\n }\n }\n\n const isFacetWithoutRowCol = isFacetModel(model) && !isFacetMapping(model.facet);\n\n const axes = headerComponent.axes;\n\n const hasAxes = axes?.length > 0;\n if (title || hasAxes) {\n const sizeChannel = channel === 'row' ? 'height' : 'width';\n\n return {\n name: model.getName(`${channel}_${headerType}`),\n type: 'group',\n role: `${channel}-${headerType}`,\n\n ...(layoutHeader.facetFieldDef\n ? {\n from: {data: model.getName(`${channel}_domain`)},\n sort: getSort(facetFieldDef, channel)\n }\n : {}),\n ...(hasAxes && isFacetWithoutRowCol\n ? {\n from: {data: model.getName(`facet_domain_${channel}`)}\n }\n : {}),\n\n ...(title ? {title} : {}),\n ...(headerComponent.sizeSignal\n ? {\n encode: {\n update: {\n [sizeChannel]: headerComponent.sizeSignal\n }\n }\n }\n : {}),\n ...(hasAxes ? {axes} : {})\n };\n }\n }\n return null;\n}\n\nconst LAYOUT_TITLE_BAND = {\n column: {\n start: 0,\n end: 1\n },\n row: {\n start: 1,\n end: 0\n }\n};\n\nexport function getLayoutTitleBand(titleAnchor: TitleAnchor, headerChannel: HeaderChannel) {\n return LAYOUT_TITLE_BAND[headerChannel][titleAnchor];\n}\n\nexport function assembleLayoutTitleBand(\n headerComponentIndex: LayoutHeaderComponentIndex,\n config: Config\n): RowCol {\n const titleBand = {};\n\n for (const channel of FACET_CHANNELS) {\n const headerComponent = headerComponentIndex[channel];\n if (headerComponent?.facetFieldDef) {\n const {titleAnchor, titleOrient} = getHeaderProperties(\n ['titleAnchor', 'titleOrient'],\n headerComponent.facetFieldDef.header,\n config,\n channel\n );\n\n const headerChannel = getHeaderChannel(channel, titleOrient);\n const band = getLayoutTitleBand(titleAnchor, headerChannel);\n if (band !== undefined) {\n titleBand[headerChannel] = band;\n }\n }\n }\n\n return isEmpty(titleBand) ? undefined : titleBand;\n}\n\nexport function assembleHeaderProperties(\n config: Config,\n facetFieldDef: FacetFieldDef,\n channel: FacetChannel,\n properties: (keyof CoreHeader)[],\n propertiesMap: Partial, keyof TitleConfig>>\n): Partial {\n const props = {};\n for (const prop of properties) {\n if (!propertiesMap[prop]) {\n continue;\n }\n\n const value = getHeaderProperty(prop, facetFieldDef?.header, config, channel);\n if (value !== undefined) {\n props[propertiesMap[prop]] = value;\n }\n }\n return props;\n}\n","import {InitSignal, NewSignal} from 'vega';\nimport {getViewConfigContinuousSize} from '../../config';\nimport {hasDiscreteDomain} from '../../scale';\nimport {getFirstDefined} from '../../util';\nimport {isSignalRef, isVgRangeStep, VgRangeStep} from '../../vega.schema';\nimport {signalOrStringValue} from '../common';\nimport {isFacetModel, Model} from '../model';\nimport {ScaleComponent} from '../scale/component';\nimport {LayoutSizeType} from './component';\n\nexport function assembleLayoutSignals(model: Model): NewSignal[] {\n return [\n ...sizeSignals(model, 'width'),\n ...sizeSignals(model, 'height'),\n ...sizeSignals(model, 'childWidth'),\n ...sizeSignals(model, 'childHeight')\n ];\n}\n\nexport function sizeSignals(model: Model, sizeType: LayoutSizeType): (NewSignal | InitSignal)[] {\n const channel = sizeType === 'width' ? 'x' : 'y';\n const size = model.component.layoutSize.get(sizeType);\n if (!size || size === 'merged') {\n return [];\n }\n\n // Read size signal name from name map, just in case it is the top-level size signal that got renamed.\n const name = model.getSizeSignalRef(sizeType).signal;\n\n if (size === 'step') {\n const scaleComponent = model.getScaleComponent(channel);\n\n if (scaleComponent) {\n const type = scaleComponent.get('type');\n const range = scaleComponent.get('range');\n\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const scaleName = model.scaleName(channel);\n\n if (isFacetModel(model.parent)) {\n // If parent is facet and this is an independent scale, return only signal signal\n // as the width/height will be calculated using the cardinality from\n // facet's aggregate rather than reading from scale domain\n const parentResolve = model.parent.component.resolve;\n if (parentResolve.scale[channel] === 'independent') {\n return [stepSignal(scaleName, range)];\n }\n }\n\n return [\n stepSignal(scaleName, range),\n {\n name,\n update: sizeExpr(scaleName, scaleComponent, `domain('${scaleName}').length`)\n }\n ];\n }\n }\n /* istanbul ignore next: Condition should not happen -- only for warning in development. */\n throw new Error('layout size is step although width/height is not step.');\n } else if (size == 'container') {\n const isWidth = name.endsWith('width');\n const expr = isWidth ? 'containerSize()[0]' : 'containerSize()[1]';\n const defaultValue = getViewConfigContinuousSize(model.config.view, isWidth ? 'width' : 'height');\n const safeExpr = `isFinite(${expr}) ? ${expr} : ${defaultValue}`;\n return [{name, init: safeExpr, on: [{update: safeExpr, events: 'window:resize'}]}];\n } else {\n return [\n {\n name,\n value: size\n }\n ];\n }\n}\n\nfunction stepSignal(scaleName: string, range: VgRangeStep): NewSignal {\n const name = `${scaleName}_step`;\n if (isSignalRef(range.step)) {\n return {name, update: range.step.signal};\n } else {\n return {name, value: range.step};\n }\n}\n\nexport function sizeExpr(scaleName: string, scaleComponent: ScaleComponent, cardinality: string) {\n const type = scaleComponent.get('type');\n const padding = scaleComponent.get('padding');\n const paddingOuter = getFirstDefined(scaleComponent.get('paddingOuter'), padding);\n\n let paddingInner = scaleComponent.get('paddingInner');\n paddingInner =\n type === 'band'\n ? // only band has real paddingInner\n paddingInner !== undefined\n ? paddingInner\n : padding\n : // For point, as calculated in https://github.com/vega/vega-scale/blob/master/src/band.js#L128,\n // it's equivalent to have paddingInner = 1 since there is only n-1 steps between n points.\n 1;\n return `bandspace(${cardinality}, ${signalOrStringValue(paddingInner)}, ${signalOrStringValue(\n paddingOuter\n )}) * ${scaleName}_step`;\n}\n","import {Split} from '../split';\n\nexport type LayoutSize = number | 'container' | 'step' | 'merged';\n\nexport interface LayoutSizeIndex {\n width?: LayoutSize;\n\n childWidth?: LayoutSize;\n\n height?: LayoutSize;\n\n childHeight?: LayoutSize;\n}\n\nexport type LayoutSizeType = keyof LayoutSizeIndex;\n\nexport type LayoutSizeComponent = Split;\n\nexport function getSizeTypeFromLayoutSizeType(layoutSizeType: LayoutSizeType): 'width' | 'height' {\n return layoutSizeType === 'childWidth' ? 'width' : layoutSizeType === 'childHeight' ? 'height' : layoutSizeType;\n}\n","import {GuideEncodingEntry} from '../guide';\nimport {keys} from '../util';\nimport {VgEncodeChannel} from '../vega.schema';\nimport {signalOrValueRef} from './common';\nimport {wrapCondition} from './mark/encode/conditional';\nimport {UnitModel} from './unit';\n\nexport function guideEncodeEntry(encoding: GuideEncodingEntry, model: UnitModel) {\n return keys(encoding).reduce((encode, channel: VgEncodeChannel) => {\n return {\n ...encode,\n ...wrapCondition({\n model,\n channelDef: encoding[channel],\n vgChannel: channel,\n mainRefFn: def => signalOrValueRef(def.value),\n invalidValueRef: undefined // guide encoding won't show invalid values for the scale\n })\n };\n }, {});\n}\n","import {isXorY, ScaleChannel} from '../channel';\nimport * as log from '../log';\nimport {Resolve, ResolveMode} from '../resolve';\nimport {isConcatModel, isFacetModel, isLayerModel, Model} from './model';\n\nexport function defaultScaleResolve(channel: ScaleChannel, model: Model): ResolveMode {\n if (isFacetModel(model)) {\n return channel === 'theta' ? 'independent' : 'shared';\n } else if (isLayerModel(model)) {\n return 'shared';\n } else if (isConcatModel(model)) {\n return isXorY(channel) || channel === 'theta' || channel === 'radius' ? 'independent' : 'shared';\n }\n /* istanbul ignore next: should never reach here. */\n throw new Error('invalid model type for resolve');\n}\n\nexport function parseGuideResolve(resolve: Resolve, channel: ScaleChannel): ResolveMode {\n const channelScaleResolve = resolve.scale[channel];\n const guide = isXorY(channel) ? 'axis' : 'legend';\n\n if (channelScaleResolve === 'independent') {\n if (resolve[guide][channel] === 'shared') {\n log.warn(log.message.independentScaleMeansIndependentGuide(channel));\n }\n return 'independent';\n }\n\n return resolve[guide][channel] || 'shared';\n}\n","import {Legend as VgLegend} from 'vega';\nimport {NonPositionScaleChannel} from '../../channel';\nimport {COMMON_LEGEND_PROPERTY_INDEX, LegendInternal} from '../../legend';\nimport {Flag, keys} from '../../util';\nimport {Split} from '../split';\n\nexport type LegendComponentProps = VgLegend & {\n labelExpr?: string;\n selections?: string[];\n disable?: boolean;\n};\n\nconst LEGEND_COMPONENT_PROPERTY_INDEX: Flag = {\n ...COMMON_LEGEND_PROPERTY_INDEX,\n disable: 1,\n labelExpr: 1,\n selections: 1,\n // channel scales\n opacity: 1,\n shape: 1,\n stroke: 1,\n fill: 1,\n size: 1,\n strokeWidth: 1,\n strokeDash: 1,\n // encode\n encode: 1\n};\n\nexport const LEGEND_COMPONENT_PROPERTIES = keys(LEGEND_COMPONENT_PROPERTY_INDEX);\n\nexport class LegendComponent extends Split {}\n\nexport type LegendComponentIndex = Partial>;\n\nexport type LegendInternalIndex = Partial>;\n","import {ColorValueRef, EncodeEntry, Gradient, LegendEncode, LegendType, SignalRef, SymbolEncodeEntry} from 'vega';\nimport {array, isArray, stringValue} from 'vega-util';\nimport {COLOR, NonPositionScaleChannel, OPACITY} from '../../channel';\nimport {\n Conditional,\n DatumDef,\n hasConditionalValueDef,\n isFieldDef,\n isValueDef,\n TypedFieldDef,\n Value,\n ValueDef\n} from '../../channeldef';\nimport {Encoding} from '../../encoding';\nimport {FILL_STROKE_CONFIG} from '../../mark';\nimport {getFirstDefined, isEmpty, varName} from '../../util';\nimport {applyMarkConfig, signalOrValueRef} from '../common';\nimport {formatCustomType, isCustomFormatType} from '../format';\nimport * as mixins from '../mark/encode';\nimport {STORE} from '../selection';\nimport {UnitModel} from '../unit';\nimport {LegendComponent} from './component';\n\nexport interface LegendEncodeParams {\n fieldOrDatumDef: TypedFieldDef | DatumDef;\n model: UnitModel;\n channel: NonPositionScaleChannel;\n legendCmpt: LegendComponent;\n legendType: LegendType;\n}\n\nexport const legendEncodeRules: {\n [part in keyof LegendEncode]?: (spec: EncodeEntry, params: LegendEncodeParams) => EncodeEntry;\n} = {\n symbols,\n gradient,\n labels,\n entries\n};\n\nexport function symbols(\n symbolsSpec: any,\n {fieldOrDatumDef, model, channel, legendCmpt, legendType}: LegendEncodeParams\n): SymbolEncodeEntry {\n if (legendType !== 'symbol') {\n return undefined;\n }\n\n const {markDef, encoding, config, mark} = model;\n const filled = markDef.filled && mark !== 'trail';\n\n let out = {\n ...applyMarkConfig({}, model, FILL_STROKE_CONFIG),\n ...mixins.color(model, {filled})\n } as SymbolEncodeEntry; // FIXME: remove this when VgEncodeEntry is compatible with SymbolEncodeEntry\n\n const symbolOpacity = legendCmpt.get('symbolOpacity') ?? config.legend.symbolOpacity;\n const symbolFillColor = legendCmpt.get('symbolFillColor') ?? config.legend.symbolFillColor;\n const symbolStrokeColor = legendCmpt.get('symbolStrokeColor') ?? config.legend.symbolStrokeColor;\n\n const opacity = symbolOpacity === undefined ? getMaxValue(encoding.opacity) ?? markDef.opacity : undefined;\n\n if (out.fill) {\n // for fill legend, we don't want any fill in symbol\n if (channel === 'fill' || (filled && channel === COLOR)) {\n delete out.fill;\n } else {\n if (out.fill['field']) {\n // For others, set fill to some opaque value (or nothing if a color is already set)\n if (symbolFillColor) {\n delete out.fill;\n } else {\n out.fill = signalOrValueRef(config.legend.symbolBaseFillColor ?? 'black');\n out.fillOpacity = signalOrValueRef(opacity ?? 1);\n }\n } else if (isArray(out.fill)) {\n const fill =\n getFirstConditionValue(encoding.fill ?? encoding.color) ?? markDef.fill ?? (filled && markDef.color);\n if (fill) {\n out.fill = signalOrValueRef(fill) as ColorValueRef;\n }\n }\n }\n }\n\n if (out.stroke) {\n if (channel === 'stroke' || (!filled && channel === COLOR)) {\n delete out.stroke;\n } else {\n if (out.stroke['field'] || symbolStrokeColor) {\n // For others, remove stroke field\n delete out.stroke;\n } else if (isArray(out.stroke)) {\n const stroke = getFirstDefined(\n getFirstConditionValue(encoding.stroke || encoding.color),\n markDef.stroke,\n filled ? markDef.color : undefined\n );\n if (stroke) {\n out.stroke = {value: stroke} as ColorValueRef;\n }\n }\n }\n }\n\n if (channel !== OPACITY) {\n const condition = isFieldDef(fieldOrDatumDef) && selectedCondition(model, legendCmpt, fieldOrDatumDef);\n\n if (condition) {\n out.opacity = [\n {test: condition, ...signalOrValueRef(opacity ?? 1)},\n signalOrValueRef(config.legend.unselectedOpacity)\n ];\n } else if (opacity) {\n out.opacity = signalOrValueRef(opacity);\n }\n }\n\n out = {...out, ...symbolsSpec};\n\n return isEmpty(out) ? undefined : out;\n}\n\nexport function gradient(gradientSpec: any, {model, legendType, legendCmpt}: LegendEncodeParams) {\n if (legendType !== 'gradient') {\n return undefined;\n }\n\n const {config, markDef, encoding} = model;\n\n let out: SymbolEncodeEntry = {};\n\n const gradientOpacity = legendCmpt.get('gradientOpacity') ?? config.legend.gradientOpacity;\n const opacity = gradientOpacity === undefined ? getMaxValue(encoding.opacity) || markDef.opacity : undefined;\n if (opacity) {\n // only apply opacity if it is neither zero or undefined\n out.opacity = signalOrValueRef(opacity);\n }\n\n out = {...out, ...gradientSpec};\n return isEmpty(out) ? undefined : out;\n}\n\nexport function labels(specifiedlabelsSpec: any, {fieldOrDatumDef, model, channel, legendCmpt}: LegendEncodeParams) {\n const legend = model.legend(channel) || {};\n const config = model.config;\n\n const condition = isFieldDef(fieldOrDatumDef) ? selectedCondition(model, legendCmpt, fieldOrDatumDef) : undefined;\n const opacity = condition ? [{test: condition, value: 1}, {value: config.legend.unselectedOpacity}] : undefined;\n\n const {format, formatType} = legend;\n\n let text = undefined;\n\n if (isCustomFormatType(formatType)) {\n text = formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format,\n formatType,\n config\n });\n } else if (format === undefined && formatType === undefined && config.customFormatTypes) {\n if (fieldOrDatumDef.type === 'quantitative' && config.numberFormatType) {\n text = formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format: config.numberFormat,\n formatType: config.numberFormatType,\n config\n });\n } else if (\n fieldOrDatumDef.type === 'temporal' &&\n config.timeFormatType &&\n isFieldDef(fieldOrDatumDef) &&\n fieldOrDatumDef.timeUnit === undefined\n ) {\n text = formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format: config.timeFormat,\n formatType: config.timeFormatType,\n config\n });\n }\n }\n\n const labelsSpec = {\n ...(opacity ? {opacity} : {}),\n ...(text ? {text} : {}),\n ...specifiedlabelsSpec\n };\n\n return isEmpty(labelsSpec) ? undefined : labelsSpec;\n}\n\nexport function entries(entriesSpec: any, {legendCmpt}: LegendEncodeParams) {\n const selections = legendCmpt.get('selections');\n return selections?.length ? {...entriesSpec, fill: {value: 'transparent'}} : entriesSpec;\n}\n\nfunction getMaxValue(channelDef: Encoding['opacity']) {\n return getConditionValue(channelDef, (v: number, conditionalDef) => Math.max(v, conditionalDef.value as any));\n}\n\nexport function getFirstConditionValue(\n channelDef: Encoding['fill' | 'stroke' | 'shape']\n): V {\n return getConditionValue(channelDef, (v: V, conditionalDef: Conditional>) => {\n return getFirstDefined(v, conditionalDef.value);\n });\n}\n\nfunction getConditionValue(\n channelDef: Encoding['fill' | 'stroke' | 'shape' | 'opacity'],\n reducer: (val: V, conditionalDef: Conditional>) => V\n): V {\n if (hasConditionalValueDef(channelDef)) {\n return array(channelDef.condition).reduce(reducer, channelDef.value as any);\n } else if (isValueDef(channelDef)) {\n return channelDef.value as any;\n }\n return undefined;\n}\n\nfunction selectedCondition(model: UnitModel, legendCmpt: LegendComponent, fieldDef: TypedFieldDef) {\n const selections = legendCmpt.get('selections');\n if (!selections?.length) return undefined;\n\n const field = stringValue(fieldDef.field);\n return selections\n .map(name => {\n const store = stringValue(varName(name) + STORE);\n return `(!length(data(${store})) || (${name}[${field}] && indexof(${name}[${field}], datum.value) >= 0))`;\n })\n .join(' || ');\n}\n","import {LabelOverlap, LegendOrient, LegendType, Orientation, SignalRef, SymbolShape} from 'vega';\nimport {isArray} from 'vega-util';\nimport {isColorChannel} from '../../channel';\nimport {DatumDef, MarkPropFieldOrDatumDef, title as fieldDefTitle, TypedFieldDef, valueArray} from '../../channeldef';\nimport {Config} from '../../config';\nimport {Encoding} from '../../encoding';\nimport {Legend, LegendConfig, LegendInternal} from '../../legend';\nimport {Mark, MarkDef} from '../../mark';\nimport {isContinuousToContinuous, ScaleType} from '../../scale';\nimport {TimeUnit} from '../../timeunit';\nimport {contains, getFirstDefined} from '../../util';\nimport {isSignalRef} from '../../vega.schema';\nimport {guideFormat, guideFormatType} from '../format';\nimport {Model} from '../model';\nimport {UnitModel} from '../unit';\nimport {NonPositionScaleChannel} from './../../channel';\nimport {LegendComponentProps} from './component';\nimport {getFirstConditionValue} from './encode';\n\nexport interface LegendRuleParams {\n legend: LegendInternal;\n channel: NonPositionScaleChannel;\n model: UnitModel;\n markDef: MarkDef;\n encoding: Encoding;\n fieldOrDatumDef: MarkPropFieldOrDatumDef;\n legendConfig: LegendConfig;\n config: Config;\n scaleType: ScaleType;\n orient: LegendOrient;\n legendType: LegendType;\n direction: Orientation;\n}\n\nexport const legendRules: {\n [k in keyof LegendComponentProps]?: (params: LegendRuleParams) => LegendComponentProps[k];\n} = {\n direction: ({direction}) => direction,\n\n format: ({fieldOrDatumDef, legend, config}) => {\n const {format, formatType} = legend;\n return guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format, formatType, config, false);\n },\n\n formatType: ({legend, fieldOrDatumDef, scaleType}) => {\n const {formatType} = legend;\n return guideFormatType(formatType, fieldOrDatumDef, scaleType);\n },\n\n gradientLength: params => {\n const {legend, legendConfig} = params;\n return legend.gradientLength ?? legendConfig.gradientLength ?? defaultGradientLength(params);\n },\n\n labelOverlap: ({legend, legendConfig, scaleType}) =>\n legend.labelOverlap ?? legendConfig.labelOverlap ?? defaultLabelOverlap(scaleType),\n\n symbolType: ({legend, markDef, channel, encoding}) =>\n legend.symbolType ?? defaultSymbolType(markDef.type, channel, encoding.shape, markDef.shape),\n\n title: ({fieldOrDatumDef, config}) => fieldDefTitle(fieldOrDatumDef, config, {allowDisabling: true}),\n\n type: ({legendType, scaleType, channel}) => {\n if (isColorChannel(channel) && isContinuousToContinuous(scaleType)) {\n if (legendType === 'gradient') {\n return undefined;\n }\n } else if (legendType === 'symbol') {\n return undefined;\n }\n return legendType;\n }, // depended by other property, let's define upfront\n\n values: ({fieldOrDatumDef, legend}) => values(legend, fieldOrDatumDef)\n};\n\nexport function values(legend: LegendInternal, fieldOrDatumDef: TypedFieldDef | DatumDef) {\n const vals = legend.values;\n\n if (isArray(vals)) {\n return valueArray(fieldOrDatumDef, vals);\n } else if (isSignalRef(vals)) {\n return vals;\n }\n return undefined;\n}\n\nexport function defaultSymbolType(\n mark: Mark,\n channel: NonPositionScaleChannel,\n shapeChannelDef: Encoding['shape'],\n markShape: SymbolShape | SignalRef\n): SymbolShape | SignalRef {\n if (channel !== 'shape') {\n // use the value from the shape encoding or the mark config if they exist\n const shape = getFirstConditionValue(shapeChannelDef) ?? markShape;\n if (shape) {\n return shape;\n }\n }\n\n switch (mark) {\n case 'bar':\n case 'rect':\n case 'image':\n case 'square':\n return 'square';\n case 'line':\n case 'trail':\n case 'rule':\n return 'stroke';\n case 'arc':\n case 'point':\n case 'circle':\n case 'tick':\n case 'geoshape':\n case 'area':\n case 'text':\n return 'circle';\n }\n}\n\nexport function clipHeight(legendType: LegendType) {\n if (legendType === 'gradient') {\n return 20;\n }\n return undefined;\n}\n\nexport function getLegendType(params: {\n legend: LegendInternal;\n channel: NonPositionScaleChannel;\n timeUnit?: TimeUnit;\n scaleType: ScaleType;\n}): LegendType {\n const {legend} = params;\n\n return getFirstDefined(legend.type, defaultType(params));\n}\n\nexport function defaultType({\n channel,\n timeUnit,\n scaleType\n}: {\n channel: NonPositionScaleChannel;\n timeUnit?: TimeUnit;\n scaleType: ScaleType;\n}): LegendType {\n // Following the logic in https://github.com/vega/vega-parser/blob/master/src/parsers/legend.js\n\n if (isColorChannel(channel)) {\n if (contains(['quarter', 'month', 'day'], timeUnit)) {\n return 'symbol';\n }\n\n if (isContinuousToContinuous(scaleType)) {\n return 'gradient';\n }\n }\n return 'symbol';\n}\n\nexport function getDirection({\n legendConfig,\n legendType,\n orient,\n legend\n}: {\n orient: LegendOrient;\n legendConfig: LegendConfig;\n legendType: LegendType;\n legend: Legend;\n}): Orientation {\n return (\n legend.direction ??\n legendConfig[legendType ? 'gradientDirection' : 'symbolDirection'] ??\n defaultDirection(orient, legendType)\n );\n}\n\nexport function defaultDirection(orient: LegendOrient, legendType: LegendType): 'horizontal' | undefined {\n switch (orient) {\n case 'top':\n case 'bottom':\n return 'horizontal';\n\n case 'left':\n case 'right':\n case 'none':\n case undefined: // undefined = \"right\" in Vega\n return undefined; // vertical is Vega's default\n default:\n // top-left / ...\n // For inner legend, uses compact layout like Tableau\n return legendType === 'gradient' ? 'horizontal' : undefined;\n }\n}\n\nexport function defaultGradientLength({\n legendConfig,\n model,\n direction,\n orient,\n scaleType\n}: {\n scaleType: ScaleType;\n direction: Orientation;\n orient: LegendOrient;\n model: Model;\n legendConfig: LegendConfig;\n}) {\n const {\n gradientHorizontalMaxLength,\n gradientHorizontalMinLength,\n gradientVerticalMaxLength,\n gradientVerticalMinLength\n } = legendConfig;\n if (isContinuousToContinuous(scaleType)) {\n if (direction === 'horizontal') {\n if (orient === 'top' || orient === 'bottom') {\n return gradientLengthSignal(model, 'width', gradientHorizontalMinLength, gradientHorizontalMaxLength);\n } else {\n return gradientHorizontalMinLength;\n }\n } else {\n // vertical / undefined (Vega uses vertical by default)\n return gradientLengthSignal(model, 'height', gradientVerticalMinLength, gradientVerticalMaxLength);\n }\n }\n return undefined;\n}\n\nfunction gradientLengthSignal(model: Model, sizeType: 'width' | 'height', min: number, max: number) {\n const sizeSignal = model.getSizeSignalRef(sizeType).signal;\n return {signal: `clamp(${sizeSignal}, ${min}, ${max})`};\n}\n\nexport function defaultLabelOverlap(scaleType: ScaleType): LabelOverlap {\n if (contains(['quantile', 'threshold', 'log', 'symlog'], scaleType)) {\n return 'greedy';\n }\n return undefined;\n}\n","import {Legend as VgLegend, LegendEncode} from 'vega';\nimport {COLOR, NonPositionScaleChannel, SHAPE} from '../../channel';\nimport {DatumDef, FieldDef, getFieldOrDatumDef, isFieldDef, MarkPropDatumDef, MarkPropFieldDef} from '../../channeldef';\nimport {LegendInternal, LEGEND_SCALE_CHANNELS} from '../../legend';\nimport {normalizeTimeUnit} from '../../timeunit';\nimport {GEOJSON} from '../../type';\nimport {deleteNestedProperty, isEmpty, keys, varName} from '../../util';\nimport {mergeTitleComponent} from '../common';\nimport {guideEncodeEntry} from '../guide';\nimport {isUnitModel, Model} from '../model';\nimport {parseGuideResolve} from '../resolve';\nimport {parseInteractiveLegend} from '../selection/legends';\nimport {defaultTieBreaker, Explicit, makeImplicit, mergeValuesWithExplicit} from '../split';\nimport {UnitModel} from '../unit';\nimport {LegendComponent, LegendComponentIndex, LegendComponentProps, LEGEND_COMPONENT_PROPERTIES} from './component';\nimport {LegendEncodeParams, legendEncodeRules} from './encode';\nimport {getDirection, getLegendType, LegendRuleParams, legendRules} from './properties';\n\nexport function parseLegend(model: Model) {\n const legendComponent = isUnitModel(model) ? parseUnitLegend(model) : parseNonUnitLegend(model);\n model.component.legends = legendComponent;\n return legendComponent;\n}\n\nfunction parseUnitLegend(model: UnitModel): LegendComponentIndex {\n const {encoding} = model;\n\n const legendComponent: LegendComponentIndex = {};\n\n for (const channel of [COLOR, ...LEGEND_SCALE_CHANNELS]) {\n const def = getFieldOrDatumDef(encoding[channel]) as MarkPropFieldDef | MarkPropDatumDef;\n\n if (!def || !model.getScaleComponent(channel)) {\n continue;\n }\n\n if (channel === SHAPE && isFieldDef(def) && def.type === GEOJSON) {\n continue;\n }\n\n legendComponent[channel] = parseLegendForChannel(model, channel);\n }\n\n return legendComponent;\n}\n\nfunction getLegendDefWithScale(model: UnitModel, channel: NonPositionScaleChannel): VgLegend {\n const scale = model.scaleName(channel);\n if (model.mark === 'trail') {\n if (channel === 'color') {\n // trail is a filled mark, but its default symbolType (\"stroke\") should use \"stroke\"\n return {stroke: scale};\n } else if (channel === 'size') {\n return {strokeWidth: scale};\n }\n }\n\n if (channel === 'color') {\n return model.markDef.filled ? {fill: scale} : {stroke: scale};\n }\n return {[channel]: scale};\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isExplicit(\n value: T,\n property: keyof LegendComponentProps,\n legend: LegendInternal,\n fieldDef: FieldDef\n) {\n switch (property) {\n case 'disable':\n return legend !== undefined; // if axis is specified or null/false, then its enable/disable state is explicit\n case 'values':\n // specified legend.values is already respected, but may get transformed.\n return !!legend?.values;\n case 'title':\n // title can be explicit if fieldDef.title is set\n if (property === 'title' && value === fieldDef?.title) {\n return true;\n }\n }\n // Otherwise, things are explicit if the returned value matches the specified property\n return value === (legend || {})[property];\n}\n\nexport function parseLegendForChannel(model: UnitModel, channel: NonPositionScaleChannel): LegendComponent {\n let legend = model.legend(channel);\n\n const {markDef, encoding, config} = model;\n const legendConfig = config.legend;\n const legendCmpt = new LegendComponent({}, getLegendDefWithScale(model, channel));\n parseInteractiveLegend(model, channel, legendCmpt);\n\n const disable = legend !== undefined ? !legend : legendConfig.disable;\n legendCmpt.set('disable', disable, legend !== undefined);\n if (disable) {\n return legendCmpt;\n }\n\n legend = legend || {};\n\n const scaleType = model.getScaleComponent(channel).get('type');\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) as MarkPropFieldDef | DatumDef;\n const timeUnit = isFieldDef(fieldOrDatumDef) ? normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : undefined;\n\n const orient = legend.orient || config.legend.orient || 'right';\n const legendType = getLegendType({legend, channel, timeUnit, scaleType});\n\n const direction = getDirection({legend, legendType, orient, legendConfig});\n\n const ruleParams: LegendRuleParams = {\n legend,\n channel,\n model,\n markDef,\n encoding,\n fieldOrDatumDef,\n legendConfig,\n config,\n scaleType,\n orient,\n legendType,\n direction\n };\n\n for (const property of LEGEND_COMPONENT_PROPERTIES) {\n if (\n (legendType === 'gradient' && property.startsWith('symbol')) ||\n (legendType === 'symbol' && property.startsWith('gradient'))\n ) {\n continue;\n }\n\n const value = property in legendRules ? legendRules[property](ruleParams) : legend[property];\n if (value !== undefined) {\n const explicit = isExplicit(value, property, legend, model.fieldDef(channel));\n if (explicit || config.legend[property] === undefined) {\n legendCmpt.set(property, value, explicit);\n }\n }\n }\n\n const legendEncoding = legend?.encoding ?? {};\n const selections = legendCmpt.get('selections');\n const legendEncode: LegendEncode = {};\n\n const legendEncodeParams: LegendEncodeParams = {fieldOrDatumDef, model, channel, legendCmpt, legendType};\n\n for (const part of ['labels', 'legend', 'title', 'symbols', 'gradient', 'entries']) {\n const legendEncodingPart = guideEncodeEntry(legendEncoding[part] ?? {}, model);\n\n const value =\n part in legendEncodeRules\n ? legendEncodeRules[part](legendEncodingPart, legendEncodeParams) // apply rule\n : legendEncodingPart; // no rule -- just default values\n\n if (value !== undefined && !isEmpty(value)) {\n legendEncode[part] = {\n ...(selections?.length && isFieldDef(fieldOrDatumDef)\n ? {name: `${varName(fieldOrDatumDef.field)}_legend_${part}`}\n : {}),\n ...(selections?.length ? {interactive: !!selections} : {}),\n update: value\n };\n }\n }\n\n if (!isEmpty(legendEncode)) {\n legendCmpt.set('encode', legendEncode, !!legend?.encoding);\n }\n\n return legendCmpt;\n}\n\nfunction parseNonUnitLegend(model: Model) {\n const {legends, resolve} = model.component;\n\n for (const child of model.children) {\n parseLegend(child);\n\n for (const channel of keys(child.component.legends)) {\n resolve.legend[channel] = parseGuideResolve(model.component.resolve, channel);\n\n if (resolve.legend[channel] === 'shared') {\n // If the resolve says shared (and has not been overridden)\n // We will try to merge and see if there is a conflict\n\n legends[channel] = mergeLegendComponent(legends[channel], child.component.legends[channel]);\n\n if (!legends[channel]) {\n // If merge returns nothing, there is a conflict so we cannot make the legend shared.\n // Thus, mark legend as independent and remove the legend component.\n resolve.legend[channel] = 'independent';\n delete legends[channel];\n }\n }\n }\n }\n\n for (const channel of keys(legends)) {\n for (const child of model.children) {\n if (!child.component.legends[channel]) {\n // skip if the child does not have a particular legend\n continue;\n }\n\n if (resolve.legend[channel] === 'shared') {\n // After merging shared legend, make sure to remove legend from child\n delete child.component.legends[channel];\n }\n }\n }\n\n return legends;\n}\n\nexport function mergeLegendComponent(mergedLegend: LegendComponent, childLegend: LegendComponent): LegendComponent {\n if (!mergedLegend) {\n return childLegend.clone();\n }\n const mergedOrient = mergedLegend.getWithExplicit('orient');\n const childOrient = childLegend.getWithExplicit('orient');\n\n if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {\n // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)\n // Cannot merge due to inconsistent orient\n return undefined;\n }\n\n let typeMerged = false;\n // Otherwise, let's merge\n for (const prop of LEGEND_COMPONENT_PROPERTIES) {\n const mergedValueWithExplicit = mergeValuesWithExplicit(\n mergedLegend.getWithExplicit(prop),\n childLegend.getWithExplicit(prop),\n prop,\n 'legend',\n\n // Tie breaker function\n (v1: Explicit, v2: Explicit): any => {\n switch (prop) {\n case 'symbolType':\n return mergeSymbolType(v1, v2);\n case 'title':\n return mergeTitleComponent(v1, v2);\n case 'type':\n // There are only two types. If we have different types, then prefer symbol over gradient.\n typeMerged = true;\n return makeImplicit('symbol');\n }\n return defaultTieBreaker(v1, v2, prop, 'legend');\n }\n );\n mergedLegend.setWithExplicit(prop, mergedValueWithExplicit);\n }\n if (typeMerged) {\n if (mergedLegend.implicit?.encode?.gradient) {\n deleteNestedProperty(mergedLegend.implicit, ['encode', 'gradient']);\n }\n if (mergedLegend.explicit?.encode?.gradient) {\n deleteNestedProperty(mergedLegend.explicit, ['encode', 'gradient']);\n }\n }\n\n return mergedLegend;\n}\n\nfunction mergeSymbolType(st1: Explicit, st2: Explicit) {\n if (st2.value === 'circle') {\n // prefer \"circle\" over \"stroke\"\n return st2;\n }\n return st1;\n}\n","import {Legend as VgLegend, LegendEncode} from 'vega';\nimport {Config} from '../../config';\nimport {LEGEND_SCALE_CHANNELS} from '../../legend';\nimport {keys, replaceAll, stringify, vals} from '../../util';\nimport {isSignalRef, VgEncodeChannel, VgValueRef} from '../../vega.schema';\nimport {Model} from '../model';\nimport {LegendComponent} from './component';\nimport {mergeLegendComponent} from './parse';\n\nfunction setLegendEncode(\n legend: VgLegend,\n part: keyof LegendEncode,\n vgProp: VgEncodeChannel,\n vgRef: VgValueRef | VgValueRef[]\n) {\n legend.encode ??= {};\n legend.encode[part] ??= {};\n legend.encode[part].update ??= {};\n // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291\n (legend.encode[part].update[vgProp] as any) = vgRef;\n}\n\nexport function assembleLegends(model: Model): VgLegend[] {\n const legendComponentIndex = model.component.legends;\n const legendByDomain: Record = {};\n\n for (const channel of keys(legendComponentIndex)) {\n const scaleComponent = model.getScaleComponent(channel);\n const domainHash = stringify(scaleComponent.get('domains'));\n if (legendByDomain[domainHash]) {\n for (const mergedLegendComponent of legendByDomain[domainHash]) {\n const merged = mergeLegendComponent(mergedLegendComponent, legendComponentIndex[channel]);\n if (!merged) {\n // If cannot merge, need to add this legend separately\n legendByDomain[domainHash].push(legendComponentIndex[channel]);\n }\n }\n } else {\n legendByDomain[domainHash] = [legendComponentIndex[channel].clone()];\n }\n }\n\n const legends = vals(legendByDomain)\n .flat()\n .map(l => assembleLegend(l, model.config))\n .filter(l => l !== undefined);\n\n return legends;\n}\n\nexport function assembleLegend(legendCmpt: LegendComponent, config: Config) {\n const {disable, labelExpr, selections, ...legend} = legendCmpt.combine();\n\n if (disable) {\n return undefined;\n }\n\n if (config.aria === false && legend.aria == undefined) {\n legend.aria = false;\n }\n\n if (legend.encode?.symbols) {\n const out = legend.encode.symbols.update;\n if (out.fill && out.fill['value'] !== 'transparent' && !out.stroke && !legend.stroke) {\n // For non color channel's legend, we need to override symbol stroke config from Vega config if stroke channel is not used.\n out.stroke = {value: 'transparent'};\n }\n\n // Remove properties that the legend is encoding.\n for (const property of LEGEND_SCALE_CHANNELS) {\n if (legend[property]) {\n delete out[property];\n }\n }\n }\n\n if (!legend.title) {\n // title schema doesn't include null, ''\n delete legend.title;\n }\n\n if (labelExpr !== undefined) {\n let expr = labelExpr;\n if (legend.encode?.labels?.update && isSignalRef(legend.encode.labels.update.text)) {\n expr = replaceAll(labelExpr, 'datum.label', legend.encode.labels.update.text.signal);\n }\n setLegendEncode(legend, 'labels', 'text', {signal: expr});\n }\n\n return legend;\n}\n","import {Projection as VgProjection, SignalRef} from 'vega';\nimport {contains} from '../../util';\nimport {isSignalRef} from '../../vega.schema';\nimport {isConcatModel, isLayerModel, Model} from '../model';\n\nexport function assembleProjections(model: Model): VgProjection[] {\n if (isLayerModel(model) || isConcatModel(model)) {\n return assembleProjectionsForModelAndChildren(model);\n } else {\n return assembleProjectionForModel(model);\n }\n}\n\nexport function assembleProjectionsForModelAndChildren(model: Model): VgProjection[] {\n return model.children.reduce((projections, child) => {\n return projections.concat(child.assembleProjections());\n }, assembleProjectionForModel(model));\n}\n\nexport function assembleProjectionForModel(model: Model): VgProjection[] {\n const component = model.component.projection;\n if (!component || component.merged) {\n return [];\n }\n\n const projection = component.combine();\n const {name} = projection; // we need to extract name so that it is always present in the output and pass TS type validation\n\n if (!component.data) {\n // generate custom projection, no automatic fitting\n return [\n {\n name,\n // translate to center by default\n translate: {signal: '[width / 2, height / 2]'},\n // parameters, overwrite default translate if specified\n ...projection\n }\n ];\n } else {\n // generate projection that uses extent fitting\n const size: SignalRef = {\n signal: `[${component.size.map(ref => ref.signal).join(', ')}]`\n };\n\n const fits: string[] = component.data.reduce((sources, data) => {\n const source: string = isSignalRef(data) ? data.signal : `data('${model.lookupDataSource(data)}')`;\n if (!contains(sources, source)) {\n // build a unique list of sources\n sources.push(source);\n }\n return sources;\n }, []);\n\n if (fits.length <= 0) {\n throw new Error(\"Projection's fit didn't find any data sources\");\n }\n\n return [\n {\n name,\n size,\n fit: {\n signal: fits.length > 1 ? `[${fits.join(', ')}]` : fits[0]\n },\n ...projection\n }\n ];\n }\n}\n","import {BaseProjection, SignalRef, Vector2} from 'vega';\nimport {ExprRef} from './expr';\nimport {MapExcludeValueRefAndReplaceSignalWith, ProjectionType} from './vega.schema';\n\nexport interface Projection\n extends MapExcludeValueRefAndReplaceSignalWith {\n /**\n * The cartographic projection to use. This value is case-insensitive, for example `\"albers\"` and `\"Albers\"` indicate the same projection type. You can find all valid projection types [in the documentation](https://vega.github.io/vega-lite/docs/projection.html#projection-types).\n *\n * __Default value:__ `equalEarth`\n */\n type?: ProjectionType | ES; // Re-declare to override docs\n\n /**\n * The projection’s scale (zoom) factor, overriding automatic fitting. The default scale is projection-specific. The scale factor corresponds linearly to the distance between projected points; however, scale factor values are not equivalent across projections.\n */\n scale?: number | ES; // Re-declare to override docs\n\n /**\n * The projection’s translation offset as a two-element array `[tx, ty]`.\n */\n translate?: Vector2 | ES; // TODO: figure what's VL default value\n}\n\n/**\n * Any property of Projection can be in config\n */\nexport type ProjectionConfig = Projection;\n\nexport const PROJECTION_PROPERTIES: (keyof Projection)[] = [\n 'type',\n 'clipAngle',\n 'clipExtent',\n 'center',\n 'rotate',\n 'precision',\n 'reflectX',\n 'reflectY',\n 'coefficient',\n 'distance',\n 'fraction',\n 'lobes',\n 'parallel',\n 'radius',\n 'ratio',\n 'spacing',\n 'tilt'\n];\n","import {Projection as VgProjection, SignalRef} from 'vega';\nimport {Projection} from '../../projection';\nimport {Split} from '../split';\n\nexport class ProjectionComponent extends Split {\n public merged = false;\n\n constructor(\n name: string,\n public specifiedProjection: Projection,\n public size: SignalRef[],\n public data: (string | SignalRef)[]\n ) {\n super(\n {...specifiedProjection}, // all explicit properties of projection\n {name} // name as initial implicit property\n );\n }\n\n /**\n * Whether the projection parameters should fit provided data.\n */\n public get isFit() {\n return !!this.data;\n }\n}\n","import type {SignalRef} from 'vega';\nimport {hasOwnProperty} from 'vega-util';\nimport {LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2, SHAPE} from '../../channel';\nimport {getFieldOrDatumDef} from '../../channeldef';\nimport {DataSourceType} from '../../data';\nimport {replaceExprRef} from '../../expr';\nimport {PROJECTION_PROPERTIES} from '../../projection';\nimport {GEOJSON} from '../../type';\nimport {deepEqual, duplicate, every} from '../../util';\nimport {isUnitModel, Model} from '../model';\nimport {UnitModel} from '../unit';\nimport {ProjectionComponent} from './component';\n\nexport function parseProjection(model: Model) {\n model.component.projection = isUnitModel(model) ? parseUnitProjection(model) : parseNonUnitProjections(model);\n}\n\nfunction parseUnitProjection(model: UnitModel): ProjectionComponent {\n if (model.hasProjection) {\n const proj = replaceExprRef(model.specifiedProjection);\n const fit = !(proj && (proj.scale != null || proj.translate != null));\n const size = fit ? [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')] : undefined;\n const data = fit ? gatherFitData(model) : undefined;\n\n const projComp = new ProjectionComponent(\n model.projectionName(true),\n {\n ...replaceExprRef(model.config.projection),\n ...proj\n },\n size,\n data\n );\n\n if (!projComp.get('type')) {\n projComp.set('type', 'equalEarth', false);\n }\n\n return projComp;\n }\n\n return undefined;\n}\n\nfunction gatherFitData(model: UnitModel) {\n const data: (SignalRef | string)[] = [];\n\n const {encoding} = model;\n\n for (const posssiblePair of [\n [LONGITUDE, LATITUDE],\n [LONGITUDE2, LATITUDE2]\n ]) {\n if (getFieldOrDatumDef(encoding[posssiblePair[0]]) || getFieldOrDatumDef(encoding[posssiblePair[1]])) {\n data.push({\n signal: model.getName(`geojson_${data.length}`)\n });\n }\n }\n\n if (model.channelHasField(SHAPE) && model.typedFieldDef(SHAPE).type === GEOJSON) {\n data.push({\n signal: model.getName(`geojson_${data.length}`)\n });\n }\n\n if (data.length === 0) {\n // main source is geojson, so we can just use that\n data.push(model.requestDataName(DataSourceType.Main));\n }\n\n return data;\n}\n\nfunction mergeIfNoConflict(first: ProjectionComponent, second: ProjectionComponent): ProjectionComponent {\n const allPropertiesShared = every(PROJECTION_PROPERTIES, prop => {\n // neither has the property\n if (!hasOwnProperty(first.explicit, prop) && !hasOwnProperty(second.explicit, prop)) {\n return true;\n }\n // both have property and an equal value for property\n if (\n hasOwnProperty(first.explicit, prop) &&\n hasOwnProperty(second.explicit, prop) &&\n // some properties might be signals or objects and require hashing for comparison\n deepEqual(first.get(prop), second.get(prop))\n ) {\n return true;\n }\n return false;\n });\n\n const size = deepEqual(first.size, second.size);\n if (size) {\n if (allPropertiesShared) {\n return first;\n } else if (deepEqual(first.explicit, {})) {\n return second;\n } else if (deepEqual(second.explicit, {})) {\n return first;\n }\n }\n\n // if all properties don't match, let each unit spec have its own projection\n return null;\n}\n\nfunction parseNonUnitProjections(model: Model): ProjectionComponent {\n if (model.children.length === 0) {\n return undefined;\n }\n\n let nonUnitProjection: ProjectionComponent;\n\n // parse all children first\n for (const child of model.children) {\n parseProjection(child);\n }\n\n // analyze parsed projections, attempt to merge\n const mergable = every(model.children, child => {\n const projection = child.component.projection;\n if (!projection) {\n // child layer does not use a projection\n return true;\n } else if (!nonUnitProjection) {\n // cached 'projection' is null, cache this one\n nonUnitProjection = projection;\n return true;\n } else {\n const merge = mergeIfNoConflict(nonUnitProjection, projection);\n if (merge) {\n nonUnitProjection = merge;\n }\n return !!merge;\n }\n });\n\n // if cached one and all other children share the same projection,\n if (nonUnitProjection && mergable) {\n // so we can elevate it to the layer level\n const name = model.projectionName(true);\n const modelProjection = new ProjectionComponent(\n name,\n nonUnitProjection.specifiedProjection,\n nonUnitProjection.size,\n duplicate(nonUnitProjection.data)\n );\n\n // rename and assign all others as merged\n for (const child of model.children) {\n const projection = child.component.projection;\n if (projection) {\n if (projection.isFit) {\n modelProjection.data.push(...child.component.projection.data);\n }\n child.renameProjection(projection.get('name'), name);\n projection.merged = true;\n }\n }\n\n return modelProjection;\n }\n\n return undefined;\n}\n","import {BinTransform as VgBinTransform, Transforms as VgTransform} from 'vega';\nimport {isString} from 'vega-util';\nimport {BinParams, binToString, isBinning, isParameterExtent} from '../../bin';\nimport {Channel} from '../../channel';\nimport {binRequiresRange, FieldName, isTypedFieldDef, normalizeBin, TypedFieldDef, vgField} from '../../channeldef';\nimport {Config} from '../../config';\nimport {BinTransform} from '../../transform';\nimport {Dict, duplicate, hash, isEmpty, keys, replacePathInField, unique, vals} from '../../util';\nimport {binFormatExpression} from '../format';\nimport {isUnitModel, Model, ModelWithField} from '../model';\nimport {parseSelectionExtent} from '../selection/parse';\nimport {NonPositionScaleChannel, PositionChannel} from './../../channel';\nimport {DataFlowNode} from './dataflow';\n\nfunction rangeFormula(model: ModelWithField, fieldDef: TypedFieldDef, channel: Channel, config: Config) {\n if (binRequiresRange(fieldDef, channel)) {\n // read format from axis or legend, if there is no format then use config.numberFormat\n\n const guide = isUnitModel(model)\n ? model.axis(channel as PositionChannel) ?? model.legend(channel as NonPositionScaleChannel) ?? {}\n : {};\n\n const startField = vgField(fieldDef, {expr: 'datum'});\n const endField = vgField(fieldDef, {expr: 'datum', binSuffix: 'end'});\n\n return {\n formulaAs: vgField(fieldDef, {binSuffix: 'range', forAs: true}),\n formula: binFormatExpression(startField, endField, guide.format, guide.formatType, config)\n };\n }\n return {};\n}\n\nfunction binKey(bin: BinParams, field: string) {\n return `${binToString(bin)}_${field}`;\n}\n\nfunction getSignalsFromModel(model: Model, key: string) {\n return {\n signal: model.getName(`${key}_bins`),\n extentSignal: model.getName(`${key}_extent`)\n };\n}\n\nexport function getBinSignalName(model: Model, field: string, bin: boolean | BinParams) {\n const normalizedBin = normalizeBin(bin, undefined) ?? {};\n const key = binKey(normalizedBin, field);\n return model.getName(`${key}_bins`);\n}\n\nfunction isBinTransform(t: TypedFieldDef | BinTransform): t is BinTransform {\n return 'as' in t;\n}\n\nfunction createBinComponent(t: TypedFieldDef | BinTransform, bin: boolean | BinParams, model: Model) {\n let as: [string, string];\n let span: string;\n\n if (isBinTransform(t)) {\n as = isString(t.as) ? [t.as, `${t.as}_end`] : [t.as[0], t.as[1]];\n } else {\n as = [vgField(t, {forAs: true}), vgField(t, {binSuffix: 'end', forAs: true})];\n }\n\n const normalizedBin = {...normalizeBin(bin, undefined)};\n const key = binKey(normalizedBin, t.field);\n const {signal, extentSignal} = getSignalsFromModel(model, key);\n\n if (isParameterExtent(normalizedBin.extent)) {\n const ext = normalizedBin.extent;\n span = parseSelectionExtent(model, ext.param, ext);\n delete normalizedBin.extent; // Vega-Lite selection extent map to Vega's span property.\n }\n\n const binComponent: BinComponent = {\n bin: normalizedBin,\n field: t.field,\n as: [as],\n ...(signal ? {signal} : {}),\n ...(extentSignal ? {extentSignal} : {}),\n ...(span ? {span} : {})\n };\n\n return {key, binComponent};\n}\n\nexport interface BinComponent {\n bin: BinParams;\n field: FieldName;\n extentSignal?: string;\n signal?: string;\n span?: string;\n\n /** Pairs of strings of the names of start and end signals */\n as: [string, string][];\n\n // Range Formula\n\n formula?: string;\n formulaAs?: string;\n}\n\nexport class BinNode extends DataFlowNode {\n public clone() {\n return new BinNode(null, duplicate(this.bins));\n }\n\n constructor(\n parent: DataFlowNode,\n private bins: Dict\n ) {\n super(parent);\n }\n\n public static makeFromEncoding(parent: DataFlowNode, model: ModelWithField) {\n const bins = model.reduceFieldDef((binComponentIndex: Dict, fieldDef, channel) => {\n if (isTypedFieldDef(fieldDef) && isBinning(fieldDef.bin)) {\n const {key, binComponent} = createBinComponent(fieldDef, fieldDef.bin, model);\n binComponentIndex[key] = {\n ...binComponent,\n ...binComponentIndex[key],\n ...rangeFormula(model, fieldDef, channel, model.config)\n };\n }\n return binComponentIndex;\n }, {} as Dict);\n\n if (isEmpty(bins)) {\n return null;\n }\n\n return new BinNode(parent, bins);\n }\n\n /**\n * Creates a bin node from BinTransform.\n * The optional parameter should provide\n */\n public static makeFromTransform(parent: DataFlowNode, t: BinTransform, model: Model) {\n const {key, binComponent} = createBinComponent(t, t.bin, model);\n return new BinNode(parent, {\n [key]: binComponent\n });\n }\n\n /**\n * Merge bin nodes. This method either integrates the bin config from the other node\n * or if this node already has a bin config, renames the corresponding signal in the model.\n */\n public merge(other: BinNode, renameSignal: (s1: string, s2: string) => void) {\n for (const key of keys(other.bins)) {\n if (key in this.bins) {\n renameSignal(other.bins[key].signal, this.bins[key].signal);\n // Ensure that we don't have duplicate names for signal pairs\n this.bins[key].as = unique([...this.bins[key].as, ...other.bins[key].as], hash);\n } else {\n this.bins[key] = other.bins[key];\n }\n }\n\n for (const child of other.children) {\n other.removeChild(child);\n child.parent = this;\n }\n other.remove();\n }\n\n public producedFields() {\n return new Set(\n vals(this.bins)\n .map(c => c.as)\n .flat(2)\n );\n }\n\n public dependentFields() {\n return new Set(vals(this.bins).map(c => c.field));\n }\n\n public hash() {\n return `Bin ${hash(this.bins)}`;\n }\n\n public assemble(): VgTransform[] {\n return vals(this.bins).flatMap(bin => {\n const transform: VgTransform[] = [];\n\n const [binAs, ...remainingAs] = bin.as;\n const {extent, ...params} = bin.bin;\n const binTrans: VgBinTransform = {\n type: 'bin',\n field: replacePathInField(bin.field),\n as: binAs,\n signal: bin.signal,\n ...(!isParameterExtent(extent) ? {extent} : {extent: null}),\n ...(bin.span ? {span: {signal: `span(${bin.span})`}} : {}),\n ...params\n };\n\n if (!extent && bin.extentSignal) {\n transform.push({\n type: 'extent',\n field: replacePathInField(bin.field),\n signal: bin.extentSignal\n });\n binTrans.extent = {signal: bin.extentSignal};\n }\n\n transform.push(binTrans);\n\n for (const as of remainingAs) {\n for (let i = 0; i < 2; i++) {\n transform.push({\n type: 'formula',\n expr: vgField({field: binAs[i]}, {expr: 'datum'}),\n as: as[i]\n });\n }\n }\n\n if (bin.formula) {\n transform.push({\n type: 'formula',\n expr: bin.formula,\n as: bin.formulaAs\n });\n }\n return transform;\n });\n }\n}\n","import {AggregateOp, AggregateTransform as VgAggregateTransform} from 'vega';\nimport {isArgmaxDef, isArgminDef} from '../../aggregate';\nimport {\n Channel,\n getPositionChannelFromLatLong,\n getSecondaryRangeChannel,\n isGeoPositionChannel,\n isScaleChannel,\n isXorY\n} from '../../channel';\nimport {\n binRequiresRange,\n FieldDef,\n getBandPosition,\n hasBandEnd,\n isScaleFieldDef,\n isTypedFieldDef,\n vgField\n} from '../../channeldef';\nimport * as log from '../../log';\nimport {isFieldRange} from '../../scale';\nimport {AggregateTransform} from '../../transform';\nimport {Dict, duplicate, hash, keys, replacePathInField, setEqual} from '../../util';\nimport {isUnitModel, ModelWithField} from '../model';\nimport {UnitModel} from '../unit';\nimport {DataFlowNode} from './dataflow';\nimport {isRectBasedMark} from '../../mark';\nimport {OFFSETTED_RECT_END_SUFFIX, OFFSETTED_RECT_START_SUFFIX} from './timeunit';\n\ntype Measures = Dict>>>;\n\nfunction addDimension(dims: Set, channel: Channel, fieldDef: FieldDef, model: ModelWithField) {\n const channelDef2 = isUnitModel(model) ? model.encoding[getSecondaryRangeChannel(channel)] : undefined;\n\n if (\n isTypedFieldDef(fieldDef) &&\n isUnitModel(model) &&\n hasBandEnd(fieldDef, channelDef2, model.markDef, model.config)\n ) {\n dims.add(vgField(fieldDef, {}));\n dims.add(vgField(fieldDef, {suffix: 'end'}));\n\n const {mark, markDef, config} = model;\n\n const bandPosition = getBandPosition({fieldDef, markDef, config});\n\n if (isRectBasedMark(mark) && bandPosition !== 0.5 && isXorY(channel)) {\n dims.add(vgField(fieldDef, {suffix: OFFSETTED_RECT_START_SUFFIX}));\n dims.add(vgField(fieldDef, {suffix: OFFSETTED_RECT_END_SUFFIX}));\n }\n\n if (fieldDef.bin && binRequiresRange(fieldDef, channel)) {\n dims.add(vgField(fieldDef, {binSuffix: 'range'}));\n }\n } else if (isGeoPositionChannel(channel)) {\n const posChannel = getPositionChannelFromLatLong(channel);\n dims.add(model.getName(posChannel));\n } else {\n dims.add(vgField(fieldDef));\n }\n if (isScaleFieldDef(fieldDef) && isFieldRange(fieldDef.scale?.range)) {\n dims.add(fieldDef.scale.range.field);\n }\n return dims;\n}\n\nfunction mergeMeasures(parentMeasures: Measures, childMeasures: Measures) {\n for (const field of keys(childMeasures)) {\n // when we merge a measure, we either have to add an aggregation operator or even a new field\n const ops = childMeasures[field];\n for (const op of keys(ops)) {\n if (field in parentMeasures) {\n // add operator to existing measure field\n parentMeasures[field][op] = new Set([...(parentMeasures[field][op] ?? []), ...ops[op]]);\n } else {\n parentMeasures[field] = {[op]: ops[op]};\n }\n }\n }\n}\n\nexport class AggregateNode extends DataFlowNode {\n public clone() {\n return new AggregateNode(null, new Set(this.dimensions), duplicate(this.measures));\n }\n\n /**\n * @param dimensions string set for dimensions\n * @param measures dictionary mapping field name => dict of aggregation functions and names to use\n */\n constructor(\n parent: DataFlowNode,\n private dimensions: Set,\n private measures: Measures\n ) {\n super(parent);\n }\n\n get groupBy() {\n return this.dimensions;\n }\n\n public static makeFromEncoding(parent: DataFlowNode, model: UnitModel): AggregateNode {\n let isAggregate = false;\n model.forEachFieldDef(fd => {\n if (fd.aggregate) {\n isAggregate = true;\n }\n });\n\n const meas: Measures = {};\n const dims = new Set();\n\n if (!isAggregate) {\n // no need to create this node if the model has no aggregation\n return null;\n }\n\n model.forEachFieldDef((fieldDef, channel: Channel) => {\n const {aggregate, field} = fieldDef;\n if (aggregate) {\n if (aggregate === 'count') {\n meas['*'] ??= {};\n meas['*']['count'] = new Set([vgField(fieldDef, {forAs: true})]);\n } else {\n if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {\n const op = isArgminDef(aggregate) ? 'argmin' : 'argmax';\n const argField = aggregate[op];\n meas[argField] ??= {};\n meas[argField][op] = new Set([vgField({op, field: argField}, {forAs: true})]);\n } else {\n meas[field] ??= {};\n meas[field][aggregate] = new Set([vgField(fieldDef, {forAs: true})]);\n }\n\n // For scale channel with domain === 'unaggregated', add min/max so we can use their union as unaggregated domain\n if (isScaleChannel(channel) && model.scaleDomain(channel) === 'unaggregated') {\n meas[field] ??= {};\n meas[field]['min'] = new Set([vgField({field, aggregate: 'min'}, {forAs: true})]);\n meas[field]['max'] = new Set([vgField({field, aggregate: 'max'}, {forAs: true})]);\n }\n }\n } else {\n addDimension(dims, channel, fieldDef, model);\n }\n });\n\n if (dims.size + keys(meas).length === 0) {\n return null;\n }\n\n return new AggregateNode(parent, dims, meas);\n }\n\n public static makeFromTransform(parent: DataFlowNode, t: AggregateTransform): AggregateNode {\n const dims = new Set();\n const meas: Measures = {};\n\n for (const s of t.aggregate) {\n const {op, field, as} = s;\n if (op) {\n if (op === 'count') {\n meas['*'] ??= {};\n meas['*']['count'] = new Set([as ? as : vgField(s, {forAs: true})]);\n } else {\n meas[field] ??= {};\n meas[field][op] ??= new Set();\n meas[field][op].add(as ? as : vgField(s, {forAs: true}));\n }\n }\n }\n\n for (const s of t.groupby ?? []) {\n dims.add(s);\n }\n\n if (dims.size + keys(meas).length === 0) {\n return null;\n }\n\n return new AggregateNode(parent, dims, meas);\n }\n\n public merge(other: AggregateNode): boolean {\n if (setEqual(this.dimensions, other.dimensions)) {\n mergeMeasures(this.measures, other.measures);\n return true;\n }\n log.debug('different dimensions, cannot merge');\n return false;\n }\n\n public addDimensions(fields: readonly string[]) {\n fields.forEach(this.dimensions.add, this.dimensions);\n }\n\n public dependentFields() {\n return new Set([...this.dimensions, ...keys(this.measures)]);\n }\n\n public producedFields() {\n const out = new Set();\n\n for (const field of keys(this.measures)) {\n for (const op of keys(this.measures[field])) {\n const m = this.measures[field][op];\n if (m.size === 0) {\n out.add(`${op}_${field}`);\n } else {\n m.forEach(out.add, out);\n }\n }\n }\n\n return out;\n }\n\n public hash() {\n return `Aggregate ${hash({dimensions: this.dimensions, measures: this.measures})}`;\n }\n\n public assemble(): VgAggregateTransform {\n const ops: AggregateOp[] = [];\n const fields: string[] = [];\n const as: string[] = [];\n\n for (const field of keys(this.measures)) {\n for (const op of keys(this.measures[field])) {\n for (const alias of this.measures[field][op]) {\n as.push(alias);\n ops.push(op);\n fields.push(field === '*' ? null : replacePathInField(field));\n }\n }\n }\n\n const result: VgAggregateTransform = {\n type: 'aggregate',\n groupby: [...this.dimensions].map(replacePathInField),\n ops,\n fields,\n as\n };\n\n return result;\n }\n}\n","import {AggregateOp} from 'vega';\nimport {isArray} from 'vega-util';\nimport {isBinning} from '../../bin';\nimport {COLUMN, FACET_CHANNELS, POSITION_SCALE_CHANNELS, ROW} from '../../channel';\nimport {vgField} from '../../channeldef';\nimport * as log from '../../log';\nimport {hasDiscreteDomain} from '../../scale';\nimport {DEFAULT_SORT_OP, EncodingSortField, isSortField} from '../../sort';\nimport {hash} from '../../util';\nimport {isVgRangeStep, VgData} from '../../vega.schema';\nimport {FacetModel} from '../facet';\nimport {HEADER_CHANNELS, HEADER_TYPES} from '../header/component';\nimport {Model} from '../model';\nimport {assembleDomain, getFieldFromDomain} from '../scale/domain';\nimport {sortArrayIndexField} from './calculate';\nimport {DataFlowNode} from './dataflow';\n\ninterface ChildIndependentFieldsWithStep {\n x?: string;\n y?: string;\n}\n\ninterface FacetChannelInfo {\n name: string;\n fields: string[];\n sortField?: EncodingSortField;\n\n sortIndexField?: string;\n}\n\n/**\n * A node that helps us track what fields we are faceting by.\n */\nexport class FacetNode extends DataFlowNode {\n private readonly column: FacetChannelInfo;\n\n private readonly row: FacetChannelInfo;\n\n private readonly facet: FacetChannelInfo;\n\n private readonly childModel: Model;\n\n /**\n * @param model The facet model.\n * @param name The name that this facet source will have.\n * @param data The source data for this facet data.\n */\n public constructor(\n parent: DataFlowNode,\n public readonly model: FacetModel,\n public readonly name: string,\n public data: string\n ) {\n super(parent);\n\n for (const channel of FACET_CHANNELS) {\n const fieldDef = model.facet[channel];\n if (fieldDef) {\n const {bin, sort} = fieldDef;\n this[channel] = {\n name: model.getName(`${channel}_domain`),\n fields: [vgField(fieldDef), ...(isBinning(bin) ? [vgField(fieldDef, {binSuffix: 'end'})] : [])],\n ...(isSortField(sort)\n ? {sortField: sort}\n : isArray(sort)\n ? {sortIndexField: sortArrayIndexField(fieldDef, channel)}\n : {})\n };\n }\n }\n this.childModel = model.child;\n }\n\n public hash() {\n let out = `Facet`;\n\n for (const channel of FACET_CHANNELS) {\n if (this[channel]) {\n out += ` ${channel.charAt(0)}:${hash(this[channel])}`;\n }\n }\n\n return out;\n }\n\n get fields() {\n const f: string[] = [];\n\n for (const channel of FACET_CHANNELS) {\n if (this[channel]?.fields) {\n f.push(...this[channel].fields);\n }\n }\n return f;\n }\n\n public dependentFields() {\n const depFields = new Set(this.fields);\n\n for (const channel of FACET_CHANNELS) {\n if (this[channel]) {\n if (this[channel].sortField) {\n depFields.add(this[channel].sortField.field);\n }\n if (this[channel].sortIndexField) {\n depFields.add(this[channel].sortIndexField);\n }\n }\n }\n\n return depFields;\n }\n\n public producedFields() {\n return new Set(); // facet does not produce any new fields\n }\n\n /**\n * The name to reference this source is its name.\n */\n public getSource() {\n return this.name;\n }\n\n private getChildIndependentFieldsWithStep() {\n const childIndependentFieldsWithStep: ChildIndependentFieldsWithStep = {};\n\n for (const channel of POSITION_SCALE_CHANNELS) {\n const childScaleComponent = this.childModel.component.scales[channel];\n if (childScaleComponent && !childScaleComponent.merged) {\n // independent scale\n const type = childScaleComponent.get('type');\n const range = childScaleComponent.get('range');\n\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const domain = assembleDomain(this.childModel, channel);\n const field = getFieldFromDomain(domain);\n if (field) {\n childIndependentFieldsWithStep[channel] = field;\n } else {\n log.warn(log.message.unknownField(channel));\n }\n }\n }\n }\n\n return childIndependentFieldsWithStep;\n }\n\n private assembleRowColumnHeaderData(\n channel: 'row' | 'column' | 'facet',\n crossedDataName: string,\n childIndependentFieldsWithStep: ChildIndependentFieldsWithStep\n ): VgData {\n const childChannel = {row: 'y', column: 'x', facet: undefined}[channel];\n\n const fields: string[] = [];\n const ops: AggregateOp[] = [];\n const as: string[] = [];\n\n if (childChannel && childIndependentFieldsWithStep && childIndependentFieldsWithStep[childChannel]) {\n if (crossedDataName) {\n // If there is a crossed data, calculate max\n fields.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);\n\n ops.push('max');\n } else {\n // If there is no crossed data, just calculate distinct\n fields.push(childIndependentFieldsWithStep[childChannel]);\n ops.push('distinct');\n }\n // Although it is technically a max, just name it distinct so it's easier to refer to it\n as.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);\n }\n\n const {sortField, sortIndexField} = this[channel];\n if (sortField) {\n const {op = DEFAULT_SORT_OP, field} = sortField;\n fields.push(field);\n ops.push(op);\n as.push(vgField(sortField, {forAs: true}));\n } else if (sortIndexField) {\n fields.push(sortIndexField);\n ops.push('max');\n as.push(sortIndexField);\n }\n\n return {\n name: this[channel].name,\n // Use data from the crossed one if it exist\n source: crossedDataName ?? this.data,\n transform: [\n {\n type: 'aggregate',\n groupby: this[channel].fields,\n ...(fields.length\n ? {\n fields,\n ops,\n as\n }\n : {})\n }\n ]\n };\n }\n\n private assembleFacetHeaderData(childIndependentFieldsWithStep: ChildIndependentFieldsWithStep) {\n const {columns} = this.model.layout;\n const {layoutHeaders} = this.model.component;\n const data: VgData[] = [];\n\n const hasSharedAxis: {row?: true; column?: true} = {};\n for (const headerChannel of HEADER_CHANNELS) {\n for (const headerType of HEADER_TYPES) {\n const headers = (layoutHeaders[headerChannel] && layoutHeaders[headerChannel][headerType]) ?? [];\n for (const header of headers) {\n if (header.axes?.length > 0) {\n hasSharedAxis[headerChannel] = true;\n break;\n }\n }\n }\n\n if (hasSharedAxis[headerChannel]) {\n const cardinality = `length(data(\"${this.facet.name}\"))`;\n\n const stop =\n headerChannel === 'row'\n ? columns\n ? {signal: `ceil(${cardinality} / ${columns})`}\n : 1\n : columns\n ? {signal: `min(${cardinality}, ${columns})`}\n : {signal: cardinality};\n\n data.push({\n name: `${this.facet.name}_${headerChannel}`,\n transform: [\n {\n type: 'sequence',\n start: 0,\n stop\n }\n ]\n });\n }\n }\n\n const {row, column} = hasSharedAxis;\n\n if (row || column) {\n data.unshift(this.assembleRowColumnHeaderData('facet', null, childIndependentFieldsWithStep));\n }\n\n return data;\n }\n\n public assemble() {\n const data: VgData[] = [];\n let crossedDataName = null;\n const childIndependentFieldsWithStep = this.getChildIndependentFieldsWithStep();\n\n const {column, row, facet} = this;\n\n if (column && row && (childIndependentFieldsWithStep.x || childIndependentFieldsWithStep.y)) {\n // Need to create a cross dataset to correctly calculate cardinality\n crossedDataName = `cross_${this.column.name}_${this.row.name}`;\n\n const fields: string[] = [].concat(\n childIndependentFieldsWithStep.x ?? [],\n childIndependentFieldsWithStep.y ?? []\n );\n const ops = fields.map((): AggregateOp => 'distinct');\n\n data.push({\n name: crossedDataName,\n source: this.data,\n transform: [\n {\n type: 'aggregate',\n groupby: this.fields,\n fields,\n ops\n }\n ]\n });\n }\n\n for (const channel of [COLUMN, ROW]) {\n if (this[channel]) {\n data.push(this.assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep));\n }\n }\n\n if (facet) {\n const facetData = this.assembleFacetHeaderData(childIndependentFieldsWithStep);\n if (facetData) {\n data.push(...facetData);\n }\n }\n\n return data;\n }\n}\n","import {FormulaTransform as VgFormulaTransform, SignalRef} from 'vega';\nimport {isNumber, isString} from 'vega-util';\nimport {AncestorParse} from '.';\nimport {isMinMaxOp} from '../../aggregate';\nimport {getMainRangeChannel, SingleDefChannel} from '../../channel';\nimport {\n isFieldDef,\n isFieldOrDatumDefForTimeFormat,\n isScaleFieldDef,\n isTypedFieldDef,\n TypedFieldDef\n} from '../../channeldef';\nimport {isGenerator, Parse} from '../../data';\nimport {DateTime, isDateTime} from '../../datetime';\nimport * as log from '../../log';\nimport {forEachLeaf} from '../../logical';\nimport {isPathMark} from '../../mark';\nimport {\n isFieldEqualPredicate,\n isFieldGTEPredicate,\n isFieldGTPredicate,\n isFieldLTEPredicate,\n isFieldLTPredicate,\n isFieldOneOfPredicate,\n isFieldPredicate,\n isFieldRangePredicate\n} from '../../predicate';\nimport {isSortField} from '../../sort';\nimport {FilterTransform} from '../../transform';\nimport {accessPathDepth, accessPathWithDatum, Dict, duplicate, hash, keys, removePathFromField} from '../../util';\nimport {signalRefOrValue} from '../common';\nimport {isFacetModel, isUnitModel, Model} from '../model';\nimport {Split} from '../split';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * Remove quotes from a string.\n */\nfunction unquote(pattern: string) {\n if ((pattern.startsWith(\"'\") && pattern.endsWith(\"'\")) || (pattern.startsWith('\"') && pattern.endsWith('\"'))) {\n return pattern.slice(1, -1);\n }\n return pattern;\n}\n\n/**\n * @param field The field.\n * @param parse What to parse the field as.\n */\nfunction parseExpression(field: string, parse: string): string {\n const f = accessPathWithDatum(field);\n if (parse === 'number') {\n return `toNumber(${f})`;\n } else if (parse === 'boolean') {\n return `toBoolean(${f})`;\n } else if (parse === 'string') {\n return `toString(${f})`;\n } else if (parse === 'date') {\n return `toDate(${f})`;\n } else if (parse === 'flatten') {\n return f;\n } else if (parse.startsWith('date:')) {\n const specifier = unquote(parse.slice(5, parse.length));\n return `timeParse(${f},'${specifier}')`;\n } else if (parse.startsWith('utc:')) {\n const specifier = unquote(parse.slice(4, parse.length));\n return `utcParse(${f},'${specifier}')`;\n } else {\n log.warn(log.message.unrecognizedParse(parse));\n return null;\n }\n}\n\nexport function getImplicitFromFilterTransform(transform: FilterTransform) {\n const implicit: Dict = {};\n forEachLeaf(transform.filter, filter => {\n if (isFieldPredicate(filter)) {\n // Automatically add a parse node for filters with filter objects\n let val: string | number | boolean | DateTime | SignalRef = null;\n\n // For EqualFilter, just use the equal property.\n // For RangeFilter and OneOfFilter, all array members should have\n // the same type, so we only use the first one.\n if (isFieldEqualPredicate(filter)) {\n val = signalRefOrValue(filter.equal);\n } else if (isFieldLTEPredicate(filter)) {\n val = signalRefOrValue(filter.lte);\n } else if (isFieldLTPredicate(filter)) {\n val = signalRefOrValue(filter.lt);\n } else if (isFieldGTPredicate(filter)) {\n val = signalRefOrValue(filter.gt);\n } else if (isFieldGTEPredicate(filter)) {\n val = signalRefOrValue(filter.gte);\n } else if (isFieldRangePredicate(filter)) {\n val = filter.range[0];\n } else if (isFieldOneOfPredicate(filter)) {\n val = (filter.oneOf ?? filter['in'])[0];\n } // else -- for filter expression, we can't infer anything\n\n if (val) {\n if (isDateTime(val)) {\n implicit[filter.field] = 'date';\n } else if (isNumber(val)) {\n implicit[filter.field] = 'number';\n } else if (isString(val)) {\n implicit[filter.field] = 'string';\n }\n }\n\n if (filter.timeUnit) {\n implicit[filter.field] = 'date';\n }\n }\n });\n\n return implicit;\n}\n\n/**\n * Creates a parse node for implicit parsing from a model and updates ancestorParse.\n */\nexport function getImplicitFromEncoding(model: Model) {\n const implicit: Dict = {};\n\n function add(fieldDef: TypedFieldDef) {\n if (isFieldOrDatumDefForTimeFormat(fieldDef)) {\n implicit[fieldDef.field] = 'date';\n } else if (\n fieldDef.type === 'quantitative' &&\n isMinMaxOp(fieldDef.aggregate) // we need to parse numbers to support correct min and max\n ) {\n implicit[fieldDef.field] = 'number';\n } else if (accessPathDepth(fieldDef.field) > 1) {\n // For non-date/non-number (strings and booleans), derive a flattened field for a referenced nested field.\n // (Parsing numbers / dates already flattens numeric and temporal fields.)\n if (!(fieldDef.field in implicit)) {\n implicit[fieldDef.field] = 'flatten';\n }\n } else if (isScaleFieldDef(fieldDef) && isSortField(fieldDef.sort) && accessPathDepth(fieldDef.sort.field) > 1) {\n // Flatten fields that we sort by but that are not otherwise flattened.\n if (!(fieldDef.sort.field in implicit)) {\n implicit[fieldDef.sort.field] = 'flatten';\n }\n }\n }\n\n if (isUnitModel(model) || isFacetModel(model)) {\n // Parse encoded fields\n model.forEachFieldDef((fieldDef, channel) => {\n if (isTypedFieldDef(fieldDef)) {\n add(fieldDef);\n } else {\n const mainChannel = getMainRangeChannel(channel);\n const mainFieldDef = model.fieldDef(mainChannel as SingleDefChannel) as TypedFieldDef;\n add({\n ...fieldDef,\n type: mainFieldDef.type\n });\n }\n });\n }\n\n // Parse quantitative dimension fields of path marks as numbers so that we sort them correctly.\n if (isUnitModel(model)) {\n const {mark, markDef, encoding} = model;\n if (\n isPathMark(mark) &&\n // No need to sort by dimension if we have a connected scatterplot (order channel is present)\n !model.encoding.order\n ) {\n const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';\n const dimensionChannelDef = encoding[dimensionChannel];\n if (\n isFieldDef(dimensionChannelDef) &&\n dimensionChannelDef.type === 'quantitative' &&\n !(dimensionChannelDef.field in implicit)\n ) {\n implicit[dimensionChannelDef.field] = 'number';\n }\n }\n }\n\n return implicit;\n}\n\n/**\n * Creates a parse node for implicit parsing from a model and updates ancestorParse.\n */\nexport function getImplicitFromSelection(model: Model) {\n const implicit: Dict = {};\n\n if (isUnitModel(model) && model.component.selection) {\n for (const name of keys(model.component.selection)) {\n const selCmpt = model.component.selection[name];\n for (const proj of selCmpt.project.items) {\n if (!proj.channel && accessPathDepth(proj.field) > 1) {\n implicit[proj.field] = 'flatten';\n }\n }\n }\n }\n\n return implicit;\n}\n\nexport class ParseNode extends DataFlowNode {\n private _parse: Parse;\n\n public clone() {\n return new ParseNode(null, duplicate(this._parse));\n }\n\n constructor(parent: DataFlowNode, parse: Parse) {\n super(parent);\n\n this._parse = parse;\n }\n\n public hash() {\n return `Parse ${hash(this._parse)}`;\n }\n\n /**\n * Creates a parse node from a data.format.parse and updates ancestorParse.\n */\n public static makeExplicit(parent: DataFlowNode, model: Model, ancestorParse: AncestorParse) {\n // Custom parse\n let explicit = {};\n const data = model.data;\n if (!isGenerator(data) && data?.format?.parse) {\n explicit = data.format.parse;\n }\n\n return this.makeWithAncestors(parent, explicit, {}, ancestorParse);\n }\n\n /**\n * Creates a parse node from \"explicit\" parse and \"implicit\" parse and updates ancestorParse.\n */\n public static makeWithAncestors(\n parent: DataFlowNode,\n explicit: Parse,\n implicit: Parse,\n ancestorParse: AncestorParse\n ) {\n // We should not parse what has already been parsed in a parent (explicitly or implicitly) or what has been derived (maked as \"derived\"). We also don't need to flatten a field that has already been parsed.\n for (const field of keys(implicit)) {\n const parsedAs = ancestorParse.getWithExplicit(field);\n if (parsedAs.value !== undefined) {\n // We always ignore derived fields even if they are implicitly defined because we expect users to create the right types.\n if (\n parsedAs.explicit ||\n parsedAs.value === implicit[field] ||\n parsedAs.value === 'derived' ||\n implicit[field] === 'flatten'\n ) {\n delete implicit[field];\n } else {\n log.warn(log.message.differentParse(field, implicit[field], parsedAs.value));\n }\n }\n }\n\n for (const field of keys(explicit)) {\n const parsedAs = ancestorParse.get(field);\n if (parsedAs !== undefined) {\n // Don't parse a field again if it has been parsed with the same type already.\n if (parsedAs === explicit[field]) {\n delete explicit[field];\n } else {\n log.warn(log.message.differentParse(field, explicit[field], parsedAs));\n }\n }\n }\n\n const parse = new Split(explicit, implicit);\n\n // add the format parse from this model so that children don't parse the same field again\n ancestorParse.copyAll(parse);\n\n // copy only non-null parses\n const p: Dict = {};\n for (const key of keys(parse.combine())) {\n const val = parse.get(key);\n if (val !== null) {\n p[key] = val;\n }\n }\n\n if (keys(p).length === 0 || ancestorParse.parseNothing) {\n return null;\n }\n\n return new ParseNode(parent, p);\n }\n\n public get parse() {\n return this._parse;\n }\n\n public merge(other: ParseNode) {\n this._parse = {...this._parse, ...other.parse};\n other.remove();\n }\n\n /**\n * Assemble an object for Vega's format.parse property.\n */\n public assembleFormatParse() {\n const formatParse: Dict = {};\n for (const field of keys(this._parse)) {\n const p = this._parse[field];\n if (accessPathDepth(field) === 1) {\n formatParse[field] = p;\n }\n }\n return formatParse;\n }\n\n // format parse depends and produces all fields in its parse\n public producedFields() {\n return new Set(keys(this._parse));\n }\n\n public dependentFields() {\n return new Set(keys(this._parse));\n }\n\n public assembleTransforms(onlyNested = false): VgFormulaTransform[] {\n return keys(this._parse)\n .filter(field => (onlyNested ? accessPathDepth(field) > 1 : true))\n .map(field => {\n const expr = parseExpression(field, this._parse[field]);\n if (!expr) {\n return null;\n }\n\n const formula: VgFormulaTransform = {\n type: 'formula',\n expr,\n as: removePathFromField(field) // Vega output is always flattened\n };\n return formula;\n })\n .filter(t => t !== null);\n }\n}\n","import {SELECTION_ID} from '../../selection';\nimport {IdentifierTransform as VgIdentifierTransform} from 'vega';\nimport {DataFlowNode} from './dataflow';\n\nexport class IdentifierNode extends DataFlowNode {\n public clone() {\n return new IdentifierNode(null);\n }\n\n constructor(parent: DataFlowNode) {\n super(parent);\n }\n\n public dependentFields() {\n return new Set();\n }\n\n public producedFields() {\n return new Set([SELECTION_ID]);\n }\n\n public hash() {\n return 'Identifier';\n }\n\n public assemble(): VgIdentifierTransform {\n return {type: 'identifier', as: SELECTION_ID};\n }\n}\n","import {GraticuleTransform as VgGraticuleTransform} from 'vega';\nimport {GraticuleParams} from '../../data';\nimport {hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\nexport class GraticuleNode extends DataFlowNode {\n public clone() {\n return new GraticuleNode(null, this.params);\n }\n\n constructor(\n parent: DataFlowNode,\n private params: true | GraticuleParams\n ) {\n super(parent);\n }\n\n public dependentFields() {\n return new Set();\n }\n\n public producedFields(): undefined {\n return undefined; // there should never be a node before graticule\n }\n\n public hash() {\n return `Graticule ${hash(this.params)}`;\n }\n\n public assemble(): VgGraticuleTransform {\n return {\n type: 'graticule',\n ...(this.params === true ? {} : this.params)\n };\n }\n}\n","import {SequenceParams} from '../../data';\nimport {hash} from '../../util';\nimport {SequenceTransform as VgSequenceTransform} from 'vega';\nimport {DataFlowNode} from './dataflow';\n\nexport class SequenceNode extends DataFlowNode {\n public clone() {\n return new SequenceNode(null, this.params);\n }\n\n constructor(\n parent: DataFlowNode,\n private params: SequenceParams\n ) {\n super(parent);\n }\n\n public dependentFields() {\n return new Set();\n }\n\n public producedFields() {\n return new Set([this.params.as ?? 'data']);\n }\n\n public hash() {\n return `Hash ${hash(this.params)}`;\n }\n\n public assemble(): VgSequenceTransform {\n return {\n type: 'sequence',\n ...this.params\n };\n }\n}\n","import {\n Data,\n DataFormat,\n DataFormatType,\n isGenerator,\n isInlineData,\n isNamedData,\n isSphereGenerator,\n isUrlData\n} from '../../data';\nimport {contains, isEmpty, omit} from '../../util';\nimport {VgData} from '../../vega.schema';\nimport {DataFlowNode} from './dataflow';\n\nexport class SourceNode extends DataFlowNode {\n private _data: Partial;\n\n private _name: string;\n\n private _generator: boolean;\n\n constructor(data: Data) {\n super(null); // source cannot have parent\n\n data ??= {name: 'source'};\n let format;\n\n if (!isGenerator(data)) {\n format = data.format ? {...omit(data.format, ['parse'])} : ({} as DataFormat);\n }\n\n if (isInlineData(data)) {\n this._data = {values: data.values};\n } else if (isUrlData(data)) {\n this._data = {url: data.url};\n\n if (!format.type) {\n // Extract extension from URL using snippet from\n // http://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript\n let defaultExtension = /(?:\\.([^.]+))?$/.exec(data.url)[1];\n if (!contains(['json', 'csv', 'tsv', 'dsv', 'topojson'], defaultExtension)) {\n defaultExtension = 'json';\n }\n\n // defaultExtension has type string but we ensure that it is DataFormatType above\n format.type = defaultExtension as DataFormatType;\n }\n } else if (isSphereGenerator(data)) {\n // hardwire GeoJSON sphere data into output specification\n this._data = {values: [{type: 'Sphere'}]};\n } else if (isNamedData(data) || isGenerator(data)) {\n this._data = {};\n }\n\n // set flag to check if generator\n this._generator = isGenerator(data);\n\n // any dataset can be named\n if (data.name) {\n this._name = data.name;\n }\n\n if (format && !isEmpty(format)) {\n this._data.format = format;\n }\n }\n\n public dependentFields() {\n return new Set();\n }\n\n public producedFields(): undefined {\n return undefined; // we don't know what this source produces\n }\n\n get data() {\n return this._data;\n }\n\n public hasName(): boolean {\n return !!this._name;\n }\n\n get isGenerator() {\n return this._generator;\n }\n\n get dataName() {\n return this._name;\n }\n\n set dataName(name: string) {\n this._name = name;\n }\n\n set parent(parent: DataFlowNode) {\n throw new Error('Source nodes have to be roots.');\n }\n\n public remove() {\n throw new Error('Source nodes are roots and cannot be removed.');\n }\n\n public hash(): string | number {\n throw new Error('Cannot hash sources');\n }\n\n public assemble(): VgData {\n return {\n name: this._name,\n ...this._data,\n transform: []\n };\n }\n}\n","import {DataFlowNode} from './dataflow';\nimport {GraticuleNode} from './graticule';\nimport {SequenceNode} from './sequence';\nimport {SourceNode} from './source';\n\n/**\n * Whether this dataflow node is the source of the dataflow that produces data i.e. a source or a generator.\n */\nexport function isDataSourceNode(node: DataFlowNode) {\n return node instanceof SourceNode || node instanceof GraticuleNode || node instanceof SequenceNode;\n}\n\n/**\n * Abstract base class for Dataflow optimizers.\n * Contains only mutation handling logic. Subclasses need to implement iteration logic.\n */\nexport abstract class Optimizer {\n #modified: boolean;\n\n constructor() {\n this.#modified = false;\n }\n\n // Once true, #modified is never set to false\n public setModified() {\n this.#modified = true;\n }\n\n get modifiedFlag() {\n return this.#modified;\n }\n\n /**\n * Run the optimization for the tree with the provided root.\n */\n public abstract optimize(root: DataFlowNode): boolean;\n}\n\n/**\n * Starts from a node and runs the optimization function (the \"run\" method) upwards to the root,\n * depending on the continue and modified flag values returned by the optimization function.\n */\nexport abstract class BottomUpOptimizer extends Optimizer {\n /**\n * Run the optimizer at the node. This method should not change the parent of the passed in node (it should only affect children).\n */\n public abstract run(node: DataFlowNode): void;\n\n /**\n * Compute a map of node depths that we can use to determine a topological sort order.\n */\n private getNodeDepths(\n node: DataFlowNode,\n depth: number,\n depths: Map\n ): Map {\n depths.set(node, depth);\n\n for (const child of node.children) {\n this.getNodeDepths(child, depth + 1, depths);\n }\n\n return depths;\n }\n\n /**\n * Run the optimizer on all nodes starting from the leaves.\n */\n public optimize(node: DataFlowNode): boolean {\n const depths = this.getNodeDepths(node, 0, new Map());\n const topologicalSort = [...depths.entries()].sort((a, b) => b[1] - a[1]);\n\n for (const tuple of topologicalSort) {\n this.run(tuple[0]);\n }\n\n return this.modifiedFlag;\n }\n}\n\n/**\n * The optimizer function (the \"run\" method), is invoked on the given node and then continues recursively.\n */\nexport abstract class TopDownOptimizer extends Optimizer {\n /**\n * Run the optimizer at the node.\n */\n public abstract run(node: DataFlowNode): void;\n\n /**\n * Run the optimizer depth first on all nodes starting from the roots.\n */\n public optimize(node: DataFlowNode): boolean {\n this.run(node);\n\n for (const child of node.children) {\n this.optimize(child);\n }\n\n return this.modifiedFlag;\n }\n}\n","import {Parse} from '../../data';\nimport {Dict, fieldIntersection, hash, hasIntersection, isEmpty, keys, some} from '../../util';\nimport {Model} from '../model';\nimport {requiresSelectionId} from '../selection';\nimport {AggregateNode} from './aggregate';\nimport {BinNode} from './bin';\nimport {DataFlowNode, OutputNode} from './dataflow';\nimport {FacetNode} from './facet';\nimport {FilterNode} from './filter';\nimport {ParseNode} from './formatparse';\nimport {IdentifierNode} from './identifier';\nimport {BottomUpOptimizer, isDataSourceNode, Optimizer, TopDownOptimizer} from './optimizer';\nimport {SourceNode} from './source';\nimport {TimeUnitNode} from './timeunit';\n\n/**\n * Merge identical nodes at forks by comparing hashes.\n *\n * Does not need to iterate from leaves so we implement this with recursion as it's a bit simpler.\n */\nexport class MergeIdenticalNodes extends TopDownOptimizer {\n public mergeNodes(parent: DataFlowNode, nodes: DataFlowNode[]) {\n const mergedNode = nodes.shift();\n for (const node of nodes) {\n parent.removeChild(node);\n node.parent = mergedNode;\n node.remove();\n }\n }\n\n public run(node: DataFlowNode) {\n const hashes = node.children.map(x => x.hash());\n const buckets: {hash?: DataFlowNode[]} = {};\n\n for (let i = 0; i < hashes.length; i++) {\n if (buckets[hashes[i]] === undefined) {\n buckets[hashes[i]] = [node.children[i]];\n } else {\n buckets[hashes[i]].push(node.children[i]);\n }\n }\n\n for (const k of keys(buckets)) {\n if (buckets[k].length > 1) {\n this.setModified();\n this.mergeNodes(node, buckets[k]);\n }\n }\n }\n}\n\n/**\n * Optimizer that removes identifier nodes that are not needed for selections.\n */\nexport class RemoveUnnecessaryIdentifierNodes extends TopDownOptimizer {\n private requiresSelectionId: boolean;\n\n constructor(model: Model) {\n super();\n this.requiresSelectionId = model && requiresSelectionId(model);\n }\n\n public run(node: DataFlowNode) {\n if (node instanceof IdentifierNode) {\n // Only preserve IdentifierNodes if we have default discrete selections\n // in our model tree, and if the nodes come after tuple producing nodes.\n if (\n !(\n this.requiresSelectionId &&\n (isDataSourceNode(node.parent) || node.parent instanceof AggregateNode || node.parent instanceof ParseNode)\n )\n ) {\n this.setModified();\n node.remove();\n }\n }\n }\n}\n\n/**\n * Removes duplicate time unit nodes (as determined by the name of the output field) that may be generated due to\n * selections projected over time units. Only keeps the first time unit in any branch.\n *\n * This optimizer is a custom top down optimizer that keep track of produced fields in a branch.\n */\nexport class RemoveDuplicateTimeUnits extends Optimizer {\n public optimize(node: DataFlowNode): boolean {\n this.run(node, new Set());\n\n return this.modifiedFlag;\n }\n\n public run(node: DataFlowNode, timeUnitFields: Set) {\n let producedFields = new Set();\n\n if (node instanceof TimeUnitNode) {\n producedFields = node.producedFields();\n if (hasIntersection(producedFields, timeUnitFields)) {\n this.setModified();\n node.removeFormulas(timeUnitFields);\n if (node.producedFields.length === 0) {\n node.remove();\n }\n }\n }\n\n for (const child of node.children) {\n this.run(child, new Set([...timeUnitFields, ...producedFields]));\n }\n }\n}\n\n/**\n * Remove output nodes that are not required.\n */\nexport class RemoveUnnecessaryOutputNodes extends TopDownOptimizer {\n constructor() {\n super();\n }\n\n public run(node: DataFlowNode) {\n if (node instanceof OutputNode && !node.isRequired()) {\n this.setModified();\n node.remove();\n }\n }\n}\n\n/**\n * Move parse nodes up to forks and merges them if possible.\n */\nexport class MoveParseUp extends BottomUpOptimizer {\n public run(node: DataFlowNode) {\n if (isDataSourceNode(node)) {\n return;\n }\n\n if (node.numChildren() > 1) {\n // Don't move parse further up but continue with parent.\n return;\n }\n\n for (const child of node.children) {\n if (child instanceof ParseNode) {\n if (node instanceof ParseNode) {\n this.setModified();\n node.merge(child);\n } else {\n // Don't swap with nodes that produce something that the parse node depends on (e.g. lookup).\n if (fieldIntersection(node.producedFields(), child.dependentFields())) {\n continue;\n }\n this.setModified();\n child.swapWithParent();\n }\n }\n }\n\n return;\n }\n}\n\n/**\n * Inserts an intermediate ParseNode containing all non-conflicting parse fields and removes the empty ParseNodes.\n *\n * We assume that dependent paths that do not have a parse node can be just merged.\n */\nexport class MergeParse extends BottomUpOptimizer {\n public run(node: DataFlowNode) {\n const originalChildren = [...node.children];\n const parseChildren = node.children.filter((child): child is ParseNode => child instanceof ParseNode);\n\n if (node.numChildren() > 1 && parseChildren.length >= 1) {\n const commonParse: Parse = {};\n const conflictingParse = new Set();\n for (const parseNode of parseChildren) {\n const parse = parseNode.parse;\n for (const k of keys(parse)) {\n if (!(k in commonParse)) {\n commonParse[k] = parse[k];\n } else if (commonParse[k] !== parse[k]) {\n conflictingParse.add(k);\n }\n }\n }\n\n for (const field of conflictingParse) {\n delete commonParse[field];\n }\n\n if (!isEmpty(commonParse)) {\n this.setModified();\n const mergedParseNode = new ParseNode(node, commonParse);\n for (const childNode of originalChildren) {\n if (childNode instanceof ParseNode) {\n for (const key of keys(commonParse)) {\n delete childNode.parse[key];\n }\n }\n\n node.removeChild(childNode);\n childNode.parent = mergedParseNode;\n\n // remove empty parse nodes\n if (childNode instanceof ParseNode && keys(childNode.parse).length === 0) {\n childNode.remove();\n }\n }\n }\n }\n }\n}\n\n/**\n * Repeatedly remove leaf nodes that are not output or facet nodes.\n * The reason is that we don't need subtrees that don't have any output nodes.\n * Facet nodes are needed for the row or column domains.\n */\nexport class RemoveUnusedSubtrees extends BottomUpOptimizer {\n public run(node: DataFlowNode) {\n if (node instanceof OutputNode || node.numChildren() > 0 || node instanceof FacetNode) {\n // no need to continue with parent because it is output node or will have children (there was a fork)\n } else if (node instanceof SourceNode) {\n // ignore empty unused sources as they will be removed in optimizationDataflowHelper\n } else {\n this.setModified();\n node.remove();\n }\n }\n}\n\n/**\n * Merge adjacent time unit nodes.\n */\nexport class MergeTimeUnits extends BottomUpOptimizer {\n public run(node: DataFlowNode) {\n const timeUnitChildren = node.children.filter((x): x is TimeUnitNode => x instanceof TimeUnitNode);\n const combination = timeUnitChildren.pop();\n for (const timeUnit of timeUnitChildren) {\n this.setModified();\n combination.merge(timeUnit);\n }\n }\n}\n\nexport class MergeAggregates extends BottomUpOptimizer {\n public run(node: DataFlowNode) {\n const aggChildren = node.children.filter((child): child is AggregateNode => child instanceof AggregateNode);\n\n // Object which we'll use to map the fields which an aggregate is grouped by to\n // the set of aggregates with that grouping. This is useful as only aggregates\n // with the same group by can be merged\n const groupedAggregates: Dict = {};\n\n // Build groupedAggregates\n for (const agg of aggChildren) {\n const groupBys = hash(agg.groupBy);\n if (!(groupBys in groupedAggregates)) {\n groupedAggregates[groupBys] = [];\n }\n groupedAggregates[groupBys].push(agg);\n }\n\n // Merge aggregateNodes with same key in groupedAggregates\n for (const group of keys(groupedAggregates)) {\n const mergeableAggs = groupedAggregates[group];\n if (mergeableAggs.length > 1) {\n const mergedAggs = mergeableAggs.pop();\n for (const agg of mergeableAggs) {\n if (mergedAggs.merge(agg)) {\n node.removeChild(agg);\n agg.parent = mergedAggs;\n agg.remove();\n\n this.setModified();\n }\n }\n }\n }\n }\n}\n\n/**\n * Merge bin nodes and move them up through forks. Stop at filters, parse, identifier as we want them to stay before the bin node.\n */\nexport class MergeBins extends BottomUpOptimizer {\n constructor(private model: Model) {\n super();\n }\n\n public run(node: DataFlowNode) {\n const moveBinsUp = !(\n isDataSourceNode(node) ||\n node instanceof FilterNode ||\n node instanceof ParseNode ||\n node instanceof IdentifierNode\n );\n\n const promotableBins: BinNode[] = [];\n const remainingBins: BinNode[] = [];\n\n for (const child of node.children) {\n if (child instanceof BinNode) {\n if (moveBinsUp && !fieldIntersection(node.producedFields(), child.dependentFields())) {\n promotableBins.push(child);\n } else {\n remainingBins.push(child);\n }\n }\n }\n\n if (promotableBins.length > 0) {\n const promotedBin = promotableBins.pop();\n for (const bin of promotableBins) {\n promotedBin.merge(bin, this.model.renameSignal.bind(this.model));\n }\n this.setModified();\n if (node instanceof BinNode) {\n node.merge(promotedBin, this.model.renameSignal.bind(this.model));\n } else {\n promotedBin.swapWithParent();\n }\n }\n if (remainingBins.length > 1) {\n const remainingBin = remainingBins.pop();\n for (const bin of remainingBins) {\n remainingBin.merge(bin, this.model.renameSignal.bind(this.model));\n }\n this.setModified();\n }\n }\n}\n\n/**\n * This optimizer takes output nodes that are at a fork and moves them before the fork.\n *\n * The algorithm iterates over the children and tries to find the last output node in a chain of output nodes.\n * It then moves all output nodes before that main output node. All other children (and the children of the output nodes)\n * are inserted after the main output node.\n */\nexport class MergeOutputs extends BottomUpOptimizer {\n public run(node: DataFlowNode) {\n const children = [...node.children];\n const hasOutputChild = some(children, child => child instanceof OutputNode);\n\n if (!hasOutputChild || node.numChildren() <= 1) {\n return;\n }\n\n const otherChildren: DataFlowNode[] = [];\n\n // The output node we will connect all other nodes to.\n // Output nodes will be added before the new node, other nodes after.\n let mainOutput: OutputNode;\n\n for (const child of children) {\n if (child instanceof OutputNode) {\n let lastOutput = child;\n\n while (lastOutput.numChildren() === 1) {\n const [theChild] = lastOutput.children;\n if (theChild instanceof OutputNode) {\n lastOutput = theChild;\n } else {\n break;\n }\n }\n\n otherChildren.push(...lastOutput.children);\n\n if (mainOutput) {\n // Move the output nodes before the mainOutput. We do this by setting\n // the parent of the first not to the parent of the main output and\n // the main output's parent to the last output.\n\n // note: the child is the first output\n node.removeChild(child);\n child.parent = mainOutput.parent;\n\n mainOutput.parent.removeChild(mainOutput);\n mainOutput.parent = lastOutput;\n\n this.setModified();\n } else {\n mainOutput = lastOutput;\n }\n } else {\n otherChildren.push(child);\n }\n }\n\n if (otherChildren.length) {\n this.setModified();\n for (const child of otherChildren) {\n child.parent.removeChild(child);\n child.parent = mainOutput;\n }\n }\n }\n}\n","import {AggregateOp} from 'vega';\nimport {vgField} from '../../channeldef';\nimport {JoinAggregateTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {VgJoinAggregateTransform} from '../../vega.schema';\nimport {JoinAggregateFieldDef} from '../../transform';\nimport {unique} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for the join aggregate transform nodes.\n */\nexport class JoinAggregateTransformNode extends DataFlowNode {\n public clone() {\n return new JoinAggregateTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private readonly transform: JoinAggregateTransform\n ) {\n super(parent);\n }\n\n public addDimensions(fields: string[]) {\n this.transform.groupby = unique(this.transform.groupby.concat(fields), d => d);\n }\n\n public dependentFields() {\n const out = new Set();\n\n if (this.transform.groupby) {\n this.transform.groupby.forEach(out.add, out);\n }\n this.transform.joinaggregate\n .map(w => w.field)\n .filter(f => f !== undefined)\n .forEach(out.add, out);\n\n return out;\n }\n\n public producedFields() {\n return new Set(this.transform.joinaggregate.map(this.getDefaultName));\n }\n\n private getDefaultName(joinAggregateFieldDef: JoinAggregateFieldDef): string {\n return joinAggregateFieldDef.as ?? vgField(joinAggregateFieldDef);\n }\n\n public hash() {\n return `JoinAggregateTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgJoinAggregateTransform {\n const fields: string[] = [];\n const ops: AggregateOp[] = [];\n const as: string[] = [];\n for (const joinaggregate of this.transform.joinaggregate) {\n ops.push(joinaggregate.op);\n as.push(this.getDefaultName(joinaggregate));\n fields.push(joinaggregate.field === undefined ? null : joinaggregate.field);\n }\n\n const groupby = this.transform.groupby;\n\n return {\n type: 'joinaggregate',\n as,\n ops,\n fields,\n ...(groupby !== undefined ? {groupby} : {})\n };\n }\n}\n","import {FilterTransform as VgFilterTransform} from 'vega';\nimport {isScaleChannel} from '../../channel';\nimport {TypedFieldDef, vgField as fieldRef} from '../../channeldef';\nimport {Dict, hash, keys} from '../../util';\nimport {getScaleInvalidDataMode} from '../invalid/ScaleInvalidDataMode';\nimport {DataSourcesForHandlingInvalidValues} from '../invalid/datasources';\nimport {UnitModel} from '../unit';\nimport {DataFlowNode} from './dataflow';\nimport {isCountingAggregateOp} from '../../aggregate';\n\nexport class FilterInvalidNode extends DataFlowNode {\n public clone() {\n return new FilterInvalidNode(null, {...this.filter});\n }\n\n constructor(\n parent: DataFlowNode,\n public readonly filter: Dict>\n ) {\n super(parent);\n }\n\n public static make(\n parent: DataFlowNode,\n model: UnitModel,\n dataSourcesForHandlingInvalidValues: DataSourcesForHandlingInvalidValues\n ): FilterInvalidNode {\n const {config, markDef} = model;\n\n const {marks, scales} = dataSourcesForHandlingInvalidValues;\n if (marks === 'include-invalid-values' && scales === 'include-invalid-values') {\n // If neither marks nor scale domains need data source to filter null values, then don't add the filter.\n return null;\n }\n\n const filter = model.reduceFieldDef(\n (aggregator: Dict>, fieldDef, channel) => {\n const scaleComponent = isScaleChannel(channel) && model.getScaleComponent(channel);\n\n if (scaleComponent) {\n const scaleType = scaleComponent.get('type');\n const {aggregate} = fieldDef;\n const invalidDataMode = getScaleInvalidDataMode({\n scaleChannel: channel,\n markDef,\n config,\n scaleType,\n isCountAggregate: isCountingAggregateOp(aggregate)\n });\n\n // If the invalid data mode is include or always-valid, we don't need to filter invalid values as the scale can handle invalid values.\n if (invalidDataMode !== 'show' && invalidDataMode !== 'always-valid') {\n aggregator[fieldDef.field] = fieldDef as any; // we know that the fieldDef is a typed field def\n }\n }\n\n return aggregator;\n },\n {} as Dict>\n );\n\n if (!keys(filter).length) {\n return null;\n }\n\n return new FilterInvalidNode(parent, filter);\n }\n\n public dependentFields() {\n return new Set(keys(this.filter));\n }\n\n public producedFields() {\n return new Set(); // filter does not produce any new fields\n }\n\n public hash() {\n return `FilterInvalid ${hash(this.filter)}`;\n }\n\n /**\n * Create the VgTransforms for each of the filtered fields.\n */\n public assemble(): VgFilterTransform {\n const filters = keys(this.filter).reduce((vegaFilters, field) => {\n const fieldDef = this.filter[field];\n const ref = fieldRef(fieldDef, {expr: 'datum'});\n\n if (fieldDef !== null) {\n if (fieldDef.type === 'temporal') {\n vegaFilters.push(`(isDate(${ref}) || (${isValidFiniteNumberExpr(ref)}))`);\n } else if (fieldDef.type === 'quantitative') {\n vegaFilters.push(isValidFiniteNumberExpr(ref));\n } else {\n // should never get here\n }\n }\n return vegaFilters;\n }, [] as string[]);\n\n return filters.length > 0\n ? {\n type: 'filter',\n expr: filters.join(' && ')\n }\n : null;\n }\n}\n\nexport function isValidFiniteNumberExpr(ref: string) {\n return `isValid(${ref}) && isFinite(+${ref})`;\n}\n","import {Transforms as VgTransform} from 'vega';\nimport {isArray, isString} from 'vega-util';\nimport {FieldDef, FieldName, getFieldDef, isFieldDef, isOrderOnlyDef, vgField} from '../../channeldef';\nimport {SortFields, SortOrder} from '../../sort';\nimport {StackOffset} from '../../stack';\nimport {StackTransform} from '../../transform';\nimport {duplicate, getFirstDefined, hash} from '../../util';\nimport {sortParams} from '../common';\nimport {UnitModel} from '../unit';\nimport {DataFlowNode} from './dataflow';\nimport {isValidFiniteNumberExpr} from './filterinvalid';\n\nfunction getStackByFields(model: UnitModel): string[] {\n return model.stack.stackBy.reduce((fields, by) => {\n const fieldDef = by.fieldDef;\n\n const _field = vgField(fieldDef);\n if (_field) {\n fields.push(_field);\n }\n return fields;\n }, [] as string[]);\n}\n\nexport interface StackComponent {\n /**\n * Faceted field.\n */\n facetby: string[];\n\n dimensionFieldDefs: FieldDef[];\n\n /**\n * Stack measure's field. Used in makeFromEncoding.\n */\n stackField: string;\n\n /**\n * Level of detail fields for each level in the stacked charts such as color or detail.\n * Used in makeFromEncoding.\n */\n stackby?: string[];\n\n /**\n * Field that determines order of levels in the stacked charts.\n * Used in both but optional in transform.\n */\n sort: SortFields;\n\n /** Mode for stacking marks.\n */\n offset: StackOffset;\n\n /**\n * Whether to impute the data before stacking. Used only in makeFromEncoding.\n */\n impute?: boolean;\n\n /**\n * The data fields to group by.\n */\n groupby?: FieldName[];\n /**\n * Output field names of each stack field.\n */\n as: [FieldName, FieldName];\n}\n\nfunction isValidAsArray(as: string[] | string): as is string[] {\n return isArray(as) && as.every(s => isString(s)) && as.length > 1;\n}\n\nexport class StackNode extends DataFlowNode {\n private _stack: StackComponent;\n\n public clone() {\n return new StackNode(null, duplicate(this._stack));\n }\n\n constructor(parent: DataFlowNode, stack: StackComponent) {\n super(parent);\n\n this._stack = stack;\n }\n\n public static makeFromTransform(parent: DataFlowNode, stackTransform: StackTransform) {\n const {stack, groupby, as, offset = 'zero'} = stackTransform;\n\n const sortFields: string[] = [];\n const sortOrder: SortOrder[] = [];\n if (stackTransform.sort !== undefined) {\n for (const sortField of stackTransform.sort) {\n sortFields.push(sortField.field);\n sortOrder.push(getFirstDefined(sortField.order, 'ascending'));\n }\n }\n const sort: SortFields = {\n field: sortFields,\n order: sortOrder\n };\n let normalizedAs: [string, string];\n if (isValidAsArray(as)) {\n normalizedAs = as;\n } else if (isString(as)) {\n normalizedAs = [as, `${as}_end`];\n } else {\n normalizedAs = [`${stackTransform.stack}_start`, `${stackTransform.stack}_end`];\n }\n\n return new StackNode(parent, {\n dimensionFieldDefs: [],\n stackField: stack,\n groupby,\n offset,\n sort,\n facetby: [],\n as: normalizedAs\n });\n }\n\n public static makeFromEncoding(parent: DataFlowNode, model: UnitModel) {\n const stackProperties = model.stack;\n const {encoding} = model;\n\n if (!stackProperties) {\n return null;\n }\n\n const {groupbyChannels, fieldChannel, offset, impute} = stackProperties;\n\n const dimensionFieldDefs = groupbyChannels\n .map(groupbyChannel => {\n const cDef = encoding[groupbyChannel];\n return getFieldDef(cDef);\n })\n .filter(def => !!def);\n\n const stackby = getStackByFields(model);\n const orderDef = model.encoding.order;\n\n let sort: SortFields;\n if (isArray(orderDef) || isFieldDef(orderDef)) {\n sort = sortParams(orderDef);\n } else {\n const sortOrder = isOrderOnlyDef(orderDef) ? orderDef.sort : fieldChannel === 'y' ? 'descending' : 'ascending';\n // default = descending by stackFields\n // FIXME is the default here correct for binned fields?\n sort = stackby.reduce(\n (s, field) => {\n if (!s.field.includes(field)) {\n s.field.push(field);\n s.order.push(sortOrder);\n }\n return s;\n },\n {field: [], order: []}\n );\n }\n\n return new StackNode(parent, {\n dimensionFieldDefs,\n stackField: model.vgField(fieldChannel),\n facetby: [],\n stackby,\n sort,\n offset,\n impute,\n as: [\n model.vgField(fieldChannel, {suffix: 'start', forAs: true}),\n model.vgField(fieldChannel, {suffix: 'end', forAs: true})\n ]\n });\n }\n\n get stack(): StackComponent {\n return this._stack;\n }\n\n public addDimensions(fields: string[]) {\n this._stack.facetby.push(...fields);\n }\n\n public dependentFields() {\n const out = new Set();\n\n out.add(this._stack.stackField);\n\n this.getGroupbyFields().forEach(out.add, out);\n this._stack.facetby.forEach(out.add, out);\n this._stack.sort.field.forEach(out.add, out);\n\n return out;\n }\n\n public producedFields() {\n return new Set(this._stack.as);\n }\n\n public hash() {\n return `Stack ${hash(this._stack)}`;\n }\n\n private getGroupbyFields() {\n const {dimensionFieldDefs, impute, groupby} = this._stack;\n\n if (dimensionFieldDefs.length > 0) {\n return dimensionFieldDefs\n .map(dimensionFieldDef => {\n if (dimensionFieldDef.bin) {\n if (impute) {\n // For binned group by field with impute, we calculate bin_mid\n // as we cannot impute two fields simultaneously\n return [vgField(dimensionFieldDef, {binSuffix: 'mid'})];\n }\n return [\n // For binned group by field without impute, we need both bin (start) and bin_end\n vgField(dimensionFieldDef, {}),\n vgField(dimensionFieldDef, {binSuffix: 'end'})\n ];\n }\n return [vgField(dimensionFieldDef)];\n })\n .flat();\n }\n return groupby ?? [];\n }\n\n public assemble(): VgTransform[] {\n const transform: VgTransform[] = [];\n const {facetby, dimensionFieldDefs, stackField: field, stackby, sort, offset, impute, as} = this._stack;\n\n // Impute\n if (impute) {\n for (const dimensionFieldDef of dimensionFieldDefs) {\n const {bandPosition = 0.5, bin} = dimensionFieldDef;\n if (bin) {\n // As we can only impute one field at a time, we need to calculate\n // mid point for a binned field\n\n const binStart = vgField(dimensionFieldDef, {expr: 'datum'});\n const binEnd = vgField(dimensionFieldDef, {expr: 'datum', binSuffix: 'end'});\n transform.push({\n type: 'formula',\n expr: `${isValidFiniteNumberExpr(binStart)} ? ${bandPosition}*${binStart}+${1 - bandPosition}*${binEnd} : ${binStart}`,\n as: vgField(dimensionFieldDef, {binSuffix: 'mid', forAs: true})\n });\n }\n\n transform.push({\n type: 'impute',\n field,\n groupby: [...stackby, ...facetby],\n key: vgField(dimensionFieldDef, {binSuffix: 'mid'}),\n method: 'value',\n value: 0\n });\n }\n }\n\n // Stack\n transform.push({\n type: 'stack',\n groupby: [...this.getGroupbyFields(), ...facetby],\n field,\n sort,\n as,\n offset\n });\n\n return transform;\n }\n}\n","import {AggregateOp, WindowTransform as VgWindowTransform} from 'vega';\nimport {isAggregateOp} from '../../aggregate';\nimport {vgField} from '../../channeldef';\nimport {SortOrder} from '../../sort';\nimport {WindowFieldDef, WindowOnlyOp, WindowTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {VgComparator, VgJoinAggregateTransform} from '../../vega.schema';\nimport {unique} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for the window transform nodes\n */\nexport class WindowTransformNode extends DataFlowNode {\n public clone() {\n return new WindowTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private readonly transform: WindowTransform\n ) {\n super(parent);\n }\n\n public addDimensions(fields: string[]) {\n this.transform.groupby = unique(this.transform.groupby.concat(fields), d => d);\n }\n\n public dependentFields() {\n const out = new Set();\n\n (this.transform.groupby ?? []).forEach(out.add, out);\n (this.transform.sort ?? []).forEach(m => out.add(m.field));\n\n this.transform.window\n .map(w => w.field)\n .filter(f => f !== undefined)\n .forEach(out.add, out);\n\n return out;\n }\n\n public producedFields() {\n return new Set(this.transform.window.map(this.getDefaultName));\n }\n\n private getDefaultName(windowFieldDef: WindowFieldDef): string {\n return windowFieldDef.as ?? vgField(windowFieldDef);\n }\n\n public hash() {\n return `WindowTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgWindowTransform | VgJoinAggregateTransform {\n const fields: string[] = [];\n const ops: (AggregateOp | WindowOnlyOp)[] = [];\n const as: string[] = [];\n const params = [];\n\n for (const window of this.transform.window) {\n ops.push(window.op);\n as.push(this.getDefaultName(window));\n params.push(window.param === undefined ? null : window.param);\n fields.push(window.field === undefined ? null : window.field);\n }\n\n const frame = this.transform.frame;\n const groupby = this.transform.groupby;\n\n if (frame && frame[0] === null && frame[1] === null && ops.every(o => isAggregateOp(o))) {\n // when the window does not rely on any particular window ops or frame, switch to a simpler and more efficient joinaggregate\n return {\n type: 'joinaggregate',\n as,\n ops: ops as AggregateOp[],\n fields,\n ...(groupby !== undefined ? {groupby} : {})\n } as VgJoinAggregateTransform;\n }\n\n const sortFields: string[] = [];\n const sortOrder: SortOrder[] = [];\n if (this.transform.sort !== undefined) {\n for (const sortField of this.transform.sort) {\n sortFields.push(sortField.field);\n sortOrder.push(sortField.order ?? 'ascending');\n }\n }\n const sort: VgComparator = {\n field: sortFields,\n order: sortOrder\n };\n const ignorePeers = this.transform.ignorePeers;\n\n return {\n type: 'window',\n params,\n as,\n ops,\n fields,\n sort,\n ...(ignorePeers !== undefined ? {ignorePeers} : {}),\n ...(groupby !== undefined ? {groupby} : {}),\n ...(frame !== undefined ? {frame} : {})\n } as VgWindowTransform;\n }\n}\n","import {DataSourceType} from '../../data';\nimport {AggregateNode} from './aggregate';\nimport {DataFlowNode, OutputNode} from './dataflow';\nimport {FacetNode} from './facet';\nimport {JoinAggregateTransformNode} from './joinaggregate';\nimport {FACET_SCALE_PREFIX} from './optimize';\nimport {StackNode} from './stack';\nimport {WindowTransformNode} from './window';\n\n/**\n * Clones the subtree and ignores output nodes except for the leaves, which are renamed.\n */\nfunction cloneSubtree(facet: FacetNode) {\n function clone(node: DataFlowNode): DataFlowNode[] {\n if (!(node instanceof FacetNode)) {\n const copy = node.clone();\n\n if (copy instanceof OutputNode) {\n const newName = FACET_SCALE_PREFIX + copy.getSource();\n copy.setSource(newName);\n\n facet.model.component.data.outputNodes[newName] = copy;\n } else if (\n copy instanceof AggregateNode ||\n copy instanceof StackNode ||\n copy instanceof WindowTransformNode ||\n copy instanceof JoinAggregateTransformNode\n ) {\n copy.addDimensions(facet.fields);\n }\n for (const n of node.children.flatMap(clone)) {\n n.parent = copy;\n }\n\n return [copy];\n }\n\n return node.children.flatMap(clone);\n }\n return clone;\n}\n\n/**\n * Move facet nodes down to the next fork or output node. Also pull the main output with the facet node.\n * After moving down the facet node, make a copy of the subtree and make it a child of the main output.\n */\nexport function moveFacetDown(node: DataFlowNode) {\n if (node instanceof FacetNode) {\n if (node.numChildren() === 1 && !(node.children[0] instanceof OutputNode)) {\n // move down until we hit a fork or output node\n const child = node.children[0];\n\n if (\n child instanceof AggregateNode ||\n child instanceof StackNode ||\n child instanceof WindowTransformNode ||\n child instanceof JoinAggregateTransformNode\n ) {\n child.addDimensions(node.fields);\n }\n\n child.swapWithParent();\n moveFacetDown(node);\n } else {\n // move main to facet\n\n const facetMain = node.model.component.data.main;\n moveMainDownToFacet(facetMain);\n\n // replicate the subtree and place it before the facet's main node\n const cloner = cloneSubtree(node);\n const copy: DataFlowNode[] = node.children.map(cloner).flat();\n for (const c of copy) {\n c.parent = facetMain;\n }\n }\n } else {\n node.children.map(moveFacetDown);\n }\n}\n\nfunction moveMainDownToFacet(node: DataFlowNode) {\n if (node instanceof OutputNode && node.type === DataSourceType.Main) {\n if (node.numChildren() === 1) {\n const child = node.children[0];\n if (!(child instanceof FacetNode)) {\n child.swapWithParent();\n moveMainDownToFacet(node);\n }\n }\n }\n}\n","import {DataComponent} from '.';\nimport * as log from '../../log';\nimport {Model} from '../model';\nimport {DataFlowNode} from './dataflow';\nimport {Optimizer} from './optimizer';\nimport * as optimizers from './optimizers';\nimport {moveFacetDown} from './subtree';\n\nexport const FACET_SCALE_PREFIX = 'scale_';\nexport const MAX_OPTIMIZATION_RUNS = 5;\n\n/**\n * Iterates over a dataflow graph and checks whether all links are consistent.\n */\nexport function checkLinks(nodes: readonly DataFlowNode[]): boolean {\n for (const node of nodes) {\n for (const child of node.children) {\n if (child.parent !== node) {\n // log.error('Dataflow graph is inconsistent.', node, child);\n return false;\n }\n }\n\n if (!checkLinks(node.children)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Run the specified optimizer on the provided nodes.\n *\n * @param optimizer The optimizer instance to run.\n * @param nodes A set of nodes to optimize.\n */\nfunction runOptimizer(optimizer: Optimizer, nodes: DataFlowNode[]): boolean {\n let modified = false;\n\n for (const node of nodes) {\n modified = optimizer.optimize(node) || modified;\n }\n\n return modified;\n}\n\nfunction optimizationDataflowHelper(dataComponent: DataComponent, model: Model, firstPass: boolean) {\n let roots = dataComponent.sources;\n let modified = false;\n\n modified = runOptimizer(new optimizers.RemoveUnnecessaryOutputNodes(), roots) || modified;\n modified = runOptimizer(new optimizers.RemoveUnnecessaryIdentifierNodes(model), roots) || modified;\n\n // remove source nodes that don't have any children because they also don't have output nodes\n roots = roots.filter(r => r.numChildren() > 0);\n\n modified = runOptimizer(new optimizers.RemoveUnusedSubtrees(), roots) || modified;\n\n roots = roots.filter(r => r.numChildren() > 0);\n\n if (!firstPass) {\n // Only run these optimizations after the optimizer has moved down the facet node.\n // With this change, we can be more aggressive in the optimizations.\n modified = runOptimizer(new optimizers.MoveParseUp(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeBins(model), roots) || modified;\n modified = runOptimizer(new optimizers.RemoveDuplicateTimeUnits(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeParse(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeAggregates(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeTimeUnits(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeIdenticalNodes(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeOutputs(), roots) || modified;\n }\n\n dataComponent.sources = roots;\n\n return modified;\n}\n\n/**\n * Optimizes the dataflow of the passed in data component.\n */\nexport function optimizeDataflow(data: DataComponent, model: Model) {\n // check before optimizations\n checkLinks(data.sources);\n\n let firstPassCounter = 0;\n let secondPassCounter = 0;\n\n for (let i = 0; i < MAX_OPTIMIZATION_RUNS; i++) {\n if (!optimizationDataflowHelper(data, model, true)) {\n break;\n }\n firstPassCounter++;\n }\n\n // move facets down and make a copy of the subtree so that we can have scales at the top level\n data.sources.map(moveFacetDown);\n\n for (let i = 0; i < MAX_OPTIMIZATION_RUNS; i++) {\n if (!optimizationDataflowHelper(data, model, false)) {\n break;\n }\n secondPassCounter++;\n }\n\n // check after optimizations\n checkLinks(data.sources);\n\n if (Math.max(firstPassCounter, secondPassCounter) === MAX_OPTIMIZATION_RUNS) {\n log.warn(`Maximum optimization runs(${MAX_OPTIMIZATION_RUNS}) reached.`);\n }\n}\n","import type {SignalRef} from 'vega';\n\nexport type Rename = (oldSignalName: string) => string;\n\n/**\n * A class that behaves like a SignalRef but lazily generates the signal.\n * The provided generator function should use `Model.getSignalName` to use the correct signal name.\n */\nexport class SignalRefWrapper implements SignalRef {\n constructor(exprGenerator: () => string) {\n Object.defineProperty(this, 'signal', {\n enumerable: true,\n get: exprGenerator\n });\n }\n\n public signal: string; // for ts\n\n public static fromName(rename: Rename, signalName: string) {\n return new SignalRefWrapper(() => rename(signalName));\n }\n}\n","import type {SignalRef} from 'vega';\nimport {isObject, isString} from 'vega-util';\nimport {\n Aggregate,\n isAggregateOp,\n isArgmaxDef,\n isArgminDef,\n MULTIDOMAIN_SORT_OP_INDEX as UNIONDOMAIN_SORT_OP_INDEX,\n NonArgAggregateOp,\n SHARED_DOMAIN_OPS\n} from '../../aggregate';\nimport {isBinning, isBinParams, isParameterExtent} from '../../bin';\nimport {getSecondaryRangeChannel, isScaleChannel, isXorY, ScaleChannel} from '../../channel';\nimport {\n binRequiresRange,\n getBandPosition,\n getFieldOrDatumDef,\n hasBandEnd,\n isDatumDef,\n isFieldDef,\n ScaleDatumDef,\n ScaleFieldDef,\n TypedFieldDef,\n valueExpr,\n vgField\n} from '../../channeldef';\nimport {CompositeAggregate} from '../../compositemark';\nimport {DataSourceType} from '../../data';\nimport {DateTime} from '../../datetime';\nimport {ExprRef} from '../../expr';\nimport * as log from '../../log';\nimport {Domain, hasDiscreteDomain, isDomainUnionWith, isParameterDomain, ScaleConfig, ScaleType} from '../../scale';\nimport {ParameterExtent} from '../../selection';\nimport {DEFAULT_SORT_OP, EncodingSortField, isSortArray, isSortByEncoding, isSortField} from '../../sort';\nimport {normalizeTimeUnit, TimeUnit, TimeUnitTransformParams} from '../../timeunit';\nimport {Type} from '../../type';\nimport * as util from '../../util';\nimport {\n isDataRefDomain,\n isDataRefUnionedDomain,\n isFieldRefUnionDomain,\n isSignalRef,\n VgDomain,\n VgMultiFieldsRefWithSort,\n VgNonUnionDomain,\n VgScaleDataRefWithSort,\n VgSortField,\n VgUnionSortField\n} from '../../vega.schema';\nimport {getBinSignalName} from '../data/bin';\nimport {sortArrayIndexField} from '../data/calculate';\nimport {FACET_SCALE_PREFIX} from '../data/optimize';\nimport {isFacetModel, isUnitModel, Model} from '../model';\nimport {SignalRefWrapper} from '../signal';\nimport {Explicit, makeExplicit, makeImplicit, mergeValuesWithExplicit} from '../split';\nimport {UnitModel} from '../unit';\nimport {ScaleComponent, ScaleComponentIndex} from './component';\nimport {isPathMark, isRectBasedMark} from '../../mark';\nimport {OFFSETTED_RECT_END_SUFFIX, OFFSETTED_RECT_START_SUFFIX} from '../data/timeunit';\nimport {getScaleDataSourceForHandlingInvalidValues} from '../invalid/datasources';\nimport {getMarkConfig} from '../common';\n\nexport function parseScaleDomain(model: Model) {\n if (isUnitModel(model)) {\n parseUnitScaleDomain(model);\n } else {\n parseNonUnitScaleDomain(model);\n }\n}\n\nfunction parseUnitScaleDomain(model: UnitModel) {\n const localScaleComponents: ScaleComponentIndex = model.component.scales;\n\n for (const channel of util.keys(localScaleComponents)) {\n const domains = parseDomainForChannel(model, channel);\n const localScaleCmpt = localScaleComponents[channel];\n localScaleCmpt.setWithExplicit('domains', domains);\n parseSelectionDomain(model, channel);\n\n if (model.component.data.isFaceted) {\n // get resolve from closest facet parent as this decides whether we need to refer to cloned subtree or not\n let facetParent: Model = model;\n while (!isFacetModel(facetParent) && facetParent.parent) {\n facetParent = facetParent.parent;\n }\n\n const resolve = facetParent.component.resolve.scale[channel];\n\n if (resolve === 'shared') {\n for (const domain of domains.value) {\n // Replace the scale domain with data output from a cloned subtree after the facet.\n if (isDataRefDomain(domain)) {\n // use data from cloned subtree (which is the same as data but with a prefix added once)\n domain.data = FACET_SCALE_PREFIX + domain.data.replace(FACET_SCALE_PREFIX, '');\n }\n }\n }\n }\n }\n}\n\nfunction parseNonUnitScaleDomain(model: Model) {\n for (const child of model.children) {\n parseScaleDomain(child);\n }\n\n const localScaleComponents: ScaleComponentIndex = model.component.scales;\n\n for (const channel of util.keys(localScaleComponents)) {\n let domains: Explicit;\n let selectionExtent: ParameterExtent = null;\n\n for (const child of model.children) {\n const childComponent = child.component.scales[channel];\n if (childComponent) {\n if (domains === undefined) {\n domains = childComponent.getWithExplicit('domains');\n } else {\n domains = mergeValuesWithExplicit(\n domains,\n childComponent.getWithExplicit('domains'),\n 'domains',\n 'scale',\n domainsTieBreaker\n );\n }\n\n const se = childComponent.get('selectionExtent');\n if (selectionExtent && se && selectionExtent.param !== se.param) {\n log.warn(log.message.NEEDS_SAME_SELECTION);\n }\n selectionExtent = se;\n }\n }\n\n localScaleComponents[channel].setWithExplicit('domains', domains);\n\n if (selectionExtent) {\n localScaleComponents[channel].set('selectionExtent', selectionExtent, true);\n }\n }\n}\n\n/**\n * Remove unaggregated domain if it is not applicable\n * Add unaggregated domain if domain is not specified and config.scale.useUnaggregatedDomain is true.\n */\nfunction normalizeUnaggregatedDomain(\n domain: Domain,\n fieldDef: TypedFieldDef,\n scaleType: ScaleType,\n scaleConfig: ScaleConfig\n) {\n if (domain === 'unaggregated') {\n const {valid, reason} = canUseUnaggregatedDomain(fieldDef, scaleType);\n if (!valid) {\n log.warn(reason);\n return undefined;\n }\n } else if (domain === undefined && scaleConfig.useUnaggregatedDomain) {\n // Apply config if domain is not specified.\n const {valid} = canUseUnaggregatedDomain(fieldDef, scaleType);\n if (valid) {\n return 'unaggregated';\n }\n }\n\n return domain;\n}\n\nexport function parseDomainForChannel(model: UnitModel, channel: ScaleChannel): Explicit {\n const scaleType = model.getScaleComponent(channel).get('type');\n const {encoding} = model;\n\n const domain = normalizeUnaggregatedDomain(\n model.scaleDomain(channel),\n model.typedFieldDef(channel),\n scaleType,\n model.config.scale\n );\n if (domain !== model.scaleDomain(channel)) {\n model.specifiedScales[channel] = {\n ...model.specifiedScales[channel],\n domain\n };\n }\n\n // If channel is either X or Y then union them with X2 & Y2 if they exist\n if (channel === 'x' && getFieldOrDatumDef(encoding.x2)) {\n if (getFieldOrDatumDef(encoding.x)) {\n return mergeValuesWithExplicit(\n parseSingleChannelDomain(scaleType, domain, model, 'x'),\n parseSingleChannelDomain(scaleType, domain, model, 'x2'),\n 'domain',\n 'scale',\n domainsTieBreaker\n );\n } else {\n return parseSingleChannelDomain(scaleType, domain, model, 'x2');\n }\n } else if (channel === 'y' && getFieldOrDatumDef(encoding.y2)) {\n if (getFieldOrDatumDef(encoding.y)) {\n return mergeValuesWithExplicit(\n parseSingleChannelDomain(scaleType, domain, model, 'y'),\n parseSingleChannelDomain(scaleType, domain, model, 'y2'),\n 'domain',\n 'scale',\n domainsTieBreaker\n );\n } else {\n return parseSingleChannelDomain(scaleType, domain, model, 'y2');\n }\n }\n return parseSingleChannelDomain(scaleType, domain, model, channel);\n}\n\nfunction mapDomainToDataSignal(\n domain: (number | string | boolean | DateTime | ExprRef | SignalRef | number[])[],\n type: Type,\n timeUnit: TimeUnit\n) {\n return domain.map(v => {\n const data = valueExpr(v, {timeUnit, type});\n return {signal: `{data: ${data}}`};\n });\n}\n\nfunction convertDomainIfItIsDateTime(\n domain: (number | string | boolean | DateTime | ExprRef | SignalRef | number[])[],\n type: Type,\n timeUnit: TimeUnit | TimeUnitTransformParams\n): [number[]] | [string[]] | [boolean[]] | SignalRef[] {\n // explicit value\n const normalizedTimeUnit = normalizeTimeUnit(timeUnit)?.unit;\n if (type === 'temporal' || normalizedTimeUnit) {\n return mapDomainToDataSignal(domain, type, normalizedTimeUnit);\n }\n\n return [domain] as [number[]] | [string[]] | [boolean[]]; // Date time won't make sense\n}\n\nfunction parseSingleChannelDomain(\n scaleType: ScaleType,\n domain: Domain,\n model: UnitModel,\n channel: ScaleChannel | 'x2' | 'y2'\n): Explicit {\n const {encoding, markDef, mark, config, stack} = model;\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) as ScaleDatumDef | ScaleFieldDef;\n\n const {type} = fieldOrDatumDef;\n const timeUnit = fieldOrDatumDef['timeUnit'];\n\n const dataSourceTypeForScaleDomain = getScaleDataSourceForHandlingInvalidValues({\n invalid: getMarkConfig('invalid', markDef, config),\n isPath: isPathMark(mark)\n });\n\n if (isDomainUnionWith(domain)) {\n const defaultDomain = parseSingleChannelDomain(scaleType, undefined, model, channel);\n\n const unionWith = convertDomainIfItIsDateTime(domain.unionWith, type, timeUnit);\n\n return makeExplicit([...unionWith, ...defaultDomain.value]);\n } else if (isSignalRef(domain)) {\n return makeExplicit([domain]);\n } else if (domain && domain !== 'unaggregated' && !isParameterDomain(domain)) {\n return makeExplicit(convertDomainIfItIsDateTime(domain, type, timeUnit));\n }\n\n if (stack && channel === stack.fieldChannel) {\n if (stack.offset === 'normalize') {\n return makeImplicit([[0, 1]]);\n }\n\n const data = model.requestDataName(dataSourceTypeForScaleDomain);\n return makeImplicit([\n {\n data,\n field: model.vgField(channel, {suffix: 'start'})\n },\n {\n data,\n field: model.vgField(channel, {suffix: 'end'})\n }\n ]);\n }\n\n const sort: undefined | true | VgSortField =\n isScaleChannel(channel) && isFieldDef(fieldOrDatumDef) ? domainSort(model, channel, scaleType) : undefined;\n\n if (isDatumDef(fieldOrDatumDef)) {\n const d = convertDomainIfItIsDateTime([fieldOrDatumDef.datum], type, timeUnit);\n return makeImplicit(d);\n }\n\n const fieldDef = fieldOrDatumDef; // now we can be sure it's a fieldDef\n if (domain === 'unaggregated') {\n const {field} = fieldOrDatumDef;\n return makeImplicit([\n {\n data: model.requestDataName(dataSourceTypeForScaleDomain),\n field: vgField({field, aggregate: 'min'})\n },\n {\n data: model.requestDataName(dataSourceTypeForScaleDomain),\n field: vgField({field, aggregate: 'max'})\n }\n ]);\n } else if (isBinning(fieldDef.bin)) {\n if (hasDiscreteDomain(scaleType)) {\n if (scaleType === 'bin-ordinal') {\n // we can omit the domain as it is inferred from the `bins` property\n return makeImplicit([]);\n }\n\n // ordinal bin scale takes domain from bin_range, ordered by bin start\n // This is useful for both axis-based scale (x/y) and legend-based scale (other channels).\n return makeImplicit([\n {\n // If sort by aggregation of a specified sort field, we need to use RAW table,\n // so we can aggregate values for the scale independently from the main aggregation.\n data: util.isBoolean(sort)\n ? model.requestDataName(dataSourceTypeForScaleDomain)\n : model.requestDataName(DataSourceType.Raw),\n // Use range if we added it and the scale does not support computing a range as a signal.\n field: model.vgField(channel, binRequiresRange(fieldDef, channel) ? {binSuffix: 'range'} : {}),\n // we have to use a sort object if sort = true to make the sort correct by bin start\n sort:\n sort === true || !isObject(sort)\n ? {\n field: model.vgField(channel, {}),\n op: 'min' // min or max doesn't matter since we sort by the start of the bin range\n }\n : sort\n }\n ]);\n } else {\n // continuous scales\n const {bin} = fieldDef;\n if (isBinning(bin)) {\n const binSignal = getBinSignalName(model, fieldDef.field, bin);\n return makeImplicit([\n new SignalRefWrapper(() => {\n const signal = model.getSignalName(binSignal);\n return `[${signal}.start, ${signal}.stop]`;\n })\n ]);\n } else {\n return makeImplicit([\n {\n data: model.requestDataName(dataSourceTypeForScaleDomain),\n field: model.vgField(channel, {})\n }\n ]);\n }\n }\n } else if (fieldDef.timeUnit && util.contains(['time', 'utc'], scaleType)) {\n const fieldDef2 = encoding[getSecondaryRangeChannel(channel)];\n\n if (hasBandEnd(fieldDef, fieldDef2, markDef, config)) {\n const data = model.requestDataName(dataSourceTypeForScaleDomain);\n\n const bandPosition = getBandPosition({fieldDef, fieldDef2, markDef, config});\n const isRectWithOffset = isRectBasedMark(mark) && bandPosition !== 0.5 && isXorY(channel);\n return makeImplicit([\n {\n data,\n field: model.vgField(channel, isRectWithOffset ? {suffix: OFFSETTED_RECT_START_SUFFIX} : {})\n },\n {\n data,\n field: model.vgField(channel, {suffix: isRectWithOffset ? OFFSETTED_RECT_END_SUFFIX : 'end'})\n }\n ]);\n }\n }\n if (sort) {\n return makeImplicit([\n {\n // If sort by aggregation of a specified sort field, we need to use RAW table,\n // so we can aggregate values for the scale independently from the main aggregation.\n data: util.isBoolean(sort)\n ? model.requestDataName(dataSourceTypeForScaleDomain)\n : model.requestDataName(DataSourceType.Raw),\n field: model.vgField(channel),\n sort\n }\n ]);\n } else {\n return makeImplicit([\n {\n data: model.requestDataName(dataSourceTypeForScaleDomain),\n field: model.vgField(channel)\n }\n ]);\n }\n}\n\nfunction normalizeSortField(sort: EncodingSortField, isStackedMeasure: boolean): VgSortField {\n const {op, field, order} = sort;\n return {\n // Apply default op\n op: op ?? (isStackedMeasure ? 'sum' : DEFAULT_SORT_OP),\n // flatten nested fields\n ...(field ? {field: util.replacePathInField(field)} : {}),\n\n ...(order ? {order} : {})\n };\n}\n\nfunction parseSelectionDomain(model: UnitModel, channel: ScaleChannel) {\n const scale = model.component.scales[channel];\n const spec = model.specifiedScales[channel].domain;\n const bin = model.fieldDef(channel)?.bin;\n const domain = isParameterDomain(spec) && spec;\n const extent = isBinParams(bin) && isParameterExtent(bin.extent) && bin.extent;\n\n if (domain || extent) {\n // As scale parsing occurs before selection parsing, we cannot set\n // domainRaw directly. So instead, we store the selectionExtent on\n // the scale component, and then add domainRaw during scale assembly.\n scale.set('selectionExtent', domain ?? extent, true);\n }\n}\n\nexport function domainSort(\n model: UnitModel,\n channel: ScaleChannel,\n scaleType: ScaleType\n): undefined | true | VgSortField {\n if (!hasDiscreteDomain(scaleType)) {\n return undefined;\n }\n\n // save to cast as the only exception is the geojson type for shape, which would not generate a scale\n const fieldDef = model.fieldDef(channel) as ScaleFieldDef;\n const sort = fieldDef.sort;\n\n // if the sort is specified with array, use the derived sort index field\n if (isSortArray(sort)) {\n return {\n op: 'min',\n field: sortArrayIndexField(fieldDef, channel),\n order: 'ascending'\n };\n }\n\n const {stack} = model;\n const stackDimensions = stack\n ? new Set([...stack.groupbyFields, ...stack.stackBy.map(s => s.fieldDef.field)])\n : undefined;\n\n // Sorted based on an aggregate calculation over a specified sort field (only for ordinal scale)\n if (isSortField(sort)) {\n const isStackedMeasure = stack && !stackDimensions.has(sort.field);\n return normalizeSortField(sort, isStackedMeasure);\n } else if (isSortByEncoding(sort)) {\n const {encoding, order} = sort;\n const fieldDefToSortBy = model.fieldDef(encoding);\n const {aggregate, field} = fieldDefToSortBy;\n\n const isStackedMeasure = stack && !stackDimensions.has(field);\n\n if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {\n return normalizeSortField(\n {\n field: vgField(fieldDefToSortBy),\n order\n },\n isStackedMeasure\n );\n } else if (isAggregateOp(aggregate) || !aggregate) {\n return normalizeSortField(\n {\n op: aggregate as NonArgAggregateOp, // can't be argmin/argmax since we don't support them in encoding field def\n field,\n order\n },\n isStackedMeasure\n );\n }\n } else if (sort === 'descending') {\n return {\n op: 'min',\n field: model.vgField(channel),\n order: 'descending'\n };\n } else if (util.contains(['ascending', undefined /* default =ascending*/], sort)) {\n return true;\n }\n\n // sort == null\n return undefined;\n}\n\n/**\n * Determine if a scale can use unaggregated domain.\n * @return {Boolean} Returns true if all of the following conditions apply:\n * 1. `scale.domain` is `unaggregated`\n * 2. Aggregation function is not `count` or `sum`\n * 3. The scale is quantitative or time scale.\n */\nexport function canUseUnaggregatedDomain(\n fieldDef: TypedFieldDef,\n scaleType: ScaleType\n): {valid: boolean; reason?: string} {\n const {aggregate, type} = fieldDef;\n\n if (!aggregate) {\n return {\n valid: false,\n reason: log.message.unaggregateDomainHasNoEffectForRawField(fieldDef)\n };\n }\n\n if (isString(aggregate) && !(SHARED_DOMAIN_OPS as Set).has(aggregate)) {\n return {\n valid: false,\n reason: log.message.unaggregateDomainWithNonSharedDomainOp(aggregate)\n };\n }\n\n if (type === 'quantitative') {\n if (scaleType === 'log') {\n return {\n valid: false,\n reason: log.message.unaggregatedDomainWithLogScale(fieldDef)\n };\n }\n }\n\n return {valid: true};\n}\n\n/**\n * Tie breaker for mergeValuesWithExplicit for domains. We concat the specified values.\n */\nfunction domainsTieBreaker(\n v1: Explicit,\n v2: Explicit,\n property: 'domains',\n propertyOf: 'scale'\n) {\n if (v1.explicit && v2.explicit) {\n log.warn(log.message.mergeConflictingDomainProperty(property, propertyOf, v1.value, v2.value));\n }\n // If equal score, concat the domains so that we union them later.\n return {explicit: v1.explicit, value: [...v1.value, ...v2.value]};\n}\n\n/**\n * Converts an array of domains to a single Vega scale domain.\n */\nexport function mergeDomains(domains: VgNonUnionDomain[]): VgDomain {\n const uniqueDomains = util.unique(\n domains.map(domain => {\n // ignore sort property when computing the unique domains\n if (isDataRefDomain(domain)) {\n const {sort: _s, ...domainWithoutSort} = domain;\n return domainWithoutSort;\n }\n return domain;\n }),\n util.hash\n );\n\n const sorts: VgSortField[] = util.unique(\n domains\n .map(d => {\n if (isDataRefDomain(d)) {\n const s = d.sort;\n if (s !== undefined && !util.isBoolean(s)) {\n if ('op' in s && s.op === 'count') {\n // let's make sure that if op is count, we don't use a field\n delete s.field;\n }\n if (s.order === 'ascending') {\n // drop order: ascending as it is the default\n delete s.order;\n }\n }\n return s;\n }\n return undefined;\n })\n .filter(s => s !== undefined),\n util.hash\n );\n\n if (uniqueDomains.length === 0) {\n return undefined;\n } else if (uniqueDomains.length === 1) {\n const domain = domains[0];\n if (isDataRefDomain(domain) && sorts.length > 0) {\n let sort = sorts[0];\n if (sorts.length > 1) {\n log.warn(log.message.MORE_THAN_ONE_SORT);\n // Get sorts with non-default ops\n const filteredSorts = sorts.filter(s => isObject(s) && 'op' in s && s.op !== 'min');\n if (sorts.every(s => isObject(s) && 'op' in s) && filteredSorts.length === 1) {\n sort = filteredSorts[0];\n } else {\n sort = true;\n }\n } else {\n // Simplify domain sort by removing field and op when the field is the same as the domain field.\n if (isObject(sort) && 'field' in sort) {\n const sortField = sort.field;\n if (domain.field === sortField) {\n sort = sort.order ? {order: sort.order} : true;\n }\n }\n }\n return {\n ...domain,\n sort\n };\n }\n return domain;\n }\n\n // only keep sort properties that work with unioned domains\n const unionDomainSorts = util.unique(\n sorts.map(s => {\n if (util.isBoolean(s) || !('op' in s) || (isString(s.op) && s.op in UNIONDOMAIN_SORT_OP_INDEX)) {\n return s as VgUnionSortField;\n }\n log.warn(log.message.domainSortDropped(s));\n return true;\n }),\n util.hash\n ) as VgUnionSortField[];\n\n let sort: VgUnionSortField;\n\n if (unionDomainSorts.length === 1) {\n sort = unionDomainSorts[0];\n } else if (unionDomainSorts.length > 1) {\n log.warn(log.message.MORE_THAN_ONE_SORT);\n sort = true;\n }\n\n const allData = util.unique(\n domains.map(d => {\n if (isDataRefDomain(d)) {\n return d.data;\n }\n return null;\n }),\n x => x\n );\n\n if (allData.length === 1 && allData[0] !== null) {\n // create a union domain of different fields with a single data source\n const domain: VgMultiFieldsRefWithSort = {\n data: allData[0],\n fields: uniqueDomains.map(d => (d as VgScaleDataRefWithSort).field),\n ...(sort ? {sort} : {})\n };\n\n return domain;\n }\n\n return {fields: uniqueDomains, ...(sort ? {sort} : {})};\n}\n\n/**\n * Return a field if a scale uses a single field.\n * Return `undefined` otherwise.\n */\nexport function getFieldFromDomain(domain: VgDomain): string {\n if (isDataRefDomain(domain) && isString(domain.field)) {\n return domain.field;\n } else if (isDataRefUnionedDomain(domain)) {\n let field;\n for (const nonUnionDomain of domain.fields) {\n if (isDataRefDomain(nonUnionDomain) && isString(nonUnionDomain.field)) {\n if (!field) {\n field = nonUnionDomain.field;\n } else if (field !== nonUnionDomain.field) {\n log.warn(log.message.FACETED_INDEPENDENT_DIFFERENT_SOURCES);\n return field;\n }\n }\n }\n log.warn(log.message.FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES);\n return field;\n } else if (isFieldRefUnionDomain(domain)) {\n log.warn(log.message.FACETED_INDEPENDENT_SAME_SOURCE);\n const field = domain.fields[0];\n return isString(field) ? field : undefined;\n }\n\n return undefined;\n}\n\nexport function assembleDomain(model: Model, channel: ScaleChannel) {\n const scaleComponent: ScaleComponent = model.component.scales[channel];\n\n const domains = scaleComponent.get('domains').map((domain: VgNonUnionDomain) => {\n // Correct references to data as the original domain's data was determined\n // in parseScale, which happens before parseData. Thus the original data\n // reference can be incorrect.\n if (isDataRefDomain(domain)) {\n domain.data = model.lookupDataSource(domain.data);\n }\n\n return domain;\n });\n\n // domains is an array that has to be merged into a single vega domain\n return mergeDomains(domains);\n}\n","import {isObject} from 'vega-util';\nimport {isXorY, ScaleChannel} from '../../channel';\nimport {keys} from '../../util';\nimport {isDataRefDomain, isVgRangeStep, VgRange, VgScale} from '../../vega.schema';\nimport {isConcatModel, isLayerModel, Model} from '../model';\nimport {assembleSelectionScaleDomain} from '../selection/assemble';\nimport {assembleDomain} from './domain';\n\nexport function assembleScales(model: Model): VgScale[] {\n if (isLayerModel(model) || isConcatModel(model)) {\n // For concat and layer, include scales of children too\n return model.children.reduce((scales, child) => {\n return scales.concat(assembleScales(child));\n }, assembleScalesForModel(model));\n } else {\n // For facet, child scales would not be included in the parent's scope.\n // For unit, there is no child.\n return assembleScalesForModel(model);\n }\n}\n\nexport function assembleScalesForModel(model: Model): VgScale[] {\n return keys(model.component.scales).reduce((scales: VgScale[], channel: ScaleChannel) => {\n const scaleComponent = model.component.scales[channel];\n if (scaleComponent.merged) {\n // Skipped merged scales\n return scales;\n }\n\n const scale = scaleComponent.combine();\n const {name, type, selectionExtent, domains: _d, range: _r, reverse, ...otherScaleProps} = scale;\n const range = assembleScaleRange(scale.range, name, channel, model);\n\n const domain = assembleDomain(model, channel);\n const domainRaw = selectionExtent\n ? assembleSelectionScaleDomain(model, selectionExtent, scaleComponent, domain)\n : null;\n\n scales.push({\n name,\n type,\n ...(domain ? {domain} : {}),\n ...(domainRaw ? {domainRaw} : {}),\n range,\n ...(reverse !== undefined ? {reverse: reverse as any} : {}),\n ...otherScaleProps\n });\n\n return scales;\n }, [] as VgScale[]);\n}\n\nexport function assembleScaleRange(\n scaleRange: VgRange,\n scaleName: string,\n channel: ScaleChannel,\n model?: Model\n): VgRange {\n // add signals to x/y range\n if (isXorY(channel)) {\n if (isVgRangeStep(scaleRange)) {\n // For width/height step, use a signal created in layout assemble instead of a constant step.\n return {\n step: {signal: `${scaleName}_step`}\n };\n }\n } else if (isObject(scaleRange) && isDataRefDomain(scaleRange)) {\n return {\n ...scaleRange,\n data: model.lookupDataSource(scaleRange.data)\n };\n }\n return scaleRange;\n}\n","import type {SignalRef} from 'vega';\nimport {isArray, isNumber} from 'vega-util';\nimport {ScaleChannel} from '../../channel';\nimport {Scale, ScaleType} from '../../scale';\nimport {ParameterExtent} from '../../selection';\nimport {contains} from '../../util';\nimport {VgNonUnionDomain, VgScale} from '../../vega.schema';\nimport {Explicit, Split} from '../split';\n\n/**\n * All VgDomain property except domain.\n * (We exclude domain as we have a special \"domains\" array that allow us merge them all at once in assemble.)\n */\nexport type ScaleComponentProps = Omit & {\n domains: VgNonUnionDomain[];\n selectionExtent?: ParameterExtent;\n reverse?: boolean | SignalRef; // Need override since Vega doesn't official support scale reverse yet (though it does in practice)\n};\n\nexport type Range = ScaleComponentProps['range'];\n\nexport class ScaleComponent extends Split {\n public merged = false;\n\n constructor(name: string, typeWithExplicit: Explicit) {\n super(\n {}, // no initial explicit property\n {name} // name as initial implicit property\n );\n this.setWithExplicit('type', typeWithExplicit);\n }\n\n /**\n * Whether the scale definitely includes or not include zero in the domain\n */\n public domainHasZero(): 'definitely' | 'definitely-not' | 'maybe' {\n const scaleType = this.get('type');\n if (contains([ScaleType.LOG, ScaleType.TIME, ScaleType.UTC], scaleType)) {\n // Log scales cannot have zero.\n // Zero in time scale is arbitrary, and does not affect ratio.\n // (Time is an interval level of measurement, not ratio).\n // See https://en.wikipedia.org/wiki/Level_of_measurement for more info.\n return 'definitely-not';\n }\n\n const scaleZero = this.get('zero');\n if (\n scaleZero === true ||\n // If zero is undefined, linear/sqrt/pow scales have zero by default.\n (scaleZero === undefined && contains([ScaleType.LINEAR, ScaleType.SQRT, ScaleType.POW], scaleType))\n ) {\n return 'definitely';\n }\n\n const domains = this.get('domains');\n\n if (domains.length > 0) {\n let hasExplicitDomainWithZero = false;\n let hasExplicitDomainWithoutZero = false;\n let hasDomainBasedOnField = false;\n for (const d of domains) {\n if (isArray(d)) {\n const first = d[0];\n const last = d[d.length - 1];\n if (isNumber(first) && isNumber(last)) {\n if (first <= 0 && last >= 0) {\n hasExplicitDomainWithZero = true;\n continue;\n } else {\n hasExplicitDomainWithoutZero = true;\n continue;\n }\n }\n }\n hasDomainBasedOnField = true;\n }\n if (hasExplicitDomainWithZero) {\n return 'definitely';\n } else if (hasExplicitDomainWithoutZero && !hasDomainBasedOnField) {\n return 'definitely-not';\n }\n }\n return 'maybe';\n }\n}\n\nexport type ScaleComponentIndex = Partial>;\n\nexport type ScaleIndex = Partial>>;\n","import {RangeScheme, SignalRef} from 'vega';\nimport {isArray, isNumber, isObject} from 'vega-util';\nimport {isBinning} from '../../bin';\nimport {\n ANGLE,\n COLOR,\n FILL,\n FILLOPACITY,\n getOffsetScaleChannel,\n getSizeChannel,\n isXorY,\n isXorYOffset,\n OPACITY,\n PositionScaleChannel,\n RADIUS,\n ScaleChannel,\n SCALE_CHANNELS,\n SHAPE,\n SIZE,\n STROKE,\n STROKEDASH,\n STROKEOPACITY,\n STROKEWIDTH,\n THETA,\n X,\n XOFFSET,\n Y,\n YOFFSET\n} from '../../channel';\nimport {\n getBandPosition,\n getFieldOrDatumDef,\n isFieldDef,\n isFieldOrDatumDef,\n ScaleDatumDef,\n ScaleFieldDef\n} from '../../channeldef';\nimport {Config, getViewConfigDiscreteSize, getViewConfigDiscreteStep, ViewConfig} from '../../config';\nimport {DataSourceType} from '../../data';\nimport {channelHasFieldOrDatum} from '../../encoding';\nimport * as log from '../../log';\nimport {Mark} from '../../mark';\nimport {\n channelScalePropertyIncompatability,\n Domain,\n hasContinuousDomain,\n hasDiscreteDomain,\n isContinuousToDiscrete,\n isExtendedScheme,\n Scale,\n ScaleType,\n scaleTypeSupportProperty,\n Scheme\n} from '../../scale';\nimport {getStepFor, isStep, LayoutSizeMixins, Step} from '../../spec/base';\nimport {isDiscrete} from '../../type';\nimport * as util from '../../util';\nimport {isSignalRef, VgRange} from '../../vega.schema';\nimport {exprFromSignalRefOrValue, signalOrStringValue} from '../common';\nimport {getBinSignalName} from '../data/bin';\nimport {SignalRefWrapper} from '../signal';\nimport {Explicit, makeExplicit, makeImplicit} from '../split';\nimport {UnitModel} from '../unit';\nimport {ScaleComponentIndex} from './component';\nimport {durationExpr} from '../../timeunit';\nimport {isFacetModel} from '../model';\n\nexport const RANGE_PROPERTIES: (keyof Scale)[] = ['range', 'scheme'];\n\nexport function parseUnitScaleRange(model: UnitModel) {\n const localScaleComponents: ScaleComponentIndex = model.component.scales;\n\n // use SCALE_CHANNELS instead of scales[channel] to ensure that x, y come first!\n for (const channel of SCALE_CHANNELS) {\n const localScaleCmpt = localScaleComponents[channel];\n if (!localScaleCmpt) {\n continue;\n }\n\n const rangeWithExplicit = parseRangeForChannel(channel, model);\n\n localScaleCmpt.setWithExplicit('range', rangeWithExplicit);\n }\n}\n\nfunction getBinStepSignal(model: UnitModel, channel: 'x' | 'y'): SignalRefWrapper {\n const fieldDef = model.fieldDef(channel);\n\n if (fieldDef?.bin) {\n const {bin, field} = fieldDef;\n const sizeType = getSizeChannel(channel);\n const sizeSignal = model.getName(sizeType);\n\n if (isObject(bin) && bin.binned && bin.step !== undefined) {\n return new SignalRefWrapper(() => {\n const scaleName = model.scaleName(channel);\n const binCount = `(domain(\"${scaleName}\")[1] - domain(\"${scaleName}\")[0]) / ${bin.step}`;\n return `${model.getSignalName(sizeSignal)} / (${binCount})`;\n });\n } else if (isBinning(bin)) {\n const binSignal = getBinSignalName(model, field, bin);\n\n // TODO: extract this to be range step signal\n return new SignalRefWrapper(() => {\n const updatedName = model.getSignalName(binSignal);\n const binCount = `(${updatedName}.stop - ${updatedName}.start) / ${updatedName}.step`;\n return `${model.getSignalName(sizeSignal)} / (${binCount})`;\n });\n }\n }\n return undefined;\n}\n\n/**\n * Return mixins that includes one of the Vega range types (explicit range, range.step, range.scheme).\n */\nexport function parseRangeForChannel(channel: ScaleChannel, model: UnitModel): Explicit {\n const specifiedScale = model.specifiedScales[channel];\n const {size} = model;\n\n const mergedScaleCmpt = model.getScaleComponent(channel);\n const scaleType = mergedScaleCmpt.get('type');\n\n // Check if any of the range properties is specified.\n // If so, check if it is compatible and make sure that we only output one of the properties\n for (const property of RANGE_PROPERTIES) {\n if (specifiedScale[property] !== undefined) {\n const supportedByScaleType = scaleTypeSupportProperty(scaleType, property);\n const channelIncompatability = channelScalePropertyIncompatability(channel, property);\n if (!supportedByScaleType) {\n log.warn(log.message.scalePropertyNotWorkWithScaleType(scaleType, property, channel));\n } else if (channelIncompatability) {\n // channel\n log.warn(channelIncompatability);\n } else {\n switch (property) {\n case 'range': {\n const range = specifiedScale.range;\n if (isArray(range)) {\n if (isXorY(channel)) {\n return makeExplicit(\n range.map(v => {\n if (v === 'width' || v === 'height') {\n // get signal for width/height\n\n // Just like default range logic below, we use SignalRefWrapper to account for potential merges and renames.\n\n const sizeSignal = model.getName(v);\n const getSignalName = model.getSignalName.bind(model);\n return SignalRefWrapper.fromName(getSignalName, sizeSignal);\n }\n return v;\n })\n );\n }\n } else if (isObject(range)) {\n return makeExplicit({\n data: model.requestDataName(DataSourceType.Main),\n field: range.field,\n sort: {op: 'min', field: model.vgField(channel)}\n });\n }\n\n return makeExplicit(range);\n }\n case 'scheme':\n return makeExplicit(parseScheme(specifiedScale[property]));\n }\n }\n }\n }\n\n const sizeChannel = channel === X || channel === 'xOffset' ? 'width' : 'height';\n const sizeValue = size[sizeChannel];\n if (isStep(sizeValue)) {\n if (isXorY(channel)) {\n if (hasDiscreteDomain(scaleType)) {\n const step = getPositionStep(sizeValue, model, channel);\n // Need to be explicit so layer with step wins over layer without step\n if (step) {\n return makeExplicit({step});\n }\n } else {\n log.warn(log.message.stepDropped(sizeChannel));\n }\n } else if (isXorYOffset(channel)) {\n const positionChannel = channel === XOFFSET ? 'x' : 'y';\n const positionScaleCmpt = model.getScaleComponent(positionChannel);\n const positionScaleType = positionScaleCmpt.get('type');\n if (positionScaleType === 'band') {\n const step = getOffsetStep(sizeValue, scaleType);\n if (step) {\n return makeExplicit(step);\n }\n }\n }\n }\n\n const {rangeMin, rangeMax} = specifiedScale;\n const d = defaultRange(channel, model);\n\n if (\n (rangeMin !== undefined || rangeMax !== undefined) &&\n // it's ok to check just rangeMin's compatibility since rangeMin/rangeMax are the same\n scaleTypeSupportProperty(scaleType, 'rangeMin') &&\n isArray(d) &&\n d.length === 2\n ) {\n return makeExplicit([rangeMin ?? d[0], rangeMax ?? d[1]]);\n }\n\n return makeImplicit(d);\n}\n\nfunction parseScheme(scheme: Scheme | SignalRef): RangeScheme {\n if (isExtendedScheme(scheme)) {\n return {\n scheme: scheme.name,\n ...util.omit(scheme, ['name'])\n };\n }\n return {scheme};\n}\n\nfunction fullWidthOrHeightRange(\n channel: 'x' | 'y',\n model: UnitModel,\n scaleType: ScaleType,\n {center}: {center?: boolean} = {}\n) {\n // If step is null, use zero to width or height.\n // Note that we use SignalRefWrapper to account for potential merges and renames.\n const sizeType = getSizeChannel(channel);\n const sizeSignal = model.getName(sizeType);\n const getSignalName = model.getSignalName.bind(model);\n\n if (channel === Y && hasContinuousDomain(scaleType)) {\n // For y continuous scale, we have to start from the height as the bottom part has the max value.\n return center\n ? [\n SignalRefWrapper.fromName(name => `${getSignalName(name)}/2`, sizeSignal),\n SignalRefWrapper.fromName(name => `-${getSignalName(name)}/2`, sizeSignal)\n ]\n : [SignalRefWrapper.fromName(getSignalName, sizeSignal), 0];\n } else {\n return center\n ? [\n SignalRefWrapper.fromName(name => `-${getSignalName(name)}/2`, sizeSignal),\n SignalRefWrapper.fromName(name => `${getSignalName(name)}/2`, sizeSignal)\n ]\n : [0, SignalRefWrapper.fromName(getSignalName, sizeSignal)];\n }\n}\n\nfunction defaultRange(channel: ScaleChannel, model: UnitModel): VgRange {\n const {size, config, mark, encoding} = model;\n\n const {type} = getFieldOrDatumDef(encoding[channel]) as ScaleFieldDef | ScaleDatumDef;\n\n const mergedScaleCmpt = model.getScaleComponent(channel);\n const scaleType = mergedScaleCmpt.get('type');\n\n const {domain, domainMid} = model.specifiedScales[channel];\n\n switch (channel) {\n case X:\n case Y: {\n // If there is no explicit width/height for discrete x/y scales\n if (util.contains(['point', 'band'], scaleType)) {\n const positionSize = getDiscretePositionSize(channel, size, config.view);\n if (isStep(positionSize)) {\n const step = getPositionStep(positionSize, model, channel);\n return {step};\n }\n }\n\n return fullWidthOrHeightRange(channel, model, scaleType);\n }\n\n case XOFFSET:\n case YOFFSET:\n return getOffsetRange(channel, model, scaleType);\n\n case SIZE: {\n // TODO: support custom rangeMin, rangeMax\n const rangeMin = sizeRangeMin(mark, config);\n const rangeMax = sizeRangeMax(mark, size, model, config);\n if (isContinuousToDiscrete(scaleType)) {\n return interpolateRange(\n rangeMin,\n rangeMax,\n defaultContinuousToDiscreteCount(scaleType, config, domain, channel)\n );\n } else {\n return [rangeMin, rangeMax];\n }\n }\n\n case THETA:\n return [0, Math.PI * 2];\n\n case ANGLE:\n // TODO: add config.scale.min/maxAngleDegree (for point and text) and config.scale.min/maxAngleRadian (for arc) once we add arc marks.\n // (It's weird to add just config.scale.min/maxAngleDegree for now)\n return [0, 360];\n\n case RADIUS: {\n // max radius = half od min(width,height)\n\n return [\n 0,\n new SignalRefWrapper(() => {\n const w = model.getSignalName(isFacetModel(model.parent) ? 'child_width' : 'width');\n const h = model.getSignalName(isFacetModel(model.parent) ? 'child_height' : 'height');\n return `min(${w},${h})/2`;\n })\n ];\n }\n\n case STROKEWIDTH:\n // TODO: support custom rangeMin, rangeMax\n return [config.scale.minStrokeWidth, config.scale.maxStrokeWidth];\n case STROKEDASH:\n return [\n // TODO: add this to Vega's config.range?\n [1, 0],\n [4, 2],\n [2, 1],\n [1, 1],\n [1, 2, 4, 2]\n ];\n case SHAPE:\n return 'symbol';\n case COLOR:\n case FILL:\n case STROKE:\n if (scaleType === 'ordinal') {\n // Only nominal data uses ordinal scale by default\n return type === 'nominal' ? 'category' : 'ordinal';\n } else {\n if (domainMid !== undefined) {\n return 'diverging';\n } else {\n return mark === 'rect' || mark === 'geoshape' ? 'heatmap' : 'ramp';\n }\n }\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n // TODO: support custom rangeMin, rangeMax\n return [config.scale.minOpacity, config.scale.maxOpacity];\n }\n}\n\nfunction getPositionStep(step: Step, model: UnitModel, channel: PositionScaleChannel): number | SignalRef {\n const {encoding} = model;\n\n const mergedScaleCmpt = model.getScaleComponent(channel);\n const offsetChannel = getOffsetScaleChannel(channel);\n const offsetDef = encoding[offsetChannel];\n const stepFor = getStepFor({step, offsetIsDiscrete: isFieldOrDatumDef(offsetDef) && isDiscrete(offsetDef.type)});\n\n if (stepFor === 'offset' && channelHasFieldOrDatum(encoding, offsetChannel)) {\n const offsetScaleCmpt = model.getScaleComponent(offsetChannel);\n const offsetScaleName = model.scaleName(offsetChannel);\n\n let stepCount = `domain('${offsetScaleName}').length`;\n\n if (offsetScaleCmpt.get('type') === 'band') {\n const offsetPaddingInner = offsetScaleCmpt.get('paddingInner') ?? offsetScaleCmpt.get('padding') ?? 0;\n const offsetPaddingOuter = offsetScaleCmpt.get('paddingOuter') ?? offsetScaleCmpt.get('padding') ?? 0;\n stepCount = `bandspace(${stepCount}, ${offsetPaddingInner}, ${offsetPaddingOuter})`;\n }\n\n const paddingInner = mergedScaleCmpt.get('paddingInner') ?? mergedScaleCmpt.get('padding');\n return {\n signal: `${step.step} * ${stepCount} / (1-${exprFromSignalRefOrValue(paddingInner)})`\n };\n } else {\n return step.step;\n }\n}\n\nfunction getOffsetStep(step: Step, offsetScaleType: ScaleType) {\n const stepFor = getStepFor({step, offsetIsDiscrete: hasDiscreteDomain(offsetScaleType)});\n if (stepFor === 'offset') {\n return {step: step.step};\n }\n return undefined;\n}\n\nfunction getOffsetRange(channel: string, model: UnitModel, offsetScaleType: ScaleType): VgRange {\n const positionChannel = channel === XOFFSET ? 'x' : 'y';\n const positionScaleCmpt = model.getScaleComponent(positionChannel);\n\n if (!positionScaleCmpt) {\n return fullWidthOrHeightRange(positionChannel, model, offsetScaleType, {center: true});\n }\n\n const positionScaleType = positionScaleCmpt.get('type');\n const positionScaleName = model.scaleName(positionChannel);\n\n const {markDef, config} = model;\n\n if (positionScaleType === 'band') {\n const size = getDiscretePositionSize(positionChannel, model.size, model.config.view);\n\n if (isStep(size)) {\n // step is for offset\n const step = getOffsetStep(size, offsetScaleType);\n if (step) {\n return step;\n }\n }\n // otherwise use the position\n return [0, {signal: `bandwidth('${positionScaleName}')`}];\n } else {\n // continuous scale\n const positionDef = model.encoding[positionChannel];\n if (isFieldDef(positionDef) && positionDef.timeUnit) {\n const duration = durationExpr(positionDef.timeUnit, expr => `scale('${positionScaleName}', ${expr})`);\n const padding = model.config.scale.bandWithNestedOffsetPaddingInner;\n const bandPositionOffset =\n getBandPosition({\n fieldDef: positionDef,\n markDef,\n config\n }) - 0.5;\n const bandPositionOffsetExpr = bandPositionOffset !== 0 ? ` + ${bandPositionOffset}` : '';\n if (padding) {\n const startRatio = isSignalRef(padding)\n ? `${padding.signal}/2` + bandPositionOffsetExpr\n : `${padding / 2 + bandPositionOffset}`;\n const endRatio = isSignalRef(padding)\n ? `(1 - ${padding.signal}/2)` + bandPositionOffsetExpr\n : `${1 - padding / 2 + bandPositionOffset}`;\n return [{signal: `${startRatio} * (${duration})`}, {signal: `${endRatio} * (${duration})`}];\n }\n return [0, {signal: duration}];\n }\n return util.never(`Cannot use ${channel} scale if ${positionChannel} scale is not discrete.`);\n }\n}\n\nfunction getDiscretePositionSize(\n channel: 'x' | 'y',\n size: LayoutSizeMixins,\n viewConfig: ViewConfig\n): Step | number | 'container' {\n const sizeChannel = channel === X ? 'width' : 'height';\n const sizeValue = size[sizeChannel];\n if (sizeValue) {\n return sizeValue;\n }\n return getViewConfigDiscreteSize(viewConfig, sizeChannel);\n}\n\nexport function defaultContinuousToDiscreteCount(\n scaleType: 'quantile' | 'quantize' | 'threshold',\n config: Config,\n domain: Domain,\n channel: ScaleChannel\n) {\n switch (scaleType) {\n case 'quantile':\n return config.scale.quantileCount;\n case 'quantize':\n return config.scale.quantizeCount;\n case 'threshold':\n if (domain !== undefined && isArray(domain)) {\n return domain.length + 1;\n } else {\n log.warn(log.message.domainRequiredForThresholdScale(channel));\n // default threshold boundaries for threshold scale since domain has cardinality of 2\n return 3;\n }\n }\n}\n\n/**\n * Returns the linear interpolation of the range according to the cardinality\n *\n * @param rangeMin start of the range\n * @param rangeMax end of the range\n * @param cardinality number of values in the output range\n */\nexport function interpolateRange(\n rangeMin: number | SignalRef,\n rangeMax: number | SignalRef,\n cardinality: number\n): SignalRef {\n // always return a signal since it's better to compute the sequence in Vega later\n const f = () => {\n const rMax = signalOrStringValue(rangeMax);\n const rMin = signalOrStringValue(rangeMin);\n const step = `(${rMax} - ${rMin}) / (${cardinality} - 1)`;\n return `sequence(${rMin}, ${rMax} + ${step}, ${step})`;\n };\n if (isSignalRef(rangeMax)) {\n return new SignalRefWrapper(f);\n } else {\n return {signal: f()};\n }\n}\n\nfunction sizeRangeMin(mark: Mark, config: Config): number | SignalRef {\n switch (mark) {\n case 'bar':\n case 'tick':\n return config.scale.minBandSize;\n case 'line':\n case 'trail':\n case 'rule':\n return config.scale.minStrokeWidth;\n case 'text':\n return config.scale.minFontSize;\n case 'point':\n case 'square':\n case 'circle':\n return config.scale.minSize;\n }\n /* istanbul ignore next: should never reach here */\n // sizeRangeMin not implemented for the mark\n throw new Error(log.message.incompatibleChannel('size', mark));\n}\n\nexport const MAX_SIZE_RANGE_STEP_RATIO = 0.95;\n\nfunction sizeRangeMax(\n mark: Mark,\n size: LayoutSizeMixins,\n model: UnitModel,\n config: Config\n): number | SignalRef {\n const xyStepSignals = {\n x: getBinStepSignal(model, 'x'),\n y: getBinStepSignal(model, 'y')\n };\n\n switch (mark) {\n case 'bar':\n case 'tick': {\n if (config.scale.maxBandSize !== undefined) {\n return config.scale.maxBandSize;\n }\n const min = minXYStep(size, xyStepSignals, config.view);\n\n if (isNumber(min)) {\n return min - 1;\n } else {\n return new SignalRefWrapper(() => `${min.signal} - 1`);\n }\n }\n case 'line':\n case 'trail':\n case 'rule':\n return config.scale.maxStrokeWidth;\n case 'text':\n return config.scale.maxFontSize;\n case 'point':\n case 'square':\n case 'circle': {\n if (config.scale.maxSize) {\n return config.scale.maxSize;\n }\n\n const pointStep = minXYStep(size, xyStepSignals, config.view);\n if (isNumber(pointStep)) {\n return Math.pow(MAX_SIZE_RANGE_STEP_RATIO * pointStep, 2);\n } else {\n return new SignalRefWrapper(() => `pow(${MAX_SIZE_RANGE_STEP_RATIO} * ${pointStep.signal}, 2)`);\n }\n }\n }\n /* istanbul ignore next: should never reach here */\n // sizeRangeMax not implemented for the mark\n throw new Error(log.message.incompatibleChannel('size', mark));\n}\n\n/**\n * @returns {number} Range step of x or y or minimum between the two if both are ordinal scale.\n */\nfunction minXYStep(\n size: LayoutSizeMixins,\n xyStepSignals: {x?: SignalRefWrapper; y?: SignalRefWrapper},\n viewConfig: ViewConfig\n): number | SignalRef {\n const widthStep = isStep(size.width) ? size.width.step : getViewConfigDiscreteStep(viewConfig, 'width');\n const heightStep = isStep(size.height) ? size.height.step : getViewConfigDiscreteStep(viewConfig, 'height');\n\n if (xyStepSignals.x || xyStepSignals.y) {\n return new SignalRefWrapper(() => {\n const exprs = [\n xyStepSignals.x ? xyStepSignals.x.signal : widthStep,\n xyStepSignals.y ? xyStepSignals.y.signal : heightStep\n ];\n return `min(${exprs.join(', ')})`;\n });\n }\n\n return Math.min(widthStep, heightStep);\n}\n","import {SignalRef, TimeInterval} from 'vega';\nimport {isArray, isNumber} from 'vega-util';\nimport {isBinned, isBinning, isBinParams} from '../../bin';\nimport {\n COLOR,\n FILL,\n getSecondaryRangeChannel,\n isXorY,\n isXorYOffset,\n POLAR_POSITION_SCALE_CHANNELS,\n POSITION_SCALE_CHANNELS,\n ScaleChannel,\n STROKE\n} from '../../channel';\nimport {\n getFieldDef,\n getFieldOrDatumDef,\n isFieldDef,\n ScaleDatumDef,\n ScaleFieldDef,\n TypedFieldDef,\n valueExpr\n} from '../../channeldef';\nimport {Config} from '../../config';\nimport {isDateTime} from '../../datetime';\nimport {channelHasNestedOffsetScale} from '../../encoding';\nimport * as log from '../../log';\nimport {Mark, MarkDef, RectConfig} from '../../mark';\nimport {\n channelScalePropertyIncompatability,\n Domain,\n hasContinuousDomain,\n isContinuousToContinuous,\n isContinuousToDiscrete,\n Scale,\n ScaleConfig,\n ScaleType,\n scaleTypeSupportProperty\n} from '../../scale';\nimport {Sort} from '../../sort';\nimport {Type} from '../../type';\nimport * as util from '../../util';\nimport {contains, getFirstDefined, keys} from '../../util';\nimport {isSignalRef, VgScale} from '../../vega.schema';\nimport {getBinSignalName} from '../data/bin';\nimport {isUnitModel, Model} from '../model';\nimport {SignalRefWrapper} from '../signal';\nimport {Explicit, mergeValuesWithExplicit, tieBreakByComparing} from '../split';\nimport {UnitModel} from '../unit';\nimport {ScaleComponentIndex, ScaleComponentProps} from './component';\nimport {parseUnitScaleRange} from './range';\n\nexport function parseScaleProperty(model: Model, property: Exclude) {\n if (isUnitModel(model)) {\n parseUnitScaleProperty(model, property);\n } else {\n parseNonUnitScaleProperty(model, property);\n }\n}\n\nfunction parseUnitScaleProperty(model: UnitModel, property: Exclude) {\n const localScaleComponents: ScaleComponentIndex = model.component.scales;\n const {config, encoding, markDef, specifiedScales} = model;\n\n for (const channel of keys(localScaleComponents)) {\n const specifiedScale = specifiedScales[channel];\n const localScaleCmpt = localScaleComponents[channel];\n const mergedScaleCmpt = model.getScaleComponent(channel);\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) as ScaleFieldDef | ScaleDatumDef;\n\n const specifiedValue = specifiedScale[property];\n const scaleType = mergedScaleCmpt.get('type');\n const scalePadding = mergedScaleCmpt.get('padding');\n const scalePaddingInner = mergedScaleCmpt.get('paddingInner');\n\n const supportedByScaleType = scaleTypeSupportProperty(scaleType, property);\n const channelIncompatability = channelScalePropertyIncompatability(channel, property);\n\n if (specifiedValue !== undefined) {\n // If there is a specified value, check if it is compatible with scale type and channel\n if (!supportedByScaleType) {\n log.warn(log.message.scalePropertyNotWorkWithScaleType(scaleType, property, channel));\n } else if (channelIncompatability) {\n // channel\n log.warn(channelIncompatability);\n }\n }\n if (supportedByScaleType && channelIncompatability === undefined) {\n if (specifiedValue !== undefined) {\n const timeUnit = fieldOrDatumDef['timeUnit'];\n const type = fieldOrDatumDef.type;\n\n switch (property) {\n // domainMax/Min to signal if the value is a datetime object\n case 'domainMax':\n case 'domainMin':\n if (isDateTime(specifiedScale[property]) || type === 'temporal' || timeUnit) {\n localScaleCmpt.set(property, {signal: valueExpr(specifiedScale[property], {type, timeUnit})}, true);\n } else {\n localScaleCmpt.set(property, specifiedScale[property] as any, true);\n }\n break;\n default:\n localScaleCmpt.copyKeyFromObject>(\n property,\n specifiedScale\n );\n }\n } else {\n const value =\n property in scaleRules\n ? scaleRules[property]({\n model,\n channel,\n fieldOrDatumDef,\n scaleType,\n scalePadding,\n scalePaddingInner,\n domain: specifiedScale.domain,\n domainMin: specifiedScale.domainMin,\n domainMax: specifiedScale.domainMax,\n markDef,\n config,\n hasNestedOffsetScale: channelHasNestedOffsetScale(encoding, channel),\n hasSecondaryRangeChannel: !!encoding[getSecondaryRangeChannel(channel)]\n })\n : config.scale[property];\n if (value !== undefined) {\n localScaleCmpt.set(property, value, false);\n }\n }\n }\n }\n}\n\nexport interface ScaleRuleParams {\n model: Model;\n channel: ScaleChannel;\n fieldOrDatumDef: ScaleFieldDef | ScaleDatumDef;\n hasNestedOffsetScale: boolean;\n scaleType: ScaleType;\n scalePadding: number | SignalRef;\n scalePaddingInner: number | SignalRef;\n domain: Domain;\n domainMin: Scale['domainMin'];\n domainMax: Scale['domainMax'];\n markDef: MarkDef;\n config: Config;\n hasSecondaryRangeChannel: boolean;\n}\n\nexport const scaleRules: {\n [k in keyof Scale]?: (params: ScaleRuleParams) => Scale[k];\n} = {\n bins: ({model, fieldOrDatumDef}) => (isFieldDef(fieldOrDatumDef) ? bins(model, fieldOrDatumDef) : undefined),\n\n interpolate: ({channel, fieldOrDatumDef}) => interpolate(channel, fieldOrDatumDef.type),\n\n nice: ({scaleType, channel, domain, domainMin, domainMax, fieldOrDatumDef}) =>\n nice(scaleType, channel, domain, domainMin, domainMax, fieldOrDatumDef),\n\n padding: ({channel, scaleType, fieldOrDatumDef, markDef, config}) =>\n padding(channel, scaleType, config.scale, fieldOrDatumDef, markDef, config.bar),\n\n paddingInner: ({scalePadding, channel, markDef, scaleType, config, hasNestedOffsetScale}) =>\n paddingInner(scalePadding, channel, markDef.type, scaleType, config.scale, hasNestedOffsetScale),\n\n paddingOuter: ({scalePadding, channel, scaleType, scalePaddingInner, config, hasNestedOffsetScale}) =>\n paddingOuter(scalePadding, channel, scaleType, scalePaddingInner, config.scale, hasNestedOffsetScale),\n\n reverse: ({fieldOrDatumDef, scaleType, channel, config}) => {\n const sort = isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined;\n return reverse(scaleType, sort, channel, config.scale);\n },\n zero: ({channel, fieldOrDatumDef, domain, markDef, scaleType, config, hasSecondaryRangeChannel}) =>\n zero(channel, fieldOrDatumDef, domain, markDef, scaleType, config.scale, hasSecondaryRangeChannel)\n};\n\n// This method is here rather than in range.ts to avoid circular dependency.\nexport function parseScaleRange(model: Model) {\n if (isUnitModel(model)) {\n parseUnitScaleRange(model);\n } else {\n parseNonUnitScaleProperty(model, 'range');\n }\n}\n\nexport function parseNonUnitScaleProperty(model: Model, property: keyof (Scale | ScaleComponentProps)) {\n const localScaleComponents: ScaleComponentIndex = model.component.scales;\n\n for (const child of model.children) {\n if (property === 'range') {\n parseScaleRange(child);\n } else {\n parseScaleProperty(child, property);\n }\n }\n\n for (const channel of keys(localScaleComponents)) {\n let valueWithExplicit: Explicit;\n\n for (const child of model.children) {\n const childComponent = child.component.scales[channel];\n if (childComponent) {\n const childValueWithExplicit = childComponent.getWithExplicit(property);\n valueWithExplicit = mergeValuesWithExplicit(\n valueWithExplicit,\n childValueWithExplicit,\n property,\n 'scale',\n tieBreakByComparing((v1, v2) => {\n switch (property) {\n case 'range':\n // For step, prefer larger step\n if (v1.step && v2.step) {\n return v1.step - v2.step;\n }\n return 0;\n // TODO: precedence rule for other properties\n }\n return 0;\n })\n );\n }\n }\n localScaleComponents[channel].setWithExplicit(property, valueWithExplicit);\n }\n}\n\nexport function bins(model: Model, fieldDef: TypedFieldDef) {\n const bin = fieldDef.bin;\n if (isBinning(bin)) {\n const binSignal = getBinSignalName(model, fieldDef.field, bin);\n return new SignalRefWrapper(() => {\n return model.getSignalName(binSignal);\n });\n } else if (isBinned(bin) && isBinParams(bin) && bin.step !== undefined) {\n // start and stop will be determined from the scale domain\n return {\n step: bin.step\n };\n }\n return undefined;\n}\n\nexport function interpolate(channel: ScaleChannel, type: Type): Scale['interpolate'] {\n if (contains([COLOR, FILL, STROKE], channel) && type !== 'nominal') {\n return 'hcl';\n }\n return undefined;\n}\n\nexport function nice(\n scaleType: ScaleType,\n channel: ScaleChannel,\n specifiedDomain: Domain,\n domainMin: Scale['domainMin'],\n domainMax: Scale['domainMax'],\n fieldOrDatumDef: TypedFieldDef | ScaleDatumDef\n): boolean | TimeInterval {\n if (\n getFieldDef(fieldOrDatumDef)?.bin ||\n isArray(specifiedDomain) ||\n domainMax != null ||\n domainMin != null ||\n util.contains([ScaleType.TIME, ScaleType.UTC], scaleType)\n ) {\n return undefined;\n }\n return isXorY(channel) ? true : undefined;\n}\n\nexport function padding(\n channel: ScaleChannel,\n scaleType: ScaleType,\n scaleConfig: ScaleConfig,\n fieldOrDatumDef: TypedFieldDef | ScaleDatumDef,\n markDef: MarkDef,\n barConfig: RectConfig\n) {\n if (isXorY(channel)) {\n if (isContinuousToContinuous(scaleType)) {\n if (scaleConfig.continuousPadding !== undefined) {\n return scaleConfig.continuousPadding;\n }\n\n const {type, orient} = markDef;\n if (type === 'bar' && !(isFieldDef(fieldOrDatumDef) && (fieldOrDatumDef.bin || fieldOrDatumDef.timeUnit))) {\n if ((orient === 'vertical' && channel === 'x') || (orient === 'horizontal' && channel === 'y')) {\n return barConfig.continuousBandSize;\n }\n }\n }\n\n if (scaleType === ScaleType.POINT) {\n return scaleConfig.pointPadding;\n }\n }\n return undefined;\n}\n\nexport function paddingInner(\n paddingValue: number | SignalRef,\n channel: ScaleChannel,\n mark: Mark,\n scaleType: ScaleType,\n scaleConfig: ScaleConfig,\n hasNestedOffsetScale = false\n) {\n if (paddingValue !== undefined) {\n // If user has already manually specified \"padding\", no need to add default paddingInner.\n return undefined;\n }\n\n if (isXorY(channel)) {\n // Padding is only set for X and Y by default.\n // Basically it doesn't make sense to add padding for color and size.\n\n // paddingOuter would only be called if it's a band scale, just return the default for bandScale.\n const {\n bandPaddingInner,\n barBandPaddingInner,\n rectBandPaddingInner,\n tickBandPaddingInner,\n bandWithNestedOffsetPaddingInner\n } = scaleConfig;\n\n if (hasNestedOffsetScale) {\n return bandWithNestedOffsetPaddingInner;\n }\n\n return getFirstDefined(\n bandPaddingInner,\n mark === 'bar' ? barBandPaddingInner : mark === 'tick' ? tickBandPaddingInner : rectBandPaddingInner\n );\n } else if (isXorYOffset(channel)) {\n if (scaleType === ScaleType.BAND) {\n return scaleConfig.offsetBandPaddingInner;\n }\n }\n return undefined;\n}\n\nexport function paddingOuter(\n paddingValue: number | SignalRef,\n channel: ScaleChannel,\n scaleType: ScaleType,\n paddingInnerValue: number | SignalRef,\n scaleConfig: ScaleConfig,\n hasNestedOffsetScale = false\n) {\n if (paddingValue !== undefined) {\n // If user has already manually specified \"padding\", no need to add default paddingOuter.\n return undefined;\n }\n\n if (isXorY(channel)) {\n const {bandPaddingOuter, bandWithNestedOffsetPaddingOuter} = scaleConfig;\n if (hasNestedOffsetScale) {\n return bandWithNestedOffsetPaddingOuter;\n }\n // Padding is only set for X and Y by default.\n // Basically it doesn't make sense to add padding for color and size.\n if (scaleType === ScaleType.BAND) {\n return getFirstDefined(\n bandPaddingOuter,\n /* By default, paddingOuter is paddingInner / 2. The reason is that\n size (width/height) = step * (cardinality - paddingInner + 2 * paddingOuter).\n and we want the width/height to be integer by default.\n Note that step (by default) and cardinality are integers.) */\n isSignalRef(paddingInnerValue) ? {signal: `${paddingInnerValue.signal}/2`} : paddingInnerValue / 2\n );\n }\n } else if (isXorYOffset(channel)) {\n if (scaleType === ScaleType.POINT) {\n return 0.5; // so the point positions align with centers of band scales.\n } else if (scaleType === ScaleType.BAND) {\n return scaleConfig.offsetBandPaddingOuter;\n }\n }\n return undefined;\n}\n\nexport function reverse(\n scaleType: ScaleType,\n sort: Sort,\n channel: ScaleChannel,\n scaleConfig: ScaleConfig\n) {\n if (channel === 'x' && scaleConfig.xReverse !== undefined) {\n if (hasContinuousDomain(scaleType) && sort === 'descending') {\n if (isSignalRef(scaleConfig.xReverse)) {\n return {signal: `!${scaleConfig.xReverse.signal}`};\n } else {\n return !scaleConfig.xReverse;\n }\n }\n return scaleConfig.xReverse;\n }\n\n if (hasContinuousDomain(scaleType) && sort === 'descending') {\n // For continuous domain scales, Vega does not support domain sort.\n // Thus, we reverse range instead if sort is descending\n return true;\n }\n return undefined;\n}\n\nexport function zero(\n channel: ScaleChannel,\n fieldDef: TypedFieldDef | ScaleDatumDef,\n specifiedDomain: Domain,\n markDef: MarkDef,\n scaleType: ScaleType,\n scaleConfig: ScaleConfig,\n hasSecondaryRangeChannel: boolean\n) {\n // If users explicitly provide a domain, we should not augment zero as that will be unexpected.\n const hasCustomDomain = !!specifiedDomain && specifiedDomain !== 'unaggregated';\n if (hasCustomDomain) {\n if (hasContinuousDomain(scaleType)) {\n if (isArray(specifiedDomain)) {\n const first = specifiedDomain[0];\n const last = specifiedDomain[specifiedDomain.length - 1];\n\n if (isNumber(first) && first <= 0 && isNumber(last) && last >= 0) {\n // if the domain includes zero, make zero remain true\n return true;\n }\n }\n return false;\n }\n }\n\n // If there is no custom domain, return configZero value (=`true` as default) only for the following cases:\n\n // 1) using quantitative field with size\n // While this can be either ratio or interval fields, our assumption is that\n // ratio are more common. However, if the scaleType is discretizing scale, we want to return\n // false so that range doesn't start at zero\n if (channel === 'size' && fieldDef.type === 'quantitative' && !isContinuousToDiscrete(scaleType)) {\n return true;\n }\n\n // 2) non-binned, quantitative x-scale or y-scale\n // (For binning, we should not include zero by default because binning are calculated without zero.)\n // (For area/bar charts with ratio scale chart, we should always include zero.)\n if (\n !(isFieldDef(fieldDef) && fieldDef.bin) &&\n util.contains([...POSITION_SCALE_CHANNELS, ...POLAR_POSITION_SCALE_CHANNELS], channel)\n ) {\n const {orient, type} = markDef;\n if (contains(['bar', 'area', 'line', 'trail'], type)) {\n if ((orient === 'horizontal' && channel === 'y') || (orient === 'vertical' && channel === 'x')) {\n return false;\n }\n }\n\n if (contains(['bar', 'area'], type) && !hasSecondaryRangeChannel) {\n return true;\n }\n\n return scaleConfig?.zero;\n }\n\n return false;\n}\n","import {isBinning} from '../../bin';\nimport {\n getSizeChannel,\n isColorChannel,\n isScaleChannel,\n isXorY,\n isXorYOffset,\n rangeType,\n ScaleChannel\n} from '../../channel';\nimport {DatumDef, isFieldDef, isPositionFieldOrDatumDef, ScaleDatumDef, TypedFieldDef} from '../../channeldef';\nimport * as log from '../../log';\nimport {isRelativeBandSize, MarkDef} from '../../mark';\nimport {channelSupportScaleType, Scale, ScaleType, scaleTypeSupportDataType} from '../../scale';\nimport {normalizeTimeUnit} from '../../timeunit';\nimport * as util from '../../util';\nimport {POLAR_POSITION_SCALE_CHANNEL_INDEX} from './../../channel';\n\nexport type RangeType = 'continuous' | 'discrete' | 'flexible' | undefined;\n\n/**\n * Determine if there is a specified scale type and if it is appropriate,\n * or determine default type if type is unspecified or inappropriate.\n */\n// NOTE: CompassQL uses this method.\nexport function scaleType(\n specifiedScale: Scale,\n channel: ScaleChannel,\n fieldDef: TypedFieldDef | DatumDef,\n mark: MarkDef,\n hasNestedOffsetScale = false\n): ScaleType {\n const defaultScaleType = defaultType(channel, fieldDef, mark, hasNestedOffsetScale);\n const {type} = specifiedScale;\n\n if (!isScaleChannel(channel)) {\n // There is no scale for these channels\n return null;\n }\n if (type !== undefined) {\n // Check if explicitly specified scale type is supported by the channel\n if (!channelSupportScaleType(channel, type)) {\n log.warn(log.message.scaleTypeNotWorkWithChannel(channel, type, defaultScaleType));\n return defaultScaleType;\n }\n\n // Check if explicitly specified scale type is supported by the data type\n if (isFieldDef(fieldDef) && !scaleTypeSupportDataType(type, fieldDef.type)) {\n log.warn(log.message.scaleTypeNotWorkWithFieldDef(type, defaultScaleType));\n return defaultScaleType;\n }\n\n return type;\n }\n\n return defaultScaleType;\n}\n\n/**\n * Determine appropriate default scale type.\n */\n// NOTE: Voyager uses this method.\nfunction defaultType(\n channel: ScaleChannel,\n fieldDef: TypedFieldDef | ScaleDatumDef,\n mark: MarkDef,\n hasNestedOffsetScale: boolean\n): ScaleType {\n switch (fieldDef.type) {\n case 'nominal':\n case 'ordinal': {\n if (isColorChannel(channel) || rangeType(channel) === 'discrete') {\n if (channel === 'shape' && fieldDef.type === 'ordinal') {\n log.warn(log.message.discreteChannelCannotEncode(channel, 'ordinal'));\n }\n return 'ordinal';\n }\n\n if (isXorY(channel) || isXorYOffset(channel)) {\n if (util.contains(['rect', 'bar', 'image', 'rule', 'tick'], mark.type)) {\n // The rect/bar/tick mark should fit into a band.\n // For rule, using band scale to make rule align with axis ticks better https://github.com/vega/vega-lite/issues/3429\n return 'band';\n }\n if (hasNestedOffsetScale) {\n // If there is a nested offset scale, then there is a \"band\" for the span of the nested scale.\n return 'band';\n }\n } else if (mark.type === 'arc' && channel in POLAR_POSITION_SCALE_CHANNEL_INDEX) {\n return 'band';\n }\n\n const dimensionSize = mark[getSizeChannel(channel)];\n if (isRelativeBandSize(dimensionSize)) {\n return 'band';\n }\n\n if (isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis?.tickBand) {\n return 'band';\n }\n // Otherwise, use ordinal point scale so we can easily get center positions of the marks.\n return 'point';\n }\n\n case 'temporal':\n if (isColorChannel(channel)) {\n return 'time';\n } else if (rangeType(channel) === 'discrete') {\n log.warn(log.message.discreteChannelCannotEncode(channel, 'temporal'));\n // TODO: consider using quantize (equivalent to binning) once we have it\n return 'ordinal';\n } else if (isFieldDef(fieldDef) && fieldDef.timeUnit && normalizeTimeUnit(fieldDef.timeUnit).utc) {\n return 'utc';\n }\n return 'time';\n\n case 'quantitative':\n if (isColorChannel(channel)) {\n if (isFieldDef(fieldDef) && isBinning(fieldDef.bin)) {\n return 'bin-ordinal';\n }\n\n return 'linear';\n } else if (rangeType(channel) === 'discrete') {\n log.warn(log.message.discreteChannelCannotEncode(channel, 'quantitative'));\n // TODO: consider using quantize (equivalent to binning) once we have it\n return 'ordinal';\n }\n\n return 'linear';\n\n case 'geojson':\n return undefined;\n }\n\n /* istanbul ignore next: should never reach this */\n throw new Error(log.message.invalidFieldType(fieldDef.type));\n}\n","import {ScaleChannel, SCALE_CHANNELS, SHAPE} from '../../channel';\nimport {getFieldOrDatumDef, ScaleDatumDef, TypedFieldDef} from '../../channeldef';\nimport {channelHasNestedOffsetScale} from '../../encoding';\nimport {GEOSHAPE} from '../../mark';\nimport {\n NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES,\n scaleCompatible,\n ScaleType,\n scaleTypePrecedence\n} from '../../scale';\nimport {GEOJSON} from '../../type';\nimport {keys} from '../../util';\nimport {VgScale} from '../../vega.schema';\nimport {isUnitModel, Model} from '../model';\nimport {defaultScaleResolve} from '../resolve';\nimport {Explicit, mergeValuesWithExplicit, tieBreakByComparing} from '../split';\nimport {UnitModel} from '../unit';\nimport {ScaleComponent, ScaleComponentIndex} from './component';\nimport {parseScaleDomain} from './domain';\nimport {parseScaleProperty, parseScaleRange} from './properties';\nimport {scaleType} from './type';\n\nexport function parseScales(model: Model, {ignoreRange}: {ignoreRange?: boolean} = {}) {\n parseScaleCore(model);\n parseScaleDomain(model);\n for (const prop of NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES) {\n parseScaleProperty(model, prop);\n }\n if (!ignoreRange) {\n // range depends on zero\n parseScaleRange(model);\n }\n}\n\nexport function parseScaleCore(model: Model) {\n if (isUnitModel(model)) {\n model.component.scales = parseUnitScaleCore(model);\n } else {\n model.component.scales = parseNonUnitScaleCore(model);\n }\n}\n\n/**\n * Parse scales for all channels of a model.\n */\nfunction parseUnitScaleCore(model: UnitModel): ScaleComponentIndex {\n const {encoding, mark, markDef} = model;\n const scaleComponents: ScaleComponentIndex = {};\n for (const channel of SCALE_CHANNELS) {\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) as TypedFieldDef | ScaleDatumDef; // must be typed def to have scale\n\n // Don't generate scale for shape of geoshape\n if (fieldOrDatumDef && mark === GEOSHAPE && channel === SHAPE && fieldOrDatumDef.type === GEOJSON) {\n continue;\n }\n\n let specifiedScale = fieldOrDatumDef && fieldOrDatumDef['scale'];\n if (fieldOrDatumDef && specifiedScale !== null && specifiedScale !== false) {\n specifiedScale ??= {};\n const hasNestedOffsetScale = channelHasNestedOffsetScale(encoding, channel);\n\n const sType = scaleType(specifiedScale, channel, fieldOrDatumDef, markDef, hasNestedOffsetScale);\n scaleComponents[channel] = new ScaleComponent(model.scaleName(`${channel}`, true), {\n value: sType,\n explicit: specifiedScale.type === sType\n });\n }\n }\n return scaleComponents;\n}\n\nconst scaleTypeTieBreaker = tieBreakByComparing(\n (st1: ScaleType, st2: ScaleType) => scaleTypePrecedence(st1) - scaleTypePrecedence(st2)\n);\n\nfunction parseNonUnitScaleCore(model: Model) {\n const scaleComponents: ScaleComponentIndex = (model.component.scales = {});\n\n const scaleTypeWithExplicitIndex: Partial>> = {};\n const resolve = model.component.resolve;\n\n // Parse each child scale and determine if a particular channel can be merged.\n for (const child of model.children) {\n parseScaleCore(child);\n\n // Instead of always merging right away -- check if it is compatible to merge first!\n for (const channel of keys(child.component.scales)) {\n // if resolve is undefined, set default first\n resolve.scale[channel] ??= defaultScaleResolve(channel, model);\n\n if (resolve.scale[channel] === 'shared') {\n const explicitScaleType = scaleTypeWithExplicitIndex[channel];\n const childScaleType = child.component.scales[channel].getWithExplicit('type');\n\n if (explicitScaleType) {\n if (scaleCompatible(explicitScaleType.value, childScaleType.value)) {\n // merge scale component if type are compatible\n scaleTypeWithExplicitIndex[channel] = mergeValuesWithExplicit(\n explicitScaleType,\n childScaleType,\n 'type',\n 'scale',\n scaleTypeTieBreaker\n );\n } else {\n // Otherwise, update conflicting channel to be independent\n resolve.scale[channel] = 'independent';\n // Remove from the index so they don't get merged\n delete scaleTypeWithExplicitIndex[channel];\n }\n } else {\n scaleTypeWithExplicitIndex[channel] = childScaleType;\n }\n }\n }\n }\n\n // Merge each channel listed in the index\n for (const channel of keys(scaleTypeWithExplicitIndex)) {\n // Create new merged scale component\n const name = model.scaleName(channel, true);\n const typeWithExplicit = scaleTypeWithExplicitIndex[channel];\n scaleComponents[channel] = new ScaleComponent(name, typeWithExplicit);\n\n // rename each child and mark them as merged\n for (const child of model.children) {\n const childScale = child.component.scales[channel];\n if (childScale) {\n child.renameScale(childScale.get('name'), name);\n childScale.merged = true;\n }\n }\n }\n\n return scaleComponents;\n}\n","import {\n AnchorValue,\n Axis as VgAxis,\n Legend as VgLegend,\n NewSignal,\n Projection as VgProjection,\n Signal,\n SignalRef,\n Title as VgTitle\n} from 'vega';\nimport {\n Channel,\n ExtendedChannel,\n FACET_CHANNELS,\n getPositionScaleChannel,\n isChannel,\n isScaleChannel,\n ScaleChannel,\n SingleDefChannel\n} from '../channel';\nimport {ChannelDef, FieldDef, FieldRefOption, getFieldDef, vgField} from '../channeldef';\nimport {Config} from '../config';\nimport {Data, DataSourceType} from '../data';\nimport {forEach, reduce} from '../encoding';\nimport {ExprRef, replaceExprRef} from '../expr';\nimport * as log from '../log';\nimport {Resolve} from '../resolve';\nimport {ScaleType, hasDiscreteDomain} from '../scale';\nimport {isFacetSpec} from '../spec';\nimport {\n extractCompositionLayout,\n GenericCompositionLayoutWithColumns,\n LayoutSizeMixins,\n SpecType,\n ViewBackground\n} from '../spec/base';\nimport {NormalizedSpec} from '../spec/index';\nimport {extractTitleConfig, isText, TitleParams} from '../title';\nimport {normalizeTransform, Transform} from '../transform';\nimport {contains, Dict, duplicate, isEmpty, keys, varName} from '../util';\nimport {isVgRangeStep, VgData, VgEncodeEntry, VgLayout, VgMarkGroup} from '../vega.schema';\nimport {assembleAxes} from './axis/assemble';\nimport {AxisComponentIndex} from './axis/component';\nimport {signalOrValueRef} from './common';\nimport {ConcatModel} from './concat';\nimport {DataComponent} from './data';\nimport {FacetModel} from './facet';\nimport {assembleHeaderGroups, assembleLayoutTitleBand, assembleTitleGroup} from './header/assemble';\nimport {HEADER_CHANNELS, LayoutHeaderComponent} from './header/component';\nimport {LayerModel} from './layer';\nimport {sizeExpr} from './layoutsize/assemble';\nimport {\n getSizeTypeFromLayoutSizeType,\n LayoutSizeComponent,\n LayoutSizeIndex,\n LayoutSizeType\n} from './layoutsize/component';\nimport {assembleLegends} from './legend/assemble';\nimport {LegendComponentIndex} from './legend/component';\nimport {parseLegend} from './legend/parse';\nimport {assembleProjections} from './projection/assemble';\nimport {ProjectionComponent} from './projection/component';\nimport {parseProjection} from './projection/parse';\nimport {assembleScales} from './scale/assemble';\nimport {ScaleComponent, ScaleComponentIndex} from './scale/component';\nimport {assembleDomain, getFieldFromDomain} from './scale/domain';\nimport {parseScales} from './scale/parse';\nimport {SelectionComponent} from './selection';\nimport {Split} from './split';\nimport {UnitModel} from './unit';\n\n/**\n * Composable Components that are intermediate results of the parsing phase of the\n * compilations. The components represents parts of the specification in a form that\n * can be easily merged (during parsing for composite specs).\n * In addition, these components are easily transformed into Vega specifications\n * during the \"assemble\" phase, which is the last phase of the compilation step.\n */\nexport interface Component {\n data: DataComponent;\n\n layoutSize: LayoutSizeComponent;\n\n layoutHeaders: {\n row?: LayoutHeaderComponent;\n column?: LayoutHeaderComponent;\n facet?: LayoutHeaderComponent;\n };\n\n mark: VgMarkGroup[];\n scales: ScaleComponentIndex;\n projection: ProjectionComponent;\n selection: Dict;\n\n /** Dictionary mapping channel to VgAxis definition */\n axes: AxisComponentIndex;\n\n /** Dictionary mapping channel to VgLegend definition */\n legends: LegendComponentIndex;\n\n resolve: Resolve;\n}\n\nexport interface NameMapInterface {\n rename(oldname: string, newName: string): void;\n has(name: string): boolean;\n get(name: string): string;\n}\n\nexport class NameMap implements NameMapInterface {\n private nameMap: Dict;\n\n constructor() {\n this.nameMap = {};\n }\n\n public rename(oldName: string, newName: string) {\n this.nameMap[oldName] = newName;\n }\n\n public has(name: string): boolean {\n return this.nameMap[name] !== undefined;\n }\n\n public get(name: string): string {\n // If the name appears in the _nameMap, we need to read its new name.\n // We have to loop over the dict just in case the new name also gets renamed.\n while (this.nameMap[name] && name !== this.nameMap[name]) {\n name = this.nameMap[name];\n }\n\n return name;\n }\n}\n\n/*\n We use type guards instead of `instanceof` as `instanceof` makes\n different parts of the compiler depend on the actual implementation of\n the model classes, which in turn depend on different parts of the compiler.\n Thus, `instanceof` leads to circular dependency problems.\n\n On the other hand, type guards only make different parts of the compiler\n depend on the type of the model classes, but not the actual implementation.\n*/\n\nexport function isUnitModel(model: Model): model is UnitModel {\n return model?.type === 'unit';\n}\n\nexport function isFacetModel(model: Model): model is FacetModel {\n return model?.type === 'facet';\n}\n\nexport function isConcatModel(model: Model): model is ConcatModel {\n return model?.type === 'concat';\n}\n\nexport function isLayerModel(model: Model): model is LayerModel {\n return model?.type === 'layer';\n}\n\nexport abstract class Model {\n public readonly name: string;\n\n public size: LayoutSizeMixins;\n\n public readonly title: TitleParams;\n public readonly description: string;\n\n public readonly data: Data | null;\n public readonly transforms: Transform[];\n public readonly layout: GenericCompositionLayoutWithColumns;\n\n /** Name map for scales, which can be renamed by a model's parent. */\n protected scaleNameMap: NameMapInterface;\n\n /** Name map for projections, which can be renamed by a model's parent. */\n protected projectionNameMap: NameMapInterface;\n\n /** Name map for signals, which can be renamed by a model's parent. */\n protected signalNameMap: NameMapInterface;\n\n public readonly component: Component;\n\n public readonly view?: ViewBackground;\n\n public abstract readonly children: Model[];\n\n constructor(\n spec: NormalizedSpec,\n public readonly type: SpecType,\n public readonly parent: Model,\n parentGivenName: string,\n public readonly config: Config,\n resolve: Resolve,\n view?: ViewBackground\n ) {\n this.parent = parent;\n this.config = config;\n this.view = replaceExprRef(view);\n\n // If name is not provided, always use parent's givenName to avoid name conflicts.\n this.name = spec.name ?? parentGivenName;\n this.title = isText(spec.title) ? {text: spec.title} : spec.title ? replaceExprRef(spec.title) : undefined;\n\n // Shared name maps\n this.scaleNameMap = parent ? parent.scaleNameMap : new NameMap();\n this.projectionNameMap = parent ? parent.projectionNameMap : new NameMap();\n this.signalNameMap = parent ? parent.signalNameMap : new NameMap();\n\n this.data = spec.data;\n\n this.description = spec.description;\n this.transforms = normalizeTransform(spec.transform ?? []);\n this.layout = type === 'layer' || type === 'unit' ? {} : extractCompositionLayout(spec, type, config);\n\n this.component = {\n data: {\n sources: parent ? parent.component.data.sources : [],\n outputNodes: parent ? parent.component.data.outputNodes : {},\n outputNodeRefCounts: parent ? parent.component.data.outputNodeRefCounts : {},\n // data is faceted if the spec is a facet spec or the parent has faceted data and data is undefined\n isFaceted: isFacetSpec(spec) || (parent?.component.data.isFaceted && spec.data === undefined)\n },\n layoutSize: new Split(),\n layoutHeaders: {row: {}, column: {}, facet: {}},\n mark: null,\n resolve: {\n scale: {},\n axis: {},\n legend: {},\n ...(resolve ? duplicate(resolve) : {})\n },\n selection: null,\n scales: null,\n projection: null,\n axes: {},\n legends: {}\n };\n }\n\n public get width(): SignalRef {\n return this.getSizeSignalRef('width');\n }\n\n public get height(): SignalRef {\n return this.getSizeSignalRef('height');\n }\n\n public parse() {\n this.parseScale();\n\n this.parseLayoutSize(); // depends on scale\n this.renameTopLevelLayoutSizeSignal();\n\n this.parseSelections();\n this.parseProjection();\n this.parseData(); // (pathorder) depends on markDef; selection filters depend on parsed selections; depends on projection because some transforms require the finalized projection name.\n this.parseAxesAndHeaders(); // depends on scale and layout size\n this.parseLegends(); // depends on scale, markDef\n this.parseMarkGroup(); // depends on data name, scale, layout size, axisGroup, and children's scale, axis, legend and mark.\n }\n\n public abstract parseData(): void;\n\n public abstract parseSelections(): void;\n\n public parseScale() {\n parseScales(this);\n }\n\n public parseProjection() {\n parseProjection(this);\n }\n\n public abstract parseLayoutSize(): void;\n\n /**\n * Rename top-level spec's size to be just width / height, ignoring model name.\n * This essentially merges the top-level spec's width/height signals with the width/height signals\n * to help us reduce redundant signals declaration.\n */\n private renameTopLevelLayoutSizeSignal() {\n if (this.getName('width') !== 'width') {\n this.renameSignal(this.getName('width'), 'width');\n }\n if (this.getName('height') !== 'height') {\n this.renameSignal(this.getName('height'), 'height');\n }\n }\n\n public abstract parseMarkGroup(): void;\n\n public abstract parseAxesAndHeaders(): void;\n\n public parseLegends() {\n parseLegend(this);\n }\n\n public abstract assembleSelectionTopLevelSignals(signals: NewSignal[]): NewSignal[];\n public abstract assembleSignals(): NewSignal[];\n\n public abstract assembleSelectionData(data: readonly VgData[]): readonly VgData[];\n\n public abstract assembleGroupStyle(): string | string[];\n\n private assembleEncodeFromView(view: ViewBackground): VgEncodeEntry {\n // Exclude \"style\"\n const {style: _, ...baseView} = view;\n\n const e: VgEncodeEntry = {};\n for (const property of keys(baseView)) {\n const value = baseView[property];\n if (value !== undefined) {\n e[property] = signalOrValueRef(value);\n }\n }\n\n return e;\n }\n\n public assembleGroupEncodeEntry(isTopLevel: boolean): VgEncodeEntry {\n let encodeEntry: VgEncodeEntry = {};\n if (this.view) {\n encodeEntry = this.assembleEncodeFromView(this.view);\n }\n\n if (!isTopLevel) {\n // Descriptions are already added to the top-level description so we only need to add them to the inner views.\n if (this.description) {\n encodeEntry['description'] = signalOrValueRef(this.description);\n }\n\n // For top-level spec, we can set the global width and height signal to adjust the group size.\n // For other child specs, we have to manually set width and height in the encode entry.\n if (this.type === 'unit' || this.type === 'layer') {\n return {\n width: this.getSizeSignalRef('width'),\n height: this.getSizeSignalRef('height'),\n ...encodeEntry\n };\n }\n }\n\n return isEmpty(encodeEntry) ? undefined : encodeEntry;\n }\n\n public assembleLayout(): VgLayout {\n if (!this.layout) {\n return undefined;\n }\n\n const {spacing, ...layout} = this.layout;\n\n const {component, config} = this;\n const titleBand = assembleLayoutTitleBand(component.layoutHeaders, config);\n\n return {\n padding: spacing,\n ...this.assembleDefaultLayout(),\n ...layout,\n ...(titleBand ? {titleBand} : {})\n };\n }\n\n protected assembleDefaultLayout(): VgLayout {\n return {};\n }\n\n public abstract assembleLayoutSignals(): NewSignal[];\n\n public assembleHeaderMarks(): VgMarkGroup[] {\n const {layoutHeaders} = this.component;\n let headerMarks = [];\n\n for (const channel of FACET_CHANNELS) {\n if (layoutHeaders[channel].title) {\n headerMarks.push(assembleTitleGroup(this, channel));\n }\n }\n\n for (const channel of HEADER_CHANNELS) {\n headerMarks = headerMarks.concat(assembleHeaderGroups(this, channel));\n }\n return headerMarks;\n }\n\n public abstract assembleMarks(): VgMarkGroup[];\n\n public assembleAxes(): VgAxis[] {\n return assembleAxes(this.component.axes, this.config);\n }\n\n public assembleLegends(): VgLegend[] {\n return assembleLegends(this);\n }\n\n public assembleProjections(): VgProjection[] {\n return assembleProjections(this);\n }\n\n public assembleTitle(): VgTitle {\n const {encoding, ...titleNoEncoding} = this.title ?? ({} as TitleParams);\n\n const title: VgTitle = {\n ...extractTitleConfig(this.config.title).nonMarkTitleProperties,\n ...titleNoEncoding,\n ...(encoding ? {encode: {update: encoding}} : {})\n };\n\n if (title.text) {\n if (contains(['unit', 'layer'], this.type)) {\n // Unit/Layer\n if (contains(['middle', undefined], title.anchor)) {\n title.frame ??= 'group';\n }\n } else {\n // composition with Vega layout\n\n // Set title = \"start\" by default for composition as \"middle\" does not look nice\n // https://github.com/vega/vega/issues/960#issuecomment-471360328\n title.anchor ??= 'start';\n }\n\n return isEmpty(title) ? undefined : title;\n }\n return undefined;\n }\n\n /**\n * 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.\n */\n public assembleGroup(signals: Signal[] = []) {\n const group: VgMarkGroup = {};\n\n signals = signals.concat(this.assembleSignals());\n\n if (signals.length > 0) {\n group.signals = signals;\n }\n\n const layout = this.assembleLayout();\n if (layout) {\n group.layout = layout;\n }\n\n group.marks = [].concat(this.assembleHeaderMarks(), this.assembleMarks());\n\n // Only include scales if this spec is top-level or if parent is facet.\n // (Otherwise, it will be merged with upper-level's scope.)\n const scales = !this.parent || isFacetModel(this.parent) ? assembleScales(this) : [];\n if (scales.length > 0) {\n group.scales = scales;\n }\n\n const axes = this.assembleAxes();\n if (axes.length > 0) {\n group.axes = axes;\n }\n\n const legends = this.assembleLegends();\n if (legends.length > 0) {\n group.legends = legends;\n }\n\n return group;\n }\n\n public getName(text: string) {\n return varName((this.name ? `${this.name}_` : '') + text);\n }\n\n public getDataName(type: DataSourceType) {\n return this.getName(DataSourceType[type].toLowerCase());\n }\n\n /**\n * Request a data source name for the given data source type and mark that data source as required.\n * This method should be called in parse, so that all used data source can be correctly instantiated in assembleData().\n * You can lookup the correct dataset name in assemble with `lookupDataSource`.\n */\n public requestDataName(name: DataSourceType) {\n const fullName = this.getDataName(name);\n\n // Increase ref count. This is critical because otherwise we won't create a data source.\n // We also increase the ref counts on OutputNode.getSource() calls.\n const refCounts = this.component.data.outputNodeRefCounts;\n refCounts[fullName] = (refCounts[fullName] || 0) + 1;\n\n return fullName;\n }\n\n public getSizeSignalRef(layoutSizeType: LayoutSizeType): SignalRef {\n if (isFacetModel(this.parent)) {\n const sizeType = getSizeTypeFromLayoutSizeType(layoutSizeType);\n const channel = getPositionScaleChannel(sizeType);\n const scaleComponent = this.component.scales[channel];\n\n if (scaleComponent && !scaleComponent.merged) {\n // independent scale\n const type = scaleComponent.get('type');\n const range = scaleComponent.get('range');\n\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const scaleName = scaleComponent.get('name');\n const domain = assembleDomain(this, channel);\n const field = getFieldFromDomain(domain);\n if (field) {\n const fieldRef = vgField({aggregate: 'distinct', field}, {expr: 'datum'});\n return {\n signal: sizeExpr(scaleName, scaleComponent, fieldRef)\n };\n } else {\n log.warn(log.message.unknownField(channel));\n return null;\n }\n }\n }\n }\n\n return {\n signal: this.signalNameMap.get(this.getName(layoutSizeType))\n };\n }\n\n /**\n * Lookup the name of the datasource for an output node. You probably want to call this in assemble.\n */\n public lookupDataSource(name: string) {\n const node = this.component.data.outputNodes[name];\n\n if (!node) {\n // Name not found in map so let's just return what we got.\n // This can happen if we already have the correct name.\n return name;\n }\n\n return node.getSource();\n }\n\n public getSignalName(oldSignalName: string): string {\n return this.signalNameMap.get(oldSignalName);\n }\n\n public renameSignal(oldName: string, newName: string) {\n this.signalNameMap.rename(oldName, newName);\n }\n\n public renameScale(oldName: string, newName: string) {\n this.scaleNameMap.rename(oldName, newName);\n }\n\n public renameProjection(oldName: string, newName: string) {\n this.projectionNameMap.rename(oldName, newName);\n }\n\n /**\n * @return scale name for a given channel after the scale has been parsed and named.\n */\n public scaleName(originalScaleName: ScaleChannel | string, parse?: boolean): string {\n if (parse) {\n // During the parse phase always return a value\n // No need to refer to rename map because a scale can't be renamed\n // before it has the original name.\n return this.getName(originalScaleName);\n }\n\n // If there is a scale for the channel, it should either\n // be in the scale component or exist in the name map\n if (\n // If there is a scale for the channel, there should be a local scale component for it\n (isChannel(originalScaleName) && isScaleChannel(originalScaleName) && this.component.scales[originalScaleName]) ||\n // in the scale name map (the scale get merged by its parent)\n this.scaleNameMap.has(this.getName(originalScaleName))\n ) {\n return this.scaleNameMap.get(this.getName(originalScaleName));\n }\n return undefined;\n }\n\n /**\n * @return projection name after the projection has been parsed and named.\n */\n public projectionName(parse?: boolean): string {\n if (parse) {\n // During the parse phase always return a value\n // No need to refer to rename map because a projection can't be renamed\n // before it has the original name.\n return this.getName('projection');\n }\n\n if (\n (this.component.projection && !this.component.projection.merged) ||\n this.projectionNameMap.has(this.getName('projection'))\n ) {\n return this.projectionNameMap.get(this.getName('projection'));\n }\n return undefined;\n }\n\n /**\n * Corrects the data references in marks after assemble.\n */\n public correctDataNames = (mark: VgMarkGroup) => {\n // TODO: make this correct\n\n // for normal data references\n if (mark.from?.data) {\n mark.from.data = this.lookupDataSource(mark.from.data);\n }\n\n // for access to facet data\n if (mark.from?.facet?.data) {\n mark.from.facet.data = this.lookupDataSource(mark.from.facet.data);\n }\n\n return mark;\n };\n\n /**\n * Traverse a model's hierarchy to get the scale component for a particular channel.\n */\n public getScaleComponent(channel: ScaleChannel): ScaleComponent {\n /* istanbul ignore next: This is warning for debugging test */\n if (!this.component.scales) {\n throw new Error(\n 'getScaleComponent cannot be called before parseScale(). Make sure you have called parseScale or use parseUnitModelWithScale().'\n );\n }\n\n const localScaleComponent = this.component.scales[channel];\n if (localScaleComponent && !localScaleComponent.merged) {\n return localScaleComponent;\n }\n return this.parent ? this.parent.getScaleComponent(channel) : undefined;\n }\n\n public getScaleType(channel: ScaleChannel): ScaleType {\n const scaleComponent = this.getScaleComponent(channel);\n return scaleComponent ? scaleComponent.get('type') : undefined;\n }\n\n /**\n * Traverse a model's hierarchy to get a particular selection component.\n */\n public getSelectionComponent(variableName: string, origName: string): SelectionComponent {\n let sel = this.component.selection[variableName];\n if (!sel && this.parent) {\n sel = this.parent.getSelectionComponent(variableName, origName);\n }\n if (!sel) {\n throw new Error(log.message.selectionNotFound(origName));\n }\n return sel;\n }\n\n /**\n * Returns true if the model has a signalRef for an axis orient.\n */\n public hasAxisOrientSignalRef() {\n return (\n this.component.axes.x?.some(a => a.hasOrientSignalRef()) ||\n this.component.axes.y?.some(a => a.hasOrientSignalRef())\n );\n }\n}\n\n/** Abstract class for UnitModel and FacetModel. Both of which can contain fieldDefs as a part of its own specification. */\nexport abstract class ModelWithField extends Model {\n public abstract fieldDef(channel: SingleDefChannel): FieldDef;\n\n /** Get \"field\" reference for Vega */\n public vgField(channel: SingleDefChannel, opt: FieldRefOption = {}) {\n const fieldDef = this.fieldDef(channel);\n\n if (!fieldDef) {\n return undefined;\n }\n\n return vgField(fieldDef, opt);\n }\n\n protected abstract getMapping(): Partial>;\n\n public reduceFieldDef(f: (acc: U, fd: FieldDef, c: Channel) => U, init: T): T {\n return reduce(\n this.getMapping(),\n (acc: U, cd: ChannelDef, c: Channel) => {\n const fieldDef = getFieldDef(cd);\n if (fieldDef) {\n return f(acc, fieldDef, c);\n }\n return acc;\n },\n init\n );\n }\n\n public forEachFieldDef(f: (fd: FieldDef, c: ExtendedChannel) => void, t?: any) {\n forEach(\n this.getMapping(),\n (cd, c) => {\n const fieldDef = getFieldDef(cd);\n if (fieldDef) {\n f(fieldDef, c);\n }\n },\n t\n );\n }\n\n public abstract channelHasField(channel: Channel): boolean;\n}\n","import {KDETransform as VgKDETransform} from 'vega';\nimport {DensityTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for density transform nodes\n */\nexport class DensityTransformNode extends DataFlowNode {\n public clone() {\n return new DensityTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: DensityTransform\n ) {\n super(parent);\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = this.transform.as ?? [undefined, undefined];\n this.transform.as = [specifiedAs[0] ?? 'value', specifiedAs[1] ?? 'density'];\n const resolve = this.transform.resolve ?? 'shared';\n this.transform.resolve = resolve;\n }\n\n public dependentFields() {\n return new Set([this.transform.density, ...(this.transform.groupby ?? [])]);\n }\n\n public producedFields() {\n return new Set(this.transform.as);\n }\n\n public hash() {\n return `DensityTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgKDETransform {\n const {density, ...rest} = this.transform;\n const result: VgKDETransform = {\n type: 'kde',\n field: density,\n ...rest\n };\n result.resolve = this.transform.resolve;\n return result;\n }\n}\n","import {ExtentTransform as VgExtentTransform} from 'vega';\nimport {ExtentTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for flatten transform nodes\n */\nexport class ExtentTransformNode extends DataFlowNode {\n public clone() {\n return new ExtentTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: ExtentTransform\n ) {\n super(parent);\n this.transform = duplicate(transform);\n }\n\n public dependentFields() {\n return new Set([this.transform.extent]);\n }\n\n public producedFields() {\n return new Set([]);\n }\n\n public hash() {\n return `ExtentTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgExtentTransform {\n const {extent, param} = this.transform;\n const result: VgExtentTransform = {\n type: 'extent',\n field: extent,\n signal: param\n };\n return result;\n }\n}\n","import {FlattenTransform as VgFlattenTransform} from 'vega';\nimport {FlattenTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for flatten transform nodes\n */\nexport class FlattenTransformNode extends DataFlowNode {\n public clone() {\n return new FlattenTransformNode(this.parent, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: FlattenTransform\n ) {\n super(parent);\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const {flatten, as = []} = this.transform;\n this.transform.as = flatten.map((f, i) => as[i] ?? f);\n }\n\n public dependentFields() {\n return new Set(this.transform.flatten);\n }\n\n public producedFields() {\n return new Set(this.transform.as);\n }\n\n public hash() {\n return `FlattenTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgFlattenTransform {\n const {flatten: fields, as} = this.transform;\n\n const result: VgFlattenTransform = {\n type: 'flatten',\n fields,\n as\n };\n return result;\n }\n}\n","import {FoldTransform as VgFoldTransform} from 'vega';\nimport {FoldTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for flatten transform nodes\n */\nexport class FoldTransformNode extends DataFlowNode {\n public clone() {\n return new FoldTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: FoldTransform\n ) {\n super(parent);\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = this.transform.as ?? [undefined, undefined];\n this.transform.as = [specifiedAs[0] ?? 'key', specifiedAs[1] ?? 'value'];\n }\n\n public dependentFields() {\n return new Set(this.transform.fold);\n }\n\n public producedFields() {\n return new Set(this.transform.as);\n }\n\n public hash() {\n return `FoldTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgFoldTransform {\n const {fold, as} = this.transform;\n const result: VgFoldTransform = {\n type: 'fold',\n fields: fold,\n as\n };\n return result;\n }\n}\n","import {Transforms as VgTransform, Vector2} from 'vega';\nimport {isString} from 'vega-util';\nimport {GeoPositionChannel, LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2, SHAPE} from '../../channel';\nimport {getFieldOrDatumDef, isDatumDef, isFieldDef, isValueDef} from '../../channeldef';\nimport {GEOJSON} from '../../type';\nimport {duplicate, hash} from '../../util';\nimport {VgExprRef} from '../../vega.schema';\nimport {UnitModel} from '../unit';\nimport {DataFlowNode} from './dataflow';\n\nexport class GeoJSONNode extends DataFlowNode {\n public clone() {\n return new GeoJSONNode(null, duplicate(this.fields), this.geojson, this.signal);\n }\n\n public static parseAll(parent: DataFlowNode, model: UnitModel): DataFlowNode {\n if (model.component.projection && !model.component.projection.isFit) {\n return parent;\n }\n\n let geoJsonCounter = 0;\n\n for (const coordinates of [\n [LONGITUDE, LATITUDE],\n [LONGITUDE2, LATITUDE2]\n ] as Vector2[]) {\n const pair = coordinates.map(channel => {\n const def = getFieldOrDatumDef(model.encoding[channel]);\n return isFieldDef(def)\n ? def.field\n : isDatumDef(def)\n ? {expr: `${def.datum}`}\n : isValueDef(def)\n ? {expr: `${def['value']}`}\n : undefined;\n }) as [GeoPositionChannel, GeoPositionChannel];\n\n if (pair[0] || pair[1]) {\n parent = new GeoJSONNode(parent, pair, null, model.getName(`geojson_${geoJsonCounter++}`));\n }\n }\n\n if (model.channelHasField(SHAPE)) {\n const fieldDef = model.typedFieldDef(SHAPE);\n if (fieldDef.type === GEOJSON) {\n parent = new GeoJSONNode(parent, null, fieldDef.field, model.getName(`geojson_${geoJsonCounter++}`));\n }\n }\n\n return parent;\n }\n\n constructor(\n parent: DataFlowNode,\n private fields?: Vector2,\n private geojson?: string,\n private signal?: string\n ) {\n super(parent);\n }\n\n public dependentFields() {\n const fields = (this.fields ?? []).filter(isString) as string[];\n return new Set([...(this.geojson ? [this.geojson] : []), ...fields]);\n }\n\n public producedFields() {\n return new Set();\n }\n\n public hash() {\n return `GeoJSON ${this.geojson} ${this.signal} ${hash(this.fields)}`;\n }\n\n public assemble(): VgTransform[] {\n return [\n ...(this.geojson\n ? [\n {\n type: 'filter',\n expr: `isValid(datum[\"${this.geojson}\"])`\n } as const\n ]\n : []),\n {\n type: 'geojson',\n ...(this.fields ? {fields: this.fields} : {}),\n ...(this.geojson ? {geojson: this.geojson} : {}),\n signal: this.signal\n }\n ];\n }\n}\n","import {GeoPointTransform as VgGeoPointTransform, Vector2} from 'vega';\nimport {isString} from 'vega-util';\nimport {GeoPositionChannel, LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2} from '../../channel';\nimport {getFieldOrDatumDef, isDatumDef, isFieldDef, isValueDef} from '../../channeldef';\nimport {duplicate, hash} from '../../util';\nimport {VgExprRef} from '../../vega.schema';\nimport {UnitModel} from '../unit';\nimport {DataFlowNode} from './dataflow';\n\nexport class GeoPointNode extends DataFlowNode {\n public clone() {\n return new GeoPointNode(null, this.projection, duplicate(this.fields), duplicate(this.as));\n }\n\n constructor(\n parent: DataFlowNode,\n private projection: string,\n private fields: [string | VgExprRef, string | VgExprRef],\n private as: [string, string]\n ) {\n super(parent);\n }\n\n public static parseAll(parent: DataFlowNode, model: UnitModel): DataFlowNode {\n if (!model.projectionName()) {\n return parent;\n }\n\n for (const coordinates of [\n [LONGITUDE, LATITUDE],\n [LONGITUDE2, LATITUDE2]\n ] as Vector2[]) {\n const pair = coordinates.map(channel => {\n const def = getFieldOrDatumDef(model.encoding[channel]);\n return isFieldDef(def)\n ? def.field\n : isDatumDef(def)\n ? {expr: `${def.datum}`}\n : isValueDef(def)\n ? {expr: `${def['value']}`}\n : undefined;\n }) as [GeoPositionChannel, GeoPositionChannel];\n\n const suffix = coordinates[0] === LONGITUDE2 ? '2' : '';\n\n if (pair[0] || pair[1]) {\n parent = new GeoPointNode(parent, model.projectionName(), pair, [\n model.getName(`x${suffix}`),\n model.getName(`y${suffix}`)\n ]);\n }\n }\n\n return parent;\n }\n\n public dependentFields() {\n return new Set(this.fields.filter(isString));\n }\n\n public producedFields() {\n return new Set(this.as);\n }\n\n public hash() {\n return `Geopoint ${this.projection} ${hash(this.fields)} ${hash(this.as)}`;\n }\n\n public assemble(): VgGeoPointTransform {\n return {\n type: 'geopoint',\n projection: this.projection,\n fields: this.fields,\n as: this.as\n };\n }\n}\n","import {\n FormulaTransform as VgFormulaTransform,\n ImputeTransform as VgImputeTransform,\n SignalRef,\n WindowTransform as VgWindowTransform\n} from 'vega';\nimport {isFieldDef} from '../../channeldef';\nimport {pathGroupingFields} from '../../encoding';\nimport {ImputeSequence, ImputeTransform, isImputeSequence} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {UnitModel} from '../unit';\nimport {DataFlowNode} from './dataflow';\n\nexport class ImputeNode extends DataFlowNode {\n public clone() {\n return new ImputeNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private readonly transform: ImputeTransform\n ) {\n super(parent);\n }\n\n public dependentFields() {\n return new Set([this.transform.impute, this.transform.key, ...(this.transform.groupby ?? [])]);\n }\n\n public producedFields() {\n return new Set([this.transform.impute]);\n }\n\n private processSequence(keyvals: ImputeSequence): SignalRef {\n const {start = 0, stop, step} = keyvals;\n const result = [start, stop, ...(step ? [step] : [])].join(',');\n\n return {signal: `sequence(${result})`};\n }\n\n public static makeFromTransform(parent: DataFlowNode, imputeTransform: ImputeTransform): ImputeNode {\n return new ImputeNode(parent, imputeTransform);\n }\n\n public static makeFromEncoding(parent: DataFlowNode, model: UnitModel) {\n const encoding = model.encoding;\n const xDef = encoding.x;\n const yDef = encoding.y;\n\n if (isFieldDef(xDef) && isFieldDef(yDef)) {\n const imputedChannel = xDef.impute ? xDef : yDef.impute ? yDef : undefined;\n if (imputedChannel === undefined) {\n return undefined;\n }\n const keyChannel = xDef.impute ? yDef : yDef.impute ? xDef : undefined;\n const {method, value, frame, keyvals} = imputedChannel.impute;\n const groupbyFields = pathGroupingFields(model.mark, encoding);\n\n return new ImputeNode(parent, {\n impute: imputedChannel.field,\n key: keyChannel.field,\n ...(method ? {method} : {}),\n ...(value !== undefined ? {value} : {}),\n ...(frame ? {frame} : {}),\n ...(keyvals !== undefined ? {keyvals} : {}),\n ...(groupbyFields.length ? {groupby: groupbyFields} : {})\n });\n }\n return null;\n }\n\n public hash() {\n return `Impute ${hash(this.transform)}`;\n }\n\n public assemble() {\n const {impute, key, keyvals, method, groupby, value, frame = [null, null] as [null, null]} = this.transform;\n\n const imputeTransform: VgImputeTransform = {\n type: 'impute',\n field: impute,\n key,\n ...(keyvals ? {keyvals: isImputeSequence(keyvals) ? this.processSequence(keyvals) : keyvals} : {}),\n method: 'value',\n ...(groupby ? {groupby} : {}),\n value: !method || method === 'value' ? value : null\n };\n\n if (method && method !== 'value') {\n const deriveNewField: VgWindowTransform = {\n type: 'window',\n as: [`imputed_${impute}_value`],\n ops: [method],\n fields: [impute],\n frame,\n ignorePeers: false,\n ...(groupby ? {groupby} : {})\n };\n const replaceOriginal: VgFormulaTransform = {\n type: 'formula',\n expr: `datum.${impute} === null ? datum.imputed_${impute}_value : datum.${impute}`,\n as: impute\n };\n return [imputeTransform, deriveNewField, replaceOriginal];\n } else {\n return [imputeTransform];\n }\n }\n}\n","import {LoessTransform as VgLoessTransform} from 'vega';\nimport {LoessTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for loess transform nodes\n */\nexport class LoessTransformNode extends DataFlowNode {\n public clone() {\n return new LoessTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: LoessTransform\n ) {\n super(parent);\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = this.transform.as ?? [undefined, undefined];\n this.transform.as = [specifiedAs[0] ?? transform.on, specifiedAs[1] ?? transform.loess];\n }\n\n public dependentFields() {\n return new Set([this.transform.loess, this.transform.on, ...(this.transform.groupby ?? [])]);\n }\n\n public producedFields() {\n return new Set(this.transform.as);\n }\n\n public hash() {\n return `LoessTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgLoessTransform {\n const {loess, on, ...rest} = this.transform;\n const result: VgLoessTransform = {\n type: 'loess',\n x: on,\n y: loess,\n ...rest\n };\n return result;\n }\n}\n","import {LookupTransform as VgLookupTransform} from 'vega';\nimport {array, isString} from 'vega-util';\nimport * as log from '../../log';\nimport {isLookupData, isLookupSelection, LookupTransform} from '../../transform';\nimport {duplicate, hash, varName} from '../../util';\nimport {Model} from '../model';\nimport {DataFlowNode, OutputNode} from './dataflow';\nimport {findSource} from './parse';\nimport {SourceNode} from './source';\nimport {DataSourceType} from '../../data';\n\nexport class LookupNode extends DataFlowNode {\n public clone() {\n return new LookupNode(null, duplicate(this.transform), this.secondary);\n }\n\n constructor(\n parent: DataFlowNode,\n public readonly transform: LookupTransform,\n public readonly secondary: string\n ) {\n super(parent);\n }\n\n public static make(parent: DataFlowNode, model: Model, transform: LookupTransform, counter: number) {\n const sources = model.component.data.sources;\n const {from} = transform;\n let fromOutputNode = null;\n\n if (isLookupData(from)) {\n let fromSource = findSource(from.data, sources);\n\n if (!fromSource) {\n fromSource = new SourceNode(from.data);\n sources.push(fromSource);\n }\n\n const fromOutputName = model.getName(`lookup_${counter}`);\n fromOutputNode = new OutputNode(\n fromSource,\n fromOutputName,\n DataSourceType.Lookup,\n model.component.data.outputNodeRefCounts\n );\n model.component.data.outputNodes[fromOutputName] = fromOutputNode;\n } else if (isLookupSelection(from)) {\n const selName = from.param;\n transform = {as: selName, ...transform};\n let selCmpt;\n\n try {\n selCmpt = model.getSelectionComponent(varName(selName), selName);\n } catch (e) {\n throw new Error(log.message.cannotLookupVariableParameter(selName));\n }\n\n fromOutputNode = selCmpt.materialized;\n if (!fromOutputNode) {\n throw new Error(log.message.noSameUnitLookup(selName));\n }\n }\n\n return new LookupNode(parent, transform, fromOutputNode.getSource());\n }\n\n public dependentFields() {\n return new Set([this.transform.lookup]);\n }\n\n public producedFields() {\n return new Set(this.transform.as ? array(this.transform.as) : this.transform.from.fields);\n }\n\n public hash() {\n return `Lookup ${hash({transform: this.transform, secondary: this.secondary})}`;\n }\n\n public assemble(): VgLookupTransform {\n let foreign: Partial;\n\n if (this.transform.from.fields) {\n // lookup a few fields and add create a flat output\n foreign = {\n values: this.transform.from.fields,\n ...(this.transform.as ? {as: array(this.transform.as)} : {})\n };\n } else {\n // lookup full record and nest it\n let asName = this.transform.as;\n if (!isString(asName)) {\n log.warn(log.message.NO_FIELDS_NEEDS_AS);\n asName = '_lookup';\n }\n\n foreign = {\n as: [asName]\n };\n }\n\n return {\n type: 'lookup',\n from: this.secondary,\n key: this.transform.from.key,\n fields: [this.transform.lookup],\n ...foreign,\n ...(this.transform.default ? {default: this.transform.default} : {})\n };\n }\n}\n","import {QuantileTransform as VgQuantileTransform} from 'vega';\nimport {QuantileTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for quantile transform nodes\n */\nexport class QuantileTransformNode extends DataFlowNode {\n public clone() {\n return new QuantileTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: QuantileTransform\n ) {\n super(parent);\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = this.transform.as ?? [undefined, undefined];\n this.transform.as = [specifiedAs[0] ?? 'prob', specifiedAs[1] ?? 'value'];\n }\n\n public dependentFields() {\n return new Set([this.transform.quantile, ...(this.transform.groupby ?? [])]);\n }\n\n public producedFields() {\n return new Set(this.transform.as);\n }\n\n public hash() {\n return `QuantileTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgQuantileTransform {\n const {quantile, ...rest} = this.transform;\n const result: VgQuantileTransform = {\n type: 'quantile',\n field: quantile,\n ...rest\n };\n return result;\n }\n}\n","import {RegressionTransform as VgRegressionTransform} from 'vega';\nimport {RegressionTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for regression transform nodes\n */\nexport class RegressionTransformNode extends DataFlowNode {\n public clone() {\n return new RegressionTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: RegressionTransform\n ) {\n super(parent);\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = this.transform.as ?? [undefined, undefined];\n this.transform.as = [specifiedAs[0] ?? transform.on, specifiedAs[1] ?? transform.regression];\n }\n\n public dependentFields() {\n return new Set([this.transform.regression, this.transform.on, ...(this.transform.groupby ?? [])]);\n }\n\n public producedFields() {\n return new Set(this.transform.as);\n }\n\n public hash() {\n return `RegressionTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgRegressionTransform {\n const {regression, on, ...rest} = this.transform;\n const result: VgRegressionTransform = {\n type: 'regression',\n x: on,\n y: regression,\n ...rest\n };\n return result;\n }\n}\n","import {PivotTransform} from '../../transform';\nimport {duplicate, hash, unique} from '../../util';\nimport {PivotTransform as VgPivotTransform} from 'vega';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for pivot transform nodes.\n */\nexport class PivotTransformNode extends DataFlowNode {\n public clone() {\n return new PivotTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: PivotTransform\n ) {\n super(parent);\n }\n\n public addDimensions(fields: readonly string[]) {\n this.transform.groupby = unique((this.transform.groupby ?? []).concat(fields), d => d);\n }\n\n public producedFields(): undefined {\n return undefined; // return undefined so that potentially everything can depend on the pivot\n }\n\n public dependentFields() {\n return new Set([this.transform.pivot, this.transform.value, ...(this.transform.groupby ?? [])]);\n }\n\n public hash() {\n return `PivotTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgPivotTransform {\n const {pivot, value, groupby, limit, op} = this.transform;\n return {\n type: 'pivot',\n field: pivot,\n value,\n ...(limit !== undefined ? {limit} : {}),\n ...(op !== undefined ? {op} : {}),\n ...(groupby !== undefined ? {groupby} : {})\n };\n }\n}\n","import {SampleTransform as VgSampleTransform} from 'vega';\nimport {SampleTransform} from '../../transform';\nimport {duplicate, hash} from '../../util';\nimport {DataFlowNode} from './dataflow';\n\n/**\n * A class for the sample transform nodes\n */\nexport class SampleTransformNode extends DataFlowNode {\n public clone() {\n return new SampleTransformNode(null, duplicate(this.transform));\n }\n\n constructor(\n parent: DataFlowNode,\n private transform: SampleTransform\n ) {\n super(parent);\n }\n\n public dependentFields() {\n return new Set();\n }\n\n public producedFields() {\n return new Set();\n }\n\n public hash() {\n return `SampleTransform ${hash(this.transform)}`;\n }\n\n public assemble(): VgSampleTransform {\n return {\n type: 'sample',\n size: this.transform.sample\n };\n }\n}\n","import {InlineDataset, isUrlData} from '../../data';\nimport {Dict} from '../../util';\nimport {VgData} from '../../vega.schema';\nimport {DataComponent} from './';\nimport {AggregateNode} from './aggregate';\nimport {BinNode} from './bin';\nimport {CalculateNode} from './calculate';\nimport {DataFlowNode, OutputNode} from './dataflow';\nimport {DensityTransformNode} from './density';\nimport {ExtentTransformNode} from './extent';\nimport {FacetNode} from './facet';\nimport {FilterNode} from './filter';\nimport {FilterInvalidNode} from './filterinvalid';\nimport {FlattenTransformNode} from './flatten';\nimport {FoldTransformNode} from './fold';\nimport {ParseNode} from './formatparse';\nimport {GeoJSONNode} from './geojson';\nimport {GeoPointNode} from './geopoint';\nimport {GraticuleNode} from './graticule';\nimport {IdentifierNode} from './identifier';\nimport {ImputeNode} from './impute';\nimport {JoinAggregateTransformNode} from './joinaggregate';\nimport {LoessTransformNode} from './loess';\nimport {LookupNode} from './lookup';\nimport {QuantileTransformNode} from './quantile';\nimport {RegressionTransformNode} from './regression';\nimport {PivotTransformNode} from './pivot';\nimport {SampleTransformNode} from './sample';\nimport {SequenceNode} from './sequence';\nimport {SourceNode} from './source';\nimport {StackNode} from './stack';\nimport {TimeUnitNode} from './timeunit';\nimport {WindowTransformNode} from './window';\n\nfunction makeWalkTree(data: VgData[]) {\n // to name datasources\n let datasetIndex = 0;\n\n /**\n * Recursively walk down the tree.\n */\n function walkTree(node: DataFlowNode, dataSource: VgData) {\n if (node instanceof SourceNode) {\n // If the source is a named data source or a data source with values, we need\n // to put it in a different data source. Otherwise, Vega may override the data.\n if (!node.isGenerator && !isUrlData(node.data)) {\n data.push(dataSource);\n const newData: VgData = {\n name: null,\n source: dataSource.name,\n transform: []\n };\n dataSource = newData;\n }\n }\n\n if (node instanceof ParseNode) {\n if (node.parent instanceof SourceNode && !dataSource.source) {\n // If node's parent is a root source and the data source does not refer to another data source, use normal format parse\n dataSource.format = {\n ...dataSource.format,\n parse: node.assembleFormatParse()\n };\n\n // add calculates for all nested fields\n dataSource.transform.push(...node.assembleTransforms(true));\n } else {\n // Otherwise use Vega expression to parse\n dataSource.transform.push(...node.assembleTransforms());\n }\n }\n\n if (node instanceof FacetNode) {\n if (!dataSource.name) {\n dataSource.name = `data_${datasetIndex++}`;\n }\n\n if (!dataSource.source || dataSource.transform.length > 0) {\n data.push(dataSource);\n node.data = dataSource.name;\n } else {\n node.data = dataSource.source;\n }\n\n data.push(...node.assemble());\n\n // break here because the rest of the tree has to be taken care of by the facet.\n return;\n }\n\n if (\n node instanceof GraticuleNode ||\n node instanceof SequenceNode ||\n node instanceof FilterInvalidNode ||\n node instanceof FilterNode ||\n node instanceof CalculateNode ||\n node instanceof GeoPointNode ||\n node instanceof AggregateNode ||\n node instanceof LookupNode ||\n node instanceof WindowTransformNode ||\n node instanceof JoinAggregateTransformNode ||\n node instanceof FoldTransformNode ||\n node instanceof FlattenTransformNode ||\n node instanceof DensityTransformNode ||\n node instanceof LoessTransformNode ||\n node instanceof QuantileTransformNode ||\n node instanceof RegressionTransformNode ||\n node instanceof IdentifierNode ||\n node instanceof SampleTransformNode ||\n node instanceof PivotTransformNode ||\n node instanceof ExtentTransformNode\n ) {\n dataSource.transform.push(node.assemble());\n }\n\n if (\n node instanceof BinNode ||\n node instanceof TimeUnitNode ||\n node instanceof ImputeNode ||\n node instanceof StackNode ||\n node instanceof GeoJSONNode\n ) {\n dataSource.transform.push(...node.assemble());\n }\n\n if (node instanceof OutputNode) {\n if (dataSource.source && dataSource.transform.length === 0) {\n node.setSource(dataSource.source);\n } else if (node.parent instanceof OutputNode) {\n // Note that an output node may be required but we still do not assemble a\n // separate data source for it.\n node.setSource(dataSource.name);\n } else {\n if (!dataSource.name) {\n dataSource.name = `data_${datasetIndex++}`;\n }\n\n // Here we set the name of the datasource we generated. From now on\n // other assemblers can use it.\n node.setSource(dataSource.name);\n\n // if this node has more than one child, we will add a datasource automatically\n if (node.numChildren() === 1) {\n data.push(dataSource);\n const newData: VgData = {\n name: null,\n source: dataSource.name,\n transform: []\n };\n dataSource = newData;\n }\n }\n }\n\n switch (node.numChildren()) {\n case 0:\n // done\n if (node instanceof OutputNode && (!dataSource.source || dataSource.transform.length > 0)) {\n // do not push empty datasources that are simply references\n data.push(dataSource);\n }\n break;\n case 1:\n walkTree(node.children[0], dataSource);\n break;\n default: {\n if (!dataSource.name) {\n dataSource.name = `data_${datasetIndex++}`;\n }\n\n let source = dataSource.name;\n if (!dataSource.source || dataSource.transform.length > 0) {\n data.push(dataSource);\n } else {\n source = dataSource.source;\n }\n\n for (const child of node.children) {\n const newData: VgData = {\n name: null,\n source,\n transform: []\n };\n walkTree(child, newData);\n }\n break;\n }\n }\n }\n\n return walkTree;\n}\n\n/**\n * Assemble data sources that are derived from faceted data.\n */\nexport function assembleFacetData(root: FacetNode): VgData[] {\n const data: VgData[] = [];\n const walkTree = makeWalkTree(data);\n\n for (const child of root.children) {\n walkTree(child, {\n source: root.name,\n name: null,\n transform: []\n });\n }\n\n return data;\n}\n\n/**\n * Create Vega data array from a given compiled model and append all of them to the given array\n *\n * @param model\n * @param data array\n * @return modified data array\n */\nexport function assembleRootData(dataComponent: DataComponent, datasets: Dict): VgData[] {\n const data: VgData[] = [];\n\n // dataComponent.sources.forEach(debug);\n // draw(dataComponent.sources);\n\n const walkTree = makeWalkTree(data);\n\n let sourceIndex = 0;\n\n for (const root of dataComponent.sources) {\n // assign a name if the source does not have a name yet\n if (!root.hasName()) {\n root.dataName = `source_${sourceIndex++}`;\n }\n\n const newData: VgData = root.assemble();\n\n walkTree(root, newData);\n }\n\n // remove empty transform arrays for cleaner output\n for (const d of data) {\n if (d.transform.length === 0) {\n delete d.transform;\n }\n }\n\n // move sources without transforms (the ones that are potentially used in lookups) to the beginning\n let whereTo = 0;\n for (const [i, d] of data.entries()) {\n if ((d.transform ?? []).length === 0 && !d.source) {\n data.splice(whereTo++, 0, data.splice(i, 1)[0]);\n }\n }\n\n // now fix the from references in lookup transforms\n for (const d of data) {\n for (const t of d.transform ?? []) {\n if (t.type === 'lookup') {\n t.from = dataComponent.outputNodes[t.from].getSource();\n }\n }\n }\n\n // inline values for datasets that are in the datastore\n for (const d of data) {\n if (d.name in datasets) {\n d.values = datasets[d.name];\n }\n }\n\n return data;\n}\n","import {AxisOrient, SignalRef} from 'vega';\nimport {isArray} from 'vega-util';\nimport {FacetChannel, FACET_CHANNELS} from '../../channel';\nimport {title as fieldDefTitle} from '../../channeldef';\nimport {contains, getFirstDefined} from '../../util';\nimport {isSignalRef} from '../../vega.schema';\nimport {assembleAxis} from '../axis/assemble';\nimport {FacetModel} from '../facet';\nimport {parseGuideResolve} from '../resolve';\nimport {getHeaderProperty} from './common';\nimport {HeaderChannel, HeaderComponent} from './component';\n\nexport function getHeaderType(orient: AxisOrient | SignalRef) {\n if (orient === 'top' || orient === 'left' || isSignalRef(orient)) {\n // we always use header for orient signal since we can't dynamically make header becomes footer\n return 'header';\n }\n return 'footer';\n}\n\nexport function parseFacetHeaders(model: FacetModel) {\n for (const channel of FACET_CHANNELS) {\n parseFacetHeader(model, channel);\n }\n\n mergeChildAxis(model, 'x');\n mergeChildAxis(model, 'y');\n}\n\nfunction parseFacetHeader(model: FacetModel, channel: FacetChannel) {\n const {facet, config, child, component} = model;\n if (model.channelHasField(channel)) {\n const fieldDef = facet[channel];\n const titleConfig = getHeaderProperty('title', null, config, channel);\n let title = fieldDefTitle(fieldDef, config, {\n allowDisabling: true,\n includeDefault: titleConfig === undefined || !!titleConfig\n });\n\n if (child.component.layoutHeaders[channel].title) {\n // TODO: better handle multiline titles\n title = isArray(title) ? title.join(', ') : title;\n\n // merge title with child to produce \"Title / Subtitle / Sub-subtitle\"\n title += ` / ${child.component.layoutHeaders[channel].title}`;\n child.component.layoutHeaders[channel].title = null;\n }\n\n const labelOrient = getHeaderProperty('labelOrient', fieldDef.header, config, channel);\n\n const labels =\n fieldDef.header !== null ? getFirstDefined(fieldDef.header?.labels, config.header.labels, true) : false;\n const headerType = contains(['bottom', 'right'], labelOrient) ? 'footer' : 'header';\n\n component.layoutHeaders[channel] = {\n title: fieldDef.header !== null ? title : null,\n facetFieldDef: fieldDef,\n [headerType]: channel === 'facet' ? [] : [makeHeaderComponent(model, channel, labels)]\n };\n }\n}\n\nfunction makeHeaderComponent(model: FacetModel, channel: HeaderChannel, labels: boolean): HeaderComponent {\n const sizeType = channel === 'row' ? 'height' : 'width';\n\n return {\n labels,\n sizeSignal: model.child.component.layoutSize.get(sizeType) ? model.child.getSizeSignalRef(sizeType) : undefined,\n axes: []\n };\n}\n\nfunction mergeChildAxis(model: FacetModel, channel: 'x' | 'y') {\n const {child} = model;\n if (child.component.axes[channel]) {\n const {layoutHeaders, resolve} = model.component;\n resolve.axis[channel] = parseGuideResolve(resolve, channel);\n\n if (resolve.axis[channel] === 'shared') {\n // For shared axis, move the axes to facet's header or footer\n const headerChannel = channel === 'x' ? 'column' : 'row';\n\n const layoutHeader = layoutHeaders[headerChannel];\n for (const axisComponent of child.component.axes[channel]) {\n const headerType = getHeaderType(axisComponent.get('orient'));\n layoutHeader[headerType] ??= [makeHeaderComponent(model, headerChannel, false)];\n\n // FIXME: assemble shouldn't be called here, but we do it this way so we only extract the main part of the axes\n const mainAxis = assembleAxis(axisComponent, 'main', model.config, {header: true});\n if (mainAxis) {\n // LayoutHeader no longer keep track of property precedence, thus let's combine.\n layoutHeader[headerType][0].axes.push(mainAxis);\n }\n axisComponent.mainExtracted = true;\n }\n } else {\n // Otherwise do nothing for independent axes\n }\n }\n}\n","import {getPositionScaleChannel, getSizeChannel, POSITION_SCALE_CHANNELS} from '../../channel';\nimport {getViewConfigContinuousSize, getViewConfigDiscreteSize} from '../../config';\nimport {hasDiscreteDomain} from '../../scale';\nimport {isStep} from '../../spec/base';\nimport {isVgRangeStep} from '../../vega.schema';\nimport {ConcatModel} from '../concat';\nimport {Model} from '../model';\nimport {defaultScaleResolve} from '../resolve';\nimport {Explicit, mergeValuesWithExplicit} from '../split';\nimport {UnitModel} from '../unit';\nimport {getSizeTypeFromLayoutSizeType, LayoutSize, LayoutSizeIndex, LayoutSizeType} from './component';\n\nexport function parseLayerLayoutSize(model: Model) {\n parseChildrenLayoutSize(model);\n\n parseNonUnitLayoutSizeForChannel(model, 'width');\n parseNonUnitLayoutSizeForChannel(model, 'height');\n}\n\nexport function parseConcatLayoutSize(model: ConcatModel) {\n parseChildrenLayoutSize(model);\n\n // for columns === 1 (vconcat), we can completely merge width. Otherwise, we can treat merged width as childWidth.\n const widthType = model.layout.columns === 1 ? 'width' : 'childWidth';\n\n // for columns === undefined (hconcat), we can completely merge height. Otherwise, we can treat merged height as childHeight.\n const heightType = model.layout.columns === undefined ? 'height' : 'childHeight';\n\n parseNonUnitLayoutSizeForChannel(model, widthType);\n parseNonUnitLayoutSizeForChannel(model, heightType);\n}\n\nexport function parseChildrenLayoutSize(model: Model) {\n for (const child of model.children) {\n child.parseLayoutSize();\n }\n}\n\n/**\n * Merge child layout size (width or height).\n */\nfunction parseNonUnitLayoutSizeForChannel(model: Model, layoutSizeType: LayoutSizeType) {\n /*\n * For concat, the parent width or height might not be the same as the children's shared height.\n * For example, hconcat's subviews may share width, but the shared width is not the hconcat view's width.\n *\n * layoutSizeType represents the output of the view (could be childWidth/childHeight/width/height)\n * while the sizeType represents the properties of the child.\n */\n const sizeType = getSizeTypeFromLayoutSizeType(layoutSizeType);\n const channel = getPositionScaleChannel(sizeType);\n const resolve = model.component.resolve;\n const layoutSizeCmpt = model.component.layoutSize;\n\n let mergedSize: Explicit;\n // Try to merge layout size\n for (const child of model.children) {\n const childSize = child.component.layoutSize.getWithExplicit(sizeType);\n const scaleResolve = resolve.scale[channel] ?? defaultScaleResolve(channel, model);\n if (scaleResolve === 'independent' && childSize.value === 'step') {\n // Do not merge independent scales with range-step as their size depends\n // on the scale domains, which can be different between scales.\n mergedSize = undefined;\n break;\n }\n\n if (mergedSize) {\n if (scaleResolve === 'independent' && mergedSize.value !== childSize.value) {\n // For independent scale, only merge if all the sizes are the same.\n // If the values are different, abandon the merge!\n mergedSize = undefined;\n break;\n }\n mergedSize = mergeValuesWithExplicit(mergedSize, childSize, sizeType, '');\n } else {\n mergedSize = childSize;\n }\n }\n\n if (mergedSize) {\n // If merged, rename size and set size of all children.\n for (const child of model.children) {\n model.renameSignal(child.getName(sizeType), model.getName(layoutSizeType));\n child.component.layoutSize.set(sizeType, 'merged', false);\n }\n layoutSizeCmpt.setWithExplicit(layoutSizeType, mergedSize);\n } else {\n layoutSizeCmpt.setWithExplicit(layoutSizeType, {\n explicit: false,\n value: undefined\n });\n }\n}\n\nexport function parseUnitLayoutSize(model: UnitModel) {\n const {size, component} = model;\n for (const channel of POSITION_SCALE_CHANNELS) {\n const sizeType = getSizeChannel(channel);\n\n if (size[sizeType]) {\n const specifiedSize = size[sizeType];\n component.layoutSize.set(sizeType, isStep(specifiedSize) ? 'step' : specifiedSize, true);\n } else {\n const defaultSize = defaultUnitSize(model, sizeType);\n component.layoutSize.set(sizeType, defaultSize, false);\n }\n }\n}\n\nfunction defaultUnitSize(model: UnitModel, sizeType: 'width' | 'height'): LayoutSize {\n const channel = sizeType === 'width' ? 'x' : 'y';\n const config = model.config;\n const scaleComponent = model.getScaleComponent(channel);\n\n if (scaleComponent) {\n const scaleType = scaleComponent.get('type');\n const range = scaleComponent.get('range');\n\n if (hasDiscreteDomain(scaleType)) {\n const size = getViewConfigDiscreteSize(config.view, sizeType);\n if (isVgRangeStep(range) || isStep(size)) {\n // For discrete domain with range.step, use dynamic width/height\n return 'step';\n } else {\n return size;\n }\n } else {\n return getViewConfigContinuousSize(config.view, sizeType);\n }\n } else if (model.hasProjection || model.mark === 'arc') {\n // arc should use continuous size by default otherwise the pie is extremely small\n return getViewConfigContinuousSize(config.view, sizeType);\n } else {\n const size = getViewConfigDiscreteSize(config.view, sizeType);\n return isStep(size) ? size.step : size;\n }\n}\n","import {AggregateOp, LayoutAlign, NewSignal, SignalRef} from 'vega';\nimport {isArray} from 'vega-util';\nimport {isBinning} from '../bin';\nimport {COLUMN, ExtendedChannel, FacetChannel, FACET_CHANNELS, POSITION_SCALE_CHANNELS, ROW} from '../channel';\nimport {FieldName, FieldRefOption, initFieldDef, TypedFieldDef, vgField} from '../channeldef';\nimport {Config} from '../config';\nimport {ExprRef, replaceExprRef} from '../expr';\nimport * as log from '../log';\nimport {hasDiscreteDomain} from '../scale';\nimport {DEFAULT_SORT_OP, EncodingSortField, isSortField, SortOrder} from '../sort';\nimport {NormalizedFacetSpec} from '../spec';\nimport {EncodingFacetMapping, FacetFieldDef, FacetMapping, isFacetMapping} from '../spec/facet';\nimport {keys} from '../util';\nimport {isVgRangeStep, VgData, VgLayout, VgMarkGroup} from '../vega.schema';\nimport {buildModel} from './buildmodel';\nimport {assembleFacetData} from './data/assemble';\nimport {sortArrayIndexField} from './data/calculate';\nimport {parseData} from './data/parse';\nimport {assembleLabelTitle} from './header/assemble';\nimport {getHeaderChannel, getHeaderProperty} from './header/common';\nimport {HEADER_CHANNELS, HEADER_TYPES} from './header/component';\nimport {parseFacetHeaders} from './header/parse';\nimport {parseChildrenLayoutSize} from './layoutsize/parse';\nimport {Model, ModelWithField} from './model';\nimport {assembleDomain, getFieldFromDomain} from './scale/domain';\nimport {assembleFacetSignals} from './selection/assemble';\n\nexport function facetSortFieldName(\n fieldDef: FacetFieldDef,\n sort: EncodingSortField,\n opt?: FieldRefOption\n) {\n return vgField(sort, {suffix: `by_${vgField(fieldDef)}`, ...opt});\n}\n\nexport class FacetModel extends ModelWithField {\n public readonly facet: EncodingFacetMapping;\n\n public readonly child: Model;\n\n public readonly children: Model[];\n\n constructor(spec: NormalizedFacetSpec, parent: Model, parentGivenName: string, config: Config) {\n super(spec, 'facet', parent, parentGivenName, config, spec.resolve);\n\n this.child = buildModel(spec.spec, this, this.getName('child'), undefined, config);\n this.children = [this.child];\n\n this.facet = this.initFacet(spec.facet);\n }\n\n private initFacet(\n facet: FacetFieldDef | FacetMapping\n ): EncodingFacetMapping {\n // clone to prevent side effect to the original spec\n if (!isFacetMapping(facet)) {\n return {facet: this.initFacetFieldDef(facet, 'facet')};\n }\n\n const channels = keys(facet);\n const normalizedFacet = {};\n for (const channel of channels) {\n if (![ROW, COLUMN].includes(channel)) {\n // Drop unsupported channel\n log.warn(log.message.incompatibleChannel(channel, 'facet'));\n break;\n }\n\n const fieldDef = facet[channel];\n if (fieldDef.field === undefined) {\n log.warn(log.message.emptyFieldDef(fieldDef, channel));\n break;\n }\n\n normalizedFacet[channel] = this.initFacetFieldDef(fieldDef, channel);\n }\n\n return normalizedFacet;\n }\n\n private initFacetFieldDef(fieldDef: FacetFieldDef, channel: FacetChannel) {\n // Cast because we call initFieldDef, which assumes general FieldDef.\n // However, FacetFieldDef is a bit more constrained than the general FieldDef\n const facetFieldDef = initFieldDef(fieldDef, channel) as FacetFieldDef;\n if (facetFieldDef.header) {\n facetFieldDef.header = replaceExprRef(facetFieldDef.header);\n } else if (facetFieldDef.header === null) {\n facetFieldDef.header = null;\n }\n return facetFieldDef;\n }\n\n public channelHasField(channel: ExtendedChannel): boolean {\n return !!this.facet[channel];\n }\n\n public fieldDef(channel: ExtendedChannel): TypedFieldDef {\n return this.facet[channel];\n }\n\n public parseData() {\n this.component.data = parseData(this);\n this.child.parseData();\n }\n\n public parseLayoutSize() {\n parseChildrenLayoutSize(this);\n }\n\n public parseSelections() {\n // As a facet has a single child, the selection components are the same.\n // The child maintains its selections to assemble signals, which remain\n // within its unit.\n this.child.parseSelections();\n this.component.selection = this.child.component.selection;\n }\n\n public parseMarkGroup() {\n this.child.parseMarkGroup();\n }\n\n public parseAxesAndHeaders() {\n this.child.parseAxesAndHeaders();\n\n parseFacetHeaders(this);\n }\n\n public assembleSelectionTopLevelSignals(signals: NewSignal[]): NewSignal[] {\n return this.child.assembleSelectionTopLevelSignals(signals);\n }\n\n public assembleSignals(): NewSignal[] {\n this.child.assembleSignals();\n return [];\n }\n\n public assembleSelectionData(data: readonly VgData[]): readonly VgData[] {\n return this.child.assembleSelectionData(data);\n }\n\n private getHeaderLayoutMixins(): VgLayout {\n const layoutMixins: VgLayout = {};\n\n for (const channel of FACET_CHANNELS) {\n for (const headerType of HEADER_TYPES) {\n const layoutHeaderComponent = this.component.layoutHeaders[channel];\n const headerComponent = layoutHeaderComponent[headerType];\n\n const {facetFieldDef} = layoutHeaderComponent;\n if (facetFieldDef) {\n const titleOrient = getHeaderProperty('titleOrient', facetFieldDef.header, this.config, channel);\n\n if (['right', 'bottom'].includes(titleOrient)) {\n const headerChannel = getHeaderChannel(channel, titleOrient);\n layoutMixins.titleAnchor ??= {};\n layoutMixins.titleAnchor[headerChannel] = 'end';\n }\n }\n\n if (headerComponent?.[0]) {\n // set header/footerBand\n const sizeType = channel === 'row' ? 'height' : 'width';\n const bandType = headerType === 'header' ? 'headerBand' : 'footerBand';\n if (channel !== 'facet' && !this.child.component.layoutSize.get(sizeType)) {\n // If facet child does not have size signal, then apply headerBand\n layoutMixins[bandType] ??= {};\n layoutMixins[bandType][channel] = 0.5;\n }\n\n if (layoutHeaderComponent.title) {\n layoutMixins.offset ??= {};\n layoutMixins.offset[channel === 'row' ? 'rowTitle' : 'columnTitle'] = 10;\n }\n }\n }\n }\n return layoutMixins;\n }\n\n protected assembleDefaultLayout(): VgLayout {\n const {column, row} = this.facet;\n\n const columns = column ? this.columnDistinctSignal() : row ? 1 : undefined;\n\n let align: LayoutAlign = 'all';\n\n // Do not align the cells if the scale corresponding to the direction is indepent.\n // We always align when we facet into both row and column.\n if (!row && this.component.resolve.scale.x === 'independent') {\n align = 'none';\n } else if (!column && this.component.resolve.scale.y === 'independent') {\n align = 'none';\n }\n\n return {\n ...this.getHeaderLayoutMixins(),\n\n ...(columns ? {columns} : {}),\n bounds: 'full',\n align\n };\n }\n\n public assembleLayoutSignals(): NewSignal[] {\n // FIXME(https://github.com/vega/vega-lite/issues/1193): this can be incorrect if we have independent scales.\n return this.child.assembleLayoutSignals();\n }\n\n private columnDistinctSignal() {\n if (this.parent && this.parent instanceof FacetModel) {\n // For nested facet, we will add columns to group mark instead\n // See discussion in https://github.com/vega/vega/issues/952\n // and https://github.com/vega/vega-view/releases/tag/v1.2.6\n return undefined;\n } else {\n // In facetNode.assemble(), the name is always this.getName('column') + '_layout'.\n const facetLayoutDataName = this.getName('column_domain');\n return {signal: `length(data('${facetLayoutDataName}'))`};\n }\n }\n\n public assembleGroupStyle(): string | string[] {\n return undefined;\n }\n\n public assembleGroup(signals: NewSignal[]) {\n if (this.parent && this.parent instanceof FacetModel) {\n // Provide number of columns for layout.\n // See discussion in https://github.com/vega/vega/issues/952\n // and https://github.com/vega/vega-view/releases/tag/v1.2.6\n return {\n ...(this.channelHasField('column')\n ? {\n encode: {\n update: {\n // TODO(https://github.com/vega/vega-lite/issues/2759):\n // Correct the signal for facet of concat of facet_column\n columns: {field: vgField(this.facet.column, {prefix: 'distinct'})}\n }\n }\n }\n : {}),\n ...super.assembleGroup(signals)\n };\n }\n return super.assembleGroup(signals);\n }\n\n /**\n * Aggregate cardinality for calculating size\n */\n private getCardinalityAggregateForChild() {\n const fields: string[] = [];\n const ops: AggregateOp[] = [];\n const as: string[] = [];\n\n if (this.child instanceof FacetModel) {\n if (this.child.channelHasField('column')) {\n const field = vgField(this.child.facet.column);\n fields.push(field);\n ops.push('distinct');\n as.push(`distinct_${field}`);\n }\n } else {\n for (const channel of POSITION_SCALE_CHANNELS) {\n const childScaleComponent = this.child.component.scales[channel];\n if (childScaleComponent && !childScaleComponent.merged) {\n const type = childScaleComponent.get('type');\n const range = childScaleComponent.get('range');\n\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const domain = assembleDomain(this.child, channel);\n const field = getFieldFromDomain(domain);\n if (field) {\n fields.push(field);\n ops.push('distinct');\n as.push(`distinct_${field}`);\n } else {\n log.warn(log.message.unknownField(channel));\n }\n }\n }\n }\n }\n return {fields, ops, as};\n }\n\n private assembleFacet() {\n const {name, data} = this.component.data.facetRoot;\n const {row, column} = this.facet;\n const {fields, ops, as} = this.getCardinalityAggregateForChild();\n const groupby: string[] = [];\n\n for (const channel of FACET_CHANNELS) {\n const fieldDef = this.facet[channel];\n if (fieldDef) {\n groupby.push(vgField(fieldDef));\n\n const {bin, sort} = fieldDef;\n\n if (isBinning(bin)) {\n groupby.push(vgField(fieldDef, {binSuffix: 'end'}));\n }\n\n if (isSortField(sort)) {\n const {field, op = DEFAULT_SORT_OP} = sort;\n const outputName = facetSortFieldName(fieldDef, sort);\n if (row && column) {\n // For crossed facet, use pre-calculate field as it requires a different groupby\n // For each calculated field, apply max and assign them to the same name as\n // all values of the same group should be the same anyway.\n fields.push(outputName);\n ops.push('max');\n as.push(outputName);\n } else {\n fields.push(field);\n ops.push(op);\n as.push(outputName);\n }\n } else if (isArray(sort)) {\n const outputName = sortArrayIndexField(fieldDef, channel);\n fields.push(outputName);\n ops.push('max');\n as.push(outputName);\n }\n }\n }\n\n const cross = !!row && !!column;\n\n return {\n name,\n data,\n groupby,\n ...(cross || fields.length > 0\n ? {\n aggregate: {\n ...(cross ? {cross} : {}),\n ...(fields.length ? {fields, ops, as} : {})\n }\n }\n : {})\n };\n }\n\n private facetSortFields(channel: FacetChannel): string[] {\n const {facet} = this;\n const fieldDef = facet[channel];\n\n if (fieldDef) {\n if (isSortField(fieldDef.sort)) {\n return [facetSortFieldName(fieldDef, fieldDef.sort, {expr: 'datum'})];\n } else if (isArray(fieldDef.sort)) {\n return [sortArrayIndexField(fieldDef, channel, {expr: 'datum'})];\n }\n return [vgField(fieldDef, {expr: 'datum'})];\n }\n return [];\n }\n\n private facetSortOrder(channel: FacetChannel): SortOrder[] {\n const {facet} = this;\n const fieldDef = facet[channel];\n if (fieldDef) {\n const {sort} = fieldDef;\n const order = (isSortField(sort) ? sort.order : !isArray(sort) && sort) || 'ascending';\n return [order];\n }\n return [];\n }\n\n private assembleLabelTitle() {\n const {facet, config} = this;\n if (facet.facet) {\n // Facet always uses title to display labels\n return assembleLabelTitle(facet.facet, 'facet', config);\n }\n\n const ORTHOGONAL_ORIENT = {\n row: ['top', 'bottom'],\n column: ['left', 'right']\n };\n\n for (const channel of HEADER_CHANNELS) {\n if (facet[channel]) {\n const labelOrient = getHeaderProperty('labelOrient', facet[channel]?.header, config, channel);\n if (ORTHOGONAL_ORIENT[channel].includes(labelOrient)) {\n // Row/Column with orthogonal labelOrient must use title to display labels\n return assembleLabelTitle(facet[channel], channel, config);\n }\n }\n }\n return undefined;\n }\n\n public assembleMarks(): VgMarkGroup[] {\n const {child} = this;\n\n // If we facet by two dimensions, we need to add a cross operator to the aggregation\n // so that we create all groups\n const facetRoot = this.component.data.facetRoot;\n const data = assembleFacetData(facetRoot);\n\n const encodeEntry = child.assembleGroupEncodeEntry(false);\n\n const title = this.assembleLabelTitle() || child.assembleTitle();\n const style = child.assembleGroupStyle();\n\n const markGroup = {\n name: this.getName('cell'),\n type: 'group',\n ...(title ? {title} : {}),\n ...(style ? {style} : {}),\n from: {\n facet: this.assembleFacet()\n },\n // TODO: move this to after data\n sort: {\n field: FACET_CHANNELS.map(c => this.facetSortFields(c)).flat(),\n order: FACET_CHANNELS.map(c => this.facetSortOrder(c)).flat()\n },\n ...(data.length > 0 ? {data} : {}),\n ...(encodeEntry ? {encode: {update: encodeEntry}} : {}),\n ...child.assembleGroup(assembleFacetSignals(this, []))\n };\n\n return [markGroup];\n }\n\n protected getMapping() {\n return this.facet;\n }\n}\n","import {AncestorParse, DataComponent} from '.';\nimport {\n Data,\n isGenerator,\n isGraticuleGenerator,\n isInlineData,\n isNamedData,\n isSequenceGenerator,\n isUrlData,\n DataSourceType,\n ParseValue\n} from '../../data';\nimport {getDataSourcesForHandlingInvalidValues, DataSourcesForHandlingInvalidValues} from '../invalid/datasources';\nimport * as log from '../../log';\nimport {isPathMark} from '../../mark';\nimport {\n isAggregate,\n isBin,\n isCalculate,\n isDensity,\n isExtent,\n isFilter,\n isFlatten,\n isFold,\n isImpute,\n isJoinAggregate,\n isLoess,\n isLookup,\n isPivot,\n isQuantile,\n isRegression,\n isSample,\n isStack,\n isTimeUnit,\n isWindow\n} from '../../transform';\nimport {deepEqual, mergeDeep} from '../../util';\nimport {getMarkPropOrConfig} from '../common';\nimport {isFacetModel, isLayerModel, isUnitModel, Model} from '../model';\nimport {requiresSelectionId} from '../selection';\nimport {materializeSelections} from '../selection/parse';\nimport {AggregateNode} from './aggregate';\nimport {BinNode} from './bin';\nimport {CalculateNode} from './calculate';\nimport {DataFlowNode, OutputNode} from './dataflow';\nimport {DensityTransformNode} from './density';\nimport {ExtentTransformNode} from './extent';\nimport {FacetNode} from './facet';\nimport {FilterNode} from './filter';\nimport {FilterInvalidNode} from './filterinvalid';\nimport {FlattenTransformNode} from './flatten';\nimport {FoldTransformNode} from './fold';\nimport {\n getImplicitFromEncoding,\n getImplicitFromFilterTransform,\n getImplicitFromSelection,\n ParseNode\n} from './formatparse';\nimport {GeoJSONNode} from './geojson';\nimport {GeoPointNode} from './geopoint';\nimport {GraticuleNode} from './graticule';\nimport {IdentifierNode} from './identifier';\nimport {ImputeNode} from './impute';\nimport {JoinAggregateTransformNode} from './joinaggregate';\nimport {makeJoinAggregateFromFacet} from './joinaggregatefacet';\nimport {LoessTransformNode} from './loess';\nimport {LookupNode} from './lookup';\nimport {PivotTransformNode} from './pivot';\nimport {QuantileTransformNode} from './quantile';\nimport {RegressionTransformNode} from './regression';\nimport {SampleTransformNode} from './sample';\nimport {SequenceNode} from './sequence';\nimport {SourceNode} from './source';\nimport {StackNode} from './stack';\nimport {TimeUnitNode} from './timeunit';\nimport {WindowTransformNode} from './window';\n\nexport function findSource(data: Data, sources: SourceNode[]) {\n for (const other of sources) {\n const otherData = other.data;\n\n // if both datasets have a name defined, we cannot merge\n if (data.name && other.hasName() && data.name !== other.dataName) {\n continue;\n }\n\n const formatMesh = data['format']?.mesh;\n const otherFeature = otherData.format?.feature;\n\n // feature and mesh are mutually exclusive\n if (formatMesh && otherFeature) {\n continue;\n }\n\n // we have to extract the same feature or mesh\n const formatFeature = data['format']?.feature;\n if ((formatFeature || otherFeature) && formatFeature !== otherFeature) {\n continue;\n }\n\n const otherMesh = otherData.format?.mesh;\n if ((formatMesh || otherMesh) && formatMesh !== otherMesh) {\n continue;\n }\n\n if (isInlineData(data) && isInlineData(otherData)) {\n if (deepEqual(data.values, otherData.values)) {\n return other;\n }\n } else if (isUrlData(data) && isUrlData(otherData)) {\n if (data.url === otherData.url) {\n return other;\n }\n } else if (isNamedData(data)) {\n if (data.name === other.dataName) {\n return other;\n }\n }\n }\n return null;\n}\n\nfunction parseRoot(model: Model, sources: SourceNode[]): DataFlowNode {\n if (model.data || !model.parent) {\n // if the model defines a data source or is the root, create a source node\n\n if (model.data === null) {\n // data: null means we should ignore the parent's data so we just create a new data source\n const source = new SourceNode({values: []});\n sources.push(source);\n return source;\n }\n\n const existingSource = findSource(model.data, sources);\n\n if (existingSource) {\n if (!isGenerator(model.data)) {\n existingSource.data.format = mergeDeep({}, model.data.format, existingSource.data.format);\n }\n\n // if the new source has a name but the existing one does not, we can set it\n if (!existingSource.hasName() && model.data.name) {\n existingSource.dataName = model.data.name;\n }\n\n return existingSource;\n } else {\n const source = new SourceNode(model.data);\n sources.push(source);\n return source;\n }\n } else {\n // If we don't have a source defined (overriding parent's data), use the parent's facet root or main.\n return model.parent.component.data.facetRoot\n ? model.parent.component.data.facetRoot\n : model.parent.component.data.main;\n }\n}\n\n/**\n * Parses a transform array into a chain of connected dataflow nodes.\n */\nexport function parseTransformArray(head: DataFlowNode, model: Model, ancestorParse: AncestorParse): DataFlowNode {\n let lookupCounter = 0;\n\n for (const t of model.transforms) {\n let derivedType: ParseValue = undefined;\n let transformNode: DataFlowNode;\n\n if (isCalculate(t)) {\n transformNode = head = new CalculateNode(head, t);\n derivedType = 'derived';\n } else if (isFilter(t)) {\n const implicit = getImplicitFromFilterTransform(t);\n transformNode = head = ParseNode.makeWithAncestors(head, {}, implicit, ancestorParse) ?? head;\n\n head = new FilterNode(head, model, t.filter);\n } else if (isBin(t)) {\n transformNode = head = BinNode.makeFromTransform(head, t, model);\n derivedType = 'number';\n } else if (isTimeUnit(t)) {\n derivedType = 'date';\n const parsedAs = ancestorParse.getWithExplicit(t.field);\n // Create parse node because the input to time unit is always date.\n if (parsedAs.value === undefined) {\n head = new ParseNode(head, {[t.field]: derivedType});\n ancestorParse.set(t.field, derivedType, false);\n }\n transformNode = head = TimeUnitNode.makeFromTransform(head, t);\n } else if (isAggregate(t)) {\n transformNode = head = AggregateNode.makeFromTransform(head, t);\n derivedType = 'number';\n if (requiresSelectionId(model)) {\n head = new IdentifierNode(head);\n }\n } else if (isLookup(t)) {\n transformNode = head = LookupNode.make(head, model, t, lookupCounter++);\n derivedType = 'derived';\n } else if (isWindow(t)) {\n transformNode = head = new WindowTransformNode(head, t);\n derivedType = 'number';\n } else if (isJoinAggregate(t)) {\n transformNode = head = new JoinAggregateTransformNode(head, t);\n derivedType = 'number';\n } else if (isStack(t)) {\n transformNode = head = StackNode.makeFromTransform(head, t);\n derivedType = 'derived';\n } else if (isFold(t)) {\n transformNode = head = new FoldTransformNode(head, t);\n derivedType = 'derived';\n } else if (isExtent(t)) {\n transformNode = head = new ExtentTransformNode(head, t);\n derivedType = 'derived';\n } else if (isFlatten(t)) {\n transformNode = head = new FlattenTransformNode(head, t);\n derivedType = 'derived';\n } else if (isPivot(t)) {\n transformNode = head = new PivotTransformNode(head, t);\n derivedType = 'derived';\n } else if (isSample(t)) {\n head = new SampleTransformNode(head, t);\n } else if (isImpute(t)) {\n transformNode = head = ImputeNode.makeFromTransform(head, t);\n derivedType = 'derived';\n } else if (isDensity(t)) {\n transformNode = head = new DensityTransformNode(head, t);\n derivedType = 'derived';\n } else if (isQuantile(t)) {\n transformNode = head = new QuantileTransformNode(head, t);\n derivedType = 'derived';\n } else if (isRegression(t)) {\n transformNode = head = new RegressionTransformNode(head, t);\n derivedType = 'derived';\n } else if (isLoess(t)) {\n transformNode = head = new LoessTransformNode(head, t);\n derivedType = 'derived';\n } else {\n log.warn(log.message.invalidTransformIgnored(t));\n continue;\n }\n\n if (transformNode && derivedType !== undefined) {\n for (const field of transformNode.producedFields() ?? []) {\n ancestorParse.set(field, derivedType, false);\n }\n }\n }\n\n return head;\n}\n\n/*\nDescription of the dataflow (http://asciiflow.com/):\n +--------+\n | Source |\n +---+----+\n |\n v\n FormatParse\n (explicit)\n |\n v\n Transforms\n(Filter, Calculate, Binning, TimeUnit, Aggregate, Window, ...)\n |\n v\n FormatParse\n (implicit)\n |\n v\n Binning (in `encoding`)\n |\n v\n Timeunit (in `encoding`)\n |\n v\nFormula From Sort Array\n |\n v\n +--+--+\n | Raw |\n +-----+\n |\n v\n Aggregate (in `encoding`)\n |\n v\n Stack (in `encoding`)\n |\n v\n+- - - - - - - - - - -+\n| PreFilterInvalid | - - - -> scale domains\n|(when scales need it)|\n+- - - - - - - - - - -+\n |\n v\n Invalid Filter (if the main data source needs it)\n |\n v\n +----------+\n | Main | - - - -> scale domains\n +----------+\n |\n v\n+- - - - - - - - - - -+\n| PostFilterInvalid | - - - -> scale domains\n|(when scales need it)|\n+- - - - - - - - - - -+\n |\n v\n +-------+\n | Facet |----> \"column\", \"column-layout\", and \"row\"\n +-------+\n |\n v\n ...Child data...\n*/\n\nexport function parseData(model: Model): DataComponent {\n let head = parseRoot(model, model.component.data.sources);\n\n const {outputNodes, outputNodeRefCounts} = model.component.data;\n const data = model.data;\n\n const newData = data && (isGenerator(data) || isUrlData(data) || isInlineData(data));\n const ancestorParse =\n !newData && model.parent ? model.parent.component.data.ancestorParse.clone() : new AncestorParse();\n\n if (isGenerator(data)) {\n // insert generator transform\n if (isSequenceGenerator(data)) {\n head = new SequenceNode(head, data.sequence);\n } else if (isGraticuleGenerator(data)) {\n head = new GraticuleNode(head, data.graticule);\n }\n // no parsing necessary for generator\n ancestorParse.parseNothing = true;\n } else if (data?.format?.parse === null) {\n // format.parse: null means disable parsing\n ancestorParse.parseNothing = true;\n }\n\n head = ParseNode.makeExplicit(head, model, ancestorParse) ?? head;\n\n // Default discrete selections require an identifer transform to\n // uniquely identify data points. Add this transform at the head of\n // the pipeline such that the identifier field is available for all\n // subsequent datasets. During optimization, we will remove this\n // transform if it proves to be unnecessary. Additional identifier\n // transforms will be necessary when new tuples are constructed\n // (e.g., post-aggregation).\n head = new IdentifierNode(head);\n\n // HACK: This is equivalent for merging bin extent for union scale.\n // FIXME(https://github.com/vega/vega-lite/issues/2270): Correctly merge extent / bin node for shared bin scale\n const parentIsLayer = model.parent && isLayerModel(model.parent);\n if (isUnitModel(model) || isFacetModel(model)) {\n if (parentIsLayer) {\n head = BinNode.makeFromEncoding(head, model) ?? head;\n }\n }\n\n if (model.transforms.length > 0) {\n head = parseTransformArray(head, model, ancestorParse);\n }\n\n // create parse nodes for fields that need to be parsed (or flattened) implicitly\n const implicitSelection = getImplicitFromSelection(model);\n const implicitEncoding = getImplicitFromEncoding(model);\n head = ParseNode.makeWithAncestors(head, {}, {...implicitSelection, ...implicitEncoding}, ancestorParse) ?? head;\n\n if (isUnitModel(model)) {\n head = GeoJSONNode.parseAll(head, model);\n head = GeoPointNode.parseAll(head, model);\n }\n\n if (isUnitModel(model) || isFacetModel(model)) {\n if (!parentIsLayer) {\n head = BinNode.makeFromEncoding(head, model) ?? head;\n }\n\n head = TimeUnitNode.makeFromEncoding(head, model) ?? head;\n head = CalculateNode.parseAllForSortIndex(head, model);\n }\n\n // add an output node pre aggregation\n const raw = (head = makeOutputNode(DataSourceType.Raw, model, head));\n\n if (isUnitModel(model)) {\n const agg = AggregateNode.makeFromEncoding(head, model);\n if (agg) {\n head = agg;\n\n if (requiresSelectionId(model)) {\n head = new IdentifierNode(head);\n }\n }\n head = ImputeNode.makeFromEncoding(head, model) ?? head;\n head = StackNode.makeFromEncoding(head, model) ?? head;\n }\n\n let preFilterInvalid: OutputNode | undefined;\n let dataSourcesForHandlingInvalidValues: DataSourcesForHandlingInvalidValues | undefined;\n if (isUnitModel(model)) {\n const {markDef, mark, config} = model;\n const invalid = getMarkPropOrConfig('invalid', markDef, config);\n\n const {marks, scales} = (dataSourcesForHandlingInvalidValues = getDataSourcesForHandlingInvalidValues({\n invalid,\n isPath: isPathMark(mark)\n }));\n\n if (marks !== scales && scales === 'include-invalid-values') {\n // Create a seperate preFilterInvalid dataSource if scales need pre-filter data but marks needs post-filter.\n preFilterInvalid = head = makeOutputNode(DataSourceType.PreFilterInvalid, model, head);\n }\n\n if (marks === 'exclude-invalid-values') {\n head = FilterInvalidNode.make(head, model, dataSourcesForHandlingInvalidValues) ?? head;\n }\n }\n\n // output \"main\" node for marks\n const main = (head = makeOutputNode(DataSourceType.Main, model, head));\n\n let postFilterInvalid: OutputNode | undefined;\n if (isUnitModel(model) && dataSourcesForHandlingInvalidValues) {\n const {marks, scales} = dataSourcesForHandlingInvalidValues;\n if (marks === 'include-invalid-values' && scales === 'exclude-invalid-values') {\n // Create a seperate postFilterInvalid dataSource if scales need post-filter data but marks needs pre-filter.\n head = FilterInvalidNode.make(head, model, dataSourcesForHandlingInvalidValues) ?? head;\n\n postFilterInvalid = head = makeOutputNode(DataSourceType.PostFilterInvalid, model, head);\n }\n }\n\n if (isUnitModel(model)) {\n materializeSelections(model, main);\n }\n\n // add facet marker\n let facetRoot = null;\n if (isFacetModel(model)) {\n const facetName = model.getName('facet');\n\n // Derive new aggregate for facet's sort field\n // augment data source with new fields for crossed facet\n head = makeJoinAggregateFromFacet(head, model.facet) ?? head;\n\n facetRoot = new FacetNode(head, model, facetName, main.getSource());\n outputNodes[facetName] = facetRoot;\n }\n\n return {\n ...model.component.data,\n outputNodes,\n outputNodeRefCounts,\n raw,\n main,\n facetRoot,\n ancestorParse,\n preFilterInvalid,\n postFilterInvalid\n };\n}\n\nfunction makeOutputNode(dataSourceType: DataSourceType, model: Model, head: DataFlowNode) {\n const {outputNodes, outputNodeRefCounts} = model.component.data;\n const name = model.getDataName(dataSourceType);\n const node = new OutputNode(head, name, dataSourceType, outputNodeRefCounts);\n outputNodes[name] = node;\n return node;\n}\n","import {vgField} from '../../channeldef';\nimport {DEFAULT_SORT_OP, isSortField} from '../../sort';\nimport {FacetMapping} from '../../spec/facet';\nimport {facetSortFieldName} from '../facet';\nimport {DataFlowNode} from './dataflow';\nimport {JoinAggregateTransformNode} from './joinaggregate';\n\nexport function makeJoinAggregateFromFacet(\n parent: DataFlowNode,\n facet: FacetMapping\n): JoinAggregateTransformNode {\n const {row, column} = facet;\n if (row && column) {\n let newParent = null;\n // only need to make one for crossed facet\n for (const fieldDef of [row, column]) {\n if (isSortField(fieldDef.sort)) {\n const {field, op = DEFAULT_SORT_OP} = fieldDef.sort;\n parent = newParent = new JoinAggregateTransformNode(parent, {\n joinaggregate: [\n {\n op,\n field,\n as: facetSortFieldName(fieldDef, fieldDef.sort, {forAs: true})\n }\n ],\n groupby: [vgField(fieldDef)]\n });\n }\n }\n return newParent;\n }\n return null;\n}\n","import {NewSignal, SignalRef} from 'vega';\nimport {Config} from '../config';\nimport * as log from '../log';\nimport {isHConcatSpec, isVConcatSpec, NormalizedConcatSpec, NormalizedSpec} from '../spec';\nimport {keys} from '../util';\nimport {VgData, VgLayout} from '../vega.schema';\nimport {buildModel} from './buildmodel';\nimport {parseData} from './data/parse';\nimport {assembleLayoutSignals} from './layoutsize/assemble';\nimport {parseConcatLayoutSize} from './layoutsize/parse';\nimport {Model} from './model';\n\nexport class ConcatModel extends Model {\n public readonly children: Model[];\n\n constructor(spec: NormalizedConcatSpec, parent: Model, parentGivenName: string, config: Config) {\n super(spec, 'concat', parent, parentGivenName, config, spec.resolve);\n\n if (spec.resolve?.axis?.x === 'shared' || spec.resolve?.axis?.y === 'shared') {\n log.warn(log.message.CONCAT_CANNOT_SHARE_AXIS);\n }\n\n this.children = this.getChildren(spec).map((child, i) => {\n return buildModel(child, this, this.getName(`concat_${i}`), undefined, config);\n });\n }\n\n public parseData() {\n this.component.data = parseData(this);\n for (const child of this.children) {\n child.parseData();\n }\n }\n\n public parseSelections() {\n // Merge selections up the hierarchy so that they may be referenced\n // across unit specs. Persist their definitions within each child\n // to assemble signals which remain within output Vega unit groups.\n this.component.selection = {};\n for (const child of this.children) {\n child.parseSelections();\n for (const key of keys(child.component.selection)) {\n this.component.selection[key] = child.component.selection[key];\n }\n }\n }\n\n public parseMarkGroup() {\n for (const child of this.children) {\n child.parseMarkGroup();\n }\n }\n\n public parseAxesAndHeaders() {\n for (const child of this.children) {\n child.parseAxesAndHeaders();\n }\n\n // TODO(#2415): support shared axes\n }\n\n private getChildren(spec: NormalizedConcatSpec): NormalizedSpec[] {\n if (isVConcatSpec(spec)) {\n return spec.vconcat;\n } else if (isHConcatSpec(spec)) {\n return spec.hconcat;\n }\n return spec.concat;\n }\n\n public parseLayoutSize() {\n parseConcatLayoutSize(this);\n }\n\n public parseAxisGroup(): void {\n return null;\n }\n\n public assembleSelectionTopLevelSignals(signals: NewSignal[]): NewSignal[] {\n return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);\n }\n\n public assembleSignals(): NewSignal[] {\n this.children.forEach(child => child.assembleSignals());\n return [];\n }\n\n public assembleLayoutSignals(): NewSignal[] {\n const layoutSignals = assembleLayoutSignals(this);\n\n for (const child of this.children) {\n layoutSignals.push(...child.assembleLayoutSignals());\n }\n\n return layoutSignals;\n }\n\n public assembleSelectionData(data: readonly VgData[]): readonly VgData[] {\n return this.children.reduce((db, child) => child.assembleSelectionData(db), data);\n }\n\n public assembleMarks(): any[] {\n // only children have marks\n return this.children.map(child => {\n const title = child.assembleTitle();\n const style = child.assembleGroupStyle();\n const encodeEntry = child.assembleGroupEncodeEntry(false);\n\n return {\n type: 'group',\n name: child.getName('group'),\n ...(title ? {title} : {}),\n ...(style ? {style} : {}),\n ...(encodeEntry ? {encode: {update: encodeEntry}} : {}),\n ...child.assembleGroup()\n };\n });\n }\n\n public assembleGroupStyle(): string | string[] {\n return undefined;\n }\n\n protected assembleDefaultLayout(): VgLayout {\n const columns = this.layout.columns;\n return {\n ...(columns != null ? {columns} : {}),\n bounds: 'full',\n // Use align each so it can work with multiple plots with different size\n align: 'each'\n };\n }\n}\n","import {Axis as VgAxis, SignalRef, Text} from 'vega';\nimport {\n AxisInternal,\n AxisPart,\n AxisPropsWithCondition,\n COMMON_AXIS_PROPERTIES_INDEX,\n ConditionalAxisProp\n} from '../../axis';\nimport {FieldDefBase} from '../../channeldef';\nimport {duplicate, Flag, keys} from '../../util';\nimport {isSignalRef} from '../../vega.schema';\nimport {Split} from '../split';\n\nfunction isFalseOrNull(v: any) {\n return v === false || v === null;\n}\n\nexport type AxisComponentProps = Omit &\n Omit, 'title'> & {\n title: Text | FieldDefBase[] | SignalRef;\n labelExpr: string;\n disable: boolean;\n };\n\nconst AXIS_COMPONENT_PROPERTIES_INDEX: Flag = {\n disable: 1,\n gridScale: 1,\n scale: 1,\n ...COMMON_AXIS_PROPERTIES_INDEX,\n labelExpr: 1,\n encode: 1\n};\n\nexport const AXIS_COMPONENT_PROPERTIES = keys(AXIS_COMPONENT_PROPERTIES_INDEX);\n\nexport class AxisComponent extends Split {\n constructor(\n public readonly explicit: Partial = {},\n public readonly implicit: Partial = {},\n public mainExtracted = false\n ) {\n super();\n }\n\n public clone() {\n return new AxisComponent(duplicate(this.explicit), duplicate(this.implicit), this.mainExtracted);\n }\n\n public hasAxisPart(part: AxisPart) {\n // FIXME(https://github.com/vega/vega-lite/issues/2552) this method can be wrong if users use a Vega theme.\n\n if (part === 'axis') {\n // always has the axis container part\n return true;\n }\n\n if (part === 'grid' || part === 'title') {\n return !!this.get(part);\n }\n // Other parts are enabled by default, so they should not be false or null.\n return !isFalseOrNull(this.get(part));\n }\n\n public hasOrientSignalRef() {\n return isSignalRef(this.explicit.orient);\n }\n}\n\nexport interface AxisComponentIndex {\n x?: AxisComponent[];\n y?: AxisComponent[];\n}\n\nexport interface AxisInternalIndex {\n x?: AxisInternal;\n y?: AxisInternal;\n}\n","import {AxisEncode as VgAxisEncode, AxisOrient, SignalRef} from 'vega';\nimport {Axis, AXIS_PARTS, isAxisProperty, isConditionalAxisValue} from '../../axis';\nimport {PositionScaleChannel, POSITION_SCALE_CHANNELS} from '../../channel';\nimport {getFieldOrDatumDef, PositionDatumDef, PositionFieldDef} from '../../channeldef';\nimport {getFirstDefined, isEmpty, keys, normalizeAngle} from '../../util';\nimport {isSignalRef} from '../../vega.schema';\nimport {mergeTitleComponent} from '../common';\nimport {guideEncodeEntry} from '../guide';\nimport {LayerModel} from '../layer';\nimport {parseGuideResolve} from '../resolve';\nimport {defaultTieBreaker, Explicit, mergeValuesWithExplicit} from '../split';\nimport {UnitModel} from '../unit';\nimport {AxisComponent, AxisComponentIndex, AxisComponentProps, AXIS_COMPONENT_PROPERTIES} from './component';\nimport {getAxisConfig, getAxisConfigs} from './config';\nimport * as encode from './encode';\nimport {AxisRuleParams, axisRules, defaultOrient, getFieldDefTitle, getLabelAngle} from './properties';\nimport {guideFormat, guideFormatType} from '../format';\n\nexport function parseUnitAxes(model: UnitModel): AxisComponentIndex {\n return POSITION_SCALE_CHANNELS.reduce((axis, channel) => {\n if (model.component.scales[channel]) {\n axis[channel] = [parseAxis(channel, model)];\n }\n return axis;\n }, {} as AxisComponentIndex);\n}\n\nconst OPPOSITE_ORIENT: Record = {\n bottom: 'top',\n top: 'bottom',\n left: 'right',\n right: 'left'\n};\n\nexport function parseLayerAxes(model: LayerModel) {\n const {axes, resolve} = model.component;\n const axisCount: Record = {top: 0, bottom: 0, right: 0, left: 0};\n\n for (const child of model.children) {\n child.parseAxesAndHeaders();\n\n for (const channel of keys(child.component.axes)) {\n resolve.axis[channel] = parseGuideResolve(model.component.resolve, channel);\n if (resolve.axis[channel] === 'shared') {\n // If the resolve says shared (and has not been overridden)\n // We will try to merge and see if there is a conflict\n\n axes[channel] = mergeAxisComponents(axes[channel], child.component.axes[channel]);\n\n if (!axes[channel]) {\n // If merge returns nothing, there is a conflict so we cannot make the axis shared.\n // Thus, mark axis as independent and remove the axis component.\n resolve.axis[channel] = 'independent';\n delete axes[channel];\n }\n }\n }\n }\n\n // Move axes to layer's axis component and merge shared axes\n for (const channel of POSITION_SCALE_CHANNELS) {\n for (const child of model.children) {\n if (!child.component.axes[channel]) {\n // skip if the child does not have a particular axis\n continue;\n }\n\n if (resolve.axis[channel] === 'independent') {\n // If axes are independent, concat the axisComponent array.\n axes[channel] = (axes[channel] ?? []).concat(child.component.axes[channel]);\n\n // Automatically adjust orient\n for (const axisComponent of child.component.axes[channel]) {\n const {value: orient, explicit} = axisComponent.getWithExplicit('orient');\n if (isSignalRef(orient)) {\n continue;\n }\n\n if (axisCount[orient] > 0 && !explicit) {\n // Change axis orient if the number do not match\n const oppositeOrient = OPPOSITE_ORIENT[orient];\n if (axisCount[orient] > axisCount[oppositeOrient]) {\n axisComponent.set('orient', oppositeOrient, false);\n }\n }\n axisCount[orient]++;\n\n // TODO(https://github.com/vega/vega-lite/issues/2634): automatically add extra offset?\n }\n }\n\n // After merging, make sure to remove axes from child\n delete child.component.axes[channel];\n }\n\n // Show gridlines for first axis only for dual-axis chart\n if (resolve.axis[channel] === 'independent' && axes[channel] && axes[channel].length > 1) {\n for (const [index, axisCmpt] of (axes[channel] || []).entries()) {\n if (index > 0 && !!axisCmpt.get('grid') && !axisCmpt.explicit.grid) {\n axisCmpt.implicit.grid = false;\n }\n }\n }\n }\n}\n\nfunction mergeAxisComponents(\n mergedAxisCmpts: AxisComponent[],\n childAxisCmpts: readonly AxisComponent[]\n): AxisComponent[] {\n if (mergedAxisCmpts) {\n // FIXME: this is a bit wrong once we support multiple axes\n if (mergedAxisCmpts.length !== childAxisCmpts.length) {\n return undefined; // Cannot merge axis component with different number of axes.\n }\n const length = mergedAxisCmpts.length;\n for (let i = 0; i < length; i++) {\n const merged = mergedAxisCmpts[i];\n const child = childAxisCmpts[i];\n\n if (!!merged !== !!child) {\n return undefined;\n } else if (merged && child) {\n const mergedOrient = merged.getWithExplicit('orient');\n const childOrient = child.getWithExplicit('orient');\n\n if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {\n // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)\n\n // Cannot merge due to inconsistent orient\n return undefined;\n } else {\n mergedAxisCmpts[i] = mergeAxisComponent(merged, child);\n }\n }\n }\n } else {\n // For first one, return a copy of the child\n return childAxisCmpts.map(axisComponent => axisComponent.clone());\n }\n return mergedAxisCmpts;\n}\n\nfunction mergeAxisComponent(merged: AxisComponent, child: AxisComponent): AxisComponent {\n for (const prop of AXIS_COMPONENT_PROPERTIES) {\n const mergedValueWithExplicit = mergeValuesWithExplicit(\n merged.getWithExplicit(prop),\n child.getWithExplicit(prop),\n prop,\n 'axis',\n\n // Tie breaker function\n (v1: Explicit, v2: Explicit) => {\n switch (prop) {\n case 'title':\n return mergeTitleComponent(v1, v2);\n case 'gridScale':\n return {\n explicit: v1.explicit, // keep the old explicit\n value: getFirstDefined(v1.value, v2.value)\n };\n }\n return defaultTieBreaker(v1, v2, prop, 'axis');\n }\n );\n merged.setWithExplicit(prop, mergedValueWithExplicit);\n }\n return merged;\n}\n\nfunction isExplicit(\n value: T,\n property: keyof AxisComponentProps,\n axis: Axis,\n model: UnitModel,\n channel: PositionScaleChannel\n) {\n if (property === 'disable') {\n return axis !== undefined; // if axis is specified or null/false, then its enable/disable state is explicit\n }\n\n axis = axis || {};\n\n switch (property) {\n case 'titleAngle':\n case 'labelAngle':\n return value === (isSignalRef(axis.labelAngle) ? axis.labelAngle : normalizeAngle(axis.labelAngle));\n case 'values':\n return !!axis.values;\n // specified axis.values is already respected, but may get transformed.\n case 'encode':\n // both VL axis.encoding and axis.labelAngle affect VG axis.encode\n return !!axis.encoding || !!axis.labelAngle;\n case 'title':\n // title can be explicit if fieldDef.title is set\n if (value === getFieldDefTitle(model, channel)) {\n return true;\n }\n }\n // Otherwise, things are explicit if the returned value matches the specified property\n return value === axis[property];\n}\n\n/**\n * Properties to always include values from config\n */\nconst propsToAlwaysIncludeConfig = new Set([\n 'grid', // Grid is an exception because we need to set grid = true to generate another grid axis\n '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.\n // the rest are not axis configs in Vega, but are in VL, so we need to set too.\n 'format',\n 'formatType',\n 'orient',\n 'labelExpr',\n 'tickCount',\n 'position',\n 'tickMinStep'\n]);\n\nfunction parseAxis(channel: PositionScaleChannel, model: UnitModel): AxisComponent {\n let axis = model.axis(channel);\n\n const axisComponent = new AxisComponent();\n\n const fieldOrDatumDef = getFieldOrDatumDef(model.encoding[channel]) as\n | PositionFieldDef\n | PositionDatumDef;\n\n const {mark, config} = model;\n\n const orient =\n axis?.orient ||\n config[channel === 'x' ? 'axisX' : 'axisY']?.orient ||\n config.axis?.orient ||\n defaultOrient(channel);\n\n const scaleType = model.getScaleComponent(channel).get('type');\n\n const axisConfigs = getAxisConfigs(channel, scaleType, orient, model.config);\n\n const disable =\n axis !== undefined ? !axis : getAxisConfig('disable', config.style, axis?.style, axisConfigs).configValue;\n axisComponent.set('disable', disable, axis !== undefined);\n if (disable) {\n return axisComponent;\n }\n\n axis = axis || {};\n\n const labelAngle = getLabelAngle(fieldOrDatumDef, axis, channel, config.style, axisConfigs);\n const formatType = guideFormatType(axis.formatType, fieldOrDatumDef, scaleType);\n const format = guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, axis.format, axis.formatType, config, true);\n\n const ruleParams: AxisRuleParams = {\n fieldOrDatumDef,\n axis,\n channel,\n model,\n scaleType,\n orient,\n labelAngle,\n format,\n formatType,\n mark,\n config\n };\n // 1.2. Add properties\n for (const property of AXIS_COMPONENT_PROPERTIES) {\n const value =\n property in axisRules ? axisRules[property](ruleParams) : isAxisProperty(property) ? axis[property] : undefined;\n\n const hasValue = value !== undefined;\n\n const explicit = isExplicit(value, property, axis, model, channel);\n\n if (hasValue && explicit) {\n axisComponent.set(property, value, explicit);\n } else {\n const {configValue = undefined, configFrom = undefined} =\n isAxisProperty(property) && property !== 'values'\n ? getAxisConfig(property, config.style, axis.style, axisConfigs)\n : {};\n const hasConfigValue = configValue !== undefined;\n\n if (hasValue && !hasConfigValue) {\n // only set property if it is explicitly set or has no config value (otherwise we will accidentally override config)\n axisComponent.set(property, value, explicit);\n } else if (\n // Cases need implicit values\n // 1. Axis config that aren't available in Vega\n !(configFrom === 'vgAxisConfig') ||\n // 2. Certain properties are always included (see `propsToAlwaysIncludeConfig`'s declaration for more details)\n (propsToAlwaysIncludeConfig.has(property) && hasConfigValue) ||\n // 3. Conditional axis values and signals\n isConditionalAxisValue(configValue) ||\n isSignalRef(configValue)\n ) {\n // If a config is specified and is conditional, copy conditional value from axis config\n axisComponent.set(property, configValue, false);\n }\n }\n }\n\n // 2) Add guide encode definition groups\n const axisEncoding = axis.encoding ?? {};\n const axisEncode = AXIS_PARTS.reduce((e: VgAxisEncode, part) => {\n if (!axisComponent.hasAxisPart(part)) {\n // No need to create encode for a disabled part.\n return e;\n }\n\n const axisEncodingPart = guideEncodeEntry(axisEncoding[part] ?? {}, model);\n\n const value = part === 'labels' ? encode.labels(model, channel, axisEncodingPart) : axisEncodingPart;\n\n if (value !== undefined && !isEmpty(value)) {\n e[part] = {update: value};\n }\n return e;\n }, {} as VgAxisEncode);\n\n // FIXME: By having encode as one property, we won't have fine grained encode merging.\n if (!isEmpty(axisEncode)) {\n axisComponent.set('encode', axisEncode, !!axis.encoding || axis.labelAngle !== undefined);\n }\n\n return axisComponent;\n}\n","import {getSecondaryRangeChannel, PositionScaleChannel} from '../../channel';\nimport {channelDefType, getFieldOrDatumDef, isFieldDef, isPositionFieldOrDatumDef} from '../../channeldef';\nimport {formatCustomType, isCustomFormatType} from '../format';\nimport {UnitModel} from '../unit';\n\nexport function labels(model: UnitModel, channel: PositionScaleChannel, specifiedLabelsSpec: any) {\n const {encoding, config} = model;\n\n const fieldOrDatumDef =\n getFieldOrDatumDef(encoding[channel]) ?? getFieldOrDatumDef(encoding[getSecondaryRangeChannel(channel)]);\n const axis = model.axis(channel) || {};\n const {format, formatType} = axis;\n\n if (isCustomFormatType(formatType)) {\n return {\n text: formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format,\n formatType,\n config\n }),\n ...specifiedLabelsSpec\n };\n } else if (format === undefined && formatType === undefined && config.customFormatTypes) {\n if (channelDefType(fieldOrDatumDef) === 'quantitative') {\n if (\n isPositionFieldOrDatumDef(fieldOrDatumDef) &&\n fieldOrDatumDef.stack === 'normalize' &&\n config.normalizedNumberFormatType\n ) {\n return {\n text: formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format: config.normalizedNumberFormat,\n formatType: config.normalizedNumberFormatType,\n config\n }),\n ...specifiedLabelsSpec\n };\n } else if (config.numberFormatType) {\n return {\n text: formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format: config.numberFormat,\n formatType: config.numberFormatType,\n config\n }),\n ...specifiedLabelsSpec\n };\n }\n }\n if (\n channelDefType(fieldOrDatumDef) === 'temporal' &&\n config.timeFormatType &&\n isFieldDef(fieldOrDatumDef) &&\n !fieldOrDatumDef.timeUnit\n ) {\n return {\n text: formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format: config.timeFormat,\n formatType: config.timeFormatType,\n config\n }),\n ...specifiedLabelsSpec\n };\n }\n }\n return specifiedLabelsSpec;\n}\n","import {Config} from '../../config';\nimport {VgEncodeEntry} from '../../vega.schema';\nimport {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nfunction encodeEntry(model: UnitModel, fixedShape?: 'circle' | 'square') {\n const {config} = model;\n\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'include',\n orient: 'ignore',\n theta: 'ignore'\n }),\n ...encode.pointPosition('x', model, {defaultPos: 'mid'}),\n ...encode.pointPosition('y', model, {defaultPos: 'mid'}),\n ...encode.nonPosition('size', model),\n ...encode.nonPosition('angle', model),\n ...shapeMixins(model, config, fixedShape)\n };\n}\n\nexport function shapeMixins(model: UnitModel, config: Config, fixedShape?: 'circle' | 'square'): VgEncodeEntry {\n if (fixedShape) {\n return {shape: {value: fixedShape}};\n }\n return encode.nonPosition('shape', model);\n}\n\nexport const point: MarkCompiler = {\n vgMark: 'symbol',\n encodeEntry: (model: UnitModel) => {\n return encodeEntry(model);\n }\n};\n\nexport const circle: MarkCompiler = {\n vgMark: 'symbol',\n encodeEntry: (model: UnitModel) => {\n return encodeEntry(model, 'circle');\n }\n};\n\nexport const square: MarkCompiler = {\n vgMark: 'symbol',\n encodeEntry: (model: UnitModel) => {\n return encodeEntry(model, 'square');\n }\n};\n","import {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const rule: MarkCompiler = {\n vgMark: 'rule',\n encodeEntry: (model: UnitModel) => {\n const {markDef} = model;\n const orient = markDef.orient;\n\n if (!model.encoding.x && !model.encoding.y && !model.encoding.latitude && !model.encoding.longitude) {\n // Show nothing if we have none of x, y, lat, and long.\n return {};\n }\n\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n }),\n ...encode.pointOrRangePosition('x', model, {\n defaultPos: orient === 'horizontal' ? 'zeroOrMax' : 'mid',\n defaultPos2: 'zeroOrMin',\n range: orient !== 'vertical' // include x2 for horizontal or line segment rule\n }),\n ...encode.pointOrRangePosition('y', model, {\n defaultPos: orient === 'vertical' ? 'zeroOrMax' : 'mid',\n defaultPos2: 'zeroOrMin',\n range: orient !== 'horizontal' // include y2 for vertical or line segment rule\n }),\n ...encode.nonPosition('size', model, {\n vgChannel: 'strokeWidth' // VL's rule size is strokeWidth\n })\n };\n }\n};\n","import type {SignalRef} from 'vega';\nimport {Config} from '../../config';\nimport {Encoding} from '../../encoding';\nimport {MarkDef} from '../../mark';\nimport {getMarkPropOrConfig} from '../common';\nimport {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const text: MarkCompiler = {\n vgMark: 'text',\n\n encodeEntry: (model: UnitModel) => {\n const {config, encoding} = model;\n\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'include',\n baseline: 'include',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'include'\n }),\n ...encode.pointPosition('x', model, {defaultPos: 'mid'}),\n ...encode.pointPosition('y', model, {defaultPos: 'mid'}),\n ...encode.text(model),\n ...encode.nonPosition('size', model, {\n vgChannel: 'fontSize' // VL's text size is fontSize\n }),\n ...encode.nonPosition('angle', model),\n ...encode.valueIfDefined('align', align(model.markDef, encoding, config)),\n ...encode.valueIfDefined('baseline', baseline(model.markDef, encoding, config)),\n ...encode.pointPosition('radius', model, {defaultPos: null}),\n ...encode.pointPosition('theta', model, {defaultPos: null})\n };\n }\n};\n\nfunction align(markDef: MarkDef, encoding: Encoding, config: Config) {\n const a = getMarkPropOrConfig('align', markDef, config);\n if (a === undefined) {\n return 'center';\n }\n // If there is a config, Vega-parser will process this already.\n return undefined;\n}\n\nfunction baseline(markDef: MarkDef, encoding: Encoding, config: Config) {\n const b = getMarkPropOrConfig('baseline', markDef, config);\n if (b === undefined) {\n return 'middle';\n }\n // If there is a config, Vega-parser will process this already.\n return undefined;\n}\n","import {isNumber} from 'vega-util';\nimport {getViewConfigDiscreteStep} from '../../config';\nimport {isVgRangeStep, VgValueRef} from '../../vega.schema';\nimport {exprFromSignalRefOrValue, getMarkPropOrConfig, signalOrValueRef} from '../common';\nimport {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\nimport {getOffsetScaleChannel} from '../../channel';\n\nexport const tick: MarkCompiler = {\n vgMark: 'rect',\n\n encodeEntry: (model: UnitModel) => {\n const {config, markDef} = model;\n const orient = markDef.orient;\n\n const vgSizeChannel = orient === 'horizontal' ? 'width' : 'height';\n const vgThicknessChannel = orient === 'horizontal' ? 'height' : 'width';\n\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n }),\n\n ...encode.pointPosition('x', model, {defaultPos: 'mid', vgChannel: 'xc'}),\n ...encode.pointPosition('y', model, {defaultPos: 'mid', vgChannel: 'yc'}),\n\n // size / thickness => width / height\n ...encode.nonPosition('size', model, {\n defaultRef: defaultSize(model),\n vgChannel: vgSizeChannel\n }),\n [vgThicknessChannel]: signalOrValueRef(getMarkPropOrConfig('thickness', markDef, config))\n };\n }\n};\n\nfunction defaultSize(model: UnitModel): VgValueRef {\n const {config, markDef} = model;\n const {orient} = markDef;\n\n const vgSizeChannel = orient === 'horizontal' ? 'width' : 'height';\n const positionChannel = orient === 'horizontal' ? 'x' : 'y';\n\n const offsetScaleChannel = getOffsetScaleChannel(positionChannel);\n\n // Use offset scale if exists\n const scale = model.getScaleComponent(offsetScaleChannel) || model.getScaleComponent(positionChannel);\n const scaleName = model.scaleName(offsetScaleChannel) || model.scaleName(positionChannel);\n\n const markPropOrConfig =\n getMarkPropOrConfig('size', markDef, config, {vgChannel: vgSizeChannel}) ?? config.tick.bandSize;\n\n if (markPropOrConfig !== undefined) {\n return signalOrValueRef(markPropOrConfig);\n } else if (scale?.get('type') === 'band') {\n return {scale: scaleName, band: 1};\n }\n\n const scaleRange = scale?.get('range');\n const {tickBandPaddingInner} = config.scale;\n\n const step =\n scaleRange && isVgRangeStep(scaleRange) ? scaleRange.step : getViewConfigDiscreteStep(config.view, vgSizeChannel);\n\n if (isNumber(step) && isNumber(tickBandPaddingInner)) {\n return {value: step * (1 - tickBandPaddingInner)};\n } else {\n return {signal: `${exprFromSignalRefOrValue(tickBandPaddingInner)} * ${exprFromSignalRefOrValue(step)}`};\n }\n}\n","import {isArray} from 'vega-util';\nimport {FieldRefOption, isFieldDef, isValueDef, vgField} from '../../channeldef';\nimport {DataSourceType} from '../../data';\nimport {pathGroupingFields} from '../../encoding';\nimport {AREA, BAR, LINE, Mark, TRAIL, isPathMark} from '../../mark';\nimport {contains, getFirstDefined, isNullOrFalse, keys, omit, pick} from '../../util';\nimport {VG_CORNERRADIUS_CHANNELS, VgCompare, VgEncodeEntry} from '../../vega.schema';\nimport {getMarkConfig, getMarkPropOrConfig, getStyles, signalOrValueRef, sortParams} from '../common';\nimport {UnitModel} from '../unit';\nimport {arc} from './arc';\nimport {area} from './area';\nimport {bar} from './bar';\nimport {MarkCompiler} from './base';\nimport {geoshape} from './geoshape';\nimport {image} from './image';\nimport {line, trail} from './line';\nimport {circle, point, square} from './point';\nimport {rect} from './rect';\nimport {rule} from './rule';\nimport {text} from './text';\nimport {tick} from './tick';\n\nconst markCompiler: Record = {\n arc,\n area,\n bar,\n circle,\n geoshape,\n image,\n line,\n point,\n rect,\n rule,\n square,\n text,\n tick,\n trail\n};\n\nexport function parseMarkGroups(model: UnitModel): any[] {\n if (contains([LINE, AREA, TRAIL], model.mark)) {\n const details = pathGroupingFields(model.mark, model.encoding);\n if (details.length > 0) {\n return getPathGroups(model, details);\n }\n // otherwise use standard mark groups\n } else if (model.mark === BAR) {\n const hasCornerRadius = VG_CORNERRADIUS_CHANNELS.some(prop =>\n getMarkPropOrConfig(prop, model.markDef, model.config)\n );\n if (model.stack && !model.fieldDef('size') && hasCornerRadius) {\n return getGroupsForStackedBarWithCornerRadius(model);\n }\n }\n\n return getMarkGroup(model);\n}\n\nconst FACETED_PATH_PREFIX = 'faceted_path_';\n\nfunction getPathGroups(model: UnitModel, details: string[]) {\n // TODO: for non-stacked plot, map order to zindex. (Maybe rename order for layer to zindex?)\n\n return [\n {\n name: model.getName('pathgroup'),\n type: 'group',\n from: {\n facet: {\n name: FACETED_PATH_PREFIX + model.requestDataName(DataSourceType.Main),\n data: model.requestDataName(DataSourceType.Main),\n groupby: details\n }\n },\n encode: {\n update: {\n width: {field: {group: 'width'}},\n height: {field: {group: 'height'}}\n }\n },\n // With subfacet for line/area group, need to use faceted data from above.\n marks: getMarkGroup(model, {fromPrefix: FACETED_PATH_PREFIX})\n }\n ];\n}\n\nconst STACK_GROUP_PREFIX = 'stack_group_';\n\n/**\n * We need to put stacked bars into groups in order to enable cornerRadius for stacks.\n * If stack is used and the model doesn't have size encoding, we put the mark into groups,\n * and apply cornerRadius properties at the group.\n */\nfunction getGroupsForStackedBarWithCornerRadius(model: UnitModel) {\n // Generate the mark\n const [mark] = getMarkGroup(model, {fromPrefix: STACK_GROUP_PREFIX});\n\n // Get the scale for the stacked field\n const fieldScale = model.scaleName(model.stack.fieldChannel);\n const stackField = (opt: FieldRefOption = {}) => model.vgField(model.stack.fieldChannel, opt);\n // Find the min/max of the pixel value on the stacked direction\n const stackFieldGroup = (func: 'min' | 'max', expr: 'datum' | 'parent') => {\n const vgFieldMinMax = [\n stackField({prefix: 'min', suffix: 'start', expr}),\n stackField({prefix: 'max', suffix: 'start', expr}),\n stackField({prefix: 'min', suffix: 'end', expr}),\n stackField({prefix: 'max', suffix: 'end', expr})\n ];\n return `${func}(${vgFieldMinMax.map(field => `scale('${fieldScale}',${field})`).join(',')})`;\n };\n\n let groupUpdate: VgEncodeEntry;\n let innerGroupUpdate: VgEncodeEntry;\n\n // Build the encoding for group and an inner group\n if (model.stack.fieldChannel === 'x') {\n // Move cornerRadius, y/yc/y2/height properties to group\n // Group x/x2 should be the min/max of the marks within\n groupUpdate = {\n ...pick(mark.encode.update, ['y', 'yc', 'y2', 'height', ...VG_CORNERRADIUS_CHANNELS]),\n x: {signal: stackFieldGroup('min', 'datum')},\n x2: {signal: stackFieldGroup('max', 'datum')},\n clip: {value: true}\n };\n // Inner group should revert the x translation, and pass height through\n innerGroupUpdate = {\n x: {field: {group: 'x'}, mult: -1},\n height: {field: {group: 'height'}}\n };\n // The marks should use the same height as group, without y/yc/y2 properties (because it's already done by group)\n // This is why size encoding is not supported yet\n mark.encode.update = {\n ...omit(mark.encode.update, ['y', 'yc', 'y2']),\n height: {field: {group: 'height'}}\n };\n } else {\n groupUpdate = {\n ...pick(mark.encode.update, ['x', 'xc', 'x2', 'width']),\n y: {signal: stackFieldGroup('min', 'datum')},\n y2: {signal: stackFieldGroup('max', 'datum')},\n clip: {value: true}\n };\n innerGroupUpdate = {\n y: {field: {group: 'y'}, mult: -1},\n width: {field: {group: 'width'}}\n };\n mark.encode.update = {\n ...omit(mark.encode.update, ['x', 'xc', 'x2']),\n width: {field: {group: 'width'}}\n };\n }\n\n // Deal with cornerRadius properties\n for (const key of VG_CORNERRADIUS_CHANNELS) {\n const configValue = getMarkConfig(key, model.markDef, model.config);\n // Move from mark to group\n if (mark.encode.update[key]) {\n groupUpdate[key] = mark.encode.update[key];\n delete mark.encode.update[key];\n } else if (configValue) {\n groupUpdate[key] = signalOrValueRef(configValue);\n }\n // Overwrite any cornerRadius on mark set by config --- they are already moved to the group\n if (configValue) {\n mark.encode.update[key] = {value: 0};\n }\n }\n\n const groupby: string[] = [];\n\n if (model.stack.groupbyChannels?.length > 0) {\n for (const groupbyChannel of model.stack.groupbyChannels) {\n // For bin and time unit, we have to add bin/timeunit -end channels.\n const groupByField = model.fieldDef(groupbyChannel);\n const field = vgField(groupByField);\n if (field) {\n groupby.push(field);\n }\n\n if (groupByField?.bin || groupByField?.timeUnit) {\n groupby.push(vgField(groupByField, {binSuffix: 'end'}));\n }\n }\n }\n\n const strokeProperties = [\n 'stroke',\n 'strokeWidth',\n 'strokeJoin',\n 'strokeCap',\n 'strokeDash',\n 'strokeDashOffset',\n 'strokeMiterLimit',\n 'strokeOpacity'\n ] as const;\n\n // Generate stroke properties for the group\n groupUpdate = strokeProperties.reduce((encode, prop) => {\n if (mark.encode.update[prop]) {\n return {...encode, [prop]: mark.encode.update[prop]};\n } else {\n const configValue = getMarkConfig(prop, model.markDef, model.config);\n if (configValue !== undefined) {\n return {...encode, [prop]: signalOrValueRef(configValue)};\n } else {\n return encode;\n }\n }\n }, groupUpdate);\n\n // Apply strokeForeground and strokeOffset if stroke is used\n if (groupUpdate.stroke) {\n groupUpdate.strokeForeground = {value: true};\n groupUpdate.strokeOffset = {value: 0};\n }\n\n return [\n {\n type: 'group',\n from: {\n facet: {\n data: model.requestDataName(DataSourceType.Main),\n name: STACK_GROUP_PREFIX + model.requestDataName(DataSourceType.Main),\n groupby,\n aggregate: {\n fields: [\n stackField({suffix: 'start'}),\n stackField({suffix: 'start'}),\n stackField({suffix: 'end'}),\n stackField({suffix: 'end'})\n ],\n ops: ['min', 'max', 'min', 'max']\n }\n }\n },\n encode: {\n update: groupUpdate\n },\n marks: [\n {\n type: 'group',\n encode: {update: innerGroupUpdate},\n marks: [mark]\n }\n ]\n }\n ];\n}\n\nexport function getSort(model: UnitModel): VgCompare {\n const {encoding, stack, mark, markDef, config} = model;\n const order = encoding.order;\n if (\n (!isArray(order) && isValueDef(order) && isNullOrFalse(order.value)) ||\n (!order && isNullOrFalse(getMarkPropOrConfig('order', markDef, config)))\n ) {\n return undefined;\n } else if ((isArray(order) || isFieldDef(order)) && !stack) {\n // Sort by the order field if it is specified and the field is not stacked. (For stacked field, order specify stack order.)\n return sortParams(order, {expr: 'datum'});\n } else if (isPathMark(mark)) {\n // For both line and area, we sort values based on dimension by default\n const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';\n const dimensionChannelDef = encoding[dimensionChannel];\n if (isFieldDef(dimensionChannelDef)) {\n return {field: dimensionChannel};\n }\n }\n return undefined;\n}\n\nfunction getMarkGroup(model: UnitModel, opt: {fromPrefix: string} = {fromPrefix: ''}) {\n const {mark, markDef, encoding, config} = model;\n\n const clip = getFirstDefined(markDef.clip, scaleClip(model), projectionClip(model));\n const style = getStyles(markDef);\n const key = encoding.key;\n const sort = getSort(model);\n const interactive = interactiveFlag(model);\n const aria = getMarkPropOrConfig('aria', markDef, config);\n\n const postEncodingTransform = markCompiler[mark].postEncodingTransform\n ? markCompiler[mark].postEncodingTransform(model)\n : null;\n\n return [\n {\n name: model.getName('marks'),\n type: markCompiler[mark].vgMark,\n ...(clip ? {clip} : {}),\n ...(style ? {style} : {}),\n ...(key ? {key: key.field} : {}),\n ...(sort ? {sort} : {}),\n ...(interactive ? interactive : {}),\n ...(aria === false ? {aria} : {}),\n from: {data: opt.fromPrefix + model.requestDataName(DataSourceType.Main)},\n encode: {\n update: markCompiler[mark].encodeEntry(model)\n },\n ...(postEncodingTransform\n ? {\n transform: postEncodingTransform\n }\n : {})\n }\n ];\n}\n\n/**\n * If scales are bound to interval selections, we want to automatically clip\n * marks to account for panning/zooming interactions. We identify bound scales\n * by the selectionExtent property, which gets added during scale parsing.\n */\nfunction scaleClip(model: UnitModel) {\n const xScale = model.getScaleComponent('x');\n const yScale = model.getScaleComponent('y');\n return xScale?.get('selectionExtent') || yScale?.get('selectionExtent') ? true : undefined;\n}\n\n/**\n * If we use a custom projection with auto-fitting to the geodata extent,\n * we need to clip to ensure the chart size doesn't explode.\n */\nfunction projectionClip(model: UnitModel) {\n const projection = model.component.projection;\n return projection && !projection.isFit ? true : undefined;\n}\n\n/**\n * Only output interactive flags if we have selections defined somewhere in our model hierarchy.\n */\nfunction interactiveFlag(model: UnitModel) {\n if (!model.component.selection) return null;\n const unitCount = keys(model.component.selection).length;\n let parentCount = unitCount;\n let parent = model.parent;\n while (parent && parentCount === 0) {\n parentCount = keys(parent.component.selection).length;\n parent = parent.parent;\n }\n return parentCount\n ? {\n interactive: unitCount > 0 || model.mark === 'geoshape' || !!model.encoding.tooltip || !!model.markDef.tooltip\n }\n : null;\n}\n","import {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const arc: MarkCompiler = {\n vgMark: 'arc',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'ignore'\n }),\n ...encode.pointPosition('x', model, {defaultPos: 'mid'}),\n ...encode.pointPosition('y', model, {defaultPos: 'mid'}),\n\n // arcs are rectangles in polar coordinates\n ...encode.rectPosition(model, 'radius'),\n ...encode.rectPosition(model, 'theta')\n };\n }\n};\n","import {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const area: MarkCompiler = {\n vgMark: 'area',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'include',\n size: 'ignore',\n theta: 'ignore'\n }),\n ...encode.pointOrRangePosition('x', model, {\n defaultPos: 'zeroOrMin',\n defaultPos2: 'zeroOrMin',\n range: model.markDef.orient === 'horizontal'\n }),\n ...encode.pointOrRangePosition('y', model, {\n defaultPos: 'zeroOrMin',\n defaultPos2: 'zeroOrMin',\n range: model.markDef.orient === 'vertical'\n }),\n ...encode.defined(model)\n };\n }\n};\n","import {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const bar: MarkCompiler = {\n vgMark: 'rect',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n }),\n ...encode.rectPosition(model, 'x'),\n ...encode.rectPosition(model, 'y')\n };\n }\n};\n","import {GeoShapeTransform as VgGeoShapeTransform} from 'vega';\nimport {isFieldDef, vgField} from '../../channeldef';\nimport {GEOJSON} from '../../type';\nimport {VgPostEncodingTransform} from '../../vega.schema';\nimport {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const geoshape: MarkCompiler = {\n vgMark: 'shape',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'ignore'\n })\n };\n },\n postEncodingTransform: (model: UnitModel): VgPostEncodingTransform[] => {\n const {encoding} = model;\n const shapeDef = encoding.shape;\n\n const transform: VgGeoShapeTransform = {\n type: 'geoshape',\n projection: model.projectionName(),\n // as: 'shape',\n ...(shapeDef && isFieldDef(shapeDef) && shapeDef.type === GEOJSON\n ? {field: vgField(shapeDef, {expr: 'datum'})}\n : {})\n };\n return [transform];\n }\n};\n","import {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const image: MarkCompiler = {\n vgMark: 'image',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'ignore',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n }),\n ...encode.rectPosition(model, 'x'),\n ...encode.rectPosition(model, 'y'),\n ...encode.text(model, 'url')\n };\n }\n};\n","import {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const line: MarkCompiler = {\n vgMark: 'line',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'ignore'\n }),\n ...encode.pointPosition('x', model, {defaultPos: 'mid'}),\n ...encode.pointPosition('y', model, {defaultPos: 'mid'}),\n ...encode.nonPosition('size', model, {\n vgChannel: 'strokeWidth' // VL's line size is strokeWidth\n }),\n ...encode.defined(model)\n };\n }\n};\n\nexport const trail: MarkCompiler = {\n vgMark: 'trail',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'include',\n orient: 'ignore',\n theta: 'ignore'\n }),\n ...encode.pointPosition('x', model, {defaultPos: 'mid'}),\n ...encode.pointPosition('y', model, {defaultPos: 'mid'}),\n ...encode.nonPosition('size', model),\n ...encode.defined(model)\n };\n }\n};\n","import {UnitModel} from '../unit';\nimport {MarkCompiler} from './base';\nimport * as encode from './encode';\n\nexport const rect: MarkCompiler = {\n vgMark: 'rect',\n encodeEntry: (model: UnitModel) => {\n return {\n ...encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n }),\n ...encode.rectPosition(model, 'x'),\n ...encode.rectPosition(model, 'y')\n };\n }\n};\n","import {NewSignal, SignalRef} from 'vega';\nimport {isArray} from 'vega-util';\nimport {Axis, AxisInternal, isConditionalAxisValue} from '../axis';\nimport {\n Channel,\n GEOPOSITION_CHANNELS,\n NonPositionScaleChannel,\n NONPOSITION_SCALE_CHANNELS,\n PositionChannel,\n POSITION_SCALE_CHANNELS,\n ScaleChannel,\n SCALE_CHANNELS,\n SingleDefChannel,\n supportLegend,\n X,\n Y\n} from '../channel';\nimport {\n getFieldDef,\n getFieldOrDatumDef,\n isFieldOrDatumDef,\n isTypedFieldDef,\n MarkPropFieldOrDatumDef,\n PositionFieldDef\n} from '../channeldef';\nimport {Config} from '../config';\nimport {isGraticuleGenerator} from '../data';\nimport * as vlEncoding from '../encoding';\nimport {Encoding, initEncoding} from '../encoding';\nimport {ExprRef, replaceExprRef} from '../expr';\nimport {LegendInternal} from '../legend';\nimport {GEOSHAPE, isMarkDef, Mark, MarkDef} from '../mark';\nimport {Projection} from '../projection';\nimport {Domain, Scale} from '../scale';\nimport {isSelectionParameter, SelectionParameter} from '../selection';\nimport {LayoutSizeMixins, NormalizedUnitSpec} from '../spec';\nimport {isFrameMixins} from '../spec/base';\nimport {stack, StackProperties} from '../stack';\nimport {keys} from '../util';\nimport {VgData, VgLayout} from '../vega.schema';\nimport {assembleAxisSignals} from './axis/assemble';\nimport {AxisInternalIndex} from './axis/component';\nimport {parseUnitAxes} from './axis/parse';\nimport {signalOrValueRefWithCondition, signalRefOrValue} from './common';\nimport {parseData} from './data/parse';\nimport {assembleLayoutSignals} from './layoutsize/assemble';\nimport {initLayoutSize} from './layoutsize/init';\nimport {parseUnitLayoutSize} from './layoutsize/parse';\nimport {LegendInternalIndex} from './legend/component';\nimport {defaultFilled, initMarkdef} from './mark/init';\nimport {parseMarkGroups} from './mark/mark';\nimport {isLayerModel, Model, ModelWithField} from './model';\nimport {ScaleIndex} from './scale/component';\nimport {\n assembleTopLevelSignals,\n assembleUnitSelectionData,\n assembleUnitSelectionMarks,\n assembleUnitSelectionSignals\n} from './selection/assemble';\nimport {parseUnitSelection} from './selection/parse';\n\n/**\n * Internal model of Vega-Lite specification for the compiler.\n */\nexport class UnitModel extends ModelWithField {\n public readonly markDef: MarkDef;\n public readonly encoding: Encoding;\n\n public readonly specifiedScales: ScaleIndex = {};\n\n public readonly stack: StackProperties;\n\n protected specifiedAxes: AxisInternalIndex = {};\n\n protected specifiedLegends: LegendInternalIndex = {};\n\n public specifiedProjection: Projection = {};\n\n public readonly selection: SelectionParameter[] = [];\n public children: Model[] = [];\n\n constructor(\n spec: NormalizedUnitSpec,\n parent: Model,\n parentGivenName: string,\n parentGivenSize: LayoutSizeMixins = {},\n config: Config\n ) {\n super(spec, 'unit', parent, parentGivenName, config, undefined, isFrameMixins(spec) ? spec.view : undefined);\n\n const markDef = isMarkDef(spec.mark) ? {...spec.mark} : {type: spec.mark};\n const mark = markDef.type;\n\n // Need to init filled before other mark properties because encoding depends on filled but other mark properties depend on types inside encoding\n if (markDef.filled === undefined) {\n markDef.filled = defaultFilled(markDef, config, {\n graticule: spec.data && isGraticuleGenerator(spec.data)\n });\n }\n\n const encoding = (this.encoding = initEncoding(spec.encoding || {}, mark, markDef.filled, config));\n this.markDef = initMarkdef(markDef, encoding, config);\n\n this.size = initLayoutSize({\n encoding,\n size: isFrameMixins(spec)\n ? {\n ...parentGivenSize,\n ...(spec.width ? {width: spec.width} : {}),\n ...(spec.height ? {height: spec.height} : {})\n }\n : parentGivenSize\n });\n\n // calculate stack properties\n this.stack = stack(this.markDef, encoding);\n this.specifiedScales = this.initScales(mark, encoding);\n\n this.specifiedAxes = this.initAxes(encoding);\n this.specifiedLegends = this.initLegends(encoding);\n this.specifiedProjection = spec.projection;\n\n // Selections will be initialized upon parse.\n this.selection = (spec.params ?? []).filter(p => isSelectionParameter(p)) as SelectionParameter[];\n }\n\n public get hasProjection(): boolean {\n const {encoding} = this;\n const isGeoShapeMark = this.mark === GEOSHAPE;\n const hasGeoPosition = encoding && GEOPOSITION_CHANNELS.some(channel => isFieldOrDatumDef(encoding[channel]));\n return isGeoShapeMark || hasGeoPosition;\n }\n\n /**\n * Return specified Vega-Lite scale domain for a particular channel\n * @param channel\n */\n public scaleDomain(channel: ScaleChannel): Domain {\n const scale = this.specifiedScales[channel];\n return scale ? scale.domain : undefined;\n }\n\n public axis(channel: PositionChannel): AxisInternal {\n return this.specifiedAxes[channel];\n }\n\n public legend(channel: NonPositionScaleChannel): LegendInternal {\n return this.specifiedLegends[channel];\n }\n\n private initScales(mark: Mark, encoding: Encoding): ScaleIndex {\n return SCALE_CHANNELS.reduce((scales, channel) => {\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) as\n | PositionFieldDef\n | MarkPropFieldOrDatumDef;\n if (fieldOrDatumDef) {\n scales[channel] = this.initScale(fieldOrDatumDef.scale ?? {});\n }\n return scales;\n }, {} as ScaleIndex);\n }\n\n private initScale(scale: Scale): Scale {\n const {domain, range} = scale;\n // TODO: we could simplify this function if we had a recursive replace function\n const scaleInternal = replaceExprRef(scale);\n if (isArray(domain)) {\n scaleInternal.domain = domain.map(signalRefOrValue);\n }\n if (isArray(range)) {\n scaleInternal.range = range.map(signalRefOrValue);\n }\n return scaleInternal as Scale;\n }\n\n private initAxes(encoding: Encoding): AxisInternalIndex {\n return POSITION_SCALE_CHANNELS.reduce((_axis, channel) => {\n // Position Axis\n\n // TODO: handle ConditionFieldDef\n const channelDef = encoding[channel];\n if (\n isFieldOrDatumDef(channelDef) ||\n (channel === X && isFieldOrDatumDef(encoding.x2)) ||\n (channel === Y && isFieldOrDatumDef(encoding.y2))\n ) {\n const axisSpec = isFieldOrDatumDef(channelDef) ? channelDef.axis : undefined;\n\n _axis[channel] = axisSpec\n ? this.initAxis({...axisSpec}) // convert truthy value to object\n : axisSpec;\n }\n return _axis;\n }, {});\n }\n\n private initAxis(axis: Axis): Axis {\n const props = keys(axis);\n const axisInternal = {};\n for (const prop of props) {\n const val = axis[prop];\n axisInternal[prop as any] = isConditionalAxisValue(val)\n ? signalOrValueRefWithCondition(val)\n : signalRefOrValue(val);\n }\n return axisInternal;\n }\n\n private initLegends(encoding: Encoding): LegendInternalIndex {\n return NONPOSITION_SCALE_CHANNELS.reduce((_legend, channel) => {\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) as MarkPropFieldOrDatumDef;\n\n if (fieldOrDatumDef && supportLegend(channel)) {\n const legend = fieldOrDatumDef.legend;\n _legend[channel] = legend\n ? replaceExprRef(legend) // convert truthy value to object\n : legend;\n }\n\n return _legend;\n }, {});\n }\n\n public parseData() {\n this.component.data = parseData(this);\n }\n\n public parseLayoutSize() {\n parseUnitLayoutSize(this);\n }\n\n public parseSelections() {\n this.component.selection = parseUnitSelection(this, this.selection);\n }\n\n public parseMarkGroup() {\n this.component.mark = parseMarkGroups(this);\n }\n\n public parseAxesAndHeaders() {\n this.component.axes = parseUnitAxes(this);\n }\n\n public assembleSelectionTopLevelSignals(signals: any[]): NewSignal[] {\n return assembleTopLevelSignals(this, signals);\n }\n\n public assembleSignals(): NewSignal[] {\n return [...assembleAxisSignals(this), ...assembleUnitSelectionSignals(this, [])];\n }\n\n public assembleSelectionData(data: readonly VgData[]): VgData[] {\n return assembleUnitSelectionData(this, data);\n }\n\n public assembleLayout(): VgLayout {\n return null;\n }\n\n public assembleLayoutSignals(): NewSignal[] {\n return assembleLayoutSignals(this);\n }\n\n public assembleMarks() {\n let marks = this.component.mark ?? [];\n\n // If this unit is part of a layer, selections should augment\n // all in concert rather than each unit individually. This\n // ensures correct interleaving of clipping and brushed marks.\n if (!this.parent || !isLayerModel(this.parent)) {\n marks = assembleUnitSelectionMarks(this, marks);\n }\n\n return marks.map(this.correctDataNames);\n }\n public assembleGroupStyle(): string | string[] {\n const {style} = this.view || {};\n if (style !== undefined) {\n return style;\n }\n if (this.encoding.x || this.encoding.y) {\n return 'cell';\n } else {\n return 'view';\n }\n }\n\n protected getMapping() {\n return this.encoding;\n }\n\n public get mark(): Mark {\n return this.markDef.type;\n }\n\n public channelHasField(channel: Channel) {\n return vlEncoding.channelHasField(this.encoding, channel);\n }\n\n public fieldDef(channel: SingleDefChannel) {\n const channelDef = this.encoding[channel];\n return getFieldDef(channelDef);\n }\n\n public typedFieldDef(channel: SingleDefChannel) {\n const fieldDef = this.fieldDef(channel);\n if (isTypedFieldDef(fieldDef)) {\n return fieldDef;\n }\n return null;\n }\n}\n","import {getSizeChannel, POSITION_SCALE_CHANNELS} from '../../channel';\nimport {isContinuousFieldOrDatumDef} from '../../channeldef';\nimport {Encoding} from '../../encoding';\nimport * as log from '../../log';\nimport {isStep, LayoutSizeMixins} from '../../spec/base';\n\nexport function initLayoutSize({encoding, size}: {encoding: Encoding; size: LayoutSizeMixins}) {\n for (const channel of POSITION_SCALE_CHANNELS) {\n const sizeType = getSizeChannel(channel);\n if (isStep(size[sizeType])) {\n if (isContinuousFieldOrDatumDef(encoding[channel])) {\n delete size[sizeType];\n log.warn(log.message.stepDropped(sizeType));\n }\n }\n }\n\n return size;\n}\n","import {Legend as VgLegend, NewSignal, SignalRef, Title as VgTitle} from 'vega';\nimport {array} from 'vega-util';\nimport {Config} from '../config';\nimport * as log from '../log';\nimport {isLayerSpec, isUnitSpec, LayoutSizeMixins, NormalizedLayerSpec} from '../spec';\nimport {keys} from '../util';\nimport {VgData, VgLayout} from '../vega.schema';\nimport {assembleAxisSignals} from './axis/assemble';\nimport {parseLayerAxes} from './axis/parse';\nimport {parseData} from './data/parse';\nimport {assembleLayoutSignals} from './layoutsize/assemble';\nimport {parseLayerLayoutSize} from './layoutsize/parse';\nimport {assembleLegends} from './legend/assemble';\nimport {Model} from './model';\nimport {assembleLayerSelectionMarks} from './selection/assemble';\nimport {UnitModel} from './unit';\n\nexport class LayerModel extends Model {\n // HACK: This should be (LayerModel | UnitModel)[], but setting the correct type leads to weird error.\n // So I'm just putting generic Model for now\n public readonly children: Model[];\n\n constructor(\n spec: NormalizedLayerSpec,\n parent: Model,\n parentGivenName: string,\n parentGivenSize: LayoutSizeMixins,\n config: Config\n ) {\n super(spec, 'layer', parent, parentGivenName, config, spec.resolve, spec.view);\n\n const layoutSize = {\n ...parentGivenSize,\n ...(spec.width ? {width: spec.width} : {}),\n ...(spec.height ? {height: spec.height} : {})\n };\n\n this.children = spec.layer.map((layer, i) => {\n if (isLayerSpec(layer)) {\n return new LayerModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);\n } else if (isUnitSpec(layer)) {\n return new UnitModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);\n }\n\n throw new Error(log.message.invalidSpec(layer));\n });\n }\n\n public parseData() {\n this.component.data = parseData(this);\n for (const child of this.children) {\n child.parseData();\n }\n }\n\n public parseLayoutSize() {\n parseLayerLayoutSize(this);\n }\n\n public parseSelections() {\n // Merge selections up the hierarchy so that they may be referenced\n // across unit specs. Persist their definitions within each child\n // to assemble signals which remain within output Vega unit groups.\n this.component.selection = {};\n for (const child of this.children) {\n child.parseSelections();\n for (const key of keys(child.component.selection)) {\n this.component.selection[key] = child.component.selection[key];\n }\n }\n }\n\n public parseMarkGroup() {\n for (const child of this.children) {\n child.parseMarkGroup();\n }\n }\n\n public parseAxesAndHeaders() {\n parseLayerAxes(this);\n }\n\n public assembleSelectionTopLevelSignals(signals: NewSignal[]): NewSignal[] {\n return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);\n }\n\n // TODO: Support same named selections across children.\n public assembleSignals(): NewSignal[] {\n return this.children.reduce((signals, child) => {\n return signals.concat(child.assembleSignals());\n }, assembleAxisSignals(this));\n }\n\n public assembleLayoutSignals(): NewSignal[] {\n return this.children.reduce((signals, child) => {\n return signals.concat(child.assembleLayoutSignals());\n }, assembleLayoutSignals(this));\n }\n\n public assembleSelectionData(data: readonly VgData[]): readonly VgData[] {\n return this.children.reduce((db, child) => child.assembleSelectionData(db), data);\n }\n\n public assembleGroupStyle(): string | string[] {\n const uniqueStyles = new Set();\n for (const child of this.children) {\n for (const style of array(child.assembleGroupStyle())) {\n uniqueStyles.add(style);\n }\n }\n const styles = Array.from(uniqueStyles);\n return styles.length > 1 ? styles : styles.length === 1 ? styles[0] : undefined;\n }\n\n public assembleTitle(): VgTitle {\n let title = super.assembleTitle();\n if (title) {\n return title;\n }\n // If title does not provide layer, look into children\n for (const child of this.children) {\n title = child.assembleTitle();\n if (title) {\n return title;\n }\n }\n return undefined;\n }\n\n public assembleLayout(): VgLayout {\n return null;\n }\n\n public assembleMarks(): any[] {\n return assembleLayerSelectionMarks(\n this,\n this.children.flatMap(child => {\n return child.assembleMarks();\n })\n );\n }\n\n public assembleLegends(): VgLegend[] {\n return this.children.reduce((legends, child) => {\n return legends.concat(child.assembleLegends());\n }, assembleLegends(this));\n }\n}\n","import type {SignalRef} from 'vega';\nimport {Config} from '../config';\nimport * as log from '../log';\nimport {isAnyConcatSpec, isFacetSpec, isLayerSpec, isUnitSpec, LayoutSizeMixins, NormalizedSpec} from '../spec';\nimport {ConcatModel} from './concat';\nimport {FacetModel} from './facet';\nimport {LayerModel} from './layer';\nimport {Model} from './model';\nimport {UnitModel} from './unit';\n\nexport function buildModel(\n spec: NormalizedSpec,\n parent: Model,\n parentGivenName: string,\n unitSize: LayoutSizeMixins,\n config: Config\n): Model {\n if (isFacetSpec(spec)) {\n return new FacetModel(spec, parent, parentGivenName, config);\n } else if (isLayerSpec(spec)) {\n return new LayerModel(spec, parent, parentGivenName, unitSize, config);\n } else if (isUnitSpec(spec)) {\n return new UnitModel(spec, parent, parentGivenName, unitSize, config);\n } else if (isAnyConcatSpec(spec)) {\n return new ConcatModel(spec, parent, parentGivenName, config);\n }\n throw new Error(log.message.invalidSpec(spec));\n}\n","import pkg from '../package.json';\nexport const version = pkg.version;\n\nexport {compile} from './compile/compile';\nexport type {Config} from './config';\nexport {normalize} from './normalize';\nexport type {TopLevelSpec} from './spec';\nexport * from './util';\n","import {AutoSizeType, LoggerInterface, Spec as VgSpec} from 'vega';\nimport {isString, mergeConfig} from 'vega-util';\nimport {getPositionScaleChannel} from '../channel';\nimport * as vlFieldDef from '../channeldef';\nimport {Config, initConfig, stripAndRedirectConfig} from '../config';\nimport * as log from '../log';\nimport {normalize} from '../normalize';\nimport {assembleParameterSignals} from '../parameter';\nimport {LayoutSizeMixins, TopLevel, TopLevelSpec} from '../spec';\nimport {\n AutoSizeParams,\n Datasets,\n extractTopLevelProperties,\n getFitType,\n isFitType,\n TopLevelProperties\n} from '../spec/toplevel';\nimport {Dict, keys} from '../util';\nimport {buildModel} from './buildmodel';\nimport {assembleRootData} from './data/assemble';\nimport {optimizeDataflow} from './data/optimize';\nimport {Model} from './model';\n\nexport interface CompileOptions {\n /**\n * Sets a Vega-Lite configuration.\n */\n config?: Config;\n\n /**\n * Sets a custom logger.\n */\n logger?: LoggerInterface;\n\n /**\n * Sets a field title formatter.\n */\n fieldTitle?: vlFieldDef.FieldTitleFormatter;\n}\n\n/**\n * Vega-Lite's main function, for compiling Vega-Lite spec into Vega spec.\n *\n * At a high-level, we make the following transformations in different phases:\n *\n * Input spec\n * |\n * | (Normalization)\n * v\n * Normalized Spec (Row/Column channels in single-view specs becomes faceted specs, composite marks becomes layered specs.)\n * |\n * | (Build Model)\n * v\n * A model tree of the spec\n * |\n * | (Parse)\n * v\n * A model tree with parsed components (intermediate structure of visualization primitives in a format that can be easily merged)\n * |\n * | (Optimize)\n * v\n * A model tree with parsed components with the data component optimized\n * |\n * | (Assemble)\n * v\n * Vega spec\n *\n * @param inputSpec The Vega-Lite specification.\n * @param opt Optional arguments passed to the Vega-Lite compiler.\n * @returns An object containing the compiled Vega spec and normalized Vega-Lite spec.\n */\nexport function compile(inputSpec: TopLevelSpec, opt: CompileOptions = {}) {\n // 0. Augment opt with default opts\n if (opt.logger) {\n // set the singleton logger to the provided logger\n log.set(opt.logger);\n }\n\n if (opt.fieldTitle) {\n // set the singleton field title formatter\n vlFieldDef.setTitleFormatter(opt.fieldTitle);\n }\n\n try {\n // 1. Initialize config by deep merging default config with the config provided via option and the input spec.\n const config = initConfig(mergeConfig(opt.config, inputSpec.config));\n\n // 2. Normalize: Convert input spec -> normalized spec\n\n // - 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.\n // - Normalize autosize and width or height spec\n const spec = normalize(inputSpec, config);\n\n // 3. Build Model: normalized spec -> Model (a tree structure)\n\n // 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.\n // See the abstract `Model` class and its children (UnitModel, LayerModel, FacetModel, ConcatModel) for different types of models.\n const model: Model = buildModel(spec, null, '', undefined, config);\n\n // 4 Parse: Model --> Model with components\n\n // Note that components = intermediate representations that are equivalent to Vega specs.\n // We need these intermediate representation because we need to merge many visualization \"components\" like projections, scales, axes, and legends.\n // We will later convert these components into actual Vega specs in the assemble phase.\n\n // In this phase, we do a bottom-up traversal over the whole tree to\n // parse for each type of components once (e.g., data, layout, mark, scale).\n // By doing bottom-up traversal, we start parsing components of unit specs and\n // then merge child components of parent composite specs.\n //\n // Please see inside model.parse() for order of different components parsed.\n model.parse();\n\n // drawDataflow(model.component.data.sources);\n\n // 5. Optimize the dataflow. This will modify the data component of the model.\n optimizeDataflow(model.component.data, model);\n\n // drawDataflow(model.component.data.sources);\n\n // 6. Assemble: convert model components --> Vega Spec.\n const vgSpec = assembleTopLevelModel(\n model,\n getTopLevelProperties(inputSpec, spec.autosize, config, model),\n inputSpec.datasets,\n inputSpec.usermeta\n );\n\n return {\n spec: vgSpec,\n normalized: spec\n };\n } finally {\n // Reset the singleton logger if a logger is provided\n if (opt.logger) {\n log.reset();\n }\n // Reset the singleton field title formatter if provided\n if (opt.fieldTitle) {\n vlFieldDef.resetTitleFormatter();\n }\n }\n}\n\nfunction getTopLevelProperties(\n inputSpec: TopLevel,\n autosize: AutoSizeType | AutoSizeParams,\n config: Config,\n model: Model\n) {\n const width = model.component.layoutSize.get('width');\n const height = model.component.layoutSize.get('height');\n if (autosize === undefined) {\n autosize = {type: 'pad'};\n if (model.hasAxisOrientSignalRef()) {\n autosize.resize = true;\n }\n } else if (isString(autosize)) {\n autosize = {type: autosize};\n }\n if (width && height && isFitType(autosize.type)) {\n if (width === 'step' && height === 'step') {\n log.warn(log.message.droppingFit());\n autosize.type = 'pad';\n } else if (width === 'step' || height === 'step') {\n // effectively XOR, because else if\n\n // get step dimension\n const sizeType = width === 'step' ? 'width' : 'height';\n // log that we're dropping fit for respective channel\n log.warn(log.message.droppingFit(getPositionScaleChannel(sizeType)));\n\n // setting type to inverse fit (so if we dropped fit-x, type is now fit-y)\n const inverseSizeType = sizeType === 'width' ? 'height' : 'width';\n autosize.type = getFitType(inverseSizeType);\n }\n }\n\n return {\n ...(keys(autosize).length === 1 && autosize.type\n ? autosize.type === 'pad'\n ? {}\n : {autosize: autosize.type}\n : {autosize}),\n ...extractTopLevelProperties(config, false),\n ...extractTopLevelProperties(inputSpec, true)\n };\n}\n\n/*\n * Assemble the top-level model to a Vega spec.\n *\n * Note: this couldn't be `model.assemble()` since the top-level model\n * needs some special treatment to generate top-level properties.\n */\nfunction assembleTopLevelModel(\n model: Model,\n topLevelProperties: TopLevelProperties & LayoutSizeMixins,\n datasets: Datasets = {},\n usermeta: Dict\n): VgSpec {\n // Config with Vega-Lite only config removed.\n const vgConfig = model.config ? stripAndRedirectConfig(model.config) : undefined;\n\n const data = [].concat(\n model.assembleSelectionData([]),\n // only assemble data in the root\n assembleRootData(model.component.data, datasets)\n );\n\n const projections = model.assembleProjections();\n const title = model.assembleTitle();\n const style = model.assembleGroupStyle();\n const encodeEntry = model.assembleGroupEncodeEntry(true);\n\n let layoutSignals = model.assembleLayoutSignals();\n\n // move width and height signals with values to top level\n layoutSignals = layoutSignals.filter(signal => {\n if ((signal.name === 'width' || signal.name === 'height') && signal.value !== undefined) {\n topLevelProperties[signal.name] = +signal.value;\n return false;\n }\n return true;\n });\n\n const {params, ...otherTopLevelProps} = topLevelProperties;\n\n return {\n $schema: 'https://vega.github.io/schema/vega/v5.json',\n ...(model.description ? {description: model.description} : {}),\n ...otherTopLevelProps,\n ...(title ? {title} : {}),\n ...(style ? {style} : {}),\n ...(encodeEntry ? {encode: {update: encodeEntry}} : {}),\n data,\n ...(projections.length > 0 ? {projections} : {}),\n ...model.assembleGroup([\n ...layoutSignals,\n ...model.assembleSelectionTopLevelSignals([]),\n ...assembleParameterSignals(params)\n ]),\n ...(vgConfig ? {config: vgConfig} : {}),\n ...(usermeta ? {usermeta} : {})\n };\n}\n"],"names":["isLogicalOr","op","or","isLogicalAnd","and","isLogicalNot","not","forEachLeaf","fn","subop","normalizeLogicalComposition","normalizer","map","o","duplicate","structuredClone","never","message","Error","pick","obj","props","copy","prop","hasOwnProperty","omit","hash","a","isNumber","str","isString","stringify","length","h","i","charCodeAt","isNullOrFalse","x","contains","array","item","includes","some","arr","f","k","entries","every","mergeDeep","dest","_len","arguments","src","Array","_key","s","deepMerge_","property","keys","writeConfig","unique","values","results","u","v","val","push","setEqual","b","size","e","has","hasIntersection","key","prefixGenerator","prefixes","Set","wrappedWithAccessors","splitAccessPath","y","computedPrefixes","_","slice","join","add","fieldIntersection","undefined","isEmpty","prototype","this","Object","vals","isBoolean","varName","alphanumericS","replace","match","logicalExpr","cb","deleteNestedProperty","orderedProps","shift","titleCase","charAt","toUpperCase","substr","accessPathWithDatum","path","datum","pieces","prefix","stringValue","flatAccessWithDatum","escapePathAccess","string","replacePathInField","replaceAll","find","replacement","RegExp","removePathFromField","accessPathDepth","getFirstDefined","_len2","args","_key2","arg","idCounter","uniqueId","id","String","internalField","name","isInternalField","startsWith","normalizeAngle","angle","isNumeric","value","isNaN","parseFloat","clonedProto","getPrototypeOf","deepEqual","constructor","isArray","Map","get","ArrayBuffer","isView","source","flags","valueOf","toString","ks","call","data","seen","_stringify","node","toJSON","isFinite","JSON","out","TypeError","seenIndex","sort","splice","ROW","COLUMN","FACET","X","Y","X2","Y2","XOFFSET","YOFFSET","RADIUS","RADIUS2","THETA","THETA2","LATITUDE","LONGITUDE","LATITUDE2","LONGITUDE2","COLOR","FILL","STROKE","SHAPE","SIZE","ANGLE","OPACITY","FILLOPACITY","STROKEOPACITY","STROKEWIDTH","STROKEDASH","TEXT","ORDER","DETAIL","KEY","TOOLTIP","HREF","URL","DESCRIPTION","POLAR_POSITION_CHANNEL_INDEX","theta","theta2","radius","radius2","isPolarPositionChannel","c","GEO_POSIITON_CHANNEL_INDEX","longitude","longitude2","latitude","latitude2","getPositionChannelFromLatLong","channel","isGeoPositionChannel","GEOPOSITION_CHANNELS","UNIT_CHANNEL_INDEX","x2","y2","xOffset","yOffset","color","fill","stroke","opacity","fillOpacity","strokeOpacity","strokeWidth","strokeDash","shape","order","text","detail","tooltip","href","url","description","isColorChannel","FACET_CHANNEL_INDEX","row","column","facet","FACET_CHANNELS","CHANNEL_INDEX","CHANNELS","_o","_d","_tt1","SINGLE_DEF_CHANNEL_INDEX","_r","_c","_f","SINGLE_DEF_UNIT_CHANNEL_INDEX","isChannel","SECONDARY_RANGE_CHANNEL","isSecondaryRangeChannel","getMainRangeChannel","getVgPositionChannel","getSecondaryRangeChannel","getSizeChannel","getOffsetChannel","getOffsetScaleChannel","getMainChannelFromOffsetChannel","UNIT_CHANNELS","_x","_y","_x2","_y2","_xo","_yo","_latitude","_longitude","_latitude2","_longitude2","_theta","_theta2","_radius","_radius2","NONPOSITION_CHANNEL_INDEX","NONPOSITION_CHANNELS","POSITION_SCALE_CHANNEL_INDEX","POSITION_SCALE_CHANNELS","isXorY","POLAR_POSITION_SCALE_CHANNEL_INDEX","POLAR_POSITION_SCALE_CHANNELS","getPositionScaleChannel","sizeType","OFFSET_SCALE_CHANNEL_INDEX","isXorYOffset","_t","_tt","_hr","_u","_al","_dd","_k","_oo","NONPOSITION_SCALE_CHANNEL_INDEX","NONPOSITION_SCALE_CHANNELS","SCALE_CHANNEL_INDEX","SCALE_CHANNELS","isScaleChannel","supportMark","mark","ALL_MARKS","ALL_MARKS_EXCEPT_GEOSHAPE","area","bar","image","rect","rule","circle","point","square","tick","line","trail","geoshape","arc","getSupportedMark","_g","rangeType","AGGREGATE_OP_INDEX","argmax","argmin","average","count","distinct","exponential","exponentialb","product","max","mean","median","min","missing","q1","q3","ci0","ci1","stderr","stdev","stdevp","sum","valid","variance","variancep","MULTIDOMAIN_SORT_OP_INDEX","isArgminDef","isArgmaxDef","isAggregateOp","COUNTING_OPS","isCountingAggregateOp","aggregate","SUM_OPS","SHARED_DOMAIN_OPS","binToString","bin","normalizeBin","p","isParameterExtent","isBinning","isBinParams","binned","isBinned","isObject","extent","autoMaxBins","isExprRef","expr","replaceExprRef","index","level","newIndex","signalRefOrValue","extractTitleConfig","titleConfig","anchor","frame","offset","orient","limit","subtitleColor","subtitleFont","subtitleFontSize","subtitleFontStyle","subtitleFontWeight","subtitleLineHeight","subtitlePadding","rest","nonMarkTitleProperties","subtitle","titleMarkConfig","subtitleMarkConfig","isText","isSignalRef","signal","isVgRangeStep","range","isDataRefDomain","domain","VG_MARK_CONFIGS","aria","ariaRole","ariaRoleDescription","blend","strokeCap","strokeDashOffset","strokeJoin","strokeOffset","strokeMiterLimit","startAngle","endAngle","padAngle","innerRadius","outerRadius","interpolate","tension","align","baseline","dir","dx","dy","ellipsis","font","fontSize","fontWeight","fontStyle","lineBreak","lineHeight","cursor","cornerRadius","cornerRadiusTopLeft","cornerRadiusTopRight","cornerRadiusBottomLeft","cornerRadiusBottomRight","aspect","width","height","smooth","VG_MARK_INDEX","group","symbol","VG_CORNERRADIUS_CHANNELS","signalOrValueRefWithCondition","condition","conditionalSignalRefOrValue","signalOrValueRef","exprFromSignalRefOrValue","ref","exprFromValueRefOrSignalRef","signalOrStringValue","applyMarkConfig","model","propsList","getMarkConfig","markDef","config","getStyles","concat","type","style","getMarkPropOrConfig","opt","vgChannel","ignoreVgConfig","getMarkStyleConfig","styleConfigIndex","getStyleConfig","styles","styleConfig","sortParams","orderDef","fieldRefOption","reduce","orderChannelDef","field","vgField","mergeTitleFieldDefs","f1","f2","merged","forEach","fdToMerge","fieldDef1","mergeTitle","title1","title2","mergeTitleComponent","v1","v2","v1Val","v2Val","explicit","invalidSpec","spec","FIT_NON_SINGLE","containerSizeNonSingle","containerSizeNotCompatibleWithAutosize","droppingFit","unknownField","cannotProjectOnChannelWithoutField","cannotProjectAggregate","selectionNotSupported","NEEDS_SAME_SELECTION","columnsNotSupportByRowCol","differentParse","local","ancestor","customFormatTypeNotAllowed","offsetNestedInsideContinuousPositionScaleDropped","mainChannel","invalidFieldType","droppingColor","emptyFieldDef","fieldDef","incompatibleChannel","markOrFacet","when","channelShouldBeDiscrete","channelShouldBeDiscreteOrDiscretizing","discreteChannelCannotEncode","unaggregateDomainHasNoEffectForRawField","unaggregateDomainWithNonSharedDomainOp","unaggregatedDomainWithLogScale","scalePropertyNotWorkWithScaleType","scaleType","propName","stepDropped","MORE_THAN_ONE_SORT","invalidTimeUnit","unitName","errorBand1DNotSupport","channelRequiredForBinned","main","logger","Warn","current","warn","isDateTime","part","TIMEUNIT_PARTS","MONTHS","SHORT_MONTHS","m","DAYS","SHORT_DAYS","d","dateTimeParts","normalize","parts","day","log","year","month","lowerM","toLowerCase","monthIndex","indexOf","shortM","shortMonthIndex","normalizeMonth","quarter","q","normalizeQuarter","date","lowerD","dayIndex","shortD","shortDayIndex","normalizeDay","timeUnit","unit","dateTimeToExpr","utc","LOCAL_SINGLE_TIMEUNIT_INDEX","week","dayofyear","hours","minutes","seconds","milliseconds","isBinnedTimeUnit","isBinnedTimeUnitString","isUTCTimeUnit","t","VEGALITE_TIMEFORMAT","getTimeUnitParts","filter","containsTimeUnit","getSmallestTimeUnitPart","fullTimeUnit","fieldExpr","end","fieldRef","lastTimeUnit","dateExpr","dateTimeExprToExpr","timeUnitSpecifierExpression","normalizeTimeUnit","params","substring","durationExpr","wrap","normalizedTimeUnit","smallestUnitPart","startDate","step","getDateTimePartAndStep","DATE_PARTS","isDatePart","isFieldEqualPredicate","predicate","equal","isFieldLTPredicate","lt","isFieldLTEPredicate","lte","isFieldGTPredicate","gt","isFieldGTEPredicate","gte","isFieldRangePredicate","isFieldOneOfPredicate","oneOf","in","isFieldPredicate","predicateValueExpr","valueExpr","wrapTime","fieldFilterExpression","useInRange","rawFieldExpr","timeUnitFieldExpr","predicateValuesExpr","isFieldValidPredicate","fieldValidPredicate","lower","upper","exprs","normalizePredicate","isContinuous","isDiscrete","QUANTITATIVE","ORDINAL","TEMPORAL","NOMINAL","GEOJSON","ScaleType","LINEAR","LOG","POW","SQRT","SYMLOG","IDENTITY","SEQUENTIAL","TIME","UTC","QUANTILE","QUANTIZE","THRESHOLD","BIN_ORDINAL","POINT","BAND","SCALE_CATEGORY_INDEX","linear","pow","sqrt","symlog","identity","sequential","time","ordinal","band","quantile","quantize","threshold","scaleCompatible","scaleType1","scaleType2","scaleCategory1","scaleCategory2","SCALE_PRECEDENCE_INDEX","scaleTypePrecedence","QUANTITATIVE_SCALES","CONTINUOUS_TO_CONTINUOUS_SCALES","isQuantitative","CONTINUOUS_TO_DISCRETE_SCALES","CONTINUOUS_DOMAIN_SCALES","DISCRETE_DOMAIN_SCALES","hasDiscreteDomain","hasContinuousDomain","isContinuousToContinuous","isContinuousToDiscrete","isParameterDomain","rangeMax","rangeMin","scheme","NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX","domainMax","domainMin","domainMid","domainRaw","bins","reverse","round","clamp","nice","base","exponent","constant","zero","padding","paddingInner","paddingOuter","NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES","scaleTypeSupportProperty","channelScalePropertyIncompatability","Mark","ARC","AREA","BAR","IMAGE","LINE","RECT","RULE","TICK","TRAIL","CIRCLE","SQUARE","GEOSHAPE","isPathMark","isRectBasedMark","PRIMITIVE_MARKS","isMarkDef","FILL_STROKE_CONFIG","VL_ONLY_MARK_CONFIG_PROPERTIES","filled","invalid","timeUnitBandSize","timeUnitBandPosition","MARK_CONFIGS","isRelativeBandSize","BAR_CORNER_RADIUS_INDEX","horizontal","vertical","defaultBarConfig","binSpacing","continuousBandSize","minBandSize","defaultRectConfig","normalizeInvalidDataMode","mode","_ref","isPath","getScaleInvalidDataMode","scaleChannel","isCountAggregate","invalidMode","scaleOutputForInvalid","scale","scaledZeroOrMinOrMax","scaleName","domainHasZero","getConditionalValueRefForIncludingInvalidValue","channelDef","getFieldDef","invalidDataMode","includeAs","test","refForInvalidValues","midPointRefWithPositionInvalidTest","mainRef","midPoint","valueRefForIncludingInvalid","valueRefForFieldOrDatumDef","encode","isDatumDef","interpolatedSignalRef","fieldOrDatumDef","fieldOrDatumDef2","startSuffix","endSuffix","bandPosition","start","suffix","_ref3","channel2Def","stack","defaultRef","isFieldOrDatumDef","isTypedFieldDef","getBandPosition","fieldDef2","impute","binSuffix","binRequiresRange","isFieldDef","isValueDef","offsetMixins","widthHeightValueOrSignalRef","isFunction","isCustomFormatType","formatType","customFormatExpr","format","BIN_RANGE_DELIMITER","formatSignalRef","normalizeStack","formatCustomType","fieldToFormat","channelDefType","customFormatTypes","normalizedNumberFormatType","normalizedNumberFormat","numberFormatType","numberFormat","timeFormatType","timeFormat","isFieldOrDatumDefForTimeFormat","_ref5","rawTimeFormat","isUTCScale","formatExpression","timeFormatExpression","isScaleFieldDef","specifiedFormat","binFormatExpression","formatExpr","datumDef","datumDefToExpr","_ref2","guideFormat","omitTimeFormatConfig","isPositionFieldOrDatumDef","_ref4","guideFormatType","binNumberFormatExpr","startField","endField","DEFAULT_SORT_OP","SORT_BY_CHANNEL_INDEX","isSortByChannel","isSortField","isSortArray","isFacetMapping","isFacetFieldDef","isFacetSpec","toFieldDefBase","isSortableFieldDef","getBandSize","useVlSizeChannel","sizeChannel","discreteBandSize","hasBandEnd","isOrderOnlyDef","isConditionalDef","hasConditionalFieldDef","hasConditionalFieldOrDatumDef","isContinuousFieldOrDatumDef","cd","isNumericDataDef","isUnbinnedQuantitativeFieldOrDatumDef","isMarkPropFieldOrDatumDef","isStringFieldOrDatumDef","toStringFieldDef","argAccessor","isCount","nofn","isOpFieldDef","tu","timeUnitToString","forAs","def","defaultTitleFormatter","fieldTitle","timeUnitParams","maxbins","functionalTitleFormatter","countTitle","verbalTitleFormatter","titleFormatter","setTitleFormatter","formatter","title","allowDisabling","includeDefault","guideTitle","getGuide","defaultTitle","axis","legend","header","getFormatMixins","guide","getFieldOrDatumDef","initChannelDef","initFieldOrDatumDef","fd","guideType","newGuide","initFieldDef","initDatumDef","compositeMark","fullType","getFullName","newType","defaultType","compatible","warning","COMPATIBLE","channelCompatibility","encoding","sub","labelOrient","titleOrient","undefinedIfExprNotRequired","isTime","isLocalSingleTimeUnit","Date","parse","valueArray","console","CONDITIONAL_AXIS_PROP_INDEX","labelAlign","vgProp","labelBaseline","labelColor","labelFont","labelFontSize","labelFontStyle","labelFontWeight","labelOpacity","labelOffset","labelPadding","gridColor","gridDash","gridDashOffset","gridOpacity","gridWidth","tickColor","tickDash","tickDashOffset","tickOpacity","tickSize","tickWidth","isConditionalAxisValue","AXIS_PARTS","AXIS_PROPERTY_TYPE","grid","gridCap","gridScale","domainCap","domainColor","domainDash","domainDashOffset","domainOpacity","domainWidth","labelAngle","labelBound","labelFlush","labelFlushOffset","labelLimit","labelLineHeight","labelOverlap","labels","labelSeparation","maxExtent","minExtent","position","tickCap","tickMinStep","tickOffset","tickRound","ticks","titleAlign","titleAnchor","titleAngle","titleBaseline","titleColor","titleFont","titleFontSize","titleFontStyle","titleFontWeight","titleLimit","titleLineHeight","titleOpacity","titlePadding","titleX","titleY","tickBand","tickCount","tickExtra","translate","zindex","COMMON_AXIS_PROPERTIES_INDEX","AXIS_PROPERTIES_INDEX","labelExpr","isAxisProperty","AXIS_CONFIGS","axisBand","axisBottom","axisDiscrete","axisLeft","axisPoint","axisQuantitative","axisRight","axisTemporal","axisTop","axisX","axisXBand","axisXDiscrete","axisXPoint","axisXQuantitative","axisXTemporal","axisY","axisYBand","axisYDiscrete","axisYPoint","axisYQuantitative","axisYTemporal","isUnitSpec","CompositeMarkNormalizer","run","hasMatchingType","channelHasField","channelHasFieldOrDatum","channelHasNestedOffsetScale","isAggregate","extractTransformsFromEncoding","oldEncoding","groupby","timeUnits","aggOp","remaining","isTitleDefined","newField","newFieldDef","aggregateEntry","as","secondaryChannel","isNonPositionScaleChannel","markChannelCompatible","markSupported","primaryFieldDef","normalizeEncoding","normalizedEncoding","newChannelDef","mapping","thisArg","el","pathGroupingFields","details","getCompositeMarkTooltip","tooltipSummary","continuousAxisChannelDef","encodingWithoutContinuousAxis","withFieldName","fieldPrefix","titlePrefix","mainTitle","getTitle","escape","channelDefArray","fieldDefs","makeCompositeAggregatePartFactory","compositeMarkDef","continuousAxis","sharedEncoding","compositeMarkConfig","partName","positionPrefix","endPositionPrefix","extraEncoding","partLayerMixins","partBaseSpec","clip","compositeMarkContinuousAxis","continuousAxisChannelDef2","continuousAxisChannelDefError","continuousAxisChannelDefError2","filterAggregateFromChannelDef","continuousAxisWithoutAggregate","compositeMarkOrient","xAggregate","yAggregate","BOXPLOT","boxPlotNormalizer","normalizeBoxPlot","getBoxPlotType","_encoding","projection","_p","outerSpec","boxplot","sizeValue","boxPlotType","transform","ticksOrient","boxOrient","customTooltipWithoutAggregatedField","continuousFieldName","aliasedFieldName","boxplotSpecificAggregate","boxParamsQuartiles","postAggregateCalculates","calculate","oldContinuousAxisChannelDef","oldEncodingWithoutContinuousAxis","filteredEncoding","customTooltipWithAggregatedField","filterTooltipWithAggregatedField","boxParams","encodingWithoutSizeColorAndContinuousAxis","makeBoxPlotPart","makeBoxPlotExtent","makeBoxPlotBox","defaultBoxColor","box","makeBoxPlotMidTick","fiveSummaryTooltipEncoding","endTick","whiskerTooltipEncoding","whiskerLayers","boxLayers","layer","lowerBoxExpr","upperBoxExpr","iqrExpr","lowerWhiskerExpr","upperWhiskerExpr","joinaggregateTransform","joinaggregate","filteredWhiskerSpec","encodingWithoutSizeColorContinuousAxisAndTooltip","axisWithoutTitle","outlierLayersMixins","filteredLayersMixins","filteredLayersMixinsTransforms","unshift","continousAxisField","ERRORBAR","errorBarNormalizer","normalizeErrorBar","tooltipEncoding","errorBarParams","makeErrorBarPart","errorbar","thickness","errorBarOrientAndInputType","xError","xError2","yError","yError2","errorBarIsInputTypeRaw","inputType","isTypeAggregatedUpperLower","errorBarIsInputTypeAggregatedUpperLower","isTypeAggregatedError","errorBarIsInputTypeAggregatedError","errorBarSpecificAggregate","tooltipTitleWithFieldName","center","getTitlePrefix","centerOp","lowerExtentOp","upperExtentOp","postAggregateCalculate","errorBarAggregationAndCalculation","oldContinuousAxisChannelDef2","oldContinuousAxisChannelDefError","oldContinuousAxisChannelDefError2","oldAggregate","oldGroupBy","operation","ERRORBAND","errorBandNormalizer","normalizeErrorBand","errorBandDef","makeErrorBandPart","errorband","is2D","bandMark","bordersMark","compositeMarkRegistry","VL_ONLY_LEGEND_CONFIG","HEADER_TITLE_PROPERTIES_MAP","HEADER_LABEL_PROPERTIES_MAP","labelAnchor","HEADER_TITLE_PROPERTIES","HEADER_LABEL_PROPERTIES","HEADER_CONFIGS","headerRow","headerColumn","headerFacet","LEGEND_SCALE_CHANNELS","SELECTION_ID","defaultConfig","on","fields","toggle","resolve","clear","interval","encodings","zoom","isLegendBinding","bind","isLegendStreamBinding","isSelectionParameter","param","assembleParameterSignals","signals","init","update","isConcatSpec","isVConcatSpec","isHConcatSpec","getStepFor","offsetIsDiscrete","for","isStep","isFrameMixins","COMPOSITION_LAYOUT_PROPERTIES","bounds","columns","spacing","getViewConfigContinuousSize","viewConfig","getViewConfigDiscreteStep","getViewConfigDiscreteSize","DEFAULT_STEP","background","view","continuousWidth","continuousHeight","outliers","borders","pointPadding","barBandPaddingInner","rectBandPaddingInner","tickBandPaddingInner","bandWithNestedOffsetPaddingInner","bandWithNestedOffsetPaddingOuter","minFontSize","maxFontSize","minOpacity","maxOpacity","minSize","minStrokeWidth","maxStrokeWidth","quantileCount","quantizeCount","gradientHorizontalMaxLength","gradientHorizontalMinLength","gradientVerticalMaxLength","gradientVerticalMinLength","unselectedOpacity","selection","defaultSelectionConfig","tab10","DEFAULT_FONT_SIZE","guideLabel","groupTitle","groupSubtitle","DEFAULT_COLOR","blue","orange","red","teal","green","yellow","purple","pink","brown","gray0","gray1","gray2","gray3","gray4","gray5","gray6","gray7","gray8","gray9","gray10","gray11","gray12","gray13","gray14","gray15","getAxisConfigInternal","axisConfig","axisConfigInternal","configPropsWithExpr","initConfig","specifiedConfig","restConfig","mergedConfig","mergeConfig","fontConfig","cell","category","colorSignalConfig","fontSizeSignalConfig","outputConfig","markConfigType","axisConfigType","headerConfigType","otherScaleConfig","newScaleInvalid","styleConfigInternal","getStyleConfigInternal","MARK_STYLES","VL_ONLY_CONFIG_PROPERTIES","VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX","stripAndRedirectConfig","markType","vlOnlyMarkSpecificConfigs","redirectConfigToStyleConfig","redirectTitleConfig","toProp","compositeMarkPart","isLayerSpec","SpecMapper","mapFacet","isRepeatSpec","mapRepeat","mapHConcat","mapVConcat","mapConcat","mapLayerOrUnit","mapLayer","mapUnit","subspec","hconcat","vconcat","STACK_OFFSET_INDEX","STACKABLE_MARKS","STACK_BY_DEFAULT_MARKS","isUnbinnedQuantitative","potentialStackedChannel","isCartesianBarOrArea","xDef","yDef","fieldChannel","stackedFieldDef","stackedField","dimensionChannel","getDimensionChannel","groupbyChannels","groupbyFields","dimensionDef","dimensionField","dimensionOffsetChannel","dimensionOffsetDef","dimensionOffsetField","stackBy","sc","cDef","initMarkdef","originalMarkDef","specifiedOrient","xIsMeasure","yIsMeasure","xIsTemporal","yIsTemporal","cornerRadiusEnd","newProps","BAR_CORNER_RADIUS_END_INDEX","newProp","specifiedOpacity","specifiedfillOpacity","dropLineAndPoint","_point","_line","dropLineAndPointFromConfig","getPointOverlay","markConfig","getLineOverlay","PathOverlayNormalizer","normParams","pointOverlay","lineOverlay","stackProps","overlayEncoding","stackFieldChannel","replaceRepeaterInFacet","repeater","replaceRepeaterInMapping","replaceRepeaterInFieldDef","replaceRepeaterInEncoding","replaceRepeatInProp","repeat","replaceRepeaterInFieldOrDatumDef","replaceRepeaterInChannelDef","channelDefWithoutCondition","RuleForRangedLineNormalizer","mainChannelDef","hasX2","hasY2","mergeEncoding","parentEncoding","channels","parentChannelDef","mergedChannelDef","mergeProjection","parentProjection","isFilter","isLookup","isPivot","isDensity","isQuantile","isRegression","isLoess","isSample","isWindow","isJoinAggregate","isFlatten","isCalculate","isBin","isImpute","isTimeUnit","isStack","isFold","isExtent","normalizeTransforms","tx","normalizeBinExtent","from","normalizeChannelDef","enc","cond","ext","normalizeSelectionComposition","pred","empty","emptySelections","selectionPredicates","TopLevelSelectionsNormalizer","selections","super","views","method","proto","addSpecNameToParams","normalizedSpec","topLevelSelectionNormalizer","coreNormalizer","selectionCompatNormalizer","normalizeGenericSpec","autosize","sizeInfo","isFitCompatible","autosizeDefault","_normalizeAutoSize","normalizeAutoSize","nonFacetUnitNormalizers","hasRow","hasColumn","hasFacet","mapFacetedUnit","specWithReplacedEncoding","repeaterPrefix","n","mapUnitWithParentEncodingOrProjection","normalizeLayerOrUnit","unitNormalizer","isLayerRepeatSpec","mapLayerRepeat","mapNonLayerRepeat","childSpec","layerValue","childRepeater","childName","child","remainingProperties","repeatValues","repeatValue","rowValue","columnValue","mergedProjection","mergedEncoding","facetMapping","layout","getFacetMappingAndLayout","newEncoding","facets","defWithoutLayout","otherParams","selDef","select","TOP_LEVEL_PROPERTIES","extractTopLevelProperties","includeParams","Split","implicit","clone","combine","getWithExplicit","setWithExplicit","set","copyKeyFromSplit","copyKeyFromObject","copyAll","other","makeExplicit","makeImplicit","tieBreakByComparing","compare","propertyOf","diff","defaultTieBreaker","mergeValuesWithExplicit","tieBreaker","AncestorParse","parseNothing","isUrlData","isInlineData","isNamedData","isGenerator","isSequenceGenerator","isSphereGenerator","isGraticuleGenerator","DataSourceType","getDataSourcesForHandlingInvalidValues","marks","scales","assembleProjection","proj","hasLegend","assembleInit","isExpr","assembled","dateTimeToTimestamp","assembleUnitSelectionSignals","selCmpt","component","modifyExpr","TUPLE","selectionCompilers","defined","MODIFY","events","STORE","cleanupEmptyOnArray","assembleFacetSignals","getName","parseSelector","assembleUnitSelectionMarks","DataFlowNode","_children","_parent","parent","debugName","addChild","children","numChildren","loc","removeChild","oldChild","remove","insertAsParentOf","swapWithParent","newParent","OutputNode","cloneObj","_source","_name","refCounts","dependentFields","producedFields","_hash","getSource","isRequired","setSource","isTimeUnitTransformComponent","timeUnitComponent","offsetAs","TimeUnitNode","makeFromEncoding","formula","reduceFieldDef","isUnitModel","rectBandPosition","makeFromTransform","merge","removeFormulas","newFormula","fieldAs","assemble","transforms","startEnd","units","timezone","offsetedRectFormulas","escapedField","offsetExpr","endAs","OFFSETTED_RECT_START_SUFFIX","OFFSETTED_RECT_END_SUFFIX","smallestUnit","startExpr","endExpr","interpolateExpr","fraction","TUPLE_FIELDS","SelectionProjectionComponent","items","hasChannel","hasField","hasSelectionId","project","parsed","signalName","sg","counter","cfg","initVal","getScaleComponent","geoChannel","allSignals","scaleBindings","bound","topLevelSignals","isTopLevelLayer","namedSg","VL_SELECTION_RESOLVE","isLayerModel","BRUSH","SCALE_TRIGGER","GEO_INIT_TICK","INIT","hasProjection","filterExpr","evt","between","filters","tupleSg","scaledInterval","vname","visual","projectionName","scaled","getSizeSignalRef","coord","von","dname","hasScales","vinit","initIdx","initSg","channelSignals","centerSg","xvname","yvname","xinit","yinit","sizeSg","bbox","visualSignals","triggerSg","scaleTriggers","toNum","dataSignals","store","vgStroke","vgCursor","enter","fieldsSg","brushes","acc","cmpt","force","wrapCondition","invalidValueRef","mainRefFn","valueRefs","conditionValueRef","isConditionalParameter","parseSelectionPredicate","expression","mainValueRef","Boolean","textRef","tooltipRefForEncoding","reactiveGeom","tooltipRefFromChannelDef","markTooltip","content","tooltipData","formatConfig","tooltipFormat","toSkip","tuples","fDef","channel2","keyValues","enableAria","ariaRoleDesc","descriptionValue","nonPosition","defaultValue","commonProps","transparentIfNeeded","defaultFill","defaultStroke","colorVgChannel","fillStrokeMarkDefAndConfig","positionOffset","baseChannel","offsetType","markDefOffsetValue","pointPosition","defaultPos","pointPositionDefaultRef","valueRef","positionRef","definedValueOrConfig","zeroOrMinOrMaxPosition","zeroOrMax","widthSignal","heightSignal","mult","otherProps","scaledValueRef","ALIGNED_X_CHANNEL","left","right","BASELINED_Y_CHANNEL","top","middle","bottom","vgAlignedPositionChannel","defaultAlign","alignChannel","alignExcludingSignal","pointOrRangePosition","defaultPos2","rangePosition","pos2Mixins","vgSizeChannel","position2Ref","position2orSize","pointPosition2OrSize","dimensionSize","rectPosition","channelDef2","hasSizeDef","offsetScaleChannel","isBarBand","offsetScaleName","offsetScale","sizeMixins","hasSizeFromMarkOrEncoding","bandSize","defaultSizeRef","defaultBandAlign","posRef","vgChannel2","sizeRef","sizeOffset","positionAndSize","axes","axisTranslate","offset2","bandSizeExpr","binSpacingOffset","getBinSpacing","binSpacingOffset2","bandPositionForBandSize","useRectOffsetField","rectBinRef","startRef","rectBinPosition","hasFieldDef","bandWidth","scaleRange","bandPaddingInner","isEnd","spacingOffset","reverseExpr","axisTranslateExpr","minBandSizeExpr","spacingAndSizeOffset","ALWAYS_IGNORE","baseEncodeEntry","ignore","markDefProperties","colorRef","fieldsToBreakPath","forEachFieldDef","getScaleType","valueIfDefined","VORONOI","nearest","markname","cellDef","interactive","isVoronoi","exists","inputBindings","disableDirectManipulation","sgname","TOGGLE","tpl","idx","findIndex","addClear","vIdx","tIdx","legendBindings","projLen","selDef_","legendFilter","stream","selName","markName","ds","sgName","tuple","ANCHOR","DELTA","boundScales","scalesCompiler","INTERVAL_BRUSH","onDelta","delta","scaleCmpt","reversed","sx","sy","inputs","legends","facetModel","isFacetModel","getFacetModel","requiresSelectionId","identifier","object","startsWithDatum","getDependentFields","ast","parseExpression","dependents","visit","FilterNode","_dependentFields","dfnode","getSelectionComponent","raw","tunode","parseSelectionExtent","filterOp","isSelectionPredicate","setAxisEncode","vgRef","assembleAxis","axisCmpt","kind","disable","propType","propValue","valueOrSignalRef","conditions","propIndex","valueOrSignalCRef","signalRef","mainExtracted","hasAxisPart","titleString","assembleTitle","assembleAxisSignals","getAxisConfigFromConfigTypes","configTypes","assign","apply","configType","orient1","orientConfig1","orientConfig2","conditionalOrientAxisConfig","getAxisConfigStyle","axisConfigTypes","toMerge","getAxisConfig","axisConfigs","configFrom","configValue","axisRules","defaultGrid","gridChannel","_ref6","defaultLabelAlign","_ref7","_ref8","defaultLabelBaseline","_ref9","defaultLabelFlush","_ref10","hasTimeUnit","defaultLabelOverlap","_ref11","_ref12","_ref16","defaultTickCount","_ref17","_ref13","fieldDefTitle","getFieldDefTitle","typedFieldDef","_ref14","_ref15","defaultZindex","normalizeAngleExpr","alwaysIncludeMiddle","isX","mainOrient","CalculateNode","parseAllForSortIndex","sortValue","sortArrayIndexField","getHeaderChannel","getHeaderProperty","headerSpecificConfig","getHeaderProperties","properties","HEADER_CHANNELS","HEADER_TYPES","assembleTitleGroup","layoutHeaders","facetFieldDef","ta","headerChannel","role","defaultHeaderGuideBaseline","defaultHeaderGuideAlign","assembleHeaderProperties","assembleHeaderGroups","layoutHeader","groups","headerType","headerComponent","assembleHeaderGroup","getSort","assembleLabelTitle","titleTextExpr","isFacetWithoutRowCol","hasAxes","sizeSignal","LAYOUT_TITLE_BAND","getLayoutTitleBand","propertiesMap","assembleLayoutSignals","sizeSignals","layoutSize","scaleComponent","stepSignal","sizeExpr","isWidth","endsWith","safeExpr","cardinality","getSizeTypeFromLayoutSizeType","layoutSizeType","guideEncodeEntry","defaultScaleResolve","isConcatModel","parseGuideResolve","channelScaleResolve","LEGEND_COMPONENT_PROPERTIES","clipHeight","columnPadding","direction","fillColor","gradientLength","gradientOpacity","gradientStrokeColor","gradientStrokeWidth","gradientThickness","gridAlign","legendX","legendY","rowPadding","strokeColor","symbolDash","symbolDashOffset","symbolFillColor","symbolLimit","symbolOffset","symbolOpacity","symbolSize","symbolStrokeColor","symbolStrokeWidth","symbolType","LegendComponent","legendEncodeRules","symbols","symbolsSpec","legendCmpt","legendType","mixins","getMaxValue","symbolBaseFillColor","getFirstConditionValue","selectedCondition","gradient","gradientSpec","specifiedlabelsSpec","labelsSpec","entriesSpec","getConditionValue","conditionalDef","Math","reducer","hasConditionalValueDef","legendRules","legendConfig","gradientLengthSignal","defaultGradientLength","shapeChannelDef","markShape","defaultSymbolType","getLegendType","getDirection","defaultDirection","parseLegend","legendComponent","parseLegendForChannel","parseUnitLegend","mergeLegendComponent","parseNonUnitLegend","isExplicit","getLegendDefWithScale","legendSelections","parseInteractiveLegend","ruleParams","legendEncoding","legendEncode","legendEncodeParams","legendEncodingPart","mergedLegend","childLegend","mergedOrient","childOrient","typeMerged","mergedValueWithExplicit","mergeSymbolType","st1","st2","assembleLegends","legendComponentIndex","legendByDomain","domainHash","mergedLegendComponent","flat","l","setLegendEncode","assembleLegend","assembleProjections","projections","assembleProjectionForModel","assembleProjectionsForModelAndChildren","fits","sources","lookupDataSource","fit","PROJECTION_PROPERTIES","ProjectionComponent","specifiedProjection","isFit","parseProjection","posssiblePair","requestDataName","Main","gatherFitData","projComp","parseUnitProjection","nonUnitProjection","mergable","first","second","allPropertiesShared","mergeIfNoConflict","modelProjection","renameProjection","parseNonUnitProjections","rangeFormula","formulaAs","binKey","getBinSignalName","createBinComponent","span","isBinTransform","normalizedBin","extentSignal","getSignalsFromModel","binComponent","BinNode","binComponentIndex","renameSignal","flatMap","binAs","remainingAs","binTrans","addDimension","dims","posChannel","isFieldRange","AggregateNode","dimensions","measures","groupBy","meas","argField","scaleDomain","parentMeasures","childMeasures","ops","mergeMeasures","debug","addDimensions","alias","FacetNode","sortField","sortIndexField","childModel","depFields","getChildIndependentFieldsWithStep","childIndependentFieldsWithStep","childScaleComponent","getFieldFromDomain","assembleDomain","assembleRowColumnHeaderData","crossedDataName","childChannel","assembleFacetHeaderData","hasSharedAxis","headers","stop","facetData","unquote","pattern","getImplicitFromFilterTransform","getImplicitFromEncoding","mainFieldDef","dimensionChannelDef","ParseNode","_parse","ancestorParse","makeWithAncestors","parsedAs","assembleFormatParse","formatParse","assembleTransforms","onlyNested","IdentifierNode","GraticuleNode","SequenceNode","SourceNode","_data","defaultExtension","exec","_generator","hasName","dataName","isDataSourceNode","Optimizer","modified","setModified","modifiedFlag","BottomUpOptimizer","getNodeDepths","depth","depths","optimize","topologicalSort","TopDownOptimizer","MergeIdenticalNodes","mergeNodes","nodes","mergedNode","hashes","buckets","RemoveUnnecessaryIdentifierNodes","RemoveDuplicateTimeUnits","timeUnitFields","RemoveUnnecessaryOutputNodes","MoveParseUp","MergeParse","originalChildren","parseChildren","commonParse","conflictingParse","parseNode","mergedParseNode","childNode","RemoveUnusedSubtrees","MergeTimeUnits","timeUnitChildren","combination","pop","MergeAggregates","aggChildren","groupedAggregates","agg","groupBys","mergeableAggs","mergedAggs","MergeBins","moveBinsUp","promotableBins","remainingBins","promotedBin","remainingBin","MergeOutputs","otherChildren","mainOutput","lastOutput","theChild","JoinAggregateTransformNode","w","getDefaultName","joinAggregateFieldDef","FilterInvalidNode","make","dataSourcesForHandlingInvalidValues","aggregator","vegaFilters","isValidFiniteNumberExpr","StackNode","_stack","stackTransform","sortFields","sortOrder","normalizedAs","isValidAsArray","dimensionFieldDefs","stackField","facetby","stackProperties","groupbyChannel","stackby","by","_field","getStackByFields","getGroupbyFields","dimensionFieldDef","binStart","binEnd","WindowTransformNode","window","windowFieldDef","ignorePeers","moveFacetDown","facetMain","moveMainDownToFacet","cloner","newName","FACET_SCALE_PREFIX","outputNodes","MAX_OPTIMIZATION_RUNS","checkLinks","runOptimizer","optimizer","optimizationDataflowHelper","dataComponent","firstPass","roots","optimizers","r","SignalRefWrapper","exprGenerator","defineProperty","enumerable","fromName","rename","parseScaleDomain","localScaleComponents","util","domains","parseDomainForChannel","parseSelectionDomain","isFaceted","facetParent","parseUnitScaleDomain","selectionExtent","childComponent","domainsTieBreaker","se","parseNonUnitScaleDomain","scaleConfig","reason","canUseUnaggregatedDomain","useUnaggregatedDomain","normalizeUnaggregatedDomain","specifiedScales","parseSingleChannelDomain","convertDomainIfItIsDateTime","mapDomainToDataSignal","dataSourceTypeForScaleDomain","PreFilterInvalid","PostFilterInvalid","getScaleDataSourceForHandlingInvalidValues","isDomainUnionWith","defaultDomain","unionWith","stackDimensions","normalizeSortField","isSortByEncoding","fieldDefToSortBy","isStackedMeasure","domainSort","Raw","binSignal","getSignalName","isRectWithOffset","mergeDomains","uniqueDomains","_s","domainWithoutSort","sorts","filteredSorts","unionDomainSorts","UNIONDOMAIN_SORT_OP_INDEX","allData","isDataRefUnionedDomain","nonUnionDomain","isFieldRefUnionDomain","assembleScales","assembleScalesForModel","otherScaleProps","assembleScaleRange","parsedExtent","assembleSelectionScaleDomain","ScaleComponent","typeWithExplicit","scaleZero","hasExplicitDomainWithZero","hasExplicitDomainWithoutZero","hasDomainBasedOnField","last","RANGE_PROPERTIES","getBinStepSignal","binCount","updatedName","parseRangeForChannel","specifiedScale","supportedByScaleType","channelIncompatability","parseScheme","getPositionStep","positionChannel","getOffsetStep","mergedScaleCmpt","positionSize","getDiscretePositionSize","fullWidthOrHeightRange","offsetScaleType","positionScaleCmpt","positionScaleType","positionScaleName","positionDef","duration","bandPositionOffset","bandPositionOffsetExpr","getOffsetRange","sizeRangeMin","xyStepSignals","maxBandSize","minXYStep","maxSize","pointStep","MAX_SIZE_RANGE_STEP_RATIO","sizeRangeMax","rMax","rMin","interpolateRange","defaultContinuousToDiscreteCount","PI","defaultRange","isExtendedScheme","offsetChannel","offsetDef","offsetScaleCmpt","stepCount","widthStep","heightStep","parseScaleProperty","localScaleCmpt","specifiedValue","scalePadding","scalePaddingInner","scaleRules","hasNestedOffsetScale","hasSecondaryRangeChannel","parseUnitScaleProperty","parseNonUnitScaleProperty","specifiedDomain","barConfig","continuousPadding","paddingValue","offsetBandPaddingInner","paddingInnerValue","bandPaddingOuter","offsetBandPaddingOuter","xReverse","parseScaleRange","rangeWithExplicit","parseUnitScaleRange","valueWithExplicit","defaultScaleType","CHANNEL","channelSupportScaleType","specifiedType","fieldDefType","parseScaleCore","scaleComponents","sType","parseUnitScaleCore","scaleTypeWithExplicitIndex","explicitScaleType","childScaleType","scaleTypeTieBreaker","childScale","renameScale","parseNonUnitScaleCore","NameMap","nameMap","oldName","Model","parentGivenName","scaleNameMap","projectionNameMap","signalNameMap","specType","compositionConfig","spacingConfig","extractCompositionLayout","outputNodeRefCounts","parseScale","parseLayoutSize","renameTopLevelLayoutSizeSignal","parseSelections","parseData","parseAxesAndHeaders","parseLegends","parseMarkGroup","ignoreRange","parseScales","assembleEncodeFromView","baseView","assembleGroupEncodeEntry","isTopLevel","encodeEntry","assembleLayout","titleBand","headerComponentIndex","assembleLayoutTitleBand","assembleDefaultLayout","assembleHeaderMarks","headerMarks","assembleAxes","axisComponents","titleNoEncoding","assembleGroup","assembleSignals","assembleMarks","getDataName","fullName","oldSignalName","originalScaleName","correctDataNames","localScaleComponent","variableName","origName","sel","hasAxisOrientSignalRef","hasOrientSignalRef","ModelWithField","r1","getMapping","DensityTransformNode","specifiedAs","density","result","ExtentTransformNode","FlattenTransformNode","flatten","FoldTransformNode","fold","GeoJSONNode","geojson","parseAll","geoJsonCounter","coordinates","pair","GeoPointNode","ImputeNode","processSequence","keyvals","imputeTransform","imputedChannel","keyChannel","LoessTransformNode","loess","LookupNode","secondary","fromOutputNode","isLookupData","fromSource","findSource","fromOutputName","Lookup","isLookupSelection","materialized","lookup","foreign","asName","default","QuantileTransformNode","RegressionTransformNode","regression","PivotTransformNode","pivot","SampleTransformNode","sample","makeWalkTree","datasetIndex","walkTree","dataSource","getHeaderType","parseFacetHeader","makeHeaderComponent","mergeChildAxis","axisComponent","mainAxis","parseChildrenLayoutSize","parseNonUnitLayoutSizeForChannel","layoutSizeCmpt","mergedSize","childSize","scaleResolve","defaultUnitSize","facetSortFieldName","FacetModel","buildModel","initFacet","initFacetFieldDef","normalizedFacet","parseFacetHeaders","assembleSelectionTopLevelSignals","assembleSelectionData","getHeaderLayoutMixins","layoutMixins","layoutHeaderComponent","bandType","columnDistinctSignal","assembleGroupStyle","getCardinalityAggregateForChild","assembleFacet","facetRoot","outputName","cross","facetSortFields","facetSortOrder","ORTHOGONAL_ORIENT","root","assembleFacetData","otherData","formatMesh","mesh","otherFeature","feature","formatFeature","otherMesh","head","existingSource","parseRoot","sequence","graticule","parentIsLayer","lookupCounter","derivedType","transformNode","parseTransformArray","implicitSelection","getImplicitFromSelection","implicitEncoding","makeOutputNode","preFilterInvalid","postFilterInvalid","lookupName","materializeSelections","facetName","makeJoinAggregateFromFacet","dataSourceType","ConcatModel","getChildren","widthType","heightType","parseConcatLayoutSize","parseAxisGroup","layoutSignals","db","AXIS_COMPONENT_PROPERTIES_INDEX","AXIS_COMPONENT_PROPERTIES","AxisComponent","OPPOSITE_ORIENT","mergeAxisComponents","mergedAxisCmpts","childAxisCmpts","mergeAxisComponent","propsToAlwaysIncludeConfig","parseAxis","defaultOrient","typeBasedConfigTypes","axisChannel","axisOrient","vlOnlyConfigTypes","vgConfigTypes","vlOnlyAxisConfig","vgAxisConfig","axisConfigStyle","getAxisConfigs","getLabelAngle","hasValue","hasConfigValue","axisEncoding","axisEncode","axisEncodingPart","specifiedLabelsSpec","fixedShape","shapeMixins","vgMark","vgThicknessChannel","defaultSize","markPropOrConfig","markCompiler","postEncodingTransform","shapeDef","parseMarkGroups","FACETED_PATH_PREFIX","getMarkGroup","fromPrefix","getPathGroups","hasCornerRadius","STACK_GROUP_PREFIX","fieldScale","stackFieldGroup","func","groupUpdate","innerGroupUpdate","groupByField","strokeForeground","getGroupsForStackedBarWithCornerRadius","xScale","yScale","scaleClip","projectionClip","unitCount","parentCount","interactiveFlag","UnitModel","specifiedAxes","specifiedLegends","parentGivenSize","filledConfig","defaultFilled","defs","initEncoding","initLayoutSize","initScales","initAxes","initLegends","isGeoShapeMark","hasGeoPosition","initScale","scaleInternal","_axis","axisSpec","initAxis","axisInternal","_legend","supportLegend","specifiedSize","parseUnitLayoutSize","selDefs","selCmpts","selectionConfig","defaults","def_","parseUnitSelection","hasSelections","isPoint","assembleTopLevelSignals","dataCopy","assembleUnitSelectionData","vlEncoding","LayerModel","axisCount","oppositeOrient","parseLayerAxes","uniqueStyles","assembleLayerSelectionMarks","unitSize","isAnyConcatSpec","version","pkg","inputSpec","newLogger","vlFieldDef","firstPassCounter","secondPassCounter","optimizeDataflow","vgSpec","topLevelProperties","datasets","usermeta","vgConfig","sourceIndex","newData","whereTo","assembleRootData","otherTopLevelProps","$schema","assembleTopLevelModel","resize","autoSizeType","inverseSizeType","getFitType","getTopLevelProperties","normalized","dict","dictKeys","otherKeys"],"mappings":"+RAcO,SAASA,EAAYC,GAC1B,QAASA,EAAGC,EACd,CAEO,SAASC,EAAaF,GAC3B,QAASA,EAAGG,GACd,CAEO,SAASC,EAAaJ,GAC3B,QAASA,EAAGK,GACd,CAEO,SAASC,EAAeN,EAA2BO,GACxD,GAAIH,EAAaJ,GACfM,EAAYN,EAAGK,IAAKE,QACf,GAAIL,EAAaF,GACtB,IAAK,MAAMQ,KAASR,EAAGG,IACrBG,EAAYE,EAAOD,QAEhB,GAAIR,EAAYC,GACrB,IAAK,MAAMQ,KAASR,EAAGC,GACrBK,EAAYE,EAAOD,QAGrBA,EAAGP,EAEP,CAEO,SAASS,EACdT,EACAU,GAEA,OAAIN,EAAaJ,GACR,CAACK,IAAKI,EAA4BT,EAAGK,IAAKK,IACxCR,EAAaF,GACf,CAACG,IAAKH,EAAGG,IAAIQ,KAAIC,GAAKH,EAA4BG,EAAGF,MACnDX,EAAYC,GACd,CAACC,GAAID,EAAGC,GAAGU,KAAIC,GAAKH,EAA4BG,EAAGF,MAEnDA,EAAWV,EAEtB,CCpDaa,MAAAA,EAAYC,gBAElB,SAASC,EAAMC,GACpB,MAAM,IAAIC,MAAMD,EAClB,CAUO,SAASE,EAA0CC,EAAQC,GAChE,MAAMC,EAAY,CAAA,EAClB,IAAK,MAAMC,KAAQF,EACbG,EAAcA,eAACJ,EAAKG,KACtBD,EAAKC,GAAQH,EAAIG,IAGrB,OAAOD,CACT,CAOO,SAASG,EAA0CL,EAAQC,GAChE,MAAMC,EAAO,IAAKF,GAClB,IAAK,MAAMG,KAAQF,SACVC,EAAKC,GAEd,OAAOD,CACT,CAYO,SAASI,EAAKC,GACnB,GAAIC,EAAAA,SAASD,GACX,OAAOA,EAGT,MAAME,EAAMC,EAAAA,SAASH,GAAKA,EAAII,EAAUJ,GAGxC,GAAIE,EAAIG,OAAS,IACf,OAAOH,EAIT,IA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