-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathInteractiveGraphics.tsx
More file actions
758 lines (703 loc) · 21.5 KB
/
Copy pathInteractiveGraphics.tsx
File metadata and controls
758 lines (703 loc) · 21.5 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
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
import useResizeObserver from "@react-hook/resize-observer"
import { useCallback, useEffect, useMemo, useState } from "react"
import { SuperGrid } from "react-supergrid"
import { applyObjectLimit } from "site/utils/applyObjectLimit"
import { getGraphicsBounds } from "site/utils/getGraphicsBounds"
import { getMaxStep } from "site/utils/getMaxStep"
import { sortRectsByArea } from "site/utils/sortRectsByArea"
import {
applyToPoint,
compose,
inverse,
scale,
translate,
} from "transformation-matrix"
import useMouseMatrixTransform from "use-mouse-matrix-transform"
import { GraphicsObject } from "../../../lib"
import { DimensionOverlay } from "../DimensionOverlay"
import { ObjectLabelDialog } from "../ObjectLabelDialog"
import { Arrow } from "./Arrow"
import { Circle } from "./Circle"
import { ContextMenu } from "./ContextMenu"
import { InfiniteLine } from "./InfiniteLine"
import { InteractiveState } from "./InteractiveState"
import { Line } from "./Line"
import { Marker, MarkerPoint } from "./Marker"
import { Point } from "./Point"
import { Polygon } from "./Polygon"
import { Rect } from "./Rect"
import { Text } from "./Text"
import { Tooltip } from "./Tooltip"
import {
useDoesLineIntersectViewport,
useFilterArrows,
useFilterCircles,
useFilterLines,
useFilterPoints,
useFilterPolygons,
useFilterRects,
useFilterTexts,
useIsPointOnScreen,
} from "./hooks"
import { tooltipLayerZIndex } from "./tooltipLayer"
export type GraphicsObjectClickEvent = {
type:
| "point"
| "line"
| "infinite-line"
| "rect"
| "circle"
| "text"
| "arrow"
| "polygon"
index: number
object: any
}
export const InteractiveGraphics = ({
graphics,
onObjectClicked,
objectLimit,
height = 600,
}: {
graphics: GraphicsObject
onObjectClicked?: (event: GraphicsObjectClickEvent) => void
objectLimit?: number
height?: number
}) => {
const [activeLayers, setActiveLayers] = useState<string[] | null>(null)
const [activeStep, setActiveStep] = useState<number | null>(null)
const [showLastStep, setShowLastStep] = useState(true)
const [size, setSize] = useState({ width: 600, height })
const [contextMenu, setContextMenu] = useState<{
x: number
y: number
clientX: number
clientY: number
} | null>(null)
const [enableObjectInteraction, setEnableObjectInteraction] = useState(false)
const [selectedObjectLabel, setSelectedObjectLabel] = useState<string | null>(
null,
)
const [markers, setMarkers] = useState<MarkerPoint[]>([])
const [mousePosition, setMousePosition] = useState<{
x: number
y: number
} | null>(null)
const [hoverTooltip, setHoverTooltip] = useState<{
text: string
x: number
y: number
} | null>(null)
const availableLayers: string[] = Array.from(
new Set([
...(graphics.lines?.map((l) => l.layer!).filter(Boolean) ?? []),
...(graphics.infiniteLines?.map((l) => l.layer!).filter(Boolean) ?? []),
...(graphics.rects?.map((r) => r.layer!).filter(Boolean) ?? []),
...(graphics.polygons?.map((p) => p.layer!).filter(Boolean) ?? []),
...(graphics.points?.map((p) => p.layer!).filter(Boolean) ?? []),
...(graphics.texts?.map((t) => t.layer!).filter(Boolean) ?? []),
...(graphics.circles?.map((c) => c.layer!).filter(Boolean) ?? []),
]),
)
const maxStep = getMaxStep(graphics)
const graphicsBoundsWithPadding = useMemo(() => {
const actualBounds = getGraphicsBounds(graphics)
const width = actualBounds.maxX - actualBounds.minX
const height = actualBounds.maxY - actualBounds.minY
return {
minX: actualBounds.minX - width / 10,
minY: actualBounds.minY - height / 10,
maxX: actualBounds.maxX + width / 10,
maxY: actualBounds.maxY + height / 10,
}
}, [graphics])
const getStorageKey = useCallback(() => {
const path = window.location.pathname
const search = window.location.search
return `saved-camera-position-${path}${search}`
}, [])
const getDefaultTransform = useCallback(() => {
const width = Math.max(
graphicsBoundsWithPadding.maxX - graphicsBoundsWithPadding.minX,
1,
)
const height = Math.max(
graphicsBoundsWithPadding.maxY - graphicsBoundsWithPadding.minY,
1,
)
const scaleFactor = Math.min(size.width / width, size.height / height)
return compose(
translate(size.width / 2, size.height / 2),
scale(scaleFactor, -scaleFactor),
translate(
-(graphicsBoundsWithPadding.maxX + graphicsBoundsWithPadding.minX) / 2,
-(graphicsBoundsWithPadding.maxY + graphicsBoundsWithPadding.minY) / 2,
),
)
}, [size, graphicsBoundsWithPadding])
type SavedData = {
transform: any
markers: MarkerPoint[]
}
const getSavedData = useCallback((): SavedData | null => {
try {
const savedData = localStorage.getItem(getStorageKey())
if (savedData) {
return JSON.parse(savedData)
}
} catch (error) {
console.error("Error loading saved data:", error)
}
return null
}, [getStorageKey])
const getSavedTransform = useCallback(() => {
const savedData = getSavedData()
return savedData?.transform || null
}, [getSavedData])
const {
transform: realToScreen,
ref,
setTransform,
} = useMouseMatrixTransform({
initialTransform: getDefaultTransform(),
})
useResizeObserver(ref, (entry: ResizeObserverEntry) => {
setSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
})
// Load saved markers on mount
useEffect(() => {
const savedData = getSavedData()
if (savedData?.markers) {
setMarkers(savedData.markers)
}
}, [getSavedData])
const handleContextMenu = useCallback((event: React.MouseEvent) => {
event.preventDefault()
// Get mouse position
const mouseX = event.clientX
const mouseY = event.clientY
// Get element position
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
const elementX = rect.left
const elementY = rect.top
// Get viewport dimensions
const viewportWidth = window.innerWidth
const viewportHeight = window.innerHeight
// Menu dimensions (approximate)
const menuWidth = 160
const menuHeight = 100
// Position based on quadrant of the screen
let x = mouseX - elementX
let y = mouseY - elementY
// If mouse is in right half of viewport, position menu to the left
if (mouseX > viewportWidth / 2) {
x = x - menuWidth
}
// If mouse is in bottom half of viewport, position menu above
if (mouseY > viewportHeight / 2) {
y = y - menuHeight
}
setContextMenu({
x,
y,
clientX: mouseX,
clientY: mouseY,
})
}, [])
const saveToLocalStorage = useCallback(
(transform: any, markerPoints: MarkerPoint[]) => {
try {
const dataToSave: SavedData = {
transform,
markers: markerPoints,
}
localStorage.setItem(getStorageKey(), JSON.stringify(dataToSave))
} catch (error) {
console.error("Error saving data:", error)
}
},
[getStorageKey],
)
const handleSaveCamera = useCallback(() => {
saveToLocalStorage(realToScreen, markers)
}, [saveToLocalStorage, realToScreen, markers])
const handleLoadCamera = useCallback(() => {
try {
const savedTransform = getSavedTransform()
if (savedTransform) {
setTransform(savedTransform)
}
} catch (error) {
console.error("Error loading camera position:", error)
}
}, [getSavedTransform, setTransform])
const handleClearCamera = useCallback(() => {
try {
const defaultTransform = getDefaultTransform()
saveToLocalStorage(defaultTransform, markers)
setTransform(defaultTransform)
} catch (error) {
console.error("Error clearing camera position:", error)
}
}, [saveToLocalStorage, getDefaultTransform, setTransform, markers])
const handleAddMark = useCallback(() => {
if (!contextMenu) return
try {
// Convert screen coordinates to real-world coordinates
const screenPoint = { x: contextMenu.clientX, y: contextMenu.clientY }
const rect = ref.current?.getBoundingClientRect()
if (rect) {
const screenX = screenPoint.x - rect.left
const screenY = screenPoint.y - rect.top
// Apply inverse transform to get real-world coordinates
const inverseTransform = inverse(realToScreen)
const [realX, realY] = applyToPoint(inverseTransform, [
screenX,
screenY,
])
const newMarker: MarkerPoint = { x: realX, y: realY }
const newMarkers = [...markers, newMarker]
setMarkers(newMarkers)
const savedData = getSavedData()
if (savedData?.transform) {
saveToLocalStorage(savedData.transform, newMarkers)
}
}
} catch (error) {
console.error("Error adding marker:", error)
}
}, [contextMenu, ref, realToScreen, markers, saveToLocalStorage])
const handleClearMarks = useCallback(() => {
setMarkers([])
const savedData = getSavedData()
if (savedData?.transform) {
saveToLocalStorage(savedData.transform, [])
}
}, [getSavedData, saveToLocalStorage])
const getObjectInteractionLabel = useCallback(
(event: GraphicsObjectClickEvent) => {
switch (event.type) {
case "arrow":
return [event.object.label, event.object.inlineLabel]
.filter(Boolean)
.join("\n")
case "text":
return event.object.text ?? ""
default:
return event.object.label ?? ""
}
},
[],
)
const handleObjectClicked = useCallback(
(event: GraphicsObjectClickEvent) => {
onObjectClicked?.(event)
if (!enableObjectInteraction) return
const label = getObjectInteractionLabel(event)
setSelectedObjectLabel(label || null)
},
[enableObjectInteraction, getObjectInteractionLabel, onObjectClicked],
)
useEffect(() => {
if (!selectedObjectLabel) return
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setSelectedObjectLabel(null)
}
}
window.addEventListener("keydown", handleKeyDown)
return () => {
window.removeEventListener("keydown", handleKeyDown)
}
}, [selectedObjectLabel])
const interactiveState: InteractiveState = {
activeLayers: activeLayers,
activeStep: showLastStep ? maxStep : activeStep,
realToScreen: realToScreen,
onObjectClicked: handleObjectClicked,
setHoverTooltip,
}
const showToolbar = true
// Use custom hooks for visibility checks and filtering
const isPointOnScreen = useIsPointOnScreen(realToScreen, size)
const doesLineIntersectViewport = useDoesLineIntersectViewport(
realToScreen,
size,
)
// Filter by layer and step
const filterLayerAndStep = (obj: { layer?: string; step?: number }) => {
if (activeLayers && obj.layer && !activeLayers.includes(obj.layer))
return false
const selectedStep = showLastStep ? maxStep : activeStep
if (
selectedStep !== null &&
obj.step !== undefined &&
obj.step !== selectedStep
)
return false
return true
}
const filterLines = useFilterLines({
isPointOnScreen,
doesLineIntersectViewport,
filterLayerAndStep,
})
const filterPoints = useFilterPoints({
isPointOnScreen,
filterLayerAndStep,
})
const filterRects = useFilterRects({
realToScreen,
isPointOnScreen,
doesLineIntersectViewport,
filterLayerAndStep,
})
const filterCircles = useFilterCircles({
isPointOnScreen,
filterLayerAndStep,
realToScreen,
size,
})
const filterTexts = useFilterTexts({
isPointOnScreen,
filterLayerAndStep,
})
const filterArrows = useFilterArrows({
isPointOnScreen,
doesLineIntersectViewport,
})
const filterPolygons = useFilterPolygons({
isPointOnScreen,
doesLineIntersectViewport,
filterLayerAndStep,
})
const filterAndLimit = <T,>(
objects: T[] | undefined,
filterFn: (obj: T) => boolean,
): (T & { originalIndex: number })[] => {
if (!objects) return []
return objects
.map((obj, index) => ({ ...obj, originalIndex: index }))
.filter(filterFn)
}
const filteredLines = useMemo(
() =>
filterAndLimit(graphics.lines, filterLines).sort(
(a, b) =>
(a.zIndex ?? 0) - (b.zIndex ?? 0) ||
a.originalIndex - b.originalIndex,
),
[graphics.lines, filterLines],
)
const filteredInfiniteLines = useMemo(
() => filterAndLimit(graphics.infiniteLines, filterLayerAndStep),
[graphics.infiniteLines, filterLayerAndStep],
)
const filteredRects = useMemo(
() => sortRectsByArea(filterAndLimit(graphics.rects, filterRects)),
[graphics.rects, filterRects],
)
const filteredPolygons = useMemo(
() => filterAndLimit(graphics.polygons, filterPolygons),
[graphics.polygons, filterPolygons],
)
const filteredPoints = useMemo(
() => filterAndLimit(graphics.points, filterPoints),
[graphics.points, filterPoints],
)
const filteredCircles = useMemo(
() => filterAndLimit(graphics.circles, filterCircles),
[graphics.circles, filterCircles],
)
const filteredTexts = useMemo(
() => filterAndLimit(graphics.texts, filterTexts),
[graphics.texts, filterTexts],
)
const filteredArrows = useMemo(
() => filterAndLimit(graphics.arrows, filterArrows),
[graphics.arrows, filterArrows],
)
const limitedBuckets = useMemo(
() =>
applyObjectLimit(
{
arrows: filteredArrows,
infiniteLines: filteredInfiniteLines,
lines: filteredLines,
rects: filteredRects,
polygons: filteredPolygons,
circles: filteredCircles,
texts: filteredTexts,
points: filteredPoints,
},
[
"arrows",
"infiniteLines",
"lines",
"rects",
"polygons",
"circles",
"texts",
"points",
],
objectLimit,
),
[
filteredArrows,
filteredInfiniteLines,
filteredLines,
filteredRects,
filteredPolygons,
filteredCircles,
filteredTexts,
filteredPoints,
objectLimit,
],
)
const totalFilteredObjects =
filteredInfiniteLines.length +
filteredLines.length +
filteredRects.length +
filteredPolygons.length +
filteredPoints.length +
filteredCircles.length +
filteredTexts.length +
filteredArrows.length
const isLimitReached = objectLimit && totalFilteredObjects > objectLimit
return (
<div>
{showToolbar && (
<div
style={{
margin: 8,
display: "flex",
alignItems: "center",
gap: 12,
flexWrap: "wrap",
}}
>
{availableLayers.length > 1 && (
<select
value={activeLayers ? activeLayers[0] : ""}
onChange={(e) => {
const value = e.target.value
setActiveLayers(value === "" ? null : [value])
}}
style={{ marginRight: 8 }}
>
<option value="">All Layers</option>
{availableLayers.map((layer) => (
<option key={layer} value={layer}>
{layer}
</option>
))}
</select>
)}
{maxStep > 0 && (
<div
style={{ display: "inline-flex", alignItems: "center", gap: 8 }}
>
Step:
<input
type="number"
min={0}
max={maxStep}
value={activeStep ?? 0}
onChange={(e) => {
const value = parseInt(e.target.value)
setShowLastStep(false)
setActiveStep(Number.isNaN(value) ? null : value)
}}
disabled={activeStep === null}
/>
<label>
<input
type="checkbox"
style={{ marginRight: 4 }}
checked={activeStep !== null}
onChange={(e) => {
setShowLastStep(false)
setActiveStep(e.target.checked ? 0 : null)
}}
/>
Filter by step
</label>
<label>
<input
type="checkbox"
style={{ marginRight: 4 }}
checked={showLastStep}
onChange={(e) => {
setShowLastStep(e.target.checked)
setActiveStep(null)
}}
/>
Show last step
</label>
{isLimitReached && (
<span style={{ color: "red", fontSize: "12px" }}>
Display limited to {objectLimit} objects. Received:{" "}
{totalFilteredObjects}.
</span>
)}
</div>
)}
<label>
<input
type="checkbox"
style={{ marginRight: 4 }}
checked={enableObjectInteraction}
onChange={(event) => {
const isEnabled = event.target.checked
setEnableObjectInteraction(isEnabled)
if (!isEnabled) {
setSelectedObjectLabel(null)
}
}}
/>
Enable Object Interation
</label>
</div>
)}
<div
ref={ref}
style={{
position: "relative",
height,
overflow: "hidden",
}}
onMouseMove={(event) => {
const rect = ref.current?.getBoundingClientRect()
if (!rect) return
setMousePosition({
x: event.clientX - rect.left,
y: event.clientY - rect.top,
})
}}
onMouseLeave={() => setMousePosition(null)}
onContextMenu={handleContextMenu}
>
<DimensionOverlay transform={realToScreen}>
{limitedBuckets.arrows.map((arrow) => (
<Arrow
key={arrow.originalIndex}
arrow={arrow}
index={arrow.originalIndex}
interactiveState={interactiveState}
/>
))}
{limitedBuckets.infiniteLines.map((infiniteLine) => (
<InfiniteLine
key={infiniteLine.originalIndex}
infiniteLine={infiniteLine}
index={infiniteLine.originalIndex}
interactiveState={interactiveState}
size={size}
/>
))}
{limitedBuckets.lines.map((line) => (
<Line
key={line.originalIndex}
line={line}
index={line.originalIndex}
interactiveState={interactiveState}
size={size}
mousePosition={mousePosition}
/>
))}
{limitedBuckets.rects.map((rect) => (
<Rect
key={rect.originalIndex}
rect={rect}
index={rect.originalIndex}
interactiveState={interactiveState}
/>
))}
{limitedBuckets.polygons.map((polygon) => (
<Polygon
key={polygon.originalIndex}
polygon={polygon}
index={polygon.originalIndex}
interactiveState={interactiveState}
/>
))}
{limitedBuckets.circles.map((circle) => (
<Circle
key={circle.originalIndex}
circle={circle}
index={circle.originalIndex}
interactiveState={interactiveState}
/>
))}
{limitedBuckets.texts.map((txt) => (
<Text
key={txt.originalIndex}
textObj={txt}
index={txt.originalIndex}
interactiveState={interactiveState}
/>
))}
{limitedBuckets.points.map((point) => (
<Point
key={point.originalIndex}
point={point}
index={point.originalIndex}
interactiveState={interactiveState}
/>
))}
<SuperGrid
stringifyCoord={(x, y) => `${x.toFixed(2)}, ${y.toFixed(2)}`}
width={size.width}
height={size.height}
transform={realToScreen}
/>
</DimensionOverlay>
{markers.map((marker, index) => (
<Marker
key={index}
marker={marker}
index={index}
transform={realToScreen}
/>
))}
{hoverTooltip && (
<div
style={{
position: "absolute",
left: hoverTooltip.x,
top: hoverTooltip.y - 8,
transform: "translate(-50%, -100%)",
pointerEvents: "none",
zIndex: tooltipLayerZIndex,
}}
>
<Tooltip text={hoverTooltip.text} />
</div>
)}
{contextMenu && (
<ContextMenu
x={contextMenu.x}
y={contextMenu.y}
onSaveCamera={handleSaveCamera}
onLoadCamera={handleLoadCamera}
onClearCamera={handleClearCamera}
onAddMark={handleAddMark}
onClearMarks={handleClearMarks}
onClose={() => setContextMenu(null)}
/>
)}
{selectedObjectLabel && (
<ObjectLabelDialog
label={selectedObjectLabel}
onClose={() => {
setSelectedObjectLabel(null)
}}
/>
)}
</div>
</div>
)
}