aicommunicator 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +93 -2
  3. package/bin/aic.js +20427 -0
  4. package/host-ui/host.js +5151 -0
  5. package/host-ui/index.html +483 -0
  6. package/host-ui/lang-en.js +631 -0
  7. package/package.json +30 -4
  8. package/plugin-guide.md +997 -0
  9. package/plugins/plugin-animation/LICENSE +55 -0
  10. package/plugins/plugin-animation/dist/logic.js +2225 -0
  11. package/plugins/plugin-animation/docs/manual.md +217 -0
  12. package/plugins/plugin-animation/manifest.json +31 -0
  13. package/plugins/plugin-animation/ui/icon.svg +6 -0
  14. package/plugins/plugin-animation/ui/index.html +2266 -0
  15. package/plugins/plugin-html-design/LICENSE +55 -0
  16. package/plugins/plugin-html-design/dist/logic.js +972 -0
  17. package/plugins/plugin-html-design/docs/manual.md +100 -0
  18. package/plugins/plugin-html-design/manifest.json +39 -0
  19. package/plugins/plugin-html-design/samples/exhibition-page.json +570 -0
  20. package/plugins/plugin-html-design/ui/icon.svg +5 -0
  21. package/plugins/plugin-html-design/ui/index.html +1241 -0
  22. package/plugins/plugin-html-slides/LICENSE +55 -0
  23. package/plugins/plugin-html-slides/dist/logic.js +1323 -0
  24. package/plugins/plugin-html-slides/docs/manual.md +121 -0
  25. package/plugins/plugin-html-slides/manifest.json +39 -0
  26. package/plugins/plugin-html-slides/samples/first-week-lecture.json +1129 -0
  27. package/plugins/plugin-html-slides/ui/icon.svg +5 -0
  28. package/plugins/plugin-html-slides/ui/index.html +1349 -0
  29. package/plugins/plugin-mindmap/LICENSE +55 -0
  30. package/plugins/plugin-mindmap/dist/logic.js +966 -0
  31. package/plugins/plugin-mindmap/docs/manual.md +145 -0
  32. package/plugins/plugin-mindmap/manifest.json +39 -0
  33. package/plugins/plugin-mindmap/samples/book-club.json +480 -0
  34. package/plugins/plugin-mindmap/ui/icon.svg +5 -0
  35. package/plugins/plugin-mindmap/ui/index.html +1774 -0
  36. package/plugins/plugin-plan/LICENSE +55 -0
  37. package/plugins/plugin-plan/dist/logic.js +1029 -0
  38. package/plugins/plugin-plan/docs/manual.md +261 -0
  39. package/plugins/plugin-plan/manifest.json +51 -0
  40. package/plugins/plugin-plan/samples/kimchi-day.json +1514 -0
  41. package/plugins/plugin-plan/samples/meeting-outline.json +653 -0
  42. package/plugins/plugin-plan/samples/reading-class.json +1577 -0
  43. package/plugins/plugin-plan/ui/icon.svg +7 -0
  44. package/plugins/plugin-plan/ui/index.html +1523 -0
  45. package/plugins/plugin-png/LICENSE +55 -0
  46. package/plugins/plugin-png/dist/logic.js +1758 -0
  47. package/plugins/plugin-png/docs/manual.md +344 -0
  48. package/plugins/plugin-png/manifest.json +35 -0
  49. package/plugins/plugin-png/ui/icon.svg +5 -0
  50. package/plugins/plugin-png/ui/index.html +2885 -0
  51. package/plugins/plugin-process-log/LICENSE +55 -0
  52. package/plugins/plugin-process-log/dist/logic.js +406 -0
  53. package/plugins/plugin-process-log/docs/manual.md +131 -0
  54. package/plugins/plugin-process-log/manifest.json +43 -0
  55. package/plugins/plugin-process-log/samples/design-decisions.json +241 -0
  56. package/plugins/plugin-process-log/ui/icon.svg +7 -0
  57. package/plugins/plugin-process-log/ui/index.html +721 -0
  58. package/plugins/plugin-story/LICENSE +55 -0
  59. package/plugins/plugin-story/dist/logic.js +2201 -0
  60. package/plugins/plugin-story/docs/manual.md +428 -0
  61. package/plugins/plugin-story/manifest.json +49 -0
  62. package/plugins/plugin-story/samples/scene-body.json +758 -0
  63. package/plugins/plugin-story/samples/time-and-groups.json +989 -0
  64. package/plugins/plugin-story/ui/icon.svg +4 -0
  65. package/plugins/plugin-story/ui/index.html +2783 -0
  66. package/plugins/plugin-svg/LICENSE +55 -0
  67. package/plugins/plugin-svg/dist/logic.js +2150 -0
  68. package/plugins/plugin-svg/docs/manual.md +314 -0
  69. package/plugins/plugin-svg/manifest.json +45 -0
  70. package/plugins/plugin-svg/samples/rocket-icon.json +1305 -0
  71. package/plugins/plugin-svg/samples/yard-cat.json +7796 -0
  72. package/plugins/plugin-svg/ui/icon.svg +4 -0
  73. package/plugins/plugin-svg/ui/index.html +2017 -0
  74. package/plugins/plugin-tree/LICENSE +55 -0
  75. package/plugins/plugin-tree/dist/logic.js +505 -0
  76. package/plugins/plugin-tree/docs/manual.md +140 -0
  77. package/plugins/plugin-tree/manifest.json +45 -0
  78. package/plugins/plugin-tree/samples/book-club.json +473 -0
  79. package/plugins/plugin-tree/samples/sort-memos.json +604 -0
  80. package/plugins/plugin-tree/ui/icon.svg +7 -0
  81. package/plugins/plugin-tree/ui/index.html +1305 -0
  82. package/schema/aic_describe.input.json +11 -0
  83. package/schema/aic_describe.output.json +67 -0
  84. package/schema/aic_observe.input.json +14 -0
  85. package/schema/aic_observe.output.json +47 -0
  86. package/schema/aic_send.input.json +15 -0
  87. package/schema/aic_send.output.json +38 -0
  88. package/schema/aic_update.input.json +19 -0
  89. package/schema/aic_update.output.json +39 -0
  90. package/schema/common.json +127 -0
  91. package/template/plugin/LICENSE +55 -0
  92. package/template/plugin/README.md +27 -0
  93. package/template/plugin/docs/manual.md +31 -0
  94. package/template/plugin/logic.js +337 -0
  95. package/template/plugin/manifest.json +27 -0
  96. package/template/plugin/ui/icon.svg +4 -0
  97. package/template/plugin/ui/index.html +269 -0
@@ -0,0 +1,1523 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Task Tree</title>
7
+ <style>
8
+ :root {
9
+ color-scheme: light dark;
10
+ --bg: #f5f5f2; --panel: #ffffff; --text: #1f2328; --muted: #5f6771; --line: #dcdfe3; --soft: #f0f1f3;
11
+ --accent: #1f6a8c; --accent-text: #ffffff; --focus-bg: #e2f0f6;
12
+ --ask: #7a4d00; --ask-bg: #fff3d6; --ask-line: #e8c46a; --ai: #5b3fa8; --ai-bg: #eee8fb;
13
+ --add: #1d7a46; --add-bg: #e3f4e9; --upd: #8f5b00; --upd-bg: #fbf0d9; --mov: #3b5bb5; --mov-bg: #e6ebfa; --del: #a8321f; --del-bg: #fae6e2;
14
+ --shadow: 0 1px 3px rgba(0, 0, 0, .18);
15
+ }
16
+ @media (prefers-color-scheme: dark) {
17
+ :root {
18
+ --bg: #191b1e; --panel: #22252a; --text: #e6e8eb; --muted: #a0a8b2; --line: #383d44; --soft: #2b2f35;
19
+ --accent: #7cc0dd; --accent-text: #10222b; --focus-bg: #1f3a46;
20
+ --ask: #f1cf7e; --ask-bg: #3d3115; --ask-line: #7a6223; --ai: #c7b6f5; --ai-bg: #2f2747;
21
+ --add: #7bd6a0; --add-bg: #17392a; --upd: #eec26e; --upd-bg: #41331a; --mov: #a5b9f4; --mov-bg: #252f4f; --del: #f1a597; --del-bg: #472420;
22
+ --shadow: 0 1px 3px rgba(0, 0, 0, .6);
23
+ }
24
+ }
25
+ * { box-sizing: border-box; }
26
+ html, body { height: 100%; }
27
+ body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.6 system-ui, "Malgun Gothic", sans-serif; }
28
+
29
+ /* 작업 내용이 화면을 넓게 쓴다. 바뀐 기록 칸은 숨긴 채 시작하고 위쪽 아이콘으로 연다(rawdev 2026-11-24) */
30
+ #stage { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; margin: 0 auto; padding: 12px; align-items: start; }
31
+ #stage.with-side { grid-template-columns: minmax(0, 1fr) 280px; }
32
+ section { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px 12px; margin-bottom: 14px; }
33
+ .head { display: flex; align-items: center; justify-content: space-between; gap: 6px; margin-bottom: 6px; flex-wrap: wrap; }
34
+ h2 { font-size: 14px; margin: 0; color: var(--muted); font-weight: 600; }
35
+ ul { list-style: none; margin: 0; padding: 0; }
36
+
37
+ button { font: inherit; color: inherit; cursor: pointer; }
38
+ .btn { white-space: nowrap; background: transparent; border: 1px solid var(--line); border-radius: 5px; padding: 1px 8px; font-size: 13px; line-height: 1.6; }
39
+ .btn:hover { background: var(--soft); }
40
+ .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
41
+ .icon { background: transparent; border: 0; border-radius: 4px; padding: 0 5px; color: var(--muted); font-size: 13px; line-height: 1.6; min-width: 22px; }
42
+ .icon:hover { background: var(--soft); color: var(--text); }
43
+ .icon.armed { background: var(--del-bg); color: var(--del); font-weight: 600; }
44
+ /* 아이콘 버튼은 코어 화면과 같은 모양이다. 이름은 title 과 aria-label 에 둔다 */
45
+ .bar { display: flex; gap: 2px; margin-left: auto; flex: none; }
46
+ .icon-btn { position: relative; display: inline-flex; align-items: center; justify-content: center; flex: none; width: 28px; height: 28px; padding: 0; background: transparent; border: 1px solid transparent; border-radius: 6px; color: var(--muted); }
47
+ .icon-btn:hover { background: var(--soft); color: var(--text); }
48
+ .icon-btn[aria-expanded="true"] { background: var(--soft); border-color: var(--line); color: var(--accent); }
49
+ .icon-btn svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
50
+ .icon-btn .dot { position: absolute; top: 3px; right: 3px; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
51
+ .icon-btn .count { position: absolute; top: -3px; right: -3px; min-width: 15px; height: 15px; padding: 0 3px; border-radius: 8px; background: var(--accent); color: var(--accent-text); font-size: 10px; line-height: 15px; text-align: center; }
52
+ button:focus-visible, select:focus-visible, textarea:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
53
+
54
+ /* 뿌리: 이루려는 결과와 조건(2절) */
55
+ .goal-title { font-size: 18px; font-weight: 650; margin: 0; flex: 1; min-width: 0; overflow-wrap: anywhere; cursor: text; }
56
+ .field { display: flex; gap: 6px; font-size: 14px; margin-top: 2px; overflow-wrap: anywhere; }
57
+ .field b { flex: none; color: var(--muted); font-weight: 600; min-width: 6.5em; }
58
+ .field span { white-space: pre-wrap; }
59
+ .summary { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
60
+ .chip { font-size: 13px; border-radius: 12px; padding: 0 9px; border: 1px solid var(--line); background: transparent; }
61
+ .chip.ask { background: var(--ask-bg); border-color: var(--ask-line); color: var(--ask); }
62
+ .chip.ai { background: var(--ai-bg); border-color: transparent; color: var(--ai); }
63
+ .chip.doing { background: var(--focus-bg); border-color: transparent; color: var(--accent); }
64
+
65
+ /* 트리 */
66
+ .children { margin-left: 18px; padding-left: 8px; border-left: 1px solid var(--line); }
67
+ .node { position: relative; }
68
+ .task { position: relative; display: flex; align-items: flex-start; gap: 4px; padding: 3px 4px; border-radius: 6px; border-left: 3px solid transparent; }
69
+ .task.doing { background: var(--focus-bg); box-shadow: inset 3px 0 0 var(--accent); }
70
+ .task.focus { outline: 2px solid var(--accent); }
71
+ /* 사람이 고른 가지와 질문. 고르면 아래쪽에 AI 에게 말할 칸이 뜬다 */
72
+ .task.picked { background: var(--focus-bg); box-shadow: inset 0 0 0 2px var(--accent); }
73
+ .question.picked { box-shadow: 0 0 0 2px var(--accent); }
74
+ .task.drop-before::before, .task.drop-after::after { content: ""; position: absolute; left: 0; right: 0; height: 2px; background: var(--accent); }
75
+ .task.drop-before::before { top: -2px; }
76
+ .task.drop-after::after { bottom: -2px; }
77
+ .task.drop-in { outline: 2px dashed var(--accent); outline-offset: 1px; }
78
+ .task.dragging { opacity: .45; }
79
+ .toggle { flex: none; width: 20px; border: 0; background: transparent; color: var(--muted); padding: 0; line-height: 1.6; }
80
+ .toggle[disabled] { cursor: default; opacity: .35; }
81
+ .grip { flex: none; cursor: grab; color: var(--muted); border: 0; background: transparent; padding: 0 2px; line-height: 1.6; }
82
+ .tid { flex: none; color: var(--muted); font-size: 12px; line-height: 1.6rem; }
83
+ .task-main { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 6px; }
84
+ .title { overflow-wrap: anywhere; cursor: text; }
85
+ .task.st-done .title { color: var(--muted); text-decoration: line-through; text-decoration-thickness: 1px; }
86
+ .status { font: inherit; font-size: 12px; border: 1px solid var(--line); border-radius: 10px; padding: 0 4px; background: var(--panel); color: var(--muted); }
87
+ .badge { font-size: 12px; line-height: 1.5; border-radius: 3px; padding: 0 5px; }
88
+ .badge.ask { color: var(--ask); background: var(--ask-bg); }
89
+ .badge.ai { color: var(--ai); background: var(--ai-bg); }
90
+ .badge.dep { color: var(--muted); background: var(--soft); }
91
+ .badge.hidden-change { color: var(--upd); background: var(--upd-bg); }
92
+ .badge.detail-change { color: var(--mov); background: var(--mov-bg); }
93
+ /* 결과 확인: 맞음, 일부만, 다름이 서로 다른 색이다(9.10절 5번) */
94
+ .chk-meets { color: var(--add); border-color: var(--add); }
95
+ .chk-partial { color: var(--mov); border-color: var(--mov); }
96
+ .chk-differs { color: var(--del); border-color: var(--del); }
97
+ /* 접힌 곳이 바뀜, 자세히 보기에 바뀐 것 있음: 뜻은 title 에 두고 점 하나만 보인다 */
98
+ .mark-dot { flex: none; align-self: center; width: 8px; height: 8px; border-radius: 50%; }
99
+ .mark-dot.hidden-change { background: var(--upd); }
100
+ .mark-dot.detail-change { background: var(--mov); }
101
+ /* 가지의 도구는 ⋯ 메뉴 하나에 모은다 */
102
+ .tools { position: relative; flex: none; display: flex; align-items: flex-start; }
103
+ .more { font-weight: 700; letter-spacing: 1px; }
104
+ .menu { position: absolute; z-index: 30; right: 0; top: 100%; min-width: 12em; display: grid; padding: 4px; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; box-shadow: var(--shadow); }
105
+ .menu-item { text-align: left; background: transparent; border: 0; border-radius: 4px; padding: 3px 8px; font-size: 13px; white-space: nowrap; }
106
+ .menu-item:hover, .menu-item:focus-visible { background: var(--soft); }
107
+ .menu-item.armed { background: var(--del-bg); color: var(--del); font-weight: 600; }
108
+ @media (hover: hover) {
109
+ .tools, .mini, .tid { opacity: 0; transition: opacity .1s; }
110
+ .task:hover > .tools, .task:focus-within > .tools, .task.menu-open > .tools, .task:hover > .tid, .has-mini:hover .mini, .has-mini:focus-within .mini { opacity: 1; }
111
+ }
112
+ @media (hover: none) { .tid { display: none; } }
113
+ .detail { margin: 2px 0 6px 46px; padding: 6px 8px; border-radius: 6px; background: var(--soft); font-size: 14px; }
114
+ .detail h3 { font-size: 12px; color: var(--muted); margin: 6px 0 2px; font-weight: 600; }
115
+ .detail h3:first-child { margin-top: 0; }
116
+ .item { display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; padding: 1px 0; overflow-wrap: anywhere; }
117
+ .empty { color: var(--muted); font-size: 14px; }
118
+
119
+ /* 질문(3절): 이유, 대안과 추천, 달라질 범위, 기다리는 가지 */
120
+ .question { margin: 3px 0 6px 46px; padding: 6px 10px 8px; border-radius: 6px; border: 1px solid var(--ask-line); background: var(--ask-bg); font-size: 14px; }
121
+ .question.answered { border-color: var(--line); background: var(--panel); }
122
+ .question.delegated { border-color: transparent; background: var(--ai-bg); }
123
+ .q-text { font-weight: 600; overflow-wrap: anywhere; }
124
+ .q-meta { color: var(--muted); font-size: 13px; margin-top: 2px; overflow-wrap: anywhere; }
125
+ .options { margin-top: 4px; display: grid; gap: 3px; }
126
+ .option { display: flex; gap: 6px; align-items: baseline; padding: 3px 6px; border-radius: 5px; background: var(--panel); border: 1px solid var(--line); overflow-wrap: anywhere; }
127
+ .option.chosen { border-color: var(--accent); box-shadow: inset 3px 0 0 var(--accent); }
128
+ .option .o-body { flex: 1; min-width: 0; }
129
+ .option small { color: var(--muted); display: block; }
130
+ .answer { margin-top: 4px; padding: 4px 6px; border-radius: 5px; background: var(--soft); overflow-wrap: anywhere; }
131
+ .q-actions { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 6px; align-items: center; }
132
+ /* 답한 질문은 질문과 고른 답 한 줄로 접힌다. 누르면 펼쳐진다 */
133
+ .question.compact { padding: 2px 8px; display: flex; align-items: baseline; gap: 6px; }
134
+ .q-line { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; text-align: left; background: transparent; border: 0; padding: 0; overflow-wrap: anywhere; }
135
+ .q-line .q-text { font-weight: 500; }
136
+ .q-answer { color: var(--muted); }
137
+ .q-fold { flex: none; border: 0; background: transparent; color: var(--muted); padding: 0 2px 0 0; }
138
+
139
+ /* 변경 표시는 스토리 화면과 같다 */
140
+ .m-add { border-left-color: var(--add); background: var(--add-bg); }
141
+ .m-update { border-left-color: var(--upd); background: var(--upd-bg); }
142
+ .m-move { border-left-color: var(--mov); background: var(--mov-bg); }
143
+ .item.m-add, .option.m-add { box-shadow: inset 2px 0 0 var(--add); background: var(--add-bg); }
144
+ .item.m-update, .option.m-update { box-shadow: inset 2px 0 0 var(--upd); background: var(--upd-bg); }
145
+ .old.m-add, .old.m-update, .old.m-move { opacity: .8; }
146
+ .tag { display: inline-block; font-size: 12px; line-height: 1.5; padding: 0 5px; border-radius: 3px; border: 0; }
147
+ .tag.add { color: var(--add); background: var(--add-bg); }
148
+ .tag.update { color: var(--upd); background: var(--upd-bg); }
149
+ .tag.move { color: var(--mov); background: var(--mov-bg); }
150
+ .tag.remove { color: var(--del); background: var(--del-bg); }
151
+ .before { color: var(--muted); font-size: 13px; padding: 2px 4px 2px 8px; border-left: 2px solid var(--line); margin: 2px 0 4px 46px; overflow-wrap: anywhere; }
152
+
153
+ /* 입력 */
154
+ textarea, input[type=text], select { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--accent); border-radius: 5px; padding: 2px 6px; }
155
+ select { border-color: var(--line); max-width: 100%; }
156
+ textarea { width: 100%; display: block; resize: vertical; min-height: 2.1em; }
157
+ input[type=text] { width: 100%; }
158
+ .form { display: grid; gap: 5px; margin-top: 6px; }
159
+ .form label > span { color: var(--muted); font-size: 12px; display: block; }
160
+ .actions { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; }
161
+ .hint { color: var(--muted); font-size: 12px; margin: 2px 0 0; }
162
+ .inline { flex: 1; min-width: 12em; }
163
+
164
+ /* 부딪힘 */
165
+ .conflict { border: 1px solid var(--del); border-radius: 6px; padding: 6px 8px; margin: 4px 0 4px 46px; background: var(--panel); font-size: 14px; }
166
+ .conflict h3 { margin: 0 0 4px; font-size: 13px; color: var(--del); font-weight: 600; }
167
+ .sides { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
168
+ .side { border: 1px solid var(--line); border-radius: 5px; padding: 3px 6px; overflow-wrap: anywhere; }
169
+ .side b { display: block; font-size: 12px; color: var(--muted); font-weight: 600; }
170
+ .warn { font-size: 12px; color: var(--muted); margin: 4px 0; overflow-wrap: anywhere; }
171
+
172
+ .feed li { padding: 4px 0; border-top: 1px solid var(--line); font-size: 13px; overflow-wrap: anywhere; }
173
+ .feed li:first-child { border-top: 0; }
174
+ .who { color: var(--muted); font-size: 12px; display: block; }
175
+ .feed-head { display: block; width: 100%; text-align: left; background: transparent; border: 0; padding: 2px 3px; border-radius: 4px; color: inherit; font: inherit; cursor: pointer; }
176
+ .feed-head:hover { background: var(--soft); }
177
+ .feed-head .headline { display: block; font-size: 13px; }
178
+ .feed-head .who b { color: var(--text); }
179
+ .pending-chip { margin-left: 6px; color: var(--muted); font-size: 11px; }
180
+ .feed-detail { list-style: none; margin: 4px 0 2px; padding: 0 0 0 8px; border-left: 2px solid var(--line); max-height: 260px; overflow: auto; }
181
+ .feed-detail li { border-top: 0; padding: 1px 0; font-size: 12px; }
182
+ .feed-detail .kind-tag { color: var(--muted); font-weight: 600; }
183
+ .legend { color: var(--muted); font-size: 12px; margin: 0 0 6px; }
184
+ .readonly { background: var(--soft); border-radius: 6px; padding: 6px 10px; font-size: 14px; margin-bottom: 10px; }
185
+
186
+ /* 고른 것이 있을 때만 뜨는 말 칸. 아래쪽은 잘 보이지 않아 목표 칸(위쪽 아이콘 줄) 바로 아래에 두고, 트리를 내려 읽을 때도
187
+ 화면 맨 위에 붙어 남는다(rawdev 2026-11-25 "상단에 둬") */
188
+ #quickTalk { position: sticky; top: 6px; z-index: 20; display: flex; align-items: center; gap: 4px; margin: -6px 0 8px; background: var(--panel); border: 1px solid var(--accent); border-radius: 8px; padding: 5px 6px; box-shadow: 0 2px 10px rgba(0, 0, 0, .14); }
189
+ #quickTalk input { flex: 1; min-width: 0; }
190
+ #quickWhat { flex: none; max-width: 30%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); font-size: 12px; padding: 0 4px; }
191
+ #toast { position: fixed; z-index: 50; left: 50%; bottom: 14px; transform: translateX(-50%); background: var(--text); color: var(--bg); padding: 5px 12px; border-radius: 6px; font-size: 14px; max-width: min(90vw, 640px); }
192
+ #toast.bad { background: var(--del); color: #fff; }
193
+ #error { color: var(--del); padding: 16px; }
194
+ [hidden] { display: none !important; }
195
+
196
+ @media (max-width: 900px) {
197
+ #stage, #stage.with-side { grid-template-columns: minmax(0, 1fr); padding: 10px; }
198
+ .detail, .question, .before, .conflict { margin-left: 20px; }
199
+ .children { margin-left: 10px; padding-left: 6px; }
200
+ }
201
+ </style>
202
+ </head>
203
+ <body>
204
+ <div id="error" role="alert" hidden></div>
205
+ <main id="stage"></main>
206
+ <div id="toast" role="status" hidden></div>
207
+ <div id="quickTalk" hidden>
208
+ <span id="quickWhat"></span>
209
+ <input id="quickSaid" type="text" autocomplete="off" aria-label="What to tell the AI about the selection" placeholder="Tell the AI about the selection">
210
+ <button type="button" class="btn primary" id="quickSend" title="Send the selection and your words to the AI">Send</button>
211
+ <button type="button" class="icon" id="quickClear" title="Clear the selection" aria-label="Clear the selection">×</button>
212
+ </div>
213
+ <script>
214
+ // 작업 트리의 화면(plugin-design/task-tree.md 9.6절). 호스트 연결로만 코어와 이야기한다. 글은 모두 textContent 로 넣는다.
215
+ // 사람이 화면에서 하는 일도 모두 플러그인 조작으로 바뀌어 AI 와 같은 경로로 저장된다. 접고 펼친 것은 화면 상태라 저장하지 않는다.
216
+ 'use strict';
217
+ const stage = document.getElementById('stage');
218
+ const errorEl = document.getElementById('error');
219
+ const toastEl = document.getElementById('toast');
220
+
221
+ let nextId = 1;
222
+ const waiting = new Map();
223
+ let concept = null;
224
+ let feed = [];
225
+ const expanded = new Set(); // 펼친 가지
226
+ const seenTasks = new Set(); // 처음 볼 때만 펼칠지 정한다. 사람이 접은 것은 그대로 둔다
227
+ const details = new Set(); // 자세히 펼친 가지
228
+ const openBefore = new Set();
229
+ let focused = new Set();
230
+ let editor = null; // 지금 쓰는 칸 하나. { key, values, build, base }
231
+ let composing = false;
232
+ let dragging = null;
233
+ let committing = false;
234
+ let renderWanted = false;
235
+ // 그린 기준 알림(032 10.3절). 호스트가 읽기 응답에 붙인 표를, 그 응답을 다 그린 뒤 그대로 돌려보낸다.
236
+ let drawPending = false;
237
+ const armed = new Map();
238
+ // 숨긴 채 시작하는 것들. 화면 상태라 저장하지 않는다(rawdev 2026-11-24)
239
+ let sideOpen = false; // 바뀐 기록 칸
240
+ let helpOpen = false; // 표시 설명
241
+ let goalOpen = false; // 목표의 이루려는 것과 조건
242
+ const openQs = new Set(); // 펼친 답한 질문
243
+ let menuFor = null; // ⋯ 메뉴를 연 가지
244
+ let noticesHidden = false; // 알림은 보인 채 시작하고 사람이 숨긴다(한눈에 보아야 하는 정보)
245
+ let feedSeen = null; // 바뀐 기록 칸을 닫았을 때 본 마지막 기록. 그 뒤에 남이 한 기록이 오면 아이콘에 점을 찍는다
246
+ let feedFor = null; // feedSeen 이 어느 작업의 것인지
247
+ // capabilities() 의 edit. 보조 보기이거나 커서가 AI 에게 있으면 호스트가 false 를 준다(032 21절, 33절 7번).
248
+ // 커서가 돌아오면 호스트가 화면을 다시 올리므로 시작할 때 한 번만 읽는다
249
+ let canEdit = true;
250
+ // capabilities() 전체. conceptSelection 이면 고른 것을 말과 함께 보내고, conceptPick 이면 고르기만 한 것도 호스트에 알린다(032 30절)
251
+ let caps = {};
252
+ const SELECTION_FORMAT = 'aic.plan/selection-1';
253
+ const picked = new Set(); // 사람이 고른 가지와 질문의 id. 화면 상태라 저장하지 않는다
254
+ let lastReadOnly = true; // 마지막으로 그린 화면이 읽기만 하는 화면이었는지
255
+ let sharing = false;
256
+
257
+ // 화면 글의 언어(032 36절, plugin-guide 3.7절과 4.4절, rawdev 2026-11-25 "넣기"). 영어가 원문이고, capabilities() 의 language 가 'ko' 일
258
+ // 때만 아래 사전의 한국어를 보인다. 다른 값이거나 없으면(옛 호스트) 영어다. 사람이 언어를 바꾸면 호스트가 화면을 다시 여므로 처음 한 번만 읽는다.
259
+ // 이 화면은 이름 t 를 가지 변수로 많이 쓰므로 글을 바꾸는 함수는 tr 이다. 논리가 낸 글(요약, 거절 문장)과 코어의 알림은 영어 그대로 보인다.
260
+ let LANG = 'en';
261
+ // <ko-dictionary> 영어 원문에서 한국어로. 열쇠는 화면 코드의 tr('...') 첫 인자와 글자 그대로 같다(src/lang.test.ts 가 맞춰 본다)
262
+ const KO = {
263
+ // 위쪽 아이콘, 목표 칸
264
+ 'Task Tree': '작업 트리',
265
+ 'Expand all': '모두 펼치기',
266
+ 'Collapse all': '모두 접기',
267
+ 'What the marks mean': '표시 설명',
268
+ 'Show change history{extra}': '바뀐 기록{extra} 보기',
269
+ 'Hide change history{extra}': '바뀐 기록{extra} 숨기기',
270
+ ' (new entries)': '(새 기록 있음)',
271
+ ', {count} removed by AI': ', AI 가 지운 것 {count}개',
272
+ ', {count} hidden notice': ', 숨긴 알림 {count}개',
273
+ ', {count} hidden notices': ', 숨긴 알림 {count}개',
274
+ 'Goal': '목표',
275
+ 'Show aim and conditions': '이루려는 것과 조건 보기',
276
+ 'Hide aim and conditions': '이루려는 것과 조건 접기',
277
+ 'Edit aim and conditions': '이루려는 것과 조건 고치기',
278
+ 'The result to achieve': '이루려는 결과',
279
+ 'Write the result you want and the conditions that matter, and AI breaks it down into an action plan below. You can also just tell AI.': '이루려는 결과와 중요한 조건을 적으면, AI 가 그 아래로 실행계획을 펼칩니다. AI 에게 말로 해도 됩니다.',
280
+ 'Write the goal': '목표 적기',
281
+ 'Create': '만들기',
282
+ 'Please write the goal': '목표를 적어 주세요',
283
+ 'Waiting for answer: {text}': '답 기다림: {text}',
284
+ 'AI to decide: {text}': 'AI 가 정할 차례: {text}',
285
+ 'In progress: {text}': '하는 중: {text}',
286
+ // 쓰는 칸
287
+ 'Save': '저장',
288
+ 'Cancel': '취소',
289
+ 'Enter to save, Esc to cancel': 'Enter 로 저장, Esc 로 취소',
290
+ 'Edit': '고치기',
291
+ 'Add': '더하기',
292
+ 'Aim': '이루려는 것',
293
+ 'Conditions': '조건',
294
+ 'Method': '방법',
295
+ 'Conditions to keep': '지켜야 할 조건',
296
+ 'What it should achieve': '이루려는 것',
297
+ 'Chosen method and a short reason': '택한 방법과 짧은 이유',
298
+ 'Nothing written yet.': '아직 적은 것이 없습니다.',
299
+ // 가지 줄
300
+ 'To do': '할 일',
301
+ 'In progress': '하는 중',
302
+ 'Done': '끝남',
303
+ 'Expand': '펼치기',
304
+ 'Collapse': '접기',
305
+ 'Drag to move. Drop on the middle of a branch to put it under that branch': '끌어서 옮기기. 가지 가운데에 놓으면 그 아래로 들어갑니다',
306
+ 'Drag {name} to move': '{name} 끌어서 옮기기',
307
+ 'Branch name': '가지 이름',
308
+ 'New branch name': '새 가지 이름',
309
+ 'Rename: {name}': '이름 바꾸기: {name}',
310
+ '{name} status': '{name} 상태',
311
+ 'Waiting for answer': '답 기다림',
312
+ 'AI to decide': 'AI 가 정할 차례',
313
+ 'Needs first: {list}': '먼저 있어야 할 가지: {list}',
314
+ 'Needs {count} branch first: {list}': '먼저 있어야 할 가지 {count}개: {list}',
315
+ 'Needs {count} branches first: {list}': '먼저 있어야 할 가지 {count}개: {list}',
316
+ 'A question in the folded part is waiting for an answer': '접힌 곳에 답을 기다리는 질문이 있습니다',
317
+ '{count} question folded': '접힌 곳에 질문 {count}',
318
+ '{count} questions folded': '접힌 곳에 질문 {count}',
319
+ 'Folded part changed: a branch or question folded below has a change that is not settled yet': '접힌 곳이 바뀜: 접힌 아래 가지나 질문에 아직 확정되지 않은 변경이 있습니다',
320
+ 'Folded part changed': '접힌 곳이 바뀜',
321
+ 'Details changed: a result, dependency or link to another screen has a change that is not settled yet': '자세히 보기에 바뀐 것 있음: 결과, 의존, 다른 화면의 대상 가운데 아직 확정되지 않은 변경이 있습니다',
322
+ 'Details changed': '자세히 보기에 바뀐 것 있음',
323
+ // ⋯ 메뉴
324
+ '{name} menu': '{name} 메뉴',
325
+ 'Details, add a branch or question, move, remove': '자세히, 가지와 질문 더하기, 옮기기, 지우기',
326
+ 'Details': '자세히',
327
+ 'Close details': '자세히 닫기',
328
+ '+ Branch below': '+ 아래에 가지',
329
+ '+ Question': '+ 질문',
330
+ '↑ Move up': '↑ 위로',
331
+ '↓ Move down': '↓ 아래로',
332
+ '← Move out one level': '← 한 단계 위로 빼기',
333
+ '× Remove branch': '× 가지 지우기',
334
+ 'Remove {what}': '{what} 지우기',
335
+ 'Remove?': '지울까요?',
336
+ // 자세히
337
+ 'Id {id}': '번호 {id}',
338
+ 'Aim, conditions, method': '이루려는 것, 조건, 방법',
339
+ 'Needs first': '먼저 있어야 할 것',
340
+ 'None': '없음',
341
+ 'Waited on by: {list}': '이것을 기다리는 가지: {list}',
342
+ 'Waits for the answer to ({question}): {list}': '답 전에 기다린 가지({question}): {list}',
343
+ 'Choose a branch needed first': '먼저 있어야 할 가지 고르기',
344
+ '+ Branch needed first': '+ 먼저 있어야 할 가지',
345
+ 'Results': '결과',
346
+ 'Not checked': '확인 안 함',
347
+ 'Meets': '맞음',
348
+ 'Partly': '일부만',
349
+ 'Differs': '다름',
350
+ 'Whether the result matches the intent': '결과가 의도에 맞는지',
351
+ 'Output {id}': '결과물 {id}',
352
+ 'Note: {note}': '메모: {note}',
353
+ 'Result': '결과',
354
+ 'Note': '메모',
355
+ 'What was done and where is it?': '무엇을 했고 어디에 있나요?',
356
+ 'If it does not match, what differs': '맞지 않으면 무엇이 다른지',
357
+ '+ Result': '+ 결과',
358
+ 'Please write the result': '결과를 적어 주세요',
359
+ 'Links to other screens': '다른 화면의 대상',
360
+ // 질문
361
+ 'Question': '묻는 것',
362
+ 'What do you want to ask?': '무엇을 물을까요?',
363
+ 'Why': '이유',
364
+ 'Why it cannot be decided without asking': '스스로 정하기 어려운 이유',
365
+ 'Impact': '달라질 범위',
366
+ 'What changes depending on the answer': '답에 따라 달라질 범위',
367
+ 'Options (one per line)': '대안(한 줄에 하나)',
368
+ 'One option per line': '한 줄에 대안 하나',
369
+ 'Attach': '붙이기',
370
+ 'Please write the question': '묻는 것을 적어 주세요',
371
+ 'Fold to one line': '한 줄로 접기',
372
+ 'AI decided: {answer}': 'AI 가 정함: {answer}',
373
+ 'Answer: {answer}': '답: {answer}',
374
+ 'Why: {why}': '이유: {why}',
375
+ 'Impact: {impact}': '달라질 범위: {impact}',
376
+ 'Waiting branches: {list}': '기다리는 가지: {list}',
377
+ 'none': '없음',
378
+ 'Asked again because: {reason}': '다시 묻는 까닭: {reason}',
379
+ 'AI recommends': 'AI 추천',
380
+ 'Chosen': '고름',
381
+ 'Choose this': '이걸로',
382
+ 'Switch to this': '이걸로 바꾸기',
383
+ 'Left to AI. When AI chooses, it shows here.': 'AI 에게 맡겼습니다. AI 가 고르면 여기 적힙니다.',
384
+ 'AI decided, you left it to AI: {answer}': 'AI 가 정함, 사람이 맡김: {answer}',
385
+ 'Your own direction or words to add': '직접 적는 방향이나 덧붙일 말',
386
+ 'Answer': '답하기',
387
+ 'What changed?': '무엇이 달라졌나요?',
388
+ 'Reason to ask again': '다시 묻는 까닭',
389
+ 'Ask again': '다시 묻기',
390
+ 'Option': '대안',
391
+ 'Option name': '대안의 이름',
392
+ 'option|Details': '설명',
393
+ 'Difference and amount of work': '차이와 작업 범위',
394
+ 'Write your own answer': '직접 적어 답하기',
395
+ 'Edit answer': '답 고치기',
396
+ 'Please write something': '적을 말을 써 주세요',
397
+ 'AI may decide': 'AI 가 정해도 됨',
398
+ 'Leave this one for AI to decide': '이 정도는 AI 가 정하게 맡깁니다',
399
+ 'Please write what changed': '무엇이 달라졌는지 적어 주세요',
400
+ '+ Option': '+ 대안',
401
+ 'Please write the option name': '대안의 이름을 적어 주세요',
402
+ // 바뀐 표시와 부딪힘
403
+ 'New': '새로 생김',
404
+ 'Edited': '고침',
405
+ 'Moved': '옮김',
406
+ 'Removed': '지움',
407
+ 'Conflict': '부딪힘',
408
+ 'Show before the change': '바뀌기 전 보기',
409
+ 'Before the change: ': '바뀌기 전: ',
410
+ 'Dependency: first {first}, then {then}': '의존: 먼저 {first}, 그다음 {then}',
411
+ '{text} (answered)': '{text} (답 있음)',
412
+ 'The same place was changed in two different ways': '같은 곳을 다르게 바꿨습니다',
413
+ 'Something this points to was removed': '가리키는 것이 지워졌습니다',
414
+ ' (resolves {count} together)': ' ({count}건을 함께 풉니다)',
415
+ 'Mine': '내 것',
416
+ 'Theirs': '상대 것',
417
+ 'the other participant': '상대',
418
+ 'theirs': '상대',
419
+ 'If you pick mine, this whole change by {name} is cancelled: {summary}': '내 것을 고르면 {name} 의 이 변경이 통째로 취소됩니다: {summary}',
420
+ 'If you pick theirs, this whole change of yours is cancelled: {summary}': '상대 것을 고르면 내 이 변경이 통째로 취소됩니다: {summary}',
421
+ 'Keep mine': '내 것으로',
422
+ 'Keep {name}': '{name} 것으로',
423
+ 'Conflicts': '부딪힌 것',
424
+ 'Withdrawn changes: {list}': '철회한 변경: {list}',
425
+ // 바뀐 기록 칸
426
+ 'Change history': '바뀐 기록',
427
+ 'Nothing yet.': '아직 없습니다.',
428
+ 'branch': '가지',
429
+ 'branches': '가지',
430
+ 'question': '질문',
431
+ 'questions': '질문',
432
+ 'option': '대안',
433
+ 'options': '대안',
434
+ 'dependency': '의존',
435
+ 'dependencies': '의존',
436
+ 'result': '결과',
437
+ 'results': '결과',
438
+ 'link': '다른 화면의 대상',
439
+ 'links': '다른 화면의 대상',
440
+ 'screen': '화면',
441
+ 'screens': '화면',
442
+ 'added': '더함',
443
+ 'edited': '고침',
444
+ 'moved': '옮김',
445
+ 'removed': '지움',
446
+ '{count} {kind} {verb}': '{kind} {count}개 {verb}',
447
+ 'Read the other {count} with read_history.': '그 밖에 {count}개는 read_history 로 읽습니다.',
448
+ 'by you': '내가 함',
449
+ 'by AI': 'AI 가 함',
450
+ 'Not settled': '확정 전',
451
+ 'Show {count} older': '이전 기록 {count}개 더 보기',
452
+ 'Show older': '이전 기록 더 보기',
453
+ 'Removed by AI': 'AI 가 지운 것',
454
+ 'Hidden notices': '숨긴 알림',
455
+ 'Show above the tree': '트리 위에 보이기',
456
+ 'Notices': '알림',
457
+ 'Hide': '숨기기',
458
+ 'Hide notices. A count stays on the change history icon, and you can see them again in that panel': '알림 숨기기. 바뀐 기록 아이콘에 수가 남고, 그 칸에서 다시 봅니다',
459
+ 'Things AI changed that are not settled yet carry a mark. Your next action settles everything you can see now. A dot next to a branch means something changed in its folded part or details; hover over it for an explanation.': 'AI 가 바꾸었고 아직 확정되지 않은 것에 표시가 붙습니다. 다음 조작을 하면 지금 보이는 데까지 확정됩니다. 가지 옆의 점은 접힌 곳이나 자세히 보기에 바뀐 것이 있다는 뜻이고, 마우스를 올리면 설명이 보입니다.',
460
+ // 읽기만 하는 화면
461
+ 'This is not the screen being edited, so it is read-only. To edit, switch to this screen from the bar at the top.': '지금 편집하는 화면이 아니라 읽기만 합니다. 고치려면 위쪽 줄에서 이 화면으로 옮깁니다.',
462
+ 'Read-only for now.': '지금은 읽기만 합니다.',
463
+ // 고른 것과 AI 에게 말하는 칸
464
+ 'What to tell the AI about the selection': '고른 것에 대해 AI 에게 할 말',
465
+ 'Tell the AI about the selection': '고른 것에 대해 AI 에게 말하기',
466
+ 'Send the selection and your words to the AI': '고른 것과 적은 말을 AI 에게 보냅니다',
467
+ 'Send': '보내기',
468
+ 'Clear the selection': '고른 것 풀기',
469
+ '{count} selected': '{count}개 고름',
470
+ 'Selected: {name}': '고른 것: {name}',
471
+ '{count} items selected': '{count}개를 골랐습니다',
472
+ 'Could not send the selection': '고른 것을 보내지 못했습니다',
473
+ 'Sent selection {id} to the AI': '고른 것 {id} 를 AI 에게 보냈습니다',
474
+ };
475
+ // </ko-dictionary>
476
+
477
+ /** 화면 글. text 는 영어 원문이고 vars 의 값이 {이름} 위치에 들어간다. 한국어 화면에서 사전에 없으면 영어를 보이고 콘솔에 한 번 알린다. */
478
+ const koMissing = new Set();
479
+ function tr(text, vars) {
480
+ let out = text;
481
+ if (LANG === 'ko') {
482
+ if (Object.prototype.hasOwnProperty.call(KO, text)) out = KO[text];
483
+ else if (!koMissing.has(text)) { koMissing.add(text); console.warn(`aic.plan: no Korean text for "${text}"`); }
484
+ }
485
+ if (!vars) return out;
486
+ return out.replace(/\{(\w+)\}/g, (whole, name) => (Object.prototype.hasOwnProperty.call(vars, name) ? String(vars[name]) : whole));
487
+ }
488
+ /** 같은 영어가 두 뜻일 때. 사전에서 "문맥|원문" 을 먼저 찾는다(예: 메뉴의 Details 와 대안 칸의 Details). */
489
+ function trIn(context, text, vars) {
490
+ const key = `${context}|${text}`;
491
+ return LANG === 'ko' && Object.prototype.hasOwnProperty.call(KO, key) ? tr(key, vars) : tr(text, vars);
492
+ }
493
+
494
+ function call(method, params) {
495
+ return new Promise((resolve, reject) => {
496
+ const id = nextId++;
497
+ waiting.set(id, { resolve, reject });
498
+ parent.postMessage({ aic: 1, id, method, params }, '*');
499
+ });
500
+ }
501
+
502
+ window.addEventListener('message', (e) => {
503
+ if (e.source !== parent) return;
504
+ const d = e.data;
505
+ if (typeof d !== 'object' || d === null || d.aic !== 1) return;
506
+ if (d.event === 'change') {
507
+ refresh(typeof d.rev === 'string' ? d.rev : null);
508
+ return;
509
+ }
510
+ if (d.event === 'focus') {
511
+ focused = new Set(Array.isArray(d.targets) ? d.targets.filter((x) => typeof x === 'string') : []);
512
+ if (concept) for (const id of focused) { openPathTo(id); openQs.add(id); }
513
+ render();
514
+ return;
515
+ }
516
+ const w = waiting.get(d.id);
517
+ if (!w) return;
518
+ waiting.delete(d.id);
519
+ if (d.error) w.reject(new Error(d.error));
520
+ else w.resolve(d.result);
521
+ });
522
+
523
+ let inflight = null;
524
+ let queued = null;
525
+ // 읽는 동안 온 알림의 revision 들. 이름 없이 부른 것(null)이 하나라도 있으면 반드시 다시 읽는다
526
+ let queuedRevs = null;
527
+ function refresh(rev = null) {
528
+ if (inflight) {
529
+ (queuedRevs ??= []).push(rev);
530
+ queued ??= inflight.then(() => {
531
+ queued = null;
532
+ const revs = queuedRevs ?? [];
533
+ queuedRevs = null;
534
+ // 내 조작의 알림처럼 방금 읽은 기준 안에 든 revision 의 알림뿐이면 같은 것을 다시 읽지 않는다
535
+ if (revs.length > 0 && concept && revs.every((r) => r !== null && seq(r) <= seq(concept.base))) return undefined;
536
+ return refresh();
537
+ });
538
+ return queued;
539
+ }
540
+ inflight = (async () => {
541
+ try {
542
+ const [c, changes] = await Promise.all([call('readConcept'), call('readChanges', changesParams())]);
543
+ errorEl.hidden = true;
544
+ concept = c;
545
+ feed = changes.newChanges ?? [];
546
+ drawPending = typeof c.renderToken === 'string';
547
+ render();
548
+ } catch (err) {
549
+ errorEl.textContent = err.message;
550
+ errorEl.hidden = false;
551
+ }
552
+ })().finally(() => {
553
+ inflight = null;
554
+ });
555
+ return inflight;
556
+ }
557
+
558
+ let toastTimer = null;
559
+ function toast(text, bad = false) {
560
+ toastEl.textContent = text;
561
+ toastEl.classList.toggle('bad', bad);
562
+ toastEl.hidden = false;
563
+ clearTimeout(toastTimer);
564
+ toastTimer = setTimeout(() => { toastEl.hidden = true; }, bad ? 7000 : 3500);
565
+ }
566
+
567
+ let lastOwn = null;
568
+ const seq = (rev) => Number(String(rev).slice(1));
569
+ async function send(steps, opts = {}) {
570
+ let base = opts.base ?? concept.base;
571
+ if (lastOwn && seq(lastOwn) > seq(base)) base = lastOwn;
572
+ const req = { base, steps, ...(opts.resolves ? { resolves: opts.resolves } : {}), ...(opts.take ? { take: opts.take } : {}) };
573
+ let res;
574
+ try {
575
+ res = await call('applyOperation', req);
576
+ } catch (err) {
577
+ toast(err.message, true);
578
+ return null;
579
+ }
580
+ if (!res.ok) {
581
+ toast(res.summary ?? res.error, true);
582
+ await refresh();
583
+ return null;
584
+ }
585
+ lastOwn = res.revision;
586
+ if (res.withdrawn?.length) toast(tr('Withdrawn changes: {list}', { list: res.withdrawn.join(', ') }));
587
+ // 내 조작이 담긴 상태면 된다. 알림을 먼저 받아 이미 읽고 있는 것이 그 revision 을 담으면 한 번 더 읽지 않는다
588
+ await refresh(res.revision);
589
+ return res;
590
+ }
591
+
592
+ function el(tag, props, ...children) {
593
+ const n = document.createElement(tag);
594
+ for (const [k, v] of Object.entries(props ?? {})) {
595
+ if (k === 'class') n.className = v;
596
+ else if (k === 'on') for (const [ev, fn] of Object.entries(v)) n.addEventListener(ev, fn);
597
+ else if (k === 'value') n.value = v;
598
+ else if (v !== false && v !== null && v !== undefined) n.setAttribute(k, v === true ? '' : v);
599
+ }
600
+ for (const c of children.flat(Infinity)) {
601
+ if (c === null || c === undefined || c === false) continue;
602
+ n.append(c instanceof Node ? c : String(c));
603
+ }
604
+ return n;
605
+ }
606
+ const btn = (label, onClick, cls = 'btn', extra = {}) => el('button', { type: 'button', class: cls, on: { click: onClick }, ...extra }, label);
607
+
608
+ function deleteButton(key, what, onConfirm, opts = {}) {
609
+ const on = armed.get(key);
610
+ return el('button', {
611
+ type: 'button', class: `${opts.cls ?? 'icon'}${on ? ' armed' : ''}`, 'aria-label': tr('Remove {what}', { what }), title: tr('Remove {what}', { what }), ...(opts.extra ?? {}),
612
+ on: { click: (ev) => {
613
+ ev?.stopPropagation?.();
614
+ if (armed.get(key)) { armed.delete(key); onConfirm(); return; }
615
+ armed.set(key, true);
616
+ setTimeout(() => { if (armed.delete(key)) render(); }, 3000);
617
+ render();
618
+ } },
619
+ }, on ? tr('Remove?') : (opts.label ?? '×'));
620
+ }
621
+
622
+ // 선으로 그린 아이콘(코어 화면과 같은 모양). 정해 둔 글만 넣으므로 innerHTML 로 넣는다
623
+ const ICONS = {
624
+ expand: '<path d="M4 3.5l4 4 4-4"/><path d="M4 8.5l4 4 4-4"/>',
625
+ collapse: '<path d="M4 7.5l4-4 4 4"/><path d="M4 12.5l4-4 4 4"/>',
626
+ help: '<circle cx="8" cy="8" r="6.5"/><path d="M6.2 6.2a1.9 1.9 0 1 1 2.6 1.8c-.5.2-.8.6-.8 1.1v.5"/><path d="M8 11.7v.1"/>',
627
+ history: '<path d="M2.6 8a5.4 5.4 0 1 0 1.6-3.8"/><path d="M2.5 2.4v2.6h2.6"/><path d="M8 5v3.2l2.1 1.4"/>',
628
+ };
629
+ function iconBtn(name, label, onClick, extra = {}, count = 0, dot = false) {
630
+ const b = el('button', { type: 'button', class: 'icon-btn', 'aria-label': label, title: label, on: { click: onClick }, ...extra });
631
+ b.innerHTML = `<svg viewBox="0 0 16 16" aria-hidden="true">${ICONS[name]}</svg>`;
632
+ if (count) b.append(el('span', { class: 'count', 'aria-hidden': 'true' }, count > 99 ? '99+' : count));
633
+ else if (dot) b.append(el('span', { class: 'dot', 'aria-hidden': 'true' }));
634
+ return b;
635
+ }
636
+
637
+ // 표의 글은 읽을 때마다 번역 함수를 지나게 getter 로 둔다(언어는 capabilities 가 온 뒤에 정해진다)
638
+ const STATUS = { get todo() { return tr('To do'); }, get doing() { return tr('In progress'); }, get done() { return tr('Done'); } };
639
+ const CHECK = { get unchecked() { return tr('Not checked'); }, get meets() { return tr('Meets'); }, get partial() { return tr('Partly'); }, get differs() { return tr('Differs'); } };
640
+ const ACTION = { get add() { return tr('New'); }, get update() { return tr('Edited'); }, get move() { return tr('Moved'); }, get remove() { return tr('Removed'); } };
641
+ // 바뀐 기록의 요약. 종류의 이름(하나와 여럿), 한 일의 말, 보이는 차례(중요한 것부터)
642
+ const FEED_KIND = {
643
+ get task() { return tr('branch'); }, get question() { return tr('question'); }, get option() { return tr('option'); }, get dep() { return tr('dependency'); },
644
+ get result() { return tr('result'); }, get link() { return tr('link'); }, get instance() { return tr('screen'); },
645
+ };
646
+ const FEED_KINDS = {
647
+ get task() { return tr('branches'); }, get question() { return tr('questions'); }, get option() { return tr('options'); }, get dep() { return tr('dependencies'); },
648
+ get result() { return tr('results'); }, get link() { return tr('links'); }, get instance() { return tr('screens'); },
649
+ };
650
+ const FEED_VERB = { get add() { return tr('added'); }, get update() { return tr('edited'); }, get move() { return tr('moved'); }, get remove() { return tr('removed'); } };
651
+ const FEED_ORDER = ['task', 'question', 'option', 'result', 'dep', 'link', 'instance'];
652
+ const FEED_PAGE = 10; // 처음에 보이는 기록 수와, 더 보기 한 번에 늘어나는 수
653
+ const FEED_DETAIL_MAX = 30; // 펼쳤을 때 하나씩 보이는 바뀐 것의 수
654
+ const openFeed = new Set(); // 펼친 기록의 revision. 화면 상태라 저장하지 않는다
655
+ let feedShown = FEED_PAGE;
656
+ // 바뀐 기록은 보이는 만큼만 읽는다. 기록 한 줄에 revision 이 둘쯤 들므로 보이는 줄 수의 세 배에 여유를 더한 만큼 앞에서부터 받는다.
657
+ // 처음 읽을 때는 기준을 모르니 전부 읽는다. feedFrom 이 있으면 그보다 앞의 기록은 아직 읽지 않은 것이다.
658
+ let feedFrom = null;
659
+ const changesParams = () => {
660
+ const from = concept?.base ? seq(concept.base) - (feedShown * 3 + 20) : 0;
661
+ feedFrom = from >= 1 ? `h${from}` : null;
662
+ return feedFrom ? { since: feedFrom } : {};
663
+ };
664
+
665
+ /** 읽은 JSON 을 찾기 쉬운 모양으로 */
666
+ function model() {
667
+ const b = concept.withOthers ?? concept.body;
668
+ const m = {
669
+ root: b.root,
670
+ task: new Map(b.tasks.map((t) => [t.id, t])),
671
+ kids: new Map(),
672
+ questions: new Map(),
673
+ options: new Map(),
674
+ option: new Map(b.options.map((o) => [o.id, o])),
675
+ question: new Map(b.questions.map((q) => [q.id, q])),
676
+ results: new Map(),
677
+ links: new Map(),
678
+ deps: b.deps,
679
+ };
680
+ const push = (map, k, v) => { if (!map.has(k)) map.set(k, []); map.get(k).push(v); };
681
+ for (const t of b.tasks) if (t.parent !== null) push(m.kids, t.parent, t);
682
+ for (const q of b.questions) push(m.questions, q.task, q);
683
+ for (const o of b.options) push(m.options, o.question, o);
684
+ for (const r of b.results) push(m.results, r.task, r);
685
+ for (const l of b.links) push(m.links, l.task, l);
686
+ return m;
687
+ }
688
+
689
+ const isOpenQ = (q) => q.answer === null;
690
+ const isAiTurn = (q) => q.answer !== null && q.answer.delegated && q.answer.choice === null && q.answer.text === '';
691
+ function waitingOf(m, id) {
692
+ const qs = [...m.question.values()].filter((q) => q.blocks.includes(id));
693
+ return { person: qs.filter(isOpenQ), ai: qs.filter(isAiTurn) };
694
+ }
695
+ function ancestorsOf(m, id) {
696
+ const out = [];
697
+ const seen = new Set([id]);
698
+ let p = m.task.get(id)?.parent ?? null;
699
+ while (p !== null && m.task.has(p) && !seen.has(p)) { out.unshift(p); seen.add(p); p = m.task.get(p).parent; }
700
+ return out;
701
+ }
702
+ function subtreeOf(m, id) {
703
+ const out = [id];
704
+ for (let i = 0; i < out.length; i += 1) for (const k of m.kids.get(out[i]) ?? []) if (!out.includes(k.id)) out.push(k.id);
705
+ return out;
706
+ }
707
+ /** record 가 트리의 어느 가지에 놓이는가 */
708
+ function taskOfRecord(m, id) {
709
+ if (m.task.has(id)) return id;
710
+ if (m.question.has(id)) return m.question.get(id).task;
711
+ if (m.option.has(id)) return m.question.get(m.option.get(id).question)?.task ?? null;
712
+ const d = m.deps.find((x) => x.id === id);
713
+ if (d) return d.from;
714
+ for (const [t, rs] of [...m.results, ...m.links]) if (rs.some((r) => r.id === id)) return t;
715
+ return null;
716
+ }
717
+ function openPathTo(id) {
718
+ const m = model();
719
+ const t = taskOfRecord(m, id);
720
+ if (!t) return;
721
+ for (const a of ancestorsOf(m, t)) expanded.add(a);
722
+ if (!m.task.has(id)) expanded.add(t);
723
+ }
724
+
725
+ /** 처음 보는 가지만 펼칠지 정한다(9.6절). 뿌리 아래 첫 단계, 하는 중인 가지와 답을 기다리는 질문까지의 경로 */
726
+ function autoExpand(m, marks) {
727
+ for (const t of m.task.values()) {
728
+ if (seenTasks.has(t.id)) continue;
729
+ seenTasks.add(t.id);
730
+ if (t.parent === null) expanded.add(t.id);
731
+ const w = waitingOf(m, t.id);
732
+ const hasQ = (m.questions.get(t.id) ?? []).some((q) => isOpenQ(q) || isAiTurn(q));
733
+ if (t.status === 'doing' || w.person.length || hasQ) for (const a of ancestorsOf(m, t.id)) expanded.add(a);
734
+ if (hasQ) expanded.add(t.id);
735
+ }
736
+ // 다른 참여자가 바꾼 곳은 펼치지 않는다. 접힌 가지 옆의 "접힌 곳이 바뀜" 표시가 그것을 그린다(9.6절).
737
+ // AI 가 처음 펼친 계획을 모두 열면 첫 단계만 보인다는 처음 모양이 무너진다.
738
+ void marks;
739
+ }
740
+
741
+ function computeMarks() {
742
+ const marks = new Map();
743
+ const removed = [];
744
+ const c = concept;
745
+ const latest = c.othersPending.length ? c.othersPending[c.othersPending.length - 1].revision : null;
746
+ for (const p of c.othersPending) {
747
+ for (const ch of p.changes) {
748
+ const prev = marks.get(ch.record);
749
+ marks.set(ch.record, {
750
+ action: prev && prev.action === 'add' && ch.after !== null ? 'add' : ch.action,
751
+ before: prev ? prev.before : ch.before,
752
+ type: ch.type, owner: ch.owner, revision: p.revision, recent: p.revision === latest,
753
+ });
754
+ }
755
+ }
756
+ const held = new Set(c.conflicts.map((x) => x.record));
757
+ for (const id of held) marks.delete(id);
758
+ for (const [id, mk] of marks) {
759
+ if (mk.action === 'remove' && mk.before !== null) removed.push({ id, ...mk });
760
+ if (mk.action === 'remove') marks.delete(id);
761
+ }
762
+ return { marks, removed, held };
763
+ }
764
+
765
+ /** 의존을 조사 없이 적는다. 가지가 있으면 이름을, 없으면 id 만(9.6절). */
766
+ function depText(d) {
767
+ const b = concept.withOthers ?? concept.body;
768
+ const name = (id) => { const t = b.tasks.find((x) => x.id === id); return t ? `(${id}) ${t.title}` : `(${id})`; };
769
+ return tr('Dependency: first {first}, then {then}', { first: name(d.to), then: name(d.from) });
770
+ }
771
+
772
+ function describeContent(content) {
773
+ if (content === null || content === undefined) return tr('Removed');
774
+ if (typeof content === 'object') {
775
+ if (typeof content.title === 'string' && 'status' in content) return `${content.title} [${STATUS[content.status] ?? content.status}]`;
776
+ if (typeof content.text === 'string' && 'blocks' in content) return content.answer ? tr('{text} (answered)', { text: content.text }) : content.text;
777
+ if (typeof content.title === 'string') return content.title;
778
+ if (typeof content.text === 'string') return content.text;
779
+ if ('from' in content && 'to' in content) return depText(content);
780
+ if ('record' in content) return `${content.record} ${content.label ?? ''}`;
781
+ }
782
+ return JSON.stringify(content);
783
+ }
784
+
785
+ function conflictCard(c) {
786
+ const me = concept.me;
787
+ const group = [c, ...concept.conflicts.filter((x) => x !== c && x.sides.some((s) => c.sides.some((y) => y.revision === s.revision)))];
788
+ const ids = group.map((x) => x.id);
789
+ const mine = c.sides.find((s) => s.participant === me);
790
+ const theirs = c.sides.find((s) => s.participant !== me);
791
+ const summaryOf = (rev) => [...concept.othersPending, ...concept.myPending].find((p) => p.revision === rev)?.summary;
792
+ const theirSummary = theirs ? summaryOf(theirs.revision) : null;
793
+ const mySummary = mine ? summaryOf(mine.revision) : null;
794
+ return el('div', { class: 'conflict', 'data-conflict': c.id },
795
+ el('h3', {}, c.reason === 'same_record' ? tr('The same place was changed in two different ways') : tr('Something this points to was removed'), group.length > 1 ? tr(' (resolves {count} together)', { count: group.length }) : ''),
796
+ el('div', { class: 'sides' }, [mine, theirs].filter(Boolean).map((s) =>
797
+ el('div', { class: 'side' }, el('b', {}, s === mine ? tr('Mine') : (s.name ?? tr('Theirs'))), describeContent(s.content)))),
798
+ theirSummary ? el('p', { class: 'warn' }, tr('If you pick mine, this whole change by {name} is cancelled: {summary}', { name: theirs.name ?? tr('the other participant'), summary: theirSummary })) : null,
799
+ mySummary ? el('p', { class: 'warn' }, tr('If you pick theirs, this whole change of yours is cancelled: {summary}', { summary: mySummary })) : null,
800
+ el('div', { class: 'actions' },
801
+ btn(tr('Keep mine'), () => send([], { resolves: ids, take: 'mine' }), 'btn primary'),
802
+ theirs ? btn(tr('Keep {name}', { name: theirs.name ?? tr('theirs') }), () => send([], { resolves: ids, take: 'theirs' })) : null),
803
+ );
804
+ }
805
+
806
+ // 쓰는 칸. 칸마다 data-field 를 달아 다시 그려도 글과 커서를 잃지 않는다.
807
+ function startEdit(e) {
808
+ armed.clear();
809
+ editor = { base: concept.base, values: {}, ...e };
810
+ render();
811
+ }
812
+ function closeEditor() {
813
+ editor = null;
814
+ render();
815
+ }
816
+ async function saveEditor() {
817
+ const e = editor;
818
+ if (!e || committing) return;
819
+ const steps = e.build(e.values);
820
+ if (steps === null) return; // build 가 까닭을 알렸다
821
+ if (!steps.length) { closeEditor(); return; }
822
+ committing = true;
823
+ const res = await send(steps, { base: e.base });
824
+ committing = false;
825
+ if (editor === e) {
826
+ if (res) editor = null;
827
+ else e.base = concept.base;
828
+ }
829
+ render();
830
+ }
831
+
832
+ function input(name, placeholder, opts = {}) {
833
+ const e = editor;
834
+ const tag = opts.rows ? 'textarea' : 'input';
835
+ const box = el(tag, {
836
+ ...(opts.rows ? { rows: opts.rows } : { type: 'text' }),
837
+ placeholder, 'aria-label': opts.label ?? placeholder, 'data-field': name, value: e.values[name] ?? '',
838
+ on: {
839
+ input: (ev) => { e.values[name] = ev.target.value; },
840
+ compositionstart: () => { composing = true; },
841
+ compositionend: (ev) => { composing = false; e.values[name] = ev.target.value; if (renderWanted) render(); },
842
+ keydown: (ev) => {
843
+ if (ev.isComposing) return;
844
+ if (ev.key === 'Escape') { ev.preventDefault(); closeEditor(); }
845
+ if (ev.key === 'Enter' && (!opts.rows || !ev.shiftKey) && !(opts.rows && opts.multiline)) { ev.preventDefault(); e.values[name] = ev.target.value; saveEditor(); }
846
+ },
847
+ },
848
+ });
849
+ return opts.label ? el('label', {}, el('span', {}, opts.label), box) : box;
850
+ }
851
+ const saveRow = (label = tr('Save')) => el('div', { class: 'actions' }, btn(label, saveEditor, 'btn primary'), btn(tr('Cancel'), closeEditor), el('span', { class: 'hint' }, tr('Enter to save, Esc to cancel')));
852
+
853
+ function render() {
854
+ if (!concept) return;
855
+ if (composing || dragging || committing) { renderWanted = true; return; }
856
+ renderWanted = false;
857
+ const active = document.activeElement;
858
+ const field = active?.dataset?.field;
859
+ const quickFocus = active === quickSaid ? [quickSaid.selectionStart, quickSaid.selectionEnd] : null;
860
+ const sel = field && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
861
+
862
+ const c = concept;
863
+ const m = model();
864
+ const { marks, removed, held } = computeMarks();
865
+ autoExpand(m, marks);
866
+ const notEditing = Boolean(c.editing && c.instance && c.editing.id !== c.instance);
867
+ const readOnly = notEditing || !canEdit;
868
+ lastReadOnly = readOnly;
869
+ for (const id of picked) if (!m.task.has(id) && !m.question.has(id)) picked.delete(id);
870
+ if (!canPick()) picked.clear();
871
+ const pickedClass = (id) => (picked.has(id) ? ' picked' : '');
872
+ const conflictsOn = (id) => c.conflicts.filter((x) => x.record === id);
873
+ const markClass = (id) => {
874
+ const mk = marks.get(id);
875
+ return mk ? ` m-${mk.action}${mk.recent ? '' : ' old'}` : '';
876
+ };
877
+ const tag = (id) => {
878
+ if (held.has(id)) return el('span', { class: 'tag remove' }, tr('Conflict'));
879
+ const mk = marks.get(id);
880
+ return mk ? el('span', { class: `tag ${mk.action}` }, ACTION[mk.action]) : null;
881
+ };
882
+ const beforeToggle = (id, show) => {
883
+ const mk = marks.get(id);
884
+ if (!(mk && mk.action === 'update' && mk.before)) return tag(id);
885
+ return el('button', { type: 'button', class: 'tag update', 'aria-expanded': openBefore.has(id) ? 'true' : 'false', title: tr('Show before the change'), on: { click: (ev) => {
886
+ ev.stopPropagation();
887
+ if (openBefore.has(id)) openBefore.delete(id); else openBefore.add(id);
888
+ render();
889
+ } } }, ACTION.update);
890
+ };
891
+ const beforeView = (id) => {
892
+ const mk = marks.get(id);
893
+ return mk && mk.action === 'update' && mk.before && openBefore.has(id) ? el('div', { class: 'before' }, tr('Before the change: '), describeContent(mk.before)) : null;
894
+ };
895
+ const tlabel = (id) => `${m.task.get(id)?.title ?? id}`;
896
+ // 대안 이름과 덧붙인 말을 문장 부호를 더해 잇지 않는다
897
+ const answerBody = (a) => [a.choice ? m.option.get(a.choice)?.title : '', a.text ? `"${a.text}"` : ''].filter(Boolean).join(', ');
898
+
899
+ // 질문 카드
900
+ const questionView = (q) => {
901
+ const opts = m.options.get(q.id) ?? [];
902
+ const a = q.answer;
903
+ const cls = a === null ? '' : isAiTurn(q) ? ' delegated' : ' answered';
904
+ const key = (k) => `${k}-${q.id}`;
905
+ const answering = editor?.key === key('answer');
906
+ const reopening = editor?.key === key('reopen');
907
+ const addingOpt = editor?.key === key('opt');
908
+ const choose = (oid) => send([{ op: 'question.answer', input: { question: q.id, choice: oid } }]);
909
+ // 답한 질문은 질문과 고른 답 한 줄로 접는다. 고치는 중이거나 부딪힌 것이 있으면 펼친다
910
+ const settled = a !== null && !isAiTurn(q);
911
+ const busy = answering || reopening || addingOpt || conflictsOn(q.id).length > 0;
912
+ if (settled && !busy && !openQs.has(q.id)) {
913
+ return el('div', { class: `question compact${cls}${markClass(q.id)}${pickedClass(q.id)}`, 'data-question': q.id, 'data-target': q.id, on: { click: (ev) => pickFrom(ev, q.id) } },
914
+ el('button', { type: 'button', class: 'q-line', 'aria-expanded': 'false', title: tr('Expand'), on: { click: () => { openQs.add(q.id); render(); } } },
915
+ el('span', { class: 'q-fold', 'aria-hidden': 'true' }, '▸'),
916
+ el('span', { class: 'q-text' }, q.text),
917
+ el('span', { class: 'q-answer' }, a.delegated ? tr('AI decided: {answer}', { answer: answerBody(a) }) : tr('Answer: {answer}', { answer: answerBody(a) }))),
918
+ tag(q.id));
919
+ }
920
+ return el('div', { class: `question${cls}${markClass(q.id)}${pickedClass(q.id)}`, 'data-question': q.id, 'data-target': q.id, on: { click: (ev) => pickFrom(ev, q.id) } },
921
+ el('div', { class: 'item' },
922
+ settled ? el('button', { type: 'button', class: 'q-fold', 'aria-expanded': 'true', 'aria-label': tr('Fold to one line'), title: tr('Fold to one line'), on: { click: () => { openQs.delete(q.id); render(); } } }, '▾') : null,
923
+ el('span', { class: 'q-text' }, q.text), beforeToggle(q.id),
924
+ a === null ? el('span', { class: 'badge ask' }, tr('Waiting for answer')) : isAiTurn(q) ? el('span', { class: 'badge ai' }, tr('AI to decide')) : null,
925
+ readOnly ? null : el('span', { class: 'mini', style: 'margin-left:auto' }, deleteButton(key('del'), tr('question'), () => send([{ op: 'question.remove', input: { question: q.id } }])))),
926
+ q.why ? el('div', { class: 'q-meta' }, tr('Why: {why}', { why: q.why })) : null,
927
+ q.impact ? el('div', { class: 'q-meta' }, tr('Impact: {impact}', { impact: q.impact })) : null,
928
+ a === null || isAiTurn(q) ? el('div', { class: 'q-meta' }, tr('Waiting branches: {list}', { list: q.blocks.length ? q.blocks.map(tlabel).join(', ') : tr('none') })) : null,
929
+ q.reopened && a === null ? el('div', { class: 'q-meta' }, tr('Asked again because: {reason}', { reason: q.reopened })) : null,
930
+ beforeView(q.id),
931
+ opts.length ? el('div', { class: 'options' }, opts.map((o) => el('div', { class: `option has-mini${a?.choice === o.id ? ' chosen' : ''}${markClass(o.id)}`, 'data-option': o.id },
932
+ el('div', { class: 'o-body' }, o.title,
933
+ q.recommend === o.id ? el('span', { class: 'badge dep', style: 'margin-left:6px' }, tr('AI recommends')) : null,
934
+ a?.choice === o.id ? el('span', { class: 'badge dep', style: 'margin-left:6px' }, tr('Chosen')) : null, tag(o.id),
935
+ o.detail ? el('small', {}, o.detail) : null),
936
+ readOnly ? null : el('span', { class: 'actions' },
937
+ a?.choice !== o.id ? btn(a === null || isAiTurn(q) ? tr('Choose this') : tr('Switch to this'), () => choose(o.id), a === null ? 'btn primary' : 'btn') : null,
938
+ a?.choice !== o.id ? el('span', { class: 'mini' }, deleteButton(key(`o${o.id}`), tr('option'), () => send([{ op: 'option.remove', input: { option: o.id } }]))) : null)))) : null,
939
+ a !== null ? el('div', { class: 'answer' },
940
+ a.delegated ? (isAiTurn(q) ? tr('Left to AI. When AI chooses, it shows here.') : tr('AI decided, you left it to AI: {answer}', { answer: answerBody(a) }))
941
+ : tr('Answer: {answer}', { answer: answerBody(a) })) : null,
942
+ conflictsOn(q.id).map(conflictCard),
943
+ readOnly ? null : answering
944
+ ? el('div', { class: 'form' }, input('text', tr('Your own direction or words to add'), { rows: 2 }), saveRow(tr('Answer')))
945
+ : reopening
946
+ ? el('div', { class: 'form' }, input('reason', tr('What changed?'), { label: tr('Reason to ask again') }), saveRow(tr('Ask again')))
947
+ : addingOpt
948
+ ? el('div', { class: 'form' }, input('title', tr('Option name'), { label: tr('Option') }), input('detail', tr('Difference and amount of work'), { label: trIn('option', 'Details') }), saveRow(tr('Add')))
949
+ : el('div', { class: 'q-actions' },
950
+ btn(a === null || isAiTurn(q) ? tr('Write your own answer') : tr('Edit answer'), () => startEdit({ key: key('answer'), values: { text: a?.text ?? '' }, build: (v) => {
951
+ const text = (v.text ?? '').trim();
952
+ if (!text) { toast(tr('Please write something'), true); return null; }
953
+ return [{ op: 'question.answer', input: { question: q.id, text, ...(a?.choice ? { choice: a.choice } : {}) } }];
954
+ } })),
955
+ a === null ? btn(tr('AI may decide'), () => send([{ op: 'question.answer', input: { question: q.id, delegated: true } }]), 'btn', { title: tr('Leave this one for AI to decide') }) : null,
956
+ a !== null ? btn(tr('Ask again'), () => startEdit({ key: key('reopen'), values: {}, build: (v) => {
957
+ const reason = (v.reason ?? '').trim();
958
+ if (!reason) { toast(tr('Please write what changed'), true); return null; }
959
+ return [{ op: 'question.reopen', input: { question: q.id, reason } }];
960
+ } })) : null,
961
+ btn(tr('+ Option'), () => startEdit({ key: key('opt'), values: {}, build: (v) => {
962
+ const title = (v.title ?? '').trim();
963
+ if (!title) { toast(tr('Please write the option name'), true); return null; }
964
+ return [{ op: 'option.add', input: { question: q.id, title, detail: (v.detail ?? '').trim() } }];
965
+ } }), 'icon')),
966
+ );
967
+ };
968
+
969
+ // 자세히: 이루려는 것, 조건, 방법, 의존, 결과, 다른 화면의 대상
970
+ const detailView = (t) => {
971
+ const key = (k) => `${k}-${t.id}`;
972
+ const fieldsEditing = editor?.key === key('fields');
973
+ const deps = m.deps.filter((d) => d.from === t.id);
974
+ const waitedBy = m.deps.filter((d) => d.to === t.id);
975
+ const results = m.results.get(t.id) ?? [];
976
+ const links = m.links.get(t.id) ?? [];
977
+ const sub = new Set(subtreeOf(m, t.id));
978
+ const anc = new Set(ancestorsOf(m, t.id));
979
+ const depChoices = [...m.task.values()].filter((x) => !sub.has(x.id) && !anc.has(x.id) && !deps.some((d) => d.to === x.id));
980
+ return el('div', { class: 'detail', 'data-detail': t.id },
981
+ // 가지 번호는 줄에서 마우스를 올렸을 때만 보이므로, 터치 화면에서도 보이게 여기에 적는다
982
+ el('div', { class: 'q-meta' }, tr('Id {id}', { id: t.id })),
983
+ fieldsEditing
984
+ ? el('div', { class: 'form' },
985
+ input('aim', tr('What it should achieve'), { rows: 2, label: tr('Aim'), multiline: true }),
986
+ input('conditions', tr('Conditions to keep'), { rows: 2, label: tr('Conditions'), multiline: true }),
987
+ input('method', tr('Chosen method and a short reason'), { rows: 2, label: tr('Method'), multiline: true }),
988
+ el('div', { class: 'actions' }, btn(tr('Save'), saveEditor, 'btn primary'), btn(tr('Cancel'), closeEditor)))
989
+ : [
990
+ el('h3', {}, tr('Aim, conditions, method')),
991
+ t.aim ? el('div', { class: 'field' }, el('b', {}, tr('Aim')), el('span', {}, t.aim)) : null,
992
+ t.conditions ? el('div', { class: 'field' }, el('b', {}, tr('Conditions')), el('span', {}, t.conditions)) : null,
993
+ t.method ? el('div', { class: 'field' }, el('b', {}, tr('Method')), el('span', {}, t.method)) : null,
994
+ !t.aim && !t.conditions && !t.method ? el('div', { class: 'empty' }, tr('Nothing written yet.')) : null,
995
+ readOnly ? null : btn(tr('Edit'), () => startEdit({ key: key('fields'), values: { aim: t.aim, conditions: t.conditions, method: t.method }, build: (v) => {
996
+ const input = {};
997
+ for (const k of ['aim', 'conditions', 'method']) if ((v[k] ?? '').trim() !== t[k]) input[k] = (v[k] ?? '').trim();
998
+ return Object.keys(input).length ? [{ op: 'task.update', input: { task: t.id, ...input } }] : [];
999
+ } }), 'icon'),
1000
+ ],
1001
+ el('h3', {}, tr('Needs first')),
1002
+ deps.length ? deps.map((d) => el('div', { class: `item has-mini${markClass(d.id)}` }, `${tlabel(d.to)} [${STATUS[m.task.get(d.to)?.status] ?? ''}]`, d.note ? el('span', { class: 'q-meta' }, d.note) : null, tag(d.id),
1003
+ readOnly ? null : el('span', { class: 'mini' }, deleteButton(`dep-${d.id}`, tr('dependency'), () => send([{ op: 'dep.remove', input: { dep: d.id } }]))))) : el('div', { class: 'empty' }, tr('None')),
1004
+ waitedBy.length ? el('div', { class: 'q-meta' }, tr('Waited on by: {list}', { list: waitedBy.map((d) => tlabel(d.from)).join(', ') })) : null,
1005
+ (m.questions.get(t.id) ?? []).filter((q) => q.answer !== null && !isAiTurn(q) && q.blocks.length).map((q) =>
1006
+ el('div', { class: 'q-meta' }, tr('Waits for the answer to ({question}): {list}', { question: q.text, list: q.blocks.map(tlabel).join(', ') }))),
1007
+ readOnly || !depChoices.length ? null : el('select', { 'aria-label': tr('Choose a branch needed first'), on: { change: (ev) => {
1008
+ const v = ev.target.value;
1009
+ if (v) send([{ op: 'dep.add', input: { from: t.id, to: v } }]);
1010
+ } } }, el('option', { value: '' }, tr('+ Branch needed first')), depChoices.map((x) => el('option', { value: x.id }, x.title))),
1011
+ el('h3', {}, tr('Results')),
1012
+ results.length ? results.map((r) => el('div', { class: `item has-mini${markClass(r.id)}` },
1013
+ readOnly ? el('span', { class: `badge dep chk-${r.check}` }, CHECK[r.check])
1014
+ : el('select', { class: `status chk-${r.check}`, 'aria-label': tr('Whether the result matches the intent'), on: { change: (ev) => send([{ op: 'result.update', input: { result: r.id, check: ev.target.value } }]) } },
1015
+ Object.entries(CHECK).map(([k, v]) => el('option', { value: k, ...(r.check === k ? { selected: true } : {}) }, v))),
1016
+ el('span', {}, r.text), r.artifact ? el('span', { class: 'q-meta' }, tr('Output {id}', { id: r.artifact })) : null, r.note ? el('span', { class: 'q-meta' }, tr('Note: {note}', { note: r.note })) : null, tag(r.id),
1017
+ readOnly ? null : el('span', { class: 'mini' }, deleteButton(`res-${r.id}`, tr('result'), () => send([{ op: 'result.remove', input: { result: r.id } }]))))) : el('div', { class: 'empty' }, tr('None')),
1018
+ editor?.key === key('result')
1019
+ ? el('div', { class: 'form' }, input('text', tr('What was done and where is it?'), { label: tr('Result') }), input('note', tr('If it does not match, what differs'), { label: tr('Note') }), saveRow(tr('Add')))
1020
+ : readOnly ? null : btn(tr('+ Result'), () => startEdit({ key: key('result'), values: {}, build: (v) => {
1021
+ const text = (v.text ?? '').trim();
1022
+ if (!text) { toast(tr('Please write the result'), true); return null; }
1023
+ return [{ op: 'result.add', input: { task: t.id, text, note: (v.note ?? '').trim() } }];
1024
+ } }), 'icon'),
1025
+ links.length ? [el('h3', {}, tr('Links to other screens')), links.map((l) => el('div', { class: `item has-mini${markClass(l.id)}` },
1026
+ el('span', { class: 'badge dep' }, l.record), `${l.label}`, l.note ? el('span', { class: 'q-meta' }, l.note) : null, tag(l.id),
1027
+ readOnly ? null : el('span', { class: 'mini' }, deleteButton(`lk-${l.id}`, tr('link'), () => send([{ op: 'link.remove', input: { link: l.id } }])))))] : null,
1028
+ );
1029
+ };
1030
+
1031
+ // 가지 하나
1032
+ const taskView = (t, siblings) => {
1033
+ const kids = m.kids.get(t.id) ?? [];
1034
+ const qs = m.questions.get(t.id) ?? [];
1035
+ const isRoot = t.parent === null;
1036
+ const open = expanded.has(t.id);
1037
+ const w = waitingOf(m, t.id);
1038
+ const i = siblings.indexOf(t);
1039
+ const key = (k) => `${k}-${t.id}`;
1040
+ // 접힌 가지 안의 답을 기다리는 질문과 다른 참여자의 변경(5절)
1041
+ let hiddenAsk = 0;
1042
+ let hiddenChange = false; // 아래 가지나 거기 붙은 질문이 바뀜
1043
+ const detailChange = !details.has(t.id) && [...(m.results.get(t.id) ?? []), ...(m.links.get(t.id) ?? []), ...m.deps.filter((d) => d.from === t.id)].some((x) => marks.has(x.id));
1044
+ if (!open) {
1045
+ for (const id of subtreeOf(m, t.id)) {
1046
+ for (const q of m.questions.get(id) ?? []) if (isOpenQ(q) || isAiTurn(q)) hiddenAsk += 1;
1047
+ if (id !== t.id && marks.has(id)) hiddenChange = true;
1048
+ for (const q of m.questions.get(id) ?? []) if (marks.has(q.id) || (m.options.get(q.id) ?? []).some((o) => marks.has(o.id))) hiddenChange = true;
1049
+ // 아래 가지의 결과와 의존은 그 가지에 속한다
1050
+ if (id !== t.id) for (const x of [...(m.results.get(id) ?? []), ...(m.links.get(id) ?? []), ...m.deps.filter((d) => d.from === id)]) if (marks.has(x.id)) hiddenChange = true;
1051
+ }
1052
+ }
1053
+ const renaming = editor?.key === key('rename');
1054
+ const adding = editor?.key === key('child');
1055
+ const asking = editor?.key === key('ask');
1056
+ const canOpen = kids.length > 0 || qs.length > 0;
1057
+ const depsOut = m.deps.filter((d) => d.from === t.id);
1058
+ const menuOpen = menuFor === t.id;
1059
+ // 메뉴의 한 줄. 누르면 메뉴를 닫고 그 일을 한다
1060
+ const menuItem = (label, fn) => btn(label, (ev) => { ev?.stopPropagation?.(); menuFor = null; render(); fn(); render(); }, 'menu-item', { role: 'menuitem' });
1061
+ const row = el('div', {
1062
+ class: `task st-${t.status}${t.status === 'doing' ? ' doing' : ''}${focused.has(t.id) ? ' focus' : ''}${menuOpen ? ' menu-open' : ''}${markClass(t.id)}${pickedClass(t.id)}`,
1063
+ 'data-task': t.id, 'data-target': t.id,
1064
+ on: readOnly || isRoot ? { click: (ev) => pickFrom(ev, t.id) } : {
1065
+ click: (ev) => pickFrom(ev, t.id),
1066
+ dragover: (ev) => {
1067
+ if (dragging?.kind !== 'task' || subtreeOf(m, dragging.id).includes(t.id)) return;
1068
+ ev.preventDefault();
1069
+ const r = ev.currentTarget.getBoundingClientRect();
1070
+ const y = (ev.clientY - r.top) / r.height;
1071
+ clearDrop();
1072
+ ev.currentTarget.classList.add(y < 0.25 ? 'drop-before' : y > 0.75 ? 'drop-after' : 'drop-in');
1073
+ },
1074
+ dragleave: (ev) => ev.currentTarget.classList.remove('drop-before', 'drop-after', 'drop-in'),
1075
+ drop: (ev) => {
1076
+ const d = dragging;
1077
+ if (d?.kind !== 'task') return;
1078
+ ev.preventDefault();
1079
+ const cl = ev.currentTarget.classList;
1080
+ const where = cl.contains('drop-in') ? 'in' : cl.contains('drop-before') ? 'before' : 'after';
1081
+ endDrag();
1082
+ if (where === 'in') {
1083
+ expanded.add(t.id);
1084
+ send([{ op: 'task.move', input: { task: d.id, parent: t.id } }]);
1085
+ return;
1086
+ }
1087
+ const others = siblings.filter((x) => x.id !== d.id);
1088
+ const at = others.findIndex((x) => x.id === t.id);
1089
+ const after = where === 'before' ? (at > 0 ? others[at - 1].id : null) : t.id;
1090
+ send([{ op: 'task.move', input: { task: d.id, parent: t.parent, after } }]);
1091
+ },
1092
+ },
1093
+ },
1094
+ el('button', { type: 'button', class: 'toggle', 'aria-expanded': open ? 'true' : 'false', 'aria-label': open ? tr('Collapse') : tr('Expand'), disabled: !canOpen, on: { click: () => {
1095
+ if (open) expanded.delete(t.id); else expanded.add(t.id);
1096
+ render();
1097
+ } } }, canOpen ? (open ? '▾' : '▸') : '·'),
1098
+ readOnly || isRoot ? null : el('button', { type: 'button', class: 'grip', draggable: 'true', title: tr('Drag to move. Drop on the middle of a branch to put it under that branch'), 'aria-label': tr('Drag {name} to move', { name: t.title }), on: {
1099
+ dragstart: (ev) => {
1100
+ dragging = { kind: 'task', id: t.id };
1101
+ updateQuick();
1102
+ ev.dataTransfer.effectAllowed = 'move';
1103
+ ev.dataTransfer.setData('text/plain', t.id);
1104
+ ev.currentTarget.closest('.task').classList.add('dragging');
1105
+ },
1106
+ dragend: () => endDrag(),
1107
+ } }, '⠿'),
1108
+ el('div', { class: 'task-main' },
1109
+ renaming
1110
+ ? el('div', { class: 'inline' }, input('title', tr('Branch name'), { label: undefined }))
1111
+ : el('span', { class: 'title', tabindex: readOnly ? null : 0, role: readOnly ? null : 'button', 'aria-label': readOnly ? null : tr('Rename: {name}', { name: t.title }), on: readOnly ? {} : {
1112
+ click: () => startRename(t),
1113
+ keydown: (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); startRename(t); } },
1114
+ } }, t.title),
1115
+ readOnly ? el('span', { class: 'status' }, STATUS[t.status])
1116
+ : el('select', { class: 'status', 'aria-label': tr('{name} status', { name: t.title }), on: { change: (ev) => send([{ op: 'task.update', input: { task: t.id, status: ev.target.value } }]) } },
1117
+ Object.entries(STATUS).map(([k, v]) => el('option', { value: k, ...(t.status === k ? { selected: true } : {}) }, v))),
1118
+ w.person.length ? el('span', { class: 'badge ask' }, tr('Waiting for answer')) : null,
1119
+ w.ai.length ? el('span', { class: 'badge ai' }, tr('AI to decide')) : null,
1120
+ depsOut.length ? el('span', {
1121
+ class: 'badge dep', title: tr('Needs first: {list}', { list: depsOut.map((d) => tlabel(d.to)).join(', ') }),
1122
+ 'aria-label': depsOut.length === 1 ? tr('Needs {count} branch first: {list}', { count: 1, list: tlabel(depsOut[0].to) }) : tr('Needs {count} branches first: {list}', { count: depsOut.length, list: depsOut.map((d) => tlabel(d.to)).join(', ') }),
1123
+ }, `⇠ ${depsOut.length}`) : null,
1124
+ hiddenAsk ? el('span', { class: 'badge ask', title: tr('A question in the folded part is waiting for an answer') }, hiddenAsk === 1 ? tr('{count} question folded', { count: 1 }) : tr('{count} questions folded', { count: hiddenAsk })) : null,
1125
+ hiddenChange ? el('span', { class: 'mark-dot hidden-change', role: 'img', title: tr('Folded part changed: a branch or question folded below has a change that is not settled yet'), 'aria-label': tr('Folded part changed') }) : null,
1126
+ detailChange ? el('span', { class: 'mark-dot detail-change', role: 'img', title: tr('Details changed: a result, dependency or link to another screen has a change that is not settled yet'), 'aria-label': tr('Details changed') }) : null,
1127
+ beforeToggle(t.id),
1128
+ ),
1129
+ el('span', { class: 'tid' }, t.id),
1130
+ el('div', { class: 'tools' },
1131
+ el('button', { type: 'button', class: 'icon more', 'aria-haspopup': 'menu', 'aria-expanded': menuOpen ? 'true' : 'false', 'aria-label': tr('{name} menu', { name: t.title }), title: tr('Details, add a branch or question, move, remove'), on: { click: (ev) => {
1132
+ ev?.stopPropagation?.();
1133
+ menuFor = menuOpen ? null : t.id;
1134
+ armed.clear();
1135
+ render();
1136
+ } } }, '⋯'),
1137
+ menuOpen ? el('div', { class: 'menu', role: 'menu', 'aria-label': tr('{name} menu', { name: t.title }) },
1138
+ menuItem(details.has(t.id) ? tr('Close details') : tr('Details'), () => { if (details.has(t.id)) details.delete(t.id); else details.add(t.id); }),
1139
+ readOnly ? null : menuItem(tr('+ Branch below'), () => { expanded.add(t.id); startEdit({ key: key('child'), values: {}, build: (v) => {
1140
+ const title = (v.title ?? '').trim();
1141
+ return title ? [{ op: 'task.add', input: { parent: t.id, title } }] : [];
1142
+ } }); }),
1143
+ readOnly ? null : menuItem(tr('+ Question'), () => { expanded.add(t.id); startEdit({ key: key('ask'), values: { options: '' }, build: (v) => buildQuestion(t, v) }); }),
1144
+ !readOnly && !isRoot && i > 0 ? menuItem(tr('↑ Move up'), () => send([{ op: 'task.move', input: { task: t.id, parent: t.parent, after: i > 1 ? siblings[i - 2].id : null } }])) : null,
1145
+ !readOnly && !isRoot && i < siblings.length - 1 ? menuItem(tr('↓ Move down'), () => send([{ op: 'task.move', input: { task: t.id, parent: t.parent, after: siblings[i + 1].id } }])) : null,
1146
+ !readOnly && !isRoot && m.task.get(t.parent)?.parent !== null && m.task.get(t.parent)?.parent !== undefined
1147
+ ? menuItem(tr('← Move out one level'), () => send([{ op: 'task.move', input: { task: t.id, parent: m.task.get(t.parent).parent, after: t.parent } }])) : null,
1148
+ readOnly || isRoot ? null : deleteButton(key('del'), tr('branch'), () => { menuFor = null; send([{ op: 'task.remove', input: { task: t.id } }]); }, { cls: 'menu-item', label: tr('× Remove branch'), extra: { role: 'menuitem' } }),
1149
+ ) : null,
1150
+ ),
1151
+ );
1152
+ return el('li', { class: 'node', 'data-node': t.id },
1153
+ row,
1154
+ beforeView(t.id),
1155
+ conflictsOn(t.id).map(conflictCard),
1156
+ details.has(t.id) ? detailView(t) : null,
1157
+ open ? qs.map(questionView) : null,
1158
+ asking ? el('div', { class: 'question' }, el('div', { class: 'form' },
1159
+ input('text', tr('What do you want to ask?'), { label: tr('Question') }),
1160
+ input('why', tr('Why it cannot be decided without asking'), { label: tr('Why') }),
1161
+ input('impact', tr('What changes depending on the answer'), { label: tr('Impact') }),
1162
+ input('options', tr('One option per line'), { rows: 3, label: tr('Options (one per line)'), multiline: true }),
1163
+ el('div', { class: 'actions' }, btn(tr('Attach'), saveEditor, 'btn primary'), btn(tr('Cancel'), closeEditor)))) : null,
1164
+ open && (kids.length || adding) ? el('ul', { class: 'children' }, kids.map((k) => taskView(k, kids)), adding ? el('li', {}, el('div', { class: 'task' }, el('span', { class: 'toggle' }, '·'), el('div', { class: 'inline' }, input('title', tr('New branch name'))))) : null) : null,
1165
+ );
1166
+ };
1167
+
1168
+ const root = m.root ? m.task.get(m.root) : null;
1169
+ const allQ = [...m.question.values()];
1170
+ const openQ = allQ.filter(isOpenQ);
1171
+ const aiQ = allQ.filter(isAiTurn);
1172
+ const doing = [...m.task.values()].filter((t) => t.status === 'doing');
1173
+ const jump = (id) => { openPathTo(id); focused = new Set([taskOfRecord(m, id)]); render(); stage.querySelector(`[data-target="${CSS.escape(id)}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); };
1174
+
1175
+ // 위쪽 아이콘: 모두 펼치기, 모두 접기, 표시 설명, 바뀐 기록 칸(rawdev 2026-11-24)
1176
+ const sideRemoved = removed.filter((x) => x.owner !== null);
1177
+ const hiddenNotices = noticesHidden ? c.notices.length : 0;
1178
+ const sideCount = sideRemoved.length + hiddenNotices;
1179
+ // 처음 그릴 때 본 기록까지는 새것이 아니다. 칸이 열려 있으면 늘 다 본 것이다
1180
+ const feedList = feed.filter((x) => x.changes.length || x.summary);
1181
+ const newestOther = [...feedList].reverse().find((x) => !x.mine)?.revision ?? null;
1182
+ // 호스트는 같은 플러그인이면 작업을 바꿔도 이 화면을 그대로 쓰고 change 만 보낸다. 목표가 달라지면 다른 작업으로 보고 처음부터 본다
1183
+ const feedKey = `${c.instance}|${m.root}|${root?.title ?? ''}`;
1184
+ if (feedKey !== feedFor) { feedFor = feedKey; feedSeen = null; }
1185
+ if (feedSeen === null || sideOpen) feedSeen = newestOther ?? '';
1186
+ const feedNew = !sideOpen && newestOther !== null && newestOther !== feedSeen;
1187
+ const sideExtra = [
1188
+ feedNew ? tr(' (new entries)') : '',
1189
+ sideRemoved.length ? tr(', {count} removed by AI', { count: sideRemoved.length }) : '',
1190
+ hiddenNotices === 1 ? tr(', {count} hidden notice', { count: 1 }) : hiddenNotices ? tr(', {count} hidden notices', { count: hiddenNotices }) : '',
1191
+ ].join('');
1192
+ const sideLabel = sideOpen ? tr('Hide change history{extra}', { extra: sideExtra }) : tr('Show change history{extra}', { extra: sideExtra });
1193
+ const toolbar = el('span', { class: 'bar' },
1194
+ root ? iconBtn('expand', tr('Expand all'), () => { for (const t of m.task.values()) expanded.add(t.id); render(); }) : null,
1195
+ root ? iconBtn('collapse', tr('Collapse all'), () => { expanded.clear(); expanded.add(root.id); render(); }) : null,
1196
+ c.othersPending.length ? iconBtn('help', tr('What the marks mean'), () => { helpOpen = !helpOpen; render(); }, { 'aria-expanded': helpOpen ? 'true' : 'false' }) : null,
1197
+ iconBtn('history', sideLabel, () => { sideOpen = !sideOpen; render(); }, { 'aria-expanded': sideOpen ? 'true' : 'false', 'aria-controls': 'side' }, sideCount, feedNew));
1198
+ const goalFieldsEditing = root && editor?.key === `goalfields-${root.id}`;
1199
+ const goalShown = goalOpen || goalFieldsEditing;
1200
+ const chips = [
1201
+ openQ.map((q) => btn(tr('Waiting for answer: {text}', { text: q.text }), () => jump(q.id), 'chip ask')),
1202
+ aiQ.map((q) => btn(tr('AI to decide: {text}', { text: q.text }), () => jump(q.id), 'chip ai')),
1203
+ doing.map((t) => btn(tr('In progress: {text}', { text: t.title }), () => jump(t.id), 'chip doing')),
1204
+ ].flat();
1205
+
1206
+ const goalSection = root
1207
+ ? el('section', { 'aria-label': tr('Goal'), 'data-target': root.id, class: markClass(root.id).trim() },
1208
+ el('div', { class: 'head' },
1209
+ el('button', { type: 'button', class: 'toggle', 'aria-expanded': goalShown ? 'true' : 'false', 'aria-label': goalShown ? tr('Hide aim and conditions') : tr('Show aim and conditions'), title: goalShown ? tr('Hide aim and conditions') : tr('Show aim and conditions'), on: { click: () => {
1210
+ goalOpen = !goalShown;
1211
+ if (!goalOpen && goalFieldsEditing) editor = null;
1212
+ render();
1213
+ } } }, goalShown ? '▾' : '▸'),
1214
+ editor?.key === `goal-${root.id}`
1215
+ ? el('div', { class: 'inline' }, input('title', tr('Goal')))
1216
+ : el('h1', { class: 'goal-title', tabindex: readOnly ? null : 0, on: readOnly ? {} : { click: () => startEdit({ key: `goal-${root.id}`, values: { title: root.title }, build: (v) => renameSteps(root, v) }) } }, root.title),
1217
+ beforeToggle(root.id),
1218
+ toolbar),
1219
+ !goalShown ? null : goalFieldsEditing
1220
+ ? el('div', { class: 'form' }, input('aim', tr('The result to achieve'), { rows: 2, label: tr('Aim'), multiline: true }), input('conditions', tr('Conditions to keep'), { rows: 2, label: tr('Conditions'), multiline: true }),
1221
+ el('div', { class: 'actions' }, btn(tr('Save'), saveEditor, 'btn primary'), btn(tr('Cancel'), closeEditor)))
1222
+ : [
1223
+ root.aim ? el('div', { class: 'field' }, el('b', {}, tr('Aim')), el('span', {}, root.aim)) : null,
1224
+ root.conditions ? el('div', { class: 'field' }, el('b', {}, tr('Conditions')), el('span', {}, root.conditions)) : null,
1225
+ !root.aim && !root.conditions ? el('div', { class: 'empty' }, tr('Nothing written yet.')) : null,
1226
+ readOnly ? null : btn(tr('Edit'), () => startEdit({ key: `goalfields-${root.id}`, values: { aim: root.aim, conditions: root.conditions }, build: (v) => {
1227
+ const input = {};
1228
+ for (const k of ['aim', 'conditions']) if ((v[k] ?? '').trim() !== root[k]) input[k] = (v[k] ?? '').trim();
1229
+ return Object.keys(input).length ? [{ op: 'task.update', input: { task: root.id, ...input } }] : [];
1230
+ } }), 'icon', { title: tr('Edit aim and conditions') }),
1231
+ ],
1232
+ beforeView(root.id),
1233
+ // 기다리는 질문이나 하는 중인 가지가 있을 때만 보인다
1234
+ chips.length ? el('div', { class: 'summary' }, chips) : null,
1235
+ )
1236
+ : el('section', { 'aria-label': tr('Goal') },
1237
+ el('div', { class: 'head' }, el('h2', {}, tr('Goal')), toolbar),
1238
+ el('p', { class: 'empty' }, tr('Write the result you want and the conditions that matter, and AI breaks it down into an action plan below. You can also just tell AI.')),
1239
+ readOnly ? null : editor?.key === 'newroot'
1240
+ ? el('div', { class: 'form' }, input('title', tr('The result to achieve'), { label: tr('Goal') }), input('conditions', tr('Conditions to keep'), { rows: 2, label: tr('Conditions'), multiline: true }), saveRow(tr('Create')))
1241
+ : btn(tr('Write the goal'), () => startEdit({ key: 'newroot', values: {}, build: (v) => {
1242
+ const title = (v.title ?? '').trim();
1243
+ if (!title) { toast(tr('Please write the goal'), true); return null; }
1244
+ return [{ op: 'task.add', input: { title, conditions: (v.conditions ?? '').trim() } }];
1245
+ } }), 'btn primary'));
1246
+
1247
+ const treeSection = root
1248
+ ? el('section', { 'aria-label': tr('Task Tree') },
1249
+ helpOpen && c.othersPending.length ? el('p', { class: 'legend' }, tr('Things AI changed that are not settled yet carry a mark. Your next action settles everything you can see now. A dot next to a branch means something changed in its folded part or details; hover over it for an explanation.')) : null,
1250
+ el('ul', {}, taskView(root, [root])))
1251
+ : null;
1252
+
1253
+ // 바뀐 기록. 한 줄 요약(무엇을 몇 개 어떻게 했는지)만 보이고, 누르면 바뀐 것을 하나씩 보여 준다.
1254
+ const feedView = () => {
1255
+ const list = feed.filter((x) => x.changes.length || x.summary);
1256
+ const shown = list.slice(-feedShown).reverse();
1257
+ const headline = (x) => {
1258
+ const counts = new Map();
1259
+ for (const ch of x.changes) {
1260
+ const key = `${ch.type}|${ch.action}`;
1261
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1262
+ }
1263
+ const rank = (key) => { const i = FEED_ORDER.indexOf(key.split('|')[0]); return i < 0 ? FEED_ORDER.length : i; };
1264
+ const parts = [...counts].sort((a, b) => rank(a[0]) - rank(b[0])).map(([key, num]) => {
1265
+ const [type, action] = key.split('|');
1266
+ const kind = num === 1 ? FEED_KIND[type] ?? type : FEED_KINDS[type] ?? `${type}s`;
1267
+ return tr('{count} {kind} {verb}', { count: num, kind, verb: FEED_VERB[action] ?? action });
1268
+ });
1269
+ return parts.length ? parts.join(', ') : x.summary;
1270
+ };
1271
+ const changeLine = (ch) => {
1272
+ const text = String(describeContent(ch.after ?? ch.before)).replace(/\s+/g, ' ');
1273
+ return el('li', {}, el('span', { class: 'kind-tag' }, `${FEED_KIND[ch.type] ?? ch.type} ${FEED_VERB[ch.action] ?? ch.action}`), ' ', [...text].length > 80 ? `${[...text].slice(0, 80).join('')}...` : text);
1274
+ };
1275
+ return el('section', { 'aria-label': tr('Change history') }, el('h2', {}, tr('Change history')),
1276
+ list.length === 0 ? el('p', { class: 'empty' }, tr('Nothing yet.')) : null,
1277
+ list.length === 0 ? null : el('ul', { class: 'feed' }, shown.map((x) => {
1278
+ const open = openFeed.has(x.revision);
1279
+ const detail = open && x.changes.length
1280
+ ? el('ul', { class: 'feed-detail' }, x.changes.slice(0, FEED_DETAIL_MAX).map(changeLine),
1281
+ x.changes.length > FEED_DETAIL_MAX ? el('li', { class: 'legend' }, tr('Read the other {count} with read_history.', { count: x.changes.length - FEED_DETAIL_MAX })) : null)
1282
+ : null;
1283
+ const toggle = () => { if (open) openFeed.delete(x.revision); else openFeed.add(x.revision); render(); };
1284
+ return el('li', { class: `feed-item${open ? ' open' : ''}` },
1285
+ el('button', { type: 'button', class: 'feed-head', 'aria-expanded': open ? 'true' : 'false', on: { click: toggle } },
1286
+ el('span', { class: 'who' }, el('b', {}, x.revision), ' ', x.mine ? tr('by you') : tr('by AI'), x.inCommon ? null : el('span', { class: 'pending-chip' }, tr('Not settled'))),
1287
+ el('span', { class: 'headline' }, headline(x))),
1288
+ detail);
1289
+ })),
1290
+ list.length > feedShown || feedFrom
1291
+ ? btn(list.length > feedShown ? tr('Show {count} older', { count: Math.min(FEED_PAGE, list.length - feedShown) }) : tr('Show older'), () => {
1292
+ feedShown += FEED_PAGE;
1293
+ // 읽어 둔 것보다 더 보려면 더 앞에서부터 다시 읽는다
1294
+ if (list.length < feedShown && feedFrom) refresh();
1295
+ else render();
1296
+ }, 'btn')
1297
+ : null);
1298
+ };
1299
+
1300
+ const shownTargets = new Set([...m.task.keys(), ...m.question.keys()]);
1301
+ const restConflicts = c.conflicts.filter((x) => !shownTargets.has(x.record));
1302
+ // 오른쪽 칸은 숨긴 채 시작한다. 사람이 손대야 하는 부딪힌 것은 칸이 아니라 트리 위에 나온다
1303
+ const side = sideOpen ? el('div', { id: 'side' },
1304
+ sideRemoved.length
1305
+ ? el('section', { 'aria-label': tr('Removed by AI') }, el('h2', {}, tr('Removed by AI')),
1306
+ el('ul', {}, sideRemoved.map((x) => el('li', { class: 'item' }, describeContent(x.before), el('span', { class: 'tag remove' }, ACTION.remove)))))
1307
+ : null,
1308
+ // 사람이 숨긴 알림은 이 칸에서 다시 보고, [보이기] 로 트리 위에 되돌린다
1309
+ hiddenNotices ? el('section', { 'aria-label': tr('Hidden notices') },
1310
+ el('div', { class: 'head' }, el('h2', {}, tr('Hidden notices')), btn(tr('Show above the tree'), () => { noticesHidden = false; render(); }, 'icon')),
1311
+ c.notices.map((x) => el('div', { class: 'item' }, x.message ?? x.kind))) : null,
1312
+ feedView(),
1313
+ ) : null;
1314
+
1315
+ const noticeSection = c.notices.length && !noticesHidden
1316
+ ? el('section', { 'aria-label': tr('Notices') },
1317
+ el('div', { class: 'head' }, el('h2', {}, tr('Notices')),
1318
+ btn(tr('Hide'), () => { noticesHidden = true; render(); }, 'icon', { title: tr('Hide notices. A count stays on the change history icon, and you can see them again in that panel') })),
1319
+ c.notices.map((x) => el('div', { class: 'item' }, x.message ?? x.kind)))
1320
+ : null;
1321
+
1322
+ // 한눈에 보아야 하는 것(읽기만 하는 화면인지, 부딪힘, 알림)은 숨긴 칸이 아니라 트리 위에 둔다
1323
+ const main = el('div', { id: 'main' },
1324
+ // 커서가 AI 에게 있으면 호스트 위쪽에 "AI 가 고치는 중" 띠가 이미 있으므로 짧게만 적는다
1325
+ notEditing ? el('div', { class: 'readonly' }, tr('This is not the screen being edited, so it is read-only. To edit, switch to this screen from the bar at the top.'))
1326
+ : readOnly ? el('div', { class: 'readonly' }, tr('Read-only for now.')) : null,
1327
+ restConflicts.length ? el('section', { 'aria-label': tr('Conflicts') }, el('h2', {}, tr('Conflicts')), restConflicts.map(conflictCard)) : null,
1328
+ noticeSection, goalSection, quickEl, treeSection);
1329
+ stage.className = sideOpen ? 'with-side' : '';
1330
+ if (side) stage.replaceChildren(main, side); else stage.replaceChildren(main);
1331
+
1332
+ const back = field ? stage.querySelector(`[data-field="${CSS.escape(field)}"]`) : stage.querySelector('[data-field]');
1333
+ if (back && editor) {
1334
+ back.focus({ preventScroll: true });
1335
+ if (sel && 'setSelectionRange' in back) back.setSelectionRange(sel[0], sel[1]);
1336
+ }
1337
+ if (quickFocus && !quickEl.hidden) {
1338
+ quickSaid.focus({ preventScroll: true });
1339
+ quickSaid.setSelectionRange(quickFocus[0], quickFocus[1]);
1340
+ }
1341
+ updateQuick();
1342
+ if (drawPending) {
1343
+ drawPending = false;
1344
+ parent.postMessage({ aic: 1, event: 'rendered', token: c.renderToken }, '*');
1345
+ }
1346
+ }
1347
+
1348
+ function renameSteps(t, v) {
1349
+ const title = (v.title ?? '').trim();
1350
+ if (!title || title === t.title) return [];
1351
+ return [{ op: 'task.update', input: { task: t.id, title } }];
1352
+ }
1353
+ function startRename(t) {
1354
+ startEdit({ key: `rename-${t.id}`, values: { title: t.title }, build: (v) => renameSteps(t, v) });
1355
+ }
1356
+ function buildQuestion(t, v) {
1357
+ const text = (v.text ?? '').trim();
1358
+ if (!text) { toast(tr('Please write the question'), true); return null; }
1359
+ const options = (v.options ?? '').split(/\r?\n/).map((x) => x.trim()).filter(Boolean).map((title) => ({ title }));
1360
+ return [{ op: 'question.add', input: { task: t.id, text, why: (v.why ?? '').trim(), impact: (v.impact ?? '').trim(), options } }];
1361
+ }
1362
+
1363
+ function clearDrop() {
1364
+ for (const x of stage.querySelectorAll('.drop-before, .drop-after, .drop-in')) x.classList.remove('drop-before', 'drop-after', 'drop-in');
1365
+ }
1366
+ function endDrag() {
1367
+ dragging = null;
1368
+ clearDrop();
1369
+ for (const x of stage.querySelectorAll('.dragging')) x.classList.remove('dragging');
1370
+ if (renderWanted) render(); else updateQuick();
1371
+ }
1372
+
1373
+ // --- 고르기와 AI 에게 말하기(032 30절, rawdev 2026-11-25) ---
1374
+ // 가지 줄이나 질문 카드의 빈 곳을 누르면 고른다. Ctrl, Shift, Cmd 를 누른 채 누르면 더하거나 뺀다. 고른 것이 있으면
1375
+ // 화면 아래에 말 칸이 뜨고, 글을 적어 Enter 나 Send 를 누르면 고른 것과 글이 AI 에게 간다(shareSelection)
1376
+ const canPick = () => Boolean(caps.conceptSelection || caps.conceptPick) && canEdit && !lastReadOnly;
1377
+ const canShare = () => Boolean(caps.conceptSelection) && canEdit && !lastReadOnly;
1378
+ function pickFrom(ev, id) {
1379
+ if (!canPick() || ev.target.closest('button, select, input, textarea, a, label, .title, .menu, [role="button"], [data-field]')) return;
1380
+ if (String(window.getSelection?.() ?? '') !== '') return; // 글을 끌어 고른 것이면 가지를 고르지 않는다
1381
+ if (ev.ctrlKey || ev.metaKey || ev.shiftKey) {
1382
+ if (picked.has(id)) picked.delete(id); else picked.add(id);
1383
+ } else if (picked.size === 1 && picked.has(id)) picked.clear();
1384
+ else { picked.clear(); picked.add(id); }
1385
+ // 말 칸이 트리 위에 나타나거나 사라지면 트리가 밀린다. 누른 줄이 같은 곳에 남게 그만큼 화면을 움직인다
1386
+ const where = `.task[data-task="${CSS.escape(id)}"], .question[data-question="${CSS.escape(id)}"]`;
1387
+ const before = stage.querySelector(where)?.getBoundingClientRect().top;
1388
+ render();
1389
+ const after = stage.querySelector(where)?.getBoundingClientRect().top;
1390
+ if (typeof before === 'number' && typeof after === 'number' && after !== before) window.scrollBy?.(0, after - before);
1391
+ }
1392
+ function clearPicked() {
1393
+ if (!picked.size) return;
1394
+ picked.clear();
1395
+ render();
1396
+ }
1397
+ function selectionPayload() {
1398
+ const m = model();
1399
+ const tasks = [...picked].filter((id) => m.task.has(id));
1400
+ const questions = [...picked].filter((id) => m.question.has(id));
1401
+ const labels = {};
1402
+ for (const id of tasks) labels[id] = m.task.get(id).title.slice(0, 200);
1403
+ for (const id of questions) labels[id] = m.question.get(id).text.slice(0, 200);
1404
+ return { format: SELECTION_FORMAT, rev: concept.base, tasks, questions, labels };
1405
+ }
1406
+ const quickEl = document.getElementById('quickTalk');
1407
+ const quickSaid = document.getElementById('quickSaid');
1408
+ const quickWhat = document.getElementById('quickWhat');
1409
+ function updateQuick() {
1410
+ const show = picked.size > 0 && canShare() && !dragging;
1411
+ quickEl.hidden = !show;
1412
+ if (show) {
1413
+ const m = model();
1414
+ const one = picked.size === 1 ? [...picked][0] : null;
1415
+ quickWhat.textContent = one ? (m.task.get(one)?.title ?? m.question.get(one)?.text ?? one) : tr('{count} selected', { count: picked.size });
1416
+ quickWhat.title = one ? tr('Selected: {name}', { name: quickWhat.textContent }) : tr('{count} items selected', { count: picked.size });
1417
+ }
1418
+ syncPick();
1419
+ }
1420
+ async function shareSelection() {
1421
+ if (!canShare() || sharing || !picked.size) return;
1422
+ const said = quickSaid.value.trim();
1423
+ const p = selectionPayload();
1424
+ if (!p.tasks.length && !p.questions.length) return;
1425
+ sharing = true;
1426
+ try {
1427
+ const res = await call('shareSelection', { base: p.rev, role: 'change', said, payload: p, records: [...p.tasks, ...p.questions] });
1428
+ if (!res?.ok) { toast(res?.summary ?? res?.error ?? tr('Could not send the selection'), true); return; }
1429
+ if (quickSaid.value.trim() === said) quickSaid.value = '';
1430
+ toast(tr('Sent selection {id} to the AI', { id: res.selection }));
1431
+ } catch (err) {
1432
+ toast(err.message, true);
1433
+ } finally {
1434
+ sharing = false;
1435
+ }
1436
+ }
1437
+ // 고르기만 하고 보내지 않은 것도 AI 가 read_selection 으로 읽게 호스트에 알린다. 고른 것이나 기준이 바뀔 때만 보내고
1438
+ // 답은 기다리지 않는다. 보낸 선택이 성공하면 코어가 지우므로 그때는 따로 지우지 않는다
1439
+ let pickKey = '';
1440
+ function syncPick() {
1441
+ if (!caps.conceptPick || !canEdit || lastReadOnly || !concept) return;
1442
+ const p = picked.size ? selectionPayload() : null;
1443
+ const key = p ? JSON.stringify(p) : '';
1444
+ if (key === pickKey) return;
1445
+ pickKey = key;
1446
+ call('setPick', p ? { base: p.rev, payload: p, records: [...p.tasks, ...p.questions] } : null).catch(() => {});
1447
+ }
1448
+ quickSaid.addEventListener('compositionstart', () => { composing = true; });
1449
+ quickSaid.addEventListener('compositionend', () => { composing = false; if (renderWanted) render(); });
1450
+ quickSaid.addEventListener('keydown', (ev) => {
1451
+ if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); shareSelection(); }
1452
+ else if (ev.key === 'Escape') quickSaid.blur();
1453
+ });
1454
+ document.getElementById('quickSend').addEventListener('click', shareSelection);
1455
+ document.getElementById('quickClear').addEventListener('click', clearPicked);
1456
+ // 트리 바깥의 빈 곳을 누르거나 Esc 를 누르면 고른 것을 푼다
1457
+ stage.addEventListener('click', (ev) => {
1458
+ if (!picked.size || ev.target.closest('.task, .question, .detail, .conflict, #quickTalk, button, select, input, textarea, a, label, .menu')) return;
1459
+ clearPicked();
1460
+ });
1461
+ document.addEventListener('keydown', (ev) => {
1462
+ if (ev.key !== 'Escape' || menuFor !== null || editor || !picked.size || ev.target.closest?.('input, textarea, select, #quickTalk')) return;
1463
+ clearPicked();
1464
+ });
1465
+
1466
+ // 칸 밖을 누르면 한 줄 칸(이름)은 저장하고, 여러 칸 양식은 그대로 둔다
1467
+ document.addEventListener('focusout', (ev) => {
1468
+ const f = ev.target?.dataset?.field;
1469
+ if (!f || !editor || !/^(rename|goal)-/.test(editor.key)) return;
1470
+ const e = editor;
1471
+ setTimeout(() => {
1472
+ if (editor === e && !document.activeElement?.dataset?.field) saveEditor();
1473
+ }, 150);
1474
+ });
1475
+
1476
+ // ⋯ 메뉴는 메뉴 밖을 누르거나 Esc 를 누르면 닫힌다
1477
+ document.addEventListener('click', (ev) => {
1478
+ if (menuFor === null || ev.target?.closest?.('.menu, .more')) return;
1479
+ menuFor = null;
1480
+ render();
1481
+ });
1482
+ document.addEventListener('keydown', (ev) => {
1483
+ if (ev.key !== 'Escape' || menuFor === null) return;
1484
+ // 닫은 뒤에는 메뉴를 연 ⋯ 버튼으로 초점을 돌려준다. 다시 그리면 그 버튼이 새로 생기므로 찾아서 준다
1485
+ const t = menuFor;
1486
+ menuFor = null;
1487
+ render();
1488
+ stage.querySelector(`[data-task="${CSS.escape(t)}"] .more`)?.focus();
1489
+ });
1490
+
1491
+ /** index.html 에 적힌 고정 글을 지금 언어로 바꾸고 문서의 lang 을 맞춘다. 영어는 적힌 그대로다. */
1492
+ function applyLanguage() {
1493
+ if (document.documentElement) document.documentElement.lang = LANG;
1494
+ if (LANG === 'en') return;
1495
+ document.title = tr('Task Tree');
1496
+ quickSaid.setAttribute('aria-label', tr('What to tell the AI about the selection'));
1497
+ quickSaid.setAttribute('placeholder', tr('Tell the AI about the selection'));
1498
+ const sendBtn = document.getElementById('quickSend');
1499
+ sendBtn.textContent = tr('Send');
1500
+ sendBtn.setAttribute('title', tr('Send the selection and your words to the AI'));
1501
+ const clearBtn = document.getElementById('quickClear');
1502
+ clearBtn.setAttribute('title', tr('Clear the selection'));
1503
+ clearBtn.setAttribute('aria-label', tr('Clear the selection'));
1504
+ }
1505
+
1506
+ parent.postMessage({ aic: 1, event: 'ready', rendered: true }, '*');
1507
+ call('capabilities', {}).then((cap) => {
1508
+ if (!cap || typeof cap !== 'object') return;
1509
+ caps = cap;
1510
+ // 언어는 capabilities 에 함께 온다. 보통 첫 읽기보다 먼저 오지만, 이미 영어로 그렸으면 한 번 다시 그린다
1511
+ const lang = cap.language === 'ko' ? 'ko' : 'en';
1512
+ const langChanged = lang !== LANG;
1513
+ if (langChanged) {
1514
+ LANG = lang;
1515
+ applyLanguage();
1516
+ }
1517
+ // 고를 수 있는지는 누를 때 본다. 처음 그릴 때는 고른 것이 없으므로 다시 그리지 않아도 된다
1518
+ if (cap.edit === false) canEdit = false;
1519
+ if (concept && (langChanged || cap.edit === false)) render();
1520
+ }, () => {});
1521
+ </script>
1522
+ </body>
1523
+ </html>