-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathSchematicViewer.tsx
More file actions
604 lines (565 loc) · 18 KB
/
Copy pathSchematicViewer.tsx
File metadata and controls
604 lines (565 loc) · 18 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
import {
convertCircuitJsonToSchematicSvg,
type ColorOverrides,
} from "circuit-to-svg"
import { su } from "@tscircuit/soup-util"
import { useChangeSchematicComponentLocationsInSvg } from "lib/hooks/useChangeSchematicComponentLocationsInSvg"
import { useHighlightConnectedSchematicTraces } from "lib/hooks/useHighlightConnectedSchematicTraces"
import { useChangeSchematicTracesForMovedComponents } from "lib/hooks/useChangeSchematicTracesForMovedComponents"
import { useSchematicGroupsOverlay } from "lib/hooks/useSchematicGroupsOverlay"
import { enableDebug } from "lib/utils/debug"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import {
fromString,
identity,
toString as transformToString,
} from "transformation-matrix"
import { useMouseMatrixTransform } from "use-mouse-matrix-transform"
import { useResizeHandling } from "../hooks/use-resize-handling"
import { useComponentDragging } from "../hooks/useComponentDragging"
import type { ManualEditEvent } from "../types/edit-events"
import { EditIcon } from "./EditIcon"
import { GridIcon } from "./GridIcon"
import { ViewMenuIcon } from "./ViewMenuIcon"
import { ViewMenu } from "./ViewMenu"
import type { CircuitJson } from "circuit-json"
import { SpiceSimulationIcon } from "./SpiceSimulationIcon"
import { SpiceSimulationOverlay } from "./SpiceSimulationOverlay"
import { zIndexMap } from "../utils/z-index-map"
import { useSpiceSimulation } from "../hooks/useSpiceSimulation"
import { getSpiceFromCircuitJson } from "../utils/spice-utils"
import { getStoredBoolean, setStoredBoolean } from "lib/hooks/useLocalStorage"
import { MouseTracker } from "./MouseTracker"
import { SchematicComponentMouseTarget } from "./SchematicComponentMouseTarget"
import { SchematicPortMouseTarget } from "./SchematicPortMouseTarget"
interface Props {
circuitJson: CircuitJson
containerStyle?: React.CSSProperties
editEvents?: ManualEditEvent[]
onEditEvent?: (event: ManualEditEvent) => void
defaultEditMode?: boolean
debugGrid?: boolean
editingEnabled?: boolean
debug?: boolean
clickToInteractEnabled?: boolean
colorOverrides?: ColorOverrides
spiceSimulationEnabled?: boolean
disableGroups?: boolean
css?: string
className?: string
onSchematicComponentClicked?: (options: {
schematicComponentId: string
event: MouseEvent
}) => void
showSchematicPorts?: boolean
onSchematicPortClicked?: (options: {
schematicPortId: string
event: MouseEvent
}) => void
}
export const SchematicViewer = ({
circuitJson,
containerStyle,
editEvents: unappliedEditEvents = [],
onEditEvent,
defaultEditMode = false,
debugGrid = false,
editingEnabled = false,
debug = false,
clickToInteractEnabled = false,
colorOverrides,
spiceSimulationEnabled = false,
disableGroups = false,
onSchematicComponentClicked,
showSchematicPorts = false,
onSchematicPortClicked,
css,
className,
}: Props) => {
if (debug) {
enableDebug()
}
const [showSpiceOverlay, setShowSpiceOverlay] = useState(false)
const [spiceSimOptions, setSpiceSimOptions] = useState({
showVoltage: true,
showCurrent: false,
startTime: 0, // in ms
duration: 20, // in ms
})
const getCircuitHash = (circuitJson: CircuitJson) => {
return `${circuitJson?.length || 0}_${(circuitJson as any)?.editCount || 0}`
}
const circuitJsonKey = useMemo(
() => getCircuitHash(circuitJson),
[circuitJson],
)
const spiceString = useMemo(() => {
if (!spiceSimulationEnabled) return null
try {
return getSpiceFromCircuitJson(circuitJson, spiceSimOptions)
} catch (e) {
console.error("Failed to generate SPICE string", e)
return null
}
}, [
circuitJsonKey,
spiceSimulationEnabled,
spiceSimOptions.startTime,
spiceSimOptions.duration,
])
const [hasSpiceSimRun, setHasSpiceSimRun] = useState(false)
useEffect(() => {
setHasSpiceSimRun(false)
}, [circuitJsonKey])
const {
plotData,
nodes,
isLoading: isSpiceSimLoading,
error: spiceSimError,
} = useSpiceSimulation(hasSpiceSimRun ? spiceString : null)
const [editModeEnabled, setEditModeEnabled] = useState(defaultEditMode)
const [snapToGrid, setSnapToGrid] = useState(true)
const [showGridInternal, setShowGridInternal] = useState(false)
const showGrid = debugGrid || showGridInternal
const [isInteractionEnabled, setIsInteractionEnabled] = useState<boolean>(
!clickToInteractEnabled,
)
const [showViewMenu, setShowViewMenu] = useState(false)
const [showSchematicGroups, setShowSchematicGroups] = useState(() => {
if (disableGroups) return false
return getStoredBoolean("schematic_viewer_show_groups", false)
})
const [isHoveringClickableComponent, setIsHoveringClickableComponent] =
useState(false)
const hoveringComponentsRef = useRef<Set<string>>(new Set())
const handleComponentHoverChange = useCallback(
(componentId: string, isHovering: boolean) => {
if (isHovering) {
hoveringComponentsRef.current.add(componentId)
} else {
hoveringComponentsRef.current.delete(componentId)
}
setIsHoveringClickableComponent(hoveringComponentsRef.current.size > 0)
},
[],
)
const [isHoveringClickablePort, setIsHoveringClickablePort] = useState(false)
const hoveringPortsRef = useRef<Set<string>>(new Set())
const handlePortHoverChange = useCallback(
(portId: string, isHovering: boolean) => {
if (isHovering) {
hoveringPortsRef.current.add(portId)
} else {
hoveringPortsRef.current.delete(portId)
}
setIsHoveringClickablePort(hoveringPortsRef.current.size > 0)
},
[],
)
const svgDivRef = useRef<HTMLDivElement>(null)
const touchStartRef = useRef<{ x: number; y: number } | null>(null)
const schematicComponentIds = useMemo(() => {
try {
return (
su(circuitJson)
.schematic_component?.list()
?.map((component) => component.schematic_component_id as string) ?? []
)
} catch (err) {
console.error("Failed to derive schematic component ids", err)
return []
}
}, [circuitJsonKey, circuitJson])
const schematicPortsInfo = useMemo(() => {
if (!showSchematicPorts) return []
try {
const ports = su(circuitJson).schematic_port?.list() ?? []
return ports.map((port) => {
const sourcePort = su(circuitJson).source_port.get(port.source_port_id)
const sourceComponent = sourcePort?.source_component_id
? su(circuitJson).source_component.get(sourcePort.source_component_id)
: null
const componentName = sourceComponent?.name ?? "?"
const pinLabel =
port.display_pin_label ??
(sourcePort as any)?.pin_number ??
(sourcePort as any)?.name ??
"?"
return {
portId: port.source_port_id as string,
label: `${componentName}.${pinLabel}`,
}
})
} catch (err) {
console.error("Failed to derive schematic port info", err)
return []
}
}, [circuitJsonKey, circuitJson, showSchematicPorts])
const handleTouchStart = (e: React.TouchEvent) => {
const touch = e.touches[0]
touchStartRef.current = {
x: touch.clientX,
y: touch.clientY,
}
}
const handleTouchEnd = (e: React.TouchEvent) => {
const touch = e.changedTouches[0]
const start = touchStartRef.current
if (!start) return
const deltaX = Math.abs(touch.clientX - start.x)
const deltaY = Math.abs(touch.clientY - start.y)
if (deltaX < 10 && deltaY < 10) {
e.preventDefault()
setIsInteractionEnabled(true)
}
touchStartRef.current = null
}
const [internalEditEvents, setInternalEditEvents] = useState<
ManualEditEvent[]
>([])
const circuitJsonRef = useRef<CircuitJson>(circuitJson)
useEffect(() => {
const circuitHash = getCircuitHash(circuitJson)
const circuitHashRef = getCircuitHash(circuitJsonRef.current)
if (circuitHash !== circuitHashRef) {
setInternalEditEvents([])
circuitJsonRef.current = circuitJson
}
}, [circuitJson])
const {
ref: containerRef,
cancelDrag,
transform: svgToScreenProjection,
} = useMouseMatrixTransform({
onSetTransform(transform) {
if (!svgDivRef.current) return
svgDivRef.current.style.transform = transformToString(transform)
},
// @ts-ignore disabled is a valid prop but not typed
enabled: isInteractionEnabled && !showSpiceOverlay,
})
const { containerWidth, containerHeight } = useResizeHandling(containerRef)
const svgString = useMemo(() => {
if (!containerWidth || !containerHeight) return ""
return convertCircuitJsonToSchematicSvg(circuitJson as any, {
width: containerWidth,
height: containerHeight || 720,
drawPorts: showSchematicPorts,
grid: !showGrid
? undefined
: {
cellSize: 1,
labelCells: true,
},
colorOverrides,
css,
className,
})
}, [
circuitJsonKey,
containerWidth,
containerHeight,
showGrid,
showSchematicPorts,
])
const containerBackgroundColor = useMemo(() => {
const match = svgString.match(
/<svg[^>]*style="[^"]*background-color:\s*([^;\"]+)/i,
)
return match?.[1] ?? "transparent"
}, [svgString])
const realToSvgProjection = useMemo(() => {
if (!svgString) return identity()
const transformString = svgString.match(
/data-real-to-screen-transform="([^"]+)"/,
)?.[1]!
try {
return fromString(transformString)
} catch (e) {
console.error(e)
return identity()
}
}, [svgString])
const handleEditEvent = (event: ManualEditEvent) => {
setInternalEditEvents((prev) => [...prev, event])
if (onEditEvent) {
onEditEvent(event)
}
}
const editEventsWithUnappliedEditEvents = useMemo(() => {
return [...unappliedEditEvents, ...internalEditEvents]
}, [unappliedEditEvents, internalEditEvents])
const {
handleMouseDown,
handleTouchStart: handleComponentTouchStart,
isDragging,
activeEditEvent,
} = useComponentDragging({
onEditEvent: handleEditEvent,
cancelDrag,
realToSvgProjection,
svgToScreenProjection,
circuitJson,
editEvents: editEventsWithUnappliedEditEvents,
enabled: editModeEnabled && isInteractionEnabled && !showSpiceOverlay,
snapToGrid,
})
useChangeSchematicComponentLocationsInSvg({
svgDivRef,
editEvents: editEventsWithUnappliedEditEvents,
realToSvgProjection,
svgToScreenProjection,
activeEditEvent,
})
useChangeSchematicTracesForMovedComponents({
svgDivRef,
circuitJson,
activeEditEvent,
editEvents: editEventsWithUnappliedEditEvents,
})
useHighlightConnectedSchematicTraces({
svgDivRef,
circuitJson,
circuitJsonKey,
svgString,
})
// Add group overlays when enabled
useSchematicGroupsOverlay({
svgDivRef,
circuitJson,
circuitJsonKey,
showGroups: showSchematicGroups && !disableGroups,
})
// keep the latest touch handler without re-rendering the svg div
const handleComponentTouchStartRef = useRef(handleComponentTouchStart)
useEffect(() => {
handleComponentTouchStartRef.current = handleComponentTouchStart
}, [handleComponentTouchStart])
const svgDiv = useMemo(
() => (
<div
ref={svgDivRef}
style={{
pointerEvents: clickToInteractEnabled
? isInteractionEnabled
? "auto"
: "none"
: "auto",
transformOrigin: "0 0",
}}
className={
onSchematicComponentClicked
? "schematic-component-clickable"
: undefined
}
onTouchStart={(e) => {
if (editModeEnabled && isInteractionEnabled && !showSpiceOverlay) {
handleComponentTouchStartRef.current(e)
}
}}
// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
dangerouslySetInnerHTML={{ __html: svgString }}
/>
),
[
svgString,
isInteractionEnabled,
clickToInteractEnabled,
editModeEnabled,
showSpiceOverlay,
],
)
return (
<MouseTracker>
{onSchematicComponentClicked && (
<style>
{`.schematic-component-clickable [data-schematic-component-id]:hover { cursor: pointer !important; }`}
</style>
)}
{onSchematicPortClicked && (
<style>
{`[data-schematic-port-id]:hover { cursor: pointer !important; }`}
</style>
)}
<div
ref={containerRef}
style={{
position: "relative",
backgroundColor: containerBackgroundColor,
overflow: "hidden",
cursor: showSpiceOverlay
? "auto"
: isDragging
? "grabbing"
: clickToInteractEnabled && !isInteractionEnabled
? "pointer"
: isHoveringClickableComponent && onSchematicComponentClicked
? "pointer"
: isHoveringClickablePort && onSchematicPortClicked
? "pointer"
: "grab",
minHeight: "300px",
...containerStyle,
}}
onWheelCapture={(e) => {
if (showSpiceOverlay) {
e.stopPropagation()
}
}}
onMouseDown={(e) => {
if (clickToInteractEnabled && !isInteractionEnabled) {
e.preventDefault()
e.stopPropagation()
return
}
handleMouseDown(e)
}}
onMouseDownCapture={(e) => {
if (clickToInteractEnabled && !isInteractionEnabled) {
e.preventDefault()
e.stopPropagation()
return
}
}}
onTouchStart={(e) => {
if (showSpiceOverlay) return
handleTouchStart(e)
}}
onTouchEnd={(e) => {
if (showSpiceOverlay) return
handleTouchEnd(e)
}}
>
{!isInteractionEnabled && clickToInteractEnabled && (
<div
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
setIsInteractionEnabled(true)
}}
style={{
position: "absolute",
inset: 0,
cursor: "pointer",
zIndex: zIndexMap.clickToInteractOverlay,
display: "flex",
alignItems: "center",
justifyContent: "center",
pointerEvents: "all",
touchAction: "pan-x pan-y pinch-zoom",
}}
>
<div
style={{
backgroundColor: "rgba(0, 0, 0, 0.8)",
color: "white",
padding: "12px 24px",
borderRadius: "8px",
fontSize: "16px",
fontFamily: "sans-serif",
pointerEvents: "none",
}}
>
{typeof window !== "undefined" &&
("ontouchstart" in window || navigator.maxTouchPoints > 0)
? "Touch to Interact"
: "Click to Interact"}
</div>
</div>
)}
<ViewMenuIcon
active={showViewMenu}
onClick={() => setShowViewMenu(!showViewMenu)}
/>
{editingEnabled && (
<EditIcon
active={editModeEnabled}
onClick={() => setEditModeEnabled(!editModeEnabled)}
/>
)}
{editingEnabled && editModeEnabled && (
<GridIcon
active={snapToGrid}
onClick={() => setSnapToGrid(!snapToGrid)}
/>
)}
<ViewMenu
circuitJson={circuitJson}
circuitJsonKey={circuitJsonKey}
isVisible={showViewMenu}
onClose={() => setShowViewMenu(false)}
showGroups={showSchematicGroups}
onToggleGroups={(value) => {
if (!disableGroups) {
setShowSchematicGroups(value)
setStoredBoolean("schematic_viewer_show_groups", value)
}
}}
showGrid={showGrid}
onToggleGrid={setShowGridInternal}
/>
{spiceSimulationEnabled && (
<SpiceSimulationIcon onClick={() => setShowSpiceOverlay(true)} />
)}
{showSpiceOverlay && (
<SpiceSimulationOverlay
spiceString={spiceString}
onClose={() => setShowSpiceOverlay(false)}
plotData={plotData}
nodes={nodes}
isLoading={isSpiceSimLoading}
error={spiceSimError}
simOptions={spiceSimOptions}
onSimOptionsChange={(options) => {
setHasSpiceSimRun(true)
setSpiceSimOptions(options)
}}
hasRun={hasSpiceSimRun}
/>
)}
{onSchematicComponentClicked &&
schematicComponentIds.map((componentId) => (
<SchematicComponentMouseTarget
key={componentId}
componentId={componentId}
svgDivRef={svgDivRef}
containerRef={containerRef}
showOutline={true}
circuitJsonKey={circuitJsonKey}
onHoverChange={handleComponentHoverChange}
onComponentClick={(id, event) => {
onSchematicComponentClicked?.({
schematicComponentId: id,
event,
})
}}
/>
))}
{svgDiv}
{showSchematicPorts &&
schematicPortsInfo.map(({ portId, label }) => (
<SchematicPortMouseTarget
key={portId}
portId={portId}
portLabel={label}
svgDivRef={svgDivRef}
containerRef={containerRef}
showOutline={true}
circuitJsonKey={circuitJsonKey}
onHoverChange={handlePortHoverChange}
onPortClick={
onSchematicPortClicked
? (id, event) => {
onSchematicPortClicked?.({
schematicPortId: id,
event,
})
}
: undefined
}
/>
))}
</div>
</MouseTracker>
)
}