key-screen-framework 0.1.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 (113) hide show
  1. package/chunks/store-txJwmrlO.js +281 -0
  2. package/chunks/useArduinoBuild-CVr4XAsL.js +152 -0
  3. package/cli/check-arduino-bundle.mjs +157 -0
  4. package/cli/doctor-project.mjs +554 -0
  5. package/cli/generate-screen.mjs +286 -0
  6. package/cli/migrate-project.mjs +679 -0
  7. package/cli/new-project.mjs +344 -0
  8. package/cli/remove-screen.mjs +83 -0
  9. package/cli/screen-generation-contract.mjs +127 -0
  10. package/cli/screen-generation-renderers.mjs +71 -0
  11. package/cli/screen-module-utils.mjs +148 -0
  12. package/cli/screen-script-utils.mjs +92 -0
  13. package/cli/setup-arduino-cli.mjs +515 -0
  14. package/cli/source-module-specifiers.mjs +89 -0
  15. package/cli/sync-screens.mjs +48 -0
  16. package/main/index.js +2003 -0
  17. package/package.json +108 -0
  18. package/preload/index.js +69 -0
  19. package/renderer/components/VideoSceneScreen.js +160 -0
  20. package/renderer/hooks/index.js +6 -0
  21. package/renderer/index.js +3092 -0
  22. package/renderer/store.js +6 -0
  23. package/renderer/styles.css +1395 -0
  24. package/shared/arduino-board.js +136 -0
  25. package/shared/arduino-keyboard-shortcut.js +77 -0
  26. package/shared/index.js +25 -0
  27. package/shared/screen-catalog.js +35 -0
  28. package/shared/screen-shortcuts.js +164 -0
  29. package/shared/types.js +1 -0
  30. package/templates/project/README.md +45 -0
  31. package/templates/project/build/favicon-mac.png +0 -0
  32. package/templates/project/build/favicon.ico +0 -0
  33. package/templates/project/build/favicon.png +0 -0
  34. package/templates/project/e2e/smoke.spec.ts +10 -0
  35. package/templates/project/electron.vite.config.ts +40 -0
  36. package/templates/project/eslint.config.js +23 -0
  37. package/templates/project/gitignore +19 -0
  38. package/templates/project/media/audio/.gitkeep +1 -0
  39. package/templates/project/media/font/.gitkeep +1 -0
  40. package/templates/project/media/image/.gitkeep +1 -0
  41. package/templates/project/media/video/.gitkeep +1 -0
  42. package/templates/project/media/video/external-sample-30s.mp4 +0 -0
  43. package/templates/project/package.json +117 -0
  44. package/templates/project/playwright.config.ts +7 -0
  45. package/templates/project/postcss.config.js +6 -0
  46. package/templates/project/src/arduino-output-signals.ts +19 -0
  47. package/templates/project/src/assets/audio/.gitkeep +1 -0
  48. package/templates/project/src/assets/font/PretendardVariable.woff2 +0 -0
  49. package/templates/project/src/assets/image/.gitkeep +1 -0
  50. package/templates/project/src/assets/image/key-icon.png +0 -0
  51. package/templates/project/src/assets/video/.gitkeep +1 -0
  52. package/templates/project/src/assets/video/sample-30s.mp4 +0 -0
  53. package/templates/project/src/device-signal-handlers.test.ts +9 -0
  54. package/templates/project/src/device-signal-handlers.ts +14 -0
  55. package/templates/project/src/device-signal-targets.ts +3 -0
  56. package/templates/project/src/main/index.ts +17 -0
  57. package/templates/project/src/preload/index.ts +4 -0
  58. package/templates/project/src/project.config.ts +11 -0
  59. package/templates/project/src/renderer/index.html +16 -0
  60. package/templates/project/src/renderer/main.tsx +20 -0
  61. package/templates/project/src/renderer/vite-env.d.ts +1 -0
  62. package/templates/project/src/screen-definitions.ts +75 -0
  63. package/templates/project/src/screens/Screen001Black.test.tsx +21 -0
  64. package/templates/project/src/screens/Screen001Black.tsx +38 -0
  65. package/templates/project/src/screens/Screen002Video.test.tsx +18 -0
  66. package/templates/project/src/screens/Screen002Video.tsx +22 -0
  67. package/templates/project/src/screens/Screen003ExternalVideo.test.tsx +26 -0
  68. package/templates/project/src/screens/Screen003ExternalVideo.tsx +22 -0
  69. package/templates/project/src/store.test.ts +21 -0
  70. package/templates/project/src/store.ts +32 -0
  71. package/templates/project/src/styles.css +60 -0
  72. package/templates/project/tailwind.config.ts +69 -0
  73. package/templates/project/tsconfig.json +4 -0
  74. package/templates/project/tsconfig.node.json +32 -0
  75. package/templates/project/vitest.config.ts +20 -0
  76. package/templates/project/vitest.setup.ts +1 -0
  77. package/types/main/app-keyboard-shortcuts.d.ts +4 -0
  78. package/types/main/arduino-cli.d.ts +55 -0
  79. package/types/main/arduino-sketch-generator.d.ts +10 -0
  80. package/types/main/device-controller.d.ts +39 -0
  81. package/types/main/device-log-writer.d.ts +21 -0
  82. package/types/main/dtoa-dispatcher.d.ts +17 -0
  83. package/types/main/dtoa-handler.d.ts +9 -0
  84. package/types/main/game-session.d.ts +12 -0
  85. package/types/main/kiosk-quit.d.ts +5 -0
  86. package/types/main/media-manager.d.ts +17 -0
  87. package/types/main/runtime-paths.d.ts +10 -0
  88. package/types/main/serial-protocol.d.ts +29 -0
  89. package/types/main/start.d.ts +2 -0
  90. package/types/main/window-mode.d.ts +18 -0
  91. package/types/main/windows-key-lock.d.ts +3 -0
  92. package/types/preload/bridge.d.ts +4 -0
  93. package/types/renderer/src/App.d.ts +3 -0
  94. package/types/renderer/src/KeyScreenApp.d.ts +3 -0
  95. package/types/renderer/src/bridge.d.ts +3 -0
  96. package/types/renderer/src/components/DeviceLogOverlay.d.ts +7 -0
  97. package/types/renderer/src/components/ScreenRenderer.d.ts +7 -0
  98. package/types/renderer/src/components/SplashScreen.d.ts +7 -0
  99. package/types/renderer/src/components/VideoSceneScreen.d.ts +16 -0
  100. package/types/renderer/src/framework/AdminScreen.d.ts +3 -0
  101. package/types/renderer/src/hooks/index.d.ts +4 -0
  102. package/types/renderer/src/hooks/useArduinoBuild.d.ts +14 -0
  103. package/types/renderer/src/hooks/useAtodSignal.d.ts +12 -0
  104. package/types/renderer/src/index.d.ts +9 -0
  105. package/types/renderer/src/project-runtime.d.ts +10 -0
  106. package/types/renderer/src/screen-types.d.ts +24 -0
  107. package/types/renderer/src/store.d.ts +33 -0
  108. package/types/shared/arduino-board.d.ts +11 -0
  109. package/types/shared/arduino-keyboard-shortcut.d.ts +14 -0
  110. package/types/shared/index.d.ts +5 -0
  111. package/types/shared/screen-catalog.d.ts +19 -0
  112. package/types/shared/screen-shortcuts.d.ts +10 -0
  113. package/types/shared/types.d.ts +272 -0
@@ -0,0 +1,3092 @@
1
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
+ import { createContext, useContext, useLayoutEffect, useState, useRef, useMemo, useEffect, Suspense, StrictMode } from "react";
3
+ import { createRoot } from "react-dom/client";
4
+ import { buildDefaultGlobalShortcuts, matchesShortcut, DEBUG_DEVICE_LOG_SHORTCUT, RESET_SCREEN_TARGET, KIOSK_QUIT_SHORTCUT, normalizeShortcutAccelerator } from "../shared/screen-shortcuts.js";
5
+ import { c as configureRendererPreview, g as getGameApi, u as useAppStore } from "../chunks/store-txJwmrlO.js";
6
+ import { createPortal, flushSync } from "react-dom";
7
+ import { u as useArduinoBuild } from "../chunks/useArduinoBuild-CVr4XAsL.js";
8
+ import { c, a } from "../chunks/useArduinoBuild-CVr4XAsL.js";
9
+ import { BOARD_PRESET_FQBN, ARDUINO_BOARD_PRESETS, resolveArduinoBoardFqbn } from "../shared/arduino-board.js";
10
+ import { acceleratorToArduinoKeyboardShortcut } from "../shared/arduino-keyboard-shortcut.js";
11
+ const logTone$1 = {
12
+ in: "bg-log-in-bg",
13
+ out: "bg-log-out-bg",
14
+ system: "bg-log-system-bg",
15
+ error: "bg-log-error-bg"
16
+ };
17
+ const logLabelTone$1 = {
18
+ in: "bg-log-in-label-bg text-log-in-label-text",
19
+ out: "bg-log-out-label-bg text-log-out-label-text",
20
+ system: "bg-log-system-label-bg text-log-system-label-text",
21
+ error: "bg-log-error-label-bg text-log-error-label-text"
22
+ };
23
+ const logLayoutTone$1 = {
24
+ in: "ml-16 self-end",
25
+ out: "mr-16 self-start",
26
+ system: "mx-auto w-full max-w-[86%]"
27
+ };
28
+ const logLabelByOrigin$1 = {
29
+ in: "Device",
30
+ out: "App",
31
+ system: "SYSTEM"
32
+ };
33
+ const errorTextTone$1 = "text-[11px] font-medium uppercase tracking-[0.2em] text-log-error-label-text";
34
+ function formatLocalDateTime$1(value) {
35
+ if (!value) return "아직 없음";
36
+ const date = new Date(value);
37
+ if (Number.isNaN(date.getTime())) {
38
+ return value;
39
+ }
40
+ const year = date.getFullYear();
41
+ const month = String(date.getMonth() + 1).padStart(2, "0");
42
+ const day = String(date.getDate()).padStart(2, "0");
43
+ const hours = String(date.getHours()).padStart(2, "0");
44
+ const minutes = String(date.getMinutes()).padStart(2, "0");
45
+ const seconds = String(date.getSeconds()).padStart(2, "0");
46
+ return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
47
+ }
48
+ function translateLog$1(raw) {
49
+ if (raw === "READY") return "통신 준비 완료";
50
+ if (raw === "PONG") return "PONG 응답";
51
+ if (raw === "PING") return "PING 전송";
52
+ if (raw.startsWith("DTOA ")) return `화면 전환 요청: ${raw.slice(5).trim()}`;
53
+ if (raw.startsWith("ACK ")) return `처리 완료: ${raw.slice(4).trim()}`;
54
+ if (raw.startsWith("ERR ")) return "오류 응답";
55
+ if (raw.includes("Preview mode")) return "미리보기 모드";
56
+ return "수신 로그";
57
+ }
58
+ function DeviceLogOverlay({ deviceState, onClose }) {
59
+ return /* @__PURE__ */ jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4 py-6", children: /* @__PURE__ */ jsxs("div", { className: "flex h-[78vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-border bg-surface-strong shadow-2xl", children: [
60
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4 border-b border-border-soft px-5 py-4", children: [
61
+ /* @__PURE__ */ jsxs("div", { children: [
62
+ /* @__PURE__ */ jsx("h2", { className: "font-display text-2xl text-text", children: "디바이스 메시지 로그" }),
63
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-text-subtle", children: "어느 화면에서든 최근 로그를 확인할 수 있습니다." })
64
+ ] }),
65
+ /* @__PURE__ */ jsx(
66
+ "button",
67
+ {
68
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
69
+ onClick: onClose,
70
+ type: "button",
71
+ children: "닫기"
72
+ }
73
+ )
74
+ ] }),
75
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-3 border-b border-border-soft px-5 py-4 md:grid-cols-3", children: [
76
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface px-4 py-3", children: [
77
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "상태" }),
78
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-text", children: deviceState.status })
79
+ ] }),
80
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface px-4 py-3", children: [
81
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "선택 포트" }),
82
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-text", children: deviceState.selectedPortPath ?? "선택되지 않음" })
83
+ ] }),
84
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface px-4 py-3", children: [
85
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "업데이트 시각" }),
86
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-text", children: formatLocalDateTime$1(deviceState.updatedAt) })
87
+ ] })
88
+ ] }),
89
+ /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-auto px-5 py-4", children: /* @__PURE__ */ jsx("div", { className: "grid gap-2 pr-1", children: deviceState.messageLog.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border-soft px-4 py-6 text-sm text-text-subtle", children: "아직 기록된 로그가 없습니다." }) : deviceState.messageLog.map((entry) => {
90
+ const origin = entry.origin ?? (entry.direction === "out" ? "out" : entry.direction === "system" ? "system" : "in");
91
+ return /* @__PURE__ */ jsxs(
92
+ "div",
93
+ {
94
+ className: `w-full max-w-[84%] rounded-lg px-3 py-3 ${logTone$1[entry.direction]} ${logLayoutTone$1[origin]}`,
95
+ children: [
96
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
97
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
98
+ /* @__PURE__ */ jsx(
99
+ "span",
100
+ {
101
+ className: `rounded-md px-2 py-1 text-xs uppercase tracking-[0.25em] ${logLabelTone$1[entry.direction]}`,
102
+ children: logLabelByOrigin$1[origin]
103
+ }
104
+ ),
105
+ entry.direction === "error" ? /* @__PURE__ */ jsx("span", { className: errorTextTone$1, children: "ERROR" }) : null
106
+ ] }),
107
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-text-subtle", children: formatLocalDateTime$1(entry.createdAt) })
108
+ ] }),
109
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-text", children: translateLog$1(entry.raw) }),
110
+ /* @__PURE__ */ jsx("p", { className: "mt-1 break-all text-xs text-text-subtle", children: entry.raw })
111
+ ]
112
+ },
113
+ entry.id
114
+ );
115
+ }) }) })
116
+ ] }) });
117
+ }
118
+ const ProjectRuntimeContext = createContext(null);
119
+ function ProjectRuntimeProvider({
120
+ children,
121
+ options
122
+ }) {
123
+ useLayoutEffect(() => {
124
+ configureRendererPreview(options.screenDefinitions);
125
+ }, [options.screenDefinitions]);
126
+ return /* @__PURE__ */ jsx(ProjectRuntimeContext.Provider, { value: options, children });
127
+ }
128
+ function useProjectRuntime() {
129
+ const runtime = useContext(ProjectRuntimeContext);
130
+ if (!runtime) {
131
+ throw new Error("Project runtime is not configured. Render within KeyScreenApp.");
132
+ }
133
+ return runtime;
134
+ }
135
+ function getActiveScreenDefinition(screens, fallbackScreens, currentStepId) {
136
+ const activeScreen = screens.find((screen) => screen.id === currentStepId) ?? fallbackScreens.find((screen) => screen.id === currentStepId) ?? screens.find((screen) => screen.isInitial) ?? fallbackScreens.find((screen) => screen.isInitial) ?? screens[0] ?? fallbackScreens[0];
137
+ if (!activeScreen) {
138
+ throw new Error("At least one renderer screen definition is required.");
139
+ }
140
+ return activeScreen;
141
+ }
142
+ const screenModulePreloadPromises = /* @__PURE__ */ new WeakMap();
143
+ async function preloadScreenModule(screenModules, componentKey) {
144
+ const screenModule = screenModules[componentKey];
145
+ if (!screenModule?.preload) {
146
+ return;
147
+ }
148
+ const existingPreload = screenModulePreloadPromises.get(screenModule);
149
+ if (existingPreload) {
150
+ await existingPreload;
151
+ return;
152
+ }
153
+ const preloadPromise = Promise.resolve().then(() => screenModule.preload?.()).then(() => void 0).catch((error) => {
154
+ screenModulePreloadPromises.delete(screenModule);
155
+ throw error;
156
+ });
157
+ screenModulePreloadPromises.set(screenModule, preloadPromise);
158
+ await preloadPromise;
159
+ }
160
+ function UnknownScreen({ screenId }) {
161
+ return /* @__PURE__ */ jsxs("main", { className: "flex min-h-screen flex-col items-center justify-center bg-app-bg p-8 text-center text-text", children: [
162
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "Unknown Screen" }),
163
+ /* @__PURE__ */ jsx("h2", { className: "mt-3 font-display text-3xl text-text", children: "등록되지 않은 화면" }),
164
+ /* @__PURE__ */ jsx("p", { className: "mt-3 max-w-xl text-sm text-text-muted", children: "현재 상태값에 대응하는 화면 컴포넌트가 없습니다. 화면 레지스트리와 컴포넌트 매핑을 확인하세요." }),
165
+ /* @__PURE__ */ jsxs("p", { className: "mt-4 rounded-lg border border-border-soft bg-surface-soft px-4 py-2 text-sm text-text", children: [
166
+ "target: ",
167
+ screenId ?? "unknown"
168
+ ] })
169
+ ] });
170
+ }
171
+ function getViewportSize(sceneResolution) {
172
+ if (typeof window === "undefined") {
173
+ return sceneResolution;
174
+ }
175
+ return {
176
+ width: window.innerWidth,
177
+ height: window.innerHeight
178
+ };
179
+ }
180
+ function SceneStageFrame({
181
+ children,
182
+ sceneResolution
183
+ }) {
184
+ const [viewportSize, setViewportSize] = useState(() => getViewportSize(sceneResolution));
185
+ const { width, height } = sceneResolution;
186
+ const scale = Math.min(viewportSize.width / width, viewportSize.height / height);
187
+ useEffect(() => {
188
+ const updateViewportSize = () => setViewportSize(getViewportSize(sceneResolution));
189
+ updateViewportSize();
190
+ window.addEventListener("resize", updateViewportSize);
191
+ return () => window.removeEventListener("resize", updateViewportSize);
192
+ }, [sceneResolution]);
193
+ return /* @__PURE__ */ jsx(
194
+ "div",
195
+ {
196
+ "aria-label": `${width}x${height} scene stage`,
197
+ className: "scene-stage absolute left-1/2 top-1/2 shrink-0 overflow-hidden bg-app-bg",
198
+ style: {
199
+ width,
200
+ height,
201
+ transform: `translate(-50%, -50%) scale(${scale})`,
202
+ transformOrigin: "center"
203
+ },
204
+ children
205
+ }
206
+ );
207
+ }
208
+ function SceneStage({ children }) {
209
+ return /* @__PURE__ */ jsx("main", { className: "relative h-screen w-screen overflow-hidden bg-black", children });
210
+ }
211
+ function getPreloadTarget(activeScreen, sceneScreens) {
212
+ if (activeScreen.kind !== "scene") {
213
+ return sceneScreens[0];
214
+ }
215
+ const currentSceneIndex = sceneScreens.findIndex((screen) => screen.id === activeScreen.id);
216
+ return currentSceneIndex >= 0 ? sceneScreens[currentSceneIndex + 1] : void 0;
217
+ }
218
+ function logPreload(phase, screen, message) {
219
+ getGameApi().logPreload({
220
+ phase,
221
+ componentKey: screen.componentKey,
222
+ screenId: screen.id,
223
+ message
224
+ });
225
+ }
226
+ function waitForAnimationFrame$1() {
227
+ if (typeof window === "undefined" || typeof window.requestAnimationFrame === "undefined") {
228
+ return Promise.resolve();
229
+ }
230
+ return new Promise((resolve) => {
231
+ window.requestAnimationFrame(() => resolve());
232
+ });
233
+ }
234
+ async function waitForPaintFrames(frameCount = 2) {
235
+ for (let index = 0; index < frameCount; index += 1) {
236
+ await waitForAnimationFrame$1();
237
+ }
238
+ }
239
+ function waitWithTimeout(promise, timeoutMs = 8e3) {
240
+ let timeoutId;
241
+ const timeout = new Promise((resolve) => {
242
+ timeoutId = setTimeout(resolve, timeoutMs);
243
+ });
244
+ return Promise.race([promise, timeout]).finally(() => {
245
+ if (timeoutId) {
246
+ clearTimeout(timeoutId);
247
+ }
248
+ });
249
+ }
250
+ async function waitForImageReady(image) {
251
+ if (!image.complete) {
252
+ await new Promise((resolve) => {
253
+ const cleanup = () => {
254
+ image.removeEventListener("load", handleSettled);
255
+ image.removeEventListener("error", handleSettled);
256
+ };
257
+ const handleSettled = () => {
258
+ cleanup();
259
+ resolve();
260
+ };
261
+ image.addEventListener("load", handleSettled, { once: true });
262
+ image.addEventListener("error", handleSettled, { once: true });
263
+ });
264
+ }
265
+ if (typeof image.decode !== "function") {
266
+ return;
267
+ }
268
+ await image.decode().catch(() => void 0);
269
+ }
270
+ function waitForVideoDataReady(video) {
271
+ if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
272
+ return Promise.resolve();
273
+ }
274
+ return new Promise((resolve) => {
275
+ const cleanup = () => {
276
+ video.removeEventListener("loadeddata", handleSettled);
277
+ video.removeEventListener("canplay", handleSettled);
278
+ video.removeEventListener("error", handleSettled);
279
+ };
280
+ const handleSettled = () => {
281
+ cleanup();
282
+ resolve();
283
+ };
284
+ video.addEventListener("loadeddata", handleSettled, { once: true });
285
+ video.addEventListener("canplay", handleSettled, { once: true });
286
+ video.addEventListener("error", handleSettled, { once: true });
287
+ });
288
+ }
289
+ async function waitForVideoReady(video) {
290
+ await waitForVideoDataReady(video);
291
+ const videoWithFrameCallback = video;
292
+ if (typeof videoWithFrameCallback.requestVideoFrameCallback !== "function") {
293
+ await waitForPaintFrames(1);
294
+ return;
295
+ }
296
+ await new Promise((resolve) => {
297
+ videoWithFrameCallback.requestVideoFrameCallback?.(() => resolve());
298
+ });
299
+ }
300
+ function getBackgroundImageUrls(root) {
301
+ if (typeof window === "undefined" || typeof window.getComputedStyle === "undefined") {
302
+ return [];
303
+ }
304
+ const elements = [root, ...Array.from(root.querySelectorAll("*"))];
305
+ const urls = /* @__PURE__ */ new Set();
306
+ for (const element of elements) {
307
+ const backgroundImage = window.getComputedStyle(element).backgroundImage;
308
+ const matches = backgroundImage.matchAll(/url\((?:"([^"]+)"|'([^']+)'|([^'")]+))\)/g);
309
+ for (const match of matches) {
310
+ const url = match[1] ?? match[2] ?? match[3];
311
+ if (url && !url.startsWith("data:")) {
312
+ urls.add(url);
313
+ }
314
+ }
315
+ }
316
+ return Array.from(urls);
317
+ }
318
+ function waitForBackgroundImageReady(src) {
319
+ return new Promise((resolve) => {
320
+ const image = new Image();
321
+ image.onload = () => resolve();
322
+ image.onerror = () => resolve();
323
+ image.src = src;
324
+ });
325
+ }
326
+ async function waitForRenderableResources(root) {
327
+ const images = Array.from(root.querySelectorAll("img")).map(
328
+ (image) => waitWithTimeout(waitForImageReady(image))
329
+ );
330
+ const videos = Array.from(root.querySelectorAll("video")).map(
331
+ (video) => waitWithTimeout(waitForVideoReady(video))
332
+ );
333
+ const backgroundImages = getBackgroundImageUrls(root).map(
334
+ (src) => waitWithTimeout(waitForBackgroundImageReady(src))
335
+ );
336
+ await Promise.all([...images, ...videos, ...backgroundImages]);
337
+ await waitForPaintFrames();
338
+ }
339
+ function ScreenRenderer({ gameState, screens }) {
340
+ const { projectConfig, screenDefinitions, screenModules } = useProjectRuntime();
341
+ const requestedScreen = getActiveScreenDefinition(
342
+ screens,
343
+ screenDefinitions,
344
+ gameState.currentStepId
345
+ );
346
+ const [displayedScreenId, setDisplayedScreenId] = useState(requestedScreen.id);
347
+ const [pendingScreenId, setPendingScreenId] = useState();
348
+ const pendingScreenRef = useRef(null);
349
+ const pendingStartedAtRef = useRef(performance.now());
350
+ const pendingRenderRequestIdRef = useRef(0);
351
+ const displayedScreen = getActiveScreenDefinition(screens, screenDefinitions, displayedScreenId);
352
+ const ActiveComponent = screenModules[displayedScreen.componentKey]?.default;
353
+ const pendingScreen = pendingScreenId ? getActiveScreenDefinition(screens, screenDefinitions, pendingScreenId) : void 0;
354
+ const PendingComponent = pendingScreen ? screenModules[pendingScreen.componentKey]?.default : void 0;
355
+ const displayedGameState = useMemo(
356
+ () => ({
357
+ ...gameState,
358
+ currentStepId: displayedScreen.id
359
+ }),
360
+ [displayedScreen.id, gameState]
361
+ );
362
+ const sceneScreens = useMemo(
363
+ () => screens.filter((availableScreen) => availableScreen.kind === "scene"),
364
+ [screens]
365
+ );
366
+ useEffect(() => {
367
+ if (requestedScreen.id === displayedScreen.id) {
368
+ setPendingScreenId(void 0);
369
+ return;
370
+ }
371
+ let cancelled = false;
372
+ pendingStartedAtRef.current = performance.now();
373
+ logPreload("start", requestedScreen, `Preparing before transition from ${displayedScreen.id}.`);
374
+ void preloadScreenModule(screenModules, requestedScreen.componentKey).then(() => {
375
+ if (cancelled) {
376
+ return;
377
+ }
378
+ if (!screenModules[requestedScreen.componentKey]) {
379
+ setDisplayedScreenId(requestedScreen.id);
380
+ setPendingScreenId(void 0);
381
+ return;
382
+ }
383
+ setPendingScreenId(requestedScreen.id);
384
+ }).catch((error) => {
385
+ if (cancelled) {
386
+ return;
387
+ }
388
+ logPreload(
389
+ "error",
390
+ requestedScreen,
391
+ error instanceof Error ? error.message : String(error)
392
+ );
393
+ setDisplayedScreenId(requestedScreen.id);
394
+ });
395
+ return () => {
396
+ cancelled = true;
397
+ };
398
+ }, [displayedScreen.id, requestedScreen, screenModules]);
399
+ useEffect(() => {
400
+ const preloadTarget = getPreloadTarget(displayedScreen, sceneScreens);
401
+ if (!preloadTarget) {
402
+ if (displayedScreen.kind === "scene") {
403
+ logPreload("skip", displayedScreen, "No next indexed scene.");
404
+ }
405
+ return;
406
+ }
407
+ const startedAt = performance.now();
408
+ logPreload("start", preloadTarget, `Preloading after ${displayedScreen.id}.`);
409
+ void preloadScreenModule(screenModules, preloadTarget.componentKey).then(() => {
410
+ logPreload(
411
+ "done",
412
+ preloadTarget,
413
+ `Preloaded in ${Math.round(performance.now() - startedAt)}ms.`
414
+ );
415
+ }).catch((error) => {
416
+ logPreload(
417
+ "error",
418
+ preloadTarget,
419
+ error instanceof Error ? error.message : String(error)
420
+ );
421
+ });
422
+ }, [displayedScreen, sceneScreens, screenModules]);
423
+ useEffect(() => {
424
+ if (!pendingScreen || !PendingComponent) {
425
+ return;
426
+ }
427
+ const pendingRoot = pendingScreenRef.current;
428
+ if (!pendingRoot) {
429
+ return;
430
+ }
431
+ let cancelled = false;
432
+ const requestId = pendingRenderRequestIdRef.current + 1;
433
+ pendingRenderRequestIdRef.current = requestId;
434
+ void waitForRenderableResources(pendingRoot).then(() => {
435
+ if (cancelled || pendingRenderRequestIdRef.current !== requestId) {
436
+ return;
437
+ }
438
+ logPreload(
439
+ "done",
440
+ pendingScreen,
441
+ `Prepared and painted in ${Math.round(performance.now() - pendingStartedAtRef.current)}ms.`
442
+ );
443
+ setDisplayedScreenId(pendingScreen.id);
444
+ setPendingScreenId(void 0);
445
+ }).catch((error) => {
446
+ if (cancelled || pendingRenderRequestIdRef.current !== requestId) {
447
+ return;
448
+ }
449
+ logPreload(
450
+ "error",
451
+ pendingScreen,
452
+ error instanceof Error ? error.message : String(error)
453
+ );
454
+ setDisplayedScreenId(pendingScreen.id);
455
+ setPendingScreenId(void 0);
456
+ });
457
+ return () => {
458
+ cancelled = true;
459
+ };
460
+ }, [PendingComponent, pendingScreen]);
461
+ const renderedScreen = ActiveComponent ? /* @__PURE__ */ jsx(Suspense, { fallback: null, children: /* @__PURE__ */ jsx(ActiveComponent, { gameState: displayedGameState, screen: displayedScreen }) }) : /* @__PURE__ */ jsx(UnknownScreen, { screenId: displayedScreen.id });
462
+ const renderedPendingScreen = pendingScreen && PendingComponent ? /* @__PURE__ */ jsx(Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
463
+ PendingComponent,
464
+ {
465
+ gameState: {
466
+ ...gameState,
467
+ currentStepId: pendingScreen.id
468
+ },
469
+ screen: pendingScreen
470
+ }
471
+ ) }) : void 0;
472
+ const displayedLayer = displayedScreen.kind === "scene" ? /* @__PURE__ */ jsx(SceneStage, { children: /* @__PURE__ */ jsx(SceneStageFrame, { sceneResolution: projectConfig.sceneResolution, children: renderedScreen }) }) : renderedScreen;
473
+ const pendingLayer = pendingScreen && renderedPendingScreen && /* @__PURE__ */ jsx(
474
+ "div",
475
+ {
476
+ ref: pendingScreenRef,
477
+ "aria-hidden": "true",
478
+ className: "pointer-events-none fixed inset-0 z-0",
479
+ style: { opacity: 1e-3, transform: "translateZ(0)" },
480
+ children: pendingScreen.kind === "scene" ? /* @__PURE__ */ jsx(SceneStage, { children: /* @__PURE__ */ jsx(SceneStageFrame, { sceneResolution: projectConfig.sceneResolution, children: renderedPendingScreen }) }) : renderedPendingScreen
481
+ }
482
+ );
483
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
484
+ /* @__PURE__ */ jsx("div", { className: "relative z-10", children: displayedLayer }),
485
+ pendingLayer
486
+ ] });
487
+ }
488
+ function SplashScreen({ appIconAlt, appIconUrl, leaving }) {
489
+ return /* @__PURE__ */ jsx(
490
+ "div",
491
+ {
492
+ "aria-label": "splash screen",
493
+ className: `fixed inset-0 z-[100] flex items-center justify-center bg-black transition-opacity duration-700 ease-out ${leaving ? "opacity-0" : "opacity-100"}`,
494
+ children: /* @__PURE__ */ jsx(
495
+ "img",
496
+ {
497
+ alt: appIconAlt,
498
+ className: `h-28 w-28 object-contain transition duration-700 ease-out ${leaving ? "scale-95 opacity-0" : "scale-100 opacity-100"}`,
499
+ src: appIconUrl
500
+ }
501
+ )
502
+ }
503
+ );
504
+ }
505
+ const SPLASH_MIN_VISIBLE_MS = 800;
506
+ const SPLASH_FADE_MS = 700;
507
+ function isEditableTarget(target) {
508
+ if (!(target instanceof HTMLElement)) {
509
+ return false;
510
+ }
511
+ return target.isContentEditable || target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement;
512
+ }
513
+ function App() {
514
+ const {
515
+ appIconUrl,
516
+ deviceSignalHandlers,
517
+ getProjectStore,
518
+ projectConfig,
519
+ screenDefinitions
520
+ } = useProjectRuntime();
521
+ const { bootstrap, gameState, moveToScreen, screens, setDeviceState, setGameState, shortcuts } = useAppStore();
522
+ const [deviceLogOpen, setDeviceLogOpen] = useState(false);
523
+ const [splashState, setSplashState] = useState("visible");
524
+ const deviceState = useAppStore((state) => state.deviceState);
525
+ const defaultGlobalShortcuts = useMemo(
526
+ () => buildDefaultGlobalShortcuts(screenDefinitions),
527
+ [screenDefinitions]
528
+ );
529
+ useEffect(() => {
530
+ const startedAt = performance.now();
531
+ let readyTimer;
532
+ let fadeTimer;
533
+ let disposed = false;
534
+ void bootstrap().finally(() => {
535
+ const elapsed = performance.now() - startedAt;
536
+ const remainingMs = Math.max(0, SPLASH_MIN_VISIBLE_MS - elapsed);
537
+ readyTimer = window.setTimeout(() => {
538
+ if (disposed) {
539
+ return;
540
+ }
541
+ setSplashState("leaving");
542
+ fadeTimer = window.setTimeout(() => {
543
+ if (!disposed) {
544
+ setSplashState("hidden");
545
+ }
546
+ }, SPLASH_FADE_MS);
547
+ }, remainingMs);
548
+ });
549
+ const gameApi = getGameApi();
550
+ const disposeDevice = gameApi.onDeviceState(setDeviceState);
551
+ const disposeDeviceSignal = gameApi.onDeviceSignal((signal) => {
552
+ const handler = deviceSignalHandlers[signal.target];
553
+ if (!handler) {
554
+ console.warn(`[device] no handler registered for signal: ${signal.target}`);
555
+ return;
556
+ }
557
+ void Promise.resolve(
558
+ handler(signal, {
559
+ api: gameApi,
560
+ projectStore: getProjectStore(),
561
+ moveToScreen,
562
+ sendCommand: gameApi.sendCommand
563
+ })
564
+ ).catch((error) => {
565
+ console.error("[device] signal handler failed", error);
566
+ });
567
+ });
568
+ const disposeGame = gameApi.onGameState(setGameState);
569
+ return () => {
570
+ disposed = true;
571
+ if (readyTimer) {
572
+ window.clearTimeout(readyTimer);
573
+ }
574
+ if (fadeTimer) {
575
+ window.clearTimeout(fadeTimer);
576
+ }
577
+ disposeDevice();
578
+ disposeDeviceSignal();
579
+ disposeGame();
580
+ };
581
+ }, [bootstrap, deviceSignalHandlers, getProjectStore, moveToScreen, setDeviceState, setGameState]);
582
+ useEffect(() => {
583
+ function handleScreenShortcut(event) {
584
+ if (event.key === "Escape" && deviceLogOpen) {
585
+ event.preventDefault();
586
+ setDeviceLogOpen(false);
587
+ return;
588
+ }
589
+ if (event.repeat || isEditableTarget(event.target)) {
590
+ return;
591
+ }
592
+ if (matchesShortcut(event, { accelerator: DEBUG_DEVICE_LOG_SHORTCUT })) {
593
+ event.preventDefault();
594
+ setDeviceLogOpen((current) => !current);
595
+ return;
596
+ }
597
+ const activeShortcuts = shortcuts.length > 0 ? shortcuts : defaultGlobalShortcuts;
598
+ const matchedShortcut = activeShortcuts.find(
599
+ (shortcut) => matchesShortcut(event, shortcut)
600
+ );
601
+ if (!matchedShortcut) {
602
+ return;
603
+ }
604
+ event.preventDefault();
605
+ getGameApi().logShortcutTransition(matchedShortcut);
606
+ if (screenDefinitions.some((screen) => screen.id === matchedShortcut.target)) {
607
+ void moveToScreen(matchedShortcut.target);
608
+ }
609
+ }
610
+ window.addEventListener("keydown", handleScreenShortcut);
611
+ return () => window.removeEventListener("keydown", handleScreenShortcut);
612
+ }, [defaultGlobalShortcuts, deviceLogOpen, moveToScreen, screenDefinitions, shortcuts]);
613
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
614
+ /* @__PURE__ */ jsx(ScreenRenderer, { gameState, screens }),
615
+ deviceLogOpen ? /* @__PURE__ */ jsx(DeviceLogOverlay, { deviceState, onClose: () => setDeviceLogOpen(false) }) : null,
616
+ splashState !== "hidden" ? /* @__PURE__ */ jsx(
617
+ SplashScreen,
618
+ {
619
+ appIconAlt: projectConfig.appIconAlt,
620
+ appIconUrl,
621
+ leaving: splashState === "leaving"
622
+ }
623
+ ) : null
624
+ ] });
625
+ }
626
+ const statusLabel = {
627
+ disconnected: "연결 안 됨",
628
+ connecting: "연결 중",
629
+ connected: "연결됨",
630
+ error: "오류"
631
+ };
632
+ const statusIcon = {
633
+ disconnected: "○",
634
+ connecting: "◔",
635
+ connected: "●",
636
+ error: "!"
637
+ };
638
+ const statusIconTone = {
639
+ disconnected: "text-text-subtle",
640
+ connecting: "text-status-connecting-text",
641
+ connected: "text-aqua_signal",
642
+ error: "text-log-error-label-text"
643
+ };
644
+ const logTone = {
645
+ in: "bg-log-in-bg",
646
+ out: "bg-log-out-bg",
647
+ system: "bg-log-system-bg",
648
+ error: "bg-log-error-bg"
649
+ };
650
+ const logLabelTone = {
651
+ in: "bg-log-in-label-bg text-log-in-label-text",
652
+ out: "bg-log-out-label-bg text-log-out-label-text",
653
+ system: "bg-log-system-label-bg text-log-system-label-text",
654
+ error: "bg-log-error-label-bg text-log-error-label-text"
655
+ };
656
+ const logLayoutTone = {
657
+ in: "ml-auto mr-2 self-end",
658
+ out: "mr-auto self-start",
659
+ system: "mx-auto w-full max-w-[86%]"
660
+ };
661
+ const logLabelByOrigin = {
662
+ in: "Device",
663
+ out: "App",
664
+ system: "SYSTEM"
665
+ };
666
+ const errorTextTone = "text-[11px] font-medium uppercase tracking-[0.2em] text-log-error-label-text";
667
+ const benchmarkTone = {
668
+ normal: "border-border-soft bg-surface-subtle text-text",
669
+ good: "border-aqua_signal/50 bg-aqua_signal/10 text-text",
670
+ warning: "border-log-error-label-text/50 bg-log-error-bg text-text",
671
+ skipped: "border-border-soft bg-surface-soft text-text-muted"
672
+ };
673
+ const arduinoPhaseLabel = {
674
+ idle: "대기",
675
+ generating: "생성 중",
676
+ compiling: "컴파일 중",
677
+ uploading: "업로드 중",
678
+ "reconnecting-device": "재연결 중",
679
+ success: "성공",
680
+ error: "오류",
681
+ cancelled: "취소됨"
682
+ };
683
+ const arduinoLogTone = {
684
+ stdout: "border-border-soft bg-surface-subtle text-text-muted",
685
+ stderr: "border-log-error-label-text/40 bg-log-error-bg text-text",
686
+ system: "border-aqua_signal/30 bg-aqua_signal/10 text-text"
687
+ };
688
+ const ARDUINO_AUTO_SAVE_DEBOUNCE_MS = 1500;
689
+ const BENCHMARK_DEFAULT_PARTICLE_COUNT = 2e3;
690
+ const BENCHMARK_MIN_PARTICLE_COUNT = 100;
691
+ const BENCHMARK_MAX_PARTICLE_COUNT = 1e6;
692
+ const BENCHMARK_CANVAS_DURATION_MS = 15e3;
693
+ const BENCHMARK_TARGET_FRAME_MS = 1e3 / 60;
694
+ function shouldHideProcessedLog(raw, origin) {
695
+ const trimmed = raw.trim();
696
+ if (origin === "out" && trimmed === "PING") {
697
+ return true;
698
+ }
699
+ if (origin === "in" && trimmed === "PONG") {
700
+ return true;
701
+ }
702
+ return false;
703
+ }
704
+ function formatLocalDateTime(value) {
705
+ if (!value) return "아직 없음";
706
+ const date = new Date(value);
707
+ if (Number.isNaN(date.getTime())) {
708
+ return value;
709
+ }
710
+ const year = date.getFullYear();
711
+ const month = String(date.getMonth() + 1).padStart(2, "0");
712
+ const day = String(date.getDate()).padStart(2, "0");
713
+ const hours = String(date.getHours()).padStart(2, "0");
714
+ const minutes = String(date.getMinutes()).padStart(2, "0");
715
+ const seconds = String(date.getSeconds()).padStart(2, "0");
716
+ return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
717
+ }
718
+ function formatDuration(ms) {
719
+ return `${Math.round(ms)}ms`;
720
+ }
721
+ function formatKilobytes(kb) {
722
+ if (kb <= 0) {
723
+ return "측정 불가";
724
+ }
725
+ const mb = kb / 1024;
726
+ if (mb < 1024) {
727
+ return `${mb.toFixed(1)}MB`;
728
+ }
729
+ return `${(mb / 1024).toFixed(2)}GB`;
730
+ }
731
+ function formatBytes(bytes) {
732
+ if (bytes < 1024) return `${bytes}B`;
733
+ const kb = bytes / 1024;
734
+ if (kb < 1024) return `${kb.toFixed(1)}KB`;
735
+ const mb = kb / 1024;
736
+ if (mb < 1024) return `${mb.toFixed(1)}MB`;
737
+ return `${(mb / 1024).toFixed(2)}GB`;
738
+ }
739
+ function getMediaTypeLabel(type) {
740
+ if (type === "image") return "이미지";
741
+ if (type === "video") return "비디오";
742
+ if (type === "audio") return "오디오";
743
+ if (type === "font") return "폰트";
744
+ return type;
745
+ }
746
+ function getDurationTone(ms) {
747
+ if (ms < 80) return "good";
748
+ if (ms < 250) return "normal";
749
+ return "warning";
750
+ }
751
+ function getDurationBenchmarkVerdict(ms) {
752
+ if (ms < 80) return "빠름";
753
+ if (ms < 250) return "보통";
754
+ return "느림";
755
+ }
756
+ function getFrameTone(fps) {
757
+ if (fps >= 55) return "good";
758
+ if (fps >= 30) return "normal";
759
+ return "warning";
760
+ }
761
+ function getFrameBenchmarkVerdict(fps) {
762
+ if (fps >= 55) return "양호";
763
+ if (fps >= 30) return "주의";
764
+ return "느림";
765
+ }
766
+ function clampBenchmarkParticleCount(value) {
767
+ if (!Number.isFinite(value)) return BENCHMARK_DEFAULT_PARTICLE_COUNT;
768
+ return Math.min(
769
+ Math.max(Math.round(value), BENCHMARK_MIN_PARTICLE_COUNT),
770
+ BENCHMARK_MAX_PARTICLE_COUNT
771
+ );
772
+ }
773
+ async function measureDuration(work) {
774
+ const startedAt = performance.now();
775
+ const value = await work();
776
+ return {
777
+ value,
778
+ elapsedMs: performance.now() - startedAt
779
+ };
780
+ }
781
+ async function sampleRendererFrames(frameCount = 60) {
782
+ const requestFrame = typeof window.requestAnimationFrame === "function" ? window.requestAnimationFrame.bind(window) : (callback) => window.setTimeout(() => callback(performance.now()), 16);
783
+ const samples = [];
784
+ let previous = performance.now();
785
+ while (samples.length < frameCount) {
786
+ const timestamp = await new Promise((resolve) => requestFrame(resolve));
787
+ samples.push(timestamp - previous);
788
+ previous = timestamp;
789
+ }
790
+ const averageFrameMs = samples.reduce((sum, value) => sum + value, 0) / samples.length;
791
+ return {
792
+ averageFrameMs,
793
+ minFrameMs: Math.min(...samples),
794
+ maxFrameMs: Math.max(...samples),
795
+ fps: averageFrameMs > 0 ? 1e3 / averageFrameMs : 0
796
+ };
797
+ }
798
+ async function waitForAnimationFrame() {
799
+ const requestFrame = typeof window.requestAnimationFrame === "function" ? window.requestAnimationFrame.bind(window) : (callback) => window.setTimeout(() => callback(performance.now()), 16);
800
+ return new Promise((resolve) => requestFrame(resolve));
801
+ }
802
+ function safeGetCanvasContext(canvas, contextId) {
803
+ try {
804
+ return canvas.getContext(contextId);
805
+ } catch {
806
+ return null;
807
+ }
808
+ }
809
+ function createShader(gl, type, source) {
810
+ const shader = gl.createShader(type);
811
+ if (!shader) return null;
812
+ gl.shaderSource(shader, source);
813
+ gl.compileShader(shader);
814
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
815
+ gl.deleteShader(shader);
816
+ return null;
817
+ }
818
+ return shader;
819
+ }
820
+ function benchmarkRandom(seed) {
821
+ const value = Math.sin(seed * 12.9898) * 43758.5453;
822
+ return value - Math.floor(value);
823
+ }
824
+ function createWebGlBenchmarkRenderer(canvas) {
825
+ const gl = safeGetCanvasContext(canvas, "webgl2") ?? safeGetCanvasContext(canvas, "webgl");
826
+ if (!gl) return null;
827
+ const vertexShader = createShader(
828
+ gl,
829
+ gl.VERTEX_SHADER,
830
+ `
831
+ attribute vec2 a_position;
832
+ attribute vec4 a_color;
833
+ attribute float a_size;
834
+ varying vec4 v_color;
835
+ void main() {
836
+ gl_Position = vec4(a_position, 0.0, 1.0);
837
+ gl_PointSize = a_size;
838
+ v_color = a_color;
839
+ }
840
+ `
841
+ );
842
+ const fragmentShader = createShader(
843
+ gl,
844
+ gl.FRAGMENT_SHADER,
845
+ `
846
+ precision mediump float;
847
+ varying vec4 v_color;
848
+ void main() {
849
+ vec2 point = gl_PointCoord - vec2(0.5);
850
+ float distanceFromCenter = length(point);
851
+ if (distanceFromCenter > 0.5) {
852
+ discard;
853
+ }
854
+ float glow = 1.0 - smoothstep(0.18, 0.5, distanceFromCenter);
855
+ gl_FragColor = vec4(v_color.rgb, v_color.a * (0.42 + glow * 0.58));
856
+ }
857
+ `
858
+ );
859
+ if (!vertexShader || !fragmentShader) return null;
860
+ const program = gl.createProgram();
861
+ if (!program) return null;
862
+ gl.attachShader(program, vertexShader);
863
+ gl.attachShader(program, fragmentShader);
864
+ gl.linkProgram(program);
865
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
866
+ gl.deleteProgram(program);
867
+ return null;
868
+ }
869
+ const positionLocation = gl.getAttribLocation(program, "a_position");
870
+ const colorLocation = gl.getAttribLocation(program, "a_color");
871
+ const sizeLocation = gl.getAttribLocation(program, "a_size");
872
+ const positionBuffer = gl.createBuffer();
873
+ const colorBuffer = gl.createBuffer();
874
+ const sizeBuffer = gl.createBuffer();
875
+ if (positionLocation < 0 || colorLocation < 0 || sizeLocation < 0 || !positionBuffer || !colorBuffer || !sizeBuffer)
876
+ return null;
877
+ gl.enable(gl.BLEND);
878
+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
879
+ gl.useProgram(program);
880
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
881
+ gl.enableVertexAttribArray(positionLocation);
882
+ gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
883
+ gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
884
+ gl.enableVertexAttribArray(colorLocation);
885
+ gl.vertexAttribPointer(colorLocation, 4, gl.FLOAT, false, 0, 0);
886
+ gl.bindBuffer(gl.ARRAY_BUFFER, sizeBuffer);
887
+ gl.enableVertexAttribArray(sizeLocation);
888
+ gl.vertexAttribPointer(sizeLocation, 1, gl.FLOAT, false, 0, 0);
889
+ return {
890
+ render: (positions, colors, sizes) => {
891
+ gl.viewport(0, 0, canvas.width, canvas.height);
892
+ gl.clearColor(0, 0, 0, 0.16);
893
+ gl.clear(gl.COLOR_BUFFER_BIT);
894
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
895
+ gl.bufferData(gl.ARRAY_BUFFER, positions, gl.DYNAMIC_DRAW);
896
+ gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
897
+ gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
898
+ gl.bindBuffer(gl.ARRAY_BUFFER, sizeBuffer);
899
+ gl.bufferData(gl.ARRAY_BUFFER, sizes, gl.STATIC_DRAW);
900
+ gl.drawArrays(gl.POINTS, 0, positions.length / 2);
901
+ },
902
+ renderer: typeof WebGL2RenderingContext !== "undefined" && gl instanceof WebGL2RenderingContext ? "WebGL2" : "WebGL"
903
+ };
904
+ }
905
+ function createCanvas2dBenchmarkRenderer(canvas) {
906
+ const context = safeGetCanvasContext(canvas, "2d");
907
+ if (!context) return null;
908
+ return {
909
+ render: (positions, colors, sizes) => {
910
+ context.clearRect(0, 0, canvas.width, canvas.height);
911
+ context.fillStyle = "rgba(0, 0, 0, 0.16)";
912
+ context.fillRect(0, 0, canvas.width, canvas.height);
913
+ const halfWidth = canvas.width / 2;
914
+ const halfHeight = canvas.height / 2;
915
+ for (let index = 0; index < positions.length; index += 2) {
916
+ const particleIndex = index / 2;
917
+ const x = halfWidth + positions[index] * halfWidth;
918
+ const y = halfHeight - positions[index + 1] * halfHeight;
919
+ context.fillStyle = `rgba(${Math.round(colors[particleIndex * 4] * 255)}, ${Math.round(colors[particleIndex * 4 + 1] * 255)}, ${Math.round(colors[particleIndex * 4 + 2] * 255)}, ${colors[particleIndex * 4 + 3]})`;
920
+ context.beginPath();
921
+ context.arc(x, y, sizes[particleIndex] / 2, 0, Math.PI * 2);
922
+ context.fill();
923
+ }
924
+ },
925
+ renderer: "Canvas2D fallback"
926
+ };
927
+ }
928
+ async function runCanvasBenchmark(canvas, getPointer, particleCount) {
929
+ const pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
930
+ const width = Math.max(window.innerWidth || 1280, 360);
931
+ const height = Math.max(window.innerHeight || 720, 360);
932
+ canvas.width = Math.round(width * pixelRatio);
933
+ canvas.height = Math.round(height * pixelRatio);
934
+ canvas.style.width = `${width}px`;
935
+ canvas.style.height = `${height}px`;
936
+ const renderer = createWebGlBenchmarkRenderer(canvas) ?? createCanvas2dBenchmarkRenderer(canvas);
937
+ const positions = new Float32Array(particleCount * 2);
938
+ const velocities = new Float32Array(particleCount * 2);
939
+ const colors = new Float32Array(particleCount * 4);
940
+ const sizes = new Float32Array(particleCount);
941
+ const palette = [
942
+ [0.92, 0.97, 1],
943
+ [0.62, 0.86, 1],
944
+ [0.73, 0.7, 1],
945
+ [1, 0.78, 0.9],
946
+ [0.72, 1, 0.88],
947
+ [1, 0.9, 0.66]
948
+ ];
949
+ for (let index = 0; index < particleCount; index += 1) {
950
+ const xSeed = benchmarkRandom(index + 1);
951
+ const ySeed = benchmarkRandom(index + 101);
952
+ const speedSeed = benchmarkRandom(index + 211);
953
+ const angle = benchmarkRandom(index + 307) * Math.PI * 2;
954
+ const speed = 16e-4 + speedSeed * 58e-4;
955
+ const paletteColor = palette[index % palette.length];
956
+ const brightness = 0.78 + benchmarkRandom(index + 401) * 0.28;
957
+ positions[index * 2] = xSeed * 1.9 - 0.95;
958
+ positions[index * 2 + 1] = ySeed * 1.9 - 0.95;
959
+ velocities[index * 2] = Math.cos(angle) * speed;
960
+ velocities[index * 2 + 1] = Math.sin(angle) * speed;
961
+ colors[index * 4] = Math.min(paletteColor[0] * brightness, 1);
962
+ colors[index * 4 + 1] = Math.min(paletteColor[1] * brightness, 1);
963
+ colors[index * 4 + 2] = Math.min(paletteColor[2] * brightness, 1);
964
+ colors[index * 4 + 3] = 0.46 + benchmarkRandom(index + 503) * 0.42;
965
+ sizes[index] = 5 + benchmarkRandom(index + 607) * 16;
966
+ }
967
+ const samples = [];
968
+ let frameCount = 0;
969
+ let drawCalls = 0;
970
+ const startedAt = await waitForAnimationFrame();
971
+ let previousTimestamp = startedAt;
972
+ let timestamp = startedAt;
973
+ while (timestamp - startedAt < BENCHMARK_CANVAS_DURATION_MS) {
974
+ timestamp = await waitForAnimationFrame();
975
+ const frameMs = timestamp - previousTimestamp;
976
+ const deltaScale = Math.min(Math.max(frameMs / BENCHMARK_TARGET_FRAME_MS, 0.25), 4);
977
+ previousTimestamp = timestamp;
978
+ samples.push(frameMs);
979
+ const pointer = getPointer();
980
+ for (let index = 0; index < particleCount; index += 1) {
981
+ const xIndex = index * 2;
982
+ const yIndex = xIndex + 1;
983
+ positions[xIndex] += velocities[xIndex] * deltaScale;
984
+ positions[yIndex] += velocities[yIndex] * deltaScale;
985
+ if (pointer.active) {
986
+ const dx = positions[xIndex] - pointer.x;
987
+ const dy = positions[yIndex] - pointer.y;
988
+ const distanceSquared = dx * dx + dy * dy;
989
+ const collisionRadius = 0.18;
990
+ if (distanceSquared > 0 && distanceSquared < collisionRadius * collisionRadius) {
991
+ const distance = Math.sqrt(distanceSquared);
992
+ const normalX = dx / distance;
993
+ const normalY = dy / distance;
994
+ const push = (collisionRadius - distance) * 0.32;
995
+ const velocityDotNormal = velocities[xIndex] * normalX + velocities[yIndex] * normalY;
996
+ positions[xIndex] += normalX * push;
997
+ positions[yIndex] += normalY * push;
998
+ velocities[xIndex] += normalX * Math.max(3e-3, -velocityDotNormal * 1.35);
999
+ velocities[yIndex] += normalY * Math.max(3e-3, -velocityDotNormal * 1.35);
1000
+ }
1001
+ }
1002
+ const speed = Math.hypot(velocities[xIndex], velocities[yIndex]);
1003
+ const maxSpeed = 0.018;
1004
+ if (speed > maxSpeed) {
1005
+ velocities[xIndex] = velocities[xIndex] / speed * maxSpeed;
1006
+ velocities[yIndex] = velocities[yIndex] / speed * maxSpeed;
1007
+ }
1008
+ if (positions[xIndex] <= -1 || positions[xIndex] >= 1) {
1009
+ velocities[xIndex] *= -1;
1010
+ positions[xIndex] = Math.min(Math.max(positions[xIndex], -1), 1);
1011
+ }
1012
+ if (positions[yIndex] <= -1 || positions[yIndex] >= 1) {
1013
+ velocities[yIndex] *= -1;
1014
+ positions[yIndex] = Math.min(Math.max(positions[yIndex], -1), 1);
1015
+ }
1016
+ }
1017
+ renderer?.render(positions, colors, sizes);
1018
+ drawCalls += 1;
1019
+ frameCount += 1;
1020
+ }
1021
+ const elapsedMs = Math.max(timestamp - startedAt, BENCHMARK_TARGET_FRAME_MS);
1022
+ const frameTimes = samples.length > 0 ? samples : [elapsedMs];
1023
+ const averageFrameMs = elapsedMs / Math.max(frameCount, 1);
1024
+ const sortedFrameTimes = [...frameTimes].sort((left, right) => left - right);
1025
+ const p99FrameMs = sortedFrameTimes[Math.min(sortedFrameTimes.length - 1, Math.floor(sortedFrameTimes.length * 0.99))];
1026
+ const expectedFrames = BENCHMARK_CANVAS_DURATION_MS / BENCHMARK_TARGET_FRAME_MS;
1027
+ return {
1028
+ averageFrameMs,
1029
+ drawCalls,
1030
+ droppedFrames: Math.max(0, Math.round(expectedFrames - frameCount)),
1031
+ elapsedMs,
1032
+ fps: frameCount / elapsedMs * 1e3,
1033
+ frameCount,
1034
+ maxFrameMs: Math.max(...frameTimes),
1035
+ onePercentLowFps: p99FrameMs > 0 ? 1e3 / p99FrameMs : 0,
1036
+ particleCount,
1037
+ renderer: renderer?.renderer ?? "Canvas unavailable",
1038
+ resolution: `${canvas.width}x${canvas.height}`
1039
+ };
1040
+ }
1041
+ function formatHourBucket(value) {
1042
+ const date = new Date(value);
1043
+ if (Number.isNaN(date.getTime())) {
1044
+ return value;
1045
+ }
1046
+ const year = date.getFullYear();
1047
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1048
+ const day = String(date.getDate()).padStart(2, "0");
1049
+ const hours = String(date.getHours()).padStart(2, "0");
1050
+ return `${year}/${month}/${day} ${hours}:00`;
1051
+ }
1052
+ function toHourSectionId(bucket) {
1053
+ return `archive-hour-${bucket.replaceAll("/", "-").replaceAll(":", "-").replaceAll(" ", "-")}`;
1054
+ }
1055
+ function translateDeviceError(message) {
1056
+ if (!message) return { summary: "없음" };
1057
+ if (message === "No serial ports detected.") return { summary: "포트 없음", original: message };
1058
+ if (message === "Failed to open port.") return { summary: "포트 열기 실패", original: message };
1059
+ if (message === "Heartbeat timeout: no READY/PONG received.") {
1060
+ return {
1061
+ summary: "핸드셰이크 타임아웃",
1062
+ original: message
1063
+ };
1064
+ }
1065
+ if (message.includes("Port is not open")) return { summary: "포트 닫힘", original: message };
1066
+ if (message.includes("File not found") || message.includes("cannot find the file")) {
1067
+ return { summary: "포트 없음", original: message };
1068
+ }
1069
+ if (message.includes("Access denied") || message.includes("permission denied")) {
1070
+ return {
1071
+ summary: "포트 접근 거부",
1072
+ original: message
1073
+ };
1074
+ }
1075
+ if (message.includes("Resource busy") || message.includes("busy")) {
1076
+ return {
1077
+ summary: "포트 사용 중",
1078
+ original: message
1079
+ };
1080
+ }
1081
+ if (message.includes("UNKNOWN_COMMAND")) return { summary: "알 수 없는 명령", original: message };
1082
+ if (message.includes("INVALID_TARGET")) return { summary: "잘못된 대상", original: message };
1083
+ if (message.includes("INVALID_ACTION")) return { summary: "잘못된 동작", original: message };
1084
+ if (message.includes("ALREADY_IN_TARGET")) return { summary: "이미 해당 화면", original: message };
1085
+ if (message.includes("BUSY")) {
1086
+ return {
1087
+ summary: "처리 불가 상태",
1088
+ original: message
1089
+ };
1090
+ }
1091
+ if (message.includes("INTERNAL_ERROR")) {
1092
+ return {
1093
+ summary: "내부 오류",
1094
+ original: message
1095
+ };
1096
+ }
1097
+ return { summary: "오류", original: message };
1098
+ }
1099
+ function translateDeviceMessage(message) {
1100
+ if (!message) return { summary: "아직 없음" };
1101
+ if (message === "No serial ports detected." || message === "Failed to open port." || message === "Heartbeat timeout: no READY/PONG received." || message.includes("Port is not open") || message.includes("File not found") || message.includes("cannot find the file") || message.includes("Access denied") || message.includes("permission denied") || message.includes("Resource busy") || message.includes("UNKNOWN_COMMAND") || message.includes("INVALID_TARGET") || message.includes("INVALID_ACTION") || message.includes("ALREADY_IN_TARGET") || message.includes("BUSY") || message.includes("INTERNAL_ERROR")) {
1102
+ return translateDeviceError(message);
1103
+ }
1104
+ if (message.startsWith("Connected to ") && message.includes("Waiting for READY/PONG.")) {
1105
+ return {
1106
+ summary: "연결 시도 중",
1107
+ original: message
1108
+ };
1109
+ }
1110
+ if (message === "Disconnected from device.") return { summary: "연결 해제", original: message };
1111
+ if (message === "READY") {
1112
+ return {
1113
+ summary: "통신 준비 완료",
1114
+ original: message
1115
+ };
1116
+ }
1117
+ if (message === "PONG") {
1118
+ return {
1119
+ summary: "PONG 응답",
1120
+ original: message
1121
+ };
1122
+ }
1123
+ if (message === "PING") {
1124
+ return {
1125
+ summary: "PING 전송",
1126
+ original: message
1127
+ };
1128
+ }
1129
+ if (message.startsWith("DTOA ")) {
1130
+ const target = message.slice(5).trim();
1131
+ return {
1132
+ summary: target ? `화면 전환 요청: ${target}` : "화면 전환 요청",
1133
+ original: message
1134
+ };
1135
+ }
1136
+ if (message.startsWith("ATOD ")) {
1137
+ const [, target, action] = message.split(/\s+/);
1138
+ return {
1139
+ summary: target && action ? `장치 제어 요청: ${target} ${action}` : "장치 제어 요청",
1140
+ original: message
1141
+ };
1142
+ }
1143
+ if (message.startsWith("ACK ")) {
1144
+ const target = message.slice(4).trim();
1145
+ return {
1146
+ summary: target ? `처리 완료: ${target}` : "처리 완료",
1147
+ original: message
1148
+ };
1149
+ }
1150
+ if (message.startsWith("ERR ")) {
1151
+ const [, code, target] = message.split(/\s+/);
1152
+ const translatedError = translateDeviceError(
1153
+ code ? `${code}${target ? ` ${target}` : ""}` : message
1154
+ );
1155
+ return { summary: translatedError.summary, original: message };
1156
+ }
1157
+ if (message.includes("Preview mode")) {
1158
+ return {
1159
+ summary: "미리보기 모드",
1160
+ original: message
1161
+ };
1162
+ }
1163
+ return { summary: "수신 로그", original: message };
1164
+ }
1165
+ function translateLog(raw) {
1166
+ return translateDeviceMessage(raw).summary;
1167
+ }
1168
+ function getWindowModeLabel(mode) {
1169
+ if (mode === "kiosk") return "키오스크";
1170
+ if (mode === "fullscreen") return "전체화면";
1171
+ return "창모드";
1172
+ }
1173
+ function getShortcutKeyFromCode(code, fallbackKey) {
1174
+ if (code.startsWith("Key") && code.length === 4) {
1175
+ return code.slice(3).toUpperCase();
1176
+ }
1177
+ if (code.startsWith("Digit") && code.length === 6) {
1178
+ return code.slice(5);
1179
+ }
1180
+ const codeMap = {
1181
+ Space: "Space",
1182
+ Enter: "Enter",
1183
+ Escape: "Escape",
1184
+ Tab: "Tab",
1185
+ Backspace: "Backspace",
1186
+ Delete: "Delete",
1187
+ ArrowUp: "ArrowUp",
1188
+ ArrowDown: "ArrowDown",
1189
+ ArrowLeft: "ArrowLeft",
1190
+ ArrowRight: "ArrowRight"
1191
+ };
1192
+ if (code in codeMap) {
1193
+ return codeMap[code];
1194
+ }
1195
+ if (/^F\d{1,2}$/i.test(code)) {
1196
+ return code.toUpperCase();
1197
+ }
1198
+ return fallbackKey === " " ? "Space" : fallbackKey.length === 1 ? fallbackKey.toUpperCase() : `${fallbackKey.slice(0, 1).toUpperCase()}${fallbackKey.slice(1)}`;
1199
+ }
1200
+ function formatShortcutFromKeyboardEvent(event) {
1201
+ if (["Control", "Shift", "Alt", "Meta"].includes(event.key)) {
1202
+ return null;
1203
+ }
1204
+ const parts = [];
1205
+ if (event.ctrlKey || event.metaKey) {
1206
+ parts.push("CmdOrCtrl");
1207
+ }
1208
+ if (event.altKey) {
1209
+ parts.push("Alt");
1210
+ }
1211
+ if (event.shiftKey) {
1212
+ parts.push("Shift");
1213
+ }
1214
+ const normalizedKey = getShortcutKeyFromCode(event.code, event.key);
1215
+ parts.push(normalizedKey);
1216
+ return parts.join("+");
1217
+ }
1218
+ function ShortcutKeyChips({ accelerator }) {
1219
+ const primaryModifier = typeof navigator !== "undefined" && /mac|iphone|ipad|ipod/i.test(navigator.platform) ? "Cmd" : "Ctrl";
1220
+ return /* @__PURE__ */ jsx("span", { className: "inline-flex flex-wrap items-center gap-1.5", children: accelerator.split("+").map((part, index) => /* @__PURE__ */ jsx(
1221
+ "kbd",
1222
+ {
1223
+ className: "rounded-md border border-border-soft bg-app-bg px-2 py-1 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-text shadow-[inset_0_-1px_0_rgba(255,255,255,0.08)]",
1224
+ children: part === "CmdOrCtrl" ? primaryModifier : part
1225
+ },
1226
+ `${accelerator}-${part}-${index}`
1227
+ )) });
1228
+ }
1229
+ function createArduinoRowId(prefix) {
1230
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
1231
+ return `${prefix}-${crypto.randomUUID()}`;
1232
+ }
1233
+ return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
1234
+ }
1235
+ function uniqueNonEmpty(values) {
1236
+ return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)));
1237
+ }
1238
+ function getArduinoOutputActionOptions(output, signalDefinitions) {
1239
+ return uniqueNonEmpty([
1240
+ ...signalDefinitions.filter((signal) => signal.target === output.target).map((signal) => signal.action),
1241
+ output.action,
1242
+ "solved",
1243
+ "open",
1244
+ "unlock",
1245
+ "play",
1246
+ "reset"
1247
+ ]);
1248
+ }
1249
+ function getShortcutPreview(target, shortcuts) {
1250
+ const accelerator = shortcuts.find((shortcut) => shortcut.target === target)?.accelerator;
1251
+ if (!accelerator) {
1252
+ return { label: "단축키 없음", warning: "globalShortcuts에 매칭되는 target이 없습니다." };
1253
+ }
1254
+ const converted = acceleratorToArduinoKeyboardShortcut(accelerator);
1255
+ if (!converted.ok) {
1256
+ return { label: "HID 폴백 미지원", warning: converted.warning };
1257
+ }
1258
+ return { label: accelerator };
1259
+ }
1260
+ function formatArduinoTargetOptionLabel(target, screens) {
1261
+ const matchingScreen = screens.find((availableScreen) => availableScreen.id === target);
1262
+ if (matchingScreen) {
1263
+ return `${target} - ${matchingScreen.title}`;
1264
+ }
1265
+ if (target === RESET_SCREEN_TARGET) {
1266
+ return `${target} - 관리자 페이지 이동`;
1267
+ }
1268
+ return target;
1269
+ }
1270
+ function AdminScreen({ gameState }) {
1271
+ const { appIconUrl, arduinoOutputSignals, projectConfig, screenDefinitions } = useProjectRuntime();
1272
+ const {
1273
+ bootstrap,
1274
+ connect,
1275
+ arduinoBoardConfig,
1276
+ deviceState,
1277
+ deviceSignalTargets,
1278
+ disconnect,
1279
+ loading,
1280
+ moveToScreen,
1281
+ ports,
1282
+ screens,
1283
+ shortcuts,
1284
+ updateArduinoBoardConfig,
1285
+ updateGlobalShortcuts,
1286
+ updateWindowMode,
1287
+ windowMode,
1288
+ windowModeLocked
1289
+ } = useAppStore();
1290
+ const arduinoBuild = useArduinoBuild();
1291
+ const [archiveModalOpen, setArchiveModalOpen] = useState(false);
1292
+ const [archiveList, setArchiveList] = useState([]);
1293
+ const [selectedArchive, setSelectedArchive] = useState("");
1294
+ const [archiveEntries, setArchiveEntries] = useState([]);
1295
+ const [archiveLoading, setArchiveLoading] = useState(false);
1296
+ const [archiveViewMode, setArchiveViewMode] = useState("processed");
1297
+ const [shortcutDrafts, setShortcutDrafts] = useState({});
1298
+ const [shortcutEditMode, setShortcutEditMode] = useState(false);
1299
+ const [shortcutStatus, setShortcutStatus] = useState("");
1300
+ const [shortcutError, setShortcutError] = useState("");
1301
+ const [shortcutGuideOpen, setShortcutGuideOpen] = useState(false);
1302
+ const [windowModeError, setWindowModeError] = useState("");
1303
+ const [benchmarkModalOpen, setBenchmarkModalOpen] = useState(false);
1304
+ const [benchmarkRunning, setBenchmarkRunning] = useState(false);
1305
+ const [benchmarkResults, setBenchmarkResults] = useState([]);
1306
+ const [benchmarkSnapshot, setBenchmarkSnapshot] = useState(null);
1307
+ const [benchmarkError, setBenchmarkError] = useState("");
1308
+ const [benchmarkCanvasActive, setBenchmarkCanvasActive] = useState(false);
1309
+ const [benchmarkParticleCount, setBenchmarkParticleCount] = useState(
1310
+ BENCHMARK_DEFAULT_PARTICLE_COUNT
1311
+ );
1312
+ const [mediaModalOpen, setMediaModalOpen] = useState(false);
1313
+ const [mediaLibrary, setMediaLibrary] = useState(null);
1314
+ const [mediaLoading, setMediaLoading] = useState(false);
1315
+ const [mediaError, setMediaError] = useState("");
1316
+ const [arduinoDraft, setArduinoDraft] = useState(arduinoBoardConfig);
1317
+ const [arduinoAdvancedFqbn, setArduinoAdvancedFqbn] = useState(false);
1318
+ const [arduinoSyncState, setArduinoSyncState] = useState(
1319
+ "idle"
1320
+ );
1321
+ const [arduinoError, setArduinoError] = useState("");
1322
+ const [arduinoPreview, setArduinoPreview] = useState(null);
1323
+ const [arduinoFirmwareOpen, setArduinoFirmwareOpen] = useState(false);
1324
+ const [arduinoPreviewOpen, setArduinoPreviewOpen] = useState(false);
1325
+ const benchmarkCanvasRef = useRef(null);
1326
+ const benchmarkPointerRef = useRef({ active: false, x: 0, y: 0 });
1327
+ const arduinoAutoSaveTimerRef = useRef(void 0);
1328
+ const arduinoEditSequenceRef = useRef(0);
1329
+ const arduinoSaveSequenceRef = useRef(0);
1330
+ const registeredSceneScreens = screens.filter(
1331
+ (availableScreen) => availableScreen.kind === "scene"
1332
+ );
1333
+ const adminShortcut = shortcuts.find((shortcut) => shortcut.target === "admin")?.accelerator ?? buildDefaultGlobalShortcuts(screenDefinitions).find(
1334
+ (shortcut) => shortcut.target === "admin"
1335
+ )?.accelerator ?? "";
1336
+ const visibleArchiveEntries = archiveViewMode === "raw" ? archiveEntries : archiveEntries.filter((entry) => !shouldHideProcessedLog(entry.raw, entry.origin));
1337
+ const archiveHourSections = visibleArchiveEntries.reduce((sections, entry) => {
1338
+ const bucket = formatHourBucket(entry.createdAt);
1339
+ const lastSection = sections.at(-1);
1340
+ if (lastSection?.bucket === bucket) {
1341
+ lastSection.entries.push(entry);
1342
+ return sections;
1343
+ }
1344
+ sections.push({
1345
+ bucket,
1346
+ entries: [entry]
1347
+ });
1348
+ return sections;
1349
+ }, []);
1350
+ useEffect(() => {
1351
+ setShortcutDrafts(
1352
+ Object.fromEntries(
1353
+ screens.map((availableScreen) => [
1354
+ availableScreen.id,
1355
+ shortcuts.find((shortcut) => shortcut.target === availableScreen.id)?.accelerator ?? ""
1356
+ ])
1357
+ )
1358
+ );
1359
+ }, [screens, shortcuts]);
1360
+ useEffect(() => {
1361
+ if (!benchmarkCanvasActive) {
1362
+ benchmarkPointerRef.current = { active: false, x: 0, y: 0 };
1363
+ return;
1364
+ }
1365
+ const updatePointer = (event) => {
1366
+ const width = Math.max(window.innerWidth || 1, 1);
1367
+ const height = Math.max(window.innerHeight || 1, 1);
1368
+ benchmarkPointerRef.current = {
1369
+ active: true,
1370
+ x: event.clientX / width * 2 - 1,
1371
+ y: 1 - event.clientY / height * 2
1372
+ };
1373
+ };
1374
+ const deactivatePointer = () => {
1375
+ benchmarkPointerRef.current = {
1376
+ ...benchmarkPointerRef.current,
1377
+ active: false
1378
+ };
1379
+ };
1380
+ window.addEventListener("pointermove", updatePointer);
1381
+ window.addEventListener("mousemove", updatePointer);
1382
+ window.addEventListener("pointerleave", deactivatePointer);
1383
+ window.addEventListener("blur", deactivatePointer);
1384
+ return () => {
1385
+ window.removeEventListener("pointermove", updatePointer);
1386
+ window.removeEventListener("mousemove", updatePointer);
1387
+ window.removeEventListener("pointerleave", deactivatePointer);
1388
+ window.removeEventListener("blur", deactivatePointer);
1389
+ };
1390
+ }, [benchmarkCanvasActive]);
1391
+ useEffect(() => {
1392
+ if (arduinoFirmwareOpen) {
1393
+ return;
1394
+ }
1395
+ setArduinoDraft(arduinoBoardConfig);
1396
+ setArduinoAdvancedFqbn(
1397
+ arduinoBoardConfig.fqbn !== BOARD_PRESET_FQBN[arduinoBoardConfig.boardPreset]
1398
+ );
1399
+ }, [arduinoBoardConfig, arduinoFirmwareOpen]);
1400
+ useEffect(() => {
1401
+ return () => {
1402
+ if (arduinoAutoSaveTimerRef.current) {
1403
+ window.clearTimeout(arduinoAutoSaveTimerRef.current);
1404
+ }
1405
+ };
1406
+ }, []);
1407
+ useEffect(() => {
1408
+ if (!arduinoFirmwareOpen) {
1409
+ return;
1410
+ }
1411
+ const draftJson = JSON.stringify(arduinoDraft);
1412
+ const persistedJson = JSON.stringify(arduinoBoardConfig);
1413
+ if (draftJson === persistedJson) {
1414
+ return;
1415
+ }
1416
+ if (arduinoAutoSaveTimerRef.current) {
1417
+ window.clearTimeout(arduinoAutoSaveTimerRef.current);
1418
+ }
1419
+ setArduinoSyncState("saving");
1420
+ const draftToSave = arduinoDraft;
1421
+ const editSequenceAtSchedule = arduinoEditSequenceRef.current;
1422
+ arduinoAutoSaveTimerRef.current = window.setTimeout(() => {
1423
+ const saveSequence = arduinoSaveSequenceRef.current + 1;
1424
+ arduinoSaveSequenceRef.current = saveSequence;
1425
+ void updateArduinoBoardConfig(draftToSave).then(() => {
1426
+ if (arduinoSaveSequenceRef.current === saveSequence && arduinoEditSequenceRef.current === editSequenceAtSchedule) {
1427
+ setArduinoSyncState("saved");
1428
+ setArduinoError("");
1429
+ }
1430
+ }).catch(() => {
1431
+ if (arduinoSaveSequenceRef.current === saveSequence && arduinoEditSequenceRef.current === editSequenceAtSchedule) {
1432
+ setArduinoSyncState("error");
1433
+ setArduinoError(
1434
+ "Arduino 보드 설정 자동 저장에 실패했습니다. 핀, 대상, 동작 값을 확인하세요."
1435
+ );
1436
+ }
1437
+ });
1438
+ }, ARDUINO_AUTO_SAVE_DEBOUNCE_MS);
1439
+ }, [arduinoBoardConfig, arduinoDraft, arduinoFirmwareOpen, updateArduinoBoardConfig]);
1440
+ const openArchiveModal = async () => {
1441
+ setArchiveModalOpen(true);
1442
+ setArchiveViewMode("processed");
1443
+ setArchiveLoading(true);
1444
+ const archives = await getGameApi().listDeviceLogArchives();
1445
+ setArchiveList(archives);
1446
+ const firstArchive = archives[0]?.dateKey ?? "";
1447
+ setSelectedArchive(firstArchive);
1448
+ setArchiveEntries(firstArchive ? await getGameApi().getDeviceLogArchive(firstArchive) : []);
1449
+ setArchiveLoading(false);
1450
+ };
1451
+ const refreshMediaLibrary = async () => {
1452
+ setMediaLoading(true);
1453
+ setMediaError("");
1454
+ try {
1455
+ setMediaLibrary(await getGameApi().getMediaLibrary());
1456
+ } catch {
1457
+ setMediaError("외부 리소스 목록을 불러오지 못했습니다.");
1458
+ } finally {
1459
+ setMediaLoading(false);
1460
+ }
1461
+ };
1462
+ const openMediaModal = async () => {
1463
+ setMediaModalOpen(true);
1464
+ await refreshMediaLibrary();
1465
+ };
1466
+ const openMediaFolder = async () => {
1467
+ setMediaError("");
1468
+ try {
1469
+ const result = await getGameApi().openMediaFolder();
1470
+ if (!result.ok) {
1471
+ setMediaError(result.message ?? "외부 리소스 폴더를 열지 못했습니다.");
1472
+ }
1473
+ } catch {
1474
+ setMediaError("외부 리소스 폴더를 열지 못했습니다.");
1475
+ }
1476
+ };
1477
+ const selectArchive = async (dateKey) => {
1478
+ setSelectedArchive(dateKey);
1479
+ setArchiveLoading(true);
1480
+ setArchiveEntries(await getGameApi().getDeviceLogArchive(dateKey));
1481
+ setArchiveLoading(false);
1482
+ };
1483
+ const updateShortcutDraft = (target, accelerator) => {
1484
+ setShortcutDrafts((current) => ({
1485
+ ...current,
1486
+ [target]: accelerator
1487
+ }));
1488
+ setShortcutError("");
1489
+ setShortcutStatus("");
1490
+ };
1491
+ const restoreShortcutDrafts = () => {
1492
+ setShortcutDrafts(
1493
+ Object.fromEntries(
1494
+ screens.map((availableScreen) => [
1495
+ availableScreen.id,
1496
+ shortcuts.find((shortcut) => shortcut.target === availableScreen.id)?.accelerator ?? ""
1497
+ ])
1498
+ )
1499
+ );
1500
+ setShortcutError("");
1501
+ };
1502
+ const cancelShortcutEditMode = () => {
1503
+ restoreShortcutDrafts();
1504
+ setShortcutEditMode(false);
1505
+ setShortcutStatus("");
1506
+ };
1507
+ const toggleShortcutEditMode = () => {
1508
+ setShortcutEditMode((current) => !current);
1509
+ setShortcutError("");
1510
+ setShortcutStatus("");
1511
+ };
1512
+ const saveShortcutDrafts = async () => {
1513
+ const normalizedShortcuts = [];
1514
+ for (const availableScreen of screens) {
1515
+ const accelerator = normalizeShortcutAccelerator(shortcutDrafts[availableScreen.id] ?? "");
1516
+ if (!accelerator) {
1517
+ continue;
1518
+ }
1519
+ normalizedShortcuts.push({ accelerator, target: availableScreen.id });
1520
+ }
1521
+ try {
1522
+ await updateGlobalShortcuts(normalizedShortcuts);
1523
+ setShortcutError("");
1524
+ setShortcutStatus("단축키를 저장했습니다.");
1525
+ setShortcutEditMode(false);
1526
+ } catch {
1527
+ setShortcutError("단축키 저장에 실패했습니다. 입력값과 대상 화면을 확인하세요.");
1528
+ setShortcutStatus("");
1529
+ }
1530
+ };
1531
+ const toggleKioskMode = async () => {
1532
+ try {
1533
+ setWindowModeError("");
1534
+ await updateWindowMode(windowMode === "kiosk" ? "windowed" : "kiosk");
1535
+ } catch {
1536
+ setWindowModeError("키오스크 모드 전환에 실패했습니다.");
1537
+ }
1538
+ };
1539
+ const quitApp = () => {
1540
+ if (!window.confirm("프로그램을 종료하시겠습니까?")) {
1541
+ return;
1542
+ }
1543
+ getGameApi().quitApp();
1544
+ };
1545
+ const runPerformanceCheck = async () => {
1546
+ const gameApi = getGameApi();
1547
+ setBenchmarkRunning(true);
1548
+ setBenchmarkResults([]);
1549
+ setBenchmarkSnapshot(null);
1550
+ setBenchmarkError("");
1551
+ const record = (result) => {
1552
+ setBenchmarkResults((current) => [...current, result]);
1553
+ };
1554
+ try {
1555
+ const snapshotMeasurement = await measureDuration(() => gameApi.getPerformanceSnapshot());
1556
+ setBenchmarkSnapshot(snapshotMeasurement.value);
1557
+ record({
1558
+ id: "snapshot",
1559
+ label: "시스템 스냅샷",
1560
+ value: `${formatDuration(snapshotMeasurement.elapsedMs)} · ${getDurationBenchmarkVerdict(snapshotMeasurement.elapsedMs)}`,
1561
+ detail: `${snapshotMeasurement.value.platform}/${snapshotMeasurement.value.arch} · 앱 ${snapshotMeasurement.value.appVersion}`,
1562
+ tone: getDurationTone(snapshotMeasurement.elapsedMs)
1563
+ });
1564
+ const rendererMemory = snapshotMeasurement.value.appMetrics.find(
1565
+ (metric) => metric.type === "Tab"
1566
+ );
1567
+ record({
1568
+ id: "main-memory",
1569
+ label: "Main 프로세스 메모리",
1570
+ value: `${formatKilobytes(snapshotMeasurement.value.processMemory.privateKb)} · 참고`,
1571
+ detail: `공유 ${formatKilobytes(snapshotMeasurement.value.processMemory.sharedKb)}`,
1572
+ tone: "normal"
1573
+ });
1574
+ record({
1575
+ id: "renderer-memory",
1576
+ label: "Renderer 메모리",
1577
+ value: rendererMemory ? `${formatKilobytes(rendererMemory.memoryWorkingSetKb)} · 참고` : "측정 불가 · 건너뜀",
1578
+ detail: rendererMemory ? `CPU ${rendererMemory.cpuPercent.toFixed(1)}% · PID ${rendererMemory.pid}` : "Electron process metrics에 renderer 항목이 없습니다.",
1579
+ tone: rendererMemory ? "normal" : "skipped"
1580
+ });
1581
+ const portsMeasurement = await measureDuration(() => gameApi.listPorts());
1582
+ record({
1583
+ id: "list-ports",
1584
+ label: "포트 조회",
1585
+ value: `${formatDuration(portsMeasurement.elapsedMs)} · ${getDurationBenchmarkVerdict(portsMeasurement.elapsedMs)}`,
1586
+ detail: `${portsMeasurement.value.length}개 포트`,
1587
+ tone: getDurationTone(portsMeasurement.elapsedMs)
1588
+ });
1589
+ const deviceMeasurement = await measureDuration(() => gameApi.getDeviceState());
1590
+ record({
1591
+ id: "device-state",
1592
+ label: "디바이스 상태 조회",
1593
+ value: `${formatDuration(deviceMeasurement.elapsedMs)} · ${getDurationBenchmarkVerdict(deviceMeasurement.elapsedMs)}`,
1594
+ detail: statusLabel[deviceMeasurement.value.status],
1595
+ tone: getDurationTone(deviceMeasurement.elapsedMs)
1596
+ });
1597
+ if (deviceMeasurement.value.status === "connected") {
1598
+ const pingMeasurement = await measureDuration(() => gameApi.sendCommand({ type: "ping" }));
1599
+ record({
1600
+ id: "device-ping",
1601
+ label: "디바이스 Ping 왕복",
1602
+ value: `${formatDuration(pingMeasurement.elapsedMs)} · ${getDurationBenchmarkVerdict(pingMeasurement.elapsedMs)}`,
1603
+ detail: pingMeasurement.value.message,
1604
+ tone: getDurationTone(pingMeasurement.elapsedMs)
1605
+ });
1606
+ } else {
1607
+ record({
1608
+ id: "device-ping",
1609
+ label: "디바이스 Ping 왕복",
1610
+ value: "건너뜀",
1611
+ detail: "장치가 연결된 상태에서만 측정합니다.",
1612
+ tone: "skipped"
1613
+ });
1614
+ }
1615
+ const frameSample = await sampleRendererFrames();
1616
+ record({
1617
+ id: "renderer-frames",
1618
+ label: "Renderer 프레임 샘플",
1619
+ value: `${frameSample.fps.toFixed(1)}fps · ${getFrameBenchmarkVerdict(frameSample.fps)}`,
1620
+ detail: `평균 ${frameSample.averageFrameMs.toFixed(1)}ms · 최저 ${frameSample.minFrameMs.toFixed(1)}ms · 최고 ${frameSample.maxFrameMs.toFixed(1)}ms`,
1621
+ tone: getFrameTone(frameSample.fps)
1622
+ });
1623
+ const renderMeasurement = await measureDuration(async () => {
1624
+ flushSync(() => setBenchmarkCanvasActive(true));
1625
+ await Promise.resolve();
1626
+ const canvas = benchmarkCanvasRef.current;
1627
+ if (!canvas) {
1628
+ throw new Error("Benchmark canvas is not available.");
1629
+ }
1630
+ return runCanvasBenchmark(canvas, () => benchmarkPointerRef.current, benchmarkParticleCount);
1631
+ });
1632
+ record({
1633
+ id: "renderer-dom-render",
1634
+ label: "WebGL 렌더링 벤치마크",
1635
+ value: `${renderMeasurement.value.fps.toFixed(1)}fps · ${getFrameBenchmarkVerdict(renderMeasurement.value.fps)}`,
1636
+ detail: `${renderMeasurement.value.renderer} · ${formatDuration(renderMeasurement.value.elapsedMs)} 동안 ${renderMeasurement.value.particleCount}개의 공 · ${renderMeasurement.value.frameCount}프레임 · 평균 ${renderMeasurement.value.averageFrameMs.toFixed(1)}ms · 최대 ${renderMeasurement.value.maxFrameMs.toFixed(1)}ms · 1% low ${renderMeasurement.value.onePercentLowFps.toFixed(1)}fps · 예상 누락 ${renderMeasurement.value.droppedFrames}프레임 · ${renderMeasurement.value.drawCalls} draw · ${renderMeasurement.value.resolution}`,
1637
+ tone: getFrameTone(renderMeasurement.value.fps)
1638
+ });
1639
+ } catch {
1640
+ setBenchmarkError("성능 체크 실행 중 오류가 발생했습니다. 앱 로그를 확인하세요.");
1641
+ } finally {
1642
+ setBenchmarkCanvasActive(false);
1643
+ setBenchmarkRunning(false);
1644
+ }
1645
+ };
1646
+ const arduinoTargetOptions = uniqueNonEmpty([
1647
+ ...screens.map((availableScreen) => availableScreen.id),
1648
+ ...shortcuts.map((shortcut) => shortcut.target),
1649
+ ...deviceSignalTargets,
1650
+ ...arduinoDraft.inputs.map((input) => input.target),
1651
+ RESET_SCREEN_TARGET
1652
+ ]);
1653
+ const arduinoOutputTargetOptions = uniqueNonEmpty([
1654
+ ...arduinoOutputSignals.map((signal) => signal.target),
1655
+ ...arduinoDraft.outputs.map((output) => output.target)
1656
+ ]);
1657
+ const arduinoSyncLabel = {
1658
+ idle: "저장 대기",
1659
+ saving: "자동 저장 중",
1660
+ saved: "자동 저장 완료",
1661
+ error: "자동 저장 실패"
1662
+ }[arduinoSyncState];
1663
+ const arduinoSyncIcon = {
1664
+ idle: "○",
1665
+ saving: "◔",
1666
+ saved: "●",
1667
+ error: "!"
1668
+ }[arduinoSyncState];
1669
+ const arduinoSyncTone = {
1670
+ idle: "border-border-soft bg-surface text-text-dim",
1671
+ saving: "border-border-strong bg-surface-selected text-text",
1672
+ saved: "border-aqua_signal/40 bg-aqua_signal/10 text-aqua_signal",
1673
+ error: "border-log-error-label-text/50 bg-log-error-bg text-log-error-label-text"
1674
+ }[arduinoSyncState];
1675
+ const updateArduinoDraft = (patch) => {
1676
+ arduinoEditSequenceRef.current += 1;
1677
+ setArduinoDraft((current) => ({
1678
+ ...current,
1679
+ ...patch
1680
+ }));
1681
+ setArduinoSyncState("idle");
1682
+ setArduinoError("");
1683
+ };
1684
+ const updateArduinoBoardPreset = (boardPreset) => {
1685
+ arduinoEditSequenceRef.current += 1;
1686
+ setArduinoDraft((current) => ({
1687
+ ...current,
1688
+ boardPreset,
1689
+ fqbn: arduinoAdvancedFqbn ? current.fqbn : resolveArduinoBoardFqbn(boardPreset)
1690
+ }));
1691
+ setArduinoSyncState("idle");
1692
+ setArduinoError("");
1693
+ };
1694
+ const updateArduinoInput = (id, patch) => {
1695
+ updateArduinoDraft({
1696
+ inputs: arduinoDraft.inputs.map(
1697
+ (input) => input.id === id ? {
1698
+ ...input,
1699
+ ...patch
1700
+ } : input
1701
+ )
1702
+ });
1703
+ };
1704
+ const updateArduinoOutput = (id, patch) => {
1705
+ updateArduinoDraft({
1706
+ outputs: arduinoDraft.outputs.map(
1707
+ (output) => output.id === id ? {
1708
+ ...output,
1709
+ ...patch
1710
+ } : output
1711
+ )
1712
+ });
1713
+ };
1714
+ const addArduinoInput = () => {
1715
+ updateArduinoDraft({
1716
+ inputs: [
1717
+ ...arduinoDraft.inputs,
1718
+ {
1719
+ id: createArduinoRowId("input"),
1720
+ pin: 2,
1721
+ activeLow: true,
1722
+ debounceMs: 100,
1723
+ target: screens.find((availableScreen) => availableScreen.kind === "scene")?.id ?? ""
1724
+ }
1725
+ ]
1726
+ });
1727
+ };
1728
+ const addArduinoOutput = () => {
1729
+ const defaultSignal = arduinoOutputSignals[0];
1730
+ updateArduinoDraft({
1731
+ outputs: [
1732
+ ...arduinoDraft.outputs,
1733
+ {
1734
+ id: createArduinoRowId("output"),
1735
+ target: defaultSignal?.target ?? "",
1736
+ action: defaultSignal?.action ?? "open",
1737
+ pin: 9,
1738
+ activeHigh: true,
1739
+ pulseMs: 0
1740
+ }
1741
+ ]
1742
+ });
1743
+ };
1744
+ const saveArduinoDraft = async () => {
1745
+ const saveSequence = arduinoSaveSequenceRef.current + 1;
1746
+ const editSequenceAtStart = arduinoEditSequenceRef.current;
1747
+ arduinoSaveSequenceRef.current = saveSequence;
1748
+ try {
1749
+ await updateArduinoBoardConfig(arduinoDraft);
1750
+ if (arduinoSaveSequenceRef.current === saveSequence && arduinoEditSequenceRef.current === editSequenceAtStart) {
1751
+ setArduinoSyncState("saved");
1752
+ setArduinoError("");
1753
+ }
1754
+ return true;
1755
+ } catch {
1756
+ if (arduinoSaveSequenceRef.current === saveSequence && arduinoEditSequenceRef.current === editSequenceAtStart) {
1757
+ setArduinoSyncState("error");
1758
+ setArduinoError("Arduino 보드 설정 저장에 실패했습니다. 핀, 대상, 동작 값을 확인하세요.");
1759
+ }
1760
+ return false;
1761
+ }
1762
+ };
1763
+ const previewArduinoSketch = async () => {
1764
+ if (!await saveArduinoDraft()) {
1765
+ return;
1766
+ }
1767
+ try {
1768
+ const preview = await arduinoBuild.preview();
1769
+ setArduinoPreview(preview);
1770
+ setArduinoPreviewOpen(true);
1771
+ setArduinoError("");
1772
+ } catch {
1773
+ setArduinoError("Arduino 스케치 미리보기에 실패했습니다.");
1774
+ }
1775
+ };
1776
+ const compileArduinoSketch = async () => {
1777
+ if (!await saveArduinoDraft()) {
1778
+ return;
1779
+ }
1780
+ try {
1781
+ await arduinoBuild.compile();
1782
+ } catch {
1783
+ setArduinoError("Arduino 컴파일 요청에 실패했습니다.");
1784
+ }
1785
+ };
1786
+ const uploadArduinoSketch = async () => {
1787
+ if (!await saveArduinoDraft()) {
1788
+ return;
1789
+ }
1790
+ try {
1791
+ await arduinoBuild.upload(deviceState.selectedPortPath);
1792
+ } catch {
1793
+ setArduinoError("Arduino 업로드 요청에 실패했습니다.");
1794
+ }
1795
+ };
1796
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1797
+ /* @__PURE__ */ jsx("main", { className: "h-screen overflow-hidden bg-[linear-gradient(180deg,#141414_0%,#FFFFFF05_52%,#1d1d1d_100%)] text-text", children: /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 flex-col px-4 py-4", children: [
1798
+ /* @__PURE__ */ jsx("header", { className: "rounded-xl px-5 py-4 backdrop-blur", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-4", children: [
1799
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
1800
+ /* @__PURE__ */ jsx(
1801
+ "img",
1802
+ {
1803
+ alt: projectConfig.appIconAlt,
1804
+ className: "h-12 w-12 rounded-lg border border-border-soft bg-surface-soft p-2",
1805
+ src: appIconUrl
1806
+ }
1807
+ ),
1808
+ /* @__PURE__ */ jsxs("div", { children: [
1809
+ /* @__PURE__ */ jsx("p", { className: "font-display text-2xl tracking-[0.24em] text-text", children: projectConfig.appName }),
1810
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs uppercase tracking-[0.25em] text-text-dim", children: projectConfig.appSubtitle })
1811
+ ] })
1812
+ ] }),
1813
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-stretch gap-3", children: [
1814
+ /* @__PURE__ */ jsxs(
1815
+ "button",
1816
+ {
1817
+ className: "rounded-xl border border-border-soft bg-surface px-4 py-3 text-left text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
1818
+ onClick: () => void openMediaModal(),
1819
+ type: "button",
1820
+ children: [
1821
+ /* @__PURE__ */ jsx("span", { className: "block text-[11px] uppercase tracking-[0.25em] text-text-dim", children: "리소스" }),
1822
+ /* @__PURE__ */ jsx("span", { className: "mt-2 block text-sm font-semibold text-text", children: "관리" }),
1823
+ /* @__PURE__ */ jsx("span", { className: "mt-1 block text-xs text-text-subtle", children: mediaLibrary ? `${mediaLibrary.assets.length}개 파일` : "외부 파일" })
1824
+ ]
1825
+ }
1826
+ ),
1827
+ /* @__PURE__ */ jsxs(
1828
+ "button",
1829
+ {
1830
+ className: "rounded-xl border border-border-soft bg-surface px-4 py-3 text-left text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
1831
+ onClick: () => setArduinoFirmwareOpen(true),
1832
+ type: "button",
1833
+ children: [
1834
+ /* @__PURE__ */ jsx("span", { className: "block text-[11px] uppercase tracking-[0.25em] text-text-dim", children: "아두이노" }),
1835
+ /* @__PURE__ */ jsx("span", { className: "mt-2 block text-sm font-semibold text-text", children: "업로드" }),
1836
+ /* @__PURE__ */ jsx("span", { className: "mt-1 block text-xs text-text-subtle", children: arduinoPhaseLabel[arduinoBuild.status.phase] })
1837
+ ]
1838
+ }
1839
+ ),
1840
+ /* @__PURE__ */ jsxs(
1841
+ "button",
1842
+ {
1843
+ className: "rounded-xl border border-border-soft bg-surface px-4 py-3 text-left text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
1844
+ onClick: () => setBenchmarkModalOpen(true),
1845
+ type: "button",
1846
+ children: [
1847
+ /* @__PURE__ */ jsx("span", { className: "block text-[11px] uppercase tracking-[0.25em] text-text-dim", children: "성능" }),
1848
+ /* @__PURE__ */ jsx("span", { className: "mt-2 block text-sm font-semibold text-text", children: "체크" }),
1849
+ /* @__PURE__ */ jsx("span", { className: "mt-1 block text-xs text-text-subtle", children: benchmarkRunning ? "측정 중" : benchmarkResults.length > 0 ? "결과 보기" : "벤치마크" })
1850
+ ]
1851
+ }
1852
+ ),
1853
+ /* @__PURE__ */ jsxs(
1854
+ "button",
1855
+ {
1856
+ className: "rounded-xl border border-border-soft bg-surface px-4 py-3 text-left text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
1857
+ onClick: () => setShortcutGuideOpen(true),
1858
+ type: "button",
1859
+ children: [
1860
+ /* @__PURE__ */ jsx("span", { className: "block text-[11px] uppercase tracking-[0.25em] text-text-dim", children: "단축키" }),
1861
+ /* @__PURE__ */ jsx("span", { className: "mt-2 block text-sm font-semibold text-text", children: "가이드" }),
1862
+ /* @__PURE__ */ jsx("span", { className: "mt-1 block text-xs text-text-subtle", children: "전역 단축키 보기" })
1863
+ ]
1864
+ }
1865
+ ),
1866
+ /* @__PURE__ */ jsxs("div", { className: "inline-block shrink-0 rounded-xl border border-border-soft bg-surface px-4 py-3", children: [
1867
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
1868
+ /* @__PURE__ */ jsxs("div", { children: [
1869
+ /* @__PURE__ */ jsx("p", { className: "text-[11px] uppercase tracking-[0.25em] text-text-dim", children: "실행 모드" }),
1870
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm font-semibold text-text", children: getWindowModeLabel(windowMode) }),
1871
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-subtle", children: "키오스크 OFF 시 창모드로 돌아갑니다." })
1872
+ ] }),
1873
+ /* @__PURE__ */ jsx(
1874
+ "button",
1875
+ {
1876
+ className: `rounded-lg px-3 py-2 text-xs font-semibold transition ${windowMode === "kiosk" ? "bg-button-primary-bg text-button-primary-text hover:bg-button-primary-hover" : "border border-border text-text hover:border-border-strong hover:bg-surface-hover"} disabled:cursor-not-allowed disabled:opacity-60`,
1877
+ disabled: loading || windowModeLocked,
1878
+ onClick: () => void toggleKioskMode(),
1879
+ type: "button",
1880
+ children: windowMode === "kiosk" ? "키오스크 끄기" : "키오스크 켜기"
1881
+ }
1882
+ )
1883
+ ] }),
1884
+ windowModeLocked ? /* @__PURE__ */ jsx("p", { className: "mt-3 text-xs text-log-error-label-text", children: "환경변수로 키오스크 모드가 강제되어 관리자 화면에서 변경할 수 없습니다." }) : null,
1885
+ windowModeError ? /* @__PURE__ */ jsx("p", { className: "mt-3 text-xs text-log-error-label-text", children: windowModeError }) : null
1886
+ ] }),
1887
+ /* @__PURE__ */ jsx(
1888
+ "button",
1889
+ {
1890
+ "aria-label": "프로그램 종료",
1891
+ className: "inline-flex h-14 w-14 shrink-0 items-center justify-center rounded-xl border border-transparent bg-transparent text-log-error-label-text transition hover:bg-white/5",
1892
+ onClick: () => void quitApp(),
1893
+ type: "button",
1894
+ title: "프로그램 종료",
1895
+ children: /* @__PURE__ */ jsxs(
1896
+ "svg",
1897
+ {
1898
+ "aria-hidden": "true",
1899
+ className: "h-5 w-5",
1900
+ fill: "none",
1901
+ stroke: "currentColor",
1902
+ strokeLinecap: "round",
1903
+ strokeLinejoin: "round",
1904
+ strokeWidth: "2",
1905
+ viewBox: "0 0 24 24",
1906
+ children: [
1907
+ /* @__PURE__ */ jsx("path", { d: "M12 2v10" }),
1908
+ /* @__PURE__ */ jsx("path", { d: "M18.36 6.64a9 9 0 1 1-12.72 0" })
1909
+ ]
1910
+ }
1911
+ )
1912
+ }
1913
+ )
1914
+ ] })
1915
+ ] }) }),
1916
+ /* @__PURE__ */ jsx("section", { className: "mt-4 flex min-h-0 flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsxs("div", { className: "grid min-h-0 flex-1 auto-rows-fr gap-4 overflow-hidden lg:grid-cols-[1.2fr_0.8fr]", children: [
1917
+ /* @__PURE__ */ jsxs("article", { className: "flex h-full min-h-0 flex-col overflow-hidden rounded-xl border border-border bg-surface p-5 shadow-2xl backdrop-blur", children: [
1918
+ /* @__PURE__ */ jsx("div", { className: "flex items-start justify-between gap-4", children: /* @__PURE__ */ jsxs("div", { children: [
1919
+ /* @__PURE__ */ jsx("h1", { className: "font-display text-2xl text-white", children: "디바이스 연결" }),
1920
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-text-muted", children: "시리얼 포트를 선택하고 연결/연결 해제 및 메시지 로그를 확인합니다." })
1921
+ ] }) }),
1922
+ /* @__PURE__ */ jsxs("div", { className: "mt-4 grid min-h-0 flex-1 gap-4 xl:grid-cols-[0.82fr_1.18fr]", children: [
1923
+ /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-col gap-3", children: [
1924
+ /* @__PURE__ */ jsxs("div", { className: "min-h-0 flex-1", children: [
1925
+ /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between", children: [
1926
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "포트 목록" }),
1927
+ /* @__PURE__ */ jsx(
1928
+ "button",
1929
+ {
1930
+ "aria-label": "포트 새로고침",
1931
+ className: "inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border text-sm text-text transition hover:border-border-strong hover:bg-surface-hover",
1932
+ onClick: () => void bootstrap(),
1933
+ type: "button",
1934
+ title: "포트 새로고침",
1935
+ children: "↻"
1936
+ }
1937
+ )
1938
+ ] }),
1939
+ /* @__PURE__ */ jsx("div", { className: "grid h-[420px] gap-2 overflow-auto pr-1", children: ports.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border px-4 py-5 text-sm text-text-muted", children: "감지된 COM 포트가 없습니다. 장치를 연결한 뒤 새로고침하세요." }) : ports.map((port) => /* @__PURE__ */ jsxs(
1940
+ "button",
1941
+ {
1942
+ className: `flex items-center justify-between rounded-lg border px-4 py-4 text-left transition ${port.path === deviceState.selectedPortPath ? "border-border-strong bg-surface-selected" : "border-border-soft bg-surface-subtle hover:border-border hover:bg-surface-hover"}`,
1943
+ onClick: () => void connect(port.path),
1944
+ type: "button",
1945
+ children: [
1946
+ /* @__PURE__ */ jsxs("span", { children: [
1947
+ /* @__PURE__ */ jsx("span", { className: "block font-semibold text-text", children: port.path }),
1948
+ /* @__PURE__ */ jsx("span", { className: "mt-1 block text-sm text-text-muted", children: port.manufacturer ?? "알 수 없는 디바이스" })
1949
+ ] }),
1950
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
1951
+ /* @__PURE__ */ jsx(
1952
+ "span",
1953
+ {
1954
+ "aria-hidden": "true",
1955
+ className: `text-lg leading-none ${port.path === deviceState.selectedPortPath ? statusIconTone[deviceState.status] : "text-text-dim"}`,
1956
+ children: port.path === deviceState.selectedPortPath ? statusIcon[deviceState.status] : "○"
1957
+ }
1958
+ ),
1959
+ /* @__PURE__ */ jsx(
1960
+ "span",
1961
+ {
1962
+ className: `text-xs uppercase tracking-[0.25em] ${port.path === deviceState.selectedPortPath ? statusIconTone[deviceState.status] : "text-text-dim"}`,
1963
+ children: port.path === deviceState.selectedPortPath ? statusLabel[deviceState.status] : "대기"
1964
+ }
1965
+ )
1966
+ ] })
1967
+ ]
1968
+ },
1969
+ port.path
1970
+ )) })
1971
+ ] }),
1972
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-3 lg:grid-cols-[1.15fr_0.85fr]", children: [
1973
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface-soft p-4", children: [
1974
+ /* @__PURE__ */ jsx("dt", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "선택된 포트" }),
1975
+ /* @__PURE__ */ jsx("dd", { className: "mt-2 break-all text-sm text-text", children: deviceState.selectedPortPath ?? "선택되지 않음" })
1976
+ ] }),
1977
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface-soft p-4", children: [
1978
+ /* @__PURE__ */ jsx("dt", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "마지막 핸드셰이크" }),
1979
+ /* @__PURE__ */ jsx("dd", { className: "mt-2 break-all text-sm text-text", children: formatLocalDateTime(deviceState.lastHandshakeAt) })
1980
+ ] })
1981
+ ] }),
1982
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-2", children: [
1983
+ /* @__PURE__ */ jsx(
1984
+ "button",
1985
+ {
1986
+ className: "rounded-lg bg-button-primary-bg px-4 py-2.5 text-sm font-semibold text-button-primary-text transition hover:bg-button-primary-hover disabled:cursor-not-allowed disabled:opacity-60",
1987
+ disabled: loading,
1988
+ onClick: () => void connect(deviceState.selectedPortPath),
1989
+ type: "button",
1990
+ children: "연결"
1991
+ }
1992
+ ),
1993
+ /* @__PURE__ */ jsx(
1994
+ "button",
1995
+ {
1996
+ className: "rounded-lg border border-border px-4 py-2.5 text-sm font-semibold text-text transition hover:border-border-strong hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-60",
1997
+ disabled: loading,
1998
+ onClick: () => void disconnect(),
1999
+ type: "button",
2000
+ children: "연결 해제"
2001
+ }
2002
+ )
2003
+ ] })
2004
+ ] }),
2005
+ /* @__PURE__ */ jsx("div", { className: "flex min-h-0 flex-col gap-3", children: /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col rounded-lg border border-border-soft bg-surface-strong p-4", children: [
2006
+ /* @__PURE__ */ jsxs("div", { className: "mb-2 flex shrink-0 items-center justify-between", children: [
2007
+ /* @__PURE__ */ jsx("h2", { className: "font-display text-lg text-text", children: "메시지 로그" }),
2008
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
2009
+ /* @__PURE__ */ jsx(
2010
+ "button",
2011
+ {
2012
+ className: "rounded-lg border border-border px-3 py-1.5 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2013
+ onClick: () => void openArchiveModal(),
2014
+ type: "button",
2015
+ children: "이전 기록 보기"
2016
+ }
2017
+ ),
2018
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-text-subtle", children: "최신 50개" })
2019
+ ] })
2020
+ ] }),
2021
+ /* @__PURE__ */ jsx("div", { className: "grid min-h-0 flex-1 content-start gap-2 overflow-auto pr-0", children: deviceState.messageLog.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border-soft px-4 py-6 text-sm text-text-subtle", children: "아직 기록된 로그가 없습니다." }) : deviceState.messageLog.map((entry) => {
2022
+ const origin = entry.origin ?? (entry.direction === "out" ? "out" : entry.direction === "system" ? "system" : "in");
2023
+ return /* @__PURE__ */ jsxs(
2024
+ "div",
2025
+ {
2026
+ className: `w-full max-w-[84%] rounded-lg px-3 py-3 ${logTone[entry.direction]} ${logLayoutTone[origin]}`,
2027
+ children: [
2028
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
2029
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2030
+ /* @__PURE__ */ jsx(
2031
+ "span",
2032
+ {
2033
+ className: `rounded-md px-2 py-1 text-xs uppercase tracking-[0.25em] ${logLabelTone[entry.direction]}`,
2034
+ children: logLabelByOrigin[origin]
2035
+ }
2036
+ ),
2037
+ entry.direction === "error" ? /* @__PURE__ */ jsx("span", { className: errorTextTone, children: "ERROR" }) : null
2038
+ ] }),
2039
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-text-subtle", children: formatLocalDateTime(entry.createdAt) })
2040
+ ] }),
2041
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-text", children: translateLog(entry.raw) }),
2042
+ /* @__PURE__ */ jsx("p", { className: "mt-1 break-all text-xs text-text-subtle", children: entry.raw })
2043
+ ]
2044
+ },
2045
+ entry.id
2046
+ );
2047
+ }) })
2048
+ ] }) })
2049
+ ] })
2050
+ ] }),
2051
+ /* @__PURE__ */ jsxs("article", { className: "flex h-full min-h-0 flex-col overflow-hidden rounded-xl border border-border bg-surface p-5 shadow-2xl backdrop-blur", children: [
2052
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
2053
+ /* @__PURE__ */ jsxs("div", { children: [
2054
+ /* @__PURE__ */ jsx("h2", { className: "font-display text-2xl text-text", children: "화면 전환" }),
2055
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-text-muted", children: "화면 레지스트리에 등록된 화면을 선택하여 현재 화면을 전환합니다." })
2056
+ ] }),
2057
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2058
+ shortcutEditMode ? /* @__PURE__ */ jsxs(Fragment, { children: [
2059
+ /* @__PURE__ */ jsx(
2060
+ "button",
2061
+ {
2062
+ className: "whitespace-nowrap rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2063
+ disabled: loading,
2064
+ onClick: cancelShortcutEditMode,
2065
+ type: "button",
2066
+ children: "취소"
2067
+ }
2068
+ ),
2069
+ /* @__PURE__ */ jsx(
2070
+ "button",
2071
+ {
2072
+ className: "whitespace-nowrap rounded-lg bg-button-primary-bg px-3 py-2 text-xs font-semibold text-button-primary-text transition hover:bg-button-primary-hover disabled:cursor-not-allowed disabled:opacity-60",
2073
+ disabled: loading,
2074
+ onClick: () => void saveShortcutDrafts(),
2075
+ type: "button",
2076
+ children: "저장"
2077
+ }
2078
+ )
2079
+ ] }) : /* @__PURE__ */ jsx(
2080
+ "button",
2081
+ {
2082
+ className: "whitespace-nowrap rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2083
+ onClick: toggleShortcutEditMode,
2084
+ type: "button",
2085
+ children: "단축키 편집"
2086
+ }
2087
+ ),
2088
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface-soft px-4 py-2 text-sm text-text-muted", children: [
2089
+ "현재 화면: ",
2090
+ gameState.currentStepId ?? "없음"
2091
+ ] })
2092
+ ] })
2093
+ ] }),
2094
+ shortcutEditMode && shortcutError ? /* @__PURE__ */ jsx("p", { className: "mt-3 text-sm text-log-error-label-text", children: shortcutError }) : null,
2095
+ shortcutEditMode && shortcutStatus ? /* @__PURE__ */ jsx("p", { className: "mt-3 text-sm text-aqua_signal", children: shortcutStatus }) : null,
2096
+ /* @__PURE__ */ jsx("div", { className: "mt-4 flex min-h-0 flex-1 flex-col gap-2 overflow-auto pr-1", children: registeredSceneScreens.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "rounded-xl border border-dashed border-border-soft bg-surface-soft px-4 py-5 text-sm text-text-muted", children: [
2097
+ /* @__PURE__ */ jsx("p", { className: "font-semibold text-text", children: "등록된 scene 화면이 아직 없습니다." }),
2098
+ /* @__PURE__ */ jsx("p", { className: "mt-2 leading-6", children: "먼저 `npm run generate:screen`을 실행하고 프롬프트에 따라 `id`, `title`, `kind`, `description`을 입력해 화면을 생성하세요. 생성 후 `src/screens`의 컴포넌트를 수정하면 이 패널에 자동으로 나타납니다." }),
2099
+ /* @__PURE__ */ jsx("p", { className: "mt-3 text-xs uppercase tracking-[0.2em] text-text-subtle", children: "guide: README - Screen Framework" })
2100
+ ] }) : screens.map((availableScreen) => {
2101
+ const selected = gameState.currentStepId === availableScreen.id;
2102
+ return /* @__PURE__ */ jsxs(
2103
+ "div",
2104
+ {
2105
+ className: `rounded-lg border px-4 py-3 text-left transition ${selected ? "border-border-strong bg-surface-selected" : "border-border-soft bg-surface-subtle"}`,
2106
+ children: [
2107
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-start gap-4", children: [
2108
+ /* @__PURE__ */ jsxs("div", { children: [
2109
+ /* @__PURE__ */ jsx("p", { className: "font-semibold text-text", children: availableScreen.title }),
2110
+ /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-sm text-text-muted", children: availableScreen.id }),
2111
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs uppercase tracking-[0.2em] text-text-subtle", children: availableScreen.kind }),
2112
+ shortcuts.filter(
2113
+ (shortcut) => shortcut.target === availableScreen.id
2114
+ ).length > 0 ? /* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-wrap gap-2", children: shortcuts.filter((shortcut) => shortcut.target === availableScreen.id).map((shortcut) => /* @__PURE__ */ jsx("span", { children: /* @__PURE__ */ jsx(ShortcutKeyChips, { accelerator: shortcut.accelerator }) }, `${availableScreen.id}-${shortcut.accelerator}`)) }) : null
2115
+ ] }),
2116
+ /* @__PURE__ */ jsxs("div", { className: "ml-auto flex items-center gap-2", children: [
2117
+ /* @__PURE__ */ jsx("span", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: selected ? "현재" : "대기" }),
2118
+ /* @__PURE__ */ jsx(
2119
+ "button",
2120
+ {
2121
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-60",
2122
+ disabled: loading || selected,
2123
+ onClick: () => {
2124
+ if (screenDefinitions.some(
2125
+ (screen) => screen.id === availableScreen.id
2126
+ )) {
2127
+ void moveToScreen(availableScreen.id);
2128
+ }
2129
+ },
2130
+ type: "button",
2131
+ children: "이동"
2132
+ }
2133
+ )
2134
+ ] })
2135
+ ] }),
2136
+ shortcutEditMode ? /* @__PURE__ */ jsxs("div", { className: "mt-4 border-t border-border-soft pt-4", children: [
2137
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("div", { children: [
2138
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-text", children: "단축키" }),
2139
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-subtle", children: "이 화면으로 이동할 키를 누르면 자동으로 입력됩니다." })
2140
+ ] }) }),
2141
+ /* @__PURE__ */ jsx("div", { className: "mt-3 grid gap-3", children: /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2142
+ "Shortcut",
2143
+ /* @__PURE__ */ jsx(
2144
+ "input",
2145
+ {
2146
+ className: "rounded-lg border border-border-soft bg-app-bg px-3 py-2 text-sm text-text outline-none transition focus:border-border-strong",
2147
+ onChange: (event) => updateShortcutDraft(availableScreen.id, event.target.value),
2148
+ onKeyDown: (event) => {
2149
+ event.preventDefault();
2150
+ if (event.key === "Backspace" || event.key === "Delete") {
2151
+ updateShortcutDraft(availableScreen.id, "");
2152
+ return;
2153
+ }
2154
+ const shortcut = formatShortcutFromKeyboardEvent(event);
2155
+ if (!shortcut) {
2156
+ return;
2157
+ }
2158
+ updateShortcutDraft(availableScreen.id, shortcut);
2159
+ },
2160
+ placeholder: "키를 누르세요",
2161
+ type: "text",
2162
+ value: shortcutDrafts[availableScreen.id] ?? ""
2163
+ }
2164
+ )
2165
+ ] }) })
2166
+ ] }) : null
2167
+ ]
2168
+ },
2169
+ availableScreen.id
2170
+ );
2171
+ }) }),
2172
+ arduinoFirmwareOpen ? createPortal(
2173
+ /* @__PURE__ */ jsx(
2174
+ "div",
2175
+ {
2176
+ className: "fixed inset-0 z-[70] bg-surface-strong text-text",
2177
+ onClick: () => setArduinoFirmwareOpen(false),
2178
+ children: /* @__PURE__ */ jsxs(
2179
+ "section",
2180
+ {
2181
+ className: "flex h-dvh w-screen flex-col overflow-hidden bg-surface-strong",
2182
+ onClick: (event) => event.stopPropagation(),
2183
+ children: [
2184
+ /* @__PURE__ */ jsx("div", { className: "shrink-0 border-b border-border-soft px-5 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
2185
+ /* @__PURE__ */ jsxs("div", { children: [
2186
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "Arduino" }),
2187
+ /* @__PURE__ */ jsx("h3", { className: "mt-1 font-display text-lg text-text", children: "펌웨어 생성" }),
2188
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-muted", children: "핀 매핑은 자동 저장되며, 스케치 생성, 컴파일, 업로드를 실행합니다." })
2189
+ ] }),
2190
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2191
+ /* @__PURE__ */ jsx(
2192
+ "span",
2193
+ {
2194
+ "aria-label": arduinoSyncLabel,
2195
+ className: `inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border text-sm ${arduinoSyncTone}`,
2196
+ title: arduinoSyncLabel,
2197
+ children: arduinoSyncIcon
2198
+ }
2199
+ ),
2200
+ /* @__PURE__ */ jsx("span", { className: "rounded-lg border border-border-soft bg-surface px-3 py-2 text-xs text-text-muted", children: arduinoPhaseLabel[arduinoBuild.status.phase] }),
2201
+ /* @__PURE__ */ jsx(
2202
+ "button",
2203
+ {
2204
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2205
+ onClick: () => setArduinoFirmwareOpen(false),
2206
+ type: "button",
2207
+ children: "닫기"
2208
+ }
2209
+ )
2210
+ ] })
2211
+ ] }) }),
2212
+ /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden px-5 py-4", children: /* @__PURE__ */ jsxs("div", { className: "grid h-full min-h-0 grid-rows-[minmax(0,1fr)_minmax(220px,0.45fr)] gap-4 xl:grid-cols-[minmax(0,1.75fr)_minmax(320px,0.85fr)] xl:grid-rows-1", children: [
2213
+ /* @__PURE__ */ jsxs("div", { className: "min-h-0 overflow-auto pr-1", children: [
2214
+ arduinoError || arduinoBuild.error ? /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-log-error-bg bg-log-error-bg px-3 py-2 text-xs text-log-error-label-text", children: arduinoError || arduinoBuild.error?.message }) : null,
2215
+ arduinoBuild.status.lastResult?.message ? /* @__PURE__ */ jsx("p", { className: "mt-3 rounded-lg border border-border-soft bg-surface px-3 py-2 text-xs text-text-subtle", children: arduinoBuild.status.lastResult.message }) : null,
2216
+ /* @__PURE__ */ jsxs("div", { className: "mt-4 grid gap-3", children: [
2217
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-3 lg:grid-cols-[1fr_1fr]", children: [
2218
+ /* @__PURE__ */ jsxs("div", { children: [
2219
+ /* @__PURE__ */ jsx("p", { className: "mb-2 text-xs uppercase tracking-[0.25em] text-text-subtle", children: "보드 프리셋" }),
2220
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: ARDUINO_BOARD_PRESETS.map((preset) => /* @__PURE__ */ jsx(
2221
+ "button",
2222
+ {
2223
+ className: `rounded-lg border px-3 py-2 text-xs transition ${arduinoDraft.boardPreset === preset ? "border-border-strong bg-surface-selected text-text" : "border-border-soft bg-surface-subtle text-text-muted hover:border-border hover:bg-surface-hover"}`,
2224
+ onClick: () => updateArduinoBoardPreset(preset),
2225
+ type: "button",
2226
+ children: preset
2227
+ },
2228
+ preset
2229
+ )) })
2230
+ ] }),
2231
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-2", children: [
2232
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs text-text-muted", children: [
2233
+ /* @__PURE__ */ jsx(
2234
+ "input",
2235
+ {
2236
+ checked: arduinoAdvancedFqbn,
2237
+ onChange: (event) => {
2238
+ const enabled = event.target.checked;
2239
+ setArduinoAdvancedFqbn(enabled);
2240
+ if (!enabled) {
2241
+ updateArduinoDraft({
2242
+ fqbn: resolveArduinoBoardFqbn(
2243
+ arduinoDraft.boardPreset
2244
+ )
2245
+ });
2246
+ }
2247
+ },
2248
+ type: "checkbox"
2249
+ }
2250
+ ),
2251
+ "고급 FQBN 직접 입력"
2252
+ ] }),
2253
+ /* @__PURE__ */ jsx(
2254
+ "input",
2255
+ {
2256
+ className: "rounded-lg border border-border-soft bg-app-bg px-3 py-2 text-xs text-text outline-none transition focus:border-border-strong disabled:opacity-70",
2257
+ disabled: !arduinoAdvancedFqbn,
2258
+ onChange: (event) => updateArduinoDraft({ fqbn: event.target.value }),
2259
+ value: arduinoDraft.fqbn
2260
+ }
2261
+ )
2262
+ ] })
2263
+ ] }),
2264
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-3 lg:grid-cols-2", children: [
2265
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs text-text-muted", children: [
2266
+ /* @__PURE__ */ jsx(
2267
+ "input",
2268
+ {
2269
+ checked: arduinoDraft.keyboardFallbackEnabled,
2270
+ onChange: (event) => updateArduinoDraft({
2271
+ keyboardFallbackEnabled: event.target.checked
2272
+ }),
2273
+ type: "checkbox"
2274
+ }
2275
+ ),
2276
+ "Serial 통신 실패시 키보드로 동작"
2277
+ ] }),
2278
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2279
+ "시리얼 체크 타임아웃(ms)",
2280
+ /* @__PURE__ */ jsx(
2281
+ "input",
2282
+ {
2283
+ className: "rounded-lg border border-border-soft bg-app-bg px-3 py-2 text-xs text-text outline-none transition focus:border-border-strong",
2284
+ min: 1,
2285
+ onChange: (event) => updateArduinoDraft({
2286
+ serialHealthyTimeoutMs: Number(event.target.value)
2287
+ }),
2288
+ type: "number",
2289
+ value: arduinoDraft.serialHealthyTimeoutMs
2290
+ }
2291
+ ),
2292
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] leading-5 text-text-dim", children: "해당 시간동안 Serial 통신 실패시 키보드 제어 방식으로 변경됩니다." })
2293
+ ] })
2294
+ ] }),
2295
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface px-3 py-3", children: [
2296
+ /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between", children: [
2297
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "입력 핀" }),
2298
+ /* @__PURE__ */ jsx(
2299
+ "button",
2300
+ {
2301
+ className: "rounded-lg border border-border px-3 py-1.5 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2302
+ onClick: addArduinoInput,
2303
+ type: "button",
2304
+ children: "입력 추가"
2305
+ }
2306
+ )
2307
+ ] }),
2308
+ /* @__PURE__ */ jsx("div", { className: "grid gap-2", children: arduinoDraft.inputs.length === 0 ? /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-dashed border-border-soft px-3 py-4 text-xs text-text-subtle", children: "입력 핀 매핑이 없습니다." }) : arduinoDraft.inputs.map((input) => {
2309
+ const preview = getShortcutPreview(
2310
+ input.target,
2311
+ shortcuts
2312
+ );
2313
+ return /* @__PURE__ */ jsxs(
2314
+ "div",
2315
+ {
2316
+ className: "grid gap-2 rounded-lg border border-border-soft bg-surface-subtle px-3 py-3",
2317
+ children: [
2318
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-2 lg:grid-cols-[0.7fr_1.4fr_0.9fr]", children: [
2319
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2320
+ "핀",
2321
+ /* @__PURE__ */ jsx(
2322
+ "input",
2323
+ {
2324
+ className: "rounded-lg border border-border-soft bg-app-bg px-2 py-2 text-xs text-text outline-none focus:border-border-strong",
2325
+ min: 0,
2326
+ onChange: (event) => updateArduinoInput(input.id, {
2327
+ pin: Number(event.target.value)
2328
+ }),
2329
+ type: "number",
2330
+ value: input.pin
2331
+ }
2332
+ )
2333
+ ] }),
2334
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2335
+ "대상",
2336
+ /* @__PURE__ */ jsx(
2337
+ "select",
2338
+ {
2339
+ className: "rounded-lg border border-border-soft bg-app-bg px-2 py-2 text-xs text-text outline-none focus:border-border-strong",
2340
+ onChange: (event) => updateArduinoInput(input.id, {
2341
+ target: event.target.value
2342
+ }),
2343
+ value: input.target,
2344
+ children: arduinoTargetOptions.map((target) => /* @__PURE__ */ jsx("option", { value: target, children: formatArduinoTargetOptionLabel(
2345
+ target,
2346
+ screens
2347
+ ) }, target))
2348
+ }
2349
+ )
2350
+ ] }),
2351
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2352
+ "디바운스(ms)",
2353
+ /* @__PURE__ */ jsx(
2354
+ "input",
2355
+ {
2356
+ className: "rounded-lg border border-border-soft bg-app-bg px-2 py-2 text-xs text-text outline-none focus:border-border-strong",
2357
+ min: 0,
2358
+ onChange: (event) => updateArduinoInput(input.id, {
2359
+ debounceMs: Number(event.target.value)
2360
+ }),
2361
+ type: "number",
2362
+ value: input.debounceMs
2363
+ }
2364
+ )
2365
+ ] })
2366
+ ] }),
2367
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-3 lg:grid-cols-[minmax(0,1fr)_auto]", children: [
2368
+ /* @__PURE__ */ jsxs("div", { className: "grid min-w-0 gap-1", children: [
2369
+ /* @__PURE__ */ jsx(
2370
+ "button",
2371
+ {
2372
+ "aria-pressed": input.activeLow,
2373
+ className: `w-fit rounded-full border px-3 py-1.5 text-xs transition ${input.activeLow ? "border-aqua_signal/50 bg-aqua_signal/10 text-text" : "border-border-soft bg-app-bg text-text-muted hover:border-border"}`,
2374
+ onClick: () => updateArduinoInput(input.id, {
2375
+ activeLow: !input.activeLow
2376
+ }),
2377
+ type: "button",
2378
+ children: input.activeLow ? "LOW 신호에서 동작" : "HIGH 신호에서 동작"
2379
+ }
2380
+ ),
2381
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-text-dim", children: input.activeLow ? "GND와 해당 핀이 쇼트되면 동작합니다." : "GND와 쇼트되어 있던 연결이 끊어져 핀이 HIGH로 올라가면 동작합니다." })
2382
+ ] }),
2383
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start justify-start gap-2 lg:justify-end", children: [
2384
+ /* @__PURE__ */ jsx(
2385
+ "span",
2386
+ {
2387
+ className: `rounded-md px-2 py-1 text-xs ${preview.warning ? "bg-log-error-bg text-log-error-label-text" : "bg-aqua_signal/10 text-text"}`,
2388
+ title: preview.warning,
2389
+ children: preview.label
2390
+ }
2391
+ ),
2392
+ /* @__PURE__ */ jsx(
2393
+ "button",
2394
+ {
2395
+ className: "rounded-lg border border-border px-3 py-1.5 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2396
+ onClick: () => updateArduinoDraft({
2397
+ inputs: arduinoDraft.inputs.filter(
2398
+ (current) => current.id !== input.id
2399
+ )
2400
+ }),
2401
+ type: "button",
2402
+ children: "삭제"
2403
+ }
2404
+ )
2405
+ ] })
2406
+ ] })
2407
+ ]
2408
+ },
2409
+ input.id
2410
+ );
2411
+ }) })
2412
+ ] }),
2413
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface px-3 py-3", children: [
2414
+ /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between", children: [
2415
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "출력 핀" }),
2416
+ /* @__PURE__ */ jsx(
2417
+ "button",
2418
+ {
2419
+ className: "rounded-lg border border-border px-3 py-1.5 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2420
+ onClick: addArduinoOutput,
2421
+ type: "button",
2422
+ children: "출력 추가"
2423
+ }
2424
+ )
2425
+ ] }),
2426
+ /* @__PURE__ */ jsx("div", { className: "grid gap-2", children: arduinoDraft.outputs.length === 0 ? /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-dashed border-border-soft px-3 py-4 text-xs text-text-subtle", children: "출력 핀 매핑이 없습니다." }) : arduinoDraft.outputs.map((output) => {
2427
+ const outputActionOptions = getArduinoOutputActionOptions(
2428
+ output,
2429
+ arduinoOutputSignals
2430
+ );
2431
+ return /* @__PURE__ */ jsxs(
2432
+ "div",
2433
+ {
2434
+ className: "grid gap-2 rounded-lg border border-border-soft bg-surface-subtle px-3 py-3",
2435
+ children: [
2436
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-2 lg:grid-cols-[1.3fr_1fr_0.7fr]", children: [
2437
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2438
+ "대상",
2439
+ /* @__PURE__ */ jsx(
2440
+ "select",
2441
+ {
2442
+ className: "rounded-lg border border-border-soft bg-app-bg px-2 py-2 text-xs text-text outline-none focus:border-border-strong",
2443
+ onChange: (event) => {
2444
+ const target = event.target.value;
2445
+ const nextAction = arduinoOutputSignals.find(
2446
+ (signal) => signal.target === target
2447
+ )?.action ?? output.action;
2448
+ updateArduinoOutput(output.id, {
2449
+ target,
2450
+ action: nextAction
2451
+ });
2452
+ },
2453
+ value: output.target,
2454
+ children: arduinoOutputTargetOptions.map((target) => /* @__PURE__ */ jsx("option", { value: target, children: target }, target))
2455
+ }
2456
+ )
2457
+ ] }),
2458
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2459
+ "동작",
2460
+ /* @__PURE__ */ jsx(
2461
+ "select",
2462
+ {
2463
+ className: "rounded-lg border border-border-soft bg-app-bg px-2 py-2 text-xs text-text outline-none focus:border-border-strong",
2464
+ onChange: (event) => updateArduinoOutput(output.id, {
2465
+ action: event.target.value
2466
+ }),
2467
+ value: output.action,
2468
+ children: outputActionOptions.map((action) => /* @__PURE__ */ jsx("option", { value: action, children: action }, action))
2469
+ }
2470
+ )
2471
+ ] }),
2472
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-1 text-xs text-text-subtle", children: [
2473
+ "핀",
2474
+ /* @__PURE__ */ jsx(
2475
+ "input",
2476
+ {
2477
+ className: "rounded-lg border border-border-soft bg-app-bg px-2 py-2 text-xs text-text outline-none focus:border-border-strong",
2478
+ min: 0,
2479
+ onChange: (event) => updateArduinoOutput(output.id, {
2480
+ pin: Number(event.target.value)
2481
+ }),
2482
+ type: "number",
2483
+ value: output.pin
2484
+ }
2485
+ )
2486
+ ] })
2487
+ ] }),
2488
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
2489
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs text-text-muted", children: [
2490
+ /* @__PURE__ */ jsx(
2491
+ "input",
2492
+ {
2493
+ checked: output.activeHigh,
2494
+ onChange: (event) => updateArduinoOutput(output.id, {
2495
+ activeHigh: event.target.checked
2496
+ }),
2497
+ type: "checkbox"
2498
+ }
2499
+ ),
2500
+ "HIGH 출력 사용"
2501
+ ] }),
2502
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs text-text-subtle", children: [
2503
+ "펄스(ms)",
2504
+ /* @__PURE__ */ jsx(
2505
+ "input",
2506
+ {
2507
+ className: "w-24 rounded-lg border border-border-soft bg-app-bg px-2 py-1.5 text-xs text-text outline-none focus:border-border-strong",
2508
+ min: 0,
2509
+ onChange: (event) => updateArduinoOutput(output.id, {
2510
+ pulseMs: Number(event.target.value)
2511
+ }),
2512
+ type: "number",
2513
+ value: output.pulseMs
2514
+ }
2515
+ )
2516
+ ] }),
2517
+ /* @__PURE__ */ jsx(
2518
+ "button",
2519
+ {
2520
+ className: "rounded-lg border border-border px-3 py-1.5 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2521
+ onClick: () => updateArduinoDraft({
2522
+ outputs: arduinoDraft.outputs.filter(
2523
+ (current) => current.id !== output.id
2524
+ )
2525
+ }),
2526
+ type: "button",
2527
+ children: "삭제"
2528
+ }
2529
+ )
2530
+ ] })
2531
+ ]
2532
+ },
2533
+ output.id
2534
+ );
2535
+ }) })
2536
+ ] })
2537
+ ] })
2538
+ ] }),
2539
+ /* @__PURE__ */ jsxs("aside", { className: "flex min-h-0 flex-col rounded-lg border border-border-soft bg-app-bg px-3 py-3", children: [
2540
+ /* @__PURE__ */ jsxs("div", { className: "mb-3 grid shrink-0 grid-cols-3 gap-2", children: [
2541
+ /* @__PURE__ */ jsx(
2542
+ "button",
2543
+ {
2544
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-60",
2545
+ disabled: loading,
2546
+ onClick: () => void previewArduinoSketch(),
2547
+ type: "button",
2548
+ children: "미리보기"
2549
+ }
2550
+ ),
2551
+ /* @__PURE__ */ jsx(
2552
+ "button",
2553
+ {
2554
+ className: "rounded-lg bg-button-primary-bg px-3 py-2 text-xs font-semibold text-button-primary-text transition hover:bg-button-primary-hover disabled:cursor-not-allowed disabled:opacity-60",
2555
+ disabled: loading || arduinoBuild.compiling || arduinoBuild.uploading,
2556
+ onClick: () => void compileArduinoSketch(),
2557
+ type: "button",
2558
+ children: "컴파일"
2559
+ }
2560
+ ),
2561
+ arduinoBuild.uploading ? /* @__PURE__ */ jsx(
2562
+ "button",
2563
+ {
2564
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2565
+ onClick: arduinoBuild.cancel,
2566
+ type: "button",
2567
+ children: "빌드 취소"
2568
+ }
2569
+ ) : /* @__PURE__ */ jsx(
2570
+ "button",
2571
+ {
2572
+ className: "rounded-lg bg-button-primary-bg px-3 py-2 text-xs font-semibold text-button-primary-text transition hover:bg-button-primary-hover disabled:cursor-not-allowed disabled:opacity-60",
2573
+ disabled: loading || arduinoBuild.compiling || !deviceState.selectedPortPath,
2574
+ onClick: () => void uploadArduinoSketch(),
2575
+ type: "button",
2576
+ children: "업로드"
2577
+ }
2578
+ )
2579
+ ] }),
2580
+ /* @__PURE__ */ jsxs("div", { className: "mb-3 flex shrink-0 items-center justify-between", children: [
2581
+ /* @__PURE__ */ jsxs("div", { children: [
2582
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "빌드 로그" }),
2583
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-dim", children: "컴파일/업로드 출력" })
2584
+ ] }),
2585
+ /* @__PURE__ */ jsx(
2586
+ "button",
2587
+ {
2588
+ className: "rounded-lg border border-border px-2 py-1 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2589
+ onClick: arduinoBuild.clearLogs,
2590
+ type: "button",
2591
+ children: "지우기"
2592
+ }
2593
+ )
2594
+ ] }),
2595
+ /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-auto pr-1", children: /* @__PURE__ */ jsx("div", { className: "grid gap-1", children: arduinoBuild.logs.length === 0 ? /* @__PURE__ */ jsx("p", { className: "rounded-lg border border-dashed border-border-soft px-3 py-4 text-xs text-text-subtle", children: "아직 Arduino 빌드 로그가 없습니다." }) : arduinoBuild.logs.map((entry) => /* @__PURE__ */ jsxs(
2596
+ "div",
2597
+ {
2598
+ className: `rounded-md border px-2 py-2 text-xs ${arduinoLogTone[entry.stream]}`,
2599
+ children: [
2600
+ /* @__PURE__ */ jsx("span", { className: "mr-2 font-mono uppercase", children: entry.stream }),
2601
+ /* @__PURE__ */ jsx("span", { className: "break-all font-mono", children: entry.line })
2602
+ ]
2603
+ },
2604
+ entry.id
2605
+ )) }) })
2606
+ ] })
2607
+ ] }) })
2608
+ ]
2609
+ }
2610
+ )
2611
+ }
2612
+ ),
2613
+ document.body
2614
+ ) : null
2615
+ ] })
2616
+ ] }) })
2617
+ ] }) }),
2618
+ benchmarkModalOpen ? /* @__PURE__ */ jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4 py-6", children: /* @__PURE__ */ jsxs("section", { className: "flex max-h-[82vh] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-border bg-surface-strong shadow-2xl", children: [
2619
+ /* @__PURE__ */ jsx("div", { className: "shrink-0 border-b border-border-soft px-5 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
2620
+ /* @__PURE__ */ jsxs("div", { children: [
2621
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "Performance" }),
2622
+ /* @__PURE__ */ jsx("h3", { className: "mt-1 font-display text-lg text-text", children: "성능 체크" }),
2623
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-muted", children: "설치 PC에서 메모리, 디바이스 응답, 프레임, 전체화면 렌더링 부하를 측정합니다." })
2624
+ ] }),
2625
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2626
+ /* @__PURE__ */ jsx(
2627
+ "button",
2628
+ {
2629
+ className: "rounded-lg bg-button-primary-bg px-3 py-2 text-xs font-semibold text-button-primary-text transition hover:bg-button-primary-hover disabled:cursor-not-allowed disabled:opacity-60",
2630
+ disabled: benchmarkRunning,
2631
+ onClick: () => void runPerformanceCheck(),
2632
+ type: "button",
2633
+ children: benchmarkRunning ? "측정 중" : "성능 체크 실행"
2634
+ }
2635
+ ),
2636
+ /* @__PURE__ */ jsx(
2637
+ "button",
2638
+ {
2639
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2640
+ onClick: () => setBenchmarkModalOpen(false),
2641
+ type: "button",
2642
+ children: "닫기"
2643
+ }
2644
+ )
2645
+ ] })
2646
+ ] }) }),
2647
+ /* @__PURE__ */ jsxs("div", { className: "min-h-0 flex-1 overflow-auto px-5 py-4", children: [
2648
+ benchmarkError ? /* @__PURE__ */ jsx("p", { className: "text-xs text-log-error-label-text", children: benchmarkError }) : null,
2649
+ /* @__PURE__ */ jsxs("div", { className: "mb-3 overflow-hidden rounded-lg border border-border-soft bg-surface px-3 py-3", children: [
2650
+ /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between gap-3", children: [
2651
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.2em] text-text-subtle", children: "전체화면 렌더링 테스트" }),
2652
+ /* @__PURE__ */ jsx("p", { className: "font-mono text-xs text-text-subtle", children: benchmarkCanvasActive ? "running" : "ready" })
2653
+ ] }),
2654
+ /* @__PURE__ */ jsxs("div", { className: "mb-3 grid gap-3 rounded border border-border-soft bg-surface-subtle px-3 py-3 md:grid-cols-[1fr_180px] md:items-end", children: [
2655
+ /* @__PURE__ */ jsxs("label", { className: "grid gap-2 text-xs font-semibold text-text-muted", children: [
2656
+ "공 개수",
2657
+ /* @__PURE__ */ jsx(
2658
+ "input",
2659
+ {
2660
+ "aria-label": "공 개수",
2661
+ className: "w-full rounded border border-border-soft bg-field-bg px-3 py-2 font-mono text-sm text-text outline-none transition focus:border-border-strong disabled:cursor-not-allowed disabled:opacity-60",
2662
+ disabled: benchmarkRunning || benchmarkCanvasActive,
2663
+ max: BENCHMARK_MAX_PARTICLE_COUNT,
2664
+ min: BENCHMARK_MIN_PARTICLE_COUNT,
2665
+ onChange: (event) => setBenchmarkParticleCount(
2666
+ clampBenchmarkParticleCount(Number(event.target.value))
2667
+ ),
2668
+ step: 100,
2669
+ type: "number",
2670
+ value: benchmarkParticleCount
2671
+ }
2672
+ )
2673
+ ] }),
2674
+ /* @__PURE__ */ jsxs("p", { className: "text-right font-mono text-sm font-semibold text-text md:pb-2", children: [
2675
+ benchmarkParticleCount.toLocaleString(),
2676
+ "개"
2677
+ ] }),
2678
+ /* @__PURE__ */ jsx(
2679
+ "input",
2680
+ {
2681
+ "aria-label": "공 개수 슬라이더",
2682
+ className: "md:col-span-2 h-2 w-full accent-text",
2683
+ disabled: benchmarkRunning || benchmarkCanvasActive,
2684
+ max: BENCHMARK_MAX_PARTICLE_COUNT,
2685
+ min: BENCHMARK_MIN_PARTICLE_COUNT,
2686
+ onChange: (event) => setBenchmarkParticleCount(
2687
+ clampBenchmarkParticleCount(Number(event.target.value))
2688
+ ),
2689
+ step: 100,
2690
+ type: "range",
2691
+ value: benchmarkParticleCount
2692
+ }
2693
+ ),
2694
+ /* @__PURE__ */ jsxs("p", { className: "md:col-span-2 text-xs text-text-subtle", children: [
2695
+ BENCHMARK_MIN_PARTICLE_COUNT.toLocaleString(),
2696
+ "개부터",
2697
+ " ",
2698
+ BENCHMARK_MAX_PARTICLE_COUNT.toLocaleString(),
2699
+ "개까지 조정할 수 있습니다."
2700
+ ] })
2701
+ ] }),
2702
+ /* @__PURE__ */ jsxs("div", { className: "flex min-h-24 items-center justify-center rounded border border-dashed border-border-soft px-3 text-center text-xs leading-5 text-text-subtle", children: [
2703
+ "성능 체크 실행 시 전체 화면 WebGL canvas에서",
2704
+ " ",
2705
+ benchmarkParticleCount.toLocaleString(),
2706
+ "개의 공을 약",
2707
+ " ",
2708
+ Math.round(BENCHMARK_CANVAS_DURATION_MS / 1e3),
2709
+ "초 동안 렌더링해 FPS, 1% low, 프레임 시간을 측정합니다. 마우스를 움직이면 공과 충돌합니다."
2710
+ ] })
2711
+ ] }),
2712
+ /* @__PURE__ */ jsx("div", { className: "grid gap-2", children: benchmarkResults.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border-soft px-3 py-4 text-xs text-text-subtle", children: "아직 측정 결과가 없습니다." }) : benchmarkResults.map((result) => /* @__PURE__ */ jsxs(
2713
+ "div",
2714
+ {
2715
+ className: `rounded-lg border px-3 py-3 ${benchmarkTone[result.tone]}`,
2716
+ children: [
2717
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
2718
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: result.label }),
2719
+ /* @__PURE__ */ jsx("p", { className: "font-mono text-sm font-semibold", children: result.value })
2720
+ ] }),
2721
+ result.detail ? /* @__PURE__ */ jsx("p", { className: "mt-1 break-all text-xs text-text-subtle", children: result.detail }) : null
2722
+ ]
2723
+ },
2724
+ result.id
2725
+ )) }),
2726
+ benchmarkSnapshot ? /* @__PURE__ */ jsxs("div", { className: "mt-3 grid gap-2 sm:grid-cols-2", children: [
2727
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface px-3 py-3", children: [
2728
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.2em] text-text-subtle", children: "프로세스 수" }),
2729
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-sm font-semibold text-text", children: [
2730
+ benchmarkSnapshot.appMetrics.length,
2731
+ "개"
2732
+ ] })
2733
+ ] }),
2734
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border border-border-soft bg-surface px-3 py-3", children: [
2735
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.2em] text-text-subtle", children: "측정 시각" }),
2736
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm font-semibold text-text", children: formatLocalDateTime(benchmarkSnapshot.capturedAt) })
2737
+ ] })
2738
+ ] }) : null
2739
+ ] })
2740
+ ] }) }) : null,
2741
+ benchmarkCanvasActive ? createPortal(
2742
+ /* @__PURE__ */ jsx(
2743
+ "div",
2744
+ {
2745
+ "aria-label": "WebGL 렌더링 벤치마크",
2746
+ className: "pointer-events-none fixed inset-0 z-[55] overflow-hidden bg-black/10",
2747
+ children: /* @__PURE__ */ jsx("canvas", { className: "h-full w-full", ref: benchmarkCanvasRef })
2748
+ }
2749
+ ),
2750
+ document.body
2751
+ ) : null,
2752
+ mediaModalOpen ? createPortal(
2753
+ /* @__PURE__ */ jsx(
2754
+ "div",
2755
+ {
2756
+ className: "fixed inset-0 z-[60] flex items-center justify-center bg-black/55 px-4 py-6",
2757
+ onClick: () => setMediaModalOpen(false),
2758
+ children: /* @__PURE__ */ jsxs(
2759
+ "section",
2760
+ {
2761
+ className: "flex h-[82vh] w-full max-w-6xl flex-col overflow-hidden rounded-2xl border border-border bg-surface-strong shadow-2xl",
2762
+ onClick: (event) => event.stopPropagation(),
2763
+ children: [
2764
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4 border-b border-border-soft px-5 py-4", children: [
2765
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
2766
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "Media Library" }),
2767
+ /* @__PURE__ */ jsx("h3", { className: "mt-2 font-display text-xl text-text", children: "외부 리소스" }),
2768
+ /* @__PURE__ */ jsx("p", { className: "mt-1 break-all text-sm text-text-muted", children: mediaLibrary?.rootPath ?? "리소스 폴더 확인 중" })
2769
+ ] }),
2770
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
2771
+ /* @__PURE__ */ jsx(
2772
+ "button",
2773
+ {
2774
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-60",
2775
+ disabled: mediaLoading,
2776
+ onClick: () => void refreshMediaLibrary(),
2777
+ type: "button",
2778
+ children: "새로고침"
2779
+ }
2780
+ ),
2781
+ /* @__PURE__ */ jsx(
2782
+ "button",
2783
+ {
2784
+ className: "rounded-lg bg-button-primary-bg px-3 py-2 text-xs font-semibold text-button-primary-text transition hover:bg-button-primary-hover",
2785
+ onClick: () => void openMediaFolder(),
2786
+ type: "button",
2787
+ children: "폴더 열기"
2788
+ }
2789
+ ),
2790
+ /* @__PURE__ */ jsx(
2791
+ "button",
2792
+ {
2793
+ className: "rounded-lg border border-border px-3 py-2 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2794
+ onClick: () => setMediaModalOpen(false),
2795
+ type: "button",
2796
+ children: "닫기"
2797
+ }
2798
+ )
2799
+ ] })
2800
+ ] }),
2801
+ /* @__PURE__ */ jsxs("div", { className: "min-h-0 flex-1 overflow-auto px-5 py-4", children: [
2802
+ mediaError ? /* @__PURE__ */ jsx("p", { className: "mb-3 rounded-lg border border-log-error-bg bg-log-error-bg px-3 py-2 text-xs text-log-error-label-text", children: mediaError }) : null,
2803
+ /* @__PURE__ */ jsx("p", { className: "mb-3 rounded-lg border border-border-soft bg-surface px-3 py-2 text-xs leading-5 text-text-muted", children: "리소스 파일을 추가하거나 교체한 뒤에는 프로그램을 재시작하세요." }),
2804
+ /* @__PURE__ */ jsx("div", { className: "mb-4 grid gap-3 sm:grid-cols-4", children: ["image", "video", "audio", "font"].map((type) => /* @__PURE__ */ jsxs(
2805
+ "div",
2806
+ {
2807
+ className: "rounded-lg border border-border-soft bg-surface px-3 py-3",
2808
+ children: [
2809
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.2em] text-text-subtle", children: getMediaTypeLabel(type) }),
2810
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-xl font-semibold text-text", children: mediaLibrary?.assets.filter((asset) => asset.type === type).length ?? 0 })
2811
+ ]
2812
+ },
2813
+ type
2814
+ )) }),
2815
+ mediaLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-52 items-center justify-center rounded-lg border border-dashed border-border-soft text-sm text-text-subtle", children: "불러오는 중..." }) : !mediaLibrary || mediaLibrary.assets.length === 0 ? /* @__PURE__ */ jsx("div", { className: "rounded-lg border border-dashed border-border-soft px-4 py-8 text-sm text-text-subtle", children: "외부 리소스 파일이 없습니다. 폴더를 열고 `image`, `video`, `audio`, `font` 하위 폴더에 파일을 추가하세요." }) : /* @__PURE__ */ jsxs("div", { className: "overflow-hidden rounded-lg border border-border-soft", children: [
2816
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[120px_minmax(0,1fr)_120px_190px] gap-3 border-b border-border-soft bg-surface px-4 py-3 text-xs uppercase tracking-[0.2em] text-text-subtle", children: [
2817
+ /* @__PURE__ */ jsx("span", { children: "종류" }),
2818
+ /* @__PURE__ */ jsx("span", { children: "파일" }),
2819
+ /* @__PURE__ */ jsx("span", { children: "크기" }),
2820
+ /* @__PURE__ */ jsx("span", { children: "수정일" })
2821
+ ] }),
2822
+ /* @__PURE__ */ jsx("div", { className: "divide-y divide-border-soft", children: mediaLibrary.assets.map((asset) => /* @__PURE__ */ jsxs(
2823
+ "div",
2824
+ {
2825
+ className: "grid grid-cols-[120px_minmax(0,1fr)_120px_190px] gap-3 bg-surface-subtle px-4 py-3 text-sm text-text",
2826
+ children: [
2827
+ /* @__PURE__ */ jsx("span", { className: "text-text-muted", children: getMediaTypeLabel(asset.type) }),
2828
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0", children: [
2829
+ /* @__PURE__ */ jsx("span", { className: "block truncate font-semibold", children: asset.name }),
2830
+ /* @__PURE__ */ jsx("span", { className: "mt-1 block truncate font-mono text-xs text-text-subtle", children: asset.url })
2831
+ ] }),
2832
+ /* @__PURE__ */ jsx("span", { className: "font-mono text-xs text-text-muted", children: formatBytes(asset.sizeBytes) }),
2833
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-text-muted", children: formatLocalDateTime(asset.updatedAt) })
2834
+ ]
2835
+ },
2836
+ asset.relativePath
2837
+ )) })
2838
+ ] })
2839
+ ] })
2840
+ ]
2841
+ }
2842
+ )
2843
+ }
2844
+ ),
2845
+ document.body
2846
+ ) : null,
2847
+ archiveModalOpen ? /* @__PURE__ */ jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4 py-6", children: /* @__PURE__ */ jsxs("div", { className: "flex h-[80vh] w-full max-w-6xl overflow-hidden rounded-2xl border border-border bg-[rgba(12,16,22,0.9)] shadow-2xl backdrop-blur-xl", children: [
2848
+ /* @__PURE__ */ jsxs("aside", { className: "flex w-64 flex-col border-r border-border-soft bg-[rgba(18,22,28,0.86)] px-4 py-4", children: [
2849
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2850
+ /* @__PURE__ */ jsx("h3", { className: "font-display text-lg text-text", children: "이전 로그" }),
2851
+ /* @__PURE__ */ jsx(
2852
+ "button",
2853
+ {
2854
+ className: "rounded-lg border border-border px-2 py-1 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2855
+ onClick: () => setArchiveModalOpen(false),
2856
+ type: "button",
2857
+ children: "닫기"
2858
+ }
2859
+ )
2860
+ ] }),
2861
+ /* @__PURE__ */ jsx("div", { className: "mt-4 flex-1 overflow-auto pr-1", children: archiveList.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-text-subtle", children: "저장된 로그 파일이 없습니다." }) : /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2", children: archiveList.map((archive) => /* @__PURE__ */ jsxs(
2862
+ "button",
2863
+ {
2864
+ className: `rounded-lg border px-3 py-3 text-left transition ${selectedArchive === archive.dateKey ? "border-border-strong bg-surface-selected" : "border-border-soft bg-surface-subtle hover:border-border hover:bg-surface-hover"}`,
2865
+ onClick: () => void selectArchive(archive.dateKey),
2866
+ type: "button",
2867
+ children: [
2868
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-text", children: archive.dateKey }),
2869
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-text-subtle", children: [
2870
+ archive.entryCount,
2871
+ "건"
2872
+ ] })
2873
+ ]
2874
+ },
2875
+ archive.dateKey
2876
+ )) }) })
2877
+ ] }),
2878
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col px-5 py-4", children: [
2879
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2880
+ /* @__PURE__ */ jsxs("div", { children: [
2881
+ /* @__PURE__ */ jsx("h4", { className: "text-base font-semibold text-text", children: selectedArchive || "기록 없음" }),
2882
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-text-subtle", children: "파일시스템에 저장된 이전 메시지 로그입니다." })
2883
+ ] }),
2884
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2885
+ /* @__PURE__ */ jsx(
2886
+ "button",
2887
+ {
2888
+ className: `rounded-lg border px-3 py-1.5 text-xs transition ${archiveViewMode === "processed" ? "border-border-strong bg-surface-selected text-text" : "border-border text-text-subtle hover:border-border-strong hover:bg-surface-hover"}`,
2889
+ onClick: () => setArchiveViewMode("processed"),
2890
+ type: "button",
2891
+ children: "가공 보기"
2892
+ }
2893
+ ),
2894
+ /* @__PURE__ */ jsx(
2895
+ "button",
2896
+ {
2897
+ className: `rounded-lg border px-3 py-1.5 text-xs transition ${archiveViewMode === "raw" ? "border-border-strong bg-surface-selected text-text" : "border-border text-text-subtle hover:border-border-strong hover:bg-surface-hover"}`,
2898
+ onClick: () => setArchiveViewMode("raw"),
2899
+ type: "button",
2900
+ children: "Raw 보기"
2901
+ }
2902
+ )
2903
+ ] })
2904
+ ] }),
2905
+ /* @__PURE__ */ jsx("div", { className: "mt-4 min-h-0 flex-1 overflow-auto pr-2", children: archiveLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-text-subtle", children: "불러오는 중..." }) : visibleArchiveEntries.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-text-subtle", children: "표시할 로그가 없습니다." }) : /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 gap-4", children: [
2906
+ /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-auto pr-1", children: /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-4", children: archiveHourSections.map((section) => /* @__PURE__ */ jsxs(
2907
+ "section",
2908
+ {
2909
+ id: toHourSectionId(section.bucket),
2910
+ className: "scroll-mt-4",
2911
+ children: [
2912
+ /* @__PURE__ */ jsx("div", { className: "sticky top-0 z-10 mb-2 rounded-lg border border-border-soft bg-[rgba(18,22,28,0.92)] px-3 py-2 text-xs uppercase tracking-[0.25em] text-text-subtle backdrop-blur", children: section.bucket }),
2913
+ /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2", children: section.entries.map((entry) => {
2914
+ const origin = entry.origin ?? (entry.direction === "out" ? "out" : entry.direction === "system" ? "system" : "in");
2915
+ return /* @__PURE__ */ jsxs(
2916
+ "div",
2917
+ {
2918
+ className: `w-full max-w-[84%] rounded-lg px-3 py-3 ${logTone[entry.direction]} ${logLayoutTone[origin]}`,
2919
+ children: [
2920
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
2921
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2922
+ /* @__PURE__ */ jsx(
2923
+ "span",
2924
+ {
2925
+ className: `rounded-md px-2 py-1 text-xs uppercase tracking-[0.25em] ${logLabelTone[entry.direction]}`,
2926
+ children: logLabelByOrigin[origin]
2927
+ }
2928
+ ),
2929
+ entry.direction === "error" ? /* @__PURE__ */ jsx("span", { className: errorTextTone, children: "ERROR" }) : null
2930
+ ] }),
2931
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-text-subtle", children: formatLocalDateTime(entry.createdAt) })
2932
+ ] }),
2933
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-sm text-text", children: translateLog(entry.raw) }),
2934
+ /* @__PURE__ */ jsx("p", { className: "mt-1 break-all text-xs text-text-subtle", children: entry.raw })
2935
+ ]
2936
+ },
2937
+ entry.id
2938
+ );
2939
+ }) })
2940
+ ]
2941
+ },
2942
+ section.bucket
2943
+ )) }) }),
2944
+ /* @__PURE__ */ jsxs("aside", { className: "hidden w-36 shrink-0 border-l border-border-soft pl-4 lg:block", children: [
2945
+ /* @__PURE__ */ jsx("p", { className: "mb-2 text-xs uppercase tracking-[0.25em] text-text-subtle", children: "시간 이동" }),
2946
+ /* @__PURE__ */ jsx("div", { className: "flex max-h-full flex-col gap-2 overflow-auto pr-1", children: archiveHourSections.map((section) => /* @__PURE__ */ jsx(
2947
+ "button",
2948
+ {
2949
+ className: "rounded-lg border border-border-soft bg-surface-subtle px-3 py-2 text-left text-xs text-text-muted transition hover:border-border hover:bg-surface-hover",
2950
+ onClick: () => document.getElementById(toHourSectionId(section.bucket))?.scrollIntoView({
2951
+ block: "start",
2952
+ behavior: "smooth"
2953
+ }),
2954
+ type: "button",
2955
+ children: section.bucket.slice(11)
2956
+ },
2957
+ section.bucket
2958
+ )) })
2959
+ ] })
2960
+ ] }) })
2961
+ ] })
2962
+ ] }) }) : null,
2963
+ arduinoPreviewOpen && arduinoPreview ? createPortal(
2964
+ /* @__PURE__ */ jsx("div", { className: "fixed inset-0 z-[80] flex items-center justify-center bg-black/55 px-4 py-6", children: /* @__PURE__ */ jsxs("div", { className: "flex h-[82vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-border bg-surface-strong shadow-2xl", children: [
2965
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4 border-b border-border-soft px-5 py-4", children: [
2966
+ /* @__PURE__ */ jsxs("div", { children: [
2967
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "Arduino Sketch" }),
2968
+ /* @__PURE__ */ jsx("h3", { className: "mt-2 font-display text-xl text-text", children: "스케치 미리보기" }),
2969
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-text-muted", children: "현재 관리자 설정과 전역 단축키에서 생성된 `.ino` 내용입니다." })
2970
+ ] }),
2971
+ /* @__PURE__ */ jsx(
2972
+ "button",
2973
+ {
2974
+ className: "rounded-lg border border-border px-3 py-1.5 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
2975
+ onClick: () => setArduinoPreviewOpen(false),
2976
+ type: "button",
2977
+ children: "닫기"
2978
+ }
2979
+ )
2980
+ ] }),
2981
+ arduinoPreview.warnings.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "border-b border-border-soft bg-log-error-bg px-5 py-3", children: [
2982
+ /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-log-error-label-text", children: "warnings" }),
2983
+ /* @__PURE__ */ jsx("ul", { className: "mt-2 grid gap-1 text-xs text-text", children: arduinoPreview.warnings.map((warning) => /* @__PURE__ */ jsx("li", { children: warning }, warning)) })
2984
+ ] }) : null,
2985
+ /* @__PURE__ */ jsx("pre", { className: "min-h-0 flex-1 overflow-auto bg-app-bg px-5 py-4 font-mono text-xs leading-5 text-text-muted", children: arduinoPreview.source })
2986
+ ] }) }),
2987
+ document.body
2988
+ ) : null,
2989
+ shortcutGuideOpen ? /* @__PURE__ */ jsx(
2990
+ "div",
2991
+ {
2992
+ className: "fixed inset-0 z-50 flex items-start justify-end bg-black/45 px-4 py-4",
2993
+ onClick: () => setShortcutGuideOpen(false),
2994
+ children: /* @__PURE__ */ jsxs(
2995
+ "div",
2996
+ {
2997
+ className: "w-full max-w-md rounded-2xl border border-border bg-surface-strong p-5 shadow-2xl",
2998
+ onClick: (event) => event.stopPropagation(),
2999
+ children: [
3000
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
3001
+ /* @__PURE__ */ jsxs("div", { children: [
3002
+ /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-[0.25em] text-text-subtle", children: "Shortcut Cheat Sheet" }),
3003
+ /* @__PURE__ */ jsx("h3", { className: "mt-2 font-display text-xl text-text", children: "단축키 가이드" }),
3004
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-text-muted", children: "어느 화면에서든 사용할 수 있는 전역 단축키입니다." })
3005
+ ] }),
3006
+ /* @__PURE__ */ jsx(
3007
+ "button",
3008
+ {
3009
+ className: "rounded-lg border border-border px-3 py-1.5 text-xs text-text transition hover:border-border-strong hover:bg-surface-hover",
3010
+ onClick: () => setShortcutGuideOpen(false),
3011
+ type: "button",
3012
+ children: "닫기"
3013
+ }
3014
+ )
3015
+ ] }),
3016
+ /* @__PURE__ */ jsxs("div", { className: "mt-5 grid gap-3", children: [
3017
+ /* @__PURE__ */ jsxs("div", { className: "rounded-xl border border-border-soft bg-surface px-4 py-4", children: [
3018
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-text", children: "관리자 화면 진입" }),
3019
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-subtle", children: "다른 화면에서 관리자 대시보드로 돌아옵니다." }),
3020
+ /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx(ShortcutKeyChips, { accelerator: adminShortcut }) })
3021
+ ] }),
3022
+ /* @__PURE__ */ jsxs("div", { className: "rounded-xl border border-border-soft bg-surface px-4 py-4", children: [
3023
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-text", children: "디바이스 로그 오버레이" }),
3024
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-subtle", children: "현재 화면을 유지한 채 최근 디바이스 메시지 로그를 확인합니다." }),
3025
+ /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx(ShortcutKeyChips, { accelerator: DEBUG_DEVICE_LOG_SHORTCUT }) })
3026
+ ] }),
3027
+ /* @__PURE__ */ jsxs("div", { className: "rounded-xl border border-border-soft bg-surface px-4 py-4", children: [
3028
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold text-text", children: "키오스크 강제 종료" }),
3029
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-text-subtle", children: "키오스크 모드에서 앱을 종료합니다." }),
3030
+ /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx(ShortcutKeyChips, { accelerator: KIOSK_QUIT_SHORTCUT }) })
3031
+ ] })
3032
+ ] })
3033
+ ]
3034
+ }
3035
+ )
3036
+ }
3037
+ ) : null
3038
+ ] });
3039
+ }
3040
+ function KeyScreenApp({
3041
+ appIconUrl,
3042
+ arduinoOutputSignals,
3043
+ deviceSignalHandlers,
3044
+ getProjectStore,
3045
+ projectConfig,
3046
+ screenDefinitions,
3047
+ screenModules
3048
+ }) {
3049
+ const runtime = useMemo(
3050
+ () => ({
3051
+ appIconUrl,
3052
+ arduinoOutputSignals,
3053
+ deviceSignalHandlers,
3054
+ getProjectStore,
3055
+ projectConfig,
3056
+ screenDefinitions,
3057
+ screenModules: {
3058
+ "admin-screen": { default: AdminScreen },
3059
+ ...screenModules
3060
+ }
3061
+ }),
3062
+ [
3063
+ appIconUrl,
3064
+ arduinoOutputSignals,
3065
+ deviceSignalHandlers,
3066
+ getProjectStore,
3067
+ projectConfig,
3068
+ screenDefinitions,
3069
+ screenModules
3070
+ ]
3071
+ );
3072
+ return /* @__PURE__ */ jsx(ProjectRuntimeProvider, { options: runtime, children: /* @__PURE__ */ jsx(App, {}) });
3073
+ }
3074
+ function mountKeyScreenApp(options, element = document.getElementById("root")) {
3075
+ if (!element) {
3076
+ throw new Error("Unable to mount KeyScreenApp: target element was not found.");
3077
+ }
3078
+ const root = createRoot(element);
3079
+ root.render(
3080
+ /* @__PURE__ */ jsx(StrictMode, { children: /* @__PURE__ */ jsx(KeyScreenApp, { ...options }) })
3081
+ );
3082
+ return root;
3083
+ }
3084
+ export {
3085
+ KeyScreenApp,
3086
+ ProjectRuntimeContext,
3087
+ c as createUseAtodSignal,
3088
+ getGameApi,
3089
+ mountKeyScreenApp,
3090
+ a as useAtodSignal,
3091
+ useProjectRuntime
3092
+ };