-
Notifications
You must be signed in to change notification settings - Fork 9
/
view.js
612 lines (547 loc) · 17.8 KB
/
view.js
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
import {
parseSizeDef,
FlexDimensions,
ZERO_FLEXDIMENSIONS,
} from "../utils/layout/flexLayout";
import Padding from "../utils/layout/padding";
import {
getCachedOrCall,
initPropertyCache,
invalidatePrefix,
} from "../utils/propertyCacher";
import { isNumber, isString, span } from "vega-util";
import { scaleLog } from "d3-scale";
import { isFieldDef, getPrimaryChannel } from "../encoder/encoder";
import { appendToBaseUrl } from "../utils/url";
import { isDiscrete, bandSpace } from "vega-scale";
import { peek } from "../utils/arrayUtils";
// TODO: View classes have too many responsibilities. Come up with a way
// to separate the concerns. However, most concerns are tightly tied to
// the hierarchy, which makes the separation quite tricky.
// Separation of concerns would also make the code more easily testable.
/** Skip children */
export const VISIT_SKIP = "VISIT_SKIP";
/** Stop further visits */
export const VISIT_STOP = "VISIT_STOP";
/** @type {function(number):number} */
const defaultOpacityFunction = (parentOpacity) => parentOpacity;
/**
* @typedef {import("../spec/channel").Channel} Channel
* @typedef {import("../spec/channel").ChannelDef} ChannelDef
* @typedef {import("../spec/view").ViewSpec} ViewSpec
* @typedef {import("./viewUtils").ViewContext} ViewContext
* @typedef {import("../utils/layout/flexLayout").SizeDef} SizeDef
* @typedef {import("../utils/layout/flexLayout").LocSize} LocSize
*
* @typedef {import("../spec/view").ResolutionTarget} ResolutionTarget
* @typedef {import("./scaleResolution").default} ScaleResolution
* @typedef {import("./axisResolution").default} AxisResolution
*
* @typedef {VISIT_SKIP|VISIT_STOP|void} VisitResult
*
* @callback VisitorCallback
* @param {View} view
* @returns {VisitResult}
*
* @typedef {VisitorCallback & {
* postOrder?: function(View):void,
* beforeChildren?: function(View):void,
* afterChildren?: function(View):void}
* } Visitor
*
* @typedef {object} BroadcastMessage
* @prop {string} type Broadcast type
* @prop {any} [payload] Anything
*
* @typedef {import("./rendering").RenderingOptions} RenderingOptions
*
* @callback InteractionEventListener
* @param {import("../utils/layout/rectangle").default} coords
* Coordinates of the view
* @param {import("../utils/interactionEvent").default} event
*/
export default class View {
/**
*
* @param {ViewSpec} spec
* @param {ViewContext} context
* @param {import("./containerView").default} parent
* @param {string} name
*/
constructor(spec, context, parent, name) {
this.context = context;
this.parent = parent;
this.name = spec.name || name;
this.spec = spec;
this.resolutions = {
/**
* Channel-specific scale resolutions
* @type {Partial<Record<Channel, import("./scaleResolution").default>>}
*/
scale: {},
/**
* Channel-specific axis resolutions
* @type {Partial<Record<import("../spec/channel").PrimaryPositionalChannel, import("./axisResolution").default>>}
*/
axis: {},
};
/** @type {Record<string, (function(BroadcastMessage):void)[]>} */
this._broadcastHandlers = {};
/** @type {Record<string, InteractionEventListener[]>} */
this._capturingInteractionEventListeners = {};
/** @type {Record<string, InteractionEventListener[]>} */
this._nonCapturingInteractionEventListeners = {};
initPropertyCache(this);
/** @type {function(number):number} */
this.opacityFunction = defaultOpacityFunction;
/**
* Don't inherit encodings from parent.
* TODO: Make configurable through spec. Allow more fine-grained control.
*/
this.blockEncodingInheritance = false;
}
getPadding() {
return this._cache("size/padding", () =>
Padding.createFromConfig(this.spec.padding)
);
}
/**
* Returns a padding that indicates how much axes and titles extend over the plot area.
*
* @returns {Padding}
*/
getOverhang() {
return Padding.zero();
}
/**
* Returns the configured size, if present. Otherwise a computed or default
* height is returned.
*
* @returns {FlexDimensions}
*/
getSize() {
return this._cache("size/size", () =>
this.isVisible()
? this.getSizeFromSpec().addPadding(this.getPadding())
: ZERO_FLEXDIMENSIONS
);
}
/**
* @return {FlexDimensions}
*/
getSizeFromSpec() {
/**
* @param {"width" | "height"} dimension
* @return {SizeDef}
*/
const handleSize = (dimension) => {
let value = this.spec[dimension];
if (isStepSize(value)) {
const stepSize = value.step;
const scale = this.getScaleResolution(
dimension == "width" ? "x" : "y"
)?.getScale();
if (scale) {
// Note: this and all ancestral views need to be refreshed when the domain is changed.
let steps = 0;
if (isDiscrete(scale.type)) {
steps = scale.domain().length;
} else if (["locus", "index"].includes(scale.type)) {
const domain = scale.domain();
steps = peek(domain) - domain[0];
} else {
throw new Error(
`Cannot use step-based size with "${scale.type}" scale!`
);
}
// TODO: Type guards maybe?
const _scale =
/** @type {import("d3-scale").ScaleBand<any> | import("../genome/scaleLocus").ScaleLocus | import("../genome/scaleIndex").ScaleIndex} */ (
scale
);
steps = bandSpace(
steps,
_scale.paddingInner(),
_scale.paddingOuter()
);
return { px: steps * stepSize, grow: 0 };
} else {
throw new Error(
"Cannot use 'step' size with missing scale!"
);
}
} else {
return (value && parseSizeDef(value)) ?? { px: 0, grow: 1 };
}
};
return this._cache(
"size/sizeFromSpec",
() => new FlexDimensions(handleSize("width"), handleSize("height"))
);
}
isVisible() {
return this.context.isViewVisible(this);
}
isVisibleInSpec() {
return this.spec.visible ?? true;
}
/**
* Returns the effective opacity of this view, e.g., view's opacity multiplied
* by opacities of its ancestors.
*
* TODO: This methods makes sense only in Unit and Layer views.
*
* @returns {number}
*/
getEffectiveOpacity() {
return this.opacityFunction(this.parent?.getEffectiveOpacity() ?? 1.0);
}
getPathString() {
return [...this.getAncestors()]
.map((v) => v.name)
.reverse()
.join("/");
}
*getAncestors() {
// eslint-disable-next-line consistent-this
let view = /** @type {View} */ (this);
do {
yield view;
view = view.parent;
} while (view);
}
/**
* Handles a broadcast message that is intended for the whole view hierarchy.
*
* @param {BroadcastMessage} message
*/
handleBroadcast(message) {
// TODO: message types should be constants
for (const handler of this._broadcastHandlers[message.type] || []) {
handler(message);
}
}
/**
*
* @param {string} type
* @param {function(BroadcastMessage):void} handler
*/
_addBroadcastHandler(type, handler) {
let handlers = this._broadcastHandlers[type];
if (!handlers) {
handlers = [];
this._broadcastHandlers[type] = handlers;
}
handlers.push(handler);
}
/**
* Handles an interactionEvent
*
* @param {import("../utils/layout/rectangle").default} coords
* Coordinates of the view
* @param {import("../utils/interactionEvent").default} event
* @param {boolean} capturing
*/
handleInteractionEvent(coords, event, capturing) {
const listenersByType = capturing
? this._capturingInteractionEventListeners
: this._nonCapturingInteractionEventListeners;
for (const listener of listenersByType[event.type] || []) {
listener(coords, event);
}
}
/**
* Add an "interaction" event listener that mimics DOM's event model inside
* the view hierarchy.
*
* This is intended for GenomeSpy's internal use. It allows the views to handle
* low level interactions such as dragging, wheeling, etc.
*
* @param {string} type
* @param {InteractionEventListener} listener
* @param {boolean} [useCapture]
*/
addInteractionEventListener(type, listener, useCapture) {
const listenersByType = useCapture
? this._capturingInteractionEventListeners
: this._nonCapturingInteractionEventListeners;
let listeners = listenersByType[type];
if (!listeners) {
listeners = [];
listenersByType[type] = listeners;
}
listeners.push(listener);
}
/**
* Visits child views in depth-first order. Visitor's return value
* controls the traversal.
*
* @param {Visitor} visitor
* @returns {VisitResult}
*
*/
visit(visitor) {
try {
const result = visitor(this);
if (visitor.postOrder) {
visitor.postOrder(this);
}
if (result !== VISIT_STOP) {
return result;
}
} catch (e) {
// Augment the exception with the view
e.view = this;
throw e;
}
}
/**
* Called after all scales in the view hierarchy have been resolved.
*/
onScalesResolved() {
// Only set the opacity function once. The idea is to allow custom functions
// and prevent accidental overwrites.
if (
!this.opacityFunction ||
this.opacityFunction === defaultOpacityFunction
) {
this.opacityFunction = createViewOpacityFunction(this);
}
}
/**
* ViewRenderingContext calls this method once for each view during each rendering
* pass. The order is depth first, pre order.
*/
onBeforeRender() {
//
}
/**
* Recursively traverses the view hierarchy, computes the view coordinates,
* and coordinates the mark rendering.
*
* @param {import("./renderingContext/viewRenderingContext").default} context
* @param {import("../utils/layout/rectangle").default} coords The coordinate rectangle that the parent computed
* for the child that is being visited.
* @param {RenderingOptions} [options]
*/
render(context, coords, options = {}) {
// override
}
/**
* Returns the encodings specified in this view combined with the inherited
* encodings. However, this does not contain any defaults or inferred/adjusted/fixed
* encodings. Those are available in Mark's encoding property.
*
* @return {import("../spec/channel").Encoding}
*/
getEncoding() {
const pe =
this.parent && !this.blockEncodingInheritance
? this.parent.getEncoding()
: {};
const te = this.spec.encoding || {};
/** @type {import("../spec/channel").Encoding} */
const combined = {
...pe,
...te,
};
for (const [channel, channelDef] of Object.entries(combined)) {
if (channelDef === null) {
// Prevent propagation
delete combined[channel];
}
}
return combined;
}
/**
* @param {View} [whoIsAsking] Passed to the immediate parent. Allows for
* selectively breaking the inheritance.
* @return {function(object):any}
*/
getFacetAccessor(whoIsAsking) {
if (this.parent) {
return this.parent.getFacetAccessor(this);
}
}
/**
* Returns the fields that should be used for partitioning the data for facets.
*
* @param {View} [whoIsAsking]
* @returns {string[]}
*/
getFacetFields(whoIsAsking) {
const sampleFieldDef = this.getEncoding().sample;
if (isFieldDef(sampleFieldDef)) {
return [sampleFieldDef.field];
} else {
return this.parent?.getFacetFields(this);
}
}
/**
* Returns a texture that has a mapping for the sample locations. This is implemented
* only in the SampleView of GenomeSpy App.
*
* @returns {WebGLTexture}
*/
getSampleFacetTexture() {
return undefined;
}
/**
*
* @param {Channel} channel
* @param {ResolutionTarget} type
* @returns {ScaleResolution | AxisResolution}
*/
_getResolution(channel, type) {
channel = getPrimaryChannel(channel);
/** @type {import("./view").default } */
// eslint-disable-next-line consistent-this
let view = this;
do {
const resolution = view.resolutions[type][channel];
if (resolution) {
return resolution;
}
view = view.parent;
} while (view);
}
/**
* @param {Channel} channel
*/
getScaleResolution(channel) {
return /** @type {ScaleResolution} */ (
this._getResolution(channel, "scale")
);
}
/**
* @param {Channel} channel
*/
getAxisResolution(channel) {
return /** @type {AxisResolution} */ (
this._getResolution(channel, "axis")
);
}
/**
* @returns {string}
*/
getBaseUrl() {
return appendToBaseUrl(
() => this.parent?.getBaseUrl(),
this.spec.baseUrl
);
}
/**
* @returns {import("../data/sources/dataSource").default}
*/
getDynamicDataSource() {
throw new Error("The view does not provide dynamic data!");
}
/**
* Returns `true` if this view and its children supports picking.
*/
isPickingSupported() {
return true;
}
getTitleText() {
const title = this.spec.title;
if (title) {
return isString(title) ? title : title.text;
}
}
/**
* @param {any} key string
* @param {function(key?):T} callable A function that produces a value to be cached
* @returns {T}
* @template T
*/
_cache(key, callable) {
return getCachedOrCall(this, key, callable);
}
/**
*
* @param {string} key
* @param {"self" | "progeny" | "ancestors"} [direction]
*/
_invalidateCacheByPrefix(key, direction = "self") {
switch (direction) {
case "self":
invalidatePrefix(this, key);
break;
case "ancestors":
for (const view of this.getAncestors()) {
invalidatePrefix(view, key);
}
break;
case "progeny":
this.visit((view) => invalidatePrefix(view, key));
break;
default:
}
}
invalidateSizeCache() {
this._invalidateCacheByPrefix("size/", "ancestors");
}
/**
* Broadcasts a message to views that include the given (x, y) point.
* This is mainly intended for mouse events.
*
* @param {import("../utils/interactionEvent").default} event
*/
propagateInteractionEvent(event) {
// Subclasses must implement proper handling
}
}
/**
*
* @param {any} opacity
* @returns {opacity is import("../spec/view").DynamicOpacity}
*/
function isDynamicOpacity(opacity) {
return "unitsPerPixel" in opacity;
}
/**
*
* @param {View} view
* @returns {function(number):number}
*/
function createViewOpacityFunction(view) {
const opacityDef = view.spec.opacity;
if (opacityDef !== undefined) {
if (isNumber(opacityDef)) {
return (parentOpacity) => parentOpacity * opacityDef;
} else if (isDynamicOpacity(opacityDef)) {
/** @type {function(Channel):any} */
const getScale = (channel) => {
const scale = view.getScaleResolution(channel)?.getScale();
// Only works on linear scales
if (["linear", "index", "locus"].includes(scale?.type)) {
return scale;
}
};
const scale = opacityDef.channel
? getScale(opacityDef.channel)
: getScale("x") || getScale("y");
if (!scale) {
throw new Error(
"Cannot find a resolved quantitative scale for dynamic opacity!"
);
}
const interpolate = scaleLog()
.domain(opacityDef.unitsPerPixel)
.range(opacityDef.values)
.clamp(true);
return (parentOpacity) => {
const rangeSpan = 1000; //TODO: span(scale.range());
const unitsPerPixel = span(scale.domain()) / rangeSpan;
return interpolate(unitsPerPixel) * parentOpacity;
};
}
}
return (parentOpacity) => parentOpacity;
}
/**
*
* @param {any} size
* @return {size is import("../spec/view").Step}
*/
export const isStepSize = (size) => !!size?.step;