-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprototypingTool.js
More file actions
7138 lines (6192 loc) · 283 KB
/
prototypingTool.js
File metadata and controls
7138 lines (6192 loc) · 283 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
class PrototypingTool {
constructor() {
this.checkMobileAccess();
this.elements = [];
this.selectedElement = null;
this.selectedElements = []; // 다중 선택을 위한 배열
this.draggedElement = null;
this.resizingElement = null;
this.resizeHandle = null;
this.offset = { x: 0, y: 0 };
this.gridSize = 0;
this.history = [];
this.currentHistoryIndex = -1;
this.maxZIndex = 1;
this.clipboard = null;
this.isTextPlacementMode = false; // 텍스트 배치 모드 플래그
this.textPlacementClickHandler = null;
this.textPlacementEscHandler = null;
this.textPlacementOutsideClickHandler = null;
this.panelDefaultSize = {
width: 200,
height: 150,
};
this.snapThreshold = 5;
this.snapGuides = [];
this.zoomAnimationId = null;
// 무한 캔버스 관련 설정
this.scale = 1; // 줌 레벨
this.isPanning = false; // 패닝 중인지 여부
this.lastPanPosition = { x: 0, y: 0 }; // 마지막 패닝 위치
this.canvasOffset = { x: 100, y: 100 }; // 캔버스 오프셋
this.lastMousePosition = null;
this.autoScrollState = {
isScrolling: false,
scrollIntervalId: null,
direction: { x: 0, y: 0 },
speed: { x: 0, y: 0 },
};
// 줌 초기화 플래그
this.zoomInitialized = false;
// 테이블 기본 설정
this.tableDefaults = {
rows: 3,
cols: 3,
cellPadding: 8,
borderColor: "#dddddd",
headerBgColor: "#f5f5f5",
cellBgColor: "#ffffff",
textColor: "#000000",
fontSize: 14,
headerFontWeight: "bold",
cellFontWeight: "normal",
};
// 아이콘 경로 매핑 (HTML의 data-icon 값과 img src 경로 매핑)
this.iconPaths = {
close: "./src/images/icon-asset-x.svg",
"arrow-up": "./src/images/icon-asset-arrow.svg",
"arrow-down": "./src/images/icon-asset-arrow.svg",
plus: "./src/images/icon-asset-plus.svg",
hamburger: "./src/images/icon-asset-hamburger.svg",
home: "./src/images/icon-asset-home.svg",
search: "./src/images/icon-asset-search.svg",
user: "./src/images/icon-asset-person.svg",
setting: "./src/images/icon-asset-setting.svg",
link: "./src/images/icon-asset-link.svg",
speaker: "./src/images/icon-asset-speaker.svg",
share: "./src/images/icon-asset-share.svg",
"anglebracket-open": "./src/images/icon-asset-anlgebracket.svg",
"anglebracket-close": "./src/images/icon-asset-anlgebracket.svg",
writing: "./src/images/icon-asset-writing.svg",
image: "./src/images/icon-asset-Image.svg",
download: "./src/images/icon-asset-download.svg",
upload: "./src/images/icon-asset-upload.svg",
heart: "./src/images/icon-asset-heart.svg",
"heart-fill": "./src/images/icon-asset-heart-fill.svg",
check: "./src/images/icon-asset-check.svg",
"check-fill": "./src/images/icon-asset-check-fill.svg",
"square-check": "./src/images/icon-asset-square-check.svg",
"square-check-fill": "./src/images/icon-asset-square-check-fill.svg",
calendar: "./src/images/icon-asset-calendar.svg",
};
this.iconDefaultSize = 26; // 기본 크기
this.iconColors = [
"#000000", // 검정
"#FF0000", // 빨강
"#00FF00", // 초록
"#0000FF", // 파랑
"#FFA500", // 주황
];
this.stickyColors = [
"#fff740", // 노랑
"#ff7eb9", // 핑크
"#7afcff", // 하늘
"#98ff98", // 연두
"#ffb347", // 주황
];
this.buttonColors = ["#2E6FF2", "#fff", "#D9DBE0"];
// 페이지
this.pages = new Map(); // 페이지 저장소
this.currentPageId = null; // 현재 페이지 ID
// 줌과 패닝
this.scale = 1; // 줌 레벨
this.isPanning = false; // 패닝 중인지 여부
this.lastPanPosition = { x: 0, y: 0 }; // 마지막 패닝 위치
this.canvasOffset = { x: 0, y: 0 }; // 캔버스 오프셋
// 디바이스 프리셋
this.devicePresets = {
desktop: { width: 1920, height: 1080 },
laptop: { width: 1366, height: 768 },
iphone12: { width: 390, height: 844 },
galaxy: { width: 412, height: 915 },
ipad: { width: 820, height: 1180 },
custom: { width: null, height: null },
};
this.currentDevice = "desktop";
this.snapThreshold = 9; // 스냅이 작동할 거리 (픽셀)
this.snapEnabled = true; // 스냅 기능 활성화 여부
this.loremText =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
this.initializeEvents();
this.saveHistory();
// 툴바 드롭다운
this.initializeDropdowns();
// 헤더 버튼
this.initializeHeaderButtons();
this.loadFromLocalStorage();
// 초기화 후에 호출
this.initializeZoomAndPan();
this.initializeCanvasControls();
document.addEventListener("mousemove", (e) => {
this.lastMousePosition = { x: e.clientX, y: e.clientY };
});
}
// 헤더 버튼 초기화 메서드
initializeHeaderButtons() {
// JSON 파일 불러오기 버튼만 별도 처리 (드롭다운이 없음)
const jsonButton = document.querySelector(".json-button");
jsonButton.addEventListener("click", () => this.load());
}
// 저장 옵션 닫기 메서드
closeSaveOptions() {
const saveButton = document.querySelector(".save-button");
const saveOptions = document.querySelector(".save-options");
saveButton.classList.remove("active");
saveOptions.style.display = "none";
}
// 로컬 스토리지 저장 메서드
saveAsLocal() {
try {
// 현재 페이지 상태 저장
if (this.currentPageId) {
const currentPage = this.pages.get(this.currentPageId);
if (currentPage) {
currentPage.elements = this.elements;
currentPage.device = this.currentDevice;
currentPage.gridSize = this.gridSize;
}
}
const data = {
pages: Array.from(this.pages.entries()).map(([pageId, page]) => ({
id: pageId,
name: page.name,
elements: page.elements,
device: page.device,
gridSize: page.gridSize,
})),
currentPageId: this.currentPageId,
maxZIndex: this.maxZIndex,
};
localStorage.setItem("canvasData", JSON.stringify(data));
// 성공 알림
this.showNotification("저장 완료", "로컬 스토리지에 저장되었습니다.");
} catch (error) {
console.error("Error saving to localStorage:", error);
// 오류 알림
this.showNotification("저장 실패", "용량이 너무 큰 경우 JSON 다운로드를 이용해주세요.", "error");
}
}
loadFromLocalStorage() {
try {
const savedData = localStorage.getItem("canvasData");
if (savedData) {
const data = JSON.parse(savedData);
// Reconstruct the pages Map
this.pages = new Map(
data.pages.map((page) => [
page.id,
{
id: page.id,
name: page.name,
elements: page.elements,
device: page.device,
gridSize: page.gridSize,
},
])
);
// Set current page ID
this.currentPageId = data.currentPageId;
// Set maxZIndex
this.maxZIndex = data.maxZIndex || 1;
// Load the current page's elements and settings
if (this.currentPageId && this.pages.has(this.currentPageId)) {
const currentPage = this.pages.get(this.currentPageId);
this.elements = currentPage.elements || [];
this.currentDevice = currentPage.device;
this.setGridSize(currentPage.gridSize || 0);
}
// Render the canvas with loaded elements
this.renderCanvas();
this.updatePageList();
// Save initial state to history
this.saveHistory();
} else {
// If no saved data exists, create the initial page
this.createPage("Home");
// 초기 데스크톱 프레임 생성
this.setCanvasSize("desktop");
}
} catch (error) {
console.error("Error loading from localStorage:", error);
// If there's an error, create a new initial page
this.createPage("Home");
// 초기 데스크톱 프레임 생성
this.setCanvasSize("desktop");
}
}
// 알림 표시 메서드
showNotification(title, message, type = "success") {
const notification = document.createElement("div");
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 16px 20px;
background: ${type === "success" ? "#4CAF50" : "#F44336"};
color: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
z-index: 10000;
min-width: 300px;
font-size: 14px;
`;
notification.innerHTML = `
<div style="font-weight: bold; margin-bottom: 4px;">${title}</div>
<div>${message}</div>
`;
document.body.appendChild(notification);
// 3초 후 알림 제거
setTimeout(() => {
notification.style.opacity = "0";
notification.style.transition = "opacity 0.3s ease";
setTimeout(() => notification.remove(), 300);
}, 3000);
}
initializeDropdowns() {
// 툴바와 헤더의 드롭다운을 가진 버튼들 선택
const dropdownButtons = document.querySelectorAll(".toolbar .dropdown-container button, .header .dropdown-container button");
// 헤더와 툴바 드롭다운에 구분 클래스 추가
document.querySelectorAll(".header .dropdown-menu").forEach((dropdown) => {
dropdown.classList.add("header-dropdown");
});
document.querySelectorAll(".toolbar .dropdown-menu").forEach((dropdown) => {
dropdown.classList.add("toolbar-dropdown");
});
// 각 버튼에 클릭 이벤트 추가
dropdownButtons.forEach((button) => {
button.addEventListener("click", (e) => {
e.stopPropagation();
this.handleDropdownToggle(e);
});
});
// 드롭다운 외부 클릭 시 닫기
document.addEventListener("click", () => {
this.closeAllDropdowns();
});
// ESC 키 누를 때 모든 드롭다운 닫기
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
this.closeAllDropdowns();
}
});
// 전역 툴팁 관리자 초기화
this.initTooltipManager();
}
handleDropdownToggle(e) {
const button = e.target.closest('[aria-haspopup="true"]');
if (!button) {
return;
}
const dropdown = button.nextElementSibling;
if (!dropdown || !dropdown.classList.contains("dropdown-menu")) {
return;
}
// 현재 드롭다운이 열려있는지 확인
const isCurrentDropdownOpen = dropdown.classList.contains("show");
// 다른 모든 드롭다운 즉시 닫기
this.closeAllDropdowns();
// 현재 드롭다운이 닫혀있었다면 즉시 열기
if (!isCurrentDropdownOpen) {
// 지연 없이 즉시 열기
this.openDropdown(dropdown, button);
}
}
openDropdown(dropdown, button) {
// show 클래스와 상태를 먼저 설정
dropdown.classList.add("show");
button.setAttribute("aria-expanded", "true");
button.classList.add("active");
// 즉시 위치 설정 (애니메이션 없이)
this.positionDropdown(button, dropdown);
// 드롭다운 아이템 클릭 이벤트 바인딩
dropdown.querySelectorAll(".dropdown-item").forEach((item) => {
item.addEventListener("click", (e) => {
e.stopPropagation();
this.handleDropdownItemClick(item, dropdown);
});
});
}
moveDropdownToBody(dropdown, button) {
const isHeaderDropdown = button.closest(".header") !== null;
if (isHeaderDropdown && dropdown.parentElement !== document.body) {
// 원래 위치 정보 저장
dropdown._originalParent = dropdown.parentElement;
dropdown._originalNextSibling = dropdown.nextElementSibling;
// 현재 위치를 저장 (이후 위치 계산 참조용)
const originalRect = dropdown.getBoundingClientRect();
// body로 이동하기 전에 CSS transition 비활성화
const originalTransition = dropdown.style.transition;
dropdown.style.transition = "none";
// body로 이동
document.body.appendChild(dropdown);
// 필요한 스타일 적용
dropdown.style.position = "fixed";
dropdown.style.pointerEvents = "auto";
dropdown.style.isolation = "isolate";
// transition은 나중에 복원될 예정 (positionDropdown에서)
}
}
restoreDropdownPosition(dropdown) {
if (dropdown._originalParent && dropdown.parentElement === document.body) {
// 원래 위치로 되돌림
if (dropdown._originalNextSibling) {
dropdown._originalParent.insertBefore(dropdown, dropdown._originalNextSibling);
} else {
dropdown._originalParent.appendChild(dropdown);
}
// 참조 정리
delete dropdown._originalParent;
delete dropdown._originalNextSibling;
// 추가했던 스타일 제거
dropdown.style.position = "";
dropdown.style.pointerEvents = "";
dropdown.style.isolation = "";
}
}
initTooltipManager() {
// 전역 툴팁 요소 생성
this.globalTooltip = document.createElement("div");
this.globalTooltip.className = "global-tooltip";
this.globalTooltip.style.cssText = `
position: fixed;
background: #202124;
color: white;
padding: 6px 8px;
border-radius: 4px;
font-size: 12px;
white-space: nowrap;
opacity: 0;
visibility: hidden;
transition: all 0.2s ease;
pointer-events: none;
z-index: 999999;
transform: translateX(-50%);
`;
// 툴팁 화살표 추가
const arrow = document.createElement("div");
arrow.style.cssText = `
content: "";
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
border: 4px solid transparent;
border-bottom-color: #202124;
`;
this.globalTooltip.appendChild(arrow);
document.body.appendChild(this.globalTooltip);
// 툴바 버튼들에 이벤트 바인딩
this.bindToolbarEvents();
}
bindToolbarEvents() {
// 툴바의 모든 버튼에 툴팁 이벤트 바인딩
document.querySelectorAll(".toolbar .tool-btn").forEach((button) => {
const tooltipText = button.getAttribute("aria-label") || button.getAttribute("title");
button.addEventListener("mouseenter", (e) => {
this.showTooltip(e.target, tooltipText);
});
button.addEventListener("mouseleave", () => {
this.hideTooltip();
});
});
// 헤더의 버튼들에도 툴팁 이벤트 바인딩
document.querySelectorAll(".header .header-btn").forEach((button) => {
const tooltipText = button.getAttribute("aria-label") || button.getAttribute("title");
button.addEventListener("mouseenter", (e) => {
this.showTooltip(e.target, tooltipText);
});
button.addEventListener("mouseleave", () => {
this.hideTooltip();
});
});
}
showTooltip(element, text) {
if (!text) return;
// 숨겨진 상태인지 확인
const isHidden = !this.globalTooltip.classList.contains("show");
// 숨겨진 상태라면 transition 없이 즉시 위치 이동
if (isHidden) {
this.globalTooltip.style.transition = "none";
}
// 텍스트 설정 (첫 번째 자식이 화살표이므로 직접 textContent 설정)
this.globalTooltip.childNodes[1] ? (this.globalTooltip.childNodes[1].textContent = text) : this.globalTooltip.appendChild(document.createTextNode(text));
// 버튼 위치 계산
const rect = element.getBoundingClientRect();
// 툴팁을 버튼 중앙 아래에 배치
const left = rect.left + rect.width / 2;
const top = rect.bottom + 8;
this.globalTooltip.style.left = left + "px";
this.globalTooltip.style.top = top + "px";
// 숨겨진 상태에서만 transition 복원 및 표시
if (isHidden) {
// 브라우저가 위치 변경을 적용할 수 있도록 강제 리플로우
void this.globalTooltip.offsetHeight;
// transition 복원 후 표시
this.globalTooltip.style.transition = "all 0.2s ease";
this.globalTooltip.classList.add("show");
this.globalTooltip.style.opacity = "1";
this.globalTooltip.style.visibility = "visible";
}
}
hideTooltip() {
this.globalTooltip.classList.remove("show");
this.globalTooltip.style.opacity = "0";
this.globalTooltip.style.visibility = "hidden";
this.globalTooltip.style.transition = "none";
}
handleDropdownItemClick(dropdownItem, dropdown) {
// 드롭다운 닫기
dropdown.classList.remove("show");
// 버튼 상태 초기화
const button = dropdown.previousElementSibling;
if (button) {
button.setAttribute("aria-expanded", "false");
button.classList.remove("active");
}
// 헤더의 저장하기 드롭다운 아이템 처리
if (dropdown.classList.contains("save-options")) {
const onclick = dropdownItem.getAttribute("onclick");
if (onclick) {
// onclick 속성의 함수 호출
if (onclick.includes("saveAsLocal()")) {
this.saveAsLocal();
} else if (onclick.includes("save()")) {
this.save();
} else if (onclick.includes("exportAsImage()")) {
this.exportAsImage();
}
}
return;
}
// 헤더의 단축키 안내 드롭다운 처리 (클릭 시 아무것도 하지 않음, 단순히 드롭다운만 닫힘)
if (dropdown.classList.contains("help-options")) {
return;
}
// 아이템 타입에 따른 처리
const itemType =
dropdownItem.dataset.shape || dropdownItem.dataset.button || dropdownItem.dataset.icon || dropdownItem.dataset.input || dropdownItem.dataset.alert || dropdownItem.dataset.memo;
if (itemType) {
// 도형 추가
if (dropdownItem.dataset.shape) {
this.addElement("shape", itemType);
}
// 버튼 추가
else if (dropdownItem.dataset.button) {
this.addElement("button", itemType);
}
// 아이콘 추가
else if (dropdownItem.dataset.icon) {
this.addElement("icon", itemType);
}
// 입력 추가
else if (dropdownItem.dataset.input) {
this.addElement("input", itemType);
}
// 알림 추가
else if (dropdownItem.dataset.alert) {
this.addElement("alert", itemType);
}
// 메모 추가
else if (dropdownItem.dataset.memo) {
this.addElement("sticky-" + itemType);
}
}
}
addIconElement(iconType) {
this.maxZIndex++;
const position = this.findAvailablePosition(40, 40);
const element = {
id: Date.now(),
type: "icon",
x: position.x,
y: position.y,
width: 40,
height: 40,
name: this.generateElementName("icon"),
content: iconType,
iconType: iconType,
zIndex: this.maxZIndex,
opacity: 1,
iconSize: 40,
};
this.elements.push(element);
this.renderElement(element);
this.selectElement(element);
this.saveHistory();
// 새로 추가된 요소를 포함하여 뷰 최적화
this.optimizeViewForNewElement(element);
}
addButtonElement(buttonType) {
this.maxZIndex++;
const position = this.findAvailablePosition(120, 40);
// 버튼 타입에 따른 기본 배경색 설정
let defaultBackgroundColor;
switch (buttonType) {
case "activate":
defaultBackgroundColor = "#2E6FF2";
break;
case "normal":
defaultBackgroundColor = "#ffffff";
break;
case "hover":
case "deactivate":
defaultBackgroundColor = "#D9DBE0";
break;
default:
defaultBackgroundColor = "#2E6FF2";
}
const element = {
id: Date.now(),
type: "button",
x: position.x,
y: position.y,
width: 120,
height: 40,
name: this.generateElementName("button"),
content: "Button",
buttonType: buttonType,
zIndex: this.maxZIndex,
opacity: 1,
fontSize: 14,
backgroundColor: defaultBackgroundColor,
textColor: buttonType === "normal" ? "#000000" : buttonType === "hover" ? "#121314" : "#ffffff", // buttonType에 따른 기본 텍스트 색상
fontWeight: "normal",
};
this.elements.push(element);
this.renderElement(element);
this.selectElement(element);
this.saveHistory();
// 새로 추가된 요소를 포함하여 뷰 최적화
this.optimizeViewForNewElement(element);
}
addShapeElement(shapeType) {
this.maxZIndex++;
const height = shapeType === "line" ? 1 : shapeType === "arrow" ? 16 : 200;
const position = this.findAvailablePosition(200, height);
const element = {
id: Date.now(),
type: "shape",
x: position.x,
y: position.y,
width: 200,
height: height,
name: this.generateElementName("shape"),
content: "",
shapeType: shapeType,
zIndex: this.maxZIndex,
opacity: 1,
fill: "#D9D9D9",
borderWidth: shapeType === "line" || shapeType === "arrow" ? 1 : undefined,
borderColor: shapeType === "line" || shapeType === "arrow" ? "#000000" : undefined,
};
this.elements.push(element);
this.renderElement(element);
this.selectElement(element);
this.saveHistory();
// 새로 추가된 요소를 포함하여 뷰 최적화
this.optimizeViewForNewElement(element);
}
addInputElement(inputType) {
this.maxZIndex++;
const position = this.findAvailablePosition(322, 40);
const element = {
id: Date.now(),
type: "input",
x: position.x,
y: position.y,
width: 322,
height: 40,
name: this.generateElementName("input"),
content: "Input",
label: "Label",
buttonText: "입력",
errorMessage: "※ 유효하지 않은 정보입니다.",
inputType: inputType,
zIndex: this.maxZIndex,
opacity: 1,
fontSize: 14,
textColor: "#000000", // 입력 필드 기본 텍스트 색상
fontWeight: "normal",
};
this.elements.push(element);
this.renderElement(element);
this.selectElement(element);
this.saveHistory();
// 새로 추가된 요소를 포함하여 뷰 최적화
this.optimizeViewForNewElement(element);
}
addAlertElement(alertType) {
this.maxZIndex++;
const position = this.findAvailablePosition(338, 120);
const element = {
id: Date.now(),
type: "alert",
x: position.x,
y: position.y,
width: 338,
height: 120,
name: this.generateElementName("alert"),
content: "Alert message",
primaryButtonText: alertType === "warning" ? "나가기" : "확인",
secondaryButtonText: alertType === "warning" ? "취소" : "",
alertType: alertType,
zIndex: this.maxZIndex,
opacity: 1,
fontSize: 14,
textColor: "#121314", // 알림 기본 텍스트 색상
fontWeight: "normal",
};
this.elements.push(element);
this.renderElement(element);
this.selectElement(element);
this.saveHistory();
// 새로 추가된 요소를 포함하여 뷰 최적화
this.optimizeViewForNewElement(element);
}
addStickyElement(stickyType) {
this.maxZIndex++;
let stickyColor;
switch (stickyType) {
case "yellow":
stickyColor = "#fff740";
break;
case "pink":
stickyColor = "#ff7eb9";
break;
case "blue":
stickyColor = "#7afcff";
break;
case "green":
stickyColor = "#98ff98";
break;
case "orange":
stickyColor = "#ffb347";
break;
default:
stickyColor = "#fff740";
}
const position = this.findAvailablePosition(200, 200);
const element = {
id: Date.now(),
type: "sticky",
x: position.x,
y: position.y,
width: 200,
height: 200,
name: this.generateElementName("sticky"),
content: "Double click to edit memo",
stickyColor: stickyColor,
zIndex: this.maxZIndex,
opacity: 1,
fontSize: 16,
textColor: "#000000", // 메모 기본 텍스트 색상
fontWeight: "normal",
};
this.elements.push(element);
this.renderElement(element);
this.selectElement(element);
this.saveHistory();
// 새로 추가된 요소를 포함하여 뷰 최적화
this.optimizeViewForNewElement(element);
}
closeAllDropdowns() {
document.querySelectorAll(".dropdown-menu").forEach((dropdown) => {
if (dropdown.classList.contains("show")) {
// 부드러운 닫기 애니메이션을 위해 opacity만 먼저 변경
dropdown.style.opacity = "0";
// 짧은 애니메이션 후 완전히 제거
setTimeout(() => {
dropdown.classList.remove("show");
dropdown.style.zIndex = "";
dropdown.style.visibility = "";
dropdown.style.display = "";
dropdown.style.opacity = "";
dropdown.style.transition = "";
// 헤더 드롭다운이었다면 원래 위치로 복원
this.restoreDropdownPosition(dropdown);
}, 150); // 150ms 애니메이션
} else {
// 이미 닫혀있는 경우 즉시 정리
dropdown.classList.remove("show");
dropdown.style.zIndex = "";
dropdown.style.visibility = "";
dropdown.style.display = "";
dropdown.style.opacity = "";
dropdown.style.transition = "";
this.restoreDropdownPosition(dropdown);
}
});
// 모든 버튼 상태 즉시 초기화
document.querySelectorAll(".toolbar button, .header button").forEach((button) => {
button.setAttribute("aria-expanded", "false");
button.classList.remove("active");
});
}
positionDropdown(button, dropdown) {
const buttonRect = button.getBoundingClientRect();
const isHeaderButton = button.closest(".header") !== null;
// 헤더 드롭다운의 경우 body로 이동
if (isHeaderButton) {
this.moveDropdownToBody(dropdown, button);
}
// CSS transition을 비활성화하여 즉시 위치 변경
const originalTransition = dropdown.style.transition;
dropdown.style.transition = "none";
// 즉시 위치와 표시 상태 설정
dropdown.style.position = "fixed";
dropdown.style.display = "grid";
dropdown.style.visibility = "visible";
dropdown.style.opacity = "1";
// z-index 설정
if (isHeaderButton) {
dropdown.style.zIndex = "999999";
} else {
dropdown.style.zIndex = "10000";
}
// 위치 계산 및 즉시 적용
if (isHeaderButton) {
// 헤더 버튼의 경우: 버튼 아래에서 4px 떨어지고 오른쪽 정렬
// 먼저 임시로 화면 밖에 두고 크기 측정
dropdown.style.left = "-9999px";
dropdown.style.top = "-9999px";
// 브라우저가 크기를 계산할 수 있도록 강제 리플로우
const dropdownRect = dropdown.getBoundingClientRect();
// 실제 위치 계산 및 적용
const finalTop = buttonRect.bottom + 4;
const finalLeft = buttonRect.right - dropdownRect.width;
dropdown.style.top = `${finalTop}px`;
dropdown.style.left = `${finalLeft}px`;
} else {
// 툴바 버튼의 경우: 버튼 바로 아래 중앙 정렬
// 먼저 임시로 화면 밖에 두고 크기 측정
dropdown.style.left = "-9999px";
dropdown.style.top = "-9999px";
// 브라우저가 크기를 계산할 수 있도록 강제 리플로우
const dropdownRect = dropdown.getBoundingClientRect();
// 실제 위치 계산
const finalTop = buttonRect.bottom + 1;
const buttonCenterX = buttonRect.left + buttonRect.width / 2;
const dropdownLeft = buttonCenterX - dropdownRect.width / 2;
// 화면 경계 체크
const maxLeft = window.innerWidth - dropdownRect.width - 10;
const minLeft = 10;
const finalLeft = Math.max(minLeft, Math.min(maxLeft, dropdownLeft));
// 실제 위치 적용
dropdown.style.top = `${finalTop}px`;
dropdown.style.left = `${finalLeft}px`;
}
// 위치 설정 후 잠시 뒤에 transition 복원 (부드러운 닫기 애니메이션을 위해)
setTimeout(() => {
dropdown.style.transition = originalTransition;
}, 10);
}
// 모바일 접속 체크 메서드 추가
checkMobileAccess() {
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
const mobileOverlay = document.createElement("div");
mobileOverlay.className = "mobile-overlay";
mobileOverlay.innerHTML = `
<div class="mobile-message">
<h2>Mobile Device Detected</h2>
<p>Sorry, this prototyping tool is currently only supported on desktop environments.</p>
<p>For the best experience, please access from a desktop computer.</p>
<button class="mobile-close-btn">OK</button>
</div>
`;
document.body.appendChild(mobileOverlay);
// 확인 버튼 클릭 시 오버레이 제거
const closeBtn = mobileOverlay.querySelector(".mobile-close-btn");
closeBtn.addEventListener("click", () => {
mobileOverlay.remove();
});
}
}
createPage(pageName) {
const pageId = Date.now();
const page = {
id: pageId,
name: pageName,
elements: [],
device: this.currentDevice,
gridSize: 20, // 새 페이지의 기본 그리드 크기를 20px로 설정
};
this.pages.set(pageId, page);
if (!this.currentPageId) {
this.currentPageId = pageId;
this.gridSize = page.gridSize; // 첫 페이지인 경우에만 현재 그리드 크기 설정
this.setGridSize(page.gridSize); // 캔버스에 그리드 적용
}
this.updatePageList();
return pageId;
}
initializeEvents() {
// 이벤트 위임을 사용하여 컴포넌트 버튼 이벤트 처리
document.querySelector("#shape-options").addEventListener("click", (e) => {
const btn = e.target.closest(".component-btn");
if (btn) this.addElement(btn.dataset.type);
});
document.querySelectorAll("header > div > button").forEach((button) => {
const title = button.getAttribute("title");
if (title) {
button.setAttribute("data-tooltip", title);
}
});
document.querySelectorAll(".toolbar-group > button").forEach((button) => {
const title = button.getAttribute("title");
if (title) {
button.setAttribute("data-tooltip", title);
}
});
// 캔버스 이벤트
const canvas = document.getElementById("canvas");
canvas.addEventListener("click", (e) => {