forked from tscircuit/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNormalComponent.ts
More file actions
1906 lines (1690 loc) · 62.6 KB
/
NormalComponent.ts
File metadata and controls
1906 lines (1690 loc) · 62.6 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 { fp } from "@tscircuit/footprinter"
import { normalizeDegrees } from "@tscircuit/math-utils"
import type {
CadModelGlb,
CadModelGltf,
CadModelJscad,
CadModelObj,
CadModelProp,
CadModelStep,
CadModelStl,
CadModelWrl,
SchematicPortArrangement,
SupplierPartNumbers,
} from "@tscircuit/props"
import {
distance,
pcb_component_invalid_layer_error,
pcb_manual_edit_conflict_warning,
point3,
rotation,
schematic_manual_edit_conflict_warning,
unknown_error_finding_part,
} from "circuit-json"
import Debug from "debug"
import { Trace } from "lib/components/primitive-components/Trace/Trace"
import {
type ReactSubtree,
createInstanceFromReactElement,
} from "lib/fiber/create-instance-from-react-element"
import { underscorifyPinStyles } from "lib/soup/underscorifyPinStyles"
import { underscorifyPortArrangement } from "lib/soup/underscorifyPortArrangement"
import { getBoundsForSchematic } from "lib/utils/autorouting/getBoundsForSchematic"
import { createNetsFromProps } from "lib/utils/components/createNetsFromProps"
import { createComponentsFromCircuitJson } from "lib/utils/createComponentsFromCircuitJson"
import { filterPinLabels } from "lib/utils/filterPinLabels"
import { getBoundsOfPcbComponents } from "lib/utils/get-bounds-of-pcb-components"
import {
getPinNumberFromLabels,
getPortFromHints,
} from "lib/utils/getPortFromHints"
import {
type SchematicBoxDimensions,
getAllDimensionsForSchematicBox,
isExplicitPinMappingArrangement,
} from "lib/utils/schematic/getAllDimensionsForSchematicBox"
import { getNumericSchPinStyle } from "lib/utils/schematic/getNumericSchPinStyle"
import { getPinsFromSideDefinition } from "lib/utils/schematic/normalizePinSideDefinition"
import { parsePinNumberFromLabelsOrThrow } from "lib/utils/schematic/parsePinNumberFromLabelsOrThrow"
import {
type ReactElement,
isValidElement as isReactElement,
isValidElement,
} from "react"
import { type SchSymbol, symbols } from "schematic-symbols"
import { decomposeTSR } from "transformation-matrix"
import { ZodType, z } from "zod"
import { CadAssembly } from "../../primitive-components/CadAssembly"
import { CadModel } from "../../primitive-components/CadModel"
import { Footprint } from "../../primitive-components/Footprint"
import { Port } from "../../primitive-components/Port"
import { PrimitiveComponent } from "../PrimitiveComponent"
import type { INormalComponent } from "./INormalComponent"
import { NormalComponent__getMinimumFlexContainerSize } from "./NormalComponent__getMinimumFlexContainerSize"
import { NormalComponent__repositionOnPcb } from "./NormalComponent__repositionOnPcb"
import { NormalComponent_doInitialPcbComponentAnchorAlignment } from "./NormalComponent_doInitialPcbComponentAnchorAlignment"
import { NormalComponent_doInitialPcbFootprintStringRender } from "./NormalComponent_doInitialPcbFootprintStringRender"
import { NormalComponent_doInitialSilkscreenOverlapAdjustment } from "./NormalComponent_doInitialSilkscreenOverlapAdjustment"
import { NormalComponent_doInitialSourceDesignRuleChecks } from "./NormalComponent_doInitialSourceDesignRuleChecks"
import { isHttpUrl } from "./utils/isHttpUrl"
import { isStaticAssetPath } from "./utils/isStaticAssetPath"
import { parseLibraryFootprintRef } from "./utils/parseLibraryFootprintRef"
const debug = Debug("tscircuit:core")
const rotation3 = z.object({
x: rotation,
y: rotation,
z: rotation,
})
export type PortMap<T extends string> = {
[K in T]: Port
}
/**
* A NormalComponent is the base class for most components that a user will
* interact with. It has the ability to set a footprint and discover ports.
*
* When you're extending a NormalComponent, you almost always want to override
* initPorts() to create ports for the component.
*
* class Led extends NormalComponent<typeof resistorProps> {
* pin1: Port = this.portMap.pin1
* pin2: Port = this.portMap.pin2
*
* initPorts() {
* this.add(new Port({ pinNumber: 1, aliases: ["anode", "pos"] }))
* this.add(new Port({ pinNumber: 2, aliases: ["cathode", "neg"] }))
* }
* }
*/
export class NormalComponent<
ZodProps extends z.ZodType = any,
PortNames extends string = never,
>
extends PrimitiveComponent<ZodProps>
implements INormalComponent
{
reactSubtrees: Array<ReactSubtree> = []
_impliedFootprint?: string | undefined
_resolvedPcbCalcOffsetX: number | undefined
_resolvedPcbCalcOffsetY: number | undefined
isPrimitiveContainer = true
_isNormalComponent = true
// Mapping from camelCase attribute names to their lowercase equivalents
// This is used by the CSS selector adapter for fast attribute lookups
// Reverse mapping from lowercase to camelCase for O(1) lookups
_attributeLowerToCamelNameMap = {
_isnormalcomponent: "_isNormalComponent",
}
_asyncSupplierPartNumbers?: SupplierPartNumbers
_asyncFootprintCadModel?: CadModelProp
_isCadModelChild?: boolean
pcb_missing_footprint_error_id?: string
_hasStartedFootprintUrlLoad = false
private _invalidPinLabelMessages: string[] = []
/**
* Set to true to enable automatic silkscreen text adjustment when it overlaps with other components
*/
_adjustSilkscreenTextAutomatically = false
/**
* Override this property for component defaults
*/
get defaultInternallyConnectedPinNames(): string[][] {
return []
}
get internallyConnectedPinNames(): string[][] {
const rawPins =
this._parsedProps.internallyConnectedPins ??
this.defaultInternallyConnectedPinNames
return rawPins.map((pinGroup: (string | number)[]) =>
pinGroup.map((pin: string | number) =>
typeof pin === "number" ? `pin${pin}` : pin,
),
)
}
constructor(props: z.input<ZodProps>) {
const filteredProps = { ...props }
let invalidPinLabelsMessages: string[] = []
// Apply invalid pin label filtering for object-based pinLabels only
// Array-based pinLabels (used by PinHeader) are left unfiltered
if (filteredProps.pinLabels && !Array.isArray(filteredProps.pinLabels)) {
const { validPinLabels, invalidPinLabelsMessages: messages } =
filterPinLabels(filteredProps.pinLabels)
filteredProps.pinLabels = validPinLabels
invalidPinLabelsMessages = messages
}
super(filteredProps)
this._invalidPinLabelMessages = invalidPinLabelsMessages
this._addChildrenFromStringFootprint()
this.initPorts()
}
doInitialSourceNameDuplicateComponentRemoval(): void {
// Early return if component has no explicit name (auto-assigned names don't conflict)
if (!this.name) return
const root = this.root!
const nameMap = this.getSubcircuit().getNormalComponentNameMap?.()
const componentsWithSameName = nameMap?.get(this.props.name) ?? []
// Check if any of these components have already been processed (initialized this phase)
const conflictingComponents = componentsWithSameName.filter(
(component: NormalComponent) =>
component !== this &&
component.renderPhaseStates.SourceNameDuplicateComponentRemoval
.initialized,
)
if (conflictingComponents.length > 0) {
// Create naming conflict error
const pcbPosition = this._getGlobalPcbPositionBeforeLayout()
const schematicPosition = this._getGlobalSchematicPositionBeforeLayout()
root.db.source_failed_to_create_component_error.insert({
component_name: this.name,
error_type: "source_failed_to_create_component_error",
message: `Cannot create component "${this.name}": A component with the same name already exists`,
pcb_center: pcbPosition,
schematic_center: schematicPosition,
})
// Mark component for removal to prevent downstream issues
this.shouldBeRemoved = true
// Remove all children to prevent them from trying to attach to a non-existent parent
const childrenToRemove = [...this.children]
for (const child of childrenToRemove) {
this.remove(child)
}
}
}
/**
* Override this method for better control over the auto-discovery of ports.
*
* If you override this method just do something like:
* initPorts() {
* this.add(new Port({ pinNumber: 1, aliases: ["anode", "pos"] }))
* this.add(new Port({ pinNumber: 2, aliases: ["cathode", "neg"] }))
* }
*
* By default, we'll pull the ports from the first place we find them:
* 1. `config.schematicSymbolName`
* 2. `props.footprint`
*
*/
initPorts(
opts: {
additionalAliases?: Record<`pin${number}`, string[]>
pinCount?: number
ignoreSymbolPorts?: boolean
} = {},
) {
if (this.root?.schematicDisabled) return
const { config } = this
const portsToCreate: Port[] = []
// Handle schPortArrangement
const schPortArrangement = this._getSchematicPortArrangement()
if (schPortArrangement && !this._parsedProps.pinLabels) {
for (const side in schPortArrangement) {
const pins = (schPortArrangement as any)[side].pins
if (Array.isArray(pins)) {
for (const pinNumberOrLabel of pins) {
const pinNumber = parsePinNumberFromLabelsOrThrow(
pinNumberOrLabel,
this._parsedProps.pinLabels,
)
portsToCreate.push(
new Port(
{
pinNumber,
aliases: opts.additionalAliases?.[`pin${pinNumber}`] ?? [],
},
{
originDescription: `schPortArrangement:${side}`,
},
),
)
}
}
}
// Takes care of the case where the user only specifies the size of the
// sides, and not the pins
const sides = ["left", "right", "top", "bottom"]
let pinNum = 1
for (const side of sides) {
const size = (schPortArrangement as any)[`${side}Size`]
for (let i = 0; i < size; i++) {
portsToCreate.push(
new Port(
{
pinNumber: pinNum++,
aliases: opts.additionalAliases?.[`pin${pinNum}`] ?? [],
},
{
originDescription: `schPortArrangement:${side}`,
},
),
)
}
}
}
const pinLabels: Record<string, string | string[]> | undefined =
this._parsedProps.pinLabels
if (pinLabels) {
for (let [pinNumber, label] of Object.entries(pinLabels)) {
pinNumber = pinNumber.replace("pin", "")
let existingPort = portsToCreate.find(
(p) => p._parsedProps.pinNumber === Number(pinNumber),
)
const primaryLabel = Array.isArray(label) ? label[0] : label
const otherLabels = Array.isArray(label) ? label.slice(1) : []
if (!existingPort) {
existingPort = new Port(
{
pinNumber: parseInt(pinNumber),
name: primaryLabel,
aliases: [
...otherLabels,
...(opts.additionalAliases?.[`pin${parseInt(pinNumber)}`] ??
[]),
],
},
{
originDescription: `pinLabels:pin${pinNumber}`,
},
)
portsToCreate.push(existingPort)
} else {
existingPort.externallyAddedAliases.push(primaryLabel, ...otherLabels)
existingPort.props.name = primaryLabel
}
}
}
if (config.schematicSymbolName && !opts.ignoreSymbolPorts) {
const sym = symbols[this._getSchematicSymbolNameOrThrow()]
if (!sym) return
for (const symPort of sym.ports) {
const pinNumber = getPinNumberFromLabels(symPort.labels)
if (!pinNumber) continue
const existingPort = portsToCreate.find(
(p) => p._parsedProps.pinNumber === Number(pinNumber),
)
if (existingPort) {
existingPort.schematicSymbolPortDef = symPort
} else {
const port = getPortFromHints(
symPort.labels.concat(
opts.additionalAliases?.[`pin${pinNumber}`] ?? [],
),
)
if (port) {
port.originDescription = `schematicSymbol:labels[0]:${symPort.labels[0]}`
port.schematicSymbolPortDef = symPort
portsToCreate.push(port)
}
}
}
this.addAll(portsToCreate)
}
if (!this._getSchematicPortArrangement()) {
const hasReactSymbol = isValidElement(this.props.symbol)
const symbolAlreadyAdded = this.children.some(
(c) => c.componentName === "Symbol",
)
if (hasReactSymbol && !symbolAlreadyAdded) {
} else {
const portsFromFootprint = this.getPortsFromFootprint(opts)
const existingPorts = this._getAllPortsFromChildren()
for (const port of portsFromFootprint) {
const alreadyInPortsToCreate = portsToCreate.some((p) =>
p.isMatchingAnyOf(port.getNameAndAliases()),
)
const alreadyInExistingPorts = existingPorts.some((p) =>
p.isMatchingAnyOf(port.getNameAndAliases()),
)
if (!alreadyInPortsToCreate && !alreadyInExistingPorts) {
portsToCreate.push(port)
}
}
}
}
// Add ports that we know must exist because we know the pin count and
// missing pin numbers, and they are inside the pins array of the
// schPortArrangement
const requiredPinCount = opts.pinCount ?? this._getPinCount() ?? 0
for (let pn = 1; pn <= requiredPinCount; pn++) {
if (portsToCreate.find((p) => p._parsedProps.pinNumber === pn)) continue
if (!schPortArrangement) {
portsToCreate.push(
new Port({
pinNumber: pn,
aliases: opts.additionalAliases?.[`pin${pn}`] ?? [],
}),
)
continue
}
let explicitlyListedPinNumbersInSchPortArrangement = [
...getPinsFromSideDefinition(schPortArrangement.leftSide),
...getPinsFromSideDefinition(schPortArrangement.rightSide),
...getPinsFromSideDefinition(schPortArrangement.topSide),
...getPinsFromSideDefinition(schPortArrangement.bottomSide),
].map((pn) =>
parsePinNumberFromLabelsOrThrow(pn, this._parsedProps.pinLabels),
)
if (
[
"leftSize",
"rightSize",
"topSize",
"bottomSize",
"leftPinCount",
"rightPinCount",
"topPinCount",
"bottomPinCount",
].some((key) => key in schPortArrangement)
) {
explicitlyListedPinNumbersInSchPortArrangement = Array.from(
{ length: this._getPinCount() },
(_, i) => i + 1,
)
}
if (!explicitlyListedPinNumbersInSchPortArrangement.includes(pn)) {
continue
}
portsToCreate.push(
new Port(
{
pinNumber: pn,
aliases: opts.additionalAliases?.[`pin${pn}`] ?? [],
},
{
originDescription: `notOtherwiseAddedButDeducedFromPinCount:${pn}`,
},
),
)
}
// If no ports were created, don't throw an error
if (portsToCreate.length > 0) {
this.addAll(portsToCreate)
}
}
_getImpliedFootprintString(): string | null {
return null
}
_addChildrenFromStringFootprint() {
const { pcbRotation, pinLabels, pcbPinLabels } = this.props
let { footprint } = this.props
footprint ??= this._getImpliedFootprintString?.()
if (!footprint) return
if (typeof footprint === "string") {
if (isHttpUrl(footprint)) return
if (isStaticAssetPath(footprint)) return
if (parseLibraryFootprintRef(footprint)) return
const fpSoup = fp.string(footprint).soup()
const fpComponents = createComponentsFromCircuitJson(
{
componentName: this.name ?? this.componentName,
componentRotation: pcbRotation,
footprinterString: footprint,
pinLabels,
pcbPinLabels,
},
fpSoup as any,
) // Remove as any when footprinter gets updated
this.addAll(fpComponents)
}
}
get portMap(): PortMap<PortNames> {
return new Proxy(
{},
{
get: (target, prop): Port => {
const port = this.children.find(
(c) =>
c.componentName === "Port" &&
(c as Port).isMatchingNameOrAlias(prop as string),
)
if (!port) {
throw new Error(
`There was an issue finding the port "${prop.toString()}" inside of a ${
this.componentName
} component with name: "${
this.props.name
}". This is a bug in @tscircuit/core`,
)
}
return port as Port
},
},
) as any
}
getInstanceForReactElement(element: ReactElement): NormalComponent | null {
for (const subtree of this.reactSubtrees) {
if (subtree.element === element) return subtree.component
}
return null
}
doInitialSourceRender() {
const ftype = this.config.sourceFtype
if (!ftype) return
const { db } = this.root!
const { _parsedProps: props } = this
const source_component = db.source_component.insert({
ftype,
name: this.name,
manufacturer_part_number: props.manufacturerPartNumber ?? props.mfn,
supplier_part_numbers: props.supplierPartNumbers,
display_name: props.displayName,
})
this.source_component_id = source_component.source_component_id
}
/**
* After ports have their source_port_id assigned, create
* source_component_internal_connection records so that the connectivity
* map (and therefore DRC) knows which pins are internally connected.
*/
doInitialSourceParentAttachment(): void {
const { db } = this.root!
const internallyConnectedPorts = this._getInternallyConnectedPins()
for (const ports of internallyConnectedPorts) {
const sourcePortIds = ports
.map((port: Port) => port.source_port_id)
.filter((id): id is string => id !== null)
if (sourcePortIds.length >= 2) {
db.source_component_internal_connection.insert({
source_component_id: this.source_component_id!,
subcircuit_id: this.getSubcircuit()?.subcircuit_id!,
source_port_ids: sourcePortIds,
})
}
}
}
/**
* Render the schematic component for this NormalComponent using the
* config.schematicSymbolName if it exists, or create a generic box if
* no symbol is defined.
*
* You can override this method to do more complicated things.
*/
doInitialSchematicComponentRender() {
if (this.root?.schematicDisabled) return
const { db } = this.root!
// Insert warnings for invalid pin labels
if (this._invalidPinLabelMessages?.length && this.root?.db) {
for (const message of this._invalidPinLabelMessages) {
let property_name = "pinLabels"
const match = message.match(
/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/,
)
if (match) {
const label = match[2]
property_name = `pinLabels['${label}']`
}
this.root.db.source_property_ignored_warning.insert({
source_component_id: this.source_component_id!,
property_name,
message,
error_type: "source_property_ignored_warning",
})
}
}
const { schematicSymbolName } = this.config
const { _parsedProps: props } = this
// Check if there's a custom symbol JSX prop
if (props.symbol && isReactElement(props.symbol)) {
this._doInitialSchematicComponentRenderWithReactSymbol(props.symbol)
} else if (schematicSymbolName) {
this._doInitialSchematicComponentRenderWithSymbol()
} else {
const dimensions = this._getSchematicBoxDimensions()
if (dimensions) {
this._doInitialSchematicComponentRenderWithSchematicBoxDimensions()
}
}
const manualPlacement =
this.getSubcircuit()?._getSchematicManualPlacementForComponent(this)
if (
this.schematic_component_id &&
(this.props.schX !== undefined || this.props.schY !== undefined) &&
!!manualPlacement
) {
if (!this.schematic_component_id) {
return
}
const warning = schematic_manual_edit_conflict_warning.parse({
type: "schematic_manual_edit_conflict_warning",
schematic_manual_edit_conflict_warning_id: `schematic_manual_edit_conflict_${this.source_component_id}`,
message: `${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,
schematic_component_id: this.schematic_component_id!,
source_component_id: this.source_component_id!,
subcircuit_id: this.getSubcircuit()?.subcircuit_id,
})
db.schematic_manual_edit_conflict_warning.insert(warning)
}
// No schematic symbol or dimensions defined, this could be a board, group
// or other NormalComponent that doesn't have a schematic representation
}
_getSchematicSymbolDisplayValue(): string | undefined {
return undefined
}
_getInternallyConnectedPins(): Port[][] {
if (this.internallyConnectedPinNames.length === 0) return []
const internallyConnectedPorts: Port[][] = []
for (const netPortNames of this.internallyConnectedPinNames) {
const ports: Port[] = []
for (const portName of netPortNames) {
ports.push(this.portMap[portName as PortNames] as Port)
}
internallyConnectedPorts.push(ports)
}
return internallyConnectedPorts
}
_doInitialSchematicComponentRenderWithSymbol() {
if (this.root?.schematicDisabled) return
const { db } = this.root!
const { _parsedProps: props } = this
const symbol_name = this._getSchematicSymbolNameOrThrow()
const symbol: SchSymbol | undefined = symbols[symbol_name]
const center = this._getGlobalSchematicPositionBeforeLayout()
if (symbol) {
const schematic_component = db.schematic_component.insert({
center,
size: { ...symbol.size },
source_component_id: this.source_component_id!,
is_box_with_pins: true,
symbol_name,
symbol_display_value: this._getSchematicSymbolDisplayValue(),
})
this.schematic_component_id = schematic_component.schematic_component_id
}
}
_doInitialSchematicComponentRenderWithReactSymbol(
symbolElement: ReactElement,
) {
if (this.root?.schematicDisabled) return
const { db } = this.root!
const center = this._getGlobalSchematicPositionBeforeLayout()
const schematic_component = db.schematic_component.insert({
center,
// width/height are computed in the SchematicComponentSizeCalculation phase
size: { width: 0, height: 0 },
source_component_id: this.source_component_id!,
symbol_display_value: this._getSchematicSymbolDisplayValue(),
is_box_with_pins: false,
})
this.schematic_component_id = schematic_component.schematic_component_id
}
_doInitialSchematicComponentRenderWithSchematicBoxDimensions() {
if (this.root?.schematicDisabled) return
const { db } = this.root!
const { _parsedProps: props } = this
const dimensions = this._getSchematicBoxDimensions()!
const primaryPortLabels: Record<string, string> = {}
if (Array.isArray(props.pinLabels)) {
props.pinLabels.forEach((label: string, index: number) => {
primaryPortLabels[String(index + 1)] = label
})
} else {
for (const [port, label] of Object.entries(props.pinLabels ?? {})) {
primaryPortLabels[port] = Array.isArray(label) ? label[0] : label
}
}
const center = this._getGlobalSchematicPositionBeforeLayout()
const schPortArrangement = this._getSchematicPortArrangement()
const schematic_component = db.schematic_component.insert({
center,
rotation: props.schRotation ?? 0,
size: dimensions.getSize(),
// We should be using the full size, but circuit-to-svg incorrectly
// uses the schematic_component size to draw boxes instead of the
// schematic_box size
// size: dimensions.getSizeIncludingPins(),
port_arrangement: underscorifyPortArrangement(schPortArrangement!),
pin_spacing: props.schPinSpacing ?? 0.2,
// @ts-ignore soup needs to support distance for pin_styles
pin_styles: underscorifyPinStyles(props.schPinStyle, props.pinLabels),
port_labels: primaryPortLabels,
source_component_id: this.source_component_id!,
})
const hasTopOrBottomPins =
schPortArrangement?.topSide !== undefined ||
schPortArrangement?.bottomSide !== undefined
const schematic_box_width = dimensions?.getSize().width
const schematic_box_height = dimensions?.getSize().height
const manufacturer_part_number_schematic_text = db.schematic_text.insert({
text: props.manufacturerPartNumber ?? "",
schematic_component_id: schematic_component.schematic_component_id,
anchor: "left",
rotation: 0,
position: {
x: hasTopOrBottomPins
? center.x + (schematic_box_width ?? 0) / 2 + 0.1
: center.x - (schematic_box_width ?? 0) / 2,
y: hasTopOrBottomPins
? center.y + (schematic_box_height ?? 0) / 2 + 0.35
: center.y - (schematic_box_height ?? 0) / 2 - 0.13,
},
color: "#006464",
font_size: 0.18,
})
const component_name_text = db.schematic_text.insert({
text: props.displayName ?? props.name ?? "",
schematic_component_id: schematic_component.schematic_component_id,
anchor: "left",
rotation: 0,
position: {
x: hasTopOrBottomPins
? center.x + (schematic_box_width ?? 0) / 2 + 0.1
: center.x - (schematic_box_width ?? 0) / 2,
y: hasTopOrBottomPins
? center.y + (schematic_box_height ?? 0) / 2 + 0.55
: center.y + (schematic_box_height ?? 0) / 2 + 0.13,
},
color: "#006464",
font_size: 0.18,
})
this.schematic_component_id = schematic_component.schematic_component_id
}
doInitialPcbComponentRender() {
if (this.root?.pcbDisabled) return
const { db } = this.root!
const { _parsedProps: props } = this
const subcircuit = this.getSubcircuit()
// Validate that components can only be placed on top or bottom layers
const componentLayer = props.layer ?? "top"
if (componentLayer !== "top" && componentLayer !== "bottom") {
const error = pcb_component_invalid_layer_error.parse({
type: "pcb_component_invalid_layer_error",
message: `Component cannot be placed on layer '${componentLayer}'. Components can only be placed on 'top' or 'bottom' layers.`,
source_component_id: this.source_component_id!,
layer: componentLayer,
subcircuit_id: subcircuit.subcircuit_id ?? undefined,
})
db.pcb_component_invalid_layer_error.insert(error)
// Still create the component but with 'top' as fallback to avoid cascading errors
}
// Calculate accumulated rotation from parent transforms
const globalTransform = this._computePcbGlobalTransformBeforeLayout()
const decomposedTransform = decomposeTSR(globalTransform)
const accumulatedRotation =
(decomposedTransform.rotation.angle * 180) / Math.PI
const pcb_component = db.pcb_component.insert({
center: this._getGlobalPcbPositionBeforeLayout(),
// width/height are computed in the PcbComponentSizeCalculation phase
width: 0,
height: 0,
layer:
componentLayer === "top" || componentLayer === "bottom"
? componentLayer
: "top",
rotation: props.pcbRotation ?? accumulatedRotation,
source_component_id: this.source_component_id!,
subcircuit_id: subcircuit.subcircuit_id ?? undefined,
do_not_place: props.doNotPlace ?? false,
obstructs_within_bounds: props.obstructsWithinBounds ?? true,
metadata: props.kicadFootprintMetadata
? { kicad_footprint: props.kicadFootprintMetadata }
: undefined,
})
const footprint = props.footprint ?? this._getImpliedFootprintString()
// Check if we have a Footprint child (e.g., from inflated circuit JSON)
const hasFootprintChild = this.children.some(
(c) => c.componentName === "Footprint",
)
if (!footprint && !hasFootprintChild && !this.isGroup) {
const footprint_error = db.pcb_missing_footprint_error.insert({
message: `No footprint specified for component: ${this.getString()}`,
source_component_id: `${this.source_component_id}`,
error_type: "pcb_missing_footprint_error",
})
this.pcb_missing_footprint_error_id =
footprint_error.pcb_missing_footprint_error_id
}
this.pcb_component_id = pcb_component.pcb_component_id
const manualPlacement =
this.getSubcircuit()._getPcbManualPlacementForComponent(this)
if (
(this.props.pcbX !== undefined || this.props.pcbY !== undefined) &&
!!manualPlacement
) {
const warning = pcb_manual_edit_conflict_warning.parse({
type: "pcb_manual_edit_conflict_warning",
pcb_manual_edit_conflict_warning_id: `pcb_manual_edit_conflict_${this.source_component_id}`,
message: `${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,
pcb_component_id: this.pcb_component_id!,
source_component_id: this.source_component_id!,
subcircuit_id: subcircuit.subcircuit_id ?? undefined,
})
db.pcb_manual_edit_conflict_warning.insert(warning)
}
}
/**
* At this stage, the smtpads/pcb primitives are placed, so we can compute
* the width/height of the component
*/
doInitialPcbComponentSizeCalculation(): void {
if (this.root?.pcbDisabled) return
if (!this.pcb_component_id) return
const { db } = this.root!
const bounds = getBoundsOfPcbComponents(this.children)
if (bounds.width === 0 || bounds.height === 0) return
const center = {
x: (bounds.minX + bounds.maxX) / 2,
y: (bounds.minY + bounds.maxY) / 2,
}
db.pcb_component.update(this.pcb_component_id!, {
center,
width: bounds.width,
height: bounds.height,
})
}
updatePcbComponentSizeCalculation(): void {
this.doInitialPcbComponentSizeCalculation()
}
/**
* Calculate and update the size of a custom schematic symbol based on its children
*/
doInitialSchematicComponentSizeCalculation(): void {
if (this.root?.schematicDisabled) return
if (!this.schematic_component_id) return
const { db } = this.root!
const schematic_component = db.schematic_component.get(
this.schematic_component_id,
)
// Only update size for custom symbols (not predefined symbols)
if (!schematic_component) return
// Get all schematic primitives from this component's subtree (recursively)
const schematicElements: any[] = []
const collectSchematicPrimitives = (children: any[]) => {
for (const child of children) {
if (
child.isSchematicPrimitive &&
child.componentName === "SchematicLine"
) {
const line = db.schematic_line.get((child as any).schematic_line_id)
if (line) schematicElements.push(line)
}
if (
child.isSchematicPrimitive &&
child.componentName === "SchematicRect"
) {
const rect = db.schematic_rect.get((child as any).schematic_rect_id)
if (rect) schematicElements.push(rect)
}
if (
child.isSchematicPrimitive &&
child.componentName === "SchematicCircle"
) {
const circle = db.schematic_circle.get(
(child as any).schematic_circle_id,
)
if (circle) schematicElements.push(circle)
}
if (
child.isSchematicPrimitive &&
child.componentName === "SchematicArc"
) {
const arc = db.schematic_arc.get((child as any).schematic_arc_id)
if (arc) schematicElements.push(arc)
}
if (
child.isSchematicPrimitive &&
child.componentName === "SchematicText"
) {
const text = db.schematic_text.get((child as any).schematic_text_id)
if (text) schematicElements.push(text)
}
if (
child.isSchematicPrimitive &&
child.componentName === "SchematicPath"
) {
const pathIds = (child as any).schematic_path_ids as string[]
if (pathIds) {
for (const pathId of pathIds) {
const path = db.schematic_path.get(pathId)
if (path) schematicElements.push(path)
}
}
}
// Recursively check children
if (child.children && child.children.length > 0) {
collectSchematicPrimitives(child.children)
}
}
}
collectSchematicPrimitives(this.children)
if (schematicElements.length === 0) return
const bounds = getBoundsForSchematic(schematicElements)
const width = Math.abs(bounds.maxX - bounds.minX)
const height = Math.abs(bounds.maxY - bounds.minY)
if (width === 0 && height === 0) return
// Calculate the center of the bounds
// The schematic_component center should be centered around its contents
const centerX = (bounds.minX + bounds.maxX) / 2
const centerY = (bounds.minY + bounds.maxY) / 2
// Update the schematic component with calculated bounds and center
db.schematic_component.update(this.schematic_component_id!, {
center: {
x: centerX,
y: centerY,
},
size: {
width,
height,
},
})
}
updateSchematicComponentSizeCalculation(): void {
this.doInitialSchematicComponentSizeCalculation()
}
doInitialPcbComponentAnchorAlignment(): void {
NormalComponent_doInitialPcbComponentAnchorAlignment(this)
}
updatePcbComponentAnchorAlignment(): void {
this.doInitialPcbComponentAnchorAlignment()
}
_renderReactSubtree(element: ReactElement): ReactSubtree {
const component = createInstanceFromReactElement(element)
return {
element,
component,
}
}
doInitialInitializePortsFromChildren(): void {
this.initPorts()
}
doInitialReactSubtreesRender(): void {
// Add React-based footprint subtree if provided
const fpElm = this.props.footprint
if (isValidElement(fpElm)) {
const hasFootprintChild = this.children.some(
(c) => c.componentName === "Footprint",