-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathPrimitiveComponent.ts
More file actions
1322 lines (1176 loc) · 41 KB
/
PrimitiveComponent.ts
File metadata and controls
1322 lines (1176 loc) · 41 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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { PcbSx } from "@tscircuit/props"
import type { AnySourceComponent, LayerRef } from "circuit-json"
import { type Options, selectAll, selectOne } from "css-select"
import Debug from "debug"
import type { IsolatedCircuit } from "lib/IsolatedCircuit"
import type { RootCircuit } from "lib/RootCircuit"
import { Renderable } from "lib/components/base-components/Renderable"
import type { BoardI } from "lib/components/normal-components/BoardI"
import type { IGroup } from "lib/components/primitive-components/Group/IGroup"
import type { ISubcircuit } from "lib/components/primitive-components/Group/Subcircuit/ISubcircuit"
import type { ISymbol } from "lib/components/primitive-components/Symbol/ISymbol"
import { InvalidProps } from "lib/errors/InvalidProps"
import type { Ftype } from "lib/utils/constants"
import {
evaluateCalcString,
extractCalcIdentifiers,
} from "lib/utils/evaluateCalcString"
import { getSubcircuitPcbCalcVariables } from "lib/utils/getSubcircuitPcbCalcVariables"
import { isFootprintFlipped } from "lib/utils/pcb/transform-footprint-insertion-direction"
import { getResolvedPcbSx } from "lib/utils/pcbSx/get-resolved-pcb-sx"
import type {
SchematicBoxComponentDimensions,
SchematicBoxDimensions,
} from "lib/utils/schematic/getAllDimensionsForSchematicBox"
import { isMatchingSelector } from "lib/utils/selector-matching"
import { type SchSymbol, symbols } from "schematic-symbols"
import {
type Matrix,
applyToPoint,
compose,
flipY,
identity,
rotate,
translate,
} from "transformation-matrix"
import type { Primitive, ZodType } from "zod"
import { z } from "zod"
import {
cssSelectPrimitiveComponentAdapter,
cssSelectPrimitiveComponentAdapterOnlySubcircuits,
cssSelectPrimitiveComponentAdapterWithoutSubcircuits,
} from "./cssSelectPrimitiveComponentAdapter"
import { preprocessSelector } from "./preprocessSelector"
const cssSelectOptionsInsideSubcircuit: Options<
PrimitiveComponent,
PrimitiveComponent
> = {
adapter: cssSelectPrimitiveComponentAdapterWithoutSubcircuits,
cacheResults: true,
}
export interface BaseComponentConfig {
componentName: string
schematicSymbolName?: string | null
zodProps: z.ZodType
sourceFtype?: Ftype | null
shouldRenderAsSchematicBox?: boolean
}
/**
* A PrimitiveComponent (SmtPad, Port etc.) doesn't have the ability to contain
* React subtrees or explicit handling of the "footprint" prop. But otherwise
* has most of the features of a NormalComponent.
*/
export abstract class PrimitiveComponent<
ZodProps extends ZodType = any,
> extends Renderable {
parent: PrimitiveComponent | null = null
children: PrimitiveComponent[]
childrenPendingRemoval: PrimitiveComponent[]
get config(): BaseComponentConfig {
return {
componentName: "",
zodProps: z.object({}).passthrough(),
}
}
props: z.input<ZodProps>
_parsedProps: z.infer<ZodProps>
get componentName() {
return this.config.componentName
}
getInheritedProperty(propertyName: string) {
let current: PrimitiveComponent<ZodProps> | null = this
while (current) {
if (current._parsedProps && propertyName in current._parsedProps) {
return current._parsedProps[propertyName]
}
current = current.parent as PrimitiveComponent<ZodProps> | null // Move up to the parent
}
if (this.root?.platform && propertyName in this.root.platform) {
return this.root.platform[propertyName as keyof typeof this.root.platform]
}
return undefined // Return undefined if not found
}
getInheritedMergedProperty(propertyName: string): any {
const parentPropertyObject =
this.parent?.getInheritedMergedProperty?.(propertyName)
const myPropertyObject =
this._parsedProps?.[propertyName as keyof z.infer<ZodProps>]
return { ...parentPropertyObject, ...myPropertyObject }
}
getResolvedPcbSx(): PcbSx {
return getResolvedPcbSx({
parentResolvedPcbSx: this.parent?.getResolvedPcbSx?.(),
pcbStyle: this._parsedProps?.pcbStyle,
ownPcbSx: this._parsedProps?.pcbSx,
})
}
get lowercaseComponentName() {
return this.componentName.toLowerCase()
}
externallyAddedAliases: string[]
/**
* An subcircuit is self-contained. All the selectors inside
* a subcircuit are relative to the subcircuit group. You can have multiple
* subcircuits and their selectors will not interact with each other (even if the
* components share the same names) unless you explicitly break out some ports
*/
get isSubcircuit() {
return (
Boolean(this.props.subcircuit) ||
(this.lowercaseComponentName === "group" &&
(this?.parent as any)?.isRootCircuit)
)
}
get isGroup() {
return this.lowercaseComponentName === "group"
}
get name() {
return (this._parsedProps as any).name ?? this.fallbackUnassignedName
}
/**
* A primitive container is a component that contains one or more ports and
* primitive components that are designed to interact.
*
* For example a resistor contains ports and smtpads that interact, so the
* resistor is a primitive container. Inside a primitive container, the ports
* and pads are likely to reference each other and look for eachother during
* the port matching phase.
*
*/
isPrimitiveContainer = false
canHaveTextChildren = false
source_group_id: string | null = null
source_component_id: string | null = null
schematic_component_id: string | null = null
pcb_component_id: string | null = null
cad_component_id: string | null = null
_reportedInvalidPcbCalcWarnings = new Set<string>()
private _reportInvalidComponentPropertyError(
propertyName: string,
message: string,
): void {
if (!this.root || this._reportedInvalidPcbCalcWarnings.has(propertyName)) {
return
}
this.root.db.source_invalid_component_property_error.insert({
source_component_id: this.source_component_id || "",
property_name: propertyName,
message,
error_type: "source_invalid_component_property_error",
})
this._reportedInvalidPcbCalcWarnings.add(propertyName)
}
fallbackUnassignedName?: string
constructor(props: z.input<ZodProps>) {
super(props)
this.children = []
this.childrenPendingRemoval = []
this.props = props ?? {}
this.externallyAddedAliases = []
const zodProps =
"partial" in this.config.zodProps
? (this.config.zodProps as z.ZodObject<any, any, any>).partial({
name: true,
})
: this.config.zodProps
const parsePropsResult = zodProps.safeParse(props ?? {})
if (parsePropsResult.success) {
this._parsedProps = parsePropsResult.data as z.infer<ZodProps>
} else {
throw new InvalidProps(
this.lowercaseComponentName,
this.props,
parsePropsResult.error.format(),
)
}
}
setProps(props: Partial<z.input<ZodProps>>) {
const newProps = this.config.zodProps.parse({
...this.props,
...props,
}) as z.infer<ZodProps>
const oldProps = this.props
this.props = newProps
this._parsedProps = this.config.zodProps.parse(props) as z.infer<ZodProps>
this.onPropsChange({
oldProps,
newProps,
changedProps: Object.keys(props),
})
this.parent?.onChildChanged?.(this)
}
_getPcbRotationBeforeLayout(): number | null {
const { pcbRotation } = this.props as any
if (typeof pcbRotation === "string") {
return parseFloat(pcbRotation)
}
return pcbRotation ?? null
}
getResolvedPcbPositionProp(): { pcbX: number; pcbY: number } {
return {
pcbX: this._resolvePcbCoordinate((this._parsedProps as any).pcbX, "pcbX"),
pcbY: this._resolvePcbCoordinate((this._parsedProps as any).pcbY, "pcbY"),
}
}
doInitialValidatePcbCoordinates(): void {
if (this.root?.pcbDisabled) return
const rawProps = this.props
const rawPcbX = rawProps.pcbX
const rawPcbY = rawProps.pcbY
this._validatePcbCoordinateReferences({
rawValue: rawPcbX,
axis: "pcbX",
propertyName: "pcbX",
})
this._validatePcbCoordinateReferences({
rawValue: rawPcbY,
axis: "pcbY",
propertyName: "pcbY",
})
}
protected _validatePcbCoordinateReferences(params: {
rawValue: unknown
axis: "pcbX" | "pcbY"
propertyName?: string
}): void {
const { rawValue, axis, propertyName = axis } = params
if (typeof rawValue !== "string") return
const isNormalComponent = (this as any)._isNormalComponent === true
const allowComponentVariables =
!isNormalComponent && !this._isInsideFootprint()
let calcIdentifiers: string[] = []
try {
calcIdentifiers = extractCalcIdentifiers(rawValue)
} catch {
this._reportInvalidComponentPropertyError(
propertyName,
`Invalid ${propertyName} value for ${this.componentName}: Invalid calc() expression. expression="${rawValue}"`,
)
return
}
const includesComponentVariable = calcIdentifiers.some(
(identifier) => !identifier.startsWith("board."),
)
if (includesComponentVariable && !allowComponentVariables) {
this._reportInvalidComponentPropertyError(
propertyName,
`Invalid ${propertyName} value for ${this.componentName}: component-relative calc references are not supported for footprint elements (${this.componentName}); ${propertyName} will be ignored. expression="${rawValue}"`,
)
}
}
protected _resolvePcbCoordinate(
rawValue: unknown,
axis: "pcbX" | "pcbY",
options: {
allowBoardVariables?: boolean
allowComponentVariables?: boolean
componentVariables?: Record<string, number>
propertyName?: string
} = {},
): number {
if (rawValue == null) return 0
const propertyName = options.propertyName ?? axis
if (typeof rawValue === "number") {
if (Number.isFinite(rawValue)) return rawValue
return 0
}
if (typeof rawValue !== "string") {
throw new Error(
`Invalid ${axis} value for ${this.componentName}: ${String(rawValue)}`,
)
}
const allowBoardVariables =
options.allowBoardVariables ?? this._shouldAllowBoardVariablesByDefault()
const isNormalComponent = (this as any)._isNormalComponent === true
const allowComponentVariables =
options.allowComponentVariables ??
(!isNormalComponent && !this._isInsideFootprint())
const includesBoardVariable = rawValue.includes("board.")
const knownVariables: Record<string, number> = {}
if (allowBoardVariables) {
const board = this._getBoard()
const boardVariables = board?._getBoardCalcVariables() ?? {}
if (includesBoardVariable && !board) {
this._reportInvalidComponentPropertyError(
propertyName,
`Invalid ${propertyName} value for ${this.componentName}: no board found for board.* variables. expression="${rawValue}"`,
)
return 0
}
if (
includesBoardVariable &&
board &&
Object.keys(boardVariables).length === 0
) {
this._reportInvalidComponentPropertyError(
propertyName,
`Invalid ${propertyName} value for ${this.componentName}: Cannot do calculations based on board size when the board is auto-sized. expression="${rawValue}"`,
)
return 0
}
Object.assign(knownVariables, boardVariables)
}
if (allowComponentVariables) {
const db = this.root?.db
if (db) {
Object.assign(knownVariables, getSubcircuitPcbCalcVariables(db))
}
Object.assign(knownVariables, options.componentVariables ?? {})
}
try {
const calcIdentifiers = extractCalcIdentifiers(rawValue)
const includesComponentVariable = calcIdentifiers.some(
(identifier) => !identifier.startsWith("board."),
)
if (includesComponentVariable && !allowComponentVariables) {
if (
this._isInsideFootprint() &&
this.root &&
!this._reportedInvalidPcbCalcWarnings.has(axis)
) {
this.root.db.source_invalid_component_property_error.insert({
source_component_id: this.source_component_id || "",
property_name: axis,
message:
`component-relative calc references are not supported for footprint elements (${this.componentName}); ` +
`${axis} will be ignored. expression="${rawValue}"`,
error_type: "source_invalid_component_property_error",
})
this._reportedInvalidPcbCalcWarnings.add(axis)
}
return 0
}
return evaluateCalcString(rawValue, { knownVariables })
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
this._reportInvalidComponentPropertyError(
propertyName,
`Invalid ${propertyName} value for ${this.componentName}: ${message}. expression="${rawValue}"`,
)
return 0
}
}
private _shouldAllowBoardVariablesByDefault(): boolean {
const isNormalComponent = (this as any)._isNormalComponent === true
if (isNormalComponent) return true
return !this._isInsideFootprint() && !this._isInsideNonBoardSubcircuit()
}
private _isInsideFootprint(): boolean {
let current: PrimitiveComponent | null = this.parent
while (current) {
if ((current as any).componentName === "Footprint") {
return true
}
current = current.parent
}
return false
}
private _isInsideNonBoardSubcircuit(): boolean {
let current: PrimitiveComponent | null = this.parent
while (current) {
const componentName = (current as any).componentName
if (componentName === "Board" || componentName === "MountedBoard") {
return false
}
if (current.isSubcircuit) {
return true
}
current = current.parent
}
return false
}
/**
* Check if this component has a user-defined PCB position.
* Position can be specified via pcbX/pcbY or edge-based props.
*/
_hasUserDefinedPcbPosition(): boolean {
const props = this._parsedProps
return (
props.pcbX !== undefined ||
props.pcbY !== undefined ||
props.pcbLeftEdgeX !== undefined ||
props.pcbRightEdgeX !== undefined ||
props.pcbTopEdgeY !== undefined ||
props.pcbBottomEdgeY !== undefined
)
}
resolvePcbCoordinate(params: {
rawValue: unknown
axis: "pcbX" | "pcbY"
allowBoardVariables?: boolean
allowComponentVariables?: boolean
componentVariables?: Record<string, number>
propertyName?: string
}): number {
const {
rawValue,
axis,
allowBoardVariables,
allowComponentVariables,
componentVariables,
propertyName,
} = params
return this._resolvePcbCoordinate(rawValue, axis, {
allowBoardVariables,
allowComponentVariables,
componentVariables,
propertyName,
})
}
/**
* Computes a transformation matrix from the props of this component for PCB
* components
*/
computePcbPropsTransform(): Matrix {
const rotation = this._getPcbRotationBeforeLayout() ?? 0
const { pcbX, pcbY } = this.getResolvedPcbPositionProp()
const matrix = compose(
translate(pcbX, pcbY),
rotate((rotation * Math.PI) / 180),
)
return matrix
}
/**
* Compute a transformation matrix combining all parent transforms for PCB
* components, including this component's translation and rotation.
*
* This is used to compute this component's position as well as all children
* components positions before layout is applied
*/
_computePcbGlobalTransformBeforeLayout(): Matrix {
const manualPlacement =
this.getSubcircuit()._getPcbManualPlacementForComponent(this)
// pcbX or pcbY will override the manual placement
if (
manualPlacement &&
this.props.pcbX === undefined &&
this.props.pcbY === undefined
) {
const rotation = this._getPcbRotationBeforeLayout() ?? 0
return compose(
this.parent?._computePcbGlobalTransformBeforeLayout() ?? identity(),
compose(
translate(manualPlacement.x, manualPlacement.y),
rotate((rotation * Math.PI) / 180),
),
)
}
// If this is a primitive, and the parent primitive container is flipped,
// we flip it's position
if (this.isPcbPrimitive) {
const { isFlipped } = this._getPcbPrimitiveFlippedHelpers()
if (isFlipped) {
return compose(
this.parent?._computePcbGlobalTransformBeforeLayout() ?? identity(),
flipY(),
this.computePcbPropsTransform(),
)
}
}
return compose(
this.parent?._computePcbGlobalTransformBeforeLayout() ?? identity(),
this.computePcbPropsTransform(),
)
}
private _getEnclosingFootprint(): PrimitiveComponent | null {
let current: PrimitiveComponent | null = this.parent
while (current) {
if (current.componentName === "Footprint") {
return current
}
current = current.parent
}
return null
}
getPrimitiveContainer(): PrimitiveComponent | null {
if (this.isPrimitiveContainer) return this
return this.parent?.getPrimitiveContainer?.() ?? null
}
/**
* Get the Symbol ancestor if this component is inside a Symbol primitive container.
* Used by schematic primitives to access the symbol's resize transform.
*/
_getSymbolAncestor(): ISymbol | null {
const container = this.getPrimitiveContainer()
if (container?.componentName === "Symbol") {
return container as unknown as ISymbol
}
return null
}
/**
* Walk up the component hierarchy to find the nearest NormalComponent ancestor.
* This is useful for primitive components that need access to component IDs
* (pcb_component_id, schematic_component_id, source_component_id) from their
* parent NormalComponent, even when there are intermediate primitive containers
* like Symbol in the hierarchy.
*/
getParentNormalComponent(): any | null {
let current: any = this.parent
while (current) {
// NormalComponent has isPrimitiveContainer = true but also has these render methods
if (current.isPrimitiveContainer && current.doInitialPcbComponentRender) {
return current
}
current = current.parent
}
return null
}
/**
* Replaces text like {NAME}, {REF}, and {REFERENCE} with the
* reference designator (name) of the parent NormalComponent.
*/
protected _resolveText(): string {
const text = this._parsedProps.text
if (!text) return ""
if (
!text.includes("{NAME}") &&
!text.includes("{REF}") &&
!text.includes("{REFERENCE}")
) {
return text
}
const parentNormalComponent = this.getParentNormalComponent()
const refdes = parentNormalComponent?.name
if (!refdes) return text
return text
.replace(/\{NAME\}/g, refdes)
.replace(/\{REF\}/g, refdes)
.replace(/\{REFERENCE\}/g, refdes)
}
/**
* Emit a warning when coveredWithSolderMask is true but solderMaskMargin is also set
*/
emitSolderMaskMarginWarning(
isCoveredWithSolderMask: boolean,
solderMaskMargin: number | undefined,
): void {
if (isCoveredWithSolderMask && solderMaskMargin !== undefined) {
const parentNormalComponent = this.getParentNormalComponent()
if (parentNormalComponent?.source_component_id) {
this.root!.db.source_property_ignored_warning.insert({
source_component_id: parentNormalComponent.source_component_id,
property_name: "solderMaskMargin",
message: `solderMaskMargin is set but coveredWithSolderMask is true. When a component is fully covered with solder mask, a margin doesn't apply.`,
error_type: "source_property_ignored_warning",
})
}
}
}
/**
* Compute the PCB bounds of this component the circuit json elements
* associated with it.
*/
_getPcbCircuitJsonBounds(): {
center: { x: number; y: number }
bounds: { left: number; top: number; right: number; bottom: number }
width: number
height: number
} {
return {
center: { x: 0, y: 0 },
bounds: { left: 0, top: 0, right: 0, bottom: 0 },
width: 0,
height: 0,
}
}
/**
* Determine if this pcb primitive should be flipped because the primitive
* container is flipped
*
* TODO use footprint.originalLayer instead of assuming everything is defined
* relative to the top layer
*/
_getPcbPrimitiveFlippedHelpers(): {
isFlipped: boolean
maybeFlipLayer: (layer: LayerRef) => LayerRef
} {
const container = this.getPrimitiveContainer()
const footprint =
this.componentName === "Footprint" ? this : this._getEnclosingFootprint()
const isFlipped = !container
? false
: isFootprintFlipped({
componentLayer: container._parsedProps.layer,
originalLayer: footprint?._parsedProps.originalLayer,
})
const maybeFlipLayer = (layer: LayerRef) => {
if (isFlipped) {
return layer === "top" ? "bottom" : "top"
}
return layer
}
return { isFlipped, maybeFlipLayer }
}
/**
* Set the position of this component from the layout solver. This method
* should operate using CircuitJson associated with this component, like
* _getPcbCircuitJsonBounds it can be called multiple times as different
* parents apply layout to their children.
*/
_setPositionFromLayout(newCenter: { x: number; y: number }) {
throw new Error(
`_setPositionFromLayout not implemented for ${this.componentName}`,
)
}
/**
* Computes a transformation matrix from the props of this component for
* schematic components
*/
computeSchematicPropsTransform(): Matrix {
const { _parsedProps: props } = this
return compose(translate(props.schX ?? 0, props.schY ?? 0))
}
/**
* Compute a transformation matrix combining all parent transforms for this
* component
*/
computeSchematicGlobalTransform(): Matrix {
const manualPlacementTransform =
this._getSchematicGlobalManualPlacementTransform(this)
if (manualPlacementTransform) return manualPlacementTransform
return compose(
this.parent?.computeSchematicGlobalTransform?.() ?? identity(),
this.computeSchematicPropsTransform(),
)
}
_getSchematicSymbolName(): keyof typeof symbols | undefined {
const { _parsedProps: props } = this
const base_symbol_name = this.config
.schematicSymbolName as keyof typeof symbols
// derive rotation from schOrientation if provided
const orientationRotationMap: Record<string, number> = {
horizontal: 0,
pos_left: 0,
neg_right: 0,
pos_right: 180,
neg_left: 180,
pos_top: 270,
neg_bottom: 90,
vertical: 270,
pos_bottom: 90,
neg_top: 90,
}
let normalizedRotation =
props.schOrientation !== undefined
? orientationRotationMap[props.schOrientation]
: props.schRotation
if (normalizedRotation === undefined) {
normalizedRotation = 0
}
// Normalize rotation to be between 0 and 360
normalizedRotation = normalizedRotation % 360
if (normalizedRotation < 0) {
normalizedRotation += 360
}
// Validate that rotation is a multiple of 90 degrees
if (props.schRotation !== undefined && normalizedRotation % 90 !== 0) {
throw new Error(
`Schematic rotation ${props.schRotation} is not supported for ${this.componentName}`,
)
}
const symbol_name_horz = `${base_symbol_name}_horz` as keyof typeof symbols
const symbol_name_vert = `${base_symbol_name}_vert` as keyof typeof symbols
const symbol_name_up = `${base_symbol_name}_up` as keyof typeof symbols
const symbol_name_down = `${base_symbol_name}_down` as keyof typeof symbols
const symbol_name_left = `${base_symbol_name}_left` as keyof typeof symbols
const symbol_name_right =
`${base_symbol_name}_right` as keyof typeof symbols
if (symbol_name_right in symbols && normalizedRotation === 0) {
return symbol_name_right
}
if (symbol_name_up in symbols && normalizedRotation === 90) {
return symbol_name_up
}
if (symbol_name_left in symbols && normalizedRotation === 180) {
return symbol_name_left
}
if (symbol_name_down in symbols && normalizedRotation === 270) {
return symbol_name_down
}
if (symbol_name_horz in symbols) {
if (normalizedRotation === 0) return symbol_name_horz
if (normalizedRotation === 180) return symbol_name_horz
}
if (symbol_name_vert in symbols) {
if (normalizedRotation === 90) return symbol_name_vert
if (normalizedRotation === 270) return symbol_name_vert
}
if (base_symbol_name in symbols) return base_symbol_name
return undefined
}
_getSchematicSymbolNameOrThrow(): keyof typeof symbols {
const symbol_name = this._getSchematicSymbolName()
if (!symbol_name) {
throw new Error(
`No schematic symbol found (given: "${this.config.schematicSymbolName}")`,
)
}
return symbol_name
}
getSchematicSymbol(): SchSymbol | null {
const symbol_name = this._getSchematicSymbolName()
if (!symbol_name) return null
return symbols[symbol_name as keyof typeof symbols] ?? null
}
/**
* Subcircuit groups have a prop called "layout" that can include manual
* placements for pcb components. These are typically added from an IDE
*/
_getPcbManualPlacementForComponent(
component: PrimitiveComponent,
): { x: number; y: number } | null {
if (!this.isSubcircuit) return null
const manualEdits = this.props.manualEdits
if (!manualEdits) return null
const placementConfigPositions = manualEdits?.pcb_placements
if (!placementConfigPositions) return null
for (const position of placementConfigPositions) {
if (
isMatchingSelector(component, position.selector) ||
component.props.name === position.selector
) {
const center = applyToPoint(
this._computePcbGlobalTransformBeforeLayout(),
position.center as { x: number; y: number },
)
return center
}
}
return null
}
_getSchematicManualPlacementForComponent(
component: PrimitiveComponent,
): { x: number; y: number } | null {
if (!this.isSubcircuit) return null
const manualEdits = this.props.manualEdits
if (!manualEdits) return null
const placementConfigPositions = manualEdits.schematic_placements
if (!placementConfigPositions) return null
for (const position of placementConfigPositions) {
if (
isMatchingSelector(component, position.selector) ||
component.props.name === position.selector
) {
const center = applyToPoint(
this.computeSchematicGlobalTransform(),
position.center as { x: number; y: number },
)
return center
}
}
return null
}
_getSchematicGlobalManualPlacementTransform(
component: PrimitiveComponent,
): Matrix | null {
const manualEdits = this.getSubcircuit()?._parsedProps.manualEdits
if (!manualEdits) return null
for (const position of manualEdits.schematic_placements ?? []) {
if (
isMatchingSelector(component, position.selector) ||
component.props.name === position.selector
) {
if (position.relative_to === "group_center") {
return compose(
this.parent?._computePcbGlobalTransformBeforeLayout() ?? identity(),
translate(position.center.x, position.center.y),
)
}
}
}
return null
}
_getGlobalPcbPositionBeforeLayout(): { x: number; y: number } {
return applyToPoint(this._computePcbGlobalTransformBeforeLayout(), {
x: 0,
y: 0,
})
}
_getGlobalSchematicPositionBeforeLayout(): { x: number; y: number } {
return applyToPoint(this.computeSchematicGlobalTransform(), { x: 0, y: 0 })
}
_getBoard(): (PrimitiveComponent & BoardI) | undefined {
let current: PrimitiveComponent | Renderable | null = this
while (current) {
const maybePrimitive = current as PrimitiveComponent
const componentName = (maybePrimitive as any).componentName
// MountedBoard also creates a pcb_board, so components inside should
// be associated with it, not the parent carrier board
if (componentName === "Board" || componentName === "MountedBoard") {
return maybePrimitive as PrimitiveComponent & BoardI
}
current =
(current.parent as PrimitiveComponent | Renderable | null) ?? null
}
return this.root?._getBoard() as (PrimitiveComponent & BoardI) | undefined
}
get root(): IsolatedCircuit | null {
return this.parent?.root ?? null
}
onAddToParent(parent: PrimitiveComponent) {
this.parent = parent
}
/**
* Called whenever the props change
*/
onPropsChange(params: {
oldProps: z.infer<ZodProps>
newProps: z.infer<ZodProps>
changedProps: string[]
}) {}
onChildChanged(child: PrimitiveComponent) {
this.parent?.onChildChanged?.(child)
}
add(component: PrimitiveComponent) {
// The react reconciler will try to add text nodes as children, but
// we don't have a text component, so we just ignore them. The text is
// passed as a prop to the parent component anyway.
const textContent = (component as any).__text
if (typeof textContent === "string") {
// Components that support text children already receive the text via
// their props. Simply ignore the generated text node.
if (this.canHaveTextChildren || textContent.trim() === "") {
return
}
// Otherwise this is likely accidental text in the JSX tree.
throw new Error(
`Invalid JSX Element: Expected a React component but received text "${textContent}"`,
)
}
if (Object.keys(component).length === 0) {
// Ignore empty objects produced by the reconciler in edge cases
return
}
if (component.lowercaseComponentName === "panel") {
throw new Error("<panel> must be a root-level element")
}
if (!component.onAddToParent) {
throw new Error(
`Invalid JSX Element: Expected a React component but received "${JSON.stringify(
component,
)}"`,
)
}
component.onAddToParent(this)
component.parent = this
this.children.push(component)
}
addAll(components: PrimitiveComponent[]) {
for (const component of components) {
this.add(component)
}
}
remove(component: PrimitiveComponent) {
this.children = this.children.filter((c) => c !== component)
this.childrenPendingRemoval.push(component)
component.shouldBeRemoved = true
}
getSubcircuitSelector(): string {
const name = this.name
const endPart = name
? `${this.lowercaseComponentName}.${name}`
: this.lowercaseComponentName
if (!this.parent) return endPart
if (this.parent.isSubcircuit) return endPart
return `${this.parent.getSubcircuitSelector()} > ${endPart}`
}
getFullPathSelector(): string {
const name = this.name
const endPart = name
? `${this.lowercaseComponentName}.${name}`
: this.lowercaseComponentName
const parentSelector = this.parent?.getFullPathSelector?.()
if (!parentSelector) return endPart
return `${parentSelector} > ${endPart}`
}