Repository navigation
Expand file tree
/
Copy pathTimelineVisualisation.ts
More file actions
361 lines (306 loc) · 9.3 KB
/
Copy pathTimelineVisualisation.ts
File metadata and controls
361 lines (306 loc) · 9.3 KB
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
import * as d3 from 'd3';
import Scene from '../lib/Scene';
import CanvasCursor from '../lib/CanvasCursor';
import TimelineEvent from './TimelineEvent';
import SmoothTransform from '../lib/SmoothTransform';
import PointerTracker from '../lib/PointerTracker';
import { showModal, notifyVisibilityChange, Offset, Pair, throttle, cssVar } from '../utils';
import { Ticks } from './Ticks';
interface TimelineVisualisationConfig {
container: HTMLElement;
events: Array<TimelineEvent>;
}
/**
* A reverse flamechart visualisation.
* Features:
* - Detects user scroll attempts on mobile
* and prevents event capturing
* - Smooth zooming
* - Supports basic hit-tests for interacting with rendered data.
* - Rendering is automatically paused when the container is
* scrolled off-screen.
*/
export default class TimelineVisualisation {
/**
* Desired visualisation height,
* kept static for simplicity.
*/
static height = 500;
/**
* Desired scale extent, minimal
* and maximum levels of zoom allowed.
*/
static scaleExtent: [number, number] = [1, 100];
/**
* Holds the reference to the configuration
* of the component
*/
config: TimelineVisualisationConfig;
/**
* Rendering scene, holding drawable components
* of the visualisation and orchestrating the render pipeline
*/
scene: Scene;
/**
* Virtual cursor to track mouse position and perform
* the hit testing within the visualisation
*/
cursor: CanvasCursor;
/**
* A component allowing to detect the scroll
* attempt on mobile devices
*/
tracker: PointerTracker;
/**
* Interpolated zoom transform, smoothly changing
* its value, instead of quantified steps.
*/
smoothTransform: SmoothTransform;
/**
* Holds a reference to timeline ticks,
* denoting particular dates over X axis
*/
ticks: Ticks;
/**
* Rendering context of the canvas of the visualisation.
*/
ctx: CanvasRenderingContext2D;
/**
* Holds the chronological range of
* the visualisation.
*/
timeScale: d3.ScaleTime<number, number>;
/**
* D3 zoom used to source events for
* performing smooth zooming.
*/
zoom: d3.ZoomBehavior<Element, unknown>;
/**
* Holds the render target.
*/
canvas: d3.Selection<HTMLCanvasElement, unknown, null, undefined>;
/**
* Holds the visualisation nodes,
* incl. canvas and scroll detection overlay.
*/
container: d3.Selection<HTMLElement, unknown, null, undefined>;
/**
* Flags whether rendering cycle is paused or running.
*/
paused = true;
/**
* Width of the available viewport in logical pixels.
*/
width = 0;
/**
* Height of the available viewport in logical pixels.
*/
height = 500;
constructor(config: TimelineVisualisationConfig) {
this.config = config;
this.scene = new Scene();
this.cursor = new CanvasCursor();
this.smoothTransform = new SmoothTransform();
this.tracker = new PointerTracker();
}
/**
* Initialises all the components required
* for the visualisation to run.
*/
start() {
this.container = d3.select(this.config.container);
this.width = this.config.container.getBoundingClientRect().width;
this.height = (Math.max(...this.config.events.map(e => e.config.depth)) + 1) * TimelineEvent.lineHeight;
const domain: Pair<Date, Date> = [this.firstEvent.config.start, new Date()];
// Range from the earliest event till now
// mapped to the visualisation viewport.
this.timeScale = d3.scaleTime().domain(domain).range([0, this.width]);
this.zoom = d3
.zoom()
.scaleExtent(TimelineVisualisation.scaleExtent)
.translateExtent(this.translateExtent)
.on('zoom', this.onZoom.bind(this));
// Adding events to the scene
this.config.events.forEach((event) => {
event.applyScale(this.timeScale);
event.transform = this.smoothTransform;
this.scene.add(event);
});
// Generate date scale ticks
this.ticks = Ticks.forRange(domain)
.scale(this.timeScale)
.applyTransform(this.smoothTransform)
.baseline(this.height);
this.scene.add(this.ticks);
this.canvas = d3
.select(this.config.container)
.append('canvas')
.lower()
.attr('width', this.width * this.dpr)
.attr('height', this.height * this.dpr)
.style('width', `${this.width}px`)
.style('height', `${this.height}px`);
this.container
.on('pointermove', (e) => {
this.cursor.moveTo([e.layerX, e.layerY]);
})
.on('click', (e) => {
this.cursor.moveTo([e.layerX, e.layerY]);
this.cursor.isDown = true;
})
.on('mouseout touchend', () => {
this.cursor.hide();
})
.call(this.zoom)
.style('touch-action', 'auto')
.style('height', `${this.height}px`)
.select('.scroller')
.call(this.tracker.attach);
this.ctx = this.canvas.node().getContext('2d');
this.ctx.scale(this.dpr, this.dpr);
this.scene.add(this.cursor);
this.draw();
// Pause the visualistaion when off-screen.
notifyVisibilityChange(
this.container.node(),
this.onVisibilityChanged.bind(this)
);
window.addEventListener('resize', throttle(this.onResize.bind(this), 500));
}
/**
* Renders current state of the visualisation to the canvas.
*/
draw() {
if (!this.paused) {
this.smoothTransform.tick();
this.clear();
this.scene.draw(this.ctx);
this.processInteractions();
}
window.requestAnimationFrame(this.draw.bind(this));
}
/**
* Clears the canvas by rendering the clear rect.
*/
clear() {
this.ctx.clearRect(0, 0, this.width, this.height);
}
/**
* Performs hit testing of the events
* and currently captured cursor position.
*/
processInteractions() {
for (const event of this.config.events) {
const isHovered = this.cursor.isOver(event.boundingRect);
const isTriggered = isHovered && this.cursor.isDown;
if (isTriggered) {
this.onEventTriggered(event);
// Only capture the very first hit
// to avoid multiple events triggered at the same time.
break;
}
}
// Reset cursor regardless its current status
// to avoid triggering events the next frame.
this.cursor.isDown = false;
}
/**
* Highlights event nodes with given tag,
* by 'muting' the rest of the events.
*
* @param tag - Tag to highlight.
*/
highlight(tag: string | null): void {
for (const event of this.config.events) {
const hasTag = event.config.tags.includes(tag) || tag === null;
// Initial/mute based on the selection
const color = hasTag ? event.config.color : (cssVar('--color-timeline-muted') || 'rgba(0, 0, 0, .05)');
event.color.setValue(color);
}
}
/**
* Handles {this.zoom} events by propagating
* desired new transform to the interpolated transform container.
*/
onZoom(e) {
this.smoothTransform.targetTransform = e.transform;
}
/**
* Performs a zoom in to the boundaries of a gieven event.
*
* @param event - one of the events passed to visualisation.
*/
zoomIn(event: TimelineEvent) {
// The scale of event in the unit coordinate system.
const scale = (event.endX - event.startX) / this.width;
this.container.call(
this.zoom.transform,
// Applying translate in the unit coords and then reversed scale
// for an event to take the whole viewport.
d3.zoomIdentity.scale(1 / scale).translate(-event.startX, 0)
);
}
/**
* Handles visualisation visibility change
* by pausing/unpausing when necessary.
*
* @param isVisible - whether the visualisation is currently visible on screen.
*/
onVisibilityChanged(isVisible) {
this.paused = !isVisible;
}
/**
* Handles trigger of the given event
* by opening a modal with event contents and
* pausing the render cycle whilst it's open.
*
* @param event - event which was triggered.
*/
onEventTriggered(event: TimelineEvent) {
this.paused = true;
showModal(event.config.id, {
onClose: () => (this.paused = false),
});
}
onResize() {
this.width = this.config.container.getBoundingClientRect().width;
this.canvas
.attr('width', this.width * this.dpr)
.attr('height', this.height * this.dpr)
.style('width', `${this.width}px`)
.style('height', `${this.height}px`);
this.ctx.scale(this.dpr, this.dpr);
this.zoom.translateExtent(this.translateExtent);
this.timeScale.range([0, this.width]);
this.ticks.scale(this.timeScale).baseline(this.height);
this.config.events.forEach((event) => event.applyScale(this.timeScale));
this.container.call(this.zoom.transform, d3.zoomIdentity);
}
/**
* Returns the first event to be rendered.
* Used as the chronological boundary for the time scale.
*/
get firstEvent(): TimelineEvent {
return this.config.events[0];
}
/**
* Current device pixel ratio,
* to be used for determining the proper Canvas scaling factor.
*/
get dpr(): number {
return window.devicePixelRatio || 1;
}
/**
* Current viewport size.
*/
get viewport(): Offset {
return [this.width, this.height];
}
/**
* Returns current possible translation
* boundaries as allowed by current viewport dimensions.
*/
get translateExtent(): [Offset, Offset] {
return [[0, 0], this.viewport];
}
}