aicommunicator 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +93 -2
  3. package/bin/aic.js +20427 -0
  4. package/host-ui/host.js +5151 -0
  5. package/host-ui/index.html +483 -0
  6. package/host-ui/lang-en.js +631 -0
  7. package/package.json +30 -4
  8. package/plugin-guide.md +997 -0
  9. package/plugins/plugin-animation/LICENSE +55 -0
  10. package/plugins/plugin-animation/dist/logic.js +2225 -0
  11. package/plugins/plugin-animation/docs/manual.md +217 -0
  12. package/plugins/plugin-animation/manifest.json +31 -0
  13. package/plugins/plugin-animation/ui/icon.svg +6 -0
  14. package/plugins/plugin-animation/ui/index.html +2266 -0
  15. package/plugins/plugin-html-design/LICENSE +55 -0
  16. package/plugins/plugin-html-design/dist/logic.js +972 -0
  17. package/plugins/plugin-html-design/docs/manual.md +100 -0
  18. package/plugins/plugin-html-design/manifest.json +39 -0
  19. package/plugins/plugin-html-design/samples/exhibition-page.json +570 -0
  20. package/plugins/plugin-html-design/ui/icon.svg +5 -0
  21. package/plugins/plugin-html-design/ui/index.html +1241 -0
  22. package/plugins/plugin-html-slides/LICENSE +55 -0
  23. package/plugins/plugin-html-slides/dist/logic.js +1323 -0
  24. package/plugins/plugin-html-slides/docs/manual.md +121 -0
  25. package/plugins/plugin-html-slides/manifest.json +39 -0
  26. package/plugins/plugin-html-slides/samples/first-week-lecture.json +1129 -0
  27. package/plugins/plugin-html-slides/ui/icon.svg +5 -0
  28. package/plugins/plugin-html-slides/ui/index.html +1349 -0
  29. package/plugins/plugin-mindmap/LICENSE +55 -0
  30. package/plugins/plugin-mindmap/dist/logic.js +966 -0
  31. package/plugins/plugin-mindmap/docs/manual.md +145 -0
  32. package/plugins/plugin-mindmap/manifest.json +39 -0
  33. package/plugins/plugin-mindmap/samples/book-club.json +480 -0
  34. package/plugins/plugin-mindmap/ui/icon.svg +5 -0
  35. package/plugins/plugin-mindmap/ui/index.html +1774 -0
  36. package/plugins/plugin-plan/LICENSE +55 -0
  37. package/plugins/plugin-plan/dist/logic.js +1029 -0
  38. package/plugins/plugin-plan/docs/manual.md +261 -0
  39. package/plugins/plugin-plan/manifest.json +51 -0
  40. package/plugins/plugin-plan/samples/kimchi-day.json +1514 -0
  41. package/plugins/plugin-plan/samples/meeting-outline.json +653 -0
  42. package/plugins/plugin-plan/samples/reading-class.json +1577 -0
  43. package/plugins/plugin-plan/ui/icon.svg +7 -0
  44. package/plugins/plugin-plan/ui/index.html +1523 -0
  45. package/plugins/plugin-png/LICENSE +55 -0
  46. package/plugins/plugin-png/dist/logic.js +1758 -0
  47. package/plugins/plugin-png/docs/manual.md +344 -0
  48. package/plugins/plugin-png/manifest.json +35 -0
  49. package/plugins/plugin-png/ui/icon.svg +5 -0
  50. package/plugins/plugin-png/ui/index.html +2885 -0
  51. package/plugins/plugin-process-log/LICENSE +55 -0
  52. package/plugins/plugin-process-log/dist/logic.js +406 -0
  53. package/plugins/plugin-process-log/docs/manual.md +131 -0
  54. package/plugins/plugin-process-log/manifest.json +43 -0
  55. package/plugins/plugin-process-log/samples/design-decisions.json +241 -0
  56. package/plugins/plugin-process-log/ui/icon.svg +7 -0
  57. package/plugins/plugin-process-log/ui/index.html +721 -0
  58. package/plugins/plugin-story/LICENSE +55 -0
  59. package/plugins/plugin-story/dist/logic.js +2201 -0
  60. package/plugins/plugin-story/docs/manual.md +428 -0
  61. package/plugins/plugin-story/manifest.json +49 -0
  62. package/plugins/plugin-story/samples/scene-body.json +758 -0
  63. package/plugins/plugin-story/samples/time-and-groups.json +989 -0
  64. package/plugins/plugin-story/ui/icon.svg +4 -0
  65. package/plugins/plugin-story/ui/index.html +2783 -0
  66. package/plugins/plugin-svg/LICENSE +55 -0
  67. package/plugins/plugin-svg/dist/logic.js +2150 -0
  68. package/plugins/plugin-svg/docs/manual.md +314 -0
  69. package/plugins/plugin-svg/manifest.json +45 -0
  70. package/plugins/plugin-svg/samples/rocket-icon.json +1305 -0
  71. package/plugins/plugin-svg/samples/yard-cat.json +7796 -0
  72. package/plugins/plugin-svg/ui/icon.svg +4 -0
  73. package/plugins/plugin-svg/ui/index.html +2017 -0
  74. package/plugins/plugin-tree/LICENSE +55 -0
  75. package/plugins/plugin-tree/dist/logic.js +505 -0
  76. package/plugins/plugin-tree/docs/manual.md +140 -0
  77. package/plugins/plugin-tree/manifest.json +45 -0
  78. package/plugins/plugin-tree/samples/book-club.json +473 -0
  79. package/plugins/plugin-tree/samples/sort-memos.json +604 -0
  80. package/plugins/plugin-tree/ui/icon.svg +7 -0
  81. package/plugins/plugin-tree/ui/index.html +1305 -0
  82. package/schema/aic_describe.input.json +11 -0
  83. package/schema/aic_describe.output.json +67 -0
  84. package/schema/aic_observe.input.json +14 -0
  85. package/schema/aic_observe.output.json +47 -0
  86. package/schema/aic_send.input.json +15 -0
  87. package/schema/aic_send.output.json +38 -0
  88. package/schema/aic_update.input.json +19 -0
  89. package/schema/aic_update.output.json +39 -0
  90. package/schema/common.json +127 -0
  91. package/template/plugin/LICENSE +55 -0
  92. package/template/plugin/README.md +27 -0
  93. package/template/plugin/docs/manual.md +31 -0
  94. package/template/plugin/logic.js +337 -0
  95. package/template/plugin/manifest.json +27 -0
  96. package/template/plugin/ui/icon.svg +4 -0
  97. package/template/plugin/ui/index.html +269 -0
@@ -0,0 +1,2017 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>SVG Image</title>
7
+ <style>
8
+ :root {
9
+ color-scheme: light dark;
10
+ --bg: #f5f5f2; --panel: #ffffff; --text: #1f2328; --muted: #5f6771; --line: #dcdfe3; --soft: #f0f1f3;
11
+ --accent: #1f6a8c; --accent-text: #ffffff; --del: #a8321f; --add: #1d7a46;
12
+ --check-a: #ffffff; --check-b: #e4e7eb;
13
+ --grid: rgba(31, 106, 140, .62); --grid-text: #17506a; --halo: rgba(255, 255, 255, .9);
14
+ --node-label: #1d7a46; --node-goal: #c25e00; --sel: #1f6a8c; --sel-fill: rgba(31, 106, 140, .12);
15
+ }
16
+ @media (prefers-color-scheme: dark) {
17
+ :root {
18
+ --bg: #191b1e; --panel: #22252a; --text: #e6e8eb; --muted: #a0a8b2; --line: #383d44; --soft: #2b2f35;
19
+ --accent: #7cc0dd; --accent-text: #10222b; --del: #f1a597; --add: #7bd6a0;
20
+ --check-a: #3a3f46; --check-b: #30343a;
21
+ --grid: rgba(124, 192, 221, .7); --grid-text: #bfe3f2; --halo: rgba(17, 19, 22, .88);
22
+ --node-label: #7bd6a0; --node-goal: #ffb066; --sel: #7cc0dd; --sel-fill: rgba(124, 192, 221, .14);
23
+ }
24
+ }
25
+ * { box-sizing: border-box; }
26
+ html, body { height: 100%; }
27
+ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.55 system-ui, "Malgun Gothic", sans-serif; display: flex; flex-direction: column; }
28
+ button { font: inherit; color: inherit; cursor: pointer; }
29
+ button:focus-visible, select:focus-visible, textarea:focus-visible, input:focus-visible, #stage:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
30
+ .btn { white-space: nowrap; background: transparent; border: 1px solid var(--line); border-radius: 5px; padding: 2px 9px; font-size: 13px; }
31
+ .btn:hover { background: var(--soft); }
32
+ .btn[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
33
+ .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
34
+ .btn.small { padding: 0 6px; font-size: 12px; }
35
+ .btn[disabled] { opacity: .5; cursor: default; }
36
+
37
+ /* 위쪽 줄은 아이콘 한 줄이다. 이름은 title 과 aria-label 에 두고, 늘 보일 필요가 없는 것(조각 격자, node 보기, 저장)은 메뉴에 둔다 */
38
+ #bar { flex: none; position: relative; z-index: 5; display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: center; padding: 4px 8px; background: var(--panel); border-bottom: 1px solid var(--line); }
39
+ .group { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
40
+ .cap { color: var(--muted); font-size: 12px; margin-right: 2px; }
41
+ .reason { color: var(--del); font-size: 12px; }
42
+ #bar select { width: auto; font-size: 13px; padding: 2px 4px; }
43
+ #bar .spacer { flex: 1; }
44
+ .btn.icon { width: 28px; height: 28px; padding: 0; display: inline-flex; align-items: center; justify-content: center; font-size: 15px; line-height: 1; }
45
+ .btn.icon svg { width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
46
+ .menuBox { position: relative; display: flex; }
47
+ .menu { position: absolute; z-index: 20; top: calc(100% + 6px); right: 0; width: max-content; min-width: 200px; max-width: calc(100vw - 16px); display: grid; gap: 8px; padding: 10px 12px; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; box-shadow: 0 6px 20px rgba(0, 0, 0, .2); }
48
+ .menu h2 { font-size: 12px; color: var(--muted); margin: 0; font-weight: 600; }
49
+ .menu .group { flex-wrap: nowrap; }
50
+ .menu .swatch { font-size: 13px; color: inherit; white-space: nowrap; }
51
+ .menu .cap { white-space: nowrap; }
52
+ .swatch { display: inline-flex; align-items: center; gap: 3px; font-size: 12px; color: var(--muted); }
53
+ .swatch input[type=color] { width: 30px; height: 22px; padding: 0 1px; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); }
54
+ .swatch input[disabled] { opacity: .45; }
55
+ .zoom { min-width: 3.6em; text-align: center; font-size: 12px; font-variant-numeric: tabular-nums; }
56
+ #gridRange { width: 90px; }
57
+
58
+ /* 그림이 화면을 넓게 쓴다. 오른쪽 칸은 숨긴 채 시작하고 위쪽 줄의 버튼으로 연다 */
59
+ #main { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 8px; }
60
+ #main[data-side="open"] { grid-template-columns: minmax(0, 1fr) 320px; }
61
+ #stageBox { min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
62
+ #stageWrap { position: relative; flex: 1; min-height: 240px; display: flex; flex-direction: column; }
63
+ /* 그림 칸. 그림은 #paper 안에 논리가 준 SVG 를 그대로 넣고, 겹쳐 보기는 화면 픽셀 단위의 다른 svg(#overlay)에 그린다 */
64
+ #stage { position: relative; flex: 1; min-height: 0; overflow: hidden; background: var(--soft); border: 1px solid var(--line); border-radius: 8px; touch-action: none; user-select: none; -webkit-user-select: none; }
65
+ #stage[data-tool="point"] { cursor: crosshair; }
66
+ #stage[data-tool="move"] { cursor: move; }
67
+ #stage[data-tool="pan"], #stage.panning { cursor: grab; }
68
+ #stage.dragging { cursor: grabbing; }
69
+ /* 투명한 곳이 보이게 바둑판 무늬 위에 그린다 */
70
+ #paper { position: absolute; left: 0; top: 0; background-color: var(--check-a); background-image: linear-gradient(45deg, var(--check-b) 25%, transparent 25%, transparent 75%, var(--check-b) 75%), linear-gradient(45deg, var(--check-b) 25%, transparent 25%, transparent 75%, var(--check-b) 75%); background-size: 16px 16px; background-position: 0 0, 8px 8px; box-shadow: 0 0 0 1px var(--line), 0 2px 10px rgba(0, 0, 0, .14); }
71
+ #paper > svg { display: block; width: 100%; height: 100%; overflow: hidden; }
72
+ #overlay { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; overflow: visible; }
73
+ .ov-grid { fill: none; stroke: var(--grid); stroke-width: 1; }
74
+ .ov-piece { font: 10.5px/1 system-ui, sans-serif; fill: var(--grid-text); paint-order: stroke; stroke: var(--halo); stroke-width: 3px; stroke-linejoin: round; }
75
+ .ov-node { fill: none; stroke-width: 2; }
76
+ .ov-node.label { stroke: var(--node-label); }
77
+ .ov-node.goal { stroke: var(--node-goal); stroke-dasharray: 6 4; }
78
+ .ov-node.focus { stroke-width: 4; }
79
+ .ov-name { font: 600 12px/1 system-ui, "Malgun Gothic", sans-serif; paint-order: stroke; stroke: var(--halo); stroke-width: 3px; stroke-linejoin: round; }
80
+ .ov-name.label { fill: var(--node-label); }
81
+ .ov-name.goal { fill: var(--node-goal); }
82
+ .ov-name.sel { fill: var(--sel); }
83
+ .ov-sel { fill: var(--sel-fill); stroke: var(--sel); stroke-width: 2; }
84
+ .ov-sel.area, .ov-rubber { stroke-dasharray: 5 3; }
85
+ .ov-rubber { fill: var(--sel-fill); stroke: var(--sel); stroke-width: 1.5; }
86
+ .ov-mark { fill: none; stroke: var(--sel); stroke-width: 2; }
87
+ .note { color: var(--muted); font-size: 12px; margin: 6px 0 0; }
88
+ /* 고른 것을 AI 에게 보내는 칸. 고른 것이 있을 때만 그림 칸 위에 떠서 보인다. 그림 칸의 크기를 바꾸지 않으려는 것이다
89
+ (크기가 바뀌면 그림이 다시 맞춰져, 같은 곳을 다시 눌러 안쪽으로 들어갈 때 다른 곳이 눌린다). 눈에 먼저 들어오게 위쪽 줄
90
+ 바로 아래(그림 칸의 위)에 뜨고, 고른 것이 위쪽에 있어 가려지면 아래에 뜬다(data-at, rawdev 2026-11-25 "가능하면 상단에 둬").
91
+ 부품을 끌어 옮기거나 영역을 끌어 고르는 동안은 숨긴다(away). 고르고 아직 보내지 않았으면 테두리로 알린다 */
92
+ #talkBar { position: absolute; z-index: 3; left: 10px; right: 10px; top: 10px; max-width: 760px; margin: 0 auto; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; box-shadow: 0 4px 16px rgba(0, 0, 0, .2); }
93
+ #talkBar[data-at="bottom"] { top: auto; bottom: 10px; }
94
+ #talkBar.away { visibility: hidden; }
95
+ #talkBar.unsent { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), 0 4px 16px rgba(0, 0, 0, .2); }
96
+ #talkBar .state { margin: 0 0 6px; font-size: 13px; overflow-wrap: anywhere; }
97
+ #talkBar .state b { font-weight: 600; }
98
+ #talkBar .state .warn { color: var(--node-goal); font-weight: 600; }
99
+ #talkBar .state .done { color: var(--add); font-weight: 600; }
100
+ #talkBar .line { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
101
+ #talkBar .line select { width: auto; flex: none; }
102
+ #talkBar .line input[type=text] { flex: 1; min-width: 160px; padding: 5px 8px; }
103
+ #talkBar .line .btn { flex: none; padding: 5px 14px; font-size: 14px; }
104
+
105
+ #side { min-height: 0; overflow: auto; }
106
+ aside section { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; margin-bottom: 12px; }
107
+ aside h2, #startView h2 { font-size: 13px; color: var(--muted); margin: 0 0 6px; font-weight: 600; }
108
+ aside p { margin: 4px 0; }
109
+ .kv { display: grid; grid-template-columns: auto 1fr; gap: 2px 8px; font-size: 13px; margin: 0; }
110
+ .kv dt { color: var(--muted); }
111
+ .kv dd { margin: 0; overflow-wrap: anywhere; }
112
+ .crumbs { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; font-size: 12px; margin: 6px 0 2px; }
113
+ .chip { border: 1px solid var(--line); background: var(--soft); border-radius: 999px; padding: 0 8px; font-size: 12px; }
114
+ .chip[aria-current="true"] { border-color: var(--accent); color: var(--accent); font-weight: 600; }
115
+ .form { display: grid; gap: 6px; margin-top: 6px; }
116
+ .form label > span { display: block; color: var(--muted); font-size: 12px; }
117
+ .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
118
+ textarea, input[type=text], input[type=number], select { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--line); border-radius: 5px; padding: 3px 6px; width: 100%; }
119
+ textarea { resize: vertical; min-height: 3.2em; }
120
+ /* 부품 목록은 보이는 줄만 그린다. 부품이 2,000개여도 줄 요소는 수십 개다 */
121
+ .tree { position: relative; height: 320px; overflow: auto; border: 1px solid var(--line); border-radius: 6px; }
122
+ .tree .row { position: absolute; left: 0; right: 0; height: 26px; display: flex; align-items: center; gap: 4px; padding-right: 4px; white-space: nowrap; }
123
+ .tree .row.current { background: var(--accent); color: var(--accent-text); }
124
+ .tree .row.current .id { color: inherit; }
125
+ .tree .toggle { width: 18px; height: 20px; padding: 0; border: 0; background: none; color: inherit; flex: none; display: inline-flex; align-items: center; justify-content: center; }
126
+ /* 접고 펼치는 표시는 글꼴에 기대지 않고 삼각형으로 그린다 */
127
+ .tree .toggle::before { content: ""; width: 0; height: 0; border-top: 4.5px solid transparent; border-bottom: 4.5px solid transparent; border-left: 7px solid currentColor; transition: transform .1s; }
128
+ .tree .toggle[aria-expanded="true"]::before { transform: rotate(90deg); }
129
+ .tree .gap { width: 18px; flex: none; }
130
+ .tree .pick { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; text-align: left; background: none; border: 0; padding: 1px 2px; font-size: 13px; color: inherit; }
131
+ .tree .dot { width: 10px; height: 10px; border-radius: 2px; border: 1px solid var(--line); flex: none; }
132
+ .id { color: var(--muted); font-size: 11px; margin-left: 4px; }
133
+ .nodes { list-style: none; margin: 0; padding: 0; }
134
+ .nodes li { display: flex; gap: 6px; align-items: center; padding: 2px 0; border-top: 1px solid var(--line); }
135
+ .nodes li:first-child { border-top: 0; }
136
+ .nodes .pick { flex: 1; min-width: 0; text-align: left; background: none; border: 0; padding: 2px; font-size: 13px; color: inherit; }
137
+ .use { font-size: 11px; border-radius: 3px; padding: 0 4px; border: 1px solid currentColor; }
138
+ .use.label { color: var(--node-label); }
139
+ .use.goal { color: var(--node-goal); }
140
+
141
+ #startView { flex: 1; overflow: auto; padding: 16px; }
142
+ #startView .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; max-width: 980px; }
143
+ #startView .card { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px; display: flex; flex-direction: column; gap: 6px; }
144
+ #startView .card h3 { margin: 0; font-size: 15px; }
145
+ #startView .card p { margin: 0; }
146
+ #startView .card .btn { align-self: flex-start; margin-top: auto; }
147
+ #startView .lead { max-width: 980px; margin: 0 0 12px; }
148
+
149
+ /* 알림은 화면 아래쪽에 뜬다. 위쪽에는 보내는 칸이 뜨므로 그 글과 버튼을 덮지 않게 하고, 누르는 것은 알림을 지나간다.
150
+ 위쪽 줄(z-index 5)보다 아래에 두어 열린 메뉴를 덮지 않는다 */
151
+ #toast { position: fixed; z-index: 4; left: 50%; bottom: 16px; transform: translateX(-50%); pointer-events: none; background: var(--text); color: var(--bg); padding: 5px 12px; border-radius: 6px; font-size: 14px; max-width: min(90vw, 640px); }
152
+ #toast.bad { background: var(--del); color: #fff; }
153
+ #error { color: var(--del); padding: 16px; }
154
+ [hidden] { display: none !important; }
155
+ @media (max-width: 900px) {
156
+ body { display: block; height: auto; }
157
+ #main { display: block; }
158
+ /* 좁은 화면에서는 위아래로 쌓는다. 그림 칸만 높이를 정하고, 안내 글과 연 옆 칸은 제 높이만큼 아래로 이어진다 */
159
+ #main[data-side="open"] { display: block; }
160
+ #stageBox { display: block; overflow: visible; margin-bottom: 8px; }
161
+ #stageWrap { display: block; min-height: 0; }
162
+ #stage { height: 60vh; min-height: 260px; }
163
+ #side { overflow: visible; }
164
+ }
165
+ </style>
166
+ </head>
167
+ <body>
168
+ <div id="error" role="alert" hidden></div>
169
+ <header id="bar" hidden></header>
170
+ <div id="startView" hidden></div>
171
+ <main id="main" hidden>
172
+ <div id="stageBox">
173
+ <div id="stageWrap">
174
+ <div id="stage" tabindex="0" role="application" aria-label="Picture" data-tool="select">
175
+ <div id="paper"></div>
176
+ <svg id="overlay" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"></svg>
177
+ </div>
178
+ <div id="talkBar" role="group" aria-label="Send the selection to AI" hidden></div>
179
+ </div>
180
+ <p class="note" id="stageNote" hidden></p>
181
+ </div>
182
+ <aside id="side" aria-label="Parts and info" hidden></aside>
183
+ </main>
184
+ <div id="toast" role="status" hidden></div>
185
+ <script>
186
+ 'use strict';
187
+ // SVG 그림의 화면(plugin-design/image-editing.md 10.2절, 11.7절, 11.9절). 호스트와는 메시지로만 이야기한다(plugin-guide 4절).
188
+ // 그림은 논리가 준 SVG 글을 SVG 문서로 읽어 그대로 넣는다(7.2절). 화면이 사람의 입력으로 SVG 글을 만들지 않는다.
189
+ // 조각 격자, node, 고른 것의 표시는 그림과 따로 둔 겹쳐 보기 층(#overlay)에 createElementNS 와 textContent 로 그린다.
190
+ // 사람이 화면에서 고치는 것(옮기기, 색, 이름)은 모두 논리의 조작으로 바뀌어 AI 와 같은 경로로 저장된다.
191
+ // 확대와 이동, 도구, 고른 것, 격자 단계, 목록의 펼침은 화면 상태라 다시 읽어도 지킨다.
192
+ const SELECTION_FORMAT = 'aic.svg/selection-1';
193
+ const SVG_NS = 'http://www.w3.org/2000/svg';
194
+ // 선택 내용(payloadOf 의 labels)에 적는 도형 이름. AI 가 읽으므로 화면 언어와 상관없이 영어다. 화면에 보이는 이름은 shapeWord 다
195
+ const SHAPE_WORD = { rect: 'rectangle', circle: 'circle', ellipse: 'ellipse', line: 'line', polygon: 'polygon', path: 'path' };
196
+ const TOOLS = ['select', 'point', 'move', 'pan'];
197
+ // 그림을 그릴 때 남기는 태그. 논리는 이것만 만들지만 넣기 전에 한 번 더 거른다
198
+ const DRAW_TAGS = new Set(['svg', 'g', 'rect', 'circle', 'ellipse', 'line', 'polygon', 'path']);
199
+ const COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/;
200
+ const ROW_H = 26;
201
+ const MAX_RECORDS = 200; // 코어가 받는 선택의 record 수 한도
202
+ const MAX_CHIPS = 30;
203
+ const MAX_TALK_NAMES = 3; // 보내는 칸이 함께 고른 부품을 말할 때 이름을 적는 수
204
+ const MAX_SEL_NAMES = 8; // 함께 고른 부품이 이보다 많으면 그림 위에 이름은 적지 않고 테두리만 보인다
205
+ const ZOOM_MIN = 0.02;
206
+ const ZOOM_MAX = 64;
207
+ const DRAG_PX = 4; // 이만큼 움직여야 누르기가 아니라 끌기다
208
+ const PNG_MIN = 16; // 코어가 PNG 로 만드는 가장 긴 변의 범위
209
+ const PNG_MAX = 4096;
210
+ const TALK_ZONE = 110; // 떠 있는 보내는 칸이 그림 칸의 위나 아래에서 가리는 높이(화면 픽셀)
211
+ const PICK_PX = 4; // 가는 선을 누르기 쉽게, 바로 그 점에 부품이 없으면 이만큼 둘레를 본다
212
+
213
+ const errorEl = document.getElementById('error');
214
+ const toastEl = document.getElementById('toast');
215
+ const barEl = document.getElementById('bar');
216
+ const startEl = document.getElementById('startView');
217
+ const mainEl = document.getElementById('main');
218
+ const stage = document.getElementById('stage');
219
+ const paper = document.getElementById('paper');
220
+ const overlay = document.getElementById('overlay');
221
+ const stageNote = document.getElementById('stageNote');
222
+ const sideEl = document.getElementById('side');
223
+ const talkEl = document.getElementById('talkBar');
224
+
225
+ let nextId = 1;
226
+ const waiting = new Map();
227
+ let concept = null; // 호스트의 읽기 응답. body 는 다른 참여자의 변경까지 얹은 project 의 json 이다
228
+ let data = null; // concept.body. 그림 전체(부품, node, 샘플, 한도)
229
+ let caps = { edit: true }; // capabilities(). conceptSelection 이 있으면 선택을 보내고, conceptPick 이 있으면 고르기만 한 것도 알리며, output 에 svg 나 png 가 있으면 저장한다
230
+ let partById = new Map();
231
+ let roots = [];
232
+ let drawnSvg = null; // 지금 넣어 둔 SVG 글. 같으면 다시 넣지 않는다
233
+ let drawnBase = null; // 지금 그린 revision
234
+ let svgRoot = null;
235
+ let elById = new Map(); // 부품 id 에서 그린 요소로
236
+ let tool = 'select';
237
+ // 확대와 이동. x, y 는 그림 왼쪽 위가 그림 칸 안에서 놓인 화면 픽셀 위치다. auto 는 사람이 아직 확대나 이동을 하지 않아
238
+ // 칸의 크기가 바뀌면 다시 맞추는 상태다
239
+ const view = { zoom: 1, x: 0, y: 0, auto: true, canvasKey: null };
240
+ const grid = { on: false, level: 1 };
241
+ let showNodes = true;
242
+ let focusNode = null; // node 목록에서 눌러 보여 준 node
243
+ // 지금 고른 것. { gen, canvas, kind, part, hit, list, area, point, parts, rev, shared } 이다. 위치는 그림 단위다.
244
+ // kind 가 part 이면 part 는 지금 들어간 부품(묶음일 수 있다), hit 는 누른 곳의 가장 안쪽 도형이다.
245
+ // kind 가 parts 이면 list 는 Shift 를 누른 채 하나씩 더해 함께 고른 부품 둘 이상이다(고른 차례대로). 묶음과 그 안의 부품을
246
+ // 함께 담지 않는다(함께 옮길 때 두 번 옮겨지지 않게).
247
+ // shared 는 대화로 보낸 선택 { id, role, said } 다. 보내기를 기다리는 사이 다른 것을 고르면 늦게 온 응답이 새 선택에
248
+ // 붙지 않도록 선택 객체 안에 둔다(HTML 디자인 화면과 같다)
249
+ let selection = null;
250
+ let selectionGen = 0;
251
+ // 코어에 알려 둔 고르기만 한 것(setPick)의 내용. 같은 것을 다시 알리지 않으려고 적어 둔다. 알린 것이 없으면 null 이다
252
+ let pickSent = null;
253
+ let pngChoice = null; // PNG 로 저장할 크기. 'scale:2' 나 'size:512' 다. 고르기 전에는 그림 크기에 맞춰 정한다
254
+ let talk = { role: 'change', said: '' };
255
+ let nameDraft = { key: null, text: '' };
256
+ let colorDraft = { key: null, fill: '', stroke: '' };
257
+ const collapsed = new Set();
258
+ let drag = null; // 누르고 있는 동안의 끌기
259
+ let pendingRefresh = false; // 끄는 중에 온 바뀜. 끝나면 다시 읽는다
260
+ let spaceDown = false;
261
+ let committing = false;
262
+ let startDraft = { width: '64', height: '64' };
263
+ // 보이는 방식의 상태. 오른쪽 칸과 도구 설명은 숨긴 채 시작하고 위쪽 줄의 버튼으로 연다. 플러그인 화면은 브라우저 저장소를
264
+ // 쓰지 못하므로(sandbox) 화면을 다시 불러오면 처음 상태로 돌아간다
265
+ let sideOpen = false;
266
+ let helpOn = false;
267
+ let openMenu = null; // 열려 있는 메뉴의 이름('view', 'save'). 없으면 null 이다
268
+ let talkPlaced = null; // 보내는 칸을 위와 아래 가운데 어디에 띄울지 정해 둔 선택의 gen
269
+
270
+ // ---- 화면 글의 언어 ----
271
+ // 영어가 기본 글이고, 호스트가 capabilities 의 language 로 'ko' 를 주면 한국어로 보인다(plugin-guide 4.4절). 사람이 언어를
272
+ // 바꾸면 호스트가 화면을 다시 열므로 처음 한 번만 읽는다. 화면이 쓰는 글(버튼, 안내, 알림, title, aria-label, placeholder)만
273
+ // 바꾼다. 논리가 준 글(summary, 거절 문장, 샘플 제목과 소개, 그림의 reason), canvas.start 에 적는 reason, AI 에게 가는 선택
274
+ // 내용(payloadOf), 부품과 node 의 이름, id, 호스트의 오류 글은 바꾸지 않는다. 화면은 다른 파일을 읽지 못해 사전을 여기 둔다.
275
+ // 화면 글은 모두 t 의 첫 인자나 tn 의 둘째와 셋째 인자에 작은따옴표 글 그대로 적는다(screen-lang.test 가 본다)
276
+ let lang = 'en';
277
+ const KO = {
278
+ // 위쪽 줄과 도구
279
+ 'Select': '고르기',
280
+ 'Point': '점',
281
+ 'Move parts': '부품 옮기기',
282
+ 'Pan': '화면 이동',
283
+ 'Click a part to select its outermost group first. Click the same spot again to go one level inside. Hold Shift and click to select several together. Drag to select an area.': '부품을 누르면 맨 바깥 묶음부터 고르고, 같은 곳을 다시 누르면 한 단계 안쪽으로 들어갑니다. Shift 를 누른 채 누르면 여럿을 함께 고릅니다. 끌면 영역을 고릅니다.',
284
+ 'Click a spot to select that point and the parts that overlap there.': '한 곳을 누르면 그 점과 그곳에 겹친 부품을 고릅니다.',
285
+ 'Drag a selected part or group to move it. If you selected several, they move together. Drag a spot you did not select to move the outermost group there.': '고른 부품이나 묶음을 끌어 옮깁니다. 여럿을 골랐으면 함께 옮깁니다. 고르지 않은 곳을 끌면 그곳의 맨 바깥 묶음을 옮깁니다.',
286
+ 'Drag to move the view.': '끌어서 화면을 옮깁니다.',
287
+ 'Parts cannot be moved on a view-only screen.': '보기만 하는 화면에서는 옮기지 않습니다.',
288
+ 'Tools': '도구',
289
+ 'Choose fill color': '채움 색 고르기',
290
+ 'Choose stroke color': '선 색 고르기',
291
+ 'Color': '색',
292
+ 'Fill': '채움',
293
+ 'Stroke': '선',
294
+ 'Zoom': '확대',
295
+ 'Zoom out': '축소',
296
+ 'Zoom in': '확대',
297
+ 'Fit to screen': '화면에 맞춤',
298
+ 'Picture size': '그림 크기',
299
+ 'Picture size {size}, {parts}, {nodes}': '그림 크기 {size}, {parts}, {nodes}',
300
+ 'This is a view-only screen. Buttons that make changes are off': '보기만 하는 화면입니다. 고치는 버튼은 꺼져 있습니다',
301
+ 'View only': '보기만',
302
+ 'Piece grid level': '조각 격자의 단계',
303
+ 'Piece grid': '조각 격자',
304
+ 'View': '보기',
305
+ 'Show nodes': 'node 보기',
306
+ '{name} menu': '{name} 메뉴',
307
+ 'level {level} / {depth}': '단계 {level} / {depth}',
308
+ 'off, levels 0 to {depth}': '끔, 단계 0~{depth}',
309
+ 'Save': '저장',
310
+ 'Save as SVG file': 'SVG 파일로 저장',
311
+ 'Saves the picture as it is now as an SVG file': '지금 그림을 SVG 파일로 저장합니다',
312
+ 'Start a picture before saving': '그림을 시작한 뒤 저장합니다',
313
+ 'This core version cannot save SVG files yet': '이 코어 버전은 아직 SVG 파일 저장을 받지 않습니다',
314
+ 'PNG size': 'PNG 크기',
315
+ 'Save as PNG': 'PNG 로 저장',
316
+ 'Saves the picture as it is now as a PNG file at the chosen size. Empty areas are transparent': '지금 그림을 고른 크기의 PNG 파일로 저장합니다. 빈 곳은 투명합니다',
317
+ '{w}×{h} (original size)': '{w}×{h} (원래 크기)',
318
+ '{w}×{h} ({k}×)': '{w}×{h} ({k}배)',
319
+ 'long side {n}': '긴 변 {n}',
320
+ 'Tool help': '도구 설명',
321
+ 'Show tool help': '도구 설명 보기',
322
+ 'Hide tool help': '도구 설명 숨기기',
323
+ 'Parts and info': '부품과 정보',
324
+ 'Show parts and info (selection, naming, color, parts, nodes)': '부품과 정보 보기(고른 것, 이름 붙이기, 색, 부품 목록, node 목록)',
325
+ 'Hide parts and info': '부품과 정보 숨기기',
326
+ 'Colors cannot be changed on a view-only screen': '보기만 하는 화면에서는 색을 바꾸지 않습니다',
327
+ 'Select a shape to change its color': '도형을 고르면 색을 바꿉니다',
328
+ 'Groups have no color. Select a shape inside': '묶음에는 색이 없습니다. 안의 도형을 고릅니다',
329
+ 'Lines have no fill': '선에는 채움이 없습니다',
330
+ 'Changes the fill of {n} selected shape together': '고른 도형 {n}개의 채움을 함께 바꿉니다',
331
+ 'Changes the fill of {n} selected shapes together': '고른 도형 {n}개의 채움을 함께 바꿉니다',
332
+ 'Changes the stroke color of {n} selected shape together': '고른 도형 {n}개의 선 색을 함께 바꿉니다',
333
+ 'Changes the stroke color of {n} selected shapes together': '고른 도형 {n}개의 선 색을 함께 바꿉니다',
334
+ 'Fill {color}': '채움 {color}',
335
+ 'Stroke {color}': '선 {color}',
336
+ // 그림 칸과 도구 설명
337
+ 'Picture': '그림',
338
+ 'Send the selection to AI': '고른 것을 AI 에게 보내기',
339
+ 'Use the wheel to zoom in and out. Hold Space or the middle mouse button and drag to move the view with any tool. Press Esc to clear the selection.': '휠로 확대하고 줄이며, 스페이스나 가운데 버튼을 누른 채 끌면 어느 도구에서든 화면을 옮깁니다. 고른 것을 풀려면 Esc 를 누릅니다.',
340
+ 'On a view-only screen, the selection is not sent to AI.': '보기만 하는 화면에서는 고른 것을 AI 에게 보내지 않습니다.',
341
+ 'This host cannot receive selections from a concept screen yet.': '이 호스트는 아직 개념 화면의 선택을 받지 못합니다.',
342
+ 'When you select something, a send box appears over the picture.': '고르면 그림 위에 보내는 칸이 나옵니다.',
343
+ 'Even if you only select, AI reads it when you talk in the chat. To tell a waiting AI right away, send it from that box.': '고르기만 해도 대화창에서 말하면 AI 가 읽습니다. 기다리는 AI 에게 바로 알리려면 그 칸에서 보냅니다.',
344
+ 'Selecting alone does not tell AI. Send it from that box.': '고르기만 해서는 AI 가 알지 못합니다. 그 칸에서 보냅니다.',
345
+ // 낱말과 위치
346
+ 'rectangle': '사각형',
347
+ 'circle': '원',
348
+ 'ellipse': '타원',
349
+ 'line': '선',
350
+ 'polygon': '다각형',
351
+ 'path': '곡선',
352
+ 'group': '묶음',
353
+ 'none': '없음',
354
+ 'area {box}': '영역 {box}',
355
+ 'point {x}, {y}': '점 {x}, {y}',
356
+ 'piece {piece}': '조각 {piece}',
357
+ '{n} part': '부품 {n}개',
358
+ '{n} parts': '부품 {n}개',
359
+ '{n} node': 'node {n}개',
360
+ '{n} nodes': 'node {n}개',
361
+ '{n} shape': '도형 {n}개',
362
+ '{n} shapes': '도형 {n}개',
363
+ '{n} group': '묶음 {n}개',
364
+ '{n} groups': '묶음 {n}개',
365
+ 'and {n} more': '외 {n}개',
366
+ // 알림과 오류
367
+ 'Could not read the picture': '그림을 읽지 못했습니다',
368
+ 'Could not read the work': '읽지 못했습니다',
369
+ 'You can select up to {n} parts together': '한 번에 {n}개까지 함께 고릅니다',
370
+ 'Click inside the picture': '그림 안을 누릅니다',
371
+ 'The selected part was deleted, so the selection was cleared': '고른 부품이 지워져 고른 것을 풀었습니다',
372
+ 'Deleted parts were removed from the selection': '고른 부품 가운데 지워진 것을 뺐습니다',
373
+ 'The selected parts were deleted, so the selection was cleared': '고른 부품이 지워져 고른 것을 풀었습니다',
374
+ 'Still sending the previous operation': '앞의 조작을 보내는 중입니다',
375
+ 'This is a view-only screen, so you cannot make changes': '보기만 하는 화면에서는 고치지 않습니다',
376
+ 'The operation was rejected': '조작이 거절되었습니다',
377
+ 'Could not work out how far to move this part because of the scale of the groups around it': '이 부품은 감싼 묶음의 크기 때문에 옮길 거리를 계산하지 못했습니다',
378
+ 'No color was changed': '바뀐 색이 없습니다',
379
+ 'Write a name to keep': '남길 이름을 적습니다',
380
+ 'Could not send the selection': '선택을 보내지 못했습니다',
381
+ 'Sent the earlier selection as {id}. What you selected now is not sent yet': '앞의 선택을 {id} 로 보냈습니다. 지금 고른 것은 아직 보내지 않았습니다',
382
+ 'Sent selection {id} and your message to AI': '선택 {id} 과 말을 AI 에게 보냈습니다',
383
+ 'Sent selection {id} to AI without a message': '선택 {id} 을 말 없이 AI 에게 보냈습니다',
384
+ 'Saved: {file}': '저장했습니다: {file}',
385
+ 'Saved: {file} ({w}×{h})': '저장했습니다: {file} ({w}×{h})',
386
+ 'Could not save': '저장하지 못했습니다',
387
+ 'Write width and height as whole numbers from 1 to {side}': '너비와 높이는 1 에서 {side} 사이의 정수로 적습니다',
388
+ // 옆 칸
389
+ 'Parts': '부품 목록',
390
+ 'Parts ({n})': '부품 목록 ({n}개)',
391
+ 'What is drawn on top comes first. Click to select a part. Hold Shift and click to add it to the selection or remove it.': '위에 그려진 것이 위에 옵니다. 누르면 그 부품을 고르고, Shift 를 누른 채 누르면 고른 것에 더하거나 뺍니다.',
392
+ 'Sample {title} ({id}) version {version}': '샘플 {title}({id}) 버전 {version}',
393
+ 'Empty picture': '빈 그림',
394
+ 'Started from': '시작',
395
+ 'Size': '크기',
396
+ '{size}, piece levels 0 to {depth}': '{size}, 조각은 단계 0~{depth}',
397
+ '{n} ({shapes}, {groups}), {nodes}': '{n}개({shapes}, {groups}), {nodes}',
398
+ 'Reason': '고른 이유',
399
+ 'This is a view-only screen. Buttons that make changes are off.': '보기만 하는 화면입니다. 고치는 버튼은 꺼져 있습니다.',
400
+ 'move ({x}, {y})': '옮김 ({x}, {y})',
401
+ 'rotate {deg} degrees': '돌림 {deg}도',
402
+ 'scale {k}': '크기 {k}',
403
+ 'scale {x} across, {y} down': '크기 가로 {x} 세로 {y}',
404
+ 'Selection': '고른 것',
405
+ 'Click a part in the picture to select it, or drag to select an area. With the Point tool, click a spot to select a point.': '그림에서 부품을 누르면 그 부품을, 끌면 영역을 고릅니다. 점 도구로 한 곳을 누르면 점을 고릅니다.',
406
+ 'Hold Shift and click to select several together. With the keyboard, select from the Parts list below. Press Esc to clear the selection.': 'Shift 를 누른 채 누르면 여럿을 함께 고릅니다. 키보드로는 아래 부품 목록에서 고릅니다. 고른 것을 풀려면 Esc 를 누릅니다.',
407
+ '{n} part selected together': '함께 고른 부품 {n}개',
408
+ '{n} parts selected together': '함께 고른 부품 {n}개',
409
+ 'Kind': '종류',
410
+ 'Area': '영역',
411
+ 'Piece': '조각',
412
+ '{piece} holds all the selected parts': '{piece} 이 고른 부품을 모두 담습니다',
413
+ 'It goes outside the picture, so no piece holds it whole': '그림 밖으로 나가 조각에 통째로 들지 않습니다',
414
+ 'Click to remove': '누르면 뺍니다',
415
+ 'Remove {name}': '{name} 빼기',
416
+ 'Click to remove it from the selection': '누르면 고른 것에서 뺍니다',
417
+ 'Hold Shift and click to add or remove.': 'Shift 를 누른 채 누르면 더하거나 뺍니다.',
418
+ 'Hold Shift and click to add or remove. Drag with [Move parts] to move them together. The color boxes at the top apply to all selected shapes. To give names, select one at a time.': 'Shift 를 누른 채 누르면 더하거나 뺍니다. [부품 옮기기] 로 끌면 함께 옮기고, 위쪽의 색 칸은 고른 도형 모두에 적용합니다. 이름은 하나씩 고른 뒤 붙입니다.',
419
+ 'Selected group': '고른 묶음',
420
+ 'Selected part': '고른 부품',
421
+ 'Part': '부품',
422
+ 'group, {n} part inside': '묶음, 안의 부품 {n}개',
423
+ 'group, {n} parts inside': '묶음, 안의 부품 {n}개',
424
+ 'fits whole in {piece}': '{piece} 에 통째로 들어갑니다',
425
+ 'Placement': '배치',
426
+ 'fill {fill}, stroke {stroke} width {width}': '채움 {fill}, 선 {stroke} 굵기 {width}',
427
+ 'fill {fill}, stroke none': '채움 {fill}, 선 없음',
428
+ 'Outside to inside': '바깥에서 안쪽으로',
429
+ 'This is the innermost part. Click a group above to select that group.': '가장 안쪽 부품입니다. 위의 묶음을 누르면 그 묶음을 고릅니다.',
430
+ 'Click the same spot again to go one level inside.': '같은 곳을 다시 누르면 한 단계 안쪽으로 들어갑니다.',
431
+ 'Selected area': '고른 영역',
432
+ '{piece} holds this whole area': '{piece} 이 이 영역을 통째로 담습니다',
433
+ 'Shapes over it': '걸친 도형',
434
+ '{n}, bottom first': '{n}개, 아래에 깔린 것부터',
435
+ 'none (empty)': '없음(빈 곳)',
436
+ 'Selected point': '고른 점',
437
+ 'Shapes there': '그곳의 도형',
438
+ '{n}, top first': '{n}개, 맨 위부터',
439
+ // 보내는 칸
440
+ '{parts} ({names})': '{parts}({names})',
441
+ 'Message about this selection': '이 선택에 대해 할 말',
442
+ 'For example: make only this red. You can also send it empty': '예: 이것만 빨갛게. 비워 두고 보내도 됩니다',
443
+ 'Role of the selection': '선택의 역할',
444
+ 'To change': '바꿀 곳',
445
+ 'For reference': '참고할 곳',
446
+ 'Sent to AI (selection {id})': 'AI 에게 보냈습니다(선택 {id})',
447
+ '{sel}, message "{said}". AI reads this selection and works on it.': '{sel}, 말 "{said}". AI 가 이 선택을 읽고 일합니다.',
448
+ '{sel}, no message. AI reads this selection and works on it.': '{sel}, 말 없음. AI 가 이 선택을 읽고 일합니다.',
449
+ 'Selection: {sel}': '고른 것: {sel}',
450
+ 'AI reads this when you talk in the chat. To tell a waiting AI right away, click [Send to AI]. The message can be empty.': '대화창에서 말하면 AI 가 이것을 읽습니다. 기다리는 AI 에게 바로 알리려면 [AI 에게 보내기] 를 누릅니다. 말은 비워도 됩니다.',
451
+ 'Not sent to AI yet.': '아직 AI 에게 보내지 않았습니다.',
452
+ 'The message can be empty.': '말은 비워도 됩니다.',
453
+ 'Send to AI': 'AI 에게 보내기',
454
+ 'Sends the selection and your message to AI. The message can be empty': '고른 것과 적은 말을 AI 에게 보냅니다. 말은 비워도 됩니다',
455
+ 'Clear selection': '고른 것 풀기',
456
+ 'Clears the selection (Esc)': '고른 것을 풉니다(Esc)',
457
+ // 이름, 색, 부품 목록, node 목록
458
+ 'Name to keep': '남길 이름',
459
+ 'Part name': '부품 이름',
460
+ 'For example: left eye': '예: 왼쪽 눈',
461
+ 'Name and keep': '이름 붙여 남기기',
462
+ 'This renames the part. Parts do not get a separate node.': '이 부품의 이름을 바꿉니다. 부품에는 node 를 따로 만들지 않습니다.',
463
+ 'This keeps the area as a label node.': '이 영역을 이름표 node 로 남깁니다.',
464
+ 'This keeps the point as a label node.': '이 점을 이름표 node 로 남깁니다.',
465
+ 'Fill color': '채움 색',
466
+ 'Stroke color': '선 색',
467
+ 'Change color': '색 바꾸기',
468
+ 'Lines have no fill. Write a color like #rrggbb, or write none to remove it.': '선에는 채움이 없습니다. 색은 #rrggbb 처럼 적고, 없애려면 none 이라고 적습니다.',
469
+ 'Write a color like #rrggbb, or write none to remove it. You can also pick one in the color boxes at the top.': '색은 #rrggbb 처럼 적고, 없애려면 none 이라고 적습니다. 위쪽의 색 칸에서 골라도 됩니다.',
470
+ 'Collapse {name}': '{name} 접기',
471
+ 'Expand {name}': '{name} 펼치기',
472
+ 'Nodes ({n})': 'node 목록 ({n}개)',
473
+ 'No nodes yet. Select an area or a point and give it a name to keep it. Places AI recognized and shapes it set as targets for a change also appear here.': '아직 node 가 없습니다. 영역이나 점을 고르고 이름을 붙이면 남습니다. AI 가 알아본 곳과 고치려고 잡은 모양도 여기에 나옵니다.',
474
+ 'Label': '이름표',
475
+ 'Target shape': '목표 모양',
476
+ 'Delete': '지우기',
477
+ 'Delete node {name}': '{name} node 지우기',
478
+ // 시작 화면
479
+ '{size}, {parts}, sample id {id}, version {version}': '{size}, {parts}, 샘플 id {id}, 버전 {version}',
480
+ 'Start with this sample': '이 샘플로 시작',
481
+ 'Width': '너비',
482
+ 'Height': '높이',
483
+ 'Start from an empty picture and ask AI to draw. Icons are usually 24, 32, or 64.': '빈 그림에서 시작해 AI 에게 그려 달라고 합니다. 아이콘은 보통 24, 32, 64 입니다.',
484
+ 'The size can be 1 to {side}. It does not change after you start. Pieces split this size into four, level by level.': '크기는 1 에서 {side} 까지입니다. 시작한 뒤에는 바꾸지 않습니다. 조각은 이 크기를 넷씩 나눕니다.',
485
+ 'Start with an empty picture': '빈 그림으로 시작',
486
+ 'Start a picture': '그림 시작',
487
+ 'There is no picture yet. This is a view-only screen, so you cannot start one here.': '그림이 아직 없습니다. 보기만 하는 화면이라 여기서는 시작하지 않습니다.',
488
+ 'There is no picture yet. Choose a built-in sample, or set the size of an empty picture, to start. You can also ask AI to start one.': '그림이 아직 없습니다. 내장 샘플 하나를 고르거나 빈 그림의 크기를 정해 시작합니다. AI 에게 시작해 달라고 해도 됩니다.',
489
+ };
490
+
491
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
492
+ /** 사전의 글을 고르고 vars 의 값으로 {이름} 을 채운다. 한 번에 채우므로 값 안의 {} 는 다시 채우지 않는다. */
493
+ function langText(text, vars) {
494
+ const out = lang === 'ko' && hasOwn(KO, text) ? KO[text] : text;
495
+ return vars ? out.replace(/\{(\w+)\}/g, (m, k) => (hasOwn(vars, k) ? String(vars[k]) : m)) : out;
496
+ }
497
+ /** 화면 글. 한국어 화면이고 사전에 있으면 한국어로 보인다. */
498
+ function t(text, vars) {
499
+ return langText(text, vars);
500
+ }
501
+ /** 수가 붙는 화면 글. 영어는 하나면 one, 아니면 other 를 쓴다. {n} 에 수를 채운다. 한국어는 보통 둘이 같다. */
502
+ function tn(n, one, other, vars) {
503
+ return langText(n === 1 ? one : other, { n, ...vars });
504
+ }
505
+
506
+ /** index.html 에 고정으로 적힌 aria-label. 처음 한 번과 언어를 정할 때 적는다. */
507
+ function labelStatic() {
508
+ stage.setAttribute('aria-label', t('Picture'));
509
+ talkEl.setAttribute('aria-label', t('Send the selection to AI'));
510
+ sideEl.setAttribute('aria-label', t('Parts and info'));
511
+ }
512
+
513
+ function call(method, params) {
514
+ return new Promise((resolve, reject) => {
515
+ const id = nextId++;
516
+ waiting.set(id, { resolve, reject });
517
+ parent.postMessage({ aic: 1, id, method, params }, '*');
518
+ });
519
+ }
520
+
521
+ window.addEventListener('message', (e) => {
522
+ if (e.source !== parent) return;
523
+ const d = e.data;
524
+ if (typeof d !== 'object' || d === null || d.aic !== 1) return;
525
+ if (d.event === 'change') {
526
+ // 끌어 옮기는 중에는 다시 그리지 않고 끝난 뒤 읽는다(plugin-guide 4.7절)
527
+ if (drag) pendingRefresh = true;
528
+ else refresh();
529
+ return;
530
+ }
531
+ if (d.event) return;
532
+ const w = waiting.get(d.id);
533
+ if (!w) return;
534
+ waiting.delete(d.id);
535
+ if (d.error) w.reject(new Error(d.error));
536
+ else w.resolve(d.result);
537
+ });
538
+
539
+ // ---- 계산(그림 단위) ----
540
+
541
+ const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
542
+ const r1 = (v) => Math.round(v * 10) / 10 || 0;
543
+ const r3 = (v) => Math.round(v * 1000) / 1000 || 0;
544
+ const num = (v) => String(Math.round(v * 100) / 100 || 0);
545
+ const boxText = (b) => (b ? `${num(b.x)}, ${num(b.y)} / ${num(b.w)}×${num(b.h)}` : t('none'));
546
+ // 화면 글의 수와 낱말. 영어는 하나면 그대로, 아니면 s 를 붙인다
547
+ const partCount = (n) => tn(n, '{n} part', '{n} parts');
548
+ const nodeCount = (n) => tn(n, '{n} node', '{n} nodes');
549
+ const shapeCount = (n) => tn(n, '{n} shape', '{n} shapes');
550
+ const groupCount = (n) => tn(n, '{n} group', '{n} groups');
551
+
552
+ // 조각 계산은 packages/image-quad 와 같은 규칙이다. 루트가 q 이고 자식은 왼쪽 위 1, 오른쪽 위 2, 왼쪽 아래 3, 오른쪽 아래 4,
553
+ // 가로와 세로를 각각 반씩 나눈다. 화면에는 빌드 단계가 없어 같은 식을 여기 적고, screen.test 가 image-quad 와 견준다.
554
+
555
+ /** 조각의 영역. 이 그림에 없는 조각이면 null 이다. */
556
+ function pieceRectOf(id) {
557
+ const c = data?.canvas;
558
+ if (!c || typeof id !== 'string' || !/^q(\.[1-4])*$/.test(id)) return null;
559
+ const path = id === 'q' ? [] : id.slice(2).split('.').map(Number);
560
+ if (path.length > c.depth) return null;
561
+ let x = 0, y = 0, w = c.width, h = c.height;
562
+ for (const k of path) {
563
+ w /= 2;
564
+ h /= 2;
565
+ if (k === 2 || k === 4) x += w;
566
+ if (k === 3 || k === 4) y += h;
567
+ }
568
+ return { x, y, w, h };
569
+ }
570
+
571
+ /** 단계 level 의 격자에서 col 번째 열, row 번째 줄(0부터) 칸의 조각 id. */
572
+ function pieceIdAt(col, row, level) {
573
+ let id = 'q';
574
+ for (let k = level - 1; k >= 0; k -= 1) id += `.${((row >> k) & 1) * 2 + ((col >> k) & 1) + 1}`;
575
+ return id;
576
+ }
577
+
578
+ /** 단계 level 의 모든 칸. 겹쳐 보기와 같은 식이다. 시험이 image-quad 의 pieceRect 와 견준다. */
579
+ function pieceCells(level) {
580
+ const c = data.canvas;
581
+ const n = 2 ** level;
582
+ const out = [];
583
+ for (let row = 0; row < n; row += 1) for (let col = 0; col < n; col += 1) out.push({ id: pieceIdAt(col, row, level), x: (col * c.width) / n, y: (row * c.height) / n, w: c.width / n, h: c.height / n });
584
+ return out;
585
+ }
586
+
587
+ const containsRect = (o, r) => r.x >= o.x && r.y >= o.y && r.x + r.w <= o.x + o.w && r.y + r.h <= o.y + o.h;
588
+ const overlapsRect = (a, b) => a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
589
+
590
+ /** 영역을 통째로 담는 가장 작은 조각. */
591
+ function smallestPiece(r) {
592
+ let id = 'q';
593
+ for (let d = 0; d < data.canvas.depth; d += 1) {
594
+ const next = [1, 2, 3, 4].map((k) => `${id}.${k}`).find((k) => containsRect(pieceRectOf(k), r));
595
+ if (!next) break;
596
+ id = next;
597
+ }
598
+ return id;
599
+ }
600
+
601
+ /** 점이 든 가장 깊은 조각. 경계 위의 점은 오른쪽과 아래쪽 조각에 든다. 그림 밖이면 null 이다. */
602
+ function deepestPiece(x, y) {
603
+ const c = data.canvas;
604
+ if (!(x >= 0 && y >= 0 && x <= c.width && y <= c.height)) return null;
605
+ let id = 'q';
606
+ let r = pieceRectOf(id);
607
+ for (let d = 0; d < c.depth; d += 1) {
608
+ id += `.${(y >= r.y + r.h / 2 ? 2 : 0) + (x >= r.x + r.w / 2 ? 1 : 0) + 1}`;
609
+ r = pieceRectOf(id);
610
+ }
611
+ return id;
612
+ }
613
+
614
+ // 배치의 행렬은 논리의 placeMatrix 와 같다. 옮김(move)은 행렬의 이동 칸에만 더해지므로, 묶음 안의 부품을 그림에서 (dx, dy)
615
+ // 만큼 옮기려면 감싼 묶음들의 돌림과 크기(선형 부분)를 거꾸로 적용한 값만큼 move 를 바꾸면 된다. 기준점은 이 계산에 들지 않는다.
616
+
617
+ /** 배치의 돌림과 크기만의 2×2 행렬 [a, b, c, d]. 점 (x, y) 는 (a x + c y, b x + d y) 로 간다. */
618
+ function linearOf(place) {
619
+ const t = ((place?.rotate ?? 0) * Math.PI) / 180;
620
+ const [kx, ky] = place?.scale ?? [1, 1];
621
+ return [Math.cos(t) * kx, Math.sin(t) * kx, -Math.sin(t) * ky, Math.cos(t) * ky];
622
+ }
623
+ const mul2 = (m, k) => [m[0] * k[0] + m[2] * k[1], m[1] * k[0] + m[3] * k[1], m[0] * k[2] + m[2] * k[3], m[1] * k[2] + m[3] * k[3]];
624
+
625
+ /** 감싼 묶음들의 선형 부분을 바깥 묶음부터 곱한 것(부품의 부모 안 위치를 그림 위치로 옮길 때 쓰는 부분). */
626
+ function parentLinear(id) {
627
+ const ups = [];
628
+ for (let p = partById.get(id)?.parent; p && partById.has(p) && !ups.includes(p); p = partById.get(p).parent) ups.unshift(p);
629
+ return ups.reduce((m, g) => mul2(m, linearOf(partById.get(g).place)), [1, 0, 0, 1]);
630
+ }
631
+
632
+ /** 그림에서 (dx, dy) 만큼 옮기려면 move 를 얼마나 바꾸는지. 거꾸로 할 수 없으면 null 이다. */
633
+ function moveDelta(id, dx, dy) {
634
+ const [a, b, c, d] = parentLinear(id);
635
+ const det = a * d - b * c;
636
+ if (!Number.isFinite(det) || Math.abs(det) < 1e-12) return null;
637
+ return [(d * dx - c * dy) / det, (-b * dx + a * dy) / det];
638
+ }
639
+
640
+ /** 끈 거리를 더한 새 move. part.place 의 move 는 정하는 값이라 지금 move 에 더해 보낸다. */
641
+ function moveFor(id, dx, dy) {
642
+ const p = partById.get(id);
643
+ const dm = p ? moveDelta(id, dx, dy) : null;
644
+ if (!dm) return null;
645
+ return [r3(p.place.move[0] + dm[0]), r3(p.place.move[1] + dm[1])];
646
+ }
647
+
648
+ /** 이 부품과 감싼 묶음들. 가장 안쪽(자기)부터 바깥으로. */
649
+ function chainOf(id) {
650
+ const out = [];
651
+ for (let p = id; p && partById.has(p) && !out.includes(p); p = partById.get(p).parent) out.push(p);
652
+ return out;
653
+ }
654
+
655
+ /**
656
+ * 누를 때 고를 부품(11.7절). 처음에는 누른 곳을 감싼 맨 바깥 묶음을 고르고, 지금 고른 묶음 안을 다시 누르면 한 단계 안쪽으로
657
+ * 들어간다. 가장 안쪽까지 들어갔으면 그대로다. chain 은 누른 도형부터 바깥으로다.
658
+ */
659
+ function nextPick(chain, current) {
660
+ const at = current === null || current === undefined ? -1 : chain.indexOf(current);
661
+ if (at < 0) return chain[chain.length - 1];
662
+ return chain[Math.max(0, at - 1)];
663
+ }
664
+
665
+ /** 영역에 걸친 도형(아래에 깔린 것부터). 논리의 선택 설명과 같은 규칙이다. */
666
+ const partsInArea = (r) => data.parts.filter((p) => p.kind === 'shape' && p.box && overlapsRect(p.box, r));
667
+
668
+ // wordOf 와 labelOf 는 AI 에게 가는 선택 내용(labels)에 쓰므로 영어 그대로다. 화면에 보이는 낱말은 shapeWord 와 shownWord 다
669
+ const wordOf = (p) => (p.kind === 'group' ? 'group' : SHAPE_WORD[p.shape] ?? p.shape);
670
+ const labelOf = (p) => (p.name ? `${p.name}(${wordOf(p)})` : wordOf(p));
671
+ function shapeWord(shape) {
672
+ switch (shape) {
673
+ case 'rect': return t('rectangle');
674
+ case 'circle': return t('circle');
675
+ case 'ellipse': return t('ellipse');
676
+ case 'line': return t('line');
677
+ case 'polygon': return t('polygon');
678
+ case 'path': return t('path');
679
+ default: return shape;
680
+ }
681
+ }
682
+ const shownWord = (p) => (p.kind === 'group' ? t('group') : shapeWord(p.shape));
683
+ const titleOf = (p) => `${p.name || shownWord(p)} (${p.id})`;
684
+ const atText = (at) => (at.kind === 'region' ? t('area {box}', { box: boxText(at) }) : at.kind === 'point' ? t('point {x}, {y}', { x: num(at.x), y: num(at.y) }) : t('piece {piece}', { piece: at.piece }));
685
+
686
+ function readOnly() {
687
+ return caps.edit === false || Boolean(concept?.editing && concept.instance && concept.editing.id !== concept.instance);
688
+ }
689
+
690
+ // ---- 그림 ----
691
+
692
+ function setData(body) {
693
+ data = body ?? null;
694
+ partById = new Map((data?.parts ?? []).map((p) => [p.id, p]));
695
+ roots = (data?.parts ?? []).filter((p) => p.parent === null || !partById.has(p.parent));
696
+ const c = data?.canvas;
697
+ const key = c ? `${c.id}:${c.width}x${c.height}` : null;
698
+ if (key !== view.canvasKey) {
699
+ // 다른 그림이면 처음부터 맞추고 고른 것을 푼다
700
+ view.canvasKey = key;
701
+ view.auto = true;
702
+ selection = null;
703
+ collapsed.clear();
704
+ focusNode = null;
705
+ grid.level = c ? Math.min(1, c.depth) : 1;
706
+ }
707
+ if (c) grid.level = clamp(grid.level, 0, c.depth);
708
+ }
709
+
710
+ /** 그리기 전에 한 번 더 거른다. 논리는 이미 검사한 숫자와 색으로만 글을 만들지만, 겹쳐 두는 검사다. */
711
+ function sanitizeSvg(root) {
712
+ for (const n of Array.from(root.querySelectorAll('*'))) {
713
+ if (!DRAW_TAGS.has(n.localName)) { n.remove(); continue; }
714
+ for (const a of Array.from(n.attributes)) if (/^on|href$/i.test(a.name) || a.name === 'style') n.removeAttribute(a.name);
715
+ }
716
+ for (const a of Array.from(root.attributes ?? [])) if (/^on|href$/i.test(a.name) || a.name === 'style') root.removeAttribute(a.name);
717
+ }
718
+
719
+ function drawPicture() {
720
+ const has = Boolean(data?.canvas && typeof data.svg === 'string');
721
+ startEl.hidden = has;
722
+ mainEl.hidden = !has;
723
+ barEl.hidden = !has;
724
+ if (!has) {
725
+ paper.replaceChildren();
726
+ svgRoot = null;
727
+ elById = new Map();
728
+ drawnSvg = null;
729
+ return;
730
+ }
731
+ if (data.svg !== drawnSvg) {
732
+ // 논리가 검사한 값으로만 만든 SVG 글이다. 그래도 HTML 로 읽지 않고 SVG 문서로 읽어 넣는다(innerHTML 을 쓰지 않는다)
733
+ const doc = new DOMParser().parseFromString(data.svg, 'image/svg+xml');
734
+ const root = doc.documentElement;
735
+ if (!root || root.nodeName !== 'svg' || doc.getElementsByTagName('parsererror').length) throw new Error(t('Could not read the picture'));
736
+ sanitizeSvg(root);
737
+ const svg = document.importNode(root, true);
738
+ svg.setAttribute('aria-hidden', 'true');
739
+ paper.replaceChildren(svg);
740
+ svgRoot = svg;
741
+ elById = new Map();
742
+ for (const n of svg.querySelectorAll('[id]')) elById.set(n.getAttribute('id'), n);
743
+ drawnSvg = data.svg;
744
+ }
745
+ if (view.auto) fit();
746
+ else applyView();
747
+ }
748
+
749
+ const stageSize = () => ({ w: stage.clientWidth || 0, h: stage.clientHeight || 0 });
750
+ /** 고른 것을 AI 에게 보낼 수 있는 화면인가. 보내는 칸은 이럴 때만 뜬다. */
751
+ const canShare = () => Boolean(caps.conceptSelection) && caps.edit !== false;
752
+
753
+ /** 그림 전체가 칸에 들어오게 한다. 작은 아이콘은 크게, 큰 그림은 줄여서 보인다. */
754
+ function fit() {
755
+ const c = data?.canvas;
756
+ if (!c) return;
757
+ view.auto = true;
758
+ const { w, h } = stageSize();
759
+ // 화면이 막 올라와 칸의 크기가 아직 0 이면 크기가 정해진 뒤에 맞춘다(7.2절)
760
+ if (!(w > 0 && h > 0)) { applyView(); return; }
761
+ // 보내는 칸이 뜨는 위쪽은 비워 둔다. 고른 뒤에 뜬 칸이 그림을 가려 그 밑의 부품을 누르지 못하는 일이 없게 하려는 것이다.
762
+ // 칸이 뜨지 않는 화면이나 그러기에 너무 낮은 칸에서는 전체를 쓴다
763
+ const skip = canShare() && h - TALK_ZONE >= 160 ? TALK_ZONE : 0;
764
+ const room = h - skip;
765
+ const pad = Math.max(8, Math.min(32, w * 0.06, room * 0.06));
766
+ const z = clamp(Math.min((w - 2 * pad) / c.width, (room - 2 * pad) / c.height), ZOOM_MIN, ZOOM_MAX);
767
+ view.zoom = z;
768
+ view.x = (w - c.width * z) / 2;
769
+ view.y = skip + (room - c.height * z) / 2;
770
+ applyView();
771
+ }
772
+
773
+ function applyView() {
774
+ const c = data?.canvas;
775
+ if (!c) return;
776
+ paper.style.left = `${view.x}px`;
777
+ paper.style.top = `${view.y}px`;
778
+ paper.style.width = `${c.width * view.zoom}px`;
779
+ paper.style.height = `${c.height * view.zoom}px`;
780
+ if (bar.zoomText) bar.zoomText.textContent = `${Math.round(view.zoom * 100)}%`;
781
+ drawOverlay();
782
+ }
783
+
784
+ /** 칸 안의 화면 위치 (sx, sy) 를 그대로 두고 확대하거나 줄인다. 위치를 주지 않으면 칸 가운데다. */
785
+ function zoomAt(factor, px, py) {
786
+ if (!data?.canvas) return;
787
+ const { w, h } = stageSize();
788
+ const cx = px ?? w / 2;
789
+ const cy = py ?? h / 2;
790
+ const z = clamp(view.zoom * factor, ZOOM_MIN, ZOOM_MAX);
791
+ const gx = (cx - view.x) / view.zoom;
792
+ const gy = (cy - view.y) / view.zoom;
793
+ view.zoom = z;
794
+ view.x = cx - gx * z;
795
+ view.y = cy - gy * z;
796
+ view.auto = false;
797
+ applyView();
798
+ }
799
+
800
+ /** 그림 단위의 사각형이 칸에 보이게 확대하고 옮긴다. keepZoom 이면 확대는 그대로 두고 가운데로만 옮긴다. */
801
+ function showRect(r, keepZoom = false) {
802
+ const { w, h } = stageSize();
803
+ if (!(w > 0 && h > 0)) return;
804
+ if (!keepZoom && r.w > 0 && r.h > 0) view.zoom = clamp(Math.min((w * 0.6) / r.w, (h * 0.6) / r.h, ZOOM_MAX), ZOOM_MIN, ZOOM_MAX);
805
+ view.x = w / 2 - (r.x + r.w / 2) * view.zoom;
806
+ view.y = h / 2 - (r.y + r.h / 2) * view.zoom;
807
+ view.auto = false;
808
+ applyView();
809
+ }
810
+
811
+ /** 화면의 한 점(clientX, clientY)을 그림 단위로. */
812
+ function toDrawing(clientX, clientY) {
813
+ const b = paper.getBoundingClientRect();
814
+ return { x: (clientX - b.left) / view.zoom, y: (clientY - b.top) / view.zoom };
815
+ }
816
+ const sx = (x) => view.x + x * view.zoom;
817
+ const sy = (y) => view.y + y * view.zoom;
818
+
819
+ /**
820
+ * 그림 단위의 점에 그려진 도형. 맨 위에 그려진 것부터 아래로다. 논리의 shapesAt 처럼 채움이 있으면 안쪽, 선이 있으면 선 위를
821
+ * 본다. 판정은 브라우저가 그린 요소로 한다(isPointInFill, isPointInStroke). 칸에 보이지 않는 곳이어도 된다.
822
+ */
823
+ function stackAt(x, y) {
824
+ if (!svgRoot || typeof svgRoot.getScreenCTM !== 'function' || typeof DOMPoint !== 'function') return [];
825
+ const rootM = svgRoot.getScreenCTM();
826
+ if (!rootM) return [];
827
+ const client = new DOMPoint(x, y).matrixTransform(rootM);
828
+ const out = [];
829
+ for (let i = data.parts.length - 1; i >= 0; i -= 1) {
830
+ const p = data.parts[i];
831
+ if (p.kind !== 'shape' || !p.box) continue;
832
+ const b = p.box;
833
+ if (x < b.x - 1 || x > b.x + b.w + 1 || y < b.y - 1 || y > b.y + b.h + 1) continue;
834
+ const el = elById.get(p.id);
835
+ const m = el && el.getScreenCTM ? el.getScreenCTM() : null;
836
+ if (!m) continue;
837
+ const local = client.matrixTransform(m.inverse());
838
+ if ((p.fill && p.shape !== 'line' && el.isPointInFill(local)) || (p.stroke && el.isPointInStroke(local))) out.push(p);
839
+ }
840
+ return out;
841
+ }
842
+
843
+ /** 누른 곳의 맨 위 도형. 바로 그 점에 없으면 둘레 몇 픽셀 안을 본다(가는 선을 누르기 쉽게). */
844
+ function hitAt(x, y) {
845
+ const top = stackAt(x, y)[0];
846
+ if (top) return top;
847
+ const r = PICK_PX / view.zoom;
848
+ for (let k = 0; k < 8; k += 1) {
849
+ const t = (k * Math.PI) / 4;
850
+ const p = stackAt(x + r * Math.cos(t), y + r * Math.sin(t))[0];
851
+ if (p) return p;
852
+ }
853
+ return null;
854
+ }
855
+
856
+ // ---- 겹쳐 보기 ----
857
+
858
+ function svgEl(tag, attrs, text) {
859
+ const n = document.createElementNS(SVG_NS, tag);
860
+ for (const [k, v] of Object.entries(attrs ?? {})) if (v !== null && v !== undefined && v !== false) n.setAttribute(k, String(v));
861
+ if (text !== undefined) n.textContent = text;
862
+ return n;
863
+ }
864
+
865
+ function screenRect(r, cls, extra = {}) {
866
+ return svgEl('rect', { class: cls, x: sx(r.x), y: sy(r.y), width: Math.max(1, r.w * view.zoom), height: Math.max(1, r.h * view.zoom), ...extra });
867
+ }
868
+
869
+ /** 이름표 글. 칸 위쪽 바깥에 두고, 위가 모자라면 안쪽 위에 둔다. */
870
+ function nameText(r, text, cls) {
871
+ const x = sx(r.x) + 2;
872
+ const top = sy(r.y);
873
+ return svgEl('text', { class: `ov-name ${cls}`, x, y: top > 16 ? top - 5 : top + 14 }, text);
874
+ }
875
+
876
+ function pointMark(x, y, cls) {
877
+ const g = svgEl('g', { class: cls });
878
+ g.append(svgEl('circle', { cx: sx(x), cy: sy(y), r: 6 }), svgEl('path', { d: `M${sx(x) - 10} ${sy(y)}H${sx(x) + 10}M${sx(x)} ${sy(y) - 10}V${sy(y) + 10}` }));
879
+ return g;
880
+ }
881
+
882
+ /** 조각 격자. 선은 늘 그리고, 조각 id 는 칸에 들어갈 만큼 클 때만 칸에 보이는 것만 적는다. */
883
+ function gridMarks(w, h) {
884
+ const c = data.canvas;
885
+ const level = clamp(grid.level, 0, c.depth);
886
+ const n = 2 ** level;
887
+ const cw = (c.width / n) * view.zoom;
888
+ const ch = (c.height / n) * view.zoom;
889
+ let d = '';
890
+ for (let i = 0; i <= n; i += 1) d += `M${view.x + i * cw} ${view.y}V${view.y + c.height * view.zoom}`;
891
+ for (let j = 0; j <= n; j += 1) d += `M${view.x} ${view.y + j * ch}H${view.x + c.width * view.zoom}`;
892
+ const out = [svgEl('path', { class: 'ov-grid', d })];
893
+ const textWidth = (id) => id.length * 6.2 + 6;
894
+ if (ch < 15 || cw < textWidth(pieceIdAt(0, 0, level))) return out;
895
+ const c0 = clamp(Math.floor(-view.x / cw), 0, n - 1);
896
+ const c1 = clamp(Math.floor((w - view.x) / cw), 0, n - 1);
897
+ const r0 = clamp(Math.floor(-view.y / ch), 0, n - 1);
898
+ const r1 = clamp(Math.floor((h - view.y) / ch), 0, n - 1);
899
+ if ((c1 - c0 + 1) * (r1 - r0 + 1) > 4000) return out;
900
+ for (let row = r0; row <= r1; row += 1) {
901
+ for (let col = c0; col <= c1; col += 1) {
902
+ const id = pieceIdAt(col, row, level);
903
+ out.push(svgEl('text', { class: 'ov-piece', 'data-piece': id, x: view.x + col * cw + 3, y: view.y + row * ch + 12 }, id));
904
+ }
905
+ }
906
+ return out;
907
+ }
908
+
909
+ function nodeMarks() {
910
+ const out = [];
911
+ for (const nd of data.nodes ?? []) {
912
+ const cls = nd.use === 'goal' ? 'goal' : 'label';
913
+ const focus = nd.id === focusNode ? ' focus' : '';
914
+ const at = nd.at;
915
+ if (at.kind === 'point') {
916
+ out.push(pointMark(at.x, at.y, `ov-node ${cls}${focus}`));
917
+ out.push(svgEl('text', { class: `ov-name ${cls}`, x: sx(at.x) + 10, y: sy(at.y) - 8 }, nd.name));
918
+ continue;
919
+ }
920
+ const r = at.kind === 'region' ? at : pieceRectOf(at.piece);
921
+ if (!r) continue;
922
+ out.push(screenRect(r, `ov-node ${cls}${focus}`, { 'data-node': nd.id }));
923
+ out.push(nameText(r, nd.name, cls));
924
+ }
925
+ return out;
926
+ }
927
+
928
+ function selectionMarks() {
929
+ const s = selection;
930
+ if (!s) return [];
931
+ if (s.kind === 'part' || s.kind === 'parts') {
932
+ const ids = pickedIds();
933
+ const out = [];
934
+ for (const id of ids) {
935
+ const p = partById.get(id);
936
+ if (!p?.box) continue;
937
+ const off = drag?.type === 'move' && drag.dw && drag.items.some((it) => it.id === id) ? drag.dw : [0, 0];
938
+ const r = { x: p.box.x + off[0], y: p.box.y + off[1], w: p.box.w, h: p.box.h };
939
+ out.push(screenRect(r, 'ov-sel'));
940
+ // 여럿을 골랐을 때 이름표가 서로 덮지 않게, 많으면 이름은 적지 않는다
941
+ if (ids.length <= MAX_SEL_NAMES) out.push(nameText(r, titleOf(p), 'sel'));
942
+ }
943
+ return out;
944
+ }
945
+ if (s.kind === 'area') return [screenRect(s.area, 'ov-sel area')];
946
+ return [pointMark(s.point.x, s.point.y, 'ov-mark')];
947
+ }
948
+
949
+ function drawOverlay() {
950
+ const { w, h } = stageSize();
951
+ overlay.setAttribute('width', String(w));
952
+ overlay.setAttribute('height', String(h));
953
+ const out = [];
954
+ if (data?.canvas) {
955
+ if (grid.on) out.push(...gridMarks(w, h));
956
+ if (showNodes) out.push(...nodeMarks());
957
+ out.push(...selectionMarks());
958
+ if (drag?.type === 'pick' && drag.rect) out.push(screenRect(drag.rect, 'ov-rubber'));
959
+ }
960
+ overlay.replaceChildren(...out);
961
+ }
962
+
963
+ // ---- 고르기 ----
964
+
965
+ function setSelection(s) {
966
+ selection = s ? { gen: (selectionGen += 1), canvas: data.canvas.id, rev: drawnBase ?? concept.base, shared: null, ...s } : null;
967
+ if (selection?.kind === 'part') revealRow(selection.part);
968
+ else if (selection?.kind === 'parts') revealRow(selection.list[selection.list.length - 1]);
969
+ render();
970
+ notePick();
971
+ }
972
+
973
+ function selectPart(id, hit) {
974
+ if (!partById.has(id)) return;
975
+ setSelection({ kind: 'part', part: id, hit: hit && chainOf(hit).includes(id) ? hit : id });
976
+ }
977
+
978
+ /** 고른 부품들(고른 차례대로). 하나만 골랐으면 그것 하나이고, 영역이나 점을 골랐으면 비어 있다. */
979
+ const pickedIds = () => (selection?.kind === 'part' ? [selection.part] : selection?.kind === 'parts' ? selection.list : []);
980
+
981
+ /** 누를 때 Shift 나 Ctrl(맥에서는 Command)을 누르고 있었는지. 고른 것에 더하거나 빼는 누르기다. */
982
+ const addKey = (e) => Boolean(e && (e.shiftKey || e.ctrlKey || e.metaKey));
983
+
984
+ /**
985
+ * 고른 것에 이 부품을 더하거나, 이미 들어 있으면 뺀다(여럿 고르기). 고른 부품이 없으면 그냥 고른다. 묶음과 그 안의 부품은
986
+ * 함께 담지 않으므로, 더하는 부품을 감싼 묶음이나 그 안의 부품이 이미 들어 있으면 그것을 빼고 넣는다. 하나만 남으면 하나를
987
+ * 고른 것과 같다.
988
+ */
989
+ function togglePart(id, hit) {
990
+ if (!partById.has(id)) return;
991
+ const cur = pickedIds();
992
+ if (cur.length === 0) { selectPart(id, hit); return; }
993
+ const next = cur.includes(id) ? cur.filter((x) => x !== id) : [...cur.filter((x) => !chainOf(x).includes(id) && !chainOf(id).includes(x)), id];
994
+ if (next.length > MAX_RECORDS) { toast(t('You can select up to {n} parts together', { n: MAX_RECORDS }), true); return; }
995
+ if (next.length === 0) setSelection(null);
996
+ else if (next.length === 1) selectPart(next[0], next[0] === id ? hit : next[0]);
997
+ else setSelection({ kind: 'parts', list: next });
998
+ }
999
+
1000
+ /** 영역은 그림 안으로 자른다. 넓이가 없으면 고르지 않는다. */
1001
+ function clipArea(a, b) {
1002
+ const c = data.canvas;
1003
+ const x0 = clamp(Math.min(a.x, b.x), 0, c.width);
1004
+ const y0 = clamp(Math.min(a.y, b.y), 0, c.height);
1005
+ const x1 = clamp(Math.max(a.x, b.x), 0, c.width);
1006
+ const y1 = clamp(Math.max(a.y, b.y), 0, c.height);
1007
+ const r = { x: r1(x0), y: r1(y0), w: r1(x1 - x0), h: r1(y1 - y0) };
1008
+ return r.w > 0 && r.h > 0 ? r : null;
1009
+ }
1010
+
1011
+ function selectArea(r) {
1012
+ setSelection({ kind: 'area', area: r, parts: partsInArea(r).map((p) => p.id) });
1013
+ }
1014
+
1015
+ function selectPoint(x, y) {
1016
+ const c = data.canvas;
1017
+ if (!(x >= 0 && y >= 0 && x <= c.width && y <= c.height)) { toast(t('Click inside the picture'), true); return; }
1018
+ const pt = { x: r1(x), y: r1(y) };
1019
+ setSelection({ kind: 'point', point: pt, parts: stackAt(pt.x, pt.y).map((p) => p.id) });
1020
+ }
1021
+
1022
+ /**
1023
+ * 여럿 고르기로 누른 곳에서 더하거나 뺄 부품. 누른 곳이 이미 고른 부품(이나 그 안)이면 그 부품이다(빼려는 것이다). 아니면
1024
+ * 누른 도형을 감싼 묶음 가운데, 이미 고른 부품을 안에 담지 않은 가장 바깥 것이다. 그래서 묶음 안으로 들어가 부품 하나를 골라
1025
+ * 둔 때 같은 묶음의 다른 부품을 누르면 묶음이 아니라 그 부품이 더해진다. chain 은 누른 도형부터 바깥으로다.
1026
+ */
1027
+ function addPick(chain, picked) {
1028
+ const have = picked.find((id) => chain.includes(id));
1029
+ if (have) return have;
1030
+ const holds = (g) => picked.some((id) => chainOf(id).includes(g));
1031
+ for (let i = chain.length - 1; i >= 0; i -= 1) if (!holds(chain[i])) return chain[i];
1032
+ return chain[0];
1033
+ }
1034
+
1035
+ /** 누른 곳의 부품을 고른다. add 이면(Shift 를 누른 채) 고른 것에 더하거나 빼고, 빈 곳을 눌러도 고른 것을 풀지 않는다. */
1036
+ function clickSelect(x, y, add = false) {
1037
+ const hit = hitAt(x, y);
1038
+ const picked = pickedIds();
1039
+ if (add && picked.length) {
1040
+ if (hit) togglePart(addPick(chainOf(hit.id), picked), hit.id);
1041
+ return;
1042
+ }
1043
+ if (!hit) { if (selection) setSelection(null); return; }
1044
+ const chain = chainOf(hit.id);
1045
+ selectPart(nextPick(chain, selection?.kind === 'part' ? selection.part : null), hit.id);
1046
+ }
1047
+
1048
+ /** 다시 읽은 뒤 고른 것을 맞춘다. 고른 부품이 지워졌으면 푼다. 걸친 부품과 기준은 지금 그린 것으로 다시 적는다. */
1049
+ function reconcileSelection() {
1050
+ const s = selection;
1051
+ if (!s) return;
1052
+ if (!data?.canvas || s.canvas !== data.canvas.id) { selection = null; return; }
1053
+ if (s.kind === 'part') {
1054
+ if (!partById.has(s.part)) {
1055
+ selection = null;
1056
+ toast(t('The selected part was deleted, so the selection was cleared'));
1057
+ return;
1058
+ }
1059
+ if (!partById.has(s.hit) || !chainOf(s.hit).includes(s.part)) s.hit = s.part;
1060
+ } else if (s.kind === 'parts') {
1061
+ // 지워진 부품은 빼고, 그 사이 다른 고른 묶음 안으로 들어간 부품도 뺀다. 하나만 남으면 하나를 고른 것으로 바꾼다
1062
+ const live = s.list.filter((id) => partById.has(id));
1063
+ const list = live.filter((id) => !chainOf(id).slice(1).some((g) => live.includes(g)));
1064
+ if (list.length < s.list.length) toast(list.length ? t('Deleted parts were removed from the selection') : t('The selected parts were deleted, so the selection was cleared'));
1065
+ if (list.length === 0) { selection = null; return; }
1066
+ if (list.length === 1) {
1067
+ s.kind = 'part';
1068
+ s.part = list[0];
1069
+ s.hit = list[0];
1070
+ delete s.list;
1071
+ } else s.list = list;
1072
+ } else if (s.kind === 'area') s.parts = partsInArea(s.area).map((p) => p.id);
1073
+ else s.parts = stackAt(s.point.x, s.point.y).map((p) => p.id);
1074
+ s.rev = drawnBase;
1075
+ }
1076
+
1077
+ /** 보낼 선택 내용(aic.svg/selection-1). 위치는 그림 단위다. */
1078
+ function payloadOf(s) {
1079
+ const labels = {};
1080
+ const label = (id) => { const p = partById.get(id); if (p) labels[id] = labelOf(p); };
1081
+ const p = { format: SELECTION_FORMAT, rev: s.rev, kind: s.kind };
1082
+ if (s.kind === 'part') {
1083
+ p.part = s.part;
1084
+ p.groups = chainOf(s.part).slice(1);
1085
+ [p.part, ...p.groups].forEach(label);
1086
+ } else if (s.kind === 'parts') {
1087
+ p.parts = s.list.slice(0, MAX_RECORDS);
1088
+ p.parts.forEach(label);
1089
+ } else {
1090
+ if (s.kind === 'area') p.area = { ...s.area };
1091
+ else p.point = { ...s.point };
1092
+ p.parts = s.parts.slice(0, MAX_RECORDS);
1093
+ p.parts.forEach(label);
1094
+ }
1095
+ p.labels = labels;
1096
+ return p;
1097
+ }
1098
+
1099
+ const recordsOf = (p) => (p.kind === 'part' ? [p.part, ...p.groups] : p.parts).slice(0, MAX_RECORDS);
1100
+
1101
+ /**
1102
+ * 고르기만 하고 아직 보내지 않은 것을 코어에 알린다(setPick, plugin-guide 4.4절). 코어는 기록하지 않고 마지막 하나만 갖고 있다가
1103
+ * AI 가 read_selection 으로 읽을 때 "보내지 않음" 으로 보인다. AI 를 깨우지 않는다. 고른 것이 없어지면 null 로 지운다.
1104
+ * 답을 기다리지 않는다. 다시 읽어 그린 기준(rev)만 바뀐 때는 다시 알리지 않는다(고른 때가 새로 적히지 않게). 보낸 선택은
1105
+ * 코어가 고른 것을 지우고 대신하므로 알리지 않는다.
1106
+ */
1107
+ function notePick() {
1108
+ if (!caps.conceptPick || caps.edit === false) return;
1109
+ const s = selection && !selection.shared ? selection : null;
1110
+ const p = s ? payloadOf(s) : null;
1111
+ const key = p ? JSON.stringify({ ...p, rev: undefined }) : null;
1112
+ if (key === pickSent) return;
1113
+ pickSent = key;
1114
+ call('setPick', p ? { base: p.rev, payload: p, records: recordsOf(p) } : null).catch(() => {});
1115
+ }
1116
+
1117
+ // ---- 끌기 ----
1118
+
1119
+ /**
1120
+ * 부품 옮기기에서 끌 부품. 누른 곳에 고른 부품(묶음이면 그 안의 도형)이 있으면 다른 도형에 가려 있어도 그것을 끈다. 목록에서
1121
+ * 고른 부품을 그대로 끌 수 있게 하려는 것이다. 아니면 누른 곳 맨 위 도형의 맨 바깥 묶음을 골라 그것을 끈다.
1122
+ */
1123
+ function moveTarget(x, y) {
1124
+ const picked = pickedIds();
1125
+ const stack = picked.length ? stackAt(x, y) : [];
1126
+ const under = picked.find((id) => stack.some((p) => chainOf(p.id).includes(id)));
1127
+ if (under) return under;
1128
+ const hit = hitAt(x, y);
1129
+ if (!hit) return null;
1130
+ const chain = chainOf(hit.id);
1131
+ const near = picked.find((id) => chain.includes(id));
1132
+ if (near) return near;
1133
+ selectPart(chain[chain.length - 1], hit.id);
1134
+ return selection?.part ?? null;
1135
+ }
1136
+
1137
+ /** 함께 끌 부품들. 끄는 부품이 함께 고른 것 가운데 하나이면 고른 것 모두이고, 아니면 그 부품 하나다. */
1138
+ function moveItems(target) {
1139
+ const picked = pickedIds();
1140
+ const ids = picked.includes(target) ? picked : [target];
1141
+ const items = ids.map((id) => ({ id, el: elById.get(id) })).filter((it) => it.el);
1142
+ for (const it of items) it.orig = it.el.getAttribute('transform');
1143
+ return items.some((it) => it.id === target) ? items : [];
1144
+ }
1145
+
1146
+ function startDrag(e) {
1147
+ if (!data?.canvas || drag) return;
1148
+ const panning = e.button === 1 || tool === 'pan' || spaceDown;
1149
+ if (!panning && e.button !== 0) return;
1150
+ e.preventDefault();
1151
+ if (stage.focus) stage.focus({ preventScroll: true });
1152
+ const p = toDrawing(e.clientX, e.clientY);
1153
+ const start = { cx: e.clientX, cy: e.clientY, p };
1154
+ if (!panning && tool === 'move' && !readOnly()) {
1155
+ const target = moveTarget(p.x, p.y);
1156
+ const items = target ? moveItems(target) : [];
1157
+ if (items.length) drag = { type: 'move', start, items, dw: [0, 0], moved: false };
1158
+ }
1159
+ if (!drag) {
1160
+ if (panning || tool === 'pan' || tool === 'move') drag = { type: 'pan', start, vx: view.x, vy: view.y, moved: false };
1161
+ else drag = { type: tool === 'point' ? 'point' : 'pick', start, add: addKey(e), moved: false };
1162
+ }
1163
+ stage.classList.toggle('dragging', drag.type === 'pan');
1164
+ try { stage.setPointerCapture(e.pointerId); } catch {}
1165
+ }
1166
+
1167
+ function moveDrag(e) {
1168
+ if (!drag) return;
1169
+ const dx = e.clientX - drag.start.cx;
1170
+ const dy = e.clientY - drag.start.cy;
1171
+ if (!drag.moved && Math.hypot(dx, dy) < DRAG_PX) return;
1172
+ drag.moved = true;
1173
+ // 부품을 끌어 옮기거나 영역을 끌어 고르는 동안은 보내는 칸이 그림을 가리지 않게 숨긴다. 놓으면 다시 보인다
1174
+ if (drag.type === 'move' || drag.type === 'pick') talkEl.classList.add('away');
1175
+ if (drag.type === 'pan') {
1176
+ view.x = drag.vx + dx;
1177
+ view.y = drag.vy + dy;
1178
+ view.auto = false;
1179
+ applyView();
1180
+ } else if (drag.type === 'pick') {
1181
+ drag.rect = clipArea(drag.start.p, toDrawing(e.clientX, e.clientY));
1182
+ drawOverlay();
1183
+ } else if (drag.type === 'move') {
1184
+ // 끄는 동안은 그린 요소의 transform 앞에 옮길 거리만 붙여 미리 보인다. 놓으면 원래대로 두고 조작을 보낸다
1185
+ // 함께 고른 부품은 저마다 감싼 묶음이 달라 옮길 거리(move 의 차이)를 따로 구한다
1186
+ const dw = [dx / view.zoom, dy / view.zoom];
1187
+ const dms = drag.items.map((it) => moveDelta(it.id, dw[0], dw[1]));
1188
+ if (dms.some((dm) => !dm)) return;
1189
+ drag.dw = dw;
1190
+ drag.items.forEach((it, i) => it.el.setAttribute('transform', `translate(${dms[i][0]} ${dms[i][1]})${it.orig ? ` ${it.orig}` : ''}`));
1191
+ drawOverlay();
1192
+ }
1193
+ }
1194
+
1195
+ function endDrag(e, cancel = false) {
1196
+ const d = drag;
1197
+ if (!d) return;
1198
+ drag = null;
1199
+ stage.classList.remove('dragging');
1200
+ talkEl.classList.remove('away');
1201
+ try { stage.releasePointerCapture(e.pointerId); } catch {}
1202
+ if (d.type === 'move') {
1203
+ for (const it of d.items) {
1204
+ if (it.orig === null) it.el.removeAttribute('transform');
1205
+ else it.el.setAttribute('transform', it.orig);
1206
+ }
1207
+ }
1208
+ if (!cancel) {
1209
+ if (d.type === 'pick') {
1210
+ if (d.moved && d.rect) selectArea(d.rect);
1211
+ else if (!d.moved) clickSelect(d.start.p.x, d.start.p.y, d.add);
1212
+ } else if (d.type === 'point') selectPoint(d.start.p.x, d.start.p.y);
1213
+ else if (d.type === 'move' && d.moved) sendMove(d.items.map((it) => it.id), d.dw[0], d.dw[1]);
1214
+ }
1215
+ drawOverlay();
1216
+ if (pendingRefresh) {
1217
+ pendingRefresh = false;
1218
+ refresh();
1219
+ }
1220
+ }
1221
+
1222
+ stage.addEventListener('pointerdown', startDrag);
1223
+ stage.addEventListener('pointermove', moveDrag);
1224
+ stage.addEventListener('pointerup', (e) => endDrag(e));
1225
+ stage.addEventListener('pointercancel', (e) => endDrag(e, true));
1226
+ stage.addEventListener('wheel', (e) => {
1227
+ if (!data?.canvas) return;
1228
+ e.preventDefault();
1229
+ const b = stage.getBoundingClientRect();
1230
+ const step = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
1231
+ zoomAt(Math.exp(-clamp(step, -120, 120) * 0.0022), e.clientX - b.left - (stage.clientLeft || 0), e.clientY - b.top - (stage.clientTop || 0));
1232
+ }, { passive: false });
1233
+ stage.addEventListener('keydown', (e) => {
1234
+ if (e.key === 'Escape') { if (selection) setSelection(null); }
1235
+ else if (e.key === '+' || e.key === '=') zoomAt(1.25);
1236
+ else if (e.key === '-') zoomAt(0.8);
1237
+ else if (e.key === '0') fit();
1238
+ else return;
1239
+ e.preventDefault();
1240
+ });
1241
+ const typing = (t) => t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT');
1242
+ window.addEventListener('keydown', (e) => {
1243
+ if (e.key === 'Escape' && openMenu) { const m = bar.menus[openMenu]; setMenu(null); m.b.focus(); return; }
1244
+ if (e.code === 'Space' && !typing(e.target)) { spaceDown = true; stage.classList.add('panning'); if (e.target === stage) e.preventDefault(); }
1245
+ });
1246
+ window.addEventListener('keyup', (e) => {
1247
+ if (e.code === 'Space') { spaceDown = false; stage.classList.remove('panning'); }
1248
+ });
1249
+
1250
+ // ---- 호스트 ----
1251
+
1252
+ let inflight = null;
1253
+ let again = false;
1254
+ /** 다시 읽어 그린다. 읽는 중에 온 바뀜은 모아 두었다가 한 번만 다시 읽는다(plugin-guide 4.3절). */
1255
+ function refresh() {
1256
+ if (inflight) { again = true; return inflight; }
1257
+ inflight = (async () => {
1258
+ try {
1259
+ const c = await call('readConcept');
1260
+ if (!c || c.ok === false) throw new Error((c && (c.summary || c.error)) || t('Could not read the work'));
1261
+ if (drag) { pendingRefresh = true; return; }
1262
+ errorEl.hidden = true;
1263
+ // 다른 참여자(AI)의 아직 합쳐지지 않은 변경까지 얹은 상태를 그린다. 코어도 선택의 record 와 저장할 파일을 이 상태로 본다
1264
+ concept = { ...c, body: c.withOthers ?? c.body };
1265
+ setData(concept.body);
1266
+ drawPicture();
1267
+ drawnBase = concept.base;
1268
+ reconcileSelection();
1269
+ render();
1270
+ if (typeof c.renderToken === 'string') parent.postMessage({ aic: 1, event: 'rendered', token: c.renderToken }, '*');
1271
+ // 다시 읽으며 고른 것이 달라졌으면(지워진 부품이 빠짐, 걸친 부품이 바뀜) 코어에 알린 것도 맞춘다
1272
+ notePick();
1273
+ } catch (err) {
1274
+ errorEl.textContent = err.message;
1275
+ errorEl.hidden = false;
1276
+ }
1277
+ })().finally(() => {
1278
+ inflight = null;
1279
+ if (again) { again = false; refresh(); }
1280
+ });
1281
+ return inflight;
1282
+ }
1283
+
1284
+ let toastTimer = null;
1285
+ function toast(text, bad = false) {
1286
+ toastEl.textContent = text;
1287
+ toastEl.classList.toggle('bad', bad);
1288
+ toastEl.hidden = false;
1289
+ clearTimeout(toastTimer);
1290
+ toastTimer = setTimeout(() => { toastEl.hidden = true; }, bad ? 7000 : 3500);
1291
+ }
1292
+
1293
+ /** 조작을 보낸다. 거절되면 논리가 준 summary 를 그대로 보이고 다시 읽는다. */
1294
+ async function send(steps) {
1295
+ if (committing) { toast(t('Still sending the previous operation'), true); return null; }
1296
+ if (readOnly()) { toast(t('This is a view-only screen, so you cannot make changes'), true); return null; }
1297
+ committing = true;
1298
+ try {
1299
+ const res = await call('applyOperation', { base: concept.base, steps });
1300
+ if (!res || !res.ok) { toast(res?.summary ?? res?.error ?? t('The operation was rejected'), true); await refresh(); return null; }
1301
+ toast(res.summary);
1302
+ await refresh();
1303
+ return res;
1304
+ } catch (err) {
1305
+ toast(err.message, true);
1306
+ return null;
1307
+ } finally {
1308
+ committing = false;
1309
+ }
1310
+ }
1311
+
1312
+ /** 부품 하나(id)나 여럿(id 목록)을 그림에서 (dx, dy) 만큼 옮긴다. 여럿이면 조작 한 번에 담아 함께 되돌려진다. */
1313
+ function sendMove(ids, dx, dy) {
1314
+ const steps = [];
1315
+ for (const id of [].concat(ids)) {
1316
+ const move = moveFor(id, dx, dy);
1317
+ const p = partById.get(id);
1318
+ if (!move || !p) { toast(t('Could not work out how far to move this part because of the scale of the groups around it'), true); return null; }
1319
+ if (move[0] === p.place.move[0] && move[1] === p.place.move[1]) continue;
1320
+ steps.push({ op: 'part.place', input: { part: id, move } });
1321
+ }
1322
+ return steps.length ? send(steps) : null;
1323
+ }
1324
+
1325
+ const fullHex = (c) => (typeof c === 'string' && c.length === 4 ? `#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}` : typeof c === 'string' ? c.slice(0, 7) : null);
1326
+
1327
+ /** 고른 부품 가운데 도형(묶음이 아닌 것). 색은 도형에만 있다. */
1328
+ const pickedShapes = () => pickedIds().map((id) => partById.get(id)).filter((p) => p && p.kind === 'shape');
1329
+
1330
+ /**
1331
+ * 고른 도형의 채움이나 선 색을 바꾼다. 여럿을 골랐으면 그 도형들을 조작 한 번에 함께 바꾼다(선에는 채움이 없어 뺀다).
1332
+ * 원래 색에 투명도(#rrggbbaa)가 있으면 그대로 붙인다.
1333
+ */
1334
+ function pickColor(which, hex) {
1335
+ const steps = [];
1336
+ for (const p of pickedShapes()) {
1337
+ if (which === 'fill' && p.shape === 'line') continue;
1338
+ const old = p[which];
1339
+ const value = typeof old === 'string' && old.length === 9 ? `${hex}${old.slice(7)}` : hex;
1340
+ if (value !== old) steps.push({ op: 'part.set', input: { part: p.id, [which]: value } });
1341
+ }
1342
+ return steps.length ? send(steps) : null;
1343
+ }
1344
+
1345
+ function saveColors() {
1346
+ const p = selection?.kind === 'part' ? partById.get(selection.part) : null;
1347
+ if (!p || p.kind !== 'shape') return null;
1348
+ const input = { part: p.id };
1349
+ const read = (v) => (v.trim().toLowerCase() === '' ? undefined : v.trim().toLowerCase());
1350
+ const fill = p.shape === 'line' ? undefined : read(colorDraft.fill);
1351
+ const stroke = read(colorDraft.stroke);
1352
+ for (const [k, v] of [['fill', fill], ['stroke', stroke]]) {
1353
+ if (v === undefined) continue;
1354
+ const next = v === 'none' || v === '없음' ? 'none' : v;
1355
+ if ((next === 'none' ? null : next) !== p[k]) input[k] = next;
1356
+ }
1357
+ if (Object.keys(input).length === 1) { toast(t('No color was changed'), true); return null; }
1358
+ return send([{ op: 'part.set', input }]);
1359
+ }
1360
+
1361
+ /** [이름 붙여 남기기]: 부품이면 그 부품의 이름을, 영역이나 점이면 이름표 node 를 남긴다(11.7절). */
1362
+ function saveName() {
1363
+ const s = selection;
1364
+ const name = nameDraft.text.trim();
1365
+ if (!s || s.kind === 'parts') return null;
1366
+ if (!name) { toast(t('Write a name to keep'), true); return null; }
1367
+ const done = (res) => { if (res) nameDraft = { key: null, text: '' }; render(); return res; };
1368
+ if (s.kind === 'part') return send([{ op: 'part.set', input: { part: s.part, name } }]).then(done);
1369
+ const input = s.kind === 'area' ? { name, use: 'label', region: { ...s.area } } : { name, use: 'label', point: { ...s.point } };
1370
+ return send([{ op: 'node.add', input }]).then(done);
1371
+ }
1372
+
1373
+ function removeNode(id) {
1374
+ if (focusNode === id) focusNode = null;
1375
+ return send([{ op: 'node.remove', input: { node: id } }]);
1376
+ }
1377
+
1378
+ async function shareSelection() {
1379
+ const sel = selection;
1380
+ if (!sel) return;
1381
+ const p = payloadOf(sel);
1382
+ const role = talk.role;
1383
+ const said = talk.said;
1384
+ try {
1385
+ const res = await call('shareSelection', { base: p.rev, role, said: said.trim(), payload: p, records: recordsOf(p) });
1386
+ if (!res?.ok) { toast(res?.summary ?? res?.error ?? t('Could not send the selection'), true); return; }
1387
+ sel.shared = { id: res.selection, role, said: said.trim() };
1388
+ // 선택을 보내면 코어가 이 화면의 고르기만 한 것을 지운다. 기다리는 사이 다른 것을 골랐으면 그것을 다시 알린다
1389
+ pickSent = null;
1390
+ if (selection !== sel) { notePick(); toast(t('Sent the earlier selection as {id}. What you selected now is not sent yet', { id: res.selection })); return; }
1391
+ if (talk.said === said) talk = { role: talk.role, said: '' };
1392
+ toast(said.trim() ? t('Sent selection {id} and your message to AI', { id: res.selection }) : t('Sent selection {id} to AI without a message', { id: res.selection }));
1393
+ render();
1394
+ } catch (err) {
1395
+ toast(err.message, true);
1396
+ }
1397
+ }
1398
+
1399
+ async function saveSvg() {
1400
+ try {
1401
+ const res = await call('saveOutput', { base: concept.base, format: 'svg' });
1402
+ if (res?.ok) toast(t('Saved: {file}', { file: res.fileName ?? res.artifact }));
1403
+ else toast(res?.summary ?? res?.error ?? t('Could not save'), true);
1404
+ } catch (err) {
1405
+ toast(err.message, true);
1406
+ }
1407
+ }
1408
+
1409
+ /** PNG 로 저장할 수 있는 크기들. 배수는 원래 크기의 몇 배인지, 긴 변은 가장 긴 변의 픽셀 수다. 코어가 받는 것은 16 부터 4096 까지다. */
1410
+ function pngOptions() {
1411
+ const c = data?.canvas;
1412
+ if (!c) return [];
1413
+ const side = Math.max(c.width, c.height);
1414
+ const out = [];
1415
+ for (const k of [1, 2, 4, 8]) {
1416
+ if (side * k < PNG_MIN || side * k > PNG_MAX) continue;
1417
+ const dims = { w: Math.round(c.width * k), h: Math.round(c.height * k), k };
1418
+ out.push({ value: `scale:${k}`, label: k === 1 ? t('{w}×{h} (original size)', dims) : t('{w}×{h} ({k}×)', dims), req: { scale: k } });
1419
+ }
1420
+ for (const n of [256, 512, 1024]) out.push({ value: `size:${n}`, label: t('long side {n}', { n }), req: { size: n } });
1421
+ return out;
1422
+ }
1423
+
1424
+ /** 처음 고를 크기. 작은 아이콘은 그대로 저장하면 너무 작아 긴 변 512 로, 큰 그림은 원래 크기로 한다. */
1425
+ function pngDefault(options) {
1426
+ const c = data.canvas;
1427
+ const want = Math.max(c.width, c.height) < 512 ? 'size:512' : 'scale:1';
1428
+ return (options.find((o) => o.value === want) ?? options[0])?.value ?? null;
1429
+ }
1430
+
1431
+ async function savePng() {
1432
+ const options = pngOptions();
1433
+ const pick = options.find((o) => o.value === pngChoice) ?? options.find((o) => o.value === pngDefault(options));
1434
+ if (!pick) return;
1435
+ try {
1436
+ const res = await call('saveOutput', { base: concept.base, format: 'png', ...pick.req });
1437
+ const file = res?.fileName ?? res?.artifact;
1438
+ if (res?.ok) toast(res.width && res.height ? t('Saved: {file} ({w}×{h})', { file, w: res.width, h: res.height }) : t('Saved: {file}', { file }));
1439
+ else toast(res?.summary ?? res?.error ?? t('Could not save'), true);
1440
+ } catch (err) {
1441
+ toast(err.message, true);
1442
+ }
1443
+ }
1444
+
1445
+ function startSample(s) {
1446
+ return send([{ op: 'canvas.start', input: { sample: s.id, reason: `The person chose sample ${s.id} (${s.title}) on the screen` } }]);
1447
+ }
1448
+
1449
+ function startBlank() {
1450
+ const side = data?.limits?.side ?? 4096;
1451
+ const w = Number(startDraft.width);
1452
+ const h = Number(startDraft.height);
1453
+ if (!Number.isInteger(w) || !Number.isInteger(h) || w < 1 || h < 1 || w > side || h > side) { toast(t('Write width and height as whole numbers from 1 to {side}', { side }), true); return null; }
1454
+ return send([{ op: 'canvas.start', input: { width: w, height: h, reason: `The person chose an empty picture ${w}×${h} on the screen` } }]);
1455
+ }
1456
+
1457
+ // ---- 화면 ----
1458
+
1459
+ function el(tag, props, ...children) {
1460
+ const n = document.createElement(tag);
1461
+ for (const [k, v] of Object.entries(props ?? {})) {
1462
+ if (k === 'class') n.className = v;
1463
+ else if (k === 'on') for (const [ev, fn] of Object.entries(v)) n.addEventListener(ev, fn);
1464
+ else if (k === 'value') n.value = v;
1465
+ else if (k === 'checked') n.checked = Boolean(v);
1466
+ else if (v !== false && v !== null && v !== undefined) n.setAttribute(k, v === true ? '' : v);
1467
+ }
1468
+ for (const c of children.flat(Infinity)) {
1469
+ if (c === null || c === undefined || c === false) continue;
1470
+ n.append(c instanceof Node ? c : String(c));
1471
+ }
1472
+ return n;
1473
+ }
1474
+ const btn = (label, onClick, extra = {}) => el('button', { type: 'button', class: 'btn', on: { click: onClick }, ...extra }, label);
1475
+ const setOn = (n, on) => (on ? n.removeAttribute('disabled') : n.setAttribute('disabled', ''));
1476
+
1477
+ // 위쪽 막대와 옆 칸의 틀은 한 번만 만들고, 다시 그릴 때는 안의 내용과 상태만 바꾼다. 쓰던 칸과 목록의 스크롤을 지키려는 것이다
1478
+ const bar = {};
1479
+ // 아이콘은 정해진 선 그림이다. 사람의 입력이 들어가지 않고, 겹쳐 보기와 같이 createElementNS 로 만든다(20×20)
1480
+ const ICONS = {
1481
+ select: ['M5 3v13l3.5-3.2 2.3 4.7 1.9-.9-2.3-4.6H15z'],
1482
+ point: ['M10 6.5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7z', 'M10 2v3M10 15v3M2 10h3M15 10h3'],
1483
+ move: ['M10 2v16M2 10h16', 'M7.5 4.5L10 2l2.5 2.5M7.5 15.5L10 18l2.5-2.5M4.5 7.5L2 10l2.5 2.5M15.5 7.5L18 10l-2.5 2.5'],
1484
+ pan: ['M6.5 10.5V5.2a1.2 1.2 0 0 1 2.4 0V9M8.9 9V3.9a1.2 1.2 0 0 1 2.4 0V9M11.3 9V4.8a1.2 1.2 0 0 1 2.4 0v5.2M13.7 10V7.2a1.2 1.2 0 0 1 2.4 0v5.3c0 3-2 5.5-5 5.5h-.8c-1.8 0-3-.8-4-2.3L3.7 12a1.2 1.2 0 0 1 2-1.3l.8 1.2'],
1485
+ fit: ['M3 7V3h4M13 3h4v4M17 13v4h-4M7 17H3v-4'],
1486
+ view: ['M2 10s3-5.5 8-5.5S18 10 18 10s-3 5.5-8 5.5S2 10 2 10z', 'M10 7.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5z'],
1487
+ save: ['M10 3v9M6.5 8.5L10 12l3.5-3.5M4 14v3h12v-3'],
1488
+ help: ['M10 2.5a7.5 7.5 0 1 0 0 15a7.5 7.5 0 1 0 0-15z', 'M7.8 8a2.2 2.2 0 1 1 3.3 1.9c-.7.4-1.1.9-1.1 1.7M10 14.3v.2'],
1489
+ side: ['M3 4h14v12H3z', 'M12.5 4v12'],
1490
+ };
1491
+ function icon(name) {
1492
+ const svg = svgEl('svg', { viewBox: '0 0 20 20', 'aria-hidden': 'true', focusable: 'false' });
1493
+ for (const d of ICONS[name]) svg.append(svgEl('path', { d }));
1494
+ return svg;
1495
+ }
1496
+ /** 아이콘 버튼. 이름은 읽어 주는 프로그램과 마우스를 올렸을 때의 글(title)에 둔다. */
1497
+ const iconBtn = (name, label, onClick, extra = {}) => el('button', { type: 'button', class: 'btn icon', 'aria-label': label, title: label, on: { click: onClick }, ...extra }, icon(name));
1498
+
1499
+ /** 위쪽 줄의 메뉴. 버튼을 누르면 그 아래에 열리고, 다른 곳을 누르거나 Esc 를 누르면 닫힌다. */
1500
+ function menu(key, name, label, items) {
1501
+ const panel = el('div', { class: 'menu', role: 'group', 'aria-label': t('{name} menu', { name: label }) }, el('h2', {}, label), items);
1502
+ panel.hidden = true;
1503
+ const b = iconBtn(name, label, () => setMenu(openMenu === key ? null : key), { 'aria-haspopup': 'true', 'aria-expanded': 'false' });
1504
+ bar.menus[key] = { b, panel };
1505
+ return el('div', { class: 'menuBox' }, b, panel);
1506
+ }
1507
+ function setMenu(key) {
1508
+ openMenu = key;
1509
+ for (const [k, m] of Object.entries(bar.menus)) {
1510
+ m.panel.hidden = k !== key;
1511
+ m.b.setAttribute('aria-expanded', k === key ? 'true' : 'false');
1512
+ }
1513
+ }
1514
+ window.addEventListener('pointerdown', (e) => {
1515
+ if (openMenu && !(e.target && typeof e.target.closest === 'function' && e.target.closest('.menuBox'))) setMenu(null);
1516
+ }, true);
1517
+
1518
+ function buildBar() {
1519
+ bar.tools = {};
1520
+ bar.menus = {};
1521
+ const tools = el('div', { class: 'group', role: 'group', 'aria-label': t('Tools') }, TOOLS.map((k) => (bar.tools[k] = iconBtn(k, toolName(k), () => setTool(k)))));
1522
+ bar.fill = el('input', { type: 'color', 'aria-label': t('Choose fill color'), on: { change: (e) => pickColor('fill', e.target.value) } });
1523
+ bar.stroke = el('input', { type: 'color', 'aria-label': t('Choose stroke color'), on: { change: (e) => pickColor('stroke', e.target.value) } });
1524
+ const colors = el('div', { class: 'group', role: 'group', 'aria-label': t('Color') }, el('label', { class: 'swatch' }, t('Fill'), bar.fill), el('label', { class: 'swatch' }, t('Stroke'), bar.stroke));
1525
+ bar.zoomText = el('span', { class: 'zoom' }, '100%');
1526
+ const zoom = el('div', { class: 'group', role: 'group', 'aria-label': t('Zoom') },
1527
+ btn('−', () => zoomAt(0.8), { class: 'btn icon', 'aria-label': t('Zoom out'), title: t('Zoom out') }), bar.zoomText, btn('+', () => zoomAt(1.25), { class: 'btn icon', 'aria-label': t('Zoom in'), title: t('Zoom in') }),
1528
+ iconBtn('fit', t('Fit to screen'), () => fit()));
1529
+ // 그림의 크기는 오른쪽 칸을 열지 않아도 보인다. 아이콘은 24, 32, 64 가운데 무엇을 고치는지가 늘 보여야 한다
1530
+ bar.size = el('span', { class: 'cap', 'aria-label': t('Picture size') }, '');
1531
+ bar.ro = el('span', { class: 'cap', title: t('This is a view-only screen. Buttons that make changes are off') }, t('View only'));
1532
+ bar.ro.hidden = true;
1533
+ bar.gridOn = el('input', { type: 'checkbox', on: { change: (e) => { grid.on = e.target.checked; updateBar(); drawOverlay(); } } });
1534
+ bar.gridRange = el('input', { id: 'gridRange', type: 'range', min: '0', max: '0', step: '1', 'aria-label': t('Piece grid level'), on: { input: (e) => { grid.level = Number(e.target.value); grid.on = true; updateBar(); drawOverlay(); } } });
1535
+ bar.gridText = el('span', { class: 'cap' }, '');
1536
+ bar.nodesOn = el('input', { type: 'checkbox', checked: showNodes, on: { change: (e) => { showNodes = e.target.checked; drawOverlay(); } } });
1537
+ const viewMenu = menu('view', 'view', t('View'),
1538
+ [el('div', { class: 'group', role: 'group', 'aria-label': t('Piece grid') }, el('label', { class: 'swatch' }, bar.gridOn, t('Piece grid')), bar.gridRange, bar.gridText),
1539
+ el('div', { class: 'group' }, el('label', { class: 'swatch' }, bar.nodesOn, t('Show nodes')))]);
1540
+ bar.save = btn(t('Save as SVG file'), () => { setMenu(null); saveSvg(); });
1541
+ bar.saveWhy = el('span', { class: 'reason' }, '');
1542
+ // PNG 는 코어가 SVG 를 그려 만든다. 코어가 png 를 밝힐 때만 보인다(capabilities 의 output)
1543
+ bar.pngSize = el('select', { 'aria-label': t('PNG size'), on: { change: (e) => { pngChoice = e.target.value; } } });
1544
+ bar.png = el('div', { class: 'group', role: 'group', 'aria-label': t('Save as PNG') }, bar.pngSize, btn(t('Save as PNG'), () => { setMenu(null); savePng(); }, { title: t('Saves the picture as it is now as a PNG file at the chosen size. Empty areas are transparent') }));
1545
+ const save = menu('save', 'save', t('Save'), [el('div', { class: 'group' }, bar.save), bar.saveWhy, bar.png]);
1546
+ bar.help = iconBtn('help', t('Tool help'), () => { helpOn = !helpOn; updateBar(); }, { 'aria-pressed': 'false' });
1547
+ bar.side = iconBtn('side', t('Parts and info'), () => setSide(!sideOpen), { 'aria-pressed': 'false', 'aria-controls': 'side' });
1548
+ barEl.replaceChildren(tools, colors, zoom, bar.size, el('span', { class: 'spacer' }), bar.ro, viewMenu, save, bar.help, bar.side);
1549
+ }
1550
+
1551
+ /** 오른쪽 칸(고른 것, 이름, 색, 부품 목록, node 목록)을 열거나 닫는다. 그림을 고른다고 저절로 열리지 않는다. */
1552
+ function setSide(on) {
1553
+ sideOpen = Boolean(on);
1554
+ sideEl.hidden = !sideOpen;
1555
+ mainEl.setAttribute('data-side', sideOpen ? 'open' : 'closed');
1556
+ updateBar();
1557
+ if (!sideOpen || !data?.canvas) return;
1558
+ // 숨긴 사이에는 목록을 내리지 못했으므로, 열 때 고른 부품의 줄까지 내린다
1559
+ const picked = pickedIds();
1560
+ if (picked.length) revealRow(picked[picked.length - 1]);
1561
+ renderRows(true);
1562
+ }
1563
+
1564
+ function setTool(k) {
1565
+ if (k === 'move' && readOnly()) return;
1566
+ tool = k;
1567
+ stage.setAttribute('data-tool', k);
1568
+ updateBar();
1569
+ }
1570
+
1571
+ function updateBar() {
1572
+ const ro = readOnly();
1573
+ if (ro && tool === 'move') { tool = 'select'; stage.setAttribute('data-tool', tool); }
1574
+ for (const [k, b] of Object.entries(bar.tools)) {
1575
+ b.setAttribute('aria-pressed', k === tool ? 'true' : 'false');
1576
+ // 도구의 설명은 마우스를 올렸을 때 보인다. 늘 보고 싶으면 [도구 설명] 을 켠다
1577
+ b.setAttribute('title', `${toolName(k)}: ${k === 'move' && ro ? t('Parts cannot be moved on a view-only screen.') : toolHelp(k)}`);
1578
+ if (k === 'move') setOn(b, !ro);
1579
+ }
1580
+ bar.ro.hidden = !ro;
1581
+ const cv = data?.canvas;
1582
+ bar.size.textContent = cv ? `${cv.width}×${cv.height}` : '';
1583
+ bar.size.setAttribute('title', cv ? t('Picture size {size}, {parts}, {nodes}', { size: `${cv.width}×${cv.height}`, parts: partCount(data.parts.length), nodes: nodeCount((data.nodes ?? []).length) }) : '');
1584
+ bar.help.setAttribute('aria-pressed', helpOn ? 'true' : 'false');
1585
+ bar.help.setAttribute('title', helpOn ? t('Hide tool help') : t('Show tool help'));
1586
+ bar.side.setAttribute('aria-pressed', sideOpen ? 'true' : 'false');
1587
+ bar.side.setAttribute('title', sideOpen ? t('Hide parts and info') : t('Show parts and info (selection, naming, color, parts, nodes)'));
1588
+ stageNote.hidden = !helpOn;
1589
+ if (helpOn) stageNote.textContent = noteText();
1590
+ // 색 칸은 고른 도형 모두에 적용한다. 여럿이면 칸의 색은 그 가운데 첫 도형의 색이다
1591
+ const picked = pickedIds().length;
1592
+ const shapes = pickedShapes();
1593
+ const fillable = shapes.filter((p) => p.shape !== 'line');
1594
+ const why = ro ? t('Colors cannot be changed on a view-only screen') : !picked ? t('Select a shape to change its color') : !shapes.length ? t('Groups have no color. Select a shape inside') : '';
1595
+ setOn(bar.fill, fillable.length > 0 && !ro);
1596
+ setOn(bar.stroke, shapes.length > 0 && !ro);
1597
+ bar.fill.setAttribute('title', why || (!fillable.length ? t('Lines have no fill') : shapes.length > 1 ? tn(fillable.length, 'Changes the fill of {n} selected shape together', 'Changes the fill of {n} selected shapes together') : t('Fill {color}', { color: shapes[0].fill ?? t('none') })));
1598
+ bar.stroke.setAttribute('title', why || (shapes.length > 1 ? tn(shapes.length, 'Changes the stroke color of {n} selected shape together', 'Changes the stroke color of {n} selected shapes together') : t('Stroke {color}', { color: shapes[0].stroke ?? t('none') })));
1599
+ bar.fill.value = fullHex(fillable[0]?.fill) ?? '#ffffff';
1600
+ bar.stroke.value = fullHex(shapes[0]?.stroke) ?? '#000000';
1601
+ const depth = data?.canvas?.depth ?? 0;
1602
+ bar.gridOn.checked = grid.on;
1603
+ bar.gridRange.setAttribute('max', String(depth));
1604
+ bar.gridRange.value = String(grid.level);
1605
+ setOn(bar.gridRange, depth > 0);
1606
+ bar.gridText.textContent = grid.on ? t('level {level} / {depth}', { level: grid.level, depth }) : t('off, levels 0 to {depth}', { depth });
1607
+ const canSave = Boolean(data?.canvas) && Array.isArray(caps.output) && caps.output.includes('svg');
1608
+ setOn(bar.save, canSave);
1609
+ const saveWhy = canSave ? '' : !data?.canvas ? t('Start a picture before saving') : t('This core version cannot save SVG files yet');
1610
+ bar.save.setAttribute('title', canSave ? t('Saves the picture as it is now as an SVG file') : saveWhy);
1611
+ bar.saveWhy.textContent = saveWhy;
1612
+ const canPng = Boolean(data?.canvas) && Array.isArray(caps.output) && caps.output.includes('png');
1613
+ bar.png.hidden = !canPng;
1614
+ if (canPng) {
1615
+ // 크기 목록은 그림 크기에 따라 달라진다. 고른 것이 목록에 없으면(다른 그림) 처음 고를 크기로 돌린다
1616
+ const options = pngOptions();
1617
+ if (!options.some((o) => o.value === pngChoice)) pngChoice = pngDefault(options);
1618
+ const key = options.map((o) => o.label).join('|');
1619
+ if (bar.pngSize.getAttribute('data-key') !== key) {
1620
+ bar.pngSize.setAttribute('data-key', key);
1621
+ bar.pngSize.replaceChildren(...options.map((o) => el('option', { value: o.value }, o.label)));
1622
+ }
1623
+ bar.pngSize.value = pngChoice;
1624
+ }
1625
+ }
1626
+
1627
+ // 도구의 이름과 설명. 언어가 정해진 뒤에 부르므로 표가 아니라 함수다
1628
+ function toolName(k) {
1629
+ switch (k) {
1630
+ case 'select': return t('Select');
1631
+ case 'point': return t('Point');
1632
+ case 'move': return t('Move parts');
1633
+ case 'pan': return t('Pan');
1634
+ default: return k;
1635
+ }
1636
+ }
1637
+ function toolHelp(k) {
1638
+ switch (k) {
1639
+ case 'select': return t('Click a part to select its outermost group first. Click the same spot again to go one level inside. Hold Shift and click to select several together. Drag to select an area.');
1640
+ case 'point': return t('Click a spot to select that point and the parts that overlap there.');
1641
+ case 'move': return t('Drag a selected part or group to move it. If you selected several, they move together. Drag a spot you did not select to move the outermost group there.');
1642
+ case 'pan': return t('Drag to move the view.');
1643
+ default: return '';
1644
+ }
1645
+ }
1646
+
1647
+ /** [도구 설명] 을 켰을 때 그림 아래에 보이는 글. 지금 도구가 하는 일, 화면을 옮기는 법, 고른 것을 AI 가 아는 방법이다. */
1648
+ function noteText() {
1649
+ const common = t('Use the wheel to zoom in and out. Hold Space or the middle mouse button and drag to move the view with any tool. Press Esc to clear the selection.');
1650
+ const share = caps.edit === false ? t('On a view-only screen, the selection is not sent to AI.')
1651
+ : !caps.conceptSelection ? t('This host cannot receive selections from a concept screen yet.')
1652
+ : `${t('When you select something, a send box appears over the picture.')} ${caps.conceptPick ? t('Even if you only select, AI reads it when you talk in the chat. To tell a waiting AI right away, send it from that box.') : t('Selecting alone does not tell AI. Send it from that box.')}`;
1653
+ return `${toolName(tool)}: ${toolHelp(tool)} ${common} ${share}`;
1654
+ }
1655
+
1656
+ const sec = {};
1657
+ function buildSide() {
1658
+ for (const k of ['info', 'sel', 'name', 'color', 'parts', 'nodes']) sec[k] = el('section', { 'data-sec': k });
1659
+ sec.partsHead = el('h2', {}, t('Parts'));
1660
+ sec.tree = el('div', { class: 'tree', role: 'tree', 'aria-label': t('Parts'), 'aria-multiselectable': 'true', on: { scroll: () => renderRows() } });
1661
+ sec.treeSpacer = el('div', {});
1662
+ sec.treeRows = el('div', {});
1663
+ sec.tree.append(sec.treeSpacer, sec.treeRows);
1664
+ sec.parts.append(sec.partsHead, el('p', { class: 'note' }, t('What is drawn on top comes first. Click to select a part. Hold Shift and click to add it to the selection or remove it.')), sec.tree);
1665
+ sideEl.replaceChildren(sec.info, sec.sel, sec.name, sec.color, sec.parts, sec.nodes);
1666
+ }
1667
+
1668
+ /** 옆 칸과 보내는 칸을 다시 그릴 때 쓰던 칸(data-keep)의 초점과 커서를 지킨다(plugin-guide 4.7절). */
1669
+ function keepFocus(fn) {
1670
+ const a = document.activeElement;
1671
+ const key = a && typeof a.getAttribute === 'function' ? a.getAttribute('data-keep') : null;
1672
+ const range = key && typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd] : null;
1673
+ fn();
1674
+ if (!key) return;
1675
+ const b = document.querySelector(`[data-keep="${key}"]`);
1676
+ if (!b || b === a) return;
1677
+ b.focus();
1678
+ if (range && b.setSelectionRange) try { b.setSelectionRange(range[0], range[1]); } catch {}
1679
+ }
1680
+
1681
+ const fillSec = (n, parts) => {
1682
+ const list = (Array.isArray(parts) ? parts : [parts]).filter(Boolean);
1683
+ n.hidden = list.length === 0;
1684
+ n.replaceChildren(...list);
1685
+ };
1686
+
1687
+ function infoParts() {
1688
+ const c = data.canvas;
1689
+ const shapes = data.parts.filter((p) => p.kind === 'shape').length;
1690
+ // 샘플 제목과 그림의 reason 은 논리가 준 글이라 그대로 보인다
1691
+ const src = c.source ? t('Sample {title} ({id}) version {version}', { title: c.source.title, id: c.source.sample, version: c.source.version }) : t('Empty picture');
1692
+ return [
1693
+ el('h2', {}, t('Picture')),
1694
+ el('dl', { class: 'kv' },
1695
+ el('dt', {}, t('Started from')), el('dd', {}, src),
1696
+ el('dt', {}, t('Size')), el('dd', {}, t('{size}, piece levels 0 to {depth}', { size: `${c.width}×${c.height}`, depth: c.depth })),
1697
+ el('dt', {}, t('Parts')), el('dd', {}, t('{n} ({shapes}, {groups}), {nodes}', { n: data.parts.length, shapes: shapeCount(shapes), groups: groupCount(data.parts.length - shapes), nodes: nodeCount(data.nodes.length) })),
1698
+ el('dt', {}, t('Reason')), el('dd', {}, c.reason)),
1699
+ readOnly() ? el('p', { class: 'note' }, t('This is a view-only screen. Buttons that make changes are off.')) : null,
1700
+ ];
1701
+ }
1702
+
1703
+ const chip = (id, current) => {
1704
+ const p = partById.get(id);
1705
+ return el('button', { type: 'button', class: 'chip', 'aria-current': current ? 'true' : 'false', on: { click: () => { selectPart(id, selection?.hit); } } }, p ? (p.name || `${shownWord(p)} ${id}`) : id);
1706
+ };
1707
+
1708
+ function placeText(pl) {
1709
+ const out = [];
1710
+ if (pl.move[0] !== 0 || pl.move[1] !== 0) out.push(t('move ({x}, {y})', { x: num(pl.move[0]), y: num(pl.move[1]) }));
1711
+ if (pl.rotate !== 0) out.push(t('rotate {deg} degrees', { deg: num(pl.rotate) }));
1712
+ if (pl.scale[0] !== 1 || pl.scale[1] !== 1) out.push(pl.scale[0] === pl.scale[1] ? t('scale {k}', { k: num(pl.scale[0]) }) : t('scale {x} across, {y} down', { x: num(pl.scale[0]), y: num(pl.scale[1]) }));
1713
+ return out.join(', ');
1714
+ }
1715
+
1716
+ function selParts() {
1717
+ const s = selection;
1718
+ if (!s) {
1719
+ return [el('h2', {}, t('Selection')),
1720
+ el('p', {}, t('Click a part in the picture to select it, or drag to select an area. With the Point tool, click a spot to select a point.')),
1721
+ el('p', { class: 'note' }, t('Hold Shift and click to select several together. With the keyboard, select from the Parts list below. Press Esc to clear the selection.'))];
1722
+ }
1723
+ if (s.kind === 'parts') {
1724
+ const all = s.list.map((id) => partById.get(id)).filter(Boolean);
1725
+ const box = all.reduce((u, p) => (!p.box ? u : !u ? { ...p.box } : { x: Math.min(u.x, p.box.x), y: Math.min(u.y, p.box.y), w: Math.max(u.x + u.w, p.box.x + p.box.w) - Math.min(u.x, p.box.x), h: Math.max(u.y + u.h, p.box.y + p.box.h) - Math.min(u.y, p.box.y) }), null);
1726
+ const groups = all.filter((p) => p.kind === 'group').length;
1727
+ const inside = box && containsRect(pieceRectOf('q'), box);
1728
+ return [el('h2', {}, tn(all.length, '{n} part selected together', '{n} parts selected together')),
1729
+ el('dl', { class: 'kv' },
1730
+ el('dt', {}, t('Kind')), el('dd', {}, groups ? `${shapeCount(all.length - groups)}, ${groupCount(groups)}` : shapeCount(all.length)),
1731
+ el('dt', {}, t('Area')), el('dd', {}, boxText(box)),
1732
+ el('dt', {}, t('Piece')), el('dd', {}, inside ? t('{piece} holds all the selected parts', { piece: smallestPiece(box) }) : t('It goes outside the picture, so no piece holds it whole'))),
1733
+ el('div', { class: 'crumbs' }, el('span', { class: 'note' }, t('Click to remove')),
1734
+ all.slice(0, MAX_CHIPS).map((p) => el('button', { type: 'button', class: 'chip', 'aria-label': t('Remove {name}', { name: titleOf(p) }), title: t('Click to remove it from the selection'), on: { click: () => togglePart(p.id, p.id) } }, p.name || `${shownWord(p)} ${p.id}`)),
1735
+ all.length > MAX_CHIPS ? el('span', { class: 'note' }, t('and {n} more', { n: all.length - MAX_CHIPS })) : null),
1736
+ el('p', { class: 'note' }, readOnly() ? t('Hold Shift and click to add or remove.') : t('Hold Shift and click to add or remove. Drag with [Move parts] to move them together. The color boxes at the top apply to all selected shapes. To give names, select one at a time.'))];
1737
+ }
1738
+ if (s.kind === 'part') {
1739
+ const p = partById.get(s.part);
1740
+ const pl = placeText(p.place);
1741
+ const fill = p.fill ?? t('none');
1742
+ const out = [el('h2', {}, p.kind === 'group' ? t('Selected group') : t('Selected part')),
1743
+ el('dl', { class: 'kv' },
1744
+ el('dt', {}, t('Part')), el('dd', {}, titleOf(p)),
1745
+ el('dt', {}, t('Kind')), el('dd', {}, p.kind === 'group' ? tn(p.children?.length ?? 0, 'group, {n} part inside', 'group, {n} parts inside') : shapeWord(p.shape)),
1746
+ el('dt', {}, t('Area')), el('dd', {}, boxText(p.box)),
1747
+ el('dt', {}, t('Piece')), el('dd', {}, p.piece ? t('fits whole in {piece}', { piece: p.piece }) : t('It goes outside the picture, so no piece holds it whole')),
1748
+ pl ? [el('dt', {}, t('Placement')), el('dd', {}, pl)] : null,
1749
+ p.kind === 'shape' ? [el('dt', {}, t('Color')), el('dd', {}, p.stroke ? t('fill {fill}, stroke {stroke} width {width}', { fill, stroke: p.stroke, width: num(p.strokeWidth) }) : t('fill {fill}, stroke none', { fill }))] : null)];
1750
+ const chain = chainOf(s.hit).reverse();
1751
+ if (chain.length > 1) {
1752
+ out.push(el('div', { class: 'crumbs' }, el('span', { class: 'note' }, t('Outside to inside')), chain.map((id) => chip(id, id === s.part))));
1753
+ out.push(el('p', { class: 'note' }, s.part === s.hit ? t('This is the innermost part. Click a group above to select that group.') : t('Click the same spot again to go one level inside.')));
1754
+ }
1755
+ return out;
1756
+ }
1757
+ const list = s.parts;
1758
+ const chips = list.length ? el('div', { class: 'crumbs' }, list.slice(0, MAX_CHIPS).map((id) => chip(id, false)), list.length > MAX_CHIPS ? el('span', { class: 'note' }, t('and {n} more', { n: list.length - MAX_CHIPS })) : null) : null;
1759
+ if (s.kind === 'area') {
1760
+ return [el('h2', {}, t('Selected area')),
1761
+ el('dl', { class: 'kv' },
1762
+ el('dt', {}, t('Area')), el('dd', {}, boxText(s.area)),
1763
+ el('dt', {}, t('Piece')), el('dd', {}, t('{piece} holds this whole area', { piece: smallestPiece(s.area) })),
1764
+ el('dt', {}, t('Shapes over it')), el('dd', {}, list.length ? t('{n}, bottom first', { n: list.length }) : t('none (empty)'))),
1765
+ chips];
1766
+ }
1767
+ return [el('h2', {}, t('Selected point')),
1768
+ el('dl', { class: 'kv' },
1769
+ el('dt', {}, t('Point')), el('dd', {}, `${num(s.point.x)}, ${num(s.point.y)}`),
1770
+ el('dt', {}, t('Piece')), el('dd', {}, deepestPiece(s.point.x, s.point.y) ?? t('none')),
1771
+ el('dt', {}, t('Shapes there')), el('dd', {}, list.length ? t('{n}, top first', { n: list.length }) : t('none (empty)'))),
1772
+ chips];
1773
+ }
1774
+
1775
+ /** 고른 것을 한 줄로. 보내는 칸이 무엇을 보내는지 말할 때 쓴다. */
1776
+ function selText(s) {
1777
+ if (s.kind === 'part') { const p = partById.get(s.part); return p ? titleOf(p) : s.part; }
1778
+ if (s.kind === 'parts') {
1779
+ const names = s.list.slice(0, MAX_TALK_NAMES).map((id) => { const p = partById.get(id); return p ? titleOf(p) : id; });
1780
+ const more = s.list.length > MAX_TALK_NAMES ? ` ${t('and {n} more', { n: s.list.length - MAX_TALK_NAMES })}` : '';
1781
+ return t('{parts} ({names})', { parts: partCount(s.list.length), names: `${names.join(', ')}${more}` });
1782
+ }
1783
+ if (s.kind === 'area') return t('area {box}', { box: boxText(s.area) });
1784
+ return t('point {x}, {y}', { x: num(s.point.x), y: num(s.point.y) });
1785
+ }
1786
+
1787
+ // 고른 것을 AI 에게 보내는 칸. 고르기만 한 것은 AI 가 읽을 수는 있어도(setPick) AI 를 깨우지 않고 기록에도 남지 않으므로,
1788
+ // 고른 것이 있는 동안 그림 칸 위에 띄워 두고 아직 보내지 않았으면 그렇다고 말한다. 옛 호스트(conceptPick 없음)에서는 고르기만
1789
+ // 해서는 AI 가 알지 못한다고 적는다. 말은 비워도 보낸다(코어는 말 없는 선택을 받는다). 고른 것이 없으면 칸을 숨긴다(rawdev 2026-11-24)
1790
+ function renderTalk() {
1791
+ const s = selection;
1792
+ const can = canShare();
1793
+ // 고른 것이 없으면 칸을 숨긴다. 보낼 수 없는 화면(보기만 하는 화면, 선택을 받지 못하는 옛 호스트)에서도 띄우지 않는다.
1794
+ // 고르는 법, 보내는 법, 보내지 못하는 이유는 [도구 설명] 에 있고, 무엇을 골랐는지는 그림 위의 이름표가 말한다
1795
+ talkEl.hidden = !s || !can;
1796
+ if (!s || !can) { talkEl.replaceChildren(); talkEl.classList.toggle('unsent', false); return; }
1797
+ if (talkPlaced !== s.gen) { talkPlaced = s.gen; talkEl.setAttribute('data-at', talkAt(s)); }
1798
+ const said = el('input', { type: 'text', 'data-keep': 'said', 'aria-label': t('Message about this selection'), placeholder: t('For example: make only this red. You can also send it empty'), value: talk.said,
1799
+ on: { input: (e) => { talk.said = e.target.value; }, keydown: (e) => { if (e.key === 'Enter' && !e.isComposing && selection) shareSelection(); } } });
1800
+ const role = el('select', { 'aria-label': t('Role of the selection'), on: { change: (e) => { talk.role = e.target.value; } } },
1801
+ el('option', { value: 'change', ...(talk.role === 'change' ? { selected: true } : {}) }, t('To change')),
1802
+ el('option', { value: 'reference', ...(talk.role === 'reference' ? { selected: true } : {}) }, t('For reference')));
1803
+ let state;
1804
+ if (s.shared) {
1805
+ const rest = s.shared.said ? t('{sel}, message "{said}". AI reads this selection and works on it.', { sel: selText(s), said: s.shared.said }) : t('{sel}, no message. AI reads this selection and works on it.', { sel: selText(s) });
1806
+ state = el('p', { class: 'state' }, el('span', { class: 'done' }, t('Sent to AI (selection {id})', { id: s.shared.id })), ` ${rest}`);
1807
+ } else state = el('p', { class: 'state' }, el('b', {}, t('Selection: {sel}', { sel: selText(s) })), ' ', caps.conceptPick ? t('AI reads this when you talk in the chat. To tell a waiting AI right away, click [Send to AI]. The message can be empty.') : [el('span', { class: 'warn' }, t('Not sent to AI yet.')), ` ${t('The message can be empty.')}`]);
1808
+ // 고르기만 한 것을 AI 가 읽지 못하는 옛 호스트에서만 보내지 않은 것을 진한 테두리로 알린다
1809
+ talkEl.classList.toggle('unsent', !s.shared && !caps.conceptPick);
1810
+ talkEl.replaceChildren(state, el('div', { class: 'line' }, role, said,
1811
+ btn(t('Send to AI'), shareSelection, { class: 'btn primary', title: t('Sends the selection and your message to AI. The message can be empty') }),
1812
+ btn('×', () => setSelection(null), { class: 'btn icon', 'aria-label': t('Clear selection'), title: t('Clears the selection (Esc)') })));
1813
+ }
1814
+
1815
+ /** 보내는 칸을 띄울 곳. 보통 위(top)이고, 고른 것이 그림 칸의 위쪽에 있어 가려지면 아래(bottom)다. 고를 때 한 번만 정한다. */
1816
+ function talkAt(s) {
1817
+ const { h } = stageSize();
1818
+ const boxes = s.kind === 'area' ? [s.area] : s.kind === 'point' ? [{ x: s.point.x, y: s.point.y, w: 0, h: 0 }] : pickedIds().map((id) => partById.get(id)?.box).filter(Boolean);
1819
+ if (!boxes.length || !(h > 0)) return 'top';
1820
+ const top = Math.min(...boxes.map((b) => sy(b.y)));
1821
+ const bottom = Math.max(...boxes.map((b) => sy(b.y + b.h)));
1822
+ return top < TALK_ZONE && bottom <= h - TALK_ZONE ? 'bottom' : 'top';
1823
+ }
1824
+
1825
+ function nameParts() {
1826
+ const s = selection;
1827
+ if (!s || s.kind === 'parts' || readOnly()) return [];
1828
+ const key = s.kind === 'part' ? `part:${s.part}` : `${s.kind}:${s.gen}`;
1829
+ if (nameDraft.key !== key) nameDraft = { key, text: s.kind === 'part' ? partById.get(s.part)?.name ?? '' : '' };
1830
+ const input = el('input', { type: 'text', 'data-keep': 'name', 'aria-label': t('Name to keep'), placeholder: s.kind === 'part' ? t('Part name') : t('For example: left eye'), value: nameDraft.text,
1831
+ on: { input: (e) => { nameDraft.text = e.target.value; }, keydown: (e) => { if (e.key === 'Enter' && !e.isComposing) saveName(); } } });
1832
+ return [el('h2', {}, t('Name and keep')),
1833
+ el('div', { class: 'form' }, input, btn(t('Name and keep'), saveName)),
1834
+ el('p', { class: 'note' }, s.kind === 'part' ? t('This renames the part. Parts do not get a separate node.') : s.kind === 'area' ? t('This keeps the area as a label node.') : t('This keeps the point as a label node.'))];
1835
+ }
1836
+
1837
+ function colorParts() {
1838
+ const s = selection;
1839
+ const p = s?.kind === 'part' ? partById.get(s.part) : null;
1840
+ if (!p || p.kind !== 'shape' || readOnly()) return [];
1841
+ const key = `${p.id}:${p.fill}:${p.stroke}`;
1842
+ if (colorDraft.key !== key) colorDraft = { key, fill: p.fill ?? 'none', stroke: p.stroke ?? 'none' };
1843
+ const field = (which, label) => el('label', {}, el('span', {}, label), el('input', { type: 'text', 'data-keep': which, 'aria-label': label, value: colorDraft[which], disabled: which === 'fill' && p.shape === 'line',
1844
+ on: { input: (e) => { colorDraft[which] = e.target.value; }, keydown: (e) => { if (e.key === 'Enter' && !e.isComposing) saveColors(); } } }));
1845
+ return [el('h2', {}, t('Color')),
1846
+ el('div', { class: 'form' }, el('div', { class: 'row2' }, field('fill', t('Fill color')), field('stroke', t('Stroke color'))), btn(t('Change color'), saveColors)),
1847
+ el('p', { class: 'note' }, p.shape === 'line' ? t('Lines have no fill. Write a color like #rrggbb, or write none to remove it.') : t('Write a color like #rrggbb, or write none to remove it. You can also pick one in the color boxes at the top.'))];
1848
+ }
1849
+
1850
+ // 부품 목록: 묶음 트리. 같은 묶음 안에서는 위에 그려진 것(그리는 차례가 뒤인 것)이 위에 온다
1851
+ function treeRows() {
1852
+ const out = [];
1853
+ const walk = (ids, depth) => {
1854
+ for (let i = ids.length - 1; i >= 0; i -= 1) {
1855
+ const p = partById.get(ids[i]);
1856
+ if (!p) continue;
1857
+ const group = p.kind === 'group';
1858
+ const open = group && !collapsed.has(p.id);
1859
+ out.push({ p, depth, group, open });
1860
+ if (open) walk(p.children ?? [], depth + 1);
1861
+ }
1862
+ };
1863
+ walk(roots.map((p) => p.id), 0);
1864
+ return out;
1865
+ }
1866
+
1867
+ let rowsCache = null;
1868
+ function renderRows(rebuild = false) {
1869
+ if (!data?.canvas) return;
1870
+ if (rebuild || !rowsCache) rowsCache = treeRows();
1871
+ const rows = rowsCache;
1872
+ sec.treeSpacer.style.height = `${rows.length * ROW_H}px`;
1873
+ const top = sec.tree.scrollTop || 0;
1874
+ const height = sec.tree.clientHeight || 320;
1875
+ const first = Math.max(0, Math.floor(top / ROW_H) - 4);
1876
+ const last = Math.min(rows.length, Math.ceil((top + height) / ROW_H) + 4);
1877
+ const picked = new Set(pickedIds());
1878
+ const out = [];
1879
+ for (let i = first; i < last; i += 1) {
1880
+ const { p, depth, group, open } = rows[i];
1881
+ const paint = p.kind === 'shape' ? (p.fill ?? p.stroke) : null;
1882
+ const dot = el('span', { class: 'dot' });
1883
+ if (paint && COLOR.test(paint)) dot.style.background = paint;
1884
+ else dot.style.visibility = 'hidden';
1885
+ out.push(el('div', { class: `row${picked.has(p.id) ? ' current' : ''}`, role: 'treeitem', 'aria-level': String(depth + 1), 'aria-selected': picked.has(p.id) ? 'true' : 'false', ...(group ? { 'aria-expanded': open ? 'true' : 'false' } : {}), style: `top:${i * ROW_H}px;padding-left:${4 + depth * 14}px` },
1886
+ group ? el('button', { type: 'button', class: 'toggle', 'aria-label': open ? t('Collapse {name}', { name: p.name || t('group') }) : t('Expand {name}', { name: p.name || t('group') }), 'aria-expanded': open ? 'true' : 'false', on: { click: () => toggleGroup(p.id) } }) : el('span', { class: 'gap' }),
1887
+ dot,
1888
+ el('button', { type: 'button', class: 'pick', 'data-part': p.id, on: { click: (e) => { if (addKey(e)) togglePart(p.id, p.id); else selectPart(p.id, p.id); } } }, p.name || shownWord(p), el('span', { class: 'id' }, p.id))));
1889
+ }
1890
+ sec.treeRows.replaceChildren(...out);
1891
+ }
1892
+
1893
+ function toggleGroup(id) {
1894
+ if (collapsed.has(id)) collapsed.delete(id);
1895
+ else collapsed.add(id);
1896
+ renderRows(true);
1897
+ }
1898
+
1899
+ /** 고른 부품이 목록에 보이게 감싼 묶음을 펼치고 그 줄까지 내린다. */
1900
+ function revealRow(id) {
1901
+ for (const g of chainOf(id).slice(1)) collapsed.delete(g);
1902
+ rowsCache = treeRows();
1903
+ const i = rowsCache.findIndex((r) => r.p.id === id);
1904
+ if (i < 0) return;
1905
+ const top = sec.tree.scrollTop || 0;
1906
+ const height = sec.tree.clientHeight || 320;
1907
+ if (i * ROW_H < top || (i + 1) * ROW_H > top + height) sec.tree.scrollTop = Math.max(0, i * ROW_H - height / 2);
1908
+ }
1909
+
1910
+ function nodeParts() {
1911
+ const list = data.nodes ?? [];
1912
+ const ro = readOnly();
1913
+ return [el('h2', {}, t('Nodes ({n})', { n: list.length })),
1914
+ list.length === 0 ? el('p', { class: 'note' }, t('No nodes yet. Select an area or a point and give it a name to keep it. Places AI recognized and shapes it set as targets for a change also appear here.')) : null,
1915
+ list.length ? el('ul', { class: 'nodes' }, list.map((nd) => el('li', {},
1916
+ el('button', { type: 'button', class: 'pick', 'aria-current': nd.id === focusNode ? 'true' : 'false', on: { click: () => showNode(nd.id) } },
1917
+ el('span', { class: `use ${nd.use === 'goal' ? 'goal' : 'label'}` }, useWord(nd.use)), ' ', nd.name, el('span', { class: 'id' }, `${nd.id}, ${atText(nd.at)}`)),
1918
+ ro ? null : btn(t('Delete'), () => removeNode(nd.id), { class: 'btn small', 'aria-label': t('Delete node {name}', { name: nd.name }) })))) : null];
1919
+ }
1920
+
1921
+ /** node 의 쓰임(label, goal)을 화면에 보이는 낱말로. */
1922
+ function useWord(use) {
1923
+ if (use === 'label') return t('Label');
1924
+ if (use === 'goal') return t('Target shape');
1925
+ return use;
1926
+ }
1927
+
1928
+ /** node 목록에서 누른 node 가 있는 곳을 칸에 보이고 굵게 표시한다. */
1929
+ function showNode(id) {
1930
+ const nd = (data.nodes ?? []).find((x) => x.id === id);
1931
+ if (!nd) return;
1932
+ focusNode = id;
1933
+ if (!showNodes) { showNodes = true; bar.nodesOn.checked = true; }
1934
+ const at = nd.at;
1935
+ if (at.kind === 'point') showRect({ x: at.x, y: at.y, w: 0, h: 0 }, true);
1936
+ else showRect(at.kind === 'region' ? at : pieceRectOf(at.piece));
1937
+ render();
1938
+ }
1939
+
1940
+ function renderStart() {
1941
+ const ro = readOnly();
1942
+ const side = data?.limits?.side ?? 4096;
1943
+ const samples = (data?.samples ?? []).map((s) => el('div', { class: 'card' },
1944
+ el('h3', {}, s.title),
1945
+ el('p', {}, s.about),
1946
+ el('p', { class: 'note' }, t('{size}, {parts}, sample id {id}, version {version}', { size: `${s.width}×${s.height}`, parts: partCount(s.parts), id: s.id, version: s.version })),
1947
+ ro ? null : btn(t('Start with this sample'), () => startSample(s), { class: 'btn primary' })));
1948
+ const size = (k, label) => el('label', {}, el('span', {}, label), el('input', { type: 'number', min: '1', max: String(side), step: '1', 'aria-label': label, value: startDraft[k], on: { input: (e) => { startDraft[k] = e.target.value; } } }));
1949
+ const blank = el('div', { class: 'card' },
1950
+ el('h3', {}, t('Empty picture')),
1951
+ el('p', {}, t('Start from an empty picture and ask AI to draw. Icons are usually 24, 32, or 64.')),
1952
+ ro ? null : el('div', { class: 'form' }, el('div', { class: 'row2' }, size('width', t('Width')), size('height', t('Height')))),
1953
+ el('p', { class: 'note' }, t('The size can be 1 to {side}. It does not change after you start. Pieces split this size into four, level by level.', { side })),
1954
+ ro ? null : btn(t('Start with an empty picture'), startBlank, { class: 'btn primary' }));
1955
+ startEl.replaceChildren(
1956
+ el('h2', {}, t('Start a picture')),
1957
+ el('p', { class: 'lead' }, ro ? t('There is no picture yet. This is a view-only screen, so you cannot start one here.') : t('There is no picture yet. Choose a built-in sample, or set the size of an empty picture, to start. You can also ask AI to start one.')),
1958
+ el('div', { class: 'cards' }, samples, blank));
1959
+ }
1960
+
1961
+ function render() {
1962
+ if (!concept) return;
1963
+ if (!data?.canvas) { renderStart(); return; }
1964
+ updateBar();
1965
+ keepFocus(() => {
1966
+ fillSec(sec.info, infoParts());
1967
+ fillSec(sec.sel, selParts());
1968
+ renderTalk();
1969
+ fillSec(sec.name, nameParts());
1970
+ fillSec(sec.color, colorParts());
1971
+ fillSec(sec.nodes, nodeParts());
1972
+ });
1973
+ sec.partsHead.textContent = t('Parts ({n})', { n: data.parts.length });
1974
+ renderRows(true);
1975
+ drawOverlay();
1976
+ }
1977
+
1978
+ /**
1979
+ * 화면 글의 언어를 정한다. 위쪽 줄과 옆 칸의 틀은 만들 때 글을 적으므로 다시 만든다. 열린 메뉴는 닫는다. 호스트는 언어가
1980
+ * 바뀌면 화면을 다시 열므로 처음 capabilities 를 받을 때 한 번만 부른다.
1981
+ */
1982
+ function setLanguage(next) {
1983
+ lang = next;
1984
+ if (document.documentElement) document.documentElement.lang = next;
1985
+ labelStatic();
1986
+ openMenu = null;
1987
+ buildBar();
1988
+ buildSide();
1989
+ setSide(sideOpen);
1990
+ setTool(tool);
1991
+ // 새로 만든 위쪽 줄의 확대 비율 글을 지금 확대로 맞춘다
1992
+ if (data?.canvas && !view.auto) applyView();
1993
+ }
1994
+
1995
+ labelStatic();
1996
+ buildBar();
1997
+ buildSide();
1998
+ setSide(false);
1999
+ setTool('select');
2000
+ if (typeof ResizeObserver === 'function') {
2001
+ new ResizeObserver(() => { if (!data?.canvas) return; if (view.auto) fit(); else drawOverlay(); renderRows(); }).observe(stage);
2002
+ } else {
2003
+ window.addEventListener('resize', () => { if (data?.canvas) { if (view.auto) fit(); else drawOverlay(); } });
2004
+ }
2005
+
2006
+ parent.postMessage({ aic: 1, event: 'ready', rendered: true }, '*');
2007
+ call('capabilities', {}).then((cap) => {
2008
+ caps = { ...caps, ...(cap ?? {}) };
2009
+ // 화면 글은 영어가 기본이고, 호스트가 'ko' 를 줄 때만 한국어다. 다른 값이나 없는 값은 영어다
2010
+ if (cap?.language === 'ko') setLanguage('ko');
2011
+ // 보낼 수 있는 화면인지에 따라 그림을 맞추는 높이가 달라진다
2012
+ if (concept) { if (data?.canvas && view.auto) fit(); render(); notePick(); }
2013
+ }, () => {});
2014
+ refresh();
2015
+ </script>
2016
+ </body>
2017
+ </html>