/
Map.tsx
640 lines (500 loc) · 23.2 KB
/
Map.tsx
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
import React, {createRef} from "react";
import {RawMapData, RawMapEntityType} from "../api";
import {MapLayerManager} from "./MapLayerManager";
import {PathDrawer} from "./PathDrawer";
import {TouchHandler} from "./utils/touch_handling/TouchHandler";
import StructureManager from "./StructureManager";
import {Box, styled, Theme} from "@mui/material";
import SegmentLabelMapStructure from "./structures/map_structures/SegmentLabelMapStructure";
import semaphore from "semaphore";
import {convertNumberToRoman} from "../utils";
import {Canvas2DContextTrackingWrapper} from "./utils/Canvas2DContextTrackingWrapper";
import {TapTouchHandlerEvent} from "./utils/touch_handling/events/TapTouchHandlerEvent";
import {PanStartTouchHandlerEvent} from "./utils/touch_handling/events/PanStartTouchHandlerEvent";
import {PanMoveTouchHandlerEvent} from "./utils/touch_handling/events/PanMoveTouchHandlerEvent";
import {PanEndTouchHandlerEvent} from "./utils/touch_handling/events/PanEndTouchHandlerEvent";
import {PinchStartTouchHandlerEvent} from "./utils/touch_handling/events/PinchStartTouchHandlerEvent";
import {PinchMoveTouchHandlerEvent} from "./utils/touch_handling/events/PinchMoveTouchHandlerEvent";
import {PinchEndTouchHandlerEvent} from "./utils/touch_handling/events/PinchEndTouchHandlerEvent";
import {PointCoordinates} from "./utils/types";
import create from "zustand";
export interface MapProps {
rawMap: RawMapData;
theme: Theme;
trackSegmentSelectionOrder?: boolean;
}
export interface MapState {
selectedSegmentIds: Array<string>
}
export const usePendingMapAction = create<{
hasPendingMapAction: boolean
}>()(() => {
return {
hasPendingMapAction: false
};
});
const Container = styled(Box)({
position: "relative",
height: "100%",
width: "100%",
});
const SCROLL_PARAMETERS = {
ZOOM_IN_MULTIPLIER: 4/3 - 1,
ZOOM_OUT_MULTIPLIER: 1 - 3/4,
PIXELS_PER_FULL_STEP: 100
};
class Map<P, S> extends React.Component<P & MapProps, S & MapState > {
protected readonly canvasRef: React.RefObject<HTMLCanvasElement>;
protected structureManager: StructureManager;
protected mapLayerManager: MapLayerManager;
protected canvas!: HTMLCanvasElement;
protected ctxWrapper!: Canvas2DContextTrackingWrapper;
protected readonly resizeListener: () => void;
protected readonly visibilityStateChangeListener: () => void;
protected drawableComponents: Array<CanvasImageSource> = [];
protected drawableComponentsMutex: semaphore.Semaphore = semaphore(1); //Required to sync up with the render webWorker
protected currentScaleFactor = 1;
//TODO: understand wtf is going on there and replace with better state variables than this hack
protected touchHandlingState: any = {};
protected activeTouchEvent = false;
protected activeScrollEvent = false;
protected pendingInternalDrawableStateUpdate = false;
protected scrollTimeout: NodeJS.Timeout | undefined;
constructor(props : MapProps) {
super(props as Readonly<P & MapProps>);
this.canvasRef = createRef();
this.structureManager = new StructureManager();
this.structureManager.setPixelSize(this.props.rawMap.pixelSize);
this.mapLayerManager = new MapLayerManager();
this.state = {
selectedSegmentIds: [] as Array<string>
} as Readonly<S & MapState>;
this.resizeListener = () => {
// Save the current transformation and recreate it
// as the transformation state is lost when changing canvas size
// https://stackoverflow.com/questions/48044951/canvas-state-lost-after-changing-size
const {a, b, c, d, e, f} = this.ctxWrapper.getTransform();
//Ignore weirdness related to the URL bar on Firefox mobile
if (this.canvas.clientWidth === 0 || this.canvas.clientHeight === 0) {
return;
}
this.canvas.height = this.canvas.clientHeight;
this.canvas.width = this.canvas.clientWidth;
this.ctxWrapper.setTransform(a, b, c, d, e, f);
this.draw();
};
this.visibilityStateChangeListener = () => {
if (this.pendingInternalDrawableStateUpdate && document.visibilityState === "visible") {
this.pendingInternalDrawableStateUpdate = false;
this.updateInternalDrawableState();
}
};
}
componentDidMount(): void {
this.canvas = this.canvasRef.current!;
this.canvas.height = this.canvas.clientHeight;
this.canvas.width = this.canvas.clientWidth;
this.ctxWrapper = new Canvas2DContextTrackingWrapper(this.canvas.getContext("2d")!);
this.registerCanvasInteractionHandlers();
window.addEventListener("resize", this.resizeListener);
document.addEventListener("visibilitychange", this.visibilityStateChangeListener);
const boundingBox = {
minX: this.props.rawMap.size.x / this.props.rawMap.pixelSize,
minY: this.props.rawMap.size.y / this.props.rawMap.pixelSize,
maxX: 0,
maxY: 0
};
this.props.rawMap.layers.forEach(l => {
if (l.dimensions.x.min < boundingBox.minX) {
boundingBox.minX = l.dimensions.x.min;
}
if (l.dimensions.y.min < boundingBox.minY) {
boundingBox.minY = l.dimensions.y.min;
}
if (l.dimensions.x.max > boundingBox.maxX) {
boundingBox.maxX = l.dimensions.x.max;
}
if (l.dimensions.y.max > boundingBox.maxY) {
boundingBox.maxY = l.dimensions.y.max;
}
});
const initialScalingFactor = Math.min(
this.canvas.width / ((boundingBox.maxX - boundingBox.minX)*1.1),
this.canvas.height / ((boundingBox.maxY - boundingBox.minY)*1.1)
);
const initialxOffset = (this.canvas.width - (boundingBox.maxX - boundingBox.minX)*initialScalingFactor) / 2;
const initialyOffset = (this.canvas.height - (boundingBox.maxY - boundingBox.minY)*initialScalingFactor) / 2;
this.ctxWrapper.translate(initialxOffset, initialyOffset);
this.currentScaleFactor = initialScalingFactor;
this.ctxWrapper.scale(initialScalingFactor, initialScalingFactor);
this.ctxWrapper.translate(-boundingBox.minX, -boundingBox.minY);
this.updateInternalDrawableState();
usePendingMapAction.setState({hasPendingMapAction: false});
}
componentDidUpdate(prevProps: Readonly<MapProps>, prevState: Readonly<MapState>): void {
if (prevProps.rawMap.metaData.nonce !== this.props.rawMap.metaData.nonce) {
this.onMapUpdate();
/**
* If we're not visible, we do not need to render map updates as no one would see those anyway
* We also cannot update the map data while someone interacts with it as that causes jank
*/
if (
document.visibilityState !== "visible" ||
this.activeTouchEvent ||
this.activeScrollEvent
) {
this.pendingInternalDrawableStateUpdate = true;
} else {
this.updateInternalDrawableState();
}
} else if (this.props.theme.palette.mode !== prevProps.theme.palette.mode) {
this.updateInternalDrawableState();
}
}
protected onMapUpdate() : void {
//This can be overridden to do something when the map is updated with a new one
}
componentWillUnmount(): void {
window.removeEventListener("resize", this.resizeListener);
document.removeEventListener("visibilitychange", this.visibilityStateChangeListener);
usePendingMapAction.setState({hasPendingMapAction: false});
}
protected updateInternalDrawableState() : void {
this.structureManager.setPixelSize(this.props.rawMap.pixelSize);
this.updateDrawableComponents().then(() => {
this.draw();
});
}
protected redrawLayers() : void {
this.mapLayerManager.draw(this.props.rawMap, this.props.theme).then(() => {
this.draw();
});
}
render(): JSX.Element {
return (
<Container style={{overflow: "hidden"}}>
<canvas
ref={this.canvasRef}
style={{
width: "100%",
height: "100%",
imageRendering: "crisp-edges"
}}
/>
{this.renderAdditionalElements()}
</Container>
);
}
protected renderAdditionalElements() : JSX.Element {
return <></>;
}
protected updateDrawableComponents(): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.drawableComponentsMutex.take(async () => {
this.drawableComponents = [];
await this.mapLayerManager.draw(this.props.rawMap, this.props.theme);
this.drawableComponents.push(this.mapLayerManager.getCanvas());
const pathsImage = await PathDrawer.drawPaths( {
paths: this.props.rawMap.entities.filter(e => {
return e.type === RawMapEntityType.Path || e.type === RawMapEntityType.PredictedPath;
}),
mapWidth: this.props.rawMap.size.x,
mapHeight: this.props.rawMap.size.y,
pixelSize: this.props.rawMap.pixelSize,
paletteMode: this.props.theme.palette.mode,
});
this.drawableComponents.push(pathsImage);
this.structureManager.updateMapStructuresFromMapData(this.props.rawMap);
this.updateState();
this.drawableComponentsMutex.leave();
resolve();
});
});
}
protected updateState() : void {
const currentSegmentLabelStructures = this.structureManager.getMapStructures().filter(s => {
return s.type === SegmentLabelMapStructure.TYPE;
}) as Array<SegmentLabelMapStructure>;
const previouslySelectedSegmentIds = this.state.selectedSegmentIds;
const currentlySelectedSegmentIds = currentSegmentLabelStructures.filter(s => {
return s.selected;
}).map(s => {
return s.id;
});
// This ensures that we keep the order in which segments were selected by the user
const updatedSelectedSegmentIds = [
...previouslySelectedSegmentIds.filter(id => { //Take existing ones excluding those, which aren't selected anymore
return currentlySelectedSegmentIds.includes(id);
}),
...currentlySelectedSegmentIds.filter(id => { //Append all IDs that weren't part of the previous array
return !previouslySelectedSegmentIds.includes(id);
})
];
if (this.props.trackSegmentSelectionOrder === true) {
currentSegmentLabelStructures.forEach(s => {
const idx = updatedSelectedSegmentIds.indexOf(s.id);
if (idx >= 0) {
s.topLabel = convertNumberToRoman(idx + 1);
} else {
s.topLabel = undefined;
}
});
}
this.mapLayerManager.setSelectedSegmentIds(updatedSelectedSegmentIds);
this.setState({
selectedSegmentIds: updatedSelectedSegmentIds,
} as S & MapState);
}
protected draw() : void {
window.requestAnimationFrame(() => {
this.drawableComponentsMutex.take(() => {
const ctx = this.ctxWrapper.getContext();
this.ctxWrapper.save();
this.ctxWrapper.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctxWrapper.restore();
ctx.imageSmoothingEnabled = false;
this.drawableComponents.forEach(c => {
ctx.drawImage(c, 0, 0);
});
ctx.imageSmoothingEnabled = true;
/**
* Carries out a drawing routine on the canvas with resetting the scaling / translation of the canvas
* and restoring it afterwards.
* This allows for drawing equally thick lines no matter what the zoomlevel of the canvas currently is.
*
*/
const transformationMatrixToScreenSpace = this.ctxWrapper.getTransform();
this.ctxWrapper.save();
this.ctxWrapper.setTransform(1, 0, 0, 1, 0, 0);
this.structureManager.getMapStructures().forEach(s => {
s.draw(
this.ctxWrapper,
transformationMatrixToScreenSpace,
this.currentScaleFactor,
this.structureManager.getPixelSize()
);
});
this.structureManager.getClientStructures().forEach(s => {
s.draw(
this.ctxWrapper,
transformationMatrixToScreenSpace,
this.currentScaleFactor,
this.structureManager.getPixelSize()
);
});
this.ctxWrapper.restore();
this.drawableComponentsMutex.leave();
});
});
}
protected getCurrentViewportCenterCoordinatesInPixelSpace() : PointCoordinates {
return this.ctxWrapper.mapPointToCurrentTransform(this.canvas.width/2, this.canvas.height/2);
}
protected onTap(evt: TapTouchHandlerEvent) : boolean | void {
const currentTransform = this.ctxWrapper.getTransform();
const {x, y} = this.relativeCoordinatesToCanvas(evt.x0, evt.y0);
const tappedPointInMapSpace = this.ctxWrapper.mapPointToCurrentTransform(x, y);
const tappedPointInScreenSpace = new DOMPoint(tappedPointInMapSpace.x, tappedPointInMapSpace.y).matrixTransform(currentTransform);
let drawRequested = false;
const clientStructuresHandledTap = this.structureManager.getClientStructures().some(structure => {
const result = structure.tap(tappedPointInScreenSpace, currentTransform);
if (result.requestDraw === true) {
drawRequested = true;
}
if (result.stopPropagation) {
if (result.deleteMe === true) {
this.structureManager.removeClientStructure(structure);
}
this.updateState();
this.draw();
return true;
} else {
return false;
}
});
if (clientStructuresHandledTap) {
return true;
}
//only draw if any structure was changed
let didUpdateStructures = false;
this.structureManager.getClientStructures().forEach(s => {
if (s.active) {
didUpdateStructures = true;
}
s.active = false;
});
if (didUpdateStructures || drawRequested) {
this.draw();
}
}
protected onScroll(evt: WheelEvent) : void {
this.activeScrollEvent = true;
if (this.scrollTimeout) {
clearTimeout(this.scrollTimeout);
}
this.scrollTimeout = setTimeout(() => {
this.activeScrollEvent = false;
if (this.pendingInternalDrawableStateUpdate && !this.activeTouchEvent) {
this.pendingInternalDrawableStateUpdate = false;
this.updateInternalDrawableState();
}
}, 250);
const fullStep = evt.deltaY < 0 ? SCROLL_PARAMETERS.ZOOM_IN_MULTIPLIER : SCROLL_PARAMETERS.ZOOM_OUT_MULTIPLIER;
const factor = 1 - (fullStep * (evt.deltaY / SCROLL_PARAMETERS.PIXELS_PER_FULL_STEP));
const { scaleX: currentScaleFactor } = this.ctxWrapper.getScaleFactor();
if (
(factor * currentScaleFactor < 0.4 && factor < 1) ||
(factor * currentScaleFactor > 150 && factor > 1)
) {
return;
}
const pt = this.ctxWrapper.mapPointToCurrentTransform(evt.offsetX, evt.offsetY);
this.ctxWrapper.translate(pt.x, pt.y);
this.ctxWrapper.scale(factor, factor);
this.ctxWrapper.translate(-pt.x, -pt.y);
const { scaleX } = this.ctxWrapper.getScaleFactor();
this.currentScaleFactor = scaleX;
this.draw();
return evt.preventDefault();
}
protected startTranslate(evt: PanStartTouchHandlerEvent) : void {
const {x, y} = this.relativeCoordinatesToCanvas(evt.x0, evt.y0);
this.touchHandlingState.lastX = x;
this.touchHandlingState.lastY = y;
this.touchHandlingState.dragStart = this.ctxWrapper.mapPointToCurrentTransform(this.touchHandlingState.lastX, this.touchHandlingState.lastY);
this.activeTouchEvent = true;
}
protected moveTranslate(evt: PanMoveTouchHandlerEvent) : void {
const {x, y} = this.relativeCoordinatesToCanvas(evt.x1,evt.y1);
const oldX = this.touchHandlingState.lastX;
const oldY = this.touchHandlingState.lastY;
this.touchHandlingState.lastX = x;
this.touchHandlingState.lastY = y;
if (this.touchHandlingState.dragStart) {
const currentTransform = this.ctxWrapper.getTransform();
const currentPixelSize = this.structureManager.getPixelSize();
const invertedCurrentTransform = this.ctxWrapper.getInvertedTransform();
const wasHandled = this.structureManager.getClientStructures().some(structure => {
const result = structure.translate(
this.touchHandlingState.dragStart.matrixTransform(invertedCurrentTransform),
{x: oldX, y: oldY},
{x, y},
currentTransform,
currentPixelSize
);
if (result.stopPropagation) {
if (result.deleteMe === true) {
this.structureManager.removeMapStructure(structure);
}
this.updateState();
this.draw();
return true;
} else {
return false;
}
});
if (wasHandled) {
return;
}
// If no location stopped event handling -> pan the whole map
const pt = this.ctxWrapper.mapPointToCurrentTransform(this.touchHandlingState.lastX, this.touchHandlingState.lastY);
this.ctxWrapper.translate(pt.x - this.touchHandlingState.dragStart.x, pt.y - this.touchHandlingState.dragStart.y);
this.draw();
}
}
protected endTranslate(evt: PanEndTouchHandlerEvent | PinchEndTouchHandlerEvent) : void {
this.activeTouchEvent = false;
this.touchHandlingState.dragStart = null;
this.structureManager.getClientStructures().forEach(structure => {
if (structure.isResizing) {
structure.isResizing = false;
}
structure.postProcess();
});
this.draw();
if (this.pendingInternalDrawableStateUpdate && !this.activeScrollEvent) {
this.pendingInternalDrawableStateUpdate = false;
this.updateInternalDrawableState();
}
}
protected startPinch(evt: PinchStartTouchHandlerEvent) : void {
this.touchHandlingState.lastScaleFactor = 1;
// translate
const {x, y} = this.relativeCoordinatesToCanvas(evt.x0, evt.y0);
this.touchHandlingState.lastX = x;
this.touchHandlingState.lastY = y;
this.touchHandlingState.dragStart = this.ctxWrapper.mapPointToCurrentTransform(this.touchHandlingState.lastX, this.touchHandlingState.lastY);
this.activeTouchEvent = true;
}
protected scalePinch(evt: PinchMoveTouchHandlerEvent) : any {
const { scaleX: currentScaleFactor } = this.ctxWrapper.getScaleFactor();
const factor = evt.scale / this.touchHandlingState.lastScaleFactor;
if (factor * currentScaleFactor < 0.4 && factor < 1) {
return;
} else if (factor * currentScaleFactor > 150 && factor > 1) {
return;
}
this.touchHandlingState.lastScaleFactor = evt.scale;
const pt = this.ctxWrapper.mapPointToCurrentTransform(evt.x0, evt.y0);
this.ctxWrapper.translate(pt.x, pt.y);
this.ctxWrapper.scale(factor, factor);
this.ctxWrapper.translate(-pt.x, -pt.y);
// translate
const {x, y} = this.relativeCoordinatesToCanvas(evt.x0, evt.y0);
this.touchHandlingState.lastX = x;
this.touchHandlingState.lastY = y;
const p = this.ctxWrapper.mapPointToCurrentTransform(this.touchHandlingState.lastX, this.touchHandlingState.lastY);
this.ctxWrapper.translate(p.x - this.touchHandlingState.dragStart.x, p.y - this.touchHandlingState.dragStart.y);
this.draw();
}
protected endPinch(evt: PinchEndTouchHandlerEvent) : void {
const { scaleX } = this.ctxWrapper.getScaleFactor();
this.currentScaleFactor = scaleX;
this.endTranslate(evt);
}
protected registerCanvasInteractionHandlers(): void {
const touchHandler = new TouchHandler(this.canvas);
this.touchHandlingState.lastX = this.canvas.width / 2;
this.touchHandlingState.lastY = this.canvas.height / 2;
touchHandler.addEventListener(TapTouchHandlerEvent.TYPE, evt => {
this.onTap(evt as TapTouchHandlerEvent);
});
touchHandler.addEventListener(PanStartTouchHandlerEvent.TYPE, evt => {
this.startTranslate(evt as PanStartTouchHandlerEvent);
});
touchHandler.addEventListener(PanMoveTouchHandlerEvent.TYPE, evt => {
this.moveTranslate(evt as PanMoveTouchHandlerEvent);
});
touchHandler.addEventListener(PanEndTouchHandlerEvent.TYPE, evt => {
this.endTranslate(evt as PanEndTouchHandlerEvent);
});
touchHandler.addEventListener(PinchStartTouchHandlerEvent.TYPE, evt => {
this.startPinch(evt as PinchStartTouchHandlerEvent);
});
touchHandler.addEventListener(PinchMoveTouchHandlerEvent.TYPE, evt => {
this.scalePinch(evt as PinchMoveTouchHandlerEvent);
});
touchHandler.addEventListener(PinchEndTouchHandlerEvent.TYPE, evt => {
this.endPinch(evt as PinchEndTouchHandlerEvent);
});
//Order might be important here but I've never tested that
this.canvas.addEventListener("wheel", this.onScroll.bind(this), false);
}
/**
* Helper function for calculating coordinates relative to an HTML Element
*
* @param {number} x absolute screen coordinates x
* @param {number} y absolute screen coordinates y
*
* @returns {{x: number, y: number}} coordinates relative to the canvas element
*/
protected relativeCoordinatesToCanvas(x: number, y:number) : PointCoordinates {
const rect = this.canvas.getBoundingClientRect();
return {
x: x - rect.left,
y: y - rect.top
};
}
}
export default Map;