-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.js
More file actions
3756 lines (3230 loc) · 117 KB
/
Copy pathcode.js
File metadata and controls
3756 lines (3230 loc) · 117 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
// Likey Assistant - Figma Plugin
figma.showUI(__html__, { width: 400, height: 600, themeColors: true });
// 저장된 탭 순서 → UI로 전송
(async function sendSavedPrefs() {
try {
var tabOrder = await figma.clientStorage.getAsync('tabOrder');
if (tabOrder) {
figma.ui.postMessage({ type: 'restore-tab-order', order: tabOrder });
}
} catch(e) {}
})();
// 현재 선택된 필드명 저장 (미리보기용)
let currentFieldName = null;
function updateSelectionInfo() {
const selection = figma.currentPage.selection;
// 현재 필드명이 설정되어 있으면 일치하는 레이어 개수도 계산
let matchingCount = 0;
if (currentFieldName) {
for (const node of selection) {
matchingCount += countMatchingLayersInNode(node, currentFieldName.toLowerCase());
}
}
figma.ui.postMessage({
type: 'selection-update',
count: selection.length,
names: selection.map(node => node.name).slice(0, 3),
matchingCount: matchingCount
});
}
// 일치하는 레이어 개수 세기
function countMatchingLayers(fieldName) {
currentFieldName = fieldName;
const selection = figma.currentPage.selection;
let matchingCount = 0;
for (const node of selection) {
matchingCount += countMatchingLayersInNode(node, fieldName.toLowerCase());
}
figma.ui.postMessage({
type: 'selection-update',
count: selection.length,
names: selection.map(node => node.name).slice(0, 3),
matchingCount: matchingCount
});
}
// 노드 내에서 필드명과 일치하는 레이어 개수 재귀적으로 세기
function countMatchingLayersInNode(node, fieldNameLower) {
let count = 0;
// 현재 노드의 이름이 필드명과 일치하는지 확인
if (node.name.toLowerCase() === fieldNameLower) {
count++;
}
// 자식 노드들도 재귀적으로 탐색
if ('children' in node && node.children) {
for (const child of node.children) {
count += countMatchingLayersInNode(child, fieldNameLower);
}
}
return count;
}
// 선택 변경 감지
figma.on('selectionchange', () => {
updateSelectionInfo();
});
// 초기 선택 정보 전송
updateSelectionInfo();
// 이미지 fetch 요청에 대한 Promise resolver 맵
var _imageResolvers = {};
// UI에서 메시지 수신
figma.ui.onmessage = async (msg) => {
// ui.html에서 이미지 데이터 응답 수신
if (msg.type === 'image-data-response') {
const resolver = _imageResolvers[msg.requestId];
if (resolver) {
delete _imageResolvers[msg.requestId];
if (msg.imageData && msg.imageData.length > 0) {
resolver(new Uint8Array(msg.imageData));
} else {
resolver(null);
}
}
return;
}
if (msg.type === 'execute-command') {
await executeCommand(msg.command);
}
if (msg.type === 'get-selection-info') {
getSelectionInfo();
}
// 탭 순서 저장 (figma.clientStorage → 플러그인 재시작 후에도 유지)
if (msg.type === 'save-tab-order') {
try {
await figma.clientStorage.setAsync('tabOrder', msg.order);
} catch(e) {}
}
// 직접 텍스트 변경
if (msg.type === 'direct-text-change') {
await directTextChange(msg.text);
}
if (msg.type === 'spell-check') {
await spellCheck();
}
if (msg.type === 'spell-check-response') {
// UI에서 받은 맞춤법 검사 결과 처리
figma.ui.postMessage({
type: 'spell-results',
errors: msg.errors
});
}
// 레이어 네이밍 기능
if (msg.type === 'load-layers') {
loadSelectedLayers();
}
if (msg.type === 'rename-layers') {
renameLayers(msg.changes);
}
// 선택된 레이어 이름 변경 (Selected Change)
if (msg.type === 'rename-selected') {
renameSelectedLayers(msg.namingType);
}
// 자동 네이밍 (Auto Rename)
if (msg.type === 'auto-rename') {
autoRenameAllLayers();
}
// UI 리사이즈
if (msg.type === 'resize') {
figma.ui.resize(msg.width, msg.height);
}
// 더미 데이터 적용
if (msg.type === 'apply-dummy-data') {
applyDummyData(msg.value);
}
// 랜덤 채우기
if (msg.type === 'random-fill') {
await randomFillData(msg.category, msg.data, msg.avatarImageData || {});
}
// 이미지 채우기 (레거시 - pravatar)
if (msg.type === 'apply-image-fill') {
applyImageFill(msg.imageType);
}
// 엑셀시트 이미지 적용 (선택 레이어에 적용)
if (msg.type === 'apply-sheet-image') {
await applySheetImage(msg.imageBytes);
}
// 일치하는 레이어 개수 세기
if (msg.type === 'count-matching-layers') {
countMatchingLayers(msg.fieldName);
}
// 디자인 시스템 체커
if (msg.type === 'scan-design-system') {
scanDesignSystem(msg.checkerType);
}
// 특정 노드 선택
if (msg.type === 'select-node') {
selectNodeById(msg.nodeId);
}
// 여러 노드 선택
if (msg.type === 'select-multiple-nodes') {
selectMultipleNodes(msg.nodeIds);
}
// 코드에서 디자인 생성
if (msg.type === 'generate-from-code') {
await generateDesignFromCode(msg.codeType, msg.parsed, msg.rawCode);
}
// Tailwind → Gemini 결과로 디자인 생성
if (msg.type === 'generate-from-tailwind') {
await createDesignFromGeminiResponse(msg.geminiResult);
}
// 브라우저 렌더 → Figma 디자인 생성 (HTML/CSS, Tailwind)
if (msg.type === 'generate-from-browser-render') {
await createDesignFromBrowserRender(msg.designTree);
}
// 베리어블 생성
if (msg.type === 'create-variables') {
await createVariablesFromTokens(msg.collectionName, msg.tokens);
}
// 텍스트 스타일 생성
if (msg.type === 'create-text-styles') {
await createTextStylesFromTokens(msg.tokens);
}
// 베리어블 컬렉션 목록 조회
if (msg.type === 'get-variable-collections') {
try {
var cols = figma.variables.getLocalVariableCollections()
.map(function(c) { return { name: c.name }; });
figma.ui.postMessage({ type: 'variable-collections', collections: cols });
} catch(e) {
figma.ui.postMessage({ type: 'variable-collections', collections: [] });
}
}
// 테이블 토큰 → Light/Dark 모드 베리어블 생성
if (msg.type === 'create-table-variables') {
await createTableVariables(msg.collectionName, msg.tokens);
}
// .pen 프레임 변환
if (msg.type === 'convert-pen-frames') {
await convertPenFrames(msg.frames, msg.variables);
}
// AI 디자인 생성
if (msg.type === 'ai-generate') {
await executeAICommands(msg.commands);
}
};
// 선택된 레이어 정보 가져오기
function getSelectionInfo() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: 'selection-info',
info: '선택된 레이어가 없습니다.'
});
return;
}
const infos = selection.map(node => {
let info = `[${node.type}] ${node.name}\n`;
info += ` - ID: ${node.id}\n`;
info += ` - 위치: (${Math.round(node.x)}, ${Math.round(node.y)})\n`;
info += ` - 크기: ${Math.round(node.width)} x ${Math.round(node.height)}\n`;
if (node.type === 'TEXT') {
info += ` - 텍스트: "${node.characters}"\n`;
info += ` - 폰트 크기: ${node.fontSize}\n`;
}
if ('fills' in node && Array.isArray(node.fills) && node.fills.length > 0) {
const fill = node.fills[0];
if (fill.type === 'SOLID') {
const color = fill.color;
const hex = rgbToHex(color.r, color.g, color.b);
info += ` - 배경색: ${hex}\n`;
}
}
if ('opacity' in node) {
info += ` - 투명도: ${Math.round(node.opacity * 100)}%\n`;
}
return info;
});
figma.ui.postMessage({
type: 'selection-info',
info: infos.join('\n')
});
}
// 명령어 실행
async function executeCommand(command) {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: 'status',
status: 'error',
message: '먼저 레이어를 선택해주세요.'
});
return;
}
try {
// 명령어 파싱 및 실행
const result = await parseAndExecute(command, selection);
figma.ui.postMessage({
type: 'status',
status: 'success',
message: result
});
} catch (error) {
figma.ui.postMessage({
type: 'status',
status: 'error',
message: `오류: ${error.message}`
});
}
}
// 명령어 파싱 및 실행
async function parseAndExecute(command, selection) {
const cmd = command.toLowerCase();
// 텍스트 찾아서 변경: "기존텍스트>새텍스트" 형식
// 예: "팔로워(전체)>전체 메시지"
if (command.includes('>') && !command.startsWith('>')) {
const parts = command.split('>');
if (parts.length === 2) {
const searchText = parts[0].trim();
const newText = parts[1].trim();
let changed = 0;
for (const node of selection) {
// 선택된 노드 내의 모든 텍스트에서 검색 (컴포넌트, 인스턴스, 오토레이아웃 포함)
const textNodes = findTextNodeByContent(node, searchText);
for (const textNode of textNodes) {
const success = await replaceTextInNode(textNode, searchText, newText);
if (success) changed++;
}
}
if (changed === 0) {
throw new Error(`"${searchText}" 텍스트를 찾을 수 없습니다.`);
}
return `"${searchText}"를 "${newText}"로 ${changed}개 변경했습니다.`;
}
}
// 프레임 내 모든 텍스트 변경: ">새텍스트" 형식
if (command.startsWith('>')) {
const newText = command.slice(1).trim();
let changed = 0;
for (const node of selection) {
// 프레임/그룹/컴포넌트/인스턴스 내부 텍스트 모두 찾기
const textNodes = findAllTextNodes(node);
for (const textNode of textNodes) {
const success = await changeTextInNode(textNode, newText);
if (success) changed++;
}
}
if (changed === 0) {
throw new Error('선택된 영역에 텍스트가 없습니다.');
}
return `${changed}개의 텍스트를 "${newText}"로 변경했습니다.`;
}
// 텍스트 변경 - 기존 방식도 지원
const textMatch = command.match(/['"'"](.+?)['"'"]/);
if ((cmd.includes('텍스트') && cmd.includes('변경')) || cmd.includes('text')) {
let newText;
if (textMatch) {
newText = textMatch[1];
} else {
throw new Error("변경할 텍스트를 입력해주세요.\n예: 팔로워(전체)>전체 메시지");
}
let changed = 0;
for (const node of selection) {
const textNodes = findAllTextNodes(node);
for (const textNode of textNodes) {
const success = await changeTextInNode(textNode, newText);
if (success) changed++;
}
}
if (changed === 0) {
throw new Error('선택된 영역에 텍스트가 없습니다.');
}
return `${changed}개의 텍스트를 "${newText}"로 변경했습니다.`;
}
// 색상 변경
const colorMatch = command.match(/#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})/);
if ((cmd.includes('색') && cmd.includes('변경')) || cmd.includes('color')) {
if (!colorMatch) {
throw new Error('색상을 HEX 코드로 입력해주세요. 예: #FF5733');
}
const hex = colorMatch[0];
const rgb = hexToRgb(hex);
let changed = 0;
for (const node of selection) {
if ('fills' in node) {
const fills = JSON.parse(JSON.stringify(node.fills));
if (fills.length > 0 && fills[0].type === 'SOLID') {
fills[0].color = rgb;
node.fills = fills;
changed++;
} else {
node.fills = [{ type: 'SOLID', color: rgb }];
changed++;
}
}
}
if (changed === 0) {
throw new Error('색상을 변경할 수 없는 레이어입니다.');
}
return `${changed}개의 레이어 색상을 ${hex}로 변경했습니다.`;
}
// 크기 변경 (너비)
const widthMatch = cmd.match(/너비[를을]?\s*(\d+)/);
if (widthMatch) {
const newWidth = parseInt(widthMatch[1]);
for (const node of selection) {
if ('resize' in node) {
node.resize(newWidth, node.height);
}
}
return `너비를 ${newWidth}px로 변경했습니다.`;
}
// 크기 변경 (높이)
const heightMatch = cmd.match(/높이[를을]?\s*(\d+)/);
if (heightMatch) {
const newHeight = parseInt(heightMatch[1]);
for (const node of selection) {
if ('resize' in node) {
node.resize(node.width, newHeight);
}
}
return `높이를 ${newHeight}px로 변경했습니다.`;
}
// 투명도 변경
const opacityMatch = cmd.match(/(\d+)\s*%/);
if (cmd.includes('투명도') && opacityMatch) {
const opacity = parseInt(opacityMatch[1]) / 100;
for (const node of selection) {
if ('opacity' in node) {
node.opacity = Math.max(0, Math.min(1, opacity));
}
}
return `투명도를 ${opacityMatch[1]}%로 변경했습니다.`;
}
// 레이어 복제
if (cmd.includes('복제') || cmd.includes('복사') || cmd.includes('duplicate')) {
const newNodes = [];
for (const node of selection) {
const clone = node.clone();
clone.x += 20;
clone.y += 20;
newNodes.push(clone);
}
figma.currentPage.selection = newNodes;
return `${selection.length}개의 레이어를 복제했습니다.`;
}
// 레이어 삭제
if (cmd.includes('삭제') || cmd.includes('delete') || cmd.includes('remove')) {
const count = selection.length;
for (const node of selection) {
node.remove();
}
return `${count}개의 레이어를 삭제했습니다.`;
}
// 폰트 크기 변경
const fontSizeMatch = cmd.match(/폰트\s*(?:크기)?[를을]?\s*(\d+)/);
if (fontSizeMatch || (cmd.includes('font') && cmd.includes('size'))) {
const sizeMatch = command.match(/(\d+)/);
if (!sizeMatch) {
throw new Error('폰트 크기를 숫자로 입력해주세요.');
}
const newSize = parseInt(sizeMatch[1]);
let changed = 0;
for (const node of selection) {
if (node.type === 'TEXT') {
await figma.loadFontAsync(node.fontName);
node.fontSize = newSize;
changed++;
}
}
if (changed === 0) {
throw new Error('선택된 레이어 중 텍스트가 없습니다.');
}
return `폰트 크기를 ${newSize}px로 변경했습니다.`;
}
// 이동
const moveMatch = cmd.match(/[이동|움직|move].*?[(\(]?\s*(-?\d+)\s*,\s*(-?\d+)\s*[)\)]?/);
if (moveMatch) {
const dx = parseInt(moveMatch[1]);
const dy = parseInt(moveMatch[2]);
for (const node of selection) {
node.x += dx;
node.y += dy;
}
return `레이어를 (${dx}, ${dy})만큼 이동했습니다.`;
}
// 숨기기
if (cmd.includes('숨기') || cmd.includes('hide')) {
for (const node of selection) {
node.visible = false;
}
return `${selection.length}개의 레이어를 숨겼습니다.`;
}
// 보이기
if (cmd.includes('보이') || cmd.includes('show') || cmd.includes('표시')) {
for (const node of selection) {
node.visible = true;
}
return `${selection.length}개의 레이어를 표시했습니다.`;
}
// 이름 변경
const nameMatch = command.match(/이름[을를]?\s*['"'"](.+?)['"'"]/);
if (nameMatch) {
const newName = nameMatch[1];
for (const node of selection) {
node.name = newName;
}
return `레이어 이름을 "${newName}"으로 변경했습니다.`;
}
// 모서리 둥글기
const radiusMatch = cmd.match(/(?:모서리|라운드|radius|corner)[를을]?\s*(\d+)/);
if (radiusMatch) {
const radius = parseInt(radiusMatch[1]);
for (const node of selection) {
if ('cornerRadius' in node) {
node.cornerRadius = radius;
}
}
return `모서리 둥글기를 ${radius}px로 변경했습니다.`;
}
throw new Error(`명령어를 이해하지 못했습니다: "${command}"\n예시 명령어를 참고해주세요.`);
}
// 유틸리티 함수들
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!result) {
const shortResult = /^#?([a-f\d])([a-f\d])([a-f\d])$/i.exec(hex);
if (shortResult) {
return {
r: parseInt(shortResult[1] + shortResult[1], 16) / 255,
g: parseInt(shortResult[2] + shortResult[2], 16) / 255,
b: parseInt(shortResult[3] + shortResult[3], 16) / 255
};
}
return { r: 0, g: 0, b: 0 };
}
return {
r: parseInt(result[1], 16) / 255,
g: parseInt(result[2], 16) / 255,
b: parseInt(result[3], 16) / 255
};
}
function rgbToHex(r, g, b) {
const toHex = (c) => {
const hex = Math.round(c * 255).toString(16);
return hex.length === 1 ? '0' + hex : hex;
};
return '#' + toHex(r) + toHex(g) + toHex(b);
}
// [REFACTOR] 공통 헬퍼: 노드의 fills에 이미지 적용 (3곳 중복 제거)
function applyImageFillToNode(node, image) {
const currentFills = node.fills;
if (currentFills === figma.mixed) return false;
const fillsCopy = JSON.parse(JSON.stringify(currentFills || []));
const hasImage = fillsCopy.some(f => f.type === 'IMAGE');
if (hasImage) {
node.fills = fillsCopy.map(f =>
f.type === 'IMAGE'
? { type: 'IMAGE', imageHash: image.hash, scaleMode: f.scaleMode || 'FILL', visible: f.visible !== false, opacity: f.opacity !== undefined ? f.opacity : 1 }
: f
);
} else {
node.fills = [{ type: 'IMAGE', imageHash: image.hash, scaleMode: 'FILL' }];
}
return true;
}
// [REFACTOR] 공통 헬퍼: 노드의 fills에 IMAGE 타입이 있는지 확인
function nodeHasImageFill(node) {
if (!('fills' in node)) return false;
try {
const fills = node.fills;
return fills !== figma.mixed && Array.isArray(fills) && fills.some(f => f.type === 'IMAGE');
} catch (e) { return false; }
}
// 노드 내부의 모든 텍스트 노드 찾기 (재귀)
// 컴포넌트, 인스턴스, 오토레이아웃 모두 지원
function findAllTextNodes(node) {
const textNodes = [];
// 텍스트 노드인 경우
if (node.type === 'TEXT') {
textNodes.push(node);
return textNodes;
}
// 자식이 있는 모든 노드 타입 처리
// FRAME, GROUP, COMPONENT, COMPONENT_SET, INSTANCE, SECTION, PAGE 등
if ('children' in node && node.children) {
for (const child of node.children) {
textNodes.push(...findAllTextNodes(child));
}
}
return textNodes;
}
// 특정 텍스트를 포함하는 텍스트 노드 찾기
function findTextNodeByContent(node, searchText) {
const allTextNodes = findAllTextNodes(node);
return allTextNodes.filter(textNode =>
textNode.characters.includes(searchText)
);
}
// 인스턴스 내 텍스트 변경을 위한 헬퍼 함수
// 폰트 캐시: 이미 로드한 폰트는 재사용
var _loadedFonts = new Set();
async function loadFontCached(font) {
const key = font.family + '::' + font.style;
if (_loadedFonts.has(key)) return;
await figma.loadFontAsync(font);
_loadedFonts.add(key);
}
async function changeTextInNode(textNode, newText) {
try {
// Mixed fonts 처리
if (textNode.fontName === figma.mixed) {
const len = textNode.characters.length;
for (let i = 0; i < len; i++) {
await loadFontCached(textNode.getRangeFontName(i, i + 1));
}
} else {
await loadFontCached(textNode.fontName);
}
textNode.characters = newText;
return true;
} catch (e) {
console.error('Font load error:', e);
return false;
}
}
// 텍스트 부분 교체를 위한 헬퍼 함수
async function replaceTextInNode(textNode, searchText, newText) {
try {
// Mixed fonts 처리
if (textNode.fontName === figma.mixed) {
const len = textNode.characters.length;
for (let i = 0; i < len; i++) {
await loadFontCached(textNode.getRangeFontName(i, i + 1));
}
} else {
await loadFontCached(textNode.fontName);
}
textNode.characters = textNode.characters.replace(searchText, newText);
return true;
} catch (e) {
console.error('Font load error:', e);
return false;
}
}
// 선택된 레이어 불러오기 (네이밍용)
function loadSelectedLayers() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: 'naming-status',
status: 'error',
message: '먼저 레이어를 선택해주세요.'
});
return;
}
// 선택된 레이어와 하위 레이어 수집
const layers = [];
function collectLayers(node, depth = 0) {
// 최대 깊이 제한 (너무 깊은 중첩 방지)
if (depth > 10) return;
layers.push({
id: node.id,
name: node.name,
type: getShortType(node.type)
});
// 하위 레이어도 수집 (옵션)
if ('children' in node && node.children && depth === 0) {
// 첫 번째 레벨의 자식만 수집
for (const child of node.children) {
layers.push({
id: child.id,
name: child.name,
type: getShortType(child.type)
});
}
}
}
for (const node of selection) {
collectLayers(node);
}
figma.ui.postMessage({
type: 'layers-loaded',
layers: layers
});
}
// 레이어 타입 축약
function getShortType(type) {
const typeMap = {
'FRAME': 'Frame',
'GROUP': 'Group',
'TEXT': 'Text',
'RECTANGLE': 'Rect',
'ELLIPSE': 'Ellipse',
'VECTOR': 'Vector',
'COMPONENT': 'Comp',
'INSTANCE': 'Inst',
'COMPONENT_SET': 'Set',
'LINE': 'Line',
'POLYGON': 'Poly',
'STAR': 'Star',
'BOOLEAN_OPERATION': 'Bool',
'SLICE': 'Slice',
'SECTION': 'Sect'
};
return typeMap[type] || type;
}
// 레이어 이름 변경
function renameLayers(changes) {
let renamed = 0;
for (const change of changes) {
const node = figma.getNodeById(change.id);
if (node) {
node.name = change.name;
renamed++;
}
}
figma.ui.postMessage({
type: 'naming-status',
status: 'success',
message: `${renamed}개의 레이어 이름을 변경했습니다.`
});
}
// 선택된 레이어 이름 변경 (Selected Change)
function renameSelectedLayers(namingType) {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: 'rename-status',
status: 'error',
message: '먼저 레이어를 선택해주세요.'
});
return;
}
let renamed = 0;
function renameRecursive(node) {
// Component, Instance는 변경하지 않음
if (node.type === 'COMPONENT' || node.type === 'INSTANCE' || node.type === 'COMPONENT_SET') {
return;
}
node.name = namingType;
renamed++;
// 자식 노드도 재귀적으로 처리
if ('children' in node && node.children) {
for (const child of node.children) {
renameRecursive(child);
}
}
}
for (const node of selection) {
renameRecursive(node);
}
figma.ui.postMessage({
type: 'rename-status',
status: 'success',
message: `${renamed}개의 레이어 이름을 "${namingType}"으로 변경했습니다.`
});
}
// 자동 네이밍 (Auto Rename) - Naming Guide 규칙 적용
function autoRenameAllLayers() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: 'rename-status',
status: 'error',
message: '먼저 레이어를 선택해주세요.'
});
return;
}
let renamed = 0;
function getAutoName(node, parentIsAutoLayout = false) {
// Component, Instance는 변경하지 않음
if (node.type === 'COMPONENT' || node.type === 'INSTANCE' || node.type === 'COMPONENT_SET') {
return null;
}
// TEXT -> "Text"
if (node.type === 'TEXT') {
return 'Text';
}
// [REFACTOR] 공통 헬퍼 사용
if (nodeHasImageFill(node)) return 'Image';
// FRAME/GROUP 처리
if (node.type === 'FRAME' || node.type === 'GROUP') {
const isAutoLayout = 'layoutMode' in node && node.layoutMode !== 'NONE';
if (isAutoLayout) {
return 'Section';
} else if (parentIsAutoLayout) {
// FRAME/GROUP Inside Auto Layout -> "Item"
return 'Item';
} else {
// Frame/Group (Not Auto Layout) -> "Content"
return 'Content';
}
}
// 기타 도형들
if (node.type === 'RECTANGLE' || node.type === 'ELLIPSE' ||
node.type === 'POLYGON' || node.type === 'STAR' ||
node.type === 'LINE' || node.type === 'VECTOR') {
return nodeHasImageFill(node) ? 'Image' : 'Item';
}
return null;
}
function renameRecursive(node, parentIsAutoLayout = false) {
const newName = getAutoName(node, parentIsAutoLayout);
if (newName) {
node.name = newName;
renamed++;
}
// 현재 노드가 Auto Layout인지 확인
const isAutoLayout = 'layoutMode' in node && node.layoutMode !== 'NONE';
// 자식 노드 처리
if ('children' in node && node.children) {
for (const child of node.children) {
// Component/Instance 내부는 처리하지 않음
if (node.type !== 'COMPONENT' && node.type !== 'INSTANCE' && node.type !== 'COMPONENT_SET') {
renameRecursive(child, isAutoLayout);
}
}
}
}
for (const node of selection) {
renameRecursive(node, false);
}
figma.ui.postMessage({
type: 'rename-status',
status: 'success',
message: `${renamed}개의 레이어를 자동으로 네이밍했습니다.`
});
}
// 직접 텍스트 변경 함수
async function directTextChange(newText) {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: 'status',
status: 'error',
message: '먼저 레이어를 선택해주세요.'
});
return;
}
let changed = 0;
for (const node of selection) {
const textNodes = findAllTextNodes(node);
for (const textNode of textNodes) {
const success = await changeTextInNode(textNode, newText);
if (success) changed++;
}
}
if (changed === 0) {
figma.ui.postMessage({
type: 'status',
status: 'error',
message: '선택된 영역에 텍스트가 없습니다.'
});
return;
}
figma.ui.postMessage({
type: 'status',
status: 'success',
message: `${changed}개의 텍스트를 변경했습니다.`
});
}
// 맞춤법 검사 함수
async function spellCheck() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({
type: 'status',
status: 'error',
message: '먼저 레이어를 선택해주세요.'
});
return;
}