-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1845 lines (1712 loc) · 133 KB
/
Copy pathapp.js
File metadata and controls
1845 lines (1712 loc) · 133 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
(() => {
'use strict';
const STORAGE_KEY = 'wiresketch-state-v1';
const DEFAULT_BOARD_NAMES = ['ESP32 DevKit','OLED 0.96','USB-TTL'];
const PCB_SCHEMA_ID = 'urn:wiresketch:schema:pcb:1.0';
const ASSEMBLY_SCHEMA_ID = 'urn:wiresketch:schema:assembly:1.0';
const PIN_COLORS = ['#f05e55', '#30343b', '#f2b642', '#4c8beb', '#40ae79', '#9b6bdf', '#eb7ab1', '#59adb4'];
const INTERFACE_TYPE_DEFAULT_PINS = {
uart: ['VCC', 'GND', 'RX', 'TX'],
i2c: ['VCC', 'GND', 'SCL', 'SDA'],
spi: ['VCC', 'GND', 'SCLK', 'MISO', 'MOSI', 'CSN'],
power: ['V+', 'G'],
usb: ['VCC', 'GND', 'DP', 'DN']
};
const DEFAULT_WIRE_STYLE = {width:2.2, gap:6, routeGap:6, cornerRadius:0, showFromLabels:true, showToLabels:true};
const DEFAULT_FREE_TEXT_STYLE = {fontSize:16,fontFamily:'sans-serif',fontWeight:500,color:'#25334a',shadow:{enabled:false,color:'#000000',blur:3,offsetX:0,offsetY:2}};
const FONT_WEIGHTS = [300,500,700];
const COMPATIBLE_FONT_WEIGHTS = [300,400,500,600,700,800,900];
const FONT_FAMILIES = {
'sans-serif':'Inter,ui-sans-serif,system-ui,sans-serif',
serif:'Georgia,"Times New Roman",serif',
monospace:'ui-monospace,SFMono-Regular,Consolas,monospace',
Arial:'Arial,sans-serif',
Helvetica:'Helvetica,Arial,sans-serif',
Verdana:'Verdana,sans-serif',
Tahoma:'Tahoma,sans-serif',
Georgia:'Georgia,serif',
TimesNewRoman:'"Times New Roman",serif',
CourierNew:'"Courier New",monospace',
MicrosoftYaHei:'"Microsoft YaHei","微软雅黑",sans-serif',
PingFangSC:'"PingFang SC","苹方",sans-serif',
NotoSansSC:'"Noto Sans CJK SC","Noto Sans SC","思源黑体",sans-serif',
SimHei:'SimHei,"黑体",sans-serif',
SimSun:'SimSun,"宋体",serif',
KaiTi:'KaiTi,"楷体",serif',
FangSong:'FangSong,"仿宋",serif'
};
const NODE = { width: 230, height: 215, imageX: 15, imageY: 10, imageWidth: 200, imageHeight: 170 };
const $ = (selector, root = document) => root.querySelector(selector);
const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
const uid = (prefix) => `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`;
const escapeHtml = (value = '') => String(value).replace(/[&<>'"]/g, c => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c]));
const escapeXml = (value = '') => String(value).replace(/[&<>'"]/g, c => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c]));
const safeFileName = (value = '装配体') => String(value).replace(/[^\w\u4e00-\u9fa5-]+/g,'_');
const placeholderSvg = (label = 'PCB', width = 420, height = 260, color = '#1d5b42') => {
const safe = escapeHtml(label.slice(0, 14));
const safeColor = /^#[0-9a-f]{6}$/i.test(color) ? color : '#1d5b42';
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 420 260" preserveAspectRatio="none"><defs><pattern id="p" width="36" height="36" patternUnits="userSpaceOnUse"><path d="M0 18h10m8 0h18M18 0v10m0 8v18" stroke="rgba(255,255,255,.28)" stroke-width="2"/><circle cx="18" cy="18" r="3" fill="#d8b960"/></pattern></defs><rect width="420" height="260" rx="16" fill="${safeColor}"/><rect x="12" y="12" width="396" height="236" rx="10" fill="url(#p)" stroke="#d0aa45" stroke-width="6"/><rect x="145" y="82" width="130" height="96" rx="5" fill="#26312e"/><g fill="#d9dfe0"><rect x="45" y="35" width="72" height="32"/><rect x="302" y="38" width="65" height="54"/><rect x="55" y="185" width="105" height="34"/></g><text x="210" y="137" text-anchor="middle" dominant-baseline="middle" font-family="sans-serif" font-size="22" font-weight="700" fill="#eef8f3">${safe}</text></svg>`)}`;
};
const demoBoards = () => [
{
kind: 'wiresketch/pcb', version: 1, id: uid('pcb'), name: 'ESP32 DevKit', image: placeholderSvg('ESP32 DevKit'), imageSize:{width:420,height:260}, builtIn:true, source:'generated', generated:{width:420,height:260,color:'#1d5b42'},
interfaces: [
{id: uid('if'), name:'POWER', type:'power', rect:{x:.02,y:.22,w:.12,h:.56}, pins:['5V','GND','3V3']},
{id: uid('if'), name:'UART0', type:'uart', rect:{x:.86,y:.2,w:.12,h:.36}, pins:['TX0','RX0','GND']},
{id: uid('if'), name:'I2C', type:'i2c', rect:{x:.86,y:.62,w:.12,h:.26}, pins:['SDA','SCL','3V3','GND']}
]
},
{
kind: 'wiresketch/pcb', version: 1, id: uid('pcb'), name: 'OLED 0.96', image: placeholderSvg('OLED 0.96'), imageSize:{width:420,height:260}, builtIn:true, source:'generated', generated:{width:420,height:260,color:'#1d5b42'},
interfaces: [{id: uid('if'), name:'I2C', type:'i2c', rect:{x:.02,y:.35,w:.16,h:.3}, pins:['GND','VCC','SCL','SDA']}]
},
{
kind: 'wiresketch/pcb', version: 1, id: uid('pcb'), name: 'USB-TTL', image: placeholderSvg('USB-TTL'), imageSize:{width:420,height:260}, builtIn:true, source:'generated', generated:{width:420,height:260,color:'#1d5b42'},
interfaces: [{id: uid('if'), name:'UART', type:'uart', rect:{x:.82,y:.25,w:.16,h:.5}, pins:['5V','GND','TXD','RXD']}]
}
];
let state = loadState();
let selectedBoardId = state.boards[0]?.id || null;
let selectedInterfaceId = null;
let selectedNodeId = null;
let selectedWireId = null;
let selectedWirePinKey = null;
let selectedPort = null;
let selectedTextId = null;
let selectedItemKeys = new Set();
let pendingPort = null;
let zoom = 1;
let boardZoom = null;
let boardRenderedScale = 1;
let drawStart = null;
let interfaceDragState = null;
let dragState = null;
let nameDragState = null;
let marqueeState = null;
let ignoreCanvasClickUntil = 0;
let transparentColorPicking = false;
let imageRotationPreview = 0;
let imageRotationBusy = false;
const transparentImageCache = new Map();
const transparentImageJobs = new Map();
function transparencyKey(board) {
const config=board?.backgroundTransparency;
return config&&/^#[0-9a-f]{6}$/i.test(config.color||'')?`${config.color.toLowerCase()}|${Number(config.tolerance)||0}`:null;
}
function boardImageSource(board) {
const key=transparencyKey(board),cached=key&&transparentImageCache.get(board.id);
return cached?.key===key&&cached.source===board.image?cached.dataUrl:board?.image;
}
function loadImageSource(source) {
return new Promise((resolve,reject)=>{const image=new Image();image.onload=()=>resolve(image);image.onerror=reject;image.src=source;});
}
async function ensureTransparentBoardImage(board) {
const key=transparencyKey(board);
if(!key||!board?.image)return board?.image;
const source=board.image,cached=transparentImageCache.get(board.id);if(cached?.key===key&&cached.source===source)return cached.dataUrl;
if(transparentImageJobs.get(board.id)?.key===key&&transparentImageJobs.get(board.id)?.source===source)return transparentImageJobs.get(board.id).promise;
const promise=(async()=>{
const image=await loadImageSource(board.image);
const canvas=document.createElement('canvas');canvas.width=image.naturalWidth;canvas.height=image.naturalHeight;
const context=canvas.getContext('2d',{willReadFrequently:true});context.drawImage(image,0,0);
const pixels=context.getImageData(0,0,canvas.width,canvas.height),data=pixels.data;
const color=board.backgroundTransparency.color,red=parseInt(color.slice(1,3),16),green=parseInt(color.slice(3,5),16),blue=parseInt(color.slice(5,7),16);
const tolerance=Math.max(0,Math.min(64,Number(board.backgroundTransparency.tolerance)||0));
for(let index=0;index<data.length;index+=4){if(Math.max(Math.abs(data[index]-red),Math.abs(data[index+1]-green),Math.abs(data[index+2]-blue))<=tolerance)data[index+3]=0;}
context.putImageData(pixels,0,0);
const dataUrl=canvas.toDataURL('image/png');
if(transparencyKey(board)===key&&board.image===source)transparentImageCache.set(board.id,{key,source,dataUrl});
return dataUrl;
})().finally(()=>{const job=transparentImageJobs.get(board.id);if(job?.key===key&&job?.source===source)transparentImageJobs.delete(board.id);});
transparentImageJobs.set(board.id,{key,source,promise});
return promise;
}
function loadState() {
try {
if(typeof localStorage==='undefined')throw new Error('No browser storage');
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
if (saved?.boards) {
saved.boards.forEach(board => {
if (board.builtIn == null) board.builtIn = DEFAULT_BOARD_NAMES.includes(board.name);
if (!board.image) {
board.source='generated';
board.generated={width:420,height:260,color:'#1d5b42'};
} else if (board.builtIn && board.image.startsWith('data:image/svg+xml') && !board.source) {
board.source='generated';
board.generated={width:board.imageSize?.width||420,height:board.imageSize?.height||260,color:'#1d5b42'};
}
if (board.source==='generated') refreshGeneratedBoard(board);
});
if(isAssemblyDocument({...saved.assembly,embeddedBoards:[]}))return saved;
return {boards:saved.boards,assembly:createAssembly()};
}
} catch (_) {}
return {boards:demoBoards(),assembly:createAssembly()};
}
function createAssembly() {
return {schema:ASSEMBLY_SCHEMA_ID,schemaVersion:'1.6.0',kind:'wiresketch/assembly',version:1,id:uid('assembly'),name:'新建连接图',description:'',layout:{origin:'top-left',axisX:'right',axisY:'down',unit:'diagram-px',routing:'hybrid'},canvasSize:{width:1200,height:800},textDefaults:{...DEFAULT_FREE_TEXT_STYLE},texts:[{id:uid('text'),role:'title',text:'新建连接图',x:30,y:25}],wireDefaults:{width:DEFAULT_WIRE_STYLE.width,labelGap:DEFAULT_WIRE_STYLE.gap,routeGap:DEFAULT_WIRE_STYLE.routeGap,cornerRadius:DEFAULT_WIRE_STYLE.cornerRadius,showFromLabels:true,showToLabels:true},nodes:[],connections:[]};
}
function refreshGeneratedBoard(board) {
const config=board.generated||(board.generated={width:420,height:260,color:'#1d5b42'});
config.width=Math.max(120,Math.min(2400,+config.width||420));
config.height=Math.max(80,Math.min(1600,+config.height||260));
if(!/^#[0-9a-f]{6}$/i.test(config.color||''))config.color='#1d5b42';
board.imageSize={width:config.width,height:config.height};
board.image=placeholderSvg(board.name,config.width,config.height,config.color);
}
function redrawGeneratedBoard(board, fit=false) {
refreshGeneratedBoard(board);
if(board.id===selectedBoardId){
if(fit)boardZoom=null;
const image=$('#boardImage');
image.onload=()=>requestAnimationFrame(syncOverlay);
image.src=board.image;
}
saveState();renderBoardList();renderComponentList();
}
function applyVirtualBoardSettings() {
const board=currentBoard();if(board?.source!=='generated')return;
board.generated.width=+$('#virtualBoardWidth').value||420;
board.generated.height=+$('#virtualBoardHeight').value||260;
board.generated.color=$('#virtualBoardColor').value;
redrawGeneratedBoard(board,true);renderBoardEditor();
}
let saveTimer;
function saveState() {
$('.save-status').innerHTML = '<i></i> 保存中…';
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
$('.save-status').innerHTML = '<i></i> 已自动保存';
}, 180);
}
function currentBoard() { return state.boards.find(b => b.id === selectedBoardId); }
function currentInterface() { return currentBoard()?.interfaces.find(i => i.id === selectedInterfaceId); }
function interfaceRotation(intf) {
const rotation = Number(intf?.rotation);
return [0, 90, 180, 270].includes(rotation) ? rotation : 0;
}
function pinOneSide(intf) {
return ({0:'left', 90:'top', 180:'right', 270:'bottom'})[interfaceRotation(intf)];
}
function nodeRotation(node) {
const rotation=Number(node?.rotation);
return [0,90,180,270].includes(rotation)?rotation:0;
}
function nodeFlipX(node) { return node?.flipX===true; }
function nodeFixed(node) { return node?.fixed===true; }
function nodeNameVisible(node) { return node?.showName!==false; }
function normalizedTextStyle(style,defaults) {
const fontSize=Number(style?.fontSize),requestedWeight=Number(style?.fontWeight),fontFamily=FONT_FAMILIES[style?.fontFamily]?style.fontFamily:defaults.fontFamily,color=/^#[0-9a-f]{6}$/i.test(style?.color||'')?style.color:defaults.color;
const fallbackShadow=defaults.shadow||DEFAULT_FREE_TEXT_STYLE.shadow,configuredShadow=style?.shadow||{},blur=Number(configuredShadow.blur),offsetX=Number(configuredShadow.offsetX),offsetY=Number(configuredShadow.offsetY);
const shadow={enabled:typeof configuredShadow.enabled==='boolean'?configuredShadow.enabled:fallbackShadow.enabled,color:/^#[0-9a-f]{6}$/i.test(configuredShadow.color||'')?configuredShadow.color:fallbackShadow.color,blur:Number.isFinite(blur)?Math.max(0,Math.min(12,blur)):fallbackShadow.blur,offsetX:Number.isFinite(offsetX)?Math.max(-10,Math.min(10,offsetX)):fallbackShadow.offsetX,offsetY:Number.isFinite(offsetY)?Math.max(-10,Math.min(10,offsetY)):fallbackShadow.offsetY};
const fallbackWeight=FONT_WEIGHTS.includes(Number(defaults.fontWeight))?Number(defaults.fontWeight):DEFAULT_FREE_TEXT_STYLE.fontWeight;
const fontWeight=COMPATIBLE_FONT_WEIGHTS.includes(requestedWeight)?(requestedWeight<=400?300:requestedWeight<=600?500:700):fallbackWeight;
return {fontSize:Number.isFinite(fontSize)?Math.max(8,Math.min(72,fontSize)):defaults.fontSize,fontFamily,fontWeight,color,shadow};
}
function textFontCss(style) { return FONT_FAMILIES[style.fontFamily]||FONT_FAMILIES['sans-serif']; }
function textShadowCss(style) { return style.shadow.enabled?`${style.shadow.offsetX}px ${style.shadow.offsetY}px ${style.shadow.blur}px ${style.shadow.color}`:'none'; }
function textInlineStyle(style) { return `font-size:${style.fontSize}px;font-family:${escapeHtml(textFontCss(style))};font-weight:${style.fontWeight};color:${style.color};text-shadow:${textShadowCss(style)}`; }
function withTextStyleChange(style,property,value) {
if(!property.startsWith('shadow.'))return {...style,[property]:value};
return {...style,shadow:{...style.shadow,[property.slice(7)]:value}};
}
function populateTextStyleControls(prefix,style) {
$(`#${prefix}FontWeight`).value=style.fontWeight;
$(`#${prefix}ShadowEnabled`).checked=style.shadow.enabled;
$(`#${prefix}ShadowColor`).value=style.shadow.color;
$(`#${prefix}ShadowBlur`).value=style.shadow.blur;$(`#${prefix}ShadowBlurValue`).value=style.shadow.blur;
$(`#${prefix}ShadowX`).value=style.shadow.offsetX;$(`#${prefix}ShadowXValue`).value=style.shadow.offsetX;
$(`#${prefix}ShadowY`).value=style.shadow.offsetY;$(`#${prefix}ShadowYValue`).value=style.shadow.offsetY;
}
function bindExtendedTextStyleControls(prefix,update) {
$(`#${prefix}FontWeight`).onchange=event=>update('fontWeight',Number(event.target.value));
$(`#${prefix}ShadowEnabled`).onchange=event=>update('shadow.enabled',event.target.checked);
$(`#${prefix}ShadowColor`).oninput=event=>update('shadow.color',event.target.value);
$(`#${prefix}ShadowBlur`).oninput=event=>update('shadow.blur',Number(event.target.value));
$(`#${prefix}ShadowX`).oninput=event=>update('shadow.offsetX',Number(event.target.value));
$(`#${prefix}ShadowY`).oninput=event=>update('shadow.offsetY',Number(event.target.value));
}
function assemblyTextDefaults(assembly=state.assembly) { return normalizedTextStyle(assembly?.textDefaults,DEFAULT_FREE_TEXT_STYLE); }
function nodeNameStyle(node) { return normalizedTextStyle(node?.nameStyle,assemblyTextDefaults()); }
function freeTextStyle(item) { return normalizedTextStyle(item?.style,assemblyTextDefaults()); }
function assemblyTexts() { return Array.isArray(state.assembly.texts)?state.assembly.texts:[]; }
function selectionKey(kind,id) { return `${kind}:${id}`; }
function activateSelectedItem(kind,id,{preserveGroup=false}={}) {
const key=selectionKey(kind,id);
if(!preserveGroup||!selectedItemKeys.has(key))selectedItemKeys=new Set([key]);
selectedNodeId=kind==='node'?id:null;selectedTextId=kind==='free'?id:null;
selectedWireId=null;selectedWirePinKey=null;selectedPort=null;
}
function clearItemSelection() { selectedItemKeys.clear();selectedNodeId=null;selectedTextId=null; }
function nodeNameOffset(board,node) {
const configured=node?.nameOffset;
if(configured&&Number.isFinite(Number(configured.x))&&Number.isFinite(Number(configured.y)))return {x:Number(configured.x),y:Number(configured.y)};
const bounds=getBoardImageGeometry(board,node).bounds;
return {x:0,y:bounds.height/2+18};
}
function interfaceSingleSignalMode(node,interfaceId) { return node?.interfaceConnectionModes?.[interfaceId]==='signal'; }
function connectionMode(connection) { return connection?.mode==='signal'?'signal':'bundle'; }
function nodeScale(node) {
const scale=Number(node?.scale);
return Number.isFinite(scale)?Math.max(.5,Math.min(2,scale)):1;
}
function assemblyWireDefaults() {
const configured=state.assembly.wireDefaults||{};
const labelGap=Number(configured.labelGap);
const routeGap=Number(configured.routeGap);
const cornerRadius=Number(configured.cornerRadius);
return {
width:Math.max(1,Math.min(8,Number(configured.width)||DEFAULT_WIRE_STYLE.width)),
gap:Number.isFinite(labelGap)?Math.max(0,Math.min(24,labelGap)):DEFAULT_WIRE_STYLE.gap,
routeGap:Number.isFinite(routeGap)?Math.max(0,Math.min(20,routeGap)):DEFAULT_WIRE_STYLE.routeGap,
cornerRadius:Number.isFinite(cornerRadius)?Math.max(0,Math.min(24,cornerRadius)):DEFAULT_WIRE_STYLE.cornerRadius,
showFromLabels:configured.showFromLabels!==false,
showToLabels:configured.showToLabels!==false
};
}
function updateAssemblyWireDefaults(changes) {
const defaults=assemblyWireDefaults();
state.assembly.wireDefaults={width:defaults.width,labelGap:defaults.gap,routeGap:defaults.routeGap,cornerRadius:defaults.cornerRadius,showFromLabels:defaults.showFromLabels,showToLabels:defaults.showToLabels,...changes};
}
function signalWireStyle(signal) {
const defaults=assemblyWireDefaults(),configured=signal?.style||{};
return {
width:Math.max(1,Math.min(8,Number(configured.width)||defaults.width)),
gap:defaults.gap,
cornerRadius:typeof configured.cornerRadius==='number'?Math.max(0,Math.min(24,configured.cornerRadius)):defaults.cornerRadius,
showFromLabels:typeof configured.showFromLabels==='boolean'?configured.showFromLabels:defaults.showFromLabels,
showToLabels:typeof configured.showToLabels==='boolean'?configured.showToLabels:defaults.showToLabels
};
}
function connectionWireGap(connection) {
const configured=Number(connection?.gap);
return Number.isFinite(configured)&&configured>=0&&configured<=20?configured:assemblyWireDefaults().routeGap;
}
function interfaceLabelGap(node,interfaceId) {
const configured=Number(node?.interfaceLabelGaps?.[interfaceId]);
return Number.isFinite(configured)&&configured>=0&&configured<=24?configured:assemblyWireDefaults().gap;
}
function assemblyCanvasSize() {
const configured=state.assembly.canvasSize||{};
return {width:Math.max(600,Math.min(3000,Number(configured.width)||1200)),height:Math.max(400,Math.min(2000,Number(configured.height)||800))};
}
function switchView(view) {
$$('.mode-btn').forEach(b => b.classList.toggle('active', b.dataset.view === view));
$$('.workspace').forEach(v => v.classList.remove('active'));
$(`#${view}View`).classList.add('active');
if (view === 'assembly') { renderComponentList(); renderAssembly(); }
}
function renderBoardList() {
const query = $('#boardSearch').value.trim().toLowerCase();
const list = state.boards.filter(b => b.name.toLowerCase().includes(query));
$('#boardList').innerHTML = list.map(b => `<div class="board-row"><button class="board-item ${b.id === selectedBoardId ? 'active' : ''}" data-id="${b.id}"><img class="board-thumb" src="${boardImageSource(b) || placeholderSvg(b.name)}" alt=""><span><strong>${escapeHtml(b.name)}</strong><small>${b.interfaces.length} 个接口${b.builtIn?' · 默认':''}</small></span></button><button class="board-delete ${b.builtIn?'locked':''}" data-delete-id="${b.id}" ${b.builtIn?'disabled title="默认板卡不能删除"':'title="删除板卡"'}>${b.builtIn?'▣':'×'}</button></div>`).join('') || '<div class="property-empty"><p>没有匹配的板卡</p></div>';
$$('.board-item').forEach(el => el.onclick = () => selectBoard(el.dataset.id));
$$('.board-delete:not(:disabled)').forEach(el => el.onclick = () => deleteBoard(el.dataset.deleteId));
}
function selectBoard(id) {
selectedBoardId = id;
selectedInterfaceId = null;
boardZoom = null;
renderBoardList();
renderBoardEditor();
}
function renderBoardEditor() {
const board = currentBoard();
if (!board) return;
if(!imageRotationBusy)syncImageRotationControls(board);
$('#boardName').value = board.name;
$('#boardBreadcrumb').textContent = board.name;
const generated=board.source==='generated';
$('#virtualBoardControls').classList.toggle('hidden',!generated);
$('#imageTransparencyControls').classList.toggle('hidden',generated||!board.image);
if(generated||!board.image)setTransparentColorPicking(false);
renderTransparencyControls(board);
if(generated){
$('#virtualBoardWidth').value=board.generated.width;
$('#virtualBoardHeight').value=board.generated.height;
$('#virtualBoardColor').value=board.generated.color;
}
const img = $('#boardImage');
if (board.image) {
img.src = boardImageSource(board);
img.style.display = 'block';
$('#imageWorkspace').classList.remove('hidden');
$('#emptyImage').classList.add('hidden');
const ready = () => {
if (!board.imageSize && img.naturalWidth) {
board.imageSize = {width:img.naturalWidth, height:img.naturalHeight};
saveState();
}
requestAnimationFrame(syncOverlay);
};
img.complete ? ready() : img.onload = ready;
if(board.backgroundTransparency&&boardImageSource(board)===board.image)ensureTransparentBoardImage(board).then(()=>{if(currentBoard()===board){img.onload=ready;img.src=boardImageSource(board);}renderBoardList();renderComponentList();if($('#assemblyView').classList.contains('active'))renderAssembly();}).catch(()=>toast('图片透明背景处理失败'));
} else {
img.style.display = 'none';
$('#imageWorkspace').classList.add('hidden');
$('#emptyImage').classList.remove('hidden');
$('#interfaceOverlay').innerHTML = '';
}
renderInterfaceForm();
}
function setTransparentColorPicking(active) {
transparentColorPicking=!!active;
$('#imageStage').classList.toggle('color-picking',transparentColorPicking);
$('#pickTransparentColorBtn').classList.toggle('active',transparentColorPicking);
$('#pickTransparentColorBtn').textContent=transparentColorPicking?'请点击图片取色':'吸取透明色';
}
function renderTransparencyControls(board=currentBoard()) {
const config=board?.source==='image'?board.backgroundTransparency:null,status=$('#transparentColorStatus');
status.querySelector('span').textContent=config?.color?.toUpperCase()||'尚未设置';
status.querySelector('i').style.background=config?.color||'';
$('#clearTransparentColorBtn').classList.toggle('hidden',!config);
}
async function pickTransparentColor(e) {
const board=currentBoard(),overlay=$('#interfaceOverlay'),rect=overlay.getBoundingClientRect();
if(e.button!==0||!board?.image||board.source!=='image'||e.clientX<rect.left||e.clientX>rect.right||e.clientY<rect.top||e.clientY>rect.bottom)return;
setTransparentColorPicking(false);
try {
const image=await loadImageSource(board.image),canvas=document.createElement('canvas');canvas.width=image.naturalWidth;canvas.height=image.naturalHeight;
const context=canvas.getContext('2d',{willReadFrequently:true});context.drawImage(image,0,0);
const x=Math.min(canvas.width-1,Math.max(0,Math.floor((e.clientX-rect.left)/rect.width*canvas.width)));
const y=Math.min(canvas.height-1,Math.max(0,Math.floor((e.clientY-rect.top)/rect.height*canvas.height)));
const [red,green,blue]=context.getImageData(x,y,1,1).data;
board.backgroundTransparency={color:`#${[red,green,blue].map(value=>value.toString(16).padStart(2,'0')).join('')}`,tolerance:12};
transparentImageCache.delete(board.id);saveState();renderTransparencyControls(board);
await ensureTransparentBoardImage(board);
renderBoardEditor();renderBoardList();renderComponentList();if($('#assemblyView').classList.contains('active'))renderAssembly();
toast(`已将 ${board.backgroundTransparency.color.toUpperCase()} 设为透明`);
} catch(error) {console.error(error);toast('取色失败,请检查图片格式');}
}
function clearTransparentColor() {
const board=currentBoard();if(!board)return;
delete board.backgroundTransparency;transparentImageCache.delete(board.id);setTransparentColorPicking(false);saveState();
renderBoardEditor();renderBoardList();renderComponentList();if($('#assemblyView').classList.contains('active'))renderAssembly();toast('已恢复图片背景');
}
function rotatedCanvasSize(width,height,radians) {
const cosine=Math.abs(Math.cos(radians)),sine=Math.abs(Math.sin(radians));
return {width:Math.max(1,Math.ceil(width*cosine+height*sine)),height:Math.max(1,Math.ceil(width*sine+height*cosine))};
}
function normalizedImageRotation(value) {
const angle=Math.max(-180,Math.min(180,Number(value)||0));
return Math.round(angle*10)/10;
}
function rotationDelta(from,to) {
let delta=to-from;
while(delta>180)delta-=360;
while(delta<-180)delta+=360;
return delta;
}
function previewImportedImageRotation(targetDegrees) {
const current=normalizedImageRotation(currentBoard()?.imageRotation),target=normalizedImageRotation(targetDegrees);
imageRotationPreview=rotationDelta(current,target);
const transform=imageRotationPreview?`rotate(${imageRotationPreview}deg)`:'';
$('#boardImage').style.transform=transform;$('#interfaceOverlay').style.transform=transform;
$('#boardImage').style.transformOrigin='center';$('#interfaceOverlay').style.transformOrigin='center';
$('#imageStage').classList.toggle('image-rotation-preview',!!imageRotationPreview);
}
function syncImageRotationControls(board=currentBoard()) {
const angle=board?.source==='image'?normalizedImageRotation(board.imageRotation):0;
imageRotationPreview=0;$('#imageRotationAngle').value=angle;$('#imageRotationSlider').value=angle;
$('#imageRotationSlider').disabled=false;$('#imageRotationAngle').disabled=false;
$('#boardImage').style.transform='';$('#interfaceOverlay').style.transform='';$('#imageStage').classList.remove('image-rotation-preview');
}
function rotateInterfaceRects(board,oldWidth,oldHeight,newWidth,newHeight,radians,rotatedCenterX=newWidth/2,rotatedCenterY=newHeight/2) {
const cosine=Math.cos(radians),sine=Math.sin(radians),oldCenter={x:oldWidth/2,y:oldHeight/2},newCenter={x:rotatedCenterX,y:rotatedCenterY};
const rotate=(x,y)=>{const dx=x-oldCenter.x,dy=y-oldCenter.y;return {x:newCenter.x+dx*cosine-dy*sine,y:newCenter.y+dx*sine+dy*cosine};};
board.interfaces.forEach(intf=>{
const left=intf.rect.x*oldWidth,top=intf.rect.y*oldHeight,right=(intf.rect.x+intf.rect.w)*oldWidth,bottom=(intf.rect.y+intf.rect.h)*oldHeight;
const points=[rotate(left,top),rotate(right,top),rotate(right,bottom),rotate(left,bottom)],xs=points.map(point=>point.x),ys=points.map(point=>point.y);
const minX=Math.max(0,Math.min(...xs)),minY=Math.max(0,Math.min(...ys)),maxX=Math.min(newWidth,Math.max(...xs)),maxY=Math.min(newHeight,Math.max(...ys));
intf.rect={x:minX/newWidth,y:minY/newHeight,w:(maxX-minX)/newWidth,h:(maxY-minY)/newHeight};
const quarterTurns=Math.round((radians*180/Math.PI)/90);
if(Math.abs(radians*180/Math.PI-quarterTurns*90)<.001)intf.rotation=(interfaceRotation(intf)+quarterTurns*90+360)%360;
});
}
function trimTransparentCanvas(canvas) {
const context=canvas.getContext('2d',{willReadFrequently:true}),data=context.getImageData(0,0,canvas.width,canvas.height).data;
let left=canvas.width,top=canvas.height,right=-1,bottom=-1;
for(let y=0;y<canvas.height;y++)for(let x=0;x<canvas.width;x++){if(data[(y*canvas.width+x)*4+3]){left=Math.min(left,x);top=Math.min(top,y);right=Math.max(right,x);bottom=Math.max(bottom,y);}}
if(right<left)return {canvas,left:0,top:0};
const width=right-left+1,height=bottom-top+1;if(!left&&!top&&width===canvas.width&&height===canvas.height)return {canvas,left:0,top:0};
const trimmed=document.createElement('canvas');trimmed.width=width;trimmed.height=height;trimmed.getContext('2d').drawImage(canvas,left,top,width,height,0,0,width,height);
return {canvas:trimmed,left,top};
}
async function rotateImportedImage(requestedDegrees) {
const board=currentBoard(),target=normalizedImageRotation(requestedDegrees??$('#imageRotationAngle').value),current=normalizedImageRotation(board?.imageRotation),degrees=rotationDelta(current,target);
if(imageRotationBusy||!board?.image||board.source!=='image')return;if(!degrees){syncImageRotationControls(board);return;}
imageRotationBusy=true;$('#imageRotationSlider').disabled=true;$('#imageRotationAngle').disabled=true;setTransparentColorPicking(false);
$('#boardImage').style.transform='';$('#interfaceOverlay').style.transform='';$('#imageStage').classList.remove('image-rotation-preview');imageRotationPreview=0;
try {
const image=await loadImageSource(board.image),radians=degrees*Math.PI/180,size=rotatedCanvasSize(image.naturalWidth,image.naturalHeight,radians);
if(size.width>12000||size.height>12000||size.width*size.height>64000000)throw new RangeError('旋转后的图片尺寸过大');
const canvas=document.createElement('canvas');canvas.width=size.width;canvas.height=size.height;
const context=canvas.getContext('2d');context.imageSmoothingEnabled=true;context.imageSmoothingQuality='high';context.translate(size.width/2,size.height/2);context.rotate(radians);context.drawImage(image,-image.naturalWidth/2,-image.naturalHeight/2);
const trimmed=trimTransparentCanvas(canvas),output=trimmed.canvas;
rotateInterfaceRects(board,image.naturalWidth,image.naturalHeight,output.width,output.height,radians,size.width/2-trimmed.left,size.height/2-trimmed.top);
board.image=output.toDataURL('image/png');board.imageSize={width:output.width,height:output.height};board.imageRotation=target;transparentImageCache.delete(board.id);boardZoom=null;
await ensureTransparentBoardImage(board);saveState();renderBoardEditor();renderBoardList();renderComponentList();if($('#assemblyView').classList.contains('active'))renderAssembly();
toast(`图片角度 ${target}°`);
} catch(error) {console.error(error);toast(error instanceof RangeError?error.message:'图片旋转失败,请检查图片格式');}
finally {imageRotationBusy=false;syncImageRotationControls(board);}
}
function syncOverlay() {
const img = $('#boardImage');
const stage = $('#imageStage');
const overlay = $('#interfaceOverlay');
if (img.style.display === 'none') return;
const board = currentBoard();
const naturalWidth = board?.imageSize?.width || img.naturalWidth;
const naturalHeight = board?.imageSize?.height || img.naturalHeight;
if (!naturalWidth || !naturalHeight) return;
const maxWidth = Math.max(1, stage.clientWidth - 50);
const maxHeight = Math.max(1, stage.clientHeight - 40);
const fitScale = Math.min(maxWidth / naturalWidth, maxHeight / naturalHeight, 1);
const scale = Math.max(.02, Math.min(4, boardZoom ?? fitScale));
boardRenderedScale = scale;
const workspace = $('#imageWorkspace');
const imageWidth = naturalWidth * scale, imageHeight = naturalHeight * scale;
const workspaceWidth = Math.max(stage.clientWidth, imageWidth + 50);
const workspaceHeight = Math.max(stage.clientHeight, imageHeight + 40);
workspace.style.width = `${workspaceWidth}px`;
workspace.style.height = `${workspaceHeight}px`;
img.style.width = `${naturalWidth * scale}px`;
img.style.height = `${naturalHeight * scale}px`;
const left = (workspaceWidth-imageWidth)/2, top = (workspaceHeight-imageHeight)/2;
img.style.left = `${left}px`; img.style.top = `${top}px`;
Object.assign(overlay.style, {left:`${left}px`, top:`${top}px`, width:`${imageWidth}px`, height:`${imageHeight}px`});
$('#boardZoomLabel').textContent = `${Math.round(scale*100)}%`;
renderInterfaces();
}
function changeBoardZoom(factor) {
if (!currentBoard()?.image) return;
const stage=$('#imageStage');
const oldWidth=stage.scrollWidth, oldHeight=stage.scrollHeight;
const centerX=(stage.scrollLeft+stage.clientWidth/2)/oldWidth;
const centerY=(stage.scrollTop+stage.clientHeight/2)/oldHeight;
boardZoom=Math.max(.02,Math.min(4,boardRenderedScale*factor));
syncOverlay();
stage.scrollLeft=centerX*stage.scrollWidth-stage.clientWidth/2;
stage.scrollTop=centerY*stage.scrollHeight-stage.clientHeight/2;
}
function fitBoardImage() {
boardZoom=null;
syncOverlay();
$('#imageStage').scrollTo({left:0,top:0});
}
function renderInterfaces() {
const overlay = $('#interfaceOverlay');
const board = currentBoard();
if (!board) return;
overlay.innerHTML = board.interfaces.map(i => {
const side=pinOneSide(i),rotation=interfaceRotation(i);
return `<button class="interface-box pin1-${side} ${i.id === selectedInterfaceId ? 'selected' : ''}" data-id="${i.id}" data-label="${escapeHtml(i.name)} · ${i.pins.length}P · ${rotation}°" style="left:${i.rect.x*100}%;top:${i.rect.y*100}%;width:${i.rect.w*100}%;height:${i.rect.h*100}%"><span class="pin-one-marker pin-one-${side}" title="Pin 1">P1</span></button>`;
}).join('');
$$('.interface-box', overlay).forEach(el => el.onpointerdown = onInterfacePointerDown);
}
function onInterfacePointerDown(e) {
if (e.button !== 0) return;
e.stopPropagation();
e.preventDefault();
const intf=currentBoard()?.interfaces.find(i=>i.id===e.currentTarget.dataset.id);
const overlay=$('#interfaceOverlay'),r=overlay.getBoundingClientRect();
if(!intf||!r.width||!r.height)return;
selectedInterfaceId=intf.id;
interfaceDragState={id:intf.id,startClientX:e.clientX,startClientY:e.clientY,startX:intf.rect.x,startY:intf.rect.y,overlayWidth:r.width,overlayHeight:r.height};
$$('.interface-box',overlay).forEach(box=>box.classList.toggle('selected',box.dataset.id===intf.id));
renderInterfaceForm();
$('#imageStage').setPointerCapture(e.pointerId);
}
function moveInterface(e) {
if(!interfaceDragState)return false;
const intf=currentBoard()?.interfaces.find(i=>i.id===interfaceDragState.id);
if(!intf)return false;
intf.rect.x=Math.max(0,Math.min(1-intf.rect.w,interfaceDragState.startX+(e.clientX-interfaceDragState.startClientX)/interfaceDragState.overlayWidth));
intf.rect.y=Math.max(0,Math.min(1-intf.rect.h,interfaceDragState.startY+(e.clientY-interfaceDragState.startClientY)/interfaceDragState.overlayHeight));
const el=$$('.interface-box').find(box=>box.dataset.id===intf.id);
if(el){el.style.left=`${intf.rect.x*100}%`;el.style.top=`${intf.rect.y*100}%`;}
return true;
}
function endInterfaceDrag() {
if(!interfaceDragState)return false;
interfaceDragState=null;
saveState();
renderInterfaces();
return true;
}
function renderInterfaceForm() {
const intf = currentInterface();
$('#interfaceEmpty').classList.toggle('hidden', !!intf);
$('#interfaceForm').classList.toggle('hidden', !intf);
if (!intf) return;
$('#interfaceName').value = intf.name;
$('#interfaceType').value = intf.type || 'generic';
$('#pinCount').value = intf.pins.length;
$('#interfaceRotation').value = interfaceRotation(intf);
renderPins(intf);
}
function renderPins(intf) {
$('#pinList').innerHTML = intf.pins.map((pin, idx) => `<label class="pin-row"><span>P${idx+1}</span><input value="${escapeHtml(pin)}" data-index="${idx}" placeholder="信号名称"><i class="pin-color" style="background:${PIN_COLORS[idx % PIN_COLORS.length]}"></i></label>`).join('');
$$('#pinList input').forEach(input => input.oninput = () => { intf.pins[+input.dataset.index] = input.value; saveState(); });
}
function applyInterfaceTypeDefaults(intf, type) {
intf.type = type;
const defaultPins = INTERFACE_TYPE_DEFAULT_PINS[type];
if (defaultPins) intf.pins = [...defaultPins];
}
function newBoard() {
const board = {kind:'wiresketch/pcb', version:1, id:uid('pcb'), name:'未命名板卡', image:null, imageSize:{width:420,height:260}, source:'generated', generated:{width:420,height:260,color:'#1d5b42'}, builtIn:false, interfaces:[]};
refreshGeneratedBoard(board);
state.boards.unshift(board); selectedBoardId = board.id; selectedInterfaceId = null; boardZoom=null; saveState(); renderBoardList(); renderBoardEditor();
}
function deleteBoard(id) {
const board=state.boards.find(b=>b.id===id); if(!board||board.builtIn)return;
const nodeIds=state.assembly.nodes.filter(n=>n.boardId===id).map(n=>n.id);
const message=nodeIds.length?`“${board.name}”已在装配体中使用 ${nodeIds.length} 次。删除板卡会同时移除这些节点和相关连接,确定继续吗?`:`确定删除板卡“${board.name}”吗?`;
if(!confirm(message))return;
const removed=new Set(nodeIds);
state.boards=state.boards.filter(b=>b.id!==id);
state.assembly.nodes=state.assembly.nodes.filter(n=>!removed.has(n.id));
state.assembly.connections=state.assembly.connections.filter(c=>!removed.has(c.from.nodeId)&&!removed.has(c.to.nodeId));
if(selectedBoardId===id){selectedBoardId=state.boards[0]?.id||null;selectedInterfaceId=null;boardZoom=null;}
saveState();renderBoardList();renderBoardEditor();renderComponentList();
}
function handleImage(file) {
if (!file?.type.startsWith('image/')) return toast('请选择图片文件');
syncImageRotationControls();
const targetBoard=currentBoard();
const reader = new FileReader();
reader.onload = () => {
const dataUrl = reader.result;
const probe = new Image();
probe.onload = () => {
if(!state.boards.includes(targetBoard))return;
targetBoard.image = dataUrl;
targetBoard.imageSize = {width:probe.naturalWidth, height:probe.naturalHeight};
targetBoard.source='image';
delete targetBoard.imageRotation;
delete targetBoard.backgroundTransparency;
transparentImageCache.delete(targetBoard.id);
delete targetBoard.generated;
if(targetBoard.id===selectedBoardId)boardZoom=null;
saveState(); renderBoardEditor(); renderBoardList();
};
probe.src = dataUrl;
};
reader.readAsDataURL(file);
}
function onStagePointerDown(e) {
if(imageRotationPreview)return;
if(transparentColorPicking){e.preventDefault();pickTransparentColor(e);return;}
if (e.button !== 0 || !currentBoard()?.image || e.target.closest('.interface-box')) return;
const overlay = $('#interfaceOverlay'), r = overlay.getBoundingClientRect();
if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) return;
drawStart = {x: Math.max(0, Math.min(1, (e.clientX-r.left)/r.width)), y: Math.max(0, Math.min(1, (e.clientY-r.top)/r.height))};
const box = document.createElement('div'); box.className = 'drawing-box'; box.id = 'drawingBox'; overlay.appendChild(box);
$('#imageStage').setPointerCapture(e.pointerId);
}
function onStagePointerMove(e) {
if (moveInterface(e)) return;
if (!drawStart) return;
const overlay = $('#interfaceOverlay'), r = overlay.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (e.clientX-r.left)/r.width)), y = Math.max(0, Math.min(1, (e.clientY-r.top)/r.height));
const left = Math.min(x, drawStart.x), top = Math.min(y, drawStart.y);
Object.assign($('#drawingBox').style, {left:`${left*100}%`, top:`${top*100}%`, width:`${Math.abs(x-drawStart.x)*100}%`, height:`${Math.abs(y-drawStart.y)*100}%`});
}
function onStagePointerUp(e) {
if (endInterfaceDrag()) return;
if (!drawStart) return;
const overlay = $('#interfaceOverlay'), r = overlay.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (e.clientX-r.left)/r.width)), y = Math.max(0, Math.min(1, (e.clientY-r.top)/r.height));
const rect = {x:Math.min(x,drawStart.x), y:Math.min(y,drawStart.y), w:Math.abs(x-drawStart.x), h:Math.abs(y-drawStart.y)};
drawStart = null;
if (rect.w > .015 && rect.h > .015) {
const intf = {id:uid('if'), name:`J${currentBoard().interfaces.length+1}`, type:'generic', rect, rotation:0, pins:['Pin 1','Pin 2','Pin 3','Pin 4']};
currentBoard().interfaces.push(intf); selectedInterfaceId = intf.id; saveState(); renderBoardList(); renderInterfaces(); renderInterfaceForm(); $('#interfaceName').select();
} else renderInterfaces();
}
function deleteSelectedInterface() {
if (!selectedInterfaceId) return;
const board = currentBoard();
const removedId = selectedInterfaceId;
board.interfaces = board.interfaces.filter(i => i.id !== removedId); selectedInterfaceId = null;
state.assembly.connections = state.assembly.connections.filter(c => c.from.interfaceId !== removedId && c.to.interfaceId !== removedId);
saveState(); renderBoardList(); renderInterfaces(); renderInterfaceForm();
}
function downloadJson(data, name) {
const blob = new Blob([JSON.stringify(data, null, 2)], {type:'application/json'});
downloadBlob(blob, `${safeFileName(name)}.json`);
}
function downloadBlob(blob, fileName) {
const url = URL.createObjectURL(blob), a = document.createElement('a');
a.href = url; a.download = fileName; a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function toPcbDocument(board) {
return {
schema:PCB_SCHEMA_ID,
schemaVersion:'1.1.0',
kind:'wiresketch/pcb',
version:1,
id:board.id,
name:board.name||'未命名板卡',
description:board.description||'',
coordinateSystem:{origin:'top-left',axisX:'right',axisY:'down',regionUnit:'normalized'},
image:board.image||null,
imageSize:{width:board.imageSize?.width||420,height:board.imageSize?.height||260,unit:'px'},
source:board.source||'image',
...(board.source==='image'&&normalizedImageRotation(board.imageRotation)?{imageRotation:normalizedImageRotation(board.imageRotation)}:{}),
...(board.source==='image'&&board.backgroundTransparency?{backgroundTransparency:structuredClone(board.backgroundTransparency)}:{}),
...(board.source==='generated'?{generated:structuredClone(board.generated)}:{}),
interfaces:board.interfaces.map((intf,index)=>({
id:intf.id,
name:intf.name||`J${index+1}`,
type:intf.type||'generic',
description:intf.description||'',
rect:{x:intf.rect.x,y:intf.rect.y,w:intf.rect.w,h:intf.rect.h},
rotation:interfaceRotation(intf),
pins:intf.pins.map((pin,pinIndex)=>String(pin).trim()||`Pin ${pinIndex+1}`)
}))
};
}
function toAssemblyDocument() {
const boards=[...new Set(state.assembly.nodes.map(n=>n.boardId))].map(id=>state.boards.find(b=>b.id===id)).filter(Boolean);
const wireDefaults=assemblyWireDefaults();
return {
schema:ASSEMBLY_SCHEMA_ID,
schemaVersion:'1.6.0',
kind:'wiresketch/assembly',
version:1,
id:state.assembly.id,
name:state.assembly.name,
description:state.assembly.description||'',
layout:{origin:'top-left',axisX:'right',axisY:'down',unit:'diagram-px',routing:'hybrid'},
canvasSize:assemblyCanvasSize(),
textDefaults:assemblyTextDefaults(),
texts:assemblyTexts().map(item=>({id:item.id,...(item.role==='title'?{role:'title'}:{}),text:String(item.text||''),x:Number(item.x)||0,y:Number(item.y)||0,...(item.style?{style:freeTextStyle(item)}:{})})),
wireDefaults:{width:wireDefaults.width,labelGap:wireDefaults.gap,routeGap:wireDefaults.routeGap,cornerRadius:wireDefaults.cornerRadius,showFromLabels:wireDefaults.showFromLabels,showToLabels:wireDefaults.showToLabels},
nodes:state.assembly.nodes.map(node=>{const labelGaps=node.interfaceLabelGaps,modes=node.interfaceConnectionModes;return {id:node.id,boardId:node.boardId,label:node.label,x:node.x,y:node.y,rotation:nodeRotation(node),flipX:nodeFlipX(node),scale:nodeScale(node),fixed:nodeFixed(node),showName:nodeNameVisible(node),...(node.nameStyle?{nameStyle:nodeNameStyle(node)}:{}),...(node.nameOffset?{nameOffset:{x:Number(node.nameOffset.x)||0,y:Number(node.nameOffset.y)||0}}:{}),...(labelGaps?{interfaceLabelGaps:{...labelGaps}}:{}),...(modes&&Object.keys(modes).length?{interfaceConnectionModes:{...modes}}:{})};}),
connections:state.assembly.connections.map(connection=>({
id:connection.id,
mode:connectionMode(connection),
description:connection.description||'',
...(connection.gap==null?{}:{gap:connectionWireGap(connection)}),
from:{nodeId:connection.from.nodeId,interfaceId:connection.from.interfaceId},
to:{nodeId:connection.to.nodeId,interfaceId:connection.to.interfaceId},
pinMap:(connection.pinMap||[]).map(pair=>({
from:+pair.from,
to:+pair.to,
...(pair.label?{label:pair.label}:{}),
...(pair.style?{style:{...pair.style}}:{})
}))
})),
embeddedBoards:boards.map(toPcbDocument)
};
}
async function readJsonFiles(files) {
const results = [];
for (const file of files) { try { results.push(JSON.parse(await file.text())); } catch (_) { toast(`${file.name} 不是有效 JSON`); } }
return results;
}
async function importBoards(files) {
const docs = await readJsonFiles(files); let count = 0;
docs.flatMap(d => Array.isArray(d) ? d : [d]).forEach(board => {
if (board.kind !== 'wiresketch/pcb' || !Array.isArray(board.interfaces)) return;
const copy = structuredClone(board); if (state.boards.some(b => b.id === copy.id)) copy.id = uid('pcb');
copy.builtIn=false;
if(copy.source==='generated')refreshGeneratedBoard(copy);
state.boards.push(copy); count++;
});
if (count) { saveState(); renderBoardList(); renderComponentList(); toast(`已导入 ${count} 块板卡`); } else toast('没有找到有效的 PCB 描述');
}
function renderComponentList() {
$('#componentList').innerHTML = state.boards.map(b => `<div class="component-card" draggable="true" data-id="${b.id}"><img src="${boardImageSource(b) || placeholderSvg(b.name)}" alt=""><span><strong>${escapeHtml(b.name)}</strong><small>${b.interfaces.length} 个接口 · 点击添加</small></span></div>`).join('');
$$('.component-card').forEach(card => {
card.onclick = () => addNode(card.dataset.id);
card.ondragstart = e => e.dataTransfer.setData('text/pcb-id', card.dataset.id);
});
}
function addNode(boardId, at) {
const board = state.boards.find(b => b.id === boardId); if (!board) return;
const n = state.assembly.nodes.length;
state.assembly.nodes.push({id:uid('node'),boardId,label:board.name,x:at?.x??90+(n%4)*285,y:at?.y??70+Math.floor(n/4)*250,rotation:0,flipX:false,scale:1,fixed:false,showName:true});
saveState(); renderAssembly();
}
function renderAssembly() {
$('#assemblyName').value = state.assembly.name;
const canvas=$('#assemblyCanvas'),canvasSize=assemblyCanvasSize(),layer=$('#nodeLayer'),controlLayer=$('#nodeControlLayer'),wireLayer=$('#wireLayer'),controls=[];
canvas.style.width=`${canvasSize.width*zoom}px`;canvas.style.height=`${canvasSize.height*zoom}px`;canvas.style.backgroundSize=`${18*zoom}px ${18*zoom}px`;
layer.style.width=`${canvasSize.width}px`;layer.style.height=`${canvasSize.height}px`;
controlLayer.style.width=`${canvasSize.width}px`;controlLayer.style.height=`${canvasSize.height}px`;
wireLayer.setAttribute('width',canvasSize.width);wireLayer.setAttribute('height',canvasSize.height);
layer.style.transform = `scale(${zoom})`;
controlLayer.style.transform = `scale(${zoom})`;
wireLayer.style.transform = `scale(${zoom})`;
layer.innerHTML = state.assembly.nodes.map(node => {
const board = state.boards.find(b => b.id === node.boardId);
if (!board) return '';
const geometry = getBoardImageGeometry(board,node);
const ports = board.interfaces.map(intf => {
const anchor = getInterfaceAnchor(board, intf, node);
const pending = pendingPort?.nodeId === node.id && pendingPort?.interfaceId === intf.id ? 'pending' : '';
const selected=selectedPort?.nodeId===node.id&&selectedPort?.interfaceId===intf.id?'selected':'';
const single=interfaceSingleSignalMode(node,intf.id)?'single-mode':'';
return `<button class="node-port ${anchor.side} ${pending} ${selected} ${single}" style="left:${anchor.x}px;top:${anchor.y}px" data-node="${node.id}" data-interface="${intf.id}" title="${escapeHtml(intf.name)}"><span class="port-dot"></span><span class="port-label">${escapeHtml(intf.name)} · ${intf.pins.length}P${single?' · 单线模式':''}</span></button>`;
}).join('');
const pins=board.interfaces.filter(intf=>interfaceSingleSignalMode(node,intf.id)&&(pendingPort?.pin||selectedPort?.nodeId===node.id&&selectedPort?.interfaceId===intf.id)).flatMap(intf=>{
const anchor=getInterfaceAnchor(board,intf,node),edge=interfaceEdgeGeometry(board,intf,node,baseInterfaceSide(intf.rect)),verticalEdge=anchor.side==='left'||anchor.side==='right';
const entries=intf.pins.map((name,index)=>{const pin=index+1,point=getPinAnchor(board,intf,pin,node);return {name,index,pin,rank:0,projection:(point.x-anchor.x)*edge.dx+(point.y-anchor.y)*edge.dy};});
[...entries].sort((first,second)=>first.projection-second.projection).forEach((entry,rank)=>entry.rank=rank);
return entries.map(entry=>{
const endpoint={nodeId:node.id,interfaceId:intf.id},connectionCount=pinConnections(endpoint,entry.pin).length,connected=connectionCount>0,pending=pendingPort?.nodeId===node.id&&pendingPort?.interfaceId===intf.id&&pendingPort?.pin===entry.pin;
const offset=(entry.rank-(entries.length-1)/2)*(verticalEdge?28:82),outward=verticalEdge?53:25;
const x=anchor.x+anchor.dx*outward+edge.dx*offset,y=anchor.y+anchor.dy*outward+edge.dy*offset,color=pinSignalColor(entry.name,entry.index);
return `<button class="node-pin ${anchor.side} ${connected?'connected':''} ${pending?'pending':''}" style="left:${x}px;top:${y}px;--pin-color:${color}" data-node="${node.id}" data-interface="${intf.id}" data-pin="${entry.pin}" title="${escapeHtml(intf.name)} / ${escapeHtml(entry.name)}${connected?` · ${connectionCount} 条连接`:''}"><span class="node-pin-dot"></span><b>${entry.pin}</b><span class="node-pin-name">${escapeHtml(entry.name)}</span>${connected?`<i>×${connectionCount}</i>`:''}</button>`;
});
}).join('');
const source=geometry.source,rotation=nodeRotation(node),scaleX=nodeFlipX(node)?-1:1;
const imageSource=board.source==='generated'?placeholderSvg('',board.generated?.width,board.generated?.height,board.generated?.color):boardImageSource(board);
const nodeSelected=selectedItemKeys.has(selectionKey('node',node.id))||node.id===selectedNodeId;
const nameOffset=nodeNameOffset(board,node),nameStyle=nodeNameStyle(node),nameLabel=nodeNameVisible(node)?`<button type="button" class="node-name-label ${nodeSelected?'selected':''}" data-node-name="${node.id}" style="left:${geometry.centerX+nameOffset.x}px;top:${geometry.centerY+nameOffset.y}px;${textInlineStyle(nameStyle)}" title="拖动板卡名称">${escapeHtml(node.label)}</button>`:'';
controls.push(`<div class="node-controls" data-id="${node.id}" style="left:${node.x}px;top:${node.y}px">${ports}${pins}${nameLabel}</div>`);
return `<article class="board-node ${nodeSelected?'selected':''} ${nodeFixed(node)?'fixed':''}" data-id="${node.id}" style="left:${node.x}px;top:${node.y}px"><div class="node-body">${imageSource?`<img src="${imageSource}" data-board="${board.id}" alt="" style="left:${source.x}px;top:${source.y}px;width:${source.width}px;height:${source.height}px;transform:rotate(${rotation}deg) scaleX(${scaleX});transform-origin:center">`:`<div class="node-placeholder" style="transform:rotate(${rotation}deg) scaleX(${scaleX})"></div>`}</div><footer class="node-header"><span class="node-header-spacer">${nodeFixed(node)?'<span class="node-fixed-mark" title="位置已固定">◆</span>':''}</span><button class="node-action node-scale-down" title="缩小板卡">−</button><span class="node-scale-label">${Math.round(nodeScale(node)*100)}%</span><button class="node-action node-scale-up" title="放大板卡">+</button><button class="node-action node-flip" title="水平翻转">⇆</button><button class="node-action node-rotate" title="顺时针旋转 90°">↻</button><button class="node-action node-remove" title="移除板卡">×</button></footer></article>`;
}).join('');
const textMarkup=assemblyTexts().map(item=>{const style=freeTextStyle(item);return `<button type="button" class="assembly-text-element ${selectedItemKeys.has(selectionKey('free',item.id))||item.id===selectedTextId?'selected':''}" data-text-kind="free" data-text-id="${item.id}" style="left:${Number(item.x)||0}px;top:${Number(item.y)||0}px;${textInlineStyle(style)}">${escapeHtml(item.text||'自由文本')}</button>`;}).join('');
controlLayer.innerHTML=controls.join('')+textMarkup;
$$('.board-node').forEach(nodeEl => {
const selectNode=(preserveGroup=false)=>{activateSelectedItem('node',nodeEl.dataset.id,{preserveGroup});renderSelection();};
nodeEl.onpointerdown = e => { if(e.button!==0)return;if(!e.target.closest('.node-port,.node-pin'))selectNode(true);const node=state.assembly.nodes.find(item=>item.id===nodeEl.dataset.id);if (!nodeFixed(node)&&!e.target.closest('.node-port,.node-pin,.node-action')) startNodeDrag(e,nodeEl.dataset.id); };
nodeEl.onclick = e => {if(performance.now()<ignoreCanvasClickUntil)return;if(!e.target.closest('.node-port,.node-pin,.node-action'))selectNode(true);};
$('.node-scale-down', nodeEl).onclick = e => { e.stopPropagation(); resizeNode(nodeEl.dataset.id,-.1); };
$('.node-scale-up', nodeEl).onclick = e => { e.stopPropagation(); resizeNode(nodeEl.dataset.id,.1); };
$('.node-flip', nodeEl).onclick = e => { e.stopPropagation(); flipNode(nodeEl.dataset.id); };
$('.node-rotate', nodeEl).onclick = e => { e.stopPropagation(); rotateNode(nodeEl.dataset.id); };
$('.node-remove', nodeEl).onclick = e => { e.stopPropagation(); removeNode(nodeEl.dataset.id); };
});
$$('.node-port').forEach(port => port.onclick = e => { e.stopPropagation();clearItemSelection();selectPort(port.dataset.node, port.dataset.interface); });
$$('.node-pin').forEach(pin=>pin.onclick=e=>{e.stopPropagation();selectedPort={nodeId:pin.dataset.node,interfaceId:pin.dataset.interface};clearItemSelection();selectedWireId=null;selectedWirePinKey=null;selectPortPin(Number(pin.dataset.pin));});
$$('.node-name-label').forEach(label=>{
label.onpointerdown=e=>{if(e.button!==0)return;e.stopPropagation();startNodeNameDrag(e,label.dataset.nodeName);};
label.onclick=e=>e.stopPropagation();
});
$$('.assembly-text-element').forEach(element=>{
element.onpointerdown=e=>{if(e.button!==0)return;e.stopPropagation();startTextDrag(e,element.dataset.textKind,element.dataset.textId);};
element.onclick=e=>e.stopPropagation();
});
$$('.node-body img[data-board]').forEach(img => {
const captureSize = () => {
const board = state.boards.find(b=>b.id===img.dataset.board);
if (!board?.imageSize && img.naturalWidth) {
board.imageSize={width:img.naturalWidth,height:img.naturalHeight};
saveState(); requestAnimationFrame(renderAssembly);
}
};
img.complete ? captureSize() : img.onload=captureSize;
});
$('#assemblyEmpty').classList.toggle('hidden', state.assembly.nodes.length > 0||assemblyTexts().length > 0);
$('#nodeCount').textContent = state.assembly.nodes.length;
$('#wireCount').textContent = state.assembly.connections.reduce((total,connection)=>{
const from=endpointDetails(connection.from),to=endpointDetails(connection.to);
return total+(from.intf&&to.intf?connectionPinPairs(connection,from.intf,to.intf).length:0);
},0);
$('#zoomLabel').textContent = `${Math.round(zoom*100)}%`;
renderAssemblyProperties();
requestAnimationFrame(renderWires);
}
function renderSelection() {
$$('.board-node').forEach(n => n.classList.toggle('selected',selectedItemKeys.has(selectionKey('node',n.dataset.id))||n.dataset.id===selectedNodeId));
$$('.node-name-label').forEach(label=>label.classList.toggle('selected',selectedItemKeys.has(selectionKey('node',label.dataset.nodeName))||label.dataset.nodeName===selectedNodeId));
$$('.assembly-text-element[data-text-kind="free"]').forEach(element=>element.classList.toggle('selected',selectedItemKeys.has(selectionKey('free',element.dataset.textId))||element.dataset.textId===selectedTextId));
$$('.node-port').forEach(port=>port.classList.toggle('selected',port.dataset.node===selectedPort?.nodeId&&port.dataset.interface===selectedPort?.interfaceId));
$$('.wire-group.bundle-selectable').forEach(group=>group.classList.toggle('selected',group.dataset.id===selectedWireId&&!selectedWirePinKey));
$$('.signal-wire.selectable').forEach(w => w.classList.toggle('selected', w.closest('.wire-group')?.dataset.id===selectedWireId&&w.dataset.pinKey===selectedWirePinKey));
renderAssemblyProperties();
}
function setAssemblyZoom(nextZoom,clientX,clientY) {
const viewport=$('#assemblyViewport'),rect=viewport.getBoundingClientRect();
const cursorX=clientX==null?viewport.clientWidth/2:clientX-rect.left;
const cursorY=clientY==null?viewport.clientHeight/2:clientY-rect.top;
const logicalX=(viewport.scrollLeft+cursorX)/zoom,logicalY=(viewport.scrollTop+cursorY)/zoom;
zoom=Math.max(.4,Math.min(1.5,nextZoom));
renderAssembly();
viewport.scrollLeft=logicalX*zoom-cursorX;
viewport.scrollTop=logicalY*zoom-cursorY;
}
function wirePinKey(pair) { return `${pair.from}:${pair.to}`; }
function selectedSignal() {
const connection=state.assembly.connections.find(item=>item.id===selectedWireId);if(!connection)return null;
if(connectionMode(connection)!=='signal'||!selectedWirePinKey)return null;
const from=endpointDetails(connection.from),to=endpointDetails(connection.to);if(!from.intf||!to.intf)return null;
const signal=connectionPinPairs(connection,from.intf,to.intf).find(pair=>wirePinKey(pair)===selectedWirePinKey);
return signal?{connection,signal,from,to}:null;
}
function selectedBundle() {
const connection=state.assembly.connections.find(item=>item.id===selectedWireId);
if(!connection||connectionMode(connection)!=='bundle'||selectedWirePinKey)return null;
const from=endpointDetails(connection.from),to=endpointDetails(connection.to);
return from.intf&&to.intf?{connection,from,to}:null;
}
function editableSelectedSignal() {
const selected=selectedSignal();if(!selected)return null;
if(!selected.connection.pinMap?.length){
selected.connection.pinMap=connectionPinPairs(selected.connection,selected.from.intf,selected.to.intf).map(pair=>({from:pair.from,to:pair.to}));
}
return selected.connection.pinMap.find(pair=>wirePinKey(pair)===selectedWirePinKey)||null;
}
function renderAssemblyProperties() {
const defaults=assemblyWireDefaults(),canvasSize=assemblyCanvasSize();
$('#defaultWireWidth').value=defaults.width;
$('#defaultWireWidthValue').value=defaults.width.toFixed(1);
$('#defaultWireGap').value=defaults.gap;
$('#defaultWireGapValue').value=defaults.gap;
$('#defaultRouteGap').value=defaults.routeGap;
$('#defaultRouteGapValue').value=defaults.routeGap;
$('#defaultCornerRadius').value=defaults.cornerRadius;
$('#defaultCornerRadiusValue').value=defaults.cornerRadius;
$('#canvasWidth').value=canvasSize.width;
$('#canvasWidthValue').value=canvasSize.width;
$('#canvasHeight').value=canvasSize.height;
$('#canvasHeightValue').value=canvasSize.height;
$('#defaultShowFromLabels').checked=defaults.showFromLabels;
$('#defaultShowToLabels').checked=defaults.showToLabels;
const textDefaults=assemblyTextDefaults();
$('#defaultTextFontSize').value=textDefaults.fontSize;$('#defaultTextFontSizeValue').value=textDefaults.fontSize;
$('#defaultTextFontFamily').value=textDefaults.fontFamily;$('#defaultTextColor').value=textDefaults.color;
populateTextStyleControls('defaultText',textDefaults);
const node=state.assembly.nodes.find(item=>item.id===selectedNodeId),board=state.boards.find(item=>item.id===node?.boardId);
const textItem=assemblyTexts().find(item=>item.id===selectedTextId);
const portNode=state.assembly.nodes.find(item=>item.id===selectedPort?.nodeId),portBoard=state.boards.find(item=>item.id===portNode?.boardId),portInterface=portBoard?.interfaces.find(item=>item.id===selectedPort?.interfaceId);
const selected=selectedSignal(),bundle=selectedBundle(),hasNode=!!node&&!!board,hasPort=!!portNode&&!!portInterface,hasSignal=!!selected,hasBundle=!!bundle,hasText=!!textItem,hasMulti=selectedItemKeys.size>1;
$('#globalPropertyGroup').classList.toggle('hidden',hasMulti||hasNode||hasPort||hasSignal||hasBundle||hasText);
$('#multiPropertyGroup').classList.toggle('hidden',!hasMulti);$('#multiSelectionCount').textContent=selectedItemKeys.size;
$('#nodePropertyGroup').classList.toggle('hidden',hasMulti||!hasNode||hasPort||hasSignal||hasBundle||hasText);
$('#textPropertyGroup').classList.toggle('hidden',hasMulti||!hasText);
$('#portPropertyGroup').classList.toggle('hidden',hasMulti||!hasPort||hasSignal||hasBundle||hasText);
$('#wirePropertyGroup').classList.toggle('hidden',hasMulti||!hasSignal);
$('#bundlePropertyGroup').classList.toggle('hidden',hasMulti||!hasBundle);
$('#assemblyPropertyTitle').textContent=hasMulti?'批量选择':hasText?'文本属性':hasSignal?'信号线属性':hasBundle?'线束属性':hasPort?'端口属性':hasNode?'板卡属性':'全局属性';
if(node&&board){
const style=nodeNameStyle(node);
$('#nodePropertySummary').textContent=node.label;
$('#nodeFixed').checked=nodeFixed(node);
$('#nodeShowName').checked=nodeNameVisible(node);
$('#nodeNameFontSize').value=style.fontSize;$('#nodeNameFontSizeValue').value=style.fontSize;
$('#nodeNameFontFamily').value=style.fontFamily;$('#nodeNameColor').value=style.color;
populateTextStyleControls('nodeName',style);
$('#resetNodeNameStyleBtn').disabled=!node.nameStyle;
$('#resetNodeNamePositionBtn').disabled=!node.nameOffset;
$('#nodeInterfaceGaps').innerHTML=board.interfaces.map(intf=>{const override=node.interfaceLabelGaps?.[intf.id],value=override??defaults.gap;return `<div class="interface-gap-row"><span title="${escapeHtml(intf.name)}">${escapeHtml(intf.name)} · ${intf.pins.length}P</span><input type="range" min="0" max="24" step="1" value="${value}" data-interface="${intf.id}" aria-label="${escapeHtml(intf.name)} 信号标签间距"><output>${value}</output><button type="button" class="interface-gap-reset" data-reset-interface="${intf.id}" title="恢复全局 ${defaults.gap}" ${override==null?'disabled':''}>↺</button></div>`;}).join('')||'<div class="compact-empty">此板卡没有接口</div>';
}
if(textItem){
const style=freeTextStyle(textItem);
$('#assemblyTextContent').value=textItem.text||'';
$('#assemblyTextFontSize').value=style.fontSize;$('#assemblyTextFontSizeValue').value=style.fontSize;
$('#assemblyTextFontFamily').value=style.fontFamily;$('#assemblyTextColor').value=style.color;
populateTextStyleControls('assemblyText',style);
$('#resetAssemblyTextStyleBtn').disabled=!textItem.style;
}
if(hasPort){
const single=interfaceSingleSignalMode(portNode,portInterface.id);
$('#portPropertySummary').innerHTML=`<b>${escapeHtml(portNode.label)}</b><br>${escapeHtml(portInterface.name)} · ${portInterface.pins.length}P`;
$('#portSingleSignalMode').checked=single;
$('#portModeHint').textContent=single?'点击画布上的 Pin 托盘选择起点;随后可用的对端托盘会自动展开。':'默认按针脚顺序整束连接,删除时会删除整条线束。';
}
if(hasBundle){
const pairs=connectionPinPairs(bundle.connection,bundle.from.intf,bundle.to.intf),count=pairs.length,gap=connectionWireGap(bundle.connection);
$('#bundleEndpointSummary').innerHTML=`<b>${escapeHtml(bundle.from.node?.label||'未知板卡')}</b> / ${escapeHtml(bundle.from.intf.name)}<br><b>${escapeHtml(bundle.to.node?.label||'未知板卡')}</b> / ${escapeHtml(bundle.to.intf.name)}<br>${count} 根信号线`;
$('#bundleRouteGap').value=gap;$('#bundleRouteGapValue').value=gap;
const fromValues=pairs.map(pair=>signalWireStyle(pair).showFromLabels),toValues=pairs.map(pair=>signalWireStyle(pair).showToLabels);
$('#bundleShowFromLabels').checked=fromValues.every(Boolean);$('#bundleShowFromLabels').indeterminate=fromValues.some(Boolean)&&!fromValues.every(Boolean);
$('#bundleShowToLabels').checked=toValues.every(Boolean);$('#bundleShowToLabels').indeterminate=toValues.some(Boolean)&&!toValues.every(Boolean);
}
if(!selected)return;
const {signal,from,to}=selected,style=signalWireStyle(signal);
$('#wireEndpointSummary').innerHTML=`<b>端点 1</b> ${escapeHtml(from.node?.label||'未知板卡')} / ${escapeHtml(from.intf?.name||'未知接口')} / ${escapeHtml(signal.fromName)}<br><b>端点 2</b> ${escapeHtml(to.node?.label||'未知板卡')} / ${escapeHtml(to.intf?.name||'未知接口')} / ${escapeHtml(signal.toName)}`;
$('#wireDisplayName').value=signal.label||'';
$('#wireWidth').value=style.width;
$('#wireWidthValue').value=style.width.toFixed(1);
$('#wireCornerRadius').value=style.cornerRadius;
$('#wireCornerRadiusValue').value=style.cornerRadius;
const routeGap=connectionWireGap(selected.connection);
$('#wireRouteGap').value=routeGap;
$('#wireRouteGapValue').value=routeGap;
$('#wireShowFromLabels').checked=style.showFromLabels;
$('#wireShowToLabels').checked=style.showToLabels;
$('#deleteWireBtn').textContent=connectionMode(selected.connection)==='signal'?'删除此信号线':'删除整条线束';