-
Notifications
You must be signed in to change notification settings - Fork 592
/
channeldef.ts
1446 lines (1274 loc) · 50.9 KB
/
channeldef.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Gradient, ScaleType, SignalRef, Text} from 'vega';
import {isArray, isBoolean, isNumber, isString} from 'vega-util';
import {Aggregate, isAggregateOp, isArgmaxDef, isArgminDef, isCountingAggregateOp, isExponentialDef} from './aggregate';
import {Axis} from './axis';
import {autoMaxBins, Bin, BinParams, binToString, isBinned, isBinning} from './bin';
import {
ANGLE,
Channel,
COLOR,
COLUMN,
DESCRIPTION,
DETAIL,
ExtendedChannel,
FACET,
FILL,
FILLOPACITY,
getSizeChannel,
HREF,
isScaleChannel,
isSecondaryRangeChannel,
isXorY,
KEY,
LATITUDE,
LATITUDE2,
LONGITUDE,
LONGITUDE2,
OPACITY,
ORDER,
PolarPositionScaleChannel,
PositionScaleChannel,
RADIUS,
RADIUS2,
ROW,
SHAPE,
SIZE,
STROKE,
STROKEDASH,
STROKEOPACITY,
STROKEWIDTH,
TEXT,
THETA,
THETA2,
TOOLTIP,
URL,
X,
X2,
XOFFSET,
Y,
Y2,
YOFFSET
} from './channel';
import {getMarkConfig, getMarkPropOrConfig} from './compile/common';
import {isCustomFormatType} from './compile/format';
import {CompositeAggregate} from './compositemark';
import {Config} from './config';
import {DateTime, dateTimeToExpr, isDateTime} from './datetime';
import {Encoding} from './encoding';
import {ExprRef, isExprRef} from './expr';
import {Guide, GuideEncodingConditionalValueDef, TitleMixins} from './guide';
import {ImputeParams} from './impute';
import {Legend} from './legend';
import * as log from './log';
import {LogicalComposition} from './logical';
import {isRectBasedMark, Mark, MarkDef, RelativeBandSize} from './mark';
import {ParameterPredicate, Predicate} from './predicate';
import {hasDiscreteDomain, isContinuousToDiscrete, Scale, SCALE_CATEGORY_INDEX} from './scale';
import {isSortByChannel, Sort, SortOrder} from './sort';
import {isFacetFieldDef} from './spec/facet';
import {StackOffset} from './stack';
import {
BinnedTimeUnit,
getTimeUnitParts,
isBinnedTimeUnit,
isLocalSingleTimeUnit,
normalizeTimeUnit,
TimeUnit,
TimeUnitParams,
timeUnitToString
} from './timeunit';
import {AggregatedFieldDef, WindowFieldDef} from './transform';
import {getFullName, QUANTITATIVE, StandardType, Type} from './type';
import {
Dict,
flatAccessWithDatum,
getFirstDefined,
internalField,
omit,
removePathFromField,
replacePathInField,
stringify,
titleCase
} from './util';
import {isSignalRef} from './vega.schema';
export type PrimitiveValue = number | string | boolean | null;
export type Value<ES extends ExprRef | SignalRef = ExprRef | SignalRef> =
| PrimitiveValue
| number[]
| Gradient
| Text
| ES;
/**
* Definition object for a constant value (primitive value or gradient definition) of an encoding channel.
*/
export interface ValueDef<V extends Value = Value> {
/**
* 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).
*/
value: V;
}
export type PositionValueDef = ValueDef<number | 'width' | 'height' | ExprRef | SignalRef>;
export type NumericValueDef = ValueDef<number | ExprRef | SignalRef>;
/**
* A ValueDef with Condition<ValueDef | FieldDef> where either the condition or the value are optional.
* {
* condition: {field: ...} | {value: ...},
* value: ...,
* }
*/
/**
* @minProperties 1
*/
export type ValueDefWithCondition<F extends FieldDef<any> | DatumDef<any>, V extends Value = Value> = Partial<
ValueDef<V | ExprRef | SignalRef>
> & {
/**
* A field definition or one or more value definition(s) with a parameter predicate.
*/
condition?:
| Conditional<F>
| Conditional<ValueDef<V | ExprRef | SignalRef>>
| Conditional<ValueDef<V | ExprRef | SignalRef>>[];
};
export type StringValueDefWithCondition<F extends Field, T extends Type = StandardType> = ValueDefWithCondition<
MarkPropFieldOrDatumDef<F, T>,
string | null
>;
export type TypeForShape = 'nominal' | 'ordinal' | 'geojson';
export type ConditionalTemplate = FieldDef<any> | DatumDef | ValueDef<any> | ExprRef | SignalRef;
export type Conditional<CD extends ConditionalTemplate> = ConditionalPredicate<CD> | ConditionalParameter<CD>;
export type ConditionalPredicate<CD extends ConditionalTemplate> = {
/**
* Predicate for triggering the condition
*/
test: LogicalComposition<Predicate>;
} & CD;
export type ConditionalParameter<CD extends ConditionalTemplate> = ParameterPredicate & CD;
export function isConditionalParameter<T extends ConditionalTemplate>(c: Conditional<T>): c is ConditionalParameter<T> {
return c['param'];
}
export interface ConditionValueDefMixins<V extends Value = Value> {
/**
* One or more value definition(s) with [a parameter or a test predicate](https://vega.github.io/vega-lite/docs/condition.html).
*
* __Note:__ A field definition's `condition` property can only contain [conditional value definitions](https://vega.github.io/vega-lite/docs/condition.html#value)
* since Vega-Lite only allows at most one encoded field per encoding channel.
*/
condition?: Conditional<ValueDef<V>> | Conditional<ValueDef<V>>[];
}
/**
* A FieldDef with Condition<ValueDef>
* {
* condition: {value: ...},
* field: ...,
* ...
* }
*/
export type FieldOrDatumDefWithCondition<F extends FieldDef<any, any> | DatumDef<any>, V extends Value = Value> = F &
ConditionValueDefMixins<V | ExprRef | SignalRef>;
export type MarkPropDef<F extends Field, V extends Value, T extends Type = StandardType> =
| FieldOrDatumDefWithCondition<MarkPropFieldDef<F, T>, V>
| FieldOrDatumDefWithCondition<DatumDef<F>, V>
| ValueDefWithCondition<MarkPropFieldOrDatumDef<F, T>, V>;
export type ColorDef<F extends Field> = MarkPropDef<F, Gradient | string | null>;
export type NumericMarkPropDef<F extends Field> = MarkPropDef<F, number>;
export type NumericArrayMarkPropDef<F extends Field> = MarkPropDef<F, number[]>;
export type ShapeDef<F extends Field> = MarkPropDef<F, string | null, TypeForShape>;
export type StringFieldDefWithCondition<F extends Field> = FieldOrDatumDefWithCondition<StringFieldDef<F>, string>;
export type TextDef<F extends Field> =
| FieldOrDatumDefWithCondition<StringFieldDef<F>, Text>
| FieldOrDatumDefWithCondition<StringDatumDef<F>, Text>
| ValueDefWithCondition<StringFieldDef<F>, Text>;
/**
* A ValueDef with optional Condition<ValueDef | FieldDef>
* {
* condition: {field: ...} | {value: ...},
* value: ...,
* }
*/
/**
* Reference to a repeated value.
*/
export interface RepeatRef {
repeat: 'row' | 'column' | 'repeat' | 'layer';
}
export type FieldName = string;
export type Field = FieldName | RepeatRef;
export function isRepeatRef(field: Field | any): field is RepeatRef {
return field && !isString(field) && 'repeat' in field;
}
/** @@hidden */
export type HiddenCompositeAggregate = CompositeAggregate;
export interface FieldDefBase<F, B extends Bin = Bin> extends BandMixins {
/**
* __Required.__ A string defining the name of the field from which to pull a data value
* or an object defining iterated values from the [`repeat`](https://vega.github.io/vega-lite/docs/repeat.html) operator.
*
* __See also:__ [`field`](https://vega.github.io/vega-lite/docs/field.html) documentation.
*
* __Notes:__
* 1) Dots (`.`) and brackets (`[` and `]`) can be used to access nested objects (e.g., `"field": "foo.bar"` and `"field": "foo['bar']"`).
* 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\\]"`).
* See more details about escaping in the [field documentation](https://vega.github.io/vega-lite/docs/field.html).
* 2) `field` is not required if `aggregate` is `count`.
*/
field?: F;
// function
/**
* Time unit (e.g., `year`, `yearmonth`, `month`, `hours`) for a temporal field.
* or [a temporal field that gets casted as ordinal](https://vega.github.io/vega-lite/docs/type.html#cast).
*
* __Default value:__ `undefined` (None)
*
* __See also:__ [`timeUnit`](https://vega.github.io/vega-lite/docs/timeunit.html) documentation.
*/
timeUnit?: TimeUnit | BinnedTimeUnit | TimeUnitParams;
/**
* Aggregation function for the field
* (e.g., `"mean"`, `"sum"`, `"median"`, `"min"`, `"max"`, `"count"`).
*
* __Default value:__ `undefined` (None)
*
* __See also:__ [`aggregate`](https://vega.github.io/vega-lite/docs/aggregate.html) documentation.
*/
aggregate?: Aggregate | HiddenCompositeAggregate;
/**
* 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"`).
*
* - If `true`, default [binning parameters](https://vega.github.io/vega-lite/docs/bin.html#bin-parameters) will be applied.
*
* - 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.
*
* __Default value:__ `false`
*
* __See also:__ [`bin`](https://vega.github.io/vega-lite/docs/bin.html) documentation.
*/
bin?: B;
}
export function toFieldDefBase(fieldDef: FieldDef<string>): FieldDefBase<string> {
const {field, timeUnit, bin, aggregate} = fieldDef;
return {
...(timeUnit ? {timeUnit} : {}),
...(bin ? {bin} : {}),
...(aggregate ? {aggregate} : {}),
field
};
}
export interface TypeMixins<T extends Type> {
/**
* The type of measurement (`"quantitative"`, `"temporal"`, `"ordinal"`, or `"nominal"`) for the encoded field or constant value (`datum`).
* It can also be a `"geojson"` type for encoding ['geoshape'](https://vega.github.io/vega-lite/docs/geoshape.html).
*
* Vega-Lite automatically infers data types in many cases as discussed below. However, type is required for a field if:
* (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`
* or (2) if you wish to use an ordinal scale for a field with `bin` or `timeUnit`.
*
* __Default value:__
*
* 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:
* - `"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).
* - `"temporal"` is the default type if (1) the encoded field contains `timeUnit` or (2) the specified scale type is a time or utc scale
* - `"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`.
*
* 2) For a constant value in data domain (`datum`):
* - `"quantitative"` if the datum is a number
* - `"nominal"` if the datum is a string
* - `"temporal"` if the datum is [a date time object](https://vega.github.io/vega-lite/docs/datetime.html)
*
* __Note:__
* - 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.
* - 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`).
* - 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).
* - 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).
* - 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"`.
* - 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`).
*
* __See also:__ [`type`](https://vega.github.io/vega-lite/docs/type.html) documentation.
*/
type?: T;
}
/**
* Definition object for a data field, its type and transformation of an encoding channel.
*/
export type TypedFieldDef<
F extends Field,
T extends Type = any,
B extends Bin = boolean | BinParams | 'binned' | null // This is equivalent to Bin but we use the full form so the docs has detailed types
> = FieldDefBase<F, B> & TitleMixins & TypeMixins<T>;
export interface SortableFieldDef<
F extends Field,
T extends Type = StandardType,
B extends Bin = boolean | BinParams | null
> extends TypedFieldDef<F, T, B> {
/**
* Sort order for the encoded field.
*
* For continuous fields (quantitative or temporal), `sort` can be either `"ascending"` or `"descending"`.
*
* For discrete fields, `sort` can be one of the following:
* - `"ascending"` or `"descending"` -- for sorting by the values' natural order in JavaScript.
* - [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"}`.
* - [A sort field definition](https://vega.github.io/vega-lite/docs/sort.html#sort-field) for sorting by another field.
* - [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"`).
* - `null` indicating no sort.
*
* __Default value:__ `"ascending"`
*
* __Note:__ `null` and sorting by another channel is not supported for `row` and `column`.
*
* __See also:__ [`sort`](https://vega.github.io/vega-lite/docs/sort.html) documentation.
*/
sort?: Sort<F>;
}
export function isSortableFieldDef<F extends Field>(fieldDef: FieldDef<F>): fieldDef is SortableFieldDef<F> {
return 'sort' in fieldDef;
}
export type ScaleFieldDef<
F extends Field,
T extends Type = StandardType,
B extends Bin = boolean | BinParams | null
> = SortableFieldDef<F, T, B> & ScaleMixins;
export interface ScaleMixins {
/**
* 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.
*
* 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).
*
* __Default value:__ If undefined, default [scale properties](https://vega.github.io/vega-lite/docs/scale.html) are applied.
*
* __See also:__ [`scale`](https://vega.github.io/vega-lite/docs/scale.html) documentation.
*/
scale?: Scale | null;
}
export type OffsetDef<F extends Field, T extends Type = StandardType> =
| ScaleFieldDef<F, T>
| ScaleDatumDef<F>
| ValueDef<number>;
export interface DatumDef<
F extends Field = string,
V extends PrimitiveValue | DateTime | ExprRef | SignalRef = PrimitiveValue | DateTime | ExprRef | SignalRef
> extends Partial<TypeMixins<Type>>,
BandMixins,
TitleMixins {
/**
* A constant value in data domain.
*/
datum?: F extends RepeatRef ? V | RepeatRef : V;
// only apply Repeatref if field (F) can be RepeatRef
// FIXME(https://github.com/microsoft/TypeScript/issues/37586):
// `F extends RepeatRef` probably should be `RepeatRef extends F` but there is likely a bug in TS.
}
export interface FormatMixins {
/**
* When used with the default `"number"` and `"time"` format type, the text formatting pattern for labels of guides (axes, legends, headers) and text marks.
*
* - 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).
* - 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).
*
* See the [format documentation](https://vega.github.io/vega-lite/docs/format.html) for more examples.
*
* 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.
*
* __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.
*/
format?: string | Dict<unknown>;
/**
* 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).
*
* __Default value:__
* - `"time"` for temporal fields and ordinal and nominal fields with `timeUnit`.
* - `"number"` for quantitative fields as well as ordinal and nominal fields without `timeUnit`.
*/
formatType?: 'number' | 'time' | string;
}
export type StringDatumDef<F extends Field = string> = DatumDef<F> & FormatMixins;
export type ScaleDatumDef<F extends Field = string> = ScaleMixins & DatumDef<F>;
/**
* 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`.
*/
export type SecondaryFieldDef<F extends Field> = FieldDefBase<F, null> & TitleMixins; // x2/y2 shouldn't have bin, but we keep bin property for simplicity of the codebase.
export type Position2Def<F extends Field> = SecondaryFieldDef<F> | DatumDef<F> | PositionValueDef;
export type SecondaryChannelDef<F extends Field> = Encoding<F>['x2' | 'y2'];
/**
* Field Def without scale (and without bin: "binned" support).
*/
export type FieldDefWithoutScale<F extends Field, T extends Type = StandardType> = TypedFieldDef<F, T>;
export type LatLongFieldDef<F extends Field> = FieldDefBase<F, null> &
TitleMixins &
Partial<TypeMixins<'quantitative'>>; // Lat long shouldn't have bin, but we keep bin property for simplicity of the codebase.
export type LatLongDef<F extends Field> = LatLongFieldDef<F> | DatumDef<F>;
export type PositionFieldDefBase<F extends Field> = ScaleFieldDef<
F,
StandardType,
boolean | BinParams | 'binned' | null // This is equivalent to Bin but we use the full form so the docs has detailed types
> &
PositionBaseMixins;
export type PositionDatumDefBase<F extends Field> = ScaleDatumDef<F> & PositionBaseMixins;
export interface PositionBaseMixins {
/**
* Type of stacking offset if the field should be stacked.
* `stack` is only applicable for `x`, `y`, `theta`, and `radius` channels with continuous domains.
* For example, `stack` of `y` can be used to customize stacking for a vertical bar chart.
*
* `stack` can be one of the following values:
* - `"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).
* - `"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)). <br/>
* -`"center"` - stacking with center baseline (for [streamgraph](https://vega.github.io/vega-lite/docs/stack.html#streamgraph)).
* - `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.
*
* __Default value:__ `zero` for plots with all of the following conditions are true:
* (1) the mark is `bar`, `area`, or `arc`;
* (2) the stacked measure channel (x or y) has a linear scale;
* (3) At least one of non-position channels mapped to an unaggregated field that is different from x and y. Otherwise, `null` by default.
*
* __See also:__ [`stack`](https://vega.github.io/vega-lite/docs/stack.html) documentation.
*/
stack?: StackOffset | null | boolean;
}
export interface BandMixins {
/**
* 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`.
*
* @minimum 0
* @maximum 1
*/
bandPosition?: number;
}
export type PositionFieldDef<F extends Field> = PositionFieldDefBase<F> & PositionMixins;
export type PositionDatumDef<F extends Field> = PositionDatumDefBase<F> & PositionMixins;
export type PositionDef<F extends Field> = PositionFieldDef<F> | PositionDatumDef<F> | PositionValueDef;
export interface PositionMixins {
/**
* An object defining properties of axis's gridlines, ticks and labels.
* If `null`, the axis for the encoding channel will be removed.
*
* __Default value:__ If undefined, default [axis properties](https://vega.github.io/vega-lite/docs/axis.html) are applied.
*
* __See also:__ [`axis`](https://vega.github.io/vega-lite/docs/axis.html) documentation.
*/
axis?: Axis<ExprRef | SignalRef> | null;
/**
* An object defining the properties of the Impute Operation to be applied.
* The field value of the other positional channel is taken as `key` of the `Impute` Operation.
* The field of the `color` channel if specified is used as `groupby` of the `Impute` Operation.
*
* __See also:__ [`impute`](https://vega.github.io/vega-lite/docs/impute.html) documentation.
*/
impute?: ImputeParams | null;
}
export type PolarDef<F extends Field> = PositionFieldDefBase<F> | PositionDatumDefBase<F> | PositionValueDef;
export function getBandPosition({
fieldDef,
fieldDef2,
markDef: mark,
config
}: {
fieldDef: FieldDef<string> | DatumDef;
fieldDef2?: SecondaryChannelDef<string>;
markDef: MarkDef<Mark, SignalRef>;
config: Config<SignalRef>;
}): number {
if (isFieldOrDatumDef(fieldDef) && fieldDef.bandPosition !== undefined) {
return fieldDef.bandPosition;
}
if (isFieldDef(fieldDef)) {
const {timeUnit, bin} = fieldDef;
if (timeUnit && !fieldDef2) {
return getMarkConfig('timeUnitBandPosition', mark, config);
} else if (isBinning(bin)) {
return 0.5;
}
}
return undefined;
}
export function getBandSize({
channel,
fieldDef,
fieldDef2,
markDef: mark,
config,
scaleType,
useVlSizeChannel
}: {
channel: PositionScaleChannel | PolarPositionScaleChannel;
fieldDef: ChannelDef<string>;
fieldDef2?: SecondaryChannelDef<string>;
markDef: MarkDef<Mark, SignalRef>;
config: Config<SignalRef>;
scaleType: ScaleType;
useVlSizeChannel?: boolean;
}): number | RelativeBandSize | SignalRef {
const sizeChannel = getSizeChannel(channel);
const size = getMarkPropOrConfig(useVlSizeChannel ? 'size' : sizeChannel, mark, config, {
vgChannel: sizeChannel
});
if (size !== undefined) {
return size;
}
if (isFieldDef(fieldDef)) {
const {timeUnit, bin} = fieldDef;
if (timeUnit && !fieldDef2) {
return {band: getMarkConfig('timeUnitBandSize', mark, config)};
} else if (isBinning(bin) && !hasDiscreteDomain(scaleType)) {
return {band: 1};
}
}
if (isRectBasedMark(mark.type)) {
if (scaleType) {
if (hasDiscreteDomain(scaleType)) {
return config[mark.type]?.discreteBandSize || {band: 1};
} else {
return config[mark.type]?.continuousBandSize;
}
}
return config[mark.type]?.discreteBandSize;
}
return undefined;
}
export function hasBandEnd(
fieldDef: FieldDef<string>,
fieldDef2: SecondaryChannelDef<string>,
markDef: MarkDef<Mark, SignalRef>,
config: Config<SignalRef>
): boolean {
if (isBinning(fieldDef.bin) || (fieldDef.timeUnit && isTypedFieldDef(fieldDef) && fieldDef.type === 'temporal')) {
// Need to check bandPosition because non-rect marks (e.g., point) with timeUnit
// doesn't have to use bandEnd if there is no bandPosition.
return getBandPosition({fieldDef, fieldDef2, markDef, config}) !== undefined;
}
return false;
}
/**
* Field definition of a mark property, which can contain a legend.
*/
export type MarkPropFieldDef<F extends Field, T extends Type = Type> = ScaleFieldDef<F, T, boolean | BinParams | null> &
LegendMixins;
export type MarkPropDatumDef<F extends Field> = LegendMixins & ScaleDatumDef<F>;
export type MarkPropFieldOrDatumDef<F extends Field, T extends Type = Type> =
| MarkPropFieldDef<F, T>
| MarkPropDatumDef<F>;
export interface LegendMixins {
/**
* An object defining properties of the legend.
* If `null`, the legend for the encoding channel will be removed.
*
* __Default value:__ If undefined, default [legend properties](https://vega.github.io/vega-lite/docs/legend.html) are applied.
*
* __See also:__ [`legend`](https://vega.github.io/vega-lite/docs/legend.html) documentation.
*/
legend?: Legend<ExprRef | SignalRef> | null;
}
// Detail
// Order Path have no scale
export type OrderFieldDef<F extends Field> = FieldDefWithoutScale<F> & OrderOnlyDef;
export interface OrderOnlyDef {
/**
* The sort order. One of `"ascending"` (default) or `"descending"`.
*/
sort?: SortOrder;
}
export function isOrderOnlyDef<F extends Field>(
orderDef: OrderFieldDef<F> | OrderFieldDef<F>[] | OrderValueDef | OrderOnlyDef
): orderDef is OrderOnlyDef {
return orderDef && !!(orderDef as OrderOnlyDef).sort && !orderDef['field'];
}
export type OrderValueDef = ConditionValueDefMixins<number> & NumericValueDef;
export interface StringFieldDef<F extends Field> extends FieldDefWithoutScale<F, StandardType>, FormatMixins {}
export type FieldDef<F extends Field, T extends Type = any> = SecondaryFieldDef<F> | TypedFieldDef<F, T>;
export type ChannelDef<F extends Field = string> = Encoding<F>[keyof Encoding<F>];
export function isConditionalDef<CD extends ChannelDef<any> | GuideEncodingConditionalValueDef | ExprRef | SignalRef>(
channelDef: CD
): channelDef is CD & {condition: Conditional<any>} {
return channelDef && 'condition' in channelDef;
}
/**
* Return if a channelDef is a ConditionalValueDef with ConditionFieldDef
*/
export function hasConditionalFieldDef<F extends Field>(
channelDef: Partial<ChannelDef<F>>
): channelDef is {condition: Conditional<TypedFieldDef<F>>} {
const condition = channelDef?.['condition'];
return !!condition && !isArray(condition) && isFieldDef(condition);
}
export function hasConditionalFieldOrDatumDef<F extends Field>(
channelDef: ChannelDef<F>
): channelDef is {condition: Conditional<TypedFieldDef<F>>} {
const condition = channelDef?.['condition'];
return !!condition && !isArray(condition) && isFieldOrDatumDef(condition);
}
export function hasConditionalValueDef<F extends Field>(
channelDef: ChannelDef<F>
): channelDef is ValueDef<any> & {condition: Conditional<ValueDef<any>> | Conditional<ValueDef<any>>[]} {
const condition = channelDef?.['condition'];
return !!condition && (isArray(condition) || isValueDef(condition));
}
export function isFieldDef<F extends Field>(
channelDef: Partial<ChannelDef<F>> | FieldDefBase<F> | DatumDef<F, any>
): channelDef is FieldDefBase<F> | TypedFieldDef<F> | SecondaryFieldDef<F> {
// TODO: we can't use field in channelDef here as it's somehow failing runtime test
return channelDef && (!!channelDef['field'] || channelDef['aggregate'] === 'count');
}
export function channelDefType<F extends Field>(channelDef: ChannelDef<F>): Type | undefined {
return channelDef?.['type'];
}
export function isDatumDef<F extends Field>(
channelDef: Partial<ChannelDef<F>> | FieldDefBase<F> | DatumDef<F, any>
): channelDef is DatumDef<F, any> {
return channelDef && 'datum' in channelDef;
}
export function isContinuousFieldOrDatumDef<F extends Field>(
cd: ChannelDef<F>
): cd is TypedFieldDef<F> | DatumDef<F, number> {
// TODO: make datum support DateTime object
return (isTypedFieldDef(cd) && !isDiscrete(cd)) || isNumericDataDef(cd);
}
export function isUnbinnedQuantitativeFieldOrDatumDef<F extends Field>(cd: ChannelDef<F>) {
// TODO: make datum support DateTime object
return (isTypedFieldDef(cd) && cd.type === 'quantitative' && !cd.bin) || isNumericDataDef(cd);
}
export function isNumericDataDef<F extends Field>(cd: ChannelDef<F>): cd is DatumDef<F, number> {
return isDatumDef(cd) && isNumber(cd.datum);
}
export function isFieldOrDatumDef<F extends Field>(
channelDef: Partial<ChannelDef<F>>
): channelDef is FieldDef<F, any> | DatumDef<F> {
return isFieldDef(channelDef) || isDatumDef(channelDef);
}
export function isTypedFieldDef<F extends Field>(channelDef: ChannelDef<F>): channelDef is TypedFieldDef<F> {
return channelDef && ('field' in channelDef || channelDef['aggregate'] === 'count') && 'type' in channelDef;
}
export function isValueDef<F extends Field>(channelDef: Partial<ChannelDef<F>>): channelDef is ValueDef<any> {
return channelDef && 'value' in channelDef && 'value' in channelDef;
}
export function isScaleFieldDef<F extends Field>(channelDef: ChannelDef<F>): channelDef is ScaleFieldDef<F> {
return channelDef && ('scale' in channelDef || 'sort' in channelDef);
}
export function isPositionFieldOrDatumDef<F extends Field>(
channelDef: ChannelDef<F>
): channelDef is PositionFieldDef<F> | PositionDatumDef<F> {
return channelDef && ('axis' in channelDef || 'stack' in channelDef || 'impute' in channelDef);
}
export function isMarkPropFieldOrDatumDef<F extends Field>(
channelDef: ChannelDef<F>
): channelDef is MarkPropFieldDef<F, any> | MarkPropDatumDef<F> {
return channelDef && 'legend' in channelDef;
}
export function isStringFieldOrDatumDef<F extends Field>(
channelDef: ChannelDef<F>
): channelDef is StringFieldDef<F> | StringDatumDef<F> {
return channelDef && ('format' in channelDef || 'formatType' in channelDef);
}
export function toStringFieldDef<F extends Field>(fieldDef: FieldDef<F>): StringFieldDef<F> {
// omit properties that don't exist in string field defs
return omit(fieldDef, ['legend', 'axis', 'header', 'scale'] as any[]);
}
export interface FieldRefOption {
/** Exclude bin, aggregate, timeUnit */
nofn?: boolean;
/** Wrap the field with datum, parent, or datum.datum (e.g., datum['...'] for Vega Expression */
expr?: 'datum' | 'parent' | 'datum.datum';
/** Prepend fn with custom function prefix */
prefix?: string;
/** Append suffix to the field ref for bin (default='start') */
binSuffix?: 'end' | 'range' | 'mid';
/** Append suffix to the field ref (general) */
suffix?: string;
/**
* Use the field name for `as` in a transform.
* We will not escape nested accesses because Vega transform outputs cannot be nested.
*/
forAs?: boolean;
}
function isOpFieldDef(
fieldDef: FieldDefBase<string> | WindowFieldDef | AggregatedFieldDef
): fieldDef is WindowFieldDef | AggregatedFieldDef {
return 'op' in fieldDef;
}
/**
* Get a Vega field reference from a Vega-Lite field def.
*/
export function vgField(
fieldDef: FieldDefBase<string> | WindowFieldDef | AggregatedFieldDef,
opt: FieldRefOption = {}
): string {
let field = fieldDef.field;
const prefix = opt.prefix;
let suffix = opt.suffix;
let argAccessor = ''; // for accessing argmin/argmax field at the end without getting escaped
if (isCount(fieldDef)) {
field = internalField('count');
} else {
let fn: string;
if (!opt.nofn) {
if (isOpFieldDef(fieldDef)) {
fn = isExponentialDef(fieldDef.op) ? 'exponential' : fieldDef.op;
} else {
const {bin, aggregate, timeUnit} = fieldDef;
if (isBinning(bin)) {
fn = binToString(bin);
suffix = (opt.binSuffix ?? '') + (opt.suffix ?? '');
} else if (aggregate) {
if (isArgmaxDef(aggregate)) {
argAccessor = `["${field}"]`;
field = `argmax_${aggregate.argmax}`;
} else if (isArgminDef(aggregate)) {
argAccessor = `["${field}"]`;
field = `argmin_${aggregate.argmin}`;
} else {
fn = isExponentialDef(aggregate) ? 'exponential' : String(aggregate);
}
} else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {
fn = timeUnitToString(timeUnit);
suffix = ((!['range', 'mid'].includes(opt.binSuffix) && opt.binSuffix) || '') + (opt.suffix ?? '');
}
}
}
if (fn) {
field = field ? `${fn}_${field}` : fn;
}
}
if (suffix) {
field = `${field}_${suffix}`;
}
if (prefix) {
field = `${prefix}_${field}`;
}
if (opt.forAs) {
return removePathFromField(field);
} else if (opt.expr) {
// Expression to access flattened field. No need to escape dots.
return flatAccessWithDatum(field, opt.expr) + argAccessor;
} else {
// We flattened all fields so paths should have become dot.
return replacePathInField(field) + argAccessor;
}
}
export function isDiscrete(def: TypedFieldDef<Field> | DatumDef<any, any>) {
switch (def.type) {
case 'nominal':
case 'ordinal':
case 'geojson':
return true;
case 'quantitative':
return isFieldDef(def) && !!def.bin;
case 'temporal':
return false;
}
throw new Error(log.message.invalidFieldType(def.type));
}
export function isDiscretizing(def: TypedFieldDef<Field> | DatumDef<any, any>) {
return isScaleFieldDef(def) && isContinuousToDiscrete(def.scale?.type);
}
export function isCount(fieldDef: FieldDefBase<Field>) {
return fieldDef.aggregate === 'count';
}
export type FieldTitleFormatter = (fieldDef: FieldDefBase<string>, config: Config) => string;
export function verbalTitleFormatter(fieldDef: FieldDefBase<string>, config: Config) {
const {field, bin, timeUnit, aggregate} = fieldDef;
if (aggregate === 'count') {
return config.countTitle;
} else if (isBinning(bin)) {
return `${field} (binned)`;
} else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {
const unit = normalizeTimeUnit(timeUnit)?.unit;
if (unit) {
return `${field} (${getTimeUnitParts(unit).join('-')})`;
}
} else if (aggregate) {
if (isArgmaxDef(aggregate)) {
return `${field} for max ${aggregate.argmax}`;
} else if (isArgminDef(aggregate)) {
return `${field} for min ${aggregate.argmin}`;
} else {
const aggregateOp = isExponentialDef(aggregate) ? 'exponential' : aggregate;
return `${titleCase(aggregateOp)} of ${field}`;
}
}
return field;
}
export function functionalTitleFormatter(fieldDef: FieldDefBase<string>) {
const {aggregate, bin, timeUnit, field} = fieldDef;
if (isArgmaxDef(aggregate)) {
return `${field} for argmax(${aggregate.argmax})`;
} else if (isArgminDef(aggregate)) {
return `${field} for argmin(${aggregate.argmin})`;
}
const timeUnitParams = timeUnit && !isBinnedTimeUnit(timeUnit) ? normalizeTimeUnit(timeUnit) : undefined;
const aggregateOp = isExponentialDef(aggregate) ? 'exponential' : aggregate;
const fn =
aggregateOp || timeUnitParams?.unit || (timeUnitParams?.maxbins && 'timeunit') || (isBinning(bin) && 'bin');
if (fn) {
return `${fn.toUpperCase()}(${field})`;
} else {
return field;
}
}
export const defaultTitleFormatter: FieldTitleFormatter = (fieldDef: FieldDefBase<string>, config: Config) => {
switch (config.fieldTitle) {
case 'plain':
return fieldDef.field;
case 'functional':
return functionalTitleFormatter(fieldDef);
default:
return verbalTitleFormatter(fieldDef, config);
}
};
let titleFormatter = defaultTitleFormatter;
export function setTitleFormatter(formatter: FieldTitleFormatter) {
titleFormatter = formatter;
}
export function resetTitleFormatter() {
setTitleFormatter(defaultTitleFormatter);
}
export function title(
fieldOrDatumDef: TypedFieldDef<string> | SecondaryFieldDef<string> | DatumDef,
config: Config,
{allowDisabling, includeDefault = true}: {allowDisabling: boolean; includeDefault?: boolean}
) {
const guideTitle = getGuide(fieldOrDatumDef)?.title;
if (!isFieldDef(fieldOrDatumDef)) {
return guideTitle ?? fieldOrDatumDef.title;
}
const fieldDef = fieldOrDatumDef;
const def = includeDefault ? defaultTitle(fieldDef, config) : undefined;
if (allowDisabling) {
return getFirstDefined(guideTitle, fieldDef.title, def);
} else {
return guideTitle ?? fieldDef.title ?? def;
}
}
export function getGuide(fieldDef: TypedFieldDef<string> | SecondaryFieldDef<string> | DatumDef): Guide {
if (isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis) {
return fieldDef.axis;
} else if (isMarkPropFieldOrDatumDef(fieldDef) && fieldDef.legend) {
return fieldDef.legend;
} else if (isFacetFieldDef(fieldDef) && fieldDef.header) {
return fieldDef.header;
}
return undefined;
}
export function defaultTitle(fieldDef: FieldDefBase<string>, config: Config) {
return titleFormatter(fieldDef, config);
}
export function getFormatMixins(fieldDef: TypedFieldDef<string> | DatumDef) {
if (isStringFieldOrDatumDef(fieldDef)) {
const {format, formatType} = fieldDef;
return {format, formatType};
} else {
const guide = getGuide(fieldDef) ?? {};
const {format, formatType} = guide;
return {format, formatType};
}
}
export function defaultType<T extends TypedFieldDef<Field>>(fieldDef: T, channel: ExtendedChannel): Type {
switch (channel) {
case 'latitude':
case 'longitude':
return 'quantitative';
case 'row':
case 'column':
case 'facet':
case 'shape':