-
Notifications
You must be signed in to change notification settings - Fork 592
/
facet.ts
436 lines (373 loc) · 14.1 KB
/
facet.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
import {AggregateOp, LayoutAlign, NewSignal, SignalRef} from 'vega';
import {isArray} from 'vega-util';
import {isBinning} from '../bin';
import {COLUMN, ExtendedChannel, FacetChannel, FACET_CHANNELS, POSITION_SCALE_CHANNELS, ROW} from '../channel';
import {FieldName, FieldRefOption, initFieldDef, TypedFieldDef, vgField} from '../channeldef';
import {Config} from '../config';
import {ExprRef} from '../expr';
import * as log from '../log';
import {hasDiscreteDomain} from '../scale';
import {DEFAULT_SORT_OP, EncodingSortField, isSortField, SortOrder} from '../sort';
import {NormalizedFacetSpec} from '../spec';
import {EncodingFacetMapping, FacetFieldDef, FacetMapping, isFacetMapping} from '../spec/facet';
import {keys} from '../util';
import {isVgRangeStep, SubstituteType, VgData, VgLayout, VgMarkGroup} from '../vega.schema';
import {buildModel} from './buildmodel';
import {assembleFacetData} from './data/assemble';
import {sortArrayIndexField} from './data/calculate';
import {parseData} from './data/parse';
import {assembleLabelTitle} from './header/assemble';
import {getHeaderChannel, getHeaderProperty} from './header/common';
import {HEADER_CHANNELS, HEADER_TYPES} from './header/component';
import {parseFacetHeaders} from './header/parse';
import {parseChildrenLayoutSize} from './layoutsize/parse';
import {Model, ModelWithField} from './model';
import {assembleDomain, getFieldFromDomain} from './scale/domain';
import {assembleFacetSignals} from './selection/assemble';
export function facetSortFieldName(
fieldDef: FacetFieldDef<string>,
sort: EncodingSortField<string>,
opt?: FieldRefOption
) {
return vgField(sort, {suffix: `by_${vgField(fieldDef)}`, ...opt});
}
export class FacetModel extends ModelWithField {
public readonly facet: EncodingFacetMapping<string, SignalRef>;
public readonly child: Model;
public readonly children: Model[];
constructor(
spec: SubstituteType<NormalizedFacetSpec, ExprRef, SignalRef>,
parent: Model,
parentGivenName: string,
config: Config<SignalRef>
) {
super(spec, 'facet', parent, parentGivenName, config, spec.resolve);
this.child = buildModel(spec.spec, this, this.getName('child'), undefined, config);
this.children = [this.child];
this.facet = this.initFacet(spec.facet);
}
private initFacet(
facet: FacetFieldDef<FieldName> | FacetMapping<FieldName>
): EncodingFacetMapping<FieldName, SignalRef> {
// clone to prevent side effect to the original spec
if (!isFacetMapping(facet)) {
return {facet: this.initFacetFieldDef(facet, 'facet')};
}
const channels = keys(facet);
const normalizedFacet = {};
for (const channel of channels) {
if (![ROW, COLUMN].includes(channel)) {
// Drop unsupported channel
log.warn(log.message.incompatibleChannel(channel, 'facet'));
break;
}
const fieldDef = facet[channel];
if (fieldDef.field === undefined) {
log.warn(log.message.emptyFieldDef(fieldDef, channel));
break;
}
normalizedFacet[channel] = this.initFacetFieldDef(fieldDef, channel);
}
return normalizedFacet;
}
private initFacetFieldDef(fieldDef: FacetFieldDef<FieldName, ExprRef | SignalRef>, channel: FacetChannel) {
// Cast because we call initFieldDef, which assumes general FieldDef.
// However, FacetFieldDef is a bit more constrained than the general FieldDef
const facetFieldDef = initFieldDef(fieldDef, channel) as FacetFieldDef<FieldName, SignalRef>;
if (facetFieldDef.header === null) {
facetFieldDef.header = null;
}
return facetFieldDef;
}
public channelHasField(channel: ExtendedChannel): boolean {
return !!this.facet[channel];
}
public fieldDef(channel: ExtendedChannel): TypedFieldDef<string> {
return this.facet[channel];
}
public parseData() {
this.component.data = parseData(this);
this.child.parseData();
}
public parseLayoutSize() {
parseChildrenLayoutSize(this);
}
public parseSelections() {
// As a facet has a single child, the selection components are the same.
// The child maintains its selections to assemble signals, which remain
// within its unit.
this.child.parseSelections();
this.component.selection = this.child.component.selection;
}
public parseMarkGroup() {
this.child.parseMarkGroup();
}
public parseAxesAndHeaders() {
this.child.parseAxesAndHeaders();
parseFacetHeaders(this);
}
public assembleSelectionTopLevelSignals(signals: NewSignal[]): NewSignal[] {
return this.child.assembleSelectionTopLevelSignals(signals);
}
public assembleSignals(): NewSignal[] {
this.child.assembleSignals();
return [];
}
public assembleSelectionData(data: readonly VgData[]): readonly VgData[] {
return this.child.assembleSelectionData(data);
}
private getHeaderLayoutMixins(): VgLayout {
const layoutMixins: VgLayout = {};
for (const channel of FACET_CHANNELS) {
for (const headerType of HEADER_TYPES) {
const layoutHeaderComponent = this.component.layoutHeaders[channel];
const headerComponent = layoutHeaderComponent[headerType];
const {facetFieldDef} = layoutHeaderComponent;
if (facetFieldDef) {
const titleOrient = getHeaderProperty('titleOrient', facetFieldDef.header, this.config, channel);
if (['right', 'bottom'].includes(titleOrient)) {
const headerChannel = getHeaderChannel(channel, titleOrient);
layoutMixins.titleAnchor ??= {};
layoutMixins.titleAnchor[headerChannel] = 'end';
}
}
if (headerComponent?.[0]) {
// set header/footerBand
const sizeType = channel === 'row' ? 'height' : 'width';
const bandType = headerType === 'header' ? 'headerBand' : 'footerBand';
if (channel !== 'facet' && !this.child.component.layoutSize.get(sizeType)) {
// If facet child does not have size signal, then apply headerBand
layoutMixins[bandType] ??= {};
layoutMixins[bandType][channel] = 0.5;
}
if (layoutHeaderComponent.title) {
layoutMixins.offset ??= {};
layoutMixins.offset[channel === 'row' ? 'rowTitle' : 'columnTitle'] = 10;
}
}
}
}
return layoutMixins;
}
protected assembleDefaultLayout(): VgLayout {
const {column, row} = this.facet;
const columns = column ? this.columnDistinctSignal() : row ? 1 : undefined;
let align: LayoutAlign = 'all';
// Do not align the cells if the scale corresponding to the direction is indepent.
// We always align when we facet into both row and column.
if (!row && this.component.resolve.scale.x === 'independent') {
align = 'none';
} else if (!column && this.component.resolve.scale.y === 'independent') {
align = 'none';
}
return {
...this.getHeaderLayoutMixins(),
...(columns ? {columns} : {}),
bounds: 'full',
align
};
}
public assembleLayoutSignals(): NewSignal[] {
// FIXME(https://github.com/vega/vega-lite/issues/1193): this can be incorrect if we have independent scales.
return this.child.assembleLayoutSignals();
}
private columnDistinctSignal() {
if (this.parent && this.parent instanceof FacetModel) {
// For nested facet, we will add columns to group mark instead
// See discussion in https://github.com/vega/vega/issues/952
// and https://github.com/vega/vega-view/releases/tag/v1.2.6
return undefined;
} else {
// In facetNode.assemble(), the name is always this.getName('column') + '_layout'.
const facetLayoutDataName = this.getName('column_domain');
return {signal: `length(data('${facetLayoutDataName}'))`};
}
}
public assembleGroupStyle(): string | string[] {
return undefined;
}
public assembleGroup(signals: NewSignal[]) {
if (this.parent && this.parent instanceof FacetModel) {
// Provide number of columns for layout.
// See discussion in https://github.com/vega/vega/issues/952
// and https://github.com/vega/vega-view/releases/tag/v1.2.6
return {
...(this.channelHasField('column')
? {
encode: {
update: {
// TODO(https://github.com/vega/vega-lite/issues/2759):
// Correct the signal for facet of concat of facet_column
columns: {field: vgField(this.facet.column, {prefix: 'distinct'})}
}
}
}
: {}),
...super.assembleGroup(signals)
};
}
return super.assembleGroup(signals);
}
/**
* Aggregate cardinality for calculating size
*/
private getCardinalityAggregateForChild() {
const fields: string[] = [];
const ops: AggregateOp[] = [];
const as: string[] = [];
if (this.child instanceof FacetModel) {
if (this.child.channelHasField('column')) {
const field = vgField(this.child.facet.column);
fields.push(field);
ops.push('distinct');
as.push(`distinct_${field}`);
}
} else {
for (const channel of POSITION_SCALE_CHANNELS) {
const childScaleComponent = this.child.component.scales[channel];
if (childScaleComponent && !childScaleComponent.merged) {
const type = childScaleComponent.get('type');
const range = childScaleComponent.get('range');
if (hasDiscreteDomain(type) && isVgRangeStep(range)) {
const domain = assembleDomain(this.child, channel);
const field = getFieldFromDomain(domain);
if (field) {
fields.push(field);
ops.push('distinct');
as.push(`distinct_${field}`);
} else {
log.warn(log.message.unknownField(channel));
}
}
}
}
}
return {fields, ops, as};
}
private assembleFacet() {
const {name, data} = this.component.data.facetRoot;
const {row, column} = this.facet;
const {fields, ops, as} = this.getCardinalityAggregateForChild();
const groupby: string[] = [];
for (const channel of FACET_CHANNELS) {
const fieldDef = this.facet[channel];
if (fieldDef) {
groupby.push(vgField(fieldDef));
const {bin, sort} = fieldDef;
if (isBinning(bin)) {
groupby.push(vgField(fieldDef, {binSuffix: 'end'}));
}
if (isSortField(sort)) {
const {field, op = DEFAULT_SORT_OP} = sort;
const outputName = facetSortFieldName(fieldDef, sort);
if (row && column) {
// For crossed facet, use pre-calculate field as it requires a different groupby
// For each calculated field, apply max and assign them to the same name as
// all values of the same group should be the same anyway.
fields.push(outputName);
ops.push('max');
as.push(outputName);
} else {
fields.push(field);
ops.push(op);
as.push(outputName);
}
} else if (isArray(sort)) {
const outputName = sortArrayIndexField(fieldDef, channel);
fields.push(outputName);
ops.push('max');
as.push(outputName);
}
}
}
const cross = !!row && !!column;
return {
name,
data,
groupby,
...(cross || fields.length > 0
? {
aggregate: {
...(cross ? {cross} : {}),
...(fields.length ? {fields, ops, as} : {})
}
}
: {})
};
}
private facetSortFields(channel: FacetChannel): string[] {
const {facet} = this;
const fieldDef = facet[channel];
if (fieldDef) {
if (isSortField(fieldDef.sort)) {
return [facetSortFieldName(fieldDef, fieldDef.sort, {expr: 'datum'})];
} else if (isArray(fieldDef.sort)) {
return [sortArrayIndexField(fieldDef, channel, {expr: 'datum'})];
}
return [vgField(fieldDef, {expr: 'datum'})];
}
return [];
}
private facetSortOrder(channel: FacetChannel): SortOrder[] {
const {facet} = this;
const fieldDef = facet[channel];
if (fieldDef) {
const {sort} = fieldDef;
const order = (isSortField(sort) ? sort.order : !isArray(sort) && sort) || 'ascending';
return [order];
}
return [];
}
private assembleLabelTitle() {
const {facet, config} = this;
if (facet.facet) {
// Facet always uses title to display labels
return assembleLabelTitle(facet.facet, 'facet', config);
}
const ORTHOGONAL_ORIENT = {
row: ['top', 'bottom'],
column: ['left', 'right']
};
for (const channel of HEADER_CHANNELS) {
if (facet[channel]) {
const labelOrient = getHeaderProperty('labelOrient', facet[channel]?.header, config, channel);
if (ORTHOGONAL_ORIENT[channel].includes(labelOrient)) {
// Row/Column with orthogonal labelOrient must use title to display labels
return assembleLabelTitle(facet[channel], channel, config);
}
}
}
return undefined;
}
public assembleMarks(): VgMarkGroup[] {
const {child} = this;
// If we facet by two dimensions, we need to add a cross operator to the aggregation
// so that we create all groups
const facetRoot = this.component.data.facetRoot;
const data = assembleFacetData(facetRoot);
const encodeEntry = child.assembleGroupEncodeEntry(false);
const title = this.assembleLabelTitle() || child.assembleTitle();
const style = child.assembleGroupStyle();
const markGroup = {
name: this.getName('cell'),
type: 'group',
...(title ? {title} : {}),
...(style ? {style} : {}),
from: {
facet: this.assembleFacet()
},
// TODO: move this to after data
sort: {
field: FACET_CHANNELS.map(c => this.facetSortFields(c)).flat(),
order: FACET_CHANNELS.map(c => this.facetSortOrder(c)).flat()
},
...(data.length > 0 ? {data} : {}),
...(encodeEntry ? {encode: {update: encodeEntry}} : {}),
...child.assembleGroup(assembleFacetSignals(this, []))
};
return [markGroup];
}
protected getMapping() {
return this.facet;
}
}