thuthi-plugin 0.0.0-stage → 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 (115) hide show
  1. package/.claude-plugin/marketplace.json +55 -0
  2. package/README.md +13 -2
  3. package/bin/parallel-browser.js +109 -0
  4. package/extension/background.js +1329 -0
  5. package/extension/config.json +1 -0
  6. package/extension/guard.js +44 -0
  7. package/extension/manifest.json +10 -0
  8. package/extension/overlay.js +104 -0
  9. package/extension/popup.html +34 -0
  10. package/extension/popup.js +39 -0
  11. package/extension-reloader/manifest.json +13 -0
  12. package/extension-reloader/sw.js +17 -0
  13. package/package.json +13 -4
  14. package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
  15. package/plugins/thuthi/context.md +3 -0
  16. package/plugins/thuthi/hooks/hooks.json +15 -0
  17. package/plugins/thuthi/skills/setup/SKILL.md +55 -0
  18. package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
  19. package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
  20. package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
  21. package/plugins/thuthi/tools/legacy_launcher.py +65 -0
  22. package/plugins/thuthi/tools/statusline/statusline.py +8 -0
  23. package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
  24. package/plugins/thuthi-accounts/bin/claude-switch +5 -0
  25. package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
  26. package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
  27. package/plugins/thuthi-accounts/lib/tls.py +68 -0
  28. package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
  29. package/plugins/thuthi-accounts/setup_check.py +21 -0
  30. package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
  31. package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
  32. package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
  33. package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
  34. package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
  35. package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
  36. package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
  37. package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
  38. package/plugins/thuthi-agenda-picker/context.md +3 -0
  39. package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
  40. package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
  41. package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
  42. package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
  43. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
  44. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
  45. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
  46. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
  47. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
  48. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
  49. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
  50. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
  51. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
  52. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
  53. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
  54. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
  55. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
  56. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
  57. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
  58. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
  59. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
  60. package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
  61. package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
  62. package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
  63. package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
  64. package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
  65. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
  66. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
  67. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
  68. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
  69. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
  70. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
  71. package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
  72. package/plugins/thuthi-browser/context.md +3 -0
  73. package/plugins/thuthi-browser/hooks/hooks.json +15 -0
  74. package/plugins/thuthi-browser/lib/pbpage.py +397 -0
  75. package/plugins/thuthi-browser/setup_check.py +93 -0
  76. package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
  77. package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
  78. package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
  79. package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
  80. package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
  81. package/plugins/thuthi-demo-video/setup_check.py +14 -0
  82. package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
  83. package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
  84. package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
  85. package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
  86. package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
  87. package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
  88. package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
  89. package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
  90. package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
  91. package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
  92. package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
  93. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
  94. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
  95. package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
  96. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
  97. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
  98. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
  99. package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
  100. package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
  101. package/plugins/thuthi-orca/context.md +5 -0
  102. package/plugins/thuthi-orca/hooks/hooks.json +18 -0
  103. package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
  104. package/plugins/thuthi-orca/setup_check.py +12 -0
  105. package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
  106. package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
  107. package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
  108. package/runtime/client.js +69 -0
  109. package/runtime/daemon.js +503 -0
  110. package/runtime/focus-monitor.js +53 -0
  111. package/runtime/keys.js +86 -0
  112. package/runtime/owner.js +64 -0
  113. package/runtime/recorder.js +267 -0
  114. package/runtime/relay.js +95 -0
  115. package/runtime/session.js +1599 -0
@@ -0,0 +1,1029 @@
1
+ <!doctype html>
2
+ <html lang="ko">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>@@TITLE@@</title>
7
+ <script>
8
+ // 그리기 전에 테마를 정해 깜빡이지 않게 한다. 고른 테마는 이 브라우저에 남고, 고른 적이 없으면 시스템 설정을 따른다.
9
+ (function () {
10
+ var t = null;
11
+ try { t = localStorage.getItem('agenda-picker:theme'); } catch (e) { /* 막힌 저장소 */ }
12
+ if (t !== 'light' && t !== 'dark') t = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
13
+ document.documentElement.dataset.theme = t;
14
+ })();
15
+ </script>
16
+ <style>
17
+ :root {
18
+ --bg: #f6f6f4; --panel: #fff; --line: #e3e3df; --ink: #1d1d1b; --ink2: #444; --ink3: #6f6f6a;
19
+ --accent: #F45084; --accent-soft: #fdebf1; --now: #888; --code-bg: #f0efeb; --warn: #b4530a;
20
+ --font: "Pretendard", "Pretendard Variable", -apple-system, "Apple SD Gothic Neo", "Noto Sans KR", "Malgun Gothic", sans-serif;
21
+ --mono: ui-monospace, "SF Mono", Menlo, monospace;
22
+ color-scheme: light;
23
+ }
24
+ :root[data-theme="dark"] {
25
+ --bg: #151514; --panel: #1f1f1d; --line: #353531; --ink: #ecece9; --ink2: #c9c9c4; --ink3: #95958f;
26
+ --accent-soft: #3b1f2a; --now: #77776f; --code-bg: #2c2c29; --warn: #f0a35c;
27
+ color-scheme: dark;
28
+ }
29
+ * { box-sizing: border-box; }
30
+ body { font-family: var(--font); margin: 0; background: var(--bg); color: var(--ink); line-height: 1.6; }
31
+ html:has(dialog[open]) { overflow: hidden; }
32
+ main { max-width: 1120px; margin: 0 auto; padding: 32px 28px 72px; }
33
+ h1 { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; margin: 0 0 8px; line-height: 1.4; }
34
+ code { font-family: var(--mono); font-size: 0.88em; background: var(--code-bg); padding: 1px 5px; border-radius: 4px; white-space: nowrap; }
35
+ .muted { color: var(--ink3); }
36
+ .warn { color: var(--warn); font-weight: 600; }
37
+ button { font: inherit; color: inherit; cursor: pointer; }
38
+ .btn { border: 1px solid var(--line); background: var(--panel); border-radius: 8px; padding: 7px 14px; font-size: 14px; }
39
+ .btn:hover:not(:disabled) { border-color: var(--ink3); }
40
+ .btn:disabled { opacity: .45; cursor: default; }
41
+ .btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 700; padding: 10px 22px; font-size: 15px; }
42
+ .btn.primary:hover:not(:disabled) { filter: brightness(1.06); border-color: var(--accent); }
43
+
44
+ .rich { font-size: 14px; color: var(--ink2); }
45
+ .rich p { margin: 6px 0 10px; }
46
+ .rich ul, .rich ol { margin: 4px 0 12px; padding-left: 20px; }
47
+ .rich li { margin: 2px 0; }
48
+ .rich > :first-child { margin-top: 0; }
49
+ .rich > :last-child { margin-bottom: 0; }
50
+
51
+ .tag { display: inline-flex; align-items: center; font-size: 12px; font-weight: 700; line-height: 1; padding: 4px 8px;
52
+ border-radius: 999px; background: #555; color: #fff; white-space: nowrap; }
53
+ .tag.picked { background: var(--accent); }
54
+ .tag.now { background: var(--now); }
55
+ .tag.rec { background: transparent; color: var(--accent); box-shadow: inset 0 0 0 1.5px var(--accent); }
56
+ .tag.agreed { background: transparent; color: var(--ink2); box-shadow: inset 0 0 0 1.5px var(--ink3); }
57
+ .tag.undecided { background: transparent; color: var(--ink3); box-shadow: inset 0 0 0 1.5px var(--line); }
58
+
59
+ /* 라이트 · 다크 전환 (바닥 · 팝업 · 비교 보기에 하나씩) */
60
+ .seg { display: inline-flex; flex: none; border: 1px solid var(--line); border-radius: 999px; padding: 2px; background: var(--bg); }
61
+ .seg button { border: 0; background: none; border-radius: 999px; padding: 3px 11px; font-size: 12.5px; font-weight: 600; color: var(--ink3); line-height: 1.5; }
62
+ .seg button:hover { color: var(--ink); }
63
+ .seg button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
64
+
65
+ /* ---- 바닥 페이지 */
66
+ .lead { margin: 0 0 18px; }
67
+ .bar { display: flex; align-items: center; gap: 14px; margin: 0 0 16px; font-size: 13px; color: var(--ink3); }
68
+ .meter { flex: 0 0 160px; height: 6px; border-radius: 3px; background: var(--line); overflow: hidden; }
69
+ .meter > i { display: block; height: 100%; background: var(--accent); transition: width .2s; }
70
+ .save { margin-left: auto; font-size: 12px; padding: 3px 10px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel); }
71
+ .save.error { color: var(--warn); border-color: currentColor; }
72
+ .banner { display: flex; align-items: center; gap: 12px; margin: 0 0 16px; padding: 10px 14px; border-radius: 10px;
73
+ background: var(--accent-soft); border: 1px solid var(--accent); font-size: 14px; }
74
+ .banner[hidden] { display: none; }
75
+
76
+ .list { list-style: none; margin: 0; padding: 0; display: grid; gap: 14px; }
77
+ /* 카드: 제목 (누르면 안건 보기) · 요약 · 안마다 한 줄 (누르면 그 자리에서 고른다, 줄 끝은 그 안으로 안건 보기) */
78
+ .card { padding: 18px 20px; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; }
79
+ .card.done { border-left: 4px solid var(--accent); padding-left: 17px; }
80
+ .card-head { display: block; color: inherit; text-decoration: none; border-radius: 6px; }
81
+ .card-head:hover .card-title, .card-head:focus-visible .card-title { color: var(--accent); }
82
+ .card-head:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
83
+ .card-title { font-size: 17px; font-weight: 700; letter-spacing: -0.02em; margin: 0 0 4px; line-height: 1.45; transition: color .15s; }
84
+ .num { color: var(--ink3); margin-right: 6px; font-weight: 700; }
85
+ .card-sum { font-size: 13.5px; margin: 0; }
86
+ .hopts { display: grid; gap: 6px; margin-top: 12px; }
87
+ .hopt { display: flex; align-items: stretch; min-width: 0; border: 1px solid var(--line); border-radius: 9px;
88
+ transition: border-color .15s, background .15s; }
89
+ .hopt:hover { border-color: var(--ink3); }
90
+ .hopt.picked { border-color: var(--accent); background: var(--accent-soft); box-shadow: inset 0 0 0 1px var(--accent); }
91
+ .hopt-pick { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; border: 0; background: none; border-radius: 9px;
92
+ padding: 8px 12px; text-align: left; font-size: 14px; font-weight: 600; line-height: 1.45; }
93
+ .hopt-pick:focus-visible, .hopt-view:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
94
+ .hopt-t { min-width: 0; }
95
+ .hopt-view { flex: none; display: flex; align-items: center; padding: 0 14px; font-size: 13px; text-decoration: none; white-space: nowrap;
96
+ color: #2f6fd6; border-left: 1px solid var(--line); border-radius: 0 9px 9px 0; }
97
+ :root[data-theme="dark"] .hopt-view { color: #7aa7f0; }
98
+ .hopt-view:hover { text-decoration: underline; }
99
+ .card-note { margin-top: 8px; font-size: 13px; color: var(--ink3); }
100
+ .card-memo { margin-top: 8px; font-size: 13px; color: var(--ink2); white-space: pre-wrap; overflow-wrap: anywhere;
101
+ display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
102
+
103
+ .send { margin-top: 28px; padding: 18px 20px 20px; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; }
104
+ .send label { display: block; font-size: 14px; font-weight: 700; margin: 0 0 6px; }
105
+ textarea { width: 100%; font: inherit; font-size: 14px; color: inherit; background: var(--bg); border: 1px solid var(--line);
106
+ border-radius: 8px; padding: 9px 11px; resize: vertical; line-height: 1.55; }
107
+ textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; border-color: transparent; }
108
+ .send-row { display: flex; align-items: flex-end; justify-content: space-between; gap: 18px; margin-top: 14px; }
109
+ .send-info { font-size: 13px; color: var(--ink2); }
110
+ .send-row .btn.primary { flex: none; white-space: nowrap; }
111
+ .send-info > div + div { margin-top: 2px; }
112
+
113
+ /* ---- 안건 보기: 머리 한 줄, 가운데 그림 반반 (왼쪽 지금 · 오른쪽 안), 아래 설명 띠 (지금 · 안 두 칸, 세 줄 + 펼치기) */
114
+ dialog::backdrop { background: rgba(18, 18, 16, .55); }
115
+ dialog.cmp { width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0;
116
+ background: var(--bg); color: var(--ink); }
117
+ .cmp-in { display: flex; flex-direction: column; height: 100%; }
118
+ .cmp-head { flex: none; display: flex; align-items: center; gap: 12px; padding: 8px 14px; background: var(--panel); border-bottom: 1px solid var(--line); }
119
+ .cmp-head h2 { flex: 0 1 auto; max-width: 34vw; min-width: 0; font-size: 15.5px; font-weight: 700; letter-spacing: -0.02em; margin: 0;
120
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
121
+ .cmp-head .otabs { flex: 0 1 auto; }
122
+ .cmp-head .sp { flex: 1 0 8px; }
123
+ .cmp-nav { display: flex; align-items: center; gap: 2px; flex: none; font-size: 13px; color: var(--ink3); white-space: nowrap; }
124
+ .cmp-nav button { border: 0; background: none; border-radius: 6px; padding: 0 7px; font-size: 18px; line-height: 1.4; color: var(--ink3); }
125
+ .cmp-nav button:hover:not(:disabled) { color: var(--ink); background: var(--bg); }
126
+ .cmp-nav button:disabled { opacity: .35; cursor: default; }
127
+ .x { border: 0; background: none; font-size: 26px; line-height: 1; padding: 0 4px; color: var(--ink3); }
128
+ .x:hover { color: var(--ink); }
129
+
130
+ /* 그림 칸 높이는 fitStage() 가 그림 비율에 맞춰 정한다. 설명 띠는 내용 높이다. 둘이 화면을 넘으면 같이 줄고 (설명은 칸 안 스크롤), 남으면 아래가 빈다 */
131
+ .cmp-stage { position: relative; flex: 0 1 auto; height: 60vh; min-height: 120px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
132
+ gap: 10px; padding: 10px 12px 0; }
133
+ .cmp-stage:focus { outline: none; }
134
+ .cmp-stage.no-left { grid-template-columns: minmax(0, 1fr); }
135
+ .cmp-stage.no-left .pane.left { display: none; }
136
+ .pane { --lab: 34px; position: relative; min-width: 0; min-height: 0; overflow: hidden; background: var(--panel);
137
+ border: 1px solid var(--line); border-radius: 10px; transition: border-color .15s, box-shadow .15s; }
138
+ .pane.picked, .cell.picked { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
139
+ /* 표 (지금 · A 안 · 그림 이름 · 그림 번호) 는 그림 위 머리 줄이다. 그림 위에 얹으면 그림 제목을 가린다 */
140
+ .pane-label { position: absolute; top: 0; left: 0; right: 0; height: var(--lab); z-index: 2; display: flex; align-items: center; gap: 8px;
141
+ padding: 0 10px; border-bottom: 1px solid var(--line); pointer-events: none; font-size: 12.5px; }
142
+ .pane-label .cap, .pane-label .count { color: var(--ink2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
143
+ .pane-label .cap { font-weight: 600; }
144
+ .pane-label .count { margin-left: auto; flex: none; color: var(--ink3); }
145
+ .pane-shot { position: absolute; inset: var(--lab) 0 0 0; display: flex; align-items: flex-start; justify-content: center; overflow: hidden;
146
+ cursor: zoom-in; touch-action: none; user-select: none; -webkit-user-select: none; }
147
+ .pane-shot .media { display: block; max-width: 100%; max-height: 100%; transform-origin: 0 0; -webkit-user-drag: none; }
148
+ /* HTML 그림: 칸 너비로 그리고 내용이 칸보다 길 때만 줄인다 (layoutFrame). 누르기 · 끌기는 칸이 받는다 */
149
+ .pane-shot .media.frame { position: relative; overflow: hidden; max-width: none; max-height: none; flex: none; }
150
+ .media.frame iframe { position: absolute; left: 0; top: 0; border: 0; transform-origin: 0 0; pointer-events: none; background: transparent; }
151
+ .cmp.zoomed .pane-shot { cursor: grab; }
152
+ .cmp.dragging .pane-shot { cursor: grabbing; }
153
+ .noimg { position: absolute; inset: var(--lab) 0 0 0; display: flex; align-items: center; justify-content: center; padding: 20px; text-align: center;
154
+ font-size: 14px; color: var(--ink3); line-height: 1.6; background: var(--bg); }
155
+ .zstep { position: absolute; top: calc(50% + var(--lab) / 2); transform: translateY(-50%); z-index: 3; width: 40px; height: 40px; border-radius: 50%;
156
+ border: 1px solid var(--line); background: var(--panel); color: var(--ink); font-size: 20px; line-height: 1;
157
+ box-shadow: 0 2px 8px rgba(0,0,0,.15); opacity: .9; }
158
+ .zstep:hover:not(:disabled) { opacity: 1; border-color: var(--ink3); }
159
+ .zstep:disabled { opacity: .3; cursor: default; }
160
+ .zstep.prev { left: 8px; } .zstep.next { right: 8px; }
161
+ .zoom-hint { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); z-index: 4; pointer-events: none;
162
+ padding: 5px 12px; border-radius: 999px; background: rgba(29,29,27,.82); color: #fff; font-size: 12.5px; white-space: nowrap; }
163
+ .zoom-hint[hidden] { display: none; }
164
+
165
+ .band { flex: 0 1 auto; min-height: 168px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; padding: 10px 12px 12px; }
166
+ .band.open { min-height: 50vh; }
167
+ .band.no-left { grid-template-columns: minmax(0, 1fr); }
168
+ .band.no-left .cell.now { display: none; }
169
+ .cell { display: flex; gap: 14px; min-width: 0; min-height: 0; padding: 10px 14px 8px; background: var(--panel); border: 1px solid var(--line);
170
+ border-radius: 10px; transition: border-color .15s, box-shadow .15s; }
171
+ .cell.now { background: transparent; border-style: dashed; }
172
+ .cell-main { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: auto; overscroll-behavior: contain; }
173
+ .cell h3 { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 15px; font-weight: 700; letter-spacing: -0.02em; margin: 0; line-height: 1.45; }
174
+ .cell h3 > span:last-child { min-width: 0; }
175
+ /* 설명은 접지 않는다. 띠 높이를 넘으면 칸 안에서 스크롤한다 */
176
+ .cell .rich { font-size: 13.5px; margin-top: 4px; }
177
+ .more-btn { align-self: flex-start; border: 0; background: none; padding: 3px 0 0; font-size: 13px; color: #2f6fd6; }
178
+ :root[data-theme="dark"] .more-btn { color: #7aa7f0; }
179
+ .more-btn:hover { text-decoration: underline; }
180
+ .more-btn[hidden] { display: none; }
181
+ .more { display: none; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line); }
182
+ .band.open .more { display: block; }
183
+ .more-lbl { display: block; font-size: 13px; font-weight: 700; color: var(--ink2); margin: 0 0 4px; }
184
+ .more-sec + .more-sec { margin-top: 12px; }
185
+ .more .memo { min-height: 64px; font-size: 13.5px; padding: 6px 10px; }
186
+ .more .keys { margin-top: 10px; font-size: 12px; color: var(--ink3); }
187
+ .agreed-note { color: var(--ink2); padding-left: 10px; border-left: 3px solid var(--ink3); margin-bottom: 6px; font-size: 13.5px; }
188
+ .cell-act { flex: none; display: flex; flex-direction: column; gap: 8px; width: 150px; }
189
+ .cell-act .btn { width: 100%; }
190
+ .pick-btn { border: 1.5px solid var(--accent); color: var(--accent); background: transparent; border-radius: 8px;
191
+ padding: 8px 14px; font-size: 14.5px; font-weight: 700; }
192
+ .pick-btn:hover { background: var(--accent-soft); }
193
+ .pick-btn[aria-pressed="true"] { background: var(--accent); color: #fff; }
194
+
195
+ /* 안 바꾸기 버튼 (← → 는 그림만 넘기고, 안은 여기서 바꾼다) */
196
+ .otabs { display: flex; gap: 6px; min-width: 0; overflow-x: auto; scrollbar-width: none; }
197
+ .otab { display: inline-flex; align-items: center; gap: 6px; flex: 0 1 auto; min-width: 0; max-width: 260px;
198
+ border: 1px solid var(--line); background: var(--panel); border-radius: 10px; padding: 4px 10px 4px 5px;
199
+ font-size: 13px; font-weight: 600; color: var(--ink2); }
200
+ .otab:hover { border-color: var(--ink3); }
201
+ .otab-t { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
202
+ .otab small { flex: none; font-size: 11px; font-weight: 700; }
203
+ .otab .rec { color: var(--accent); } .otab .agr { color: var(--ink3); }
204
+ .otab.viewing { border-color: var(--ink); color: var(--ink); box-shadow: inset 0 0 0 1px var(--ink); }
205
+ .otab.picked { border-color: var(--accent); }
206
+ .otab.picked.viewing { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
207
+
208
+ kbd { font-family: var(--mono); font-size: 11px; padding: 0 4px; border: 1px solid var(--line); border-bottom-width: 2px;
209
+ border-radius: 4px; background: var(--bg); color: var(--ink2); }
210
+
211
+ .toast { position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%) translateY(20px); opacity: 0; pointer-events: none;
212
+ background: #1d1d1b; color: #fff; padding: 10px 18px; border-radius: 10px; font-size: 14px; z-index: 10;
213
+ transition: opacity .2s, transform .2s; box-shadow: 0 6px 24px rgba(0,0,0,.25); }
214
+ .toast.on { opacity: 1; transform: translateX(-50%); }
215
+ .toast.bad { background: #8a2b0c; }
216
+
217
+ @media (max-width: 1100px) { .cmp-head h2 { max-width: 22vw; } }
218
+ @media (max-width: 760px) {
219
+ .send-row { flex-direction: column; align-items: stretch; }
220
+ .cmp-head { flex-wrap: wrap; }
221
+ .cmp-head h2 { max-width: none; flex-basis: 100%; }
222
+ .cmp-stage { grid-template-columns: minmax(0, 1fr); grid-auto-rows: minmax(0, 1fr); height: 60vh !important; }
223
+ .band { grid-template-columns: minmax(0, 1fr); }
224
+ .cell-act { width: 120px; }
225
+ }
226
+ @media (prefers-reduced-motion: reduce) { * { transition: none !important; scroll-behavior: auto !important; } }
227
+ </style>
228
+ </head>
229
+ <body>
230
+ <main>
231
+ <h1 id="title"></h1>
232
+ <div id="lead" class="lead rich"></div>
233
+ <div class="bar">
234
+ <span id="progress"></span><span class="meter"><i id="meter"></i></span><span id="save" class="save"></span>
235
+ <div class="seg" role="group" aria-label="화면 테마"><button type="button" data-set-theme="light">라이트</button><button type="button" data-set-theme="dark">다크</button></div>
236
+ </div>
237
+ <div id="banner" class="banner" hidden></div>
238
+ <ol id="list" class="list"></ol>
239
+ <section class="send">
240
+ <label for="note">전체 메모</label>
241
+ <textarea id="note" rows="3" placeholder="안건 전체에 덧붙일 말이 있으면 적는다 (선택)"></textarea>
242
+ <div class="send-row">
243
+ <div id="send-info" class="send-info"></div>
244
+ <button type="button" id="send" class="btn primary">Claude 로 보내기</button>
245
+ </div>
246
+ </section>
247
+ </main>
248
+
249
+ <dialog id="cmp" class="cmp" aria-labelledby="cmp-title">
250
+ <div class="cmp-in">
251
+ <header class="cmp-head">
252
+ <h2 id="cmp-title"></h2>
253
+ <nav id="cmp-tabs" class="otabs" aria-label="안 바꾸기"></nav>
254
+ <span class="sp"></span>
255
+ <div class="cmp-nav">
256
+ <button type="button" id="cmp-prev" aria-label="이전 안건">‹</button>
257
+ <span id="cmp-pos"></span>
258
+ <button type="button" id="cmp-hnext" aria-label="다음 안건">›</button>
259
+ </div>
260
+ <div class="seg" role="group" aria-label="화면 테마"><button type="button" data-set-theme="light">라이트</button><button type="button" data-set-theme="dark">다크</button></div>
261
+ <button type="button" class="x" data-close aria-label="목록으로">×</button>
262
+ </header>
263
+ <div id="cmp-stage" class="cmp-stage" tabindex="-1" autofocus>
264
+ <section id="cmp-left" class="pane left" aria-label="지금 상태"></section>
265
+ <section id="cmp-right" class="pane right" aria-label="안"></section>
266
+ <div id="zoom-hint" class="zoom-hint" hidden></div>
267
+ </div>
268
+ <div id="band" class="band">
269
+ <section class="cell now"><div class="cell-main"><div id="band-left"></div></div></section>
270
+ <section id="cell-opt" class="cell opt">
271
+ <div class="cell-main">
272
+ <div id="band-right"></div>
273
+ <div class="more">
274
+ <div id="band-ctx"></div>
275
+ <div class="more-sec"><label class="more-lbl" for="memo">이 안건 메모</label>
276
+ <textarea id="memo" class="memo" rows="3" placeholder="고른 안에 덧붙일 조건이나 다른 의견 (선택)"></textarea></div>
277
+ <div class="keys"><kbd>←</kbd><kbd>→</kbd> 그림 · <kbd>A</kbd><kbd>B</kbd>… 안 바꾸기 · <kbd>Enter</kbd> 이 안으로 하고 다음 안건 ·
278
+ 그림을 누르면 양쪽 같은 자리를 2배로 (휠 배율 · 끌어 옮기기 · <kbd>Esc</kbd> 원래대로)</div>
279
+ </div>
280
+ <button type="button" class="more-btn" data-more></button>
281
+ </div>
282
+ <div class="cell-act">
283
+ <button type="button" id="cmp-pickbtn" class="pick-btn" data-pick="" aria-pressed="false">이 안으로</button>
284
+ <button type="button" id="cmp-next" class="btn">다음 안건 →</button>
285
+ </div>
286
+ </section>
287
+ </div>
288
+ </div>
289
+ </dialog>
290
+
291
+ <div id="toast" class="toast" role="status" aria-live="polite"></div>
292
+
293
+ <script type="application/json" id="spec-data">@@SPEC@@</script>
294
+ <script type="application/json" id="state-data">@@STATE@@</script>
295
+ <script type="application/json" id="config-data">@@CONFIG@@</script>
296
+ <script>
297
+ (() => {
298
+ 'use strict';
299
+ const byId = id => document.getElementById(id);
300
+ const readJSON = id => JSON.parse(byId(id).textContent);
301
+ const spec = readJSON('spec-data');
302
+ const cfg = readJSON('config-data');
303
+ const agendas = spec.agendas;
304
+ const LS = 'agenda-picker:' + cfg.dirKey;
305
+ const THEME_LS = 'agenda-picker:theme';
306
+ const serverMode = cfg.mode === 'server' && /^https?:$/.test(location.protocol);
307
+ const cmpDlg = byId('cmp');
308
+
309
+ // ---------------------------------------------------------------- 상태
310
+ const isObj = v => v !== null && typeof v === 'object' && !Array.isArray(v);
311
+ const strMap = m => Object.fromEntries(Object.entries(isObj(m) ? m : {}).filter(([, v]) => typeof v === 'string'));
312
+ const clean = s => {
313
+ s = isObj(s) ? s : {};
314
+ return { version: 1, updatedAt: typeof s.updatedAt === 'string' ? s.updatedAt : '',
315
+ picks: strMap(s.picks), memos: strMap(s.memos), note: typeof s.note === 'string' ? s.note : '',
316
+ seeded: strMap(s.seeded) };
317
+ };
318
+ const loadLocal = () => { try { return clean(JSON.parse(localStorage.getItem(LS) || 'null')); } catch (e) { return clean(null); } };
319
+ const saveLocal = () => { try { localStorage.setItem(LS, JSON.stringify(state)); } catch (e) { /* 사생활 보호 모드 등 */ } };
320
+
321
+ let state = clean(readJSON('state-data'));
322
+ // ver 는 바뀔 때마다 1 씩 오르고, savedVer 는 서버가 받은 마지막 ver 다. 둘이 다르면 아직 파일에 안 쓰였다.
323
+ let ver = 0, savedVer = 0;
324
+ const unsaved = () => serverMode && ver !== savedVer;
325
+ {
326
+ // 서버에 못 보낸 채 닫힌 변경이 이 브라우저에 남아 있으면 그쪽을 쓴다.
327
+ const local = loadLocal();
328
+ if (local.updatedAt && local.updatedAt > state.updatedAt) { state = local; ver = 1; }
329
+ }
330
+
331
+ // 대화에서 이미 정한 안(decided) 을 미리 골라 둔다. 같은 값은 한 번만 넣으므로 사용자가 페이지에서 바꾸거나 푼 것은
332
+ // 다시 덮지 않는다. Claude 가 decided 를 다른 값으로 고치면 (대화에서 새로 정했으면) 그 값으로 다시 맞춘다.
333
+ const decidedOf = ag => (typeof ag.decided === 'string' && ag.options.some(o => o.id === ag.decided)) ? ag.decided : '';
334
+ let seededNow = false;
335
+ agendas.forEach(ag => {
336
+ const dv = decidedOf(ag);
337
+ if (dv && state.seeded[ag.id] !== dv) { state.picks[ag.id] = dv; state.seeded[ag.id] = dv; seededNow = true; }
338
+ });
339
+
340
+ // ---------------------------------------------------------------- 도우미
341
+ const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
342
+ const inline = s => esc(s).replace(/`([^`]+)`/g, '<code>$1</code>'); // 제목은 평문, `식별자` 만 코드 칩
343
+ const agById = id => agendas.find(a => a.id === id);
344
+ const pickOf = ag => ag.options.find(o => o.id === state.picks[ag.id]) || null;
345
+ const optTag = (op, picked) => `<span class="tag${picked ? ' picked' : ''}">${esc(op.id)}</span>`;
346
+ const recTag = op => op.recommended ? '<span class="tag rec">권장</span>' : '';
347
+ const agreedTag = (ag, op) => op && decidedOf(ag) === op.id ? '<span class="tag agreed">대화에서 정함</span>' : '';
348
+ const fmtTime = iso => { const t = new Date(iso); return isNaN(t) ? '' : t.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); };
349
+
350
+ let toastTimer = 0;
351
+ function toast(msg, bad) {
352
+ const t = byId('toast');
353
+ t.textContent = msg; t.classList.toggle('bad', !!bad); t.classList.add('on');
354
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => t.classList.remove('on'), 3800);
355
+ }
356
+
357
+ // ---------------------------------------------------------------- 테마 · 그림
358
+ // 그림 한 항목은 {light, dark} 쌍이거나 src 하나다. 페이지 테마에 맞는 쪽 하나만 보이고, 없는 쪽은 있는 쪽으로 대신한다.
359
+ const theme = () => document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light';
360
+ const shotsOf = b => (b && Array.isArray(b.shots) ? b.shots : []).map(s => {
361
+ if (typeof s === 'string') s = { src: s };
362
+ if (!isObj(s)) return null;
363
+ const l = s.light || s.src || s.dark || '', d = s.dark || s.src || s.light || '';
364
+ const [w, h] = String(s.size || '').split('x').map(Number); // HTML 그림의 비율 (선택, "1200x460"). 정적 사본에서만 쓴다
365
+ if (isObj(s.figure)) return { fig: s.figure, l: '', d: '', caption: s.caption || '', w: 0, h: 0 };
366
+ return l ? { l, d, caption: s.caption || '', w: w || 0, h: h || 0 } : null;
367
+ }).filter(Boolean);
368
+ // 영상(mp4 · webm · mov · m4v)은 소리 없이 반복 재생한다.
369
+ const isVideo = src => /\.(mp4|webm|mov|m4v)$/i.test(String(src).split(/[?#]/)[0]);
370
+ // HTML(.html · .htm) 그림은 스크린샷 대신 iframe 으로 바로 그린다. 칸의 실제 너비로 그려 글자가 원래 크기이고, 높이는
371
+ // 그 너비에서 잰 내용 높이다. 스크립트는 막고 (sandbox), 같은 origin 이라 페이지가 높이를 재고 테마를 넘긴다.
372
+ // 서버도 .html 에 CSP sandbox 를 붙여, 주소로 바로 열어도 스크립트가 돌지 않는다.
373
+ const isFrame = src => /\.html?$/i.test(String(src).split(/[?#]/)[0]);
374
+ // 그림 데이터 (figure) 를 HTML 문서로 만든다. Claude 는 줄 · 상자 (그래프) 나 본문 조각 (자유) 만 적고, 틀과 공통 스타일
375
+ // (references/diagram/base.css, 서버가 cfg.figCss 로 넘긴다) 은 여기서 붙인다. 토큰을 아끼려는 것이다.
376
+ // {"title", "lanes": [{"who", "nodes": ["글|작은 글", {"t", "s", "k": "new|warn|muted"}]}], "html", "css", "note"}
377
+ function figureDoc(f) {
378
+ const node = n => {
379
+ if (typeof n === 'string') { const [t, sub] = n.split('|'); n = { t, s: sub }; }
380
+ const k = ['new', 'warn', 'muted'].includes(n.k) ? ' ' + n.k : '';
381
+ return `<div class="node${k}">${inline(n.t || '')}${n.s ? `<small>${inline(n.s)}</small>` : ''}</div>`;
382
+ };
383
+ const lanes = Array.isArray(f.lanes) ? f.lanes.map(ln => {
384
+ const who = ln && ln.who ? `<div class="who">${inline(ln.who)}</div>` : '';
385
+ return `<div class="lane${who ? '' : ' solo'}">${who}<div class="row">${(ln && Array.isArray(ln.nodes) ? ln.nodes : []).map(node).join('')}</div></div>`;
386
+ }).join('') : '';
387
+ return `<!doctype html><html data-theme="${theme()}"><head><meta charset="utf-8"><style>${cfg.figCss || ''}\n${f.css || ''}</style></head><body>` +
388
+ (f.title ? `<h1>${inline(f.title)}</h1>` : '') + lanes + (f.html || '') + (f.note ? `<p class="note">${f.note}</p>` : '') + '</body></html>';
389
+ }
390
+ const img = (s, attrs) => {
391
+ const src = theme() === 'dark' ? s.d : s.l;
392
+ if (s.fig) {
393
+ return `<div class="media frame" data-fig="1" data-sw="" data-sh="">` +
394
+ `<iframe srcdoc="${esc(figureDoc(s.fig))}" sandbox="allow-same-origin" tabindex="-1" scrolling="no" title="${esc(s.caption || s.fig.title || '그림')}"></iframe></div>`;
395
+ }
396
+ if (isFrame(s.l)) {
397
+ return `<div class="media frame" data-l="${esc(s.l)}" data-d="${esc(s.d)}" data-sw="${s.w || ''}" data-sh="${s.h || ''}">` +
398
+ `<iframe src="${esc(src)}" sandbox="allow-same-origin" tabindex="-1" scrolling="no" title="${esc(s.caption || '그림')}"></iframe></div>`;
399
+ }
400
+ const head = `class="media" src="${esc(src)}" data-l="${esc(s.l)}" data-d="${esc(s.d)}" ${attrs || ''}`;
401
+ return isVideo(s.l) ? `<video ${head} muted loop autoplay playsinline preload="auto"></video>` : `<img ${head}>`;
402
+ };
403
+ const frameDoc = fr => { try { return fr.contentDocument && fr.contentDocument.documentElement ? fr.contentDocument : null; } catch (e) { return null; } };
404
+ // 그림 문서의 <html> 에 data-theme 을 단다. 그림 HTML 은 :root[data-theme="dark"] 로 다크 색을 쓴다.
405
+ const themeFrame = fr => { const doc = frameDoc(fr); if (doc) { doc.documentElement.dataset.theme = theme(); doc.documentElement.style.colorScheme = theme(); } };
406
+ // 너비 w 로 그렸을 때의 내용 높이. iframe 높이를 1 로 줄여야 문서 높이가 칸 높이가 아니라 내용 높이로 나온다.
407
+ // 문서를 못 읽으면 (file:// 로 연 정적 사본) size 의 비율, 그것도 없으면 너비의 절반으로 둔다.
408
+ function frameHeight(box, w) {
409
+ const fr = box.firstElementChild, doc = frameDoc(fr);
410
+ if (doc && doc.body) {
411
+ fr.width = w; fr.height = 1;
412
+ const h = Math.ceil(Math.max(doc.documentElement.scrollHeight, doc.body.scrollHeight));
413
+ fr.height = h;
414
+ if (h > 1) return h;
415
+ }
416
+ const sw = +box.dataset.sw, sh = +box.dataset.sh;
417
+ return Math.round(sw && sh ? w * sh / sw : w / 2);
418
+ }
419
+ // fitStage 가 칸 높이를 정할 때 쓰는 크기 (칸 너비, 그 너비에서의 높이).
420
+ const frameNat = (box, w) => [w, frameHeight(box, w)];
421
+ // 칸 (pane-shot) 너비로 그리고, 내용이 칸보다 길면 그만큼만 줄인다.
422
+ function layoutFrame(box) {
423
+ const ps = box.parentElement, fr = box.firstElementChild;
424
+ if (!ps || !fr || !ps.clientWidth) return;
425
+ const w = ps.clientWidth, h = frameHeight(box, w), k = Math.min(1, ps.clientHeight / h);
426
+ box.style.width = w * k + 'px'; box.style.height = h * k + 'px';
427
+ fr.style.transform = k < 1 ? `scale(${k})` : '';
428
+ }
429
+
430
+ function paintTheme() {
431
+ const t = theme();
432
+ document.querySelectorAll('[data-set-theme]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.setTheme === t)));
433
+ document.querySelectorAll('.media.frame[data-fig] iframe').forEach(themeFrame);
434
+ document.querySelectorAll('.media[data-l]').forEach(el => {
435
+ const src = t === 'dark' ? el.dataset.d : el.dataset.l;
436
+ const tgt = el.classList.contains('frame') ? el.firstElementChild : el;
437
+ if (tgt.getAttribute('src') !== src) tgt.setAttribute('src', src);
438
+ else if (tgt !== el) themeFrame(tgt); // 테마마다 같은 HTML 이면 문서에 테마만 넘긴다
439
+ });
440
+ }
441
+ function setTheme(t) {
442
+ document.documentElement.dataset.theme = t;
443
+ try { localStorage.setItem(THEME_LS, t); } catch (e) { /* 막힌 저장소 */ }
444
+ paintTheme();
445
+ }
446
+ document.addEventListener('click', e => {
447
+ const b = e.target.closest('[data-set-theme]');
448
+ if (b) setTheme(b.dataset.setTheme);
449
+ });
450
+
451
+ // ---------------------------------------------------------------- 저장
452
+ let online = serverMode, saveErr = null, timer = 0, inflight = null, again = false;
453
+
454
+ function setSave() {
455
+ const el = byId('save');
456
+ let text, bad = false;
457
+ if (!serverMode) text = '이 브라우저에만 저장';
458
+ else if (saveErr && saveErr.status === 403) { text = '페이지가 오래됐다 · 새로고침'; bad = true; }
459
+ else if (!online) { text = '서버 꺼짐 · 이 브라우저에 임시 저장'; bad = true; }
460
+ else if (saveErr) { text = '저장 실패 · ' + saveErr.message; bad = true; }
461
+ else if (unsaved()) text = '저장 중…';
462
+ else text = '저장됨 · selections.json';
463
+ el.textContent = text; el.classList.toggle('error', bad);
464
+ }
465
+
466
+ async function api(method, path, body, extra) {
467
+ const opts = Object.assign({ method, cache: 'no-store', headers: { 'X-Picker-Token': cfg.token } }, extra || {});
468
+ if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
469
+ const r = await fetch(path, opts);
470
+ let data = null;
471
+ try { data = await r.json(); } catch (e) { /* 본문 없음 */ }
472
+ if (!r.ok) { const err = new Error((data && data.message) || ('HTTP ' + r.status)); err.status = r.status; throw err; }
473
+ return data;
474
+ }
475
+
476
+ function touch(delay) {
477
+ state.updatedAt = new Date().toISOString();
478
+ ver++;
479
+ saveLocal();
480
+ setSave();
481
+ clearTimeout(timer);
482
+ if (serverMode) timer = setTimeout(flush, delay || 0);
483
+ }
484
+
485
+ async function flush() {
486
+ clearTimeout(timer); timer = 0;
487
+ if (!unsaved()) return;
488
+ if (inflight) { again = true; return; }
489
+ const v = ver;
490
+ inflight = (async () => {
491
+ try { await api('PUT', '/api/state', state); savedVer = Math.max(savedVer, v); saveErr = null; online = true; }
492
+ catch (e) { saveErr = e.status ? e : null; if (!e.status) online = false; }
493
+ })();
494
+ await inflight; inflight = null; setSave();
495
+ if (again) { again = false; flush(); }
496
+ }
497
+
498
+ window.addEventListener('pagehide', () => {
499
+ if (!unsaved()) return;
500
+ try {
501
+ fetch('/api/state', { method: 'PUT', keepalive: true,
502
+ headers: { 'X-Picker-Token': cfg.token, 'Content-Type': 'application/json' }, body: JSON.stringify(state) });
503
+ } catch (e) { /* localStorage 에 남아 있어 다음에 다시 올린다 */ }
504
+ });
505
+
506
+ // ---------------------------------------------------------------- 바닥 페이지
507
+ function renderHead() {
508
+ byId('title').innerHTML = inline(spec.title);
509
+ if (spec.lead) byId('lead').innerHTML = spec.lead; else byId('lead').remove();
510
+ byId('note').value = state.note;
511
+ }
512
+
513
+ // 카드마다 안을 한 줄씩 늘어놓아 바닥에서 바로 고른다 (다시 누르면 푼다). 그림을 견주려면 줄 끝 링크로 그 안을 연 안건 보기에 들어간다.
514
+ const hasShots = ag => !!(shotsOf(ag.current).length || ag.options.some(o => shotsOf(o).length));
515
+ function renderList() {
516
+ byId('list').innerHTML = agendas.map((ag, i) => {
517
+ const op = pickOf(ag), dv = decidedOf(ag), href = '#' + encodeURIComponent(ag.id);
518
+ const memo = (state.memos[ag.id] || '').trim();
519
+ const view = hasShots(ag) ? '그림 비교 →' : '자세히 →';
520
+ const rows = ag.options.map((o, j) => {
521
+ const on = !!op && op.id === o.id;
522
+ return `<div class="hopt${on ? ' picked' : ''}">
523
+ <button type="button" class="hopt-pick" data-hpick="${esc(o.id)}" aria-pressed="${on}">${optTag(o, on)}<span class="hopt-t">${inline(o.title)}</span>${recTag(o)}${dv === o.id ? '<span class="tag agreed">대화에서 정함</span>' : ''}</button>
524
+ <a class="hopt-view" href="${href}" data-view="${j}">${view}</a></div>`;
525
+ }).join('');
526
+ const note = dv && (!op || op.id !== dv) ? `<div class="card-note">대화에서는 ${esc(dv)} 로 정했다${op ? '' : ' (지금은 풀었다)'}.</div>` : '';
527
+ return `<li><div class="card${op ? ' done' : ''}" data-ag="${esc(ag.id)}">
528
+ <a class="card-head" href="${href}"><h2 class="card-title"><span class="num">${i + 1}.</span>${inline(ag.title)}</h2></a>
529
+ ${ag.summary ? `<div class="card-sum rich">${ag.summary}</div>` : ''}
530
+ <div class="hopts" role="group" aria-label="안 고르기">${rows}</div>
531
+ ${note}
532
+ ${memo ? `<div class="card-memo">메모: ${esc(memo)}</div>` : ''}
533
+ </div></li>`;
534
+ }).join('');
535
+ const done = agendas.filter(pickOf).length;
536
+ const agreed = agendas.filter(ag => { const op = pickOf(ag); return op && op.id === decidedOf(ag); }).length;
537
+ byId('progress').textContent = `결정 ${done} / ${agendas.length}` + (agreed ? ` · 대화에서 정함 ${agreed}` : '');
538
+ byId('meter').style.width = (agendas.length ? done / agendas.length * 100 : 0) + '%';
539
+ renderSend();
540
+ }
541
+
542
+ let meta = null;
543
+ function renderSend() {
544
+ const lines = [];
545
+ const undecided = agendas.filter(a => !pickOf(a)).length;
546
+ lines.push(undecided ? `<span class="warn">미정 ${undecided}건</span>` : '모든 안건을 골랐다.');
547
+ const live = serverMode && online;
548
+ if (live && meta) {
549
+ const ls = meta.lastSent;
550
+ if (ls) {
551
+ const dl = meta.delivery && meta.delivery.seq === ls.seq ? meta.delivery : null;
552
+ if (dl && dl.pending) {
553
+ lines.push(`#${ls.seq} 을 ${fmtTime(ls.sentAt)} 에 보냈다. Claude 입력창에 넣는 중이다.`);
554
+ } else if (dl && !dl.ok && meta.consumed < ls.seq) {
555
+ lines.push(`<span class="warn">#${ls.seq} 을 ${fmtTime(ls.sentAt)} 에 보냈지만 Claude 에 넣지 못했다.</span> ${esc(dl.message)}`);
556
+ } else {
557
+ const got = meta.consumed >= ls.seq;
558
+ lines.push(`#${ls.seq} 을 ${fmtTime(ls.sentAt)} 에 보냈다. ${got ? (dl && dl.ok ? (dl.via === 'inbox' ? 'Claude 세션에 바로 넣었다.' : 'Claude 입력창에 넣었다.') : 'Claude 에 전달됐다.') : 'Claude 에 아직 전달되지 않았다.'}`);
559
+ }
560
+ if (state.updatedAt > (ls.stateUpdatedAt || '')) lines.push('<span class="warn">보낸 뒤 바뀐 선택이 있다.</span>');
561
+ }
562
+ if (!meta.waiter) lines.push('<span class="muted">Claude 가 지금 받을 준비가 안 돼 있다. 보내 두면 Claude 가 다시 기다릴 때 전달된다.</span>');
563
+ }
564
+ if (!serverMode) lines.push(`<span class="muted">파일로 연 페이지라 바로 보낼 수 없다. 버튼은 메시지를 클립보드에 복사한다. 서버가 떠 있으면 <code>http://127.0.0.1:${esc(cfg.port)}/</code> 에서 연다.</span>`);
565
+ else if (!online) lines.push('<span class="muted">서버가 꺼져 있다. 버튼은 메시지를 클립보드에 복사한다.</span>');
566
+ byId('send-info').innerHTML = lines.map(l => `<div>${l}</div>`).join('');
567
+ byId('send').textContent = live ? 'Claude 로 보내기' : '메시지 복사';
568
+ }
569
+
570
+ function showBanner(html) {
571
+ const b = byId('banner');
572
+ b.innerHTML = html; b.hidden = false;
573
+ }
574
+
575
+ byId('note').addEventListener('input', e => { state.note = e.target.value; touch(400); renderSend(); });
576
+ let wantOpt = null; // 줄 끝 링크로 들어가면 그 안을 먼저 보인다
577
+ byId('list').addEventListener('click', e => {
578
+ const b = e.target.closest('[data-hpick]');
579
+ if (b) {
580
+ const agId = b.closest('.card').dataset.ag, oid = b.dataset.hpick;
581
+ setPick(agId, oid);
582
+ const again = document.querySelector(`.card[data-ag="${CSS.escape(agId)}"] [data-hpick="${CSS.escape(oid)}"]`);
583
+ if (again) again.focus(); // 다시 그려도 키보드 자리를 잃지 않게
584
+ return;
585
+ }
586
+ const v = e.target.closest('[data-view]');
587
+ if (v) wantOpt = +v.dataset.view;
588
+ });
589
+ byId('banner').addEventListener('click', async e => {
590
+ if (e.target.closest('[data-reload]')) { await flush(); location.reload(); }
591
+ });
592
+
593
+ // ---------------------------------------------------------------- 안건 보기
594
+ // 카드를 누르면 열린다 (주소 #안건id). 머리 한 줄 (제목 · 안 버튼 · 안건 n/m · 테마 · ×), 가운데 그림 반반 (왼쪽 지금, 오른쪽 안),
595
+ // 아래 설명 띠 (지금 · 안 두 칸, 세 줄 + 펼치기). ← → 는 그림만 넘기고 (양쪽 같이), 안은 안 버튼이나 A · B · C 키로 바꾼다.
596
+ // 그림을 누르면 양쪽 그림의 같은 자리를 같이 2배로 키운다 (휠 배율, 끌어 옮기기도 양쪽이 같이). Esc 나 다시 누르면 원래대로.
597
+ let cmp = null; // { ag, oi: 보는 안 번호, step: 그림 번호 }
598
+ let bandOpen = false;
599
+ // 확대: s 배율, x · y 는 그림 크기에 대한 비율로 잰 이동. 두 그림에 같은 값을 쓰므로 크기가 달라도 같은 자리가 같은 곳에 온다.
600
+ const zoom = { s: 1, x: 0, y: 0 };
601
+ const ZMAX = 8;
602
+
603
+ // 지금 그림과 안 그림의 짝. 모든 그림에 caption 이 있으면 이름으로 (지금 "목록" ↔ A "목록"), 아니면 순서로 맞춘다.
604
+ // 한쪽에 짝이 없으면 그 칸은 비우고 사유를 적는다 (다른 그림을 대신 보이면 짝인 것처럼 보이기 때문이다).
605
+ function model() {
606
+ const ag = cmp.ag, op = ag.options[cmp.oi], L = shotsOf(ag.current), R = shotsOf(op), all = L.concat(R);
607
+ let steps;
608
+ if (all.length && all.every(s => s.caption)) {
609
+ const caps = [];
610
+ all.forEach(s => { if (!caps.includes(s.caption)) caps.push(s.caption); });
611
+ steps = caps.map(cap => ({ cap, l: L.find(s => s.caption === cap) || null, r: R.find(s => s.caption === cap) || null }));
612
+ } else {
613
+ steps = Array.from({ length: Math.max(L.length, R.length, 1) }, (_, i) => ({ cap: '', i, l: L[i] || null, r: R[i] || null }));
614
+ }
615
+ return { ag, op, L, R, steps, st: steps[Math.min(cmp.step, steps.length - 1)] };
616
+ }
617
+
618
+ const missing = (m, side) => {
619
+ const st = m.st;
620
+ if (side === 'L') {
621
+ if (!m.L.length) return '지금 상태 그림이 없다';
622
+ return st.cap ? `지금 상태에는 '${esc(st.cap)}' 그림이 없다` : `지금 상태 그림은 ${m.L.length}장뿐이다`;
623
+ }
624
+ if (!m.R.length) return `${esc(m.op.id)} 안은 그림이 없다.<br>아래 설명을 본다.`;
625
+ return st.cap ? `${esc(m.op.id)} 안에는 '${esc(st.cap)}' 그림이 없다` : `${esc(m.op.id)} 안 그림은 ${m.R.length}장뿐이다`;
626
+ };
627
+
628
+ function openCompare(ag) {
629
+ let oi = wantOpt != null && ag.options[wantOpt] ? wantOpt : ag.options.findIndex(o => o.id === state.picks[ag.id]);
630
+ wantOpt = null;
631
+ if (oi < 0) oi = ag.options.findIndex(o => o.recommended);
632
+ cmp = { ag, oi: Math.max(oi, 0), step: 0 };
633
+ bandOpen = false;
634
+ resetZoom(true);
635
+ byId('memo').value = state.memos[ag.id] || '';
636
+ paintCompare();
637
+ if (!cmpDlg.open) cmpDlg.showModal();
638
+ byId('cmp-stage').focus({ preventScroll: true });
639
+ }
640
+
641
+ const optTabs = (ag, oi) => ag.options.map((o, i) =>
642
+ `<button type="button" class="otab${i === oi ? ' viewing' : ''}" data-opt="${i}" title="${esc(o.id + '. ' + o.title)}">` +
643
+ `<span class="tag">${esc(o.id)}</span><span class="otab-t">${inline(o.title)}</span>` +
644
+ `${o.recommended ? '<small class="rec">권장</small>' : ''}${decidedOf(ag) === o.id ? '<small class="agr">정함</small>' : ''}</button>`).join('');
645
+
646
+ function paintCompare() {
647
+ const c = cmp;
648
+ if (!c) return;
649
+ const m = model(), ag = m.ag, i = agendas.indexOf(ag);
650
+ c.step = Math.min(c.step, m.steps.length - 1);
651
+ byId('cmp-title').innerHTML = `<span class="num">${i + 1}.</span>${inline(ag.title)}`;
652
+ byId('cmp-title').title = ag.title;
653
+ byId('cmp-tabs').innerHTML = optTabs(ag, c.oi);
654
+ byId('cmp-pos').textContent = `안건 ${i + 1} / ${agendas.length}`;
655
+ byId('cmp-prev').disabled = i === 0;
656
+ byId('cmp-hnext').disabled = i === agendas.length - 1;
657
+ byId('cmp-next').textContent = i === agendas.length - 1 ? '목록으로' : '다음 안건 →';
658
+ paintStage(m);
659
+ paintBand(m);
660
+ syncPicks();
661
+ fitStage();
662
+ applyZoom();
663
+ // 누른 버튼이 다시 그려져 사라졌으면 키보드가 계속 먹게 포커스를 옮긴다.
664
+ if (cmpDlg.open && !cmpDlg.contains(document.activeElement)) byId('cmp-stage').focus({ preventScroll: true });
665
+ }
666
+
667
+ const stepBtn = (m, dir) => {
668
+ if (m.steps.length < 2) return '';
669
+ const off = dir < 0 ? cmp.step === 0 : cmp.step === m.steps.length - 1;
670
+ return `<button type="button" class="zstep ${dir < 0 ? 'prev' : 'next'}" data-step="${dir}" aria-label="${dir < 0 ? '이전' : '다음'} 그림"${off ? ' disabled' : ''}>${dir < 0 ? '‹' : '›'}</button>`;
671
+ };
672
+ const capOf = (s, st) => esc((s && s.caption) || st.cap || '');
673
+
674
+ function paintStage(m) {
675
+ const ag = m.ag, st = m.st, hasLeft = !!ag.current;
676
+ byId('cmp-stage').className = 'cmp-stage' + (hasLeft ? '' : ' no-left');
677
+ const shot = (s, side) => s
678
+ ? `<div class="pane-shot" data-zoom="${side}" title="누르면 양쪽 같은 자리를 2배로">${img(s, 'alt="" draggable="false"')}</div>`
679
+ : `<div class="noimg">${missing(m, side)}</div>`;
680
+ const label = (chip, s) => {
681
+ const cap = capOf(s, m.st);
682
+ return `<div class="pane-label">${chip}${cap ? `<span class="cap">${cap}</span>` : ''}` +
683
+ `${m.steps.length > 1 ? `<span class="count">그림 ${cmp.step + 1} / ${m.steps.length}</span>` : ''}</div>`;
684
+ };
685
+ byId('cmp-left').innerHTML = hasLeft
686
+ ? label('<span class="tag now">지금</span>', st.l) + shot(st.l, 'L') + stepBtn(m, -1)
687
+ : '';
688
+ byId('cmp-right').innerHTML = label(`<span class="tag" data-optchip>${esc(m.op.id)} 안</span>`, st.r) + shot(st.r, 'R')
689
+ + (hasLeft ? '' : stepBtn(m, -1)) + stepBtn(m, 1);
690
+ byId('cmp-right').dataset.key = m.op.id;
691
+ }
692
+
693
+ // 그림 칸 높이를 보이는 그림 중 가장 세로로 긴 것에 맞춘다 (칸 너비 × 그림 비율 + 머리 줄). 그림이 아직 안 떴으면
694
+ // 임시 높이로 두고, 뜨면 (load · loadedmetadata) 다시 맞춘다. 화면이 모자라면 flex 가 줄이고 그림은 칸 안에 맞춰 작아진다.
695
+ function fitStage() {
696
+ const st = byId('cmp-stage');
697
+ if (!cmp || matchMedia('(max-width: 760px)').matches) return;
698
+ let need = 0;
699
+ st.querySelectorAll('.pane').forEach(p => {
700
+ if (!p.offsetWidth) return;
701
+ const lab = p.querySelector('.pane-label'), m = p.querySelector('.pane-shot .media');
702
+ const [nw, nh] = !m ? [0, 0] : m.classList.contains('frame') ? frameNat(m, p.clientWidth) : [m.naturalWidth || m.videoWidth, m.naturalHeight || m.videoHeight];
703
+ const body = nw && nh ? p.clientWidth * nh / nw : 220;
704
+ need = Math.max(need, (lab ? lab.offsetHeight : 0) + body);
705
+ });
706
+ st.style.height = Math.ceil(need + 12) + 'px'; // 위 여백 10 + 테두리
707
+ }
708
+
709
+ function paintBand(m) {
710
+ const ag = m.ag, op = m.op, dv = decidedOf(ag), band = byId('band');
711
+ band.className = 'band' + (ag.current ? '' : ' no-left') + (bandOpen ? ' open' : '');
712
+ byId('band-left').innerHTML = ag.current
713
+ ? `<h3><span class="tag now">지금</span><span>${inline(ag.current.title || '지금 상태')}</span></h3>` +
714
+ (ag.current.body ? `<div class="rich">${ag.current.body}</div>` : '')
715
+ : '';
716
+ byId('band-right').innerHTML =
717
+ `<h3><span class="tag" data-optchip>${esc(op.id)}</span>${recTag(op)}${agreedTag(ag, op)}<span>${inline(op.title)}</span></h3>` +
718
+ (op.body ? `<div class="rich">${op.body}</div>` : '');
719
+ byId('cell-opt').dataset.key = op.id;
720
+ byId('cmp-pickbtn').dataset.pick = op.id;
721
+ const ctx = (dv ? `<div class="agreed-note"><b>대화에서 정한 안 ${esc(dv)} 를 미리 골라 두었다.</b> ${ag.decidedNote ? inline(ag.decidedNote) + ' ' : ''}바꾸려면 다른 안을 고른다.</div>` : '')
722
+ + (ag.context ? `<div class="rich">${ag.context}</div>` : '');
723
+ byId('band-ctx').innerHTML = ctx ? `<div class="more-sec"><span class="more-lbl">안건 배경</span>${ctx}</div>` : '';
724
+ paintMore();
725
+ }
726
+
727
+ // 펼치기 버튼은 안 칸에 하나다. 설명은 늘 다 보이고, 펼치면 안건 배경 · 메모 칸이 나온다.
728
+ function paintMore() {
729
+ if (!cmp) return;
730
+ const ag = cmp.ag, memo = (state.memos[ag.id] || '').trim();
731
+ const rb = byId('band').querySelector('[data-more]');
732
+ const extra = [ag.context || decidedOf(ag) ? '안건 배경' : '', '메모'].filter(Boolean).join(' · ');
733
+ rb.textContent = bandOpen ? '▴ 접기' : `▾ 펼치기 (${extra}${memo ? ' 있음' : ' 포함'})`;
734
+ }
735
+
736
+ function setBand(open) {
737
+ bandOpen = open;
738
+ byId('band').classList.toggle('open', open);
739
+ paintMore();
740
+ requestAnimationFrame(applyZoom); // 띠가 커지면 그림 칸이 줄어 그림 크기도 바뀐다
741
+ }
742
+
743
+ // ---- 양쪽 같이 확대
744
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
745
+ function resetZoom(quiet) {
746
+ zoom.s = 1; zoom.x = 0; zoom.y = 0;
747
+ if (!quiet) applyZoom();
748
+ }
749
+ function applyZoom() {
750
+ zoom.s = clamp(zoom.s, 1, ZMAX);
751
+ if (zoom.s <= 1.001) { zoom.s = 1; zoom.x = 0; zoom.y = 0; }
752
+ zoom.x = clamp(zoom.x, 1 - zoom.s, 0);
753
+ zoom.y = clamp(zoom.y, 1 - zoom.s, 0);
754
+ cmpDlg.querySelectorAll('.pane-shot .media.frame').forEach(layoutFrame);
755
+ cmpDlg.querySelectorAll('.pane-shot .media').forEach(im => {
756
+ im.style.transform = zoom.s === 1 ? '' : `translate(${zoom.x * im.offsetWidth}px, ${zoom.y * im.offsetHeight}px) scale(${zoom.s})`;
757
+ });
758
+ const on = zoom.s > 1;
759
+ cmpDlg.classList.toggle('zoomed', on);
760
+ const hint = byId('zoom-hint');
761
+ hint.hidden = !on;
762
+ if (on) hint.textContent = `${zoom.s.toFixed(1)}배 · 휠로 배율 · 끌어서 옮기기 · 누르거나 Esc 로 원래대로`;
763
+ }
764
+ // 그림 위 한 점 (그림 크기에 대한 비율 u · v) 이 화면에서 제자리에 있도록 배율을 바꾼다.
765
+ function zoomAt(s1, u, v) {
766
+ const s0 = zoom.s;
767
+ s1 = clamp(s1, 1, ZMAX);
768
+ zoom.x += (s0 - s1) * clamp(u, 0, 1);
769
+ zoom.y += (s0 - s1) * clamp(v, 0, 1);
770
+ zoom.s = s1;
771
+ applyZoom();
772
+ }
773
+ const pointOn = (im, e) => {
774
+ const r = im.getBoundingClientRect();
775
+ return [(e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height];
776
+ };
777
+
778
+ let drag = null; // { id, x0, y0, zx, zy, im, moved }
779
+ const stage = byId('cmp-stage');
780
+ stage.addEventListener('pointerdown', e => {
781
+ const ps = e.target.closest('.pane-shot');
782
+ if (!ps || e.button !== 0) return;
783
+ const im = ps.querySelector('.media');
784
+ if (!im) return;
785
+ e.preventDefault();
786
+ drag = { id: e.pointerId, x0: e.clientX, y0: e.clientY, zx: zoom.x, zy: zoom.y, im, moved: false };
787
+ ps.setPointerCapture(e.pointerId);
788
+ });
789
+ stage.addEventListener('pointermove', e => {
790
+ if (!drag || e.pointerId !== drag.id) return;
791
+ const dx = e.clientX - drag.x0, dy = e.clientY - drag.y0;
792
+ if (!drag.moved && Math.hypot(dx, dy) < 4) return;
793
+ drag.moved = true;
794
+ if (zoom.s === 1) return;
795
+ cmpDlg.classList.add('dragging');
796
+ zoom.x = drag.zx + dx / (drag.im.offsetWidth || 1);
797
+ zoom.y = drag.zy + dy / (drag.im.offsetHeight || 1);
798
+ applyZoom();
799
+ });
800
+ const endDrag = e => {
801
+ if (!drag || e.pointerId !== drag.id) return;
802
+ const d = drag;
803
+ drag = null;
804
+ cmpDlg.classList.remove('dragging');
805
+ if (d.moved || e.type === 'pointercancel') return;
806
+ if (zoom.s > 1) return resetZoom(); // 확대 중에 누르면 원래대로
807
+ const [u, v] = pointOn(d.im, e);
808
+ zoomAt(2, u, v);
809
+ };
810
+ stage.addEventListener('pointerup', endDrag);
811
+ stage.addEventListener('pointercancel', endDrag);
812
+ stage.addEventListener('wheel', e => {
813
+ const ps = e.target.closest('.pane-shot');
814
+ const im = ps && ps.querySelector('.media');
815
+ if (!im) return;
816
+ e.preventDefault();
817
+ const [u, v] = pointOn(im, e);
818
+ zoomAt(zoom.s * Math.exp(-e.deltaY * 0.0015), u, v);
819
+ }, { passive: false });
820
+ // 테마를 바꾸거나 안을 바꿔 새 그림이 늦게 뜨면 그 크기로 다시 맞춘다.
821
+ const onMedia = e => {
822
+ if (!e.target.closest || !e.target.closest('.pane-shot')) return;
823
+ if (e.target.tagName === 'IFRAME') themeFrame(e.target);
824
+ fitStage(); applyZoom();
825
+ };
826
+ cmpDlg.addEventListener('load', onMedia, true);
827
+ cmpDlg.addEventListener('loadedmetadata', onMedia, true); // 영상은 load 대신 이것으로 크기를 안다
828
+ window.addEventListener('resize', () => { if (cmp) { fitStage(); applyZoom(); paintMore(); } });
829
+
830
+ // 고른 안 표시만 맞춘다 (다시 그리지 않는다).
831
+ function syncPicks() {
832
+ if (!cmp) return;
833
+ const ag = cmp.ag, pid = state.picks[ag.id];
834
+ cmpDlg.querySelectorAll('.otab[data-opt]').forEach(b => {
835
+ const on = ag.options[+b.dataset.opt].id === pid;
836
+ b.classList.toggle('picked', on);
837
+ b.querySelector('.tag').classList.toggle('picked', on);
838
+ });
839
+ const btn = byId('cmp-pickbtn'), on = btn.dataset.pick === pid;
840
+ btn.textContent = on ? '✓ 선택됨' : '이 안으로';
841
+ btn.setAttribute('aria-pressed', String(on));
842
+ cmpDlg.querySelectorAll('[data-key]').forEach(d => d.classList.toggle('picked', d.dataset.key === pid));
843
+ cmpDlg.querySelectorAll('[data-optchip]').forEach(t => t.classList.toggle('picked', cmp.ag.options[cmp.oi].id === pid));
844
+ }
845
+
846
+ function setPick(agId, oid) {
847
+ if (!agId) return;
848
+ if (state.picks[agId] === oid) delete state.picks[agId]; else state.picks[agId] = oid;
849
+ touch(0);
850
+ syncPicks();
851
+ renderList();
852
+ }
853
+
854
+ // 안을 바꿔도 확대는 그대로 둔다 (같은 자리를 안끼리 견준다).
855
+ function setOption(oi) {
856
+ if (!cmp || oi === cmp.oi) return;
857
+ const cap = model().st.cap;
858
+ cmp.oi = oi;
859
+ const j = cap ? model().steps.findIndex(s => s.cap === cap) : -1; // 이름으로 짝을 맞추면 보던 그림 이름을 이어 본다
860
+ if (j >= 0) cmp.step = j;
861
+ paintCompare();
862
+ }
863
+
864
+ function stepBy(d) {
865
+ const n = model().steps.length, s = Math.max(0, Math.min(n - 1, cmp.step + d));
866
+ if (s === cmp.step) return;
867
+ cmp.step = s;
868
+ resetZoom(true);
869
+ paintCompare();
870
+ }
871
+
872
+ function pickAndNext() {
873
+ const op = cmp.ag.options[cmp.oi];
874
+ if (state.picks[cmp.ag.id] !== op.id) setPick(cmp.ag.id, op.id);
875
+ go(1);
876
+ }
877
+
878
+ function route() {
879
+ const ag = agById(decodeURIComponent(location.hash.slice(1)));
880
+ if (ag) {
881
+ if (!cmp || cmp.ag !== ag) openCompare(ag);
882
+ else if (!cmpDlg.open) cmpDlg.showModal();
883
+ } else if (cmpDlg.open) cmpDlg.close();
884
+ }
885
+
886
+ function go(step) {
887
+ const i = agendas.findIndex(a => cmp && a.id === cmp.ag.id) + step;
888
+ if (i >= 0 && i < agendas.length) location.hash = '#' + encodeURIComponent(agendas[i].id);
889
+ else cmpDlg.close();
890
+ }
891
+
892
+ window.addEventListener('hashchange', route);
893
+ cmpDlg.addEventListener('close', () => {
894
+ const was = cmp && cmp.ag.id;
895
+ cmp = null;
896
+ resetZoom(true);
897
+ cmpDlg.classList.remove('zoomed', 'dragging');
898
+ if (location.hash) history.replaceState(null, '', location.pathname + location.search);
899
+ flush();
900
+ renderList();
901
+ const card = was && document.querySelector(`.card[data-ag="${CSS.escape(was)}"] .card-head`);
902
+ if (card) card.focus({ preventScroll: false });
903
+ });
904
+ cmpDlg.addEventListener('click', e => {
905
+ if (!cmp) return;
906
+ if (e.target.closest('[data-close]')) return cmpDlg.close();
907
+ const st = e.target.closest('[data-step]');
908
+ if (st) return stepBy(+st.dataset.step);
909
+ const ot = e.target.closest('[data-opt]');
910
+ if (ot) return setOption(+ot.dataset.opt);
911
+ const pk = e.target.closest('[data-pick]');
912
+ if (pk) return setPick(cmp.ag.id, pk.dataset.pick);
913
+ if (e.target.closest('[data-more]')) return setBand(!bandOpen);
914
+ });
915
+ // 다시 그리는 동안 포커스가 잠깐 dialog 밖으로 나갈 수 있어 키는 document 에서 받는다.
916
+ document.addEventListener('keydown', e => {
917
+ if (!cmpDlg.open || !cmp || e.altKey || e.metaKey || e.ctrlKey) return;
918
+ if (e.key === 'Escape' && zoom.s > 1) { e.preventDefault(); resetZoom(); return; } // 확대 중이면 원래대로만
919
+ if (e.target.closest('textarea, input, select')) return;
920
+ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
921
+ e.preventDefault();
922
+ stepBy(e.key === 'ArrowRight' ? 1 : -1);
923
+ } else if (e.key === 'Enter' && !e.target.closest('button, a')) {
924
+ e.preventDefault();
925
+ pickAndNext();
926
+ } else if (e.key.length === 1 && !e.shiftKey) {
927
+ const j = cmp.ag.options.findIndex(o => o.id.toLowerCase() === e.key.toLowerCase());
928
+ if (j >= 0) { e.preventDefault(); setOption(j); }
929
+ }
930
+ });
931
+ byId('memo').addEventListener('input', e => {
932
+ if (!cmp) return;
933
+ const v = e.target.value;
934
+ if (v.trim()) state.memos[cmp.ag.id] = v; else delete state.memos[cmp.ag.id];
935
+ touch(400);
936
+ });
937
+ byId('cmp-prev').addEventListener('click', () => go(-1));
938
+ byId('cmp-hnext').addEventListener('click', () => go(1));
939
+ byId('cmp-next').addEventListener('click', () => go(1));
940
+
941
+ // ---------------------------------------------------------------- 보내기
942
+ function pickLine(ag, op) {
943
+ const dv = decidedOf(ag), notes = [];
944
+ if (op && op.recommended) notes.push('권장안');
945
+ if (dv) notes.push(op && op.id === dv ? '대화에서 정한 안 그대로' : op ? `대화에서 정한 ${dv} 에서 바꿈` : `대화에서 정한 ${dv} 를 풀었다`);
946
+ const tail = notes.length ? ` (${notes.join(', ')})` : '';
947
+ return op ? ` 선택: ${op.id}. ${op.title}${tail}` : ` 선택: 미정${tail}`;
948
+ }
949
+
950
+ function formatMessage() {
951
+ const lines = [`[agenda-picker] 사용자가 안건 선택을 보냈다 (복사해 붙여 넣음)`, `페이지: ${spec.title}`, `폴더: ${cfg.dir}`, ''];
952
+ agendas.forEach((ag, i) => {
953
+ lines.push(`${i + 1}. ${ag.title} [${ag.id}]`);
954
+ lines.push(pickLine(ag, pickOf(ag)));
955
+ const memo = (state.memos[ag.id] || '').trim();
956
+ if (memo) memo.split('\n').forEach((ln, n) => lines.push((n ? ' ' : ' 메모: ') + ln));
957
+ });
958
+ if (state.note.trim()) { lines.push(''); state.note.trim().split('\n').forEach((ln, n) => lines.push((n ? ' ' : '전체 메모: ') + ln)); }
959
+ lines.push('', `결정 ${agendas.filter(pickOf).length}/${agendas.length}`);
960
+ return lines.join('\n');
961
+ }
962
+
963
+ async function copyText(text) {
964
+ try { await navigator.clipboard.writeText(text); return true; } catch (e) { /* 아래 방식으로 */ }
965
+ const ta = document.createElement('textarea');
966
+ ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
967
+ document.body.appendChild(ta); ta.select();
968
+ let ok = false;
969
+ try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
970
+ ta.remove();
971
+ return ok;
972
+ }
973
+
974
+ byId('send').addEventListener('click', async () => {
975
+ const undecided = agendas.filter(a => !pickOf(a)).length;
976
+ if (undecided && !confirm(`미정인 안건이 ${undecided}건 있다. 이대로 보낼까?`)) return;
977
+ const btn = byId('send');
978
+ if (serverMode && online) {
979
+ btn.disabled = true;
980
+ clearTimeout(timer); timer = 0;
981
+ const v = ver;
982
+ try {
983
+ const r = await api('POST', '/api/submit', state);
984
+ savedVer = Math.max(savedVer, v); saveErr = null;
985
+ meta = Object.assign({}, meta || {}, { lastSent: r.lastSent, consumed: r.consumed, waiter: r.waiter, via: r.via,
986
+ delivery: r.delivery || (meta && meta.delivery) || null });
987
+ if (r.delivery && !r.delivery.ok) toast(`#${r.lastSent.seq} 을 저장했지만 Claude 에 넣지 못했다. ${r.delivery.message}`, true);
988
+ else toast(`#${r.lastSent.seq} 을 Claude 로 보냈다.${r.closeTab ? ' 이 탭을 닫는다.' : ''}`);
989
+ } catch (e) {
990
+ if (!e.status) online = false;
991
+ toast('보내지 못했다: ' + e.message, true);
992
+ } finally {
993
+ btn.disabled = false; setSave(); renderSend();
994
+ }
995
+ return;
996
+ }
997
+ toast(await copyText(formatMessage()) ? '메시지를 복사했다. Claude 세션에 붙여 넣는다.' : '복사하지 못했다', false);
998
+ });
999
+
1000
+ // ---------------------------------------------------------------- 서버 상태 (2초마다)
1001
+ async function poll() {
1002
+ try {
1003
+ const m = await api('GET', '/api/meta');
1004
+ const back = !online;
1005
+ online = true; meta = m;
1006
+ if (saveErr && !saveErr.status) saveErr = null;
1007
+ if ((back || unsaved()) && !timer) flush();
1008
+ if (m.specVersion && m.specVersion !== cfg.specVersion && byId('banner').hidden) {
1009
+ showBanner('안건 내용이 바뀌었다. 지금 선택은 저장돼 있다. <button type="button" class="btn" data-reload>새로고침</button>');
1010
+ }
1011
+ } catch (e) {
1012
+ if (e.status === 403) saveErr = e; else online = false;
1013
+ }
1014
+ setSave(); renderSend();
1015
+ setTimeout(poll, document.hidden ? 6000 : 2000);
1016
+ }
1017
+
1018
+ // ---------------------------------------------------------------- 시작
1019
+ renderHead();
1020
+ renderList();
1021
+ paintTheme();
1022
+ setSave();
1023
+ route();
1024
+ if (seededNow) touch(0); // 미리 골라 둔 안을 selections.json 에도 남긴다
1025
+ if (serverMode) { if (unsaved()) flush(); poll(); }
1026
+ })();
1027
+ </script>
1028
+ </body>
1029
+ </html>