-
Notifications
You must be signed in to change notification settings - Fork 590
/
interval.ts
295 lines (266 loc) · 10.4 KB
/
interval.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
import {isObject, NewSignal, OnEvent, SignalValue, Stream} from 'vega';
import {array, stringValue} from 'vega-util';
import {SelectionCompiler, SelectionComponent, STORE, TUPLE, unitName} from '.';
import {GeoPositionChannel, LATITUDE, LONGITUDE, ScaleChannel, X, Y} from '../../channel';
import {warn} from '../../log';
import {hasContinuousDomain} from '../../scale';
import {BrushConfig, IntervalSelectionConfig, SelectionInitInterval, SELECTION_ID} from '../../selection';
import {duplicate, keys, vals} from '../../util';
import {UnitModel} from '../unit';
import {assembleInit} from './assemble';
import {SelectionProjection, TUPLE_FIELDS} from './project';
import scales from './scales';
export const BRUSH = '_brush';
export const SCALE_TRIGGER = '_scale_trigger';
const INIT = '_init';
export interface IntervalSelectionComponent {
type: 'id' | 'scaled';
mark: BrushConfig;
}
const interval: SelectionCompiler<'interval'> = {
defined: selCmpt => selCmpt.type === 'interval',
parse: (model, selCmpt, selDef) => {
const type = model.hasProjection ? 'id' : 'scaled';
const cfg = duplicate(model.config.selection.interval);
const def = {...(isObject(selDef.select) ? selDef.select : ({} as IntervalSelectionConfig))};
selCmpt.interval = {
type,
mark: {...cfg.mark, ...def.mark}
};
if (type === 'id') {
def.fields = [SELECTION_ID];
// Remap default x/y projection
if (model.hasProjection && !def.encodings) {
def.encodings = selDef.value ? (keys(selDef.value) as GeoPositionChannel[]) : [LONGITUDE, LATITUDE];
}
selDef.select = {type: 'interval', ...def};
}
if (selCmpt.translate && !scales.defined(selCmpt)) {
const filterExpr = `!event.item || event.item.mark.name !== ${stringValue(selCmpt.name + BRUSH)}`;
for (const evt of selCmpt.events) {
if (!evt.between) {
warn(`${evt} is not an ordered event stream for interval selections.`);
continue;
}
const filters = array((evt.between[0].filter ??= []));
if (filters.indexOf(filterExpr) < 0) {
filters.push(filterExpr);
}
}
}
},
signals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const tupleSg = name + TUPLE;
const channels = vals(selCmpt.project.hasChannel).filter(p => p.channel === X || p.channel === Y);
const init = selCmpt.init ? selCmpt.init[0] : null;
signals.push(
...channels.reduce((arr, proj) => arr.concat(channelSignals(model, selCmpt, proj, init && init[proj.index])), [])
);
if (selCmpt.interval.type === 'scaled') {
// Proxy scale reactions to ensure that an infinite loop doesn't occur
// when an interval selection filter touches the scale.
if (!scales.defined(selCmpt)) {
const triggerSg = name + SCALE_TRIGGER;
const scaleTriggers = channels.map(proj => {
const channel = proj.channel as 'x' | 'y';
const {data: dname, visual: vname} = proj.signals;
const scaleName = stringValue(model.scaleName(channel));
const scaleType = model.getScaleComponent(channel).get('type');
const toNum = hasContinuousDomain(scaleType) ? '+' : '';
return (
`(!isArray(${dname}) || ` +
`(${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ` +
`${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))`
);
});
signals.push({
name: triggerSg,
value: {},
on: [
{
events: channels.map(proj => ({scale: model.scaleName(proj.channel)})),
update: scaleTriggers.join(' && ') + ` ? ${triggerSg} : {}`
}
]
});
}
// Only add an interval to the store if it has valid data extents. Data extents
// are set to null if pixel extents are equal to account for intervals over
// ordinal/nominal domains which, when inverted, will still produce a valid datum.
const dataSignals = channels.map(proj => proj.signals.data);
const update = `unit: ${unitName(model)}, fields: ${name + TUPLE_FIELDS}, values`;
return signals.concat({
name: tupleSg,
...(init ? {init: `{${update}: ${assembleInit(init)}}`} : {}),
on: [
{
events: [{signal: dataSignals.join(' || ')}], // Prevents double invocation, see https://github.com/vega/vega/issues/1672.
update: `${dataSignals.join(' && ')} ? {${update}: [${dataSignals}]} : null`
}
]
});
} else {
const projection = stringValue(model.projectionName());
const {x, y} = selCmpt.project.hasChannel;
const xvname = x && x.signals.visual;
const yvname = y && y.signals.visual;
const xinit = init && init[x.index];
const yinit = init && init[y.index];
const bbox =
`[` +
`[${xvname ? xvname + '[0]' : '0'}, ${yvname ? yvname + '[0]' : '0'}],` +
`[${xvname ? xvname + '[1]' : 'width'}, ${yvname ? yvname + '[1]' : 'height'}]` +
`]`;
const intersect = `intersect(${bbox}, {markname: ${stringValue(model.getName('marks'))}}, unit.mark)`;
const base = `{unit: ${unitName(model)}, fields: [${name + TUPLE_FIELDS}[${selCmpt.project.selectionIdIdx}]]}`;
return [
{
name: name + INIT,
init: init
? `[scale(${projection}, [${xinit[0]}, ${yinit[0]}]), scale(${projection}, [${xinit[1]}, ${yinit[1]}])]`
: null
},
...signals,
{
name: tupleSg,
update: `vlSelectionTuples(${intersect}, ${base})`
}
];
}
},
marks: (model, selCmpt, marks) => {
const name = selCmpt.name;
const {x, y} = selCmpt.project.hasChannel;
const xvname = x && x.signals.visual;
const yvname = y && y.signals.visual;
const store = `data(${stringValue(selCmpt.name + STORE)})`;
// Do not add a brush if we're binding to scales.
if (scales.defined(selCmpt)) {
return marks;
}
const update: any = {
x: x !== undefined ? {signal: `${xvname}[0]`} : {value: 0},
y: y !== undefined ? {signal: `${yvname}[0]`} : {value: 0},
x2: x !== undefined ? {signal: `${xvname}[1]`} : {field: {group: 'width'}},
y2: y !== undefined ? {signal: `${yvname}[1]`} : {field: {group: 'height'}}
};
// If the selection is resolved to global, only a single interval is in
// the store. Wrap brush mark's encodings with a production rule to test
// this based on the `unit` property. Hide the brush mark if it corresponds
// to a unit different from the one in the store.
if (selCmpt.resolve === 'global') {
for (const key of keys(update)) {
update[key] = [
{
test: `${store}.length && ${store}[0].unit === ${unitName(model)}`,
...update[key]
},
{value: 0}
];
}
}
// Two brush marks ensure that fill colors and other aesthetic choices do
// not interefere with the core marks, but that the brushed region can still
// be interacted with (e.g., dragging it around).
const {fill, fillOpacity, cursor, ...stroke} = selCmpt.interval.mark;
const vgStroke = keys(stroke).reduce((def, k) => {
def[k] = [
{
test: [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`]
.filter(t => t)
.join(' && '),
value: stroke[k]
},
{value: null}
];
return def;
}, {});
return [
{
name: `${name + BRUSH}_bg`,
type: 'rect',
clip: true,
encode: {
enter: {
fill: {value: fill},
fillOpacity: {value: fillOpacity}
},
update: update
}
},
...marks,
{
name: name + BRUSH,
type: 'rect',
clip: true,
encode: {
enter: {
...(cursor ? {cursor: {value: cursor}} : {}),
fill: {value: 'transparent'}
},
update: {...update, ...vgStroke}
}
}
];
}
};
export default interval;
/**
* Returns the visual and data signals for an interval selection.
*/
function channelSignals(
model: UnitModel,
selCmpt: SelectionComponent<'interval'>,
proj: SelectionProjection,
init: SelectionInitInterval
): NewSignal[] {
const scaledInterval = selCmpt.interval.type === 'scaled';
const channel = proj.channel;
const vname = proj.signals.visual;
const scaleName = stringValue(scaledInterval ? model.scaleName(channel) : model.projectionName());
const scaled = (str: string) => `scale(${scaleName}, ${str})`;
const size = model.getSizeSignalRef(channel === X ? 'width' : 'height').signal;
const coord = `${channel}(unit)`;
const von = selCmpt.events.reduce((def: OnEvent[], evt: Stream) => {
return [
...def,
{events: evt.between[0], update: `[${coord}, ${coord}]`}, // Brush Start
{events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]`} // Brush End
];
}, []);
if (scaledInterval) {
const dname = proj.signals.data;
const hasScales = scales.defined(selCmpt);
const scale = model.getScaleComponent(channel as ScaleChannel);
const scaleType = scale ? scale.get('type') : undefined;
const vinit: SignalValue = init ? {init: assembleInit(init, true, scaled)} : {value: []};
// React to pan/zooms of continuous scales. Non-continuous scales
// (band, point) cannot be pan/zoomed and any other changes
// to their domains (e.g., filtering) should clear the brushes.
von.push({
events: {signal: selCmpt.name + SCALE_TRIGGER},
update: hasContinuousDomain(scaleType) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]`
});
return hasScales
? [{name: dname, on: []}]
: [
{name: vname, ...vinit, on: von},
{
name: dname,
...(init ? {init: assembleInit(init)} : {}), // Cannot be `value` as `init` may require datetime exprs.
on: [
{
events: {signal: vname},
update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})`
}
]
}
];
} else {
const initIdx = channel === X ? 0 : 1;
const initSg = selCmpt.name + INIT;
const vinit: SignalValue = init ? {init: `[${initSg}[0][${initIdx}], ${initSg}[1][${initIdx}]]`} : {value: []};
return [{name: vname, ...vinit, on: von}];
}
}