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,1305 @@
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>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
+ --note: #5c4a00; --note-bg: #fff6c9; --note-line: #e6d27a;
13
+ --add: #1d7a46; --add-bg: #e3f4e9; --upd: #8f5b00; --upd-bg: #fbf0d9; --mov: #3b5bb5; --mov-bg: #e6ebfa; --del: #a8321f; --del-bg: #fae6e2;
14
+ }
15
+ @media (prefers-color-scheme: dark) {
16
+ :root {
17
+ --bg: #191b1e; --panel: #22252a; --text: #e6e8eb; --muted: #a0a8b2; --line: #383d44; --soft: #2b2f35;
18
+ --accent: #7cc0dd; --accent-text: #10222b; --focus-bg: #1f3a46;
19
+ --note: #f1dc8e; --note-bg: #3a3317; --note-line: #6f6125;
20
+ --add: #7bd6a0; --add-bg: #17392a; --upd: #eec26e; --upd-bg: #41331a; --mov: #a5b9f4; --mov-bg: #252f4f; --del: #f1a597; --del-bg: #472420;
21
+ }
22
+ }
23
+ * { box-sizing: border-box; }
24
+ html, body { height: 100%; }
25
+ body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.6 system-ui, "Malgun Gothic", sans-serif; }
26
+
27
+ /* 트리가 화면을 넓게 쓴다. 오른쪽 칸(바뀐 기록 들)은 숨긴 채 시작하고 도구 줄의 아이콘으로 연다(rawdev 2026-11-24, 코어 032 34절과 같은 방향) */
28
+ #stage { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; padding: 10px 14px; align-items: start; }
29
+ #stage.with-side { grid-template-columns: minmax(0, 1fr) 280px; }
30
+ section.tree { background: transparent; border: 0; padding: 0 2px; }
31
+ /* 트리 위의 도구는 오른쪽 위에 떠 있는 아이콘 줄이다. 이름은 title 과 aria-label 에 둔다 */
32
+ .toolbar { position: sticky; top: 4px; float: right; z-index: 5; display: flex; gap: 2px; margin: 0 0 4px 8px; padding: 2px; border-radius: 8px; background: var(--bg); }
33
+ .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); }
34
+ .icon-btn:hover { background: var(--soft); color: var(--text); }
35
+ .icon-btn[aria-expanded="true"], .icon-btn[aria-pressed="true"] { background: var(--soft); border-color: var(--line); color: var(--accent); }
36
+ .icon-btn svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
37
+ .icon-btn .count { position: absolute; top: -3px; right: -3px; min-width: 15px; height: 15px; padding: 0 3px; border-radius: 8px; background: var(--del); color: #fff; font-size: 10px; line-height: 15px; text-align: center; }
38
+ .icon-btn .dot { position: absolute; top: 3px; right: 3px; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
39
+ .icon-btn .dot.low { top: auto; bottom: 2px; }
40
+ .icon-btn.help { cursor: help; }
41
+ section { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px 12px; margin-bottom: 14px; }
42
+ .head { display: flex; align-items: center; justify-content: space-between; gap: 6px; margin-bottom: 6px; flex-wrap: wrap; }
43
+ h2 { font-size: 14px; margin: 0; color: var(--muted); font-weight: 600; }
44
+ ul { list-style: none; margin: 0; padding: 0; }
45
+
46
+ button { font: inherit; color: inherit; cursor: pointer; }
47
+ .btn { white-space: nowrap; background: transparent; border: 1px solid var(--line); border-radius: 5px; padding: 1px 8px; font-size: 13px; line-height: 1.6; }
48
+ .btn:hover { background: var(--soft); }
49
+ .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
50
+ .icon { background: transparent; border: 0; border-radius: 4px; padding: 0 5px; color: var(--muted); font-size: 13px; line-height: 1.6; min-width: 22px; }
51
+ .icon:hover { background: var(--soft); color: var(--text); }
52
+ .icon.armed { background: var(--del-bg); color: var(--del); font-weight: 600; }
53
+ button:focus-visible, select:focus-visible, textarea:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
54
+
55
+ /* 트리 */
56
+ .children { margin-left: 18px; padding-left: 8px; border-left: 1px solid var(--line); }
57
+ .node { position: relative; }
58
+ .row { position: relative; display: flex; align-items: flex-start; gap: 4px; padding: 3px 4px; border-radius: 6px; border-left: 3px solid transparent; }
59
+ .row.root .title { font-size: 17px; font-weight: 650; }
60
+ .row.focus { outline: 2px solid var(--accent); }
61
+ .row.drop-before::before, .row.drop-after::after { content: ""; position: absolute; left: 0; right: 0; height: 2px; background: var(--accent); }
62
+ .row.drop-before::before { top: -2px; }
63
+ .row.drop-after::after { bottom: -2px; }
64
+ .row.drop-in { outline: 2px dashed var(--accent); outline-offset: 1px; }
65
+ .row.dragging { opacity: .45; }
66
+ .toggle { flex: none; width: 20px; border: 0; background: transparent; color: var(--muted); padding: 0; line-height: 1.6; }
67
+ .toggle[disabled] { cursor: default; opacity: .35; }
68
+ .grip { flex: none; cursor: grab; color: var(--muted); border: 0; background: transparent; padding: 0 2px; line-height: 1.6; }
69
+ .nid { flex: none; color: var(--muted); font-size: 12px; line-height: 1.6rem; }
70
+ .row-main { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 6px; }
71
+ .title { overflow-wrap: anywhere; cursor: text; }
72
+ .badge { font-size: 12px; line-height: 1.5; border-radius: 3px; padding: 0 5px; }
73
+ .badge.note { color: var(--note); background: var(--note-bg); }
74
+ .memo-count { border: 0; cursor: pointer; font: inherit; font-size: 12px; }
75
+ .memo-count[aria-expanded="true"] { box-shadow: inset 0 0 0 1px var(--note-line); }
76
+ .badge.hidden-change { color: var(--upd); background: var(--upd-bg); }
77
+ .tools { flex: none; display: flex; gap: 1px; align-items: flex-start; }
78
+ /* 노드 번호와 스티커의 메모 번호는 AI 에게 말할 때만 쓰므로 가리킬 때만 보인다 */
79
+ @media (hover: hover) {
80
+ .tools, .mini, .nid, .sticker .ref { opacity: 0; transition: opacity .1s; }
81
+ .row:hover > .tools, .row:focus-within > .tools, .has-mini:hover .mini, .has-mini:focus-within .mini,
82
+ .row:hover > .nid, .row:focus-within > .nid, .sticker:hover .ref, .sticker:focus-within .ref { opacity: 1; }
83
+ }
84
+ .item { display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; padding: 1px 0; overflow-wrap: anywhere; }
85
+ .empty { color: var(--muted); font-size: 14px; }
86
+
87
+ /* 스티커: 글은 메모함의 메모다 */
88
+ .stickers { display: flex; flex-wrap: wrap; gap: 6px; margin: 2px 0 6px 46px; }
89
+ .sticker { max-width: 340px; padding: 4px 8px 5px; border-radius: 4px; border: 1px solid var(--note-line); background: var(--note-bg); color: var(--note); font-size: 14px; box-shadow: 0 1px 2px rgba(0, 0, 0, .12); }
90
+ .sticker .memo-text { white-space: pre-wrap; overflow-wrap: anywhere; color: var(--text); }
91
+ .sticker .bar { display: flex; gap: 4px; align-items: baseline; font-size: 12px; }
92
+ .sticker .bar .mid { color: var(--muted); }
93
+ .sticker .gone { color: var(--muted); text-decoration: line-through; }
94
+ /* 접힌 스티커는 글의 앞 세 줄만 보이고, 누르면 펼친다(호스트 메모함과 같다). 화면 전체에서 하나만 펼친다 */
95
+ .sticker.closed { cursor: pointer; }
96
+ .sticker.closed:hover { border-color: var(--accent); }
97
+ .sticker.closed .memo-text { white-space: normal; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden; }
98
+ .sticker.closed .mini { display: none !important; }
99
+ .sticker.open { max-width: 520px; }
100
+ .sticker.m-add { box-shadow: inset 3px 0 0 var(--add); }
101
+ .sticker.m-update, .sticker.m-move { box-shadow: inset 3px 0 0 var(--mov); }
102
+
103
+ /* 변경 표시는 작업 트리 화면과 같다 */
104
+ .m-add { border-left-color: var(--add); background: var(--add-bg); }
105
+ .m-update { border-left-color: var(--upd); background: var(--upd-bg); }
106
+ .m-move { border-left-color: var(--mov); background: var(--mov-bg); }
107
+ .old.m-add, .old.m-update, .old.m-move { opacity: .8; }
108
+ .tag { display: inline-block; font-size: 12px; line-height: 1.5; padding: 0 5px; border-radius: 3px; border: 0; }
109
+ .tag.add { color: var(--add); background: var(--add-bg); }
110
+ .tag.update { color: var(--upd); background: var(--upd-bg); }
111
+ .tag.move { color: var(--mov); background: var(--mov-bg); }
112
+ .tag.remove { color: var(--del); background: var(--del-bg); }
113
+ .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; }
114
+
115
+ /* 입력 */
116
+ textarea, input[type=text], select { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--accent); border-radius: 5px; padding: 2px 6px; }
117
+ select { border-color: var(--line); max-width: 100%; }
118
+ textarea { width: 100%; display: block; resize: vertical; min-height: 2.1em; }
119
+ input[type=text] { width: 100%; }
120
+ .form { display: grid; grid-template-columns: minmax(0, 1fr); gap: 5px; margin: 4px 0 6px 46px; }
121
+ .form select { width: 100%; }
122
+ .form.bare { margin: 4px 0; }
123
+ .form label > span { color: var(--muted); font-size: 12px; display: block; }
124
+ .actions { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; }
125
+ .hint { color: var(--muted); font-size: 12px; margin: 2px 0 0; }
126
+ .inline { flex: 1; min-width: 12em; }
127
+ /* [+ 스티커] 를 누른 뒤 뜨는 고르기 창 */
128
+ .modal-back { position: fixed; inset: 0; z-index: 20; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(0, 0, 0, .35); }
129
+ .modal { width: min(420px, 100%); padding: 14px 16px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel); color: var(--text); box-shadow: 0 6px 24px rgba(0, 0, 0, .25); }
130
+ .modal h3 { margin: 0 0 4px; font-size: 16px; }
131
+ .modal .hint { margin: 0 0 12px; overflow-wrap: anywhere; }
132
+
133
+ /* 부딪힘 */
134
+ .conflict { border: 1px solid var(--del); border-radius: 6px; padding: 6px 8px; margin: 4px 0 4px 46px; background: var(--panel); font-size: 14px; }
135
+ .conflict h3 { margin: 0 0 4px; font-size: 13px; color: var(--del); font-weight: 600; }
136
+ .sides { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
137
+ .side { border: 1px solid var(--line); border-radius: 5px; padding: 3px 6px; overflow-wrap: anywhere; }
138
+ .side b { display: block; font-size: 12px; color: var(--muted); font-weight: 600; }
139
+ .warn { font-size: 12px; color: var(--muted); margin: 4px 0; overflow-wrap: anywhere; }
140
+
141
+ .feed li { padding: 4px 0; border-top: 1px solid var(--line); font-size: 13px; overflow-wrap: anywhere; }
142
+ .feed li:first-child { border-top: 0; }
143
+ .who { color: var(--muted); font-size: 12px; display: block; }
144
+ .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; }
145
+ .feed-head:hover { background: var(--soft); }
146
+ .feed-head .headline { display: block; font-size: 13px; }
147
+ .feed-head .who b { color: var(--text); }
148
+ .pending-chip { margin-left: 6px; color: var(--muted); font-size: 11px; }
149
+ .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; }
150
+ .feed-detail li { border-top: 0; padding: 1px 0; font-size: 12px; }
151
+ .feed-detail .kind-tag { color: var(--muted); font-weight: 600; }
152
+ .legend { color: var(--muted); font-size: 12px; margin: 0 0 6px; }
153
+ .readonly { background: var(--soft); border-radius: 6px; padding: 6px 10px; font-size: 14px; margin-bottom: 10px; }
154
+ .side-stickers .stickers { margin-left: 0; }
155
+
156
+ /* 노드 줄을 고르면 화면 위쪽, 오른쪽 위 아이콘 줄의 왼편에 AI 에게 말할 칸이 뜬다. 고른 것이 없으면 사라진다.
157
+ 아래쪽에 두면 잘 보이지 않아 위로 옮겼다(rawdev 2026-11-25 "ai에게 보내기 창이 화면 하단에 있어서 잘 안보여. 가능하면 상단에 둬").
158
+ 아이콘 줄(아이콘 다섯 개, 150px 남짓)을 가리지 않게 오른쪽을 비워 둔다. 스크롤해도 늘 위쪽에 있다 */
159
+ .row.picked { background: var(--focus-bg); box-shadow: inset 0 0 0 1px var(--accent); }
160
+ #quickTalk { position: fixed; z-index: 15; left: 12px; top: 6px; width: min(520px, calc(100% - 190px)); min-width: 200px; display: flex; gap: 4px; background: var(--panel); border: 1px solid var(--accent); border-radius: 8px; padding: 5px 6px; box-shadow: 0 2px 10px rgba(0, 0, 0, .14); }
161
+ #quickTalk input { flex: 1; min-width: 0; border-color: var(--line); }
162
+ #quickTalk .count { flex: none; align-self: center; max-width: 30%; overflow: hidden; text-overflow: ellipsis; color: var(--muted); font-size: 12px; white-space: nowrap; }
163
+ body.talking #stage { padding-top: 54px; }
164
+ #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); }
165
+ #toast.bad { background: var(--del); color: #fff; }
166
+ #error { color: var(--del); padding: 16px; }
167
+ [hidden] { display: none !important; }
168
+
169
+ /* 좁으면 바뀐 기록만 트리 아래로 내린다. 트리의 들여쓰기와 줄 모양은 너비와 상관없이 같게 둔다.
170
+ 호스트의 보기 탭(오른쪽 칸, 500px 남짓)에서도 주 화면과 같은 트리로 보이게 하려는 것이다(rawdev 2026-11-14) */
171
+ @media (max-width: 900px) {
172
+ #stage, #stage.with-side { grid-template-columns: minmax(0, 1fr); padding: 10px; }
173
+ }
174
+ /* 마우스가 없는 좁은 화면에서만 늘 보이는 도구를 이름 아래 줄로 내린다. 마우스가 있으면 도구는 가리킬 때만 보인다 */
175
+ @media (max-width: 900px) and (hover: none) {
176
+ .row { flex-wrap: wrap; }
177
+ .row > .tools { flex: 0 0 100%; flex-wrap: wrap; padding-left: 24px; }
178
+ }
179
+ /* 아주 좁은 휴대폰 너비에서만 들여쓰기를 줄인다 */
180
+ @media (max-width: 420px) {
181
+ .stickers, .before, .conflict, .form { margin-left: 20px; }
182
+ .children { margin-left: 10px; padding-left: 6px; }
183
+ }
184
+ </style>
185
+ </head>
186
+ <body>
187
+ <div id="error" role="alert" hidden></div>
188
+ <main id="stage"></main>
189
+ <div id="quickTalk" hidden>
190
+ <span class="count" id="quickCount"></span>
191
+ <input id="quickSaid" type="text" autocomplete="off" aria-label="What to tell the AI about the selected nodes" placeholder="Tell the AI about the selected nodes">
192
+ <button type="button" class="btn primary" id="quickSend" title="Send the selected nodes and your words to the AI">Send</button>
193
+ </div>
194
+ <div id="toast" role="status" hidden></div>
195
+ <script>
196
+ // 트리의 화면(plugin-design/tree.md). 호스트 연결로만 코어와 이야기한다. 글은 모두 textContent 로 넣는다.
197
+ // 사람이 화면에서 하는 일도 모두 조작으로 바뀌어 AI 와 같은 경로로 저장된다. 접고 펼친 것은 화면 상태라 저장하지 않는다.
198
+ // 스티커에는 글이 없다. 메모함에 물어 가져오고, 스티커를 붙일 때는 새 메모와 스티커를 한 요청으로 보낸다.
199
+ 'use strict';
200
+ const stage = document.getElementById('stage');
201
+ const errorEl = document.getElementById('error');
202
+ const toastEl = document.getElementById('toast');
203
+
204
+ let nextId = 1;
205
+ const waiting = new Map();
206
+ let concept = null;
207
+ let memoById = new Map();
208
+ // 메모 모두 접기(rawdev 2026-11-14). 참이면 노드의 스티커 목록을 감춘다. "메모 N개" 는 접기와 상관없이 늘 노드 옆에 나온다.
209
+ // "메모 N개" 를 누른 노드는 지금의 모두 접기 상태와 반대로 보인다(감춘 동안은 보이고, 보이는 동안은 감춘다).
210
+ // 화면 상태라 저장하지 않고, 다시 그려도 유지한다. [메모 모두 접기/펼치기] 를 누르면 노드별로 바꾼 것은 지운다
211
+ let stickersHidden = false;
212
+ const stickersFlipped = new Set();
213
+ const stickersVisible = (nodeId) => stickersHidden === stickersFlipped.has(nodeId);
214
+ // 오른쪽 칸(바뀐 기록, 지워진 노드의 스티커, 부딪힌 것, 알림). 숨긴 채 시작하지만, 사람이 손볼 것(지워진 노드의 스티커,
215
+ // 노드 밖의 부딪힘, 알림)이 새로 생기면 저절로 연다. 한눈에 보여야 하는 것이라서다(rawdev 2026-11-24). 사람이 닫으면 수가 더 늘 때까지 닫아 둔다.
216
+ // 숨긴 동안 AI 의 새 변경이 오면 아이콘에 점을 찍는다. 화면 상태라 저장하지 않는다
217
+ let sideOpen = false;
218
+ let lastAttention = 0;
219
+ let seenFeed = null; // 칸을 열었을 때 본 가장 새 기록의 revision
220
+ let canEdit = true; // 읽기만 하는 보조 보기면 거짓(032 10.2절). 그때는 메모 고치기도 숨긴다
221
+ let stickerOpen = null; // 펼친 스티커 하나의 id. 다른 것을 펴면 이것은 접힌다. 화면 상태라 저장하지 않는다
222
+ let memoChoices = null; // 스티커 칸을 열 때 읽는 메모함 전체. 칸을 닫으면 버린다
223
+ let stickerAsk = null; // [+ 스티커] 를 누른 뒤 새 메모와 메모함의 메모 가운데 고르는 창. { nodeId, key, title }
224
+ let feed = [];
225
+ const expanded = new Set(); // 펼친 노드
226
+ const seenNodes = new Set(); // 처음 볼 때만 펼칠지 정한다. 사람이 접은 것은 그대로 둔다
227
+ const openBefore = new Set();
228
+ let focused = new Set();
229
+ let editor = null; // 지금 쓰는 칸 하나. { key, values, build, base }
230
+ let composing = false;
231
+ let dragging = null;
232
+ let committing = false;
233
+ let renderWanted = false;
234
+ // 그린 기준 알림(032 10.3절). 호스트가 읽기 응답에 붙인 표를, 그 응답을 다 그린 뒤 그대로 돌려보낸다.
235
+ let drawPending = false;
236
+ const armed = new Map();
237
+ // 고른 노드(032 30절). 줄의 빈 곳을 누르면 고르고, Ctrl(Mac 은 Cmd)을 누른 채 누르면 더하거나 뺀다. Esc 로 비운다.
238
+ // 화면 상태라 저장하지 않는다. 고른 것이 있으면 위쪽에 AI 에게 말할 칸이 뜬다
239
+ let picked = [];
240
+ let caps = {}; // capabilities(). conceptSelection 이 있어야 선택을 보낸다
241
+ const SELECTION_FORMAT = 'aic.tree/selection-1';
242
+
243
+ // 화면 글의 언어(plugin-guide 3.7절, 4.4절). 코드의 영어 글이 원문이고, capabilities().language 가 "ko" 일 때만 아래 사전의 한국어를 보인다.
244
+ // 다른 값이거나 없으면(옛 호스트) 영어다. 사람이 언어를 바꾸면 호스트가 화면을 다시 열므로 처음 한 번만 읽는다.
245
+ // 값은 {name} 자리에 넣는다. 논리가 낸 글(요약, 거절 문장)과 코어가 준 글은 사전을 지나지 않고 그대로 보인다.
246
+ // 이름을 t 가 아니라 tr 로 둔 것은 이 화면의 노드 변수 t 와 겹치지 않게 하려는 것이다. src/lang.test.ts 가 사전이 빠지지 않았는지 본다.
247
+ let lang = 'en';
248
+ const KO = {
249
+ 'Changes withdrawn: {list}': '철회한 변경: {list}',
250
+ 'Remove node': '노드 지우기',
251
+ 'Remove?': '지울까요?',
252
+ 'new': '새로 생김',
253
+ 'changed': '고침',
254
+ 'moved': '옮김',
255
+ 'removed': '지움',
256
+ 'added': '더함',
257
+ 'node': '노드',
258
+ 'nodes': '노드',
259
+ 'sticker': '스티커',
260
+ 'stickers': '스티커',
261
+ 'memo': '메모',
262
+ 'memos': '메모',
263
+ 'screen': '화면',
264
+ 'screens': '화면',
265
+ '{n} {kind} {verb}': '{kind} {n}개 {verb}',
266
+ 'Reading the memo': '메모를 읽는 중입니다',
267
+ '[External result: {tool}]': '[외부 결과: {tool}]',
268
+ 'Removed target': '지워진 대상',
269
+ '{text} (removed {type})': '{text}(지워진 {type})',
270
+ 'target': '대상',
271
+ 'Removed': '지움',
272
+ 'Sticker: {text}': '스티커: {text}',
273
+ 'The same thing was changed in two ways': '같은 곳을 다르게 바꿨습니다',
274
+ 'What this points to was removed': '가리키는 것이 지워졌습니다',
275
+ ' (resolves {n} together)': ' ({n}건을 함께 풉니다)',
276
+ 'Yours': '내 것',
277
+ 'Theirs': '상대 것',
278
+ 'the other participant': '상대',
279
+ 'If you keep yours, this whole change by {name} is canceled: {summary}': '내 것을 고르면 {name} 의 이 변경이 통째로 취소됩니다: {summary}',
280
+ 'If you keep theirs, this whole change of yours is canceled: {summary}': '상대 것을 고르면 내 이 변경이 통째로 취소됩니다: {summary}',
281
+ 'Keep yours': '내 것으로',
282
+ 'Keep {name}': '{name} 것으로',
283
+ 'Keep theirs': '상대 것으로',
284
+ 'Save': '저장',
285
+ 'Enter to save, Esc to cancel': 'Enter 로 저장, Esc 로 취소',
286
+ 'Cancel': '취소',
287
+ 'The memo text is empty. To remove the memo, remove it in the memo box': '메모의 글이 비었습니다. 메모를 지우려면 메모함에서 지웁니다',
288
+ 'Hide the stickers on this node': '이 노드의 스티커를 감춥니다',
289
+ 'Show the stickers on this node': '이 노드의 스티커를 보입니다',
290
+ '{n} memo': '메모 {n}개',
291
+ '{n} memos': '메모 {n}개',
292
+ 'Which memo do you want to add as a sticker?': '어떤 메모를 스티커로 붙일까요?',
293
+ 'Node: {title}': '붙일 노드: {title}',
294
+ 'Write a new memo': '새 메모 적기',
295
+ 'What you write is kept as a new memo in the memo box and added to this node': '글을 적으면 메모함에 새 메모로 남고 이 노드에 붙습니다',
296
+ 'Pick from the memo box': '메모함의 메모 고르기',
297
+ 'Adds a memo already in the memo box to this node. No new memo is made': '메모함에 이미 있는 메모를 이 노드에 붙입니다. 메모를 새로 만들지 않습니다',
298
+ 'Reading the memo box': '메모함을 읽는 중입니다',
299
+ 'There are no other memos in the memo box to add': '메모함에 붙일 수 있는 다른 메모가 없습니다',
300
+ 'Add a memo from the memo box': '메모함의 메모 붙이기',
301
+ 'Pick one of {n} memo': '메모 {n}개 가운데 고르기',
302
+ 'Pick one of {n} memos': '메모 {n}개 가운데 고르기',
303
+ 'Write the text for the sticker': '스티커에 적을 글을 써 주세요',
304
+ 'conflict': '부딪힘',
305
+ 'Show before the change': '바뀌기 전 보기',
306
+ 'Before: ': '바뀌기 전: ',
307
+ 'Collapse memo': '메모 접기',
308
+ 'Expand memo': '메모 펼치기',
309
+ 'Memo text': '메모의 글',
310
+ 'Edit memo': '메모 고치기',
311
+ 'Enter for a new line, Ctrl+Enter to save, Esc to cancel. Marks written like [name](n3) are kept': 'Enter 는 줄 바꿈, Ctrl+Enter 로 저장, Esc 로 취소. [이름](n3) 처럼 적은 표시는 그대로 둡니다',
312
+ 'Use [Edit] to change the text here. The memo in the memo box changes too': '[고치기] 로 이 자리에서 글을 고칩니다. 메모함의 메모가 함께 바뀝니다',
313
+ 'A memo in the memo box': '메모함의 메모입니다',
314
+ 'removed node {id}': '지워진 노드 {id}',
315
+ 'Edit': '고치기',
316
+ 'Change the memo text here': '이 자리에서 메모의 글을 고칩니다',
317
+ 'Collapse': '접기',
318
+ 'Collapse the sticker': '스티커 접기',
319
+ 'Move': '옮기기',
320
+ 'Move to another node': '다른 노드에 옮겨 붙이기',
321
+ 'Remove': '떼기',
322
+ 'Remove the sticker. The memo stays in the memo box': '스티커 떼기. 메모는 메모함에 남습니다',
323
+ 'Node to move it to': '옮겨 붙일 노드',
324
+ 'Which node?': '어느 노드에 붙일까요?',
325
+ 'Click an empty part of the row to select the node and tell the AI about it. Ctrl+click selects more than one': '줄의 빈 곳을 누르면 노드를 고르고 AI 에게 말할 수 있습니다. Ctrl 을 누른 채 누르면 여러 개를 고릅니다',
326
+ 'Expand': '펼치기',
327
+ 'Drag to move. Drop on the middle of a node to put it under that node': '끌어서 옮기기. 노드 가운데에 놓으면 그 아래로 들어갑니다',
328
+ 'Drag to move {name}': '{name} 끌어서 옮기기',
329
+ 'Node name': '노드 이름',
330
+ 'Rename: {name}': '이름 바꾸기: {name}',
331
+ 'Stickers on collapsed nodes below': '접힌 아래 노드에 붙은 스티커',
332
+ '{n} sticker collapsed': '접힌 곳에 스티커 {n}',
333
+ '{n} stickers collapsed': '접힌 곳에 스티커 {n}',
334
+ 'Collapsed nodes or stickers below have changes that are not confirmed yet': '접힌 아래 노드나 스티커에 아직 확정되지 않은 변경이 있습니다',
335
+ 'changed below': '접힌 곳이 바뀜',
336
+ '+ Node': '+ 노드',
337
+ 'Add a node below': '아래에 노드 더하기',
338
+ '+ Sticker': '+ 스티커',
339
+ 'Add a sticker to this node. You are asked first whether to write a new memo or pick one from the memo box': '이 노드에 스티커 붙이기. 새 메모를 적을지 메모함의 메모를 고를지 먼저 묻습니다',
340
+ 'Move up': '위로',
341
+ 'Move down': '아래로',
342
+ 'Move out one level': '한 단계 위로 빼기',
343
+ 'It is added as soon as you pick. No new memo is made': '고르면 바로 붙습니다. 메모를 새로 만들지 않습니다',
344
+ 'Sticker text': '스티커에 적을 글',
345
+ 'Add as a new memo': '새 메모로 붙이기',
346
+ 'Add': '붙이기',
347
+ 'The text is kept as a new memo in the memo box. Enter for a new line, Ctrl+Enter to add, Esc to cancel': '글은 메모함에 새 메모로 남습니다. Enter 는 줄 바꿈, Ctrl+Enter 로 붙이기, Esc 로 취소',
348
+ 'New node name': '새 노드 이름',
349
+ 'Changes and notices': '바뀐 기록과 알림',
350
+ '{n} to look at': '손볼 것 {n}건',
351
+ 'New changes from the AI': 'AI 의 새 변경이 있습니다',
352
+ 'Tree tools': '트리 도구',
353
+ 'Things the AI changed that are not confirmed yet carry a mark. Your next operation confirms everything shown now.': 'AI 가 바꾸었고 아직 확정되지 않은 것에 표시가 붙습니다. 다음 조작을 하면 지금 보이는 데까지 확정됩니다.',
354
+ 'Expand all memos': '메모 모두 펼치기',
355
+ 'Collapse all memos': '메모 모두 접기',
356
+ 'Expand all memos: show the stickers on every node again': '메모 모두 펼치기: 모든 노드의 스티커를 다시 보입니다',
357
+ 'Collapse all memos: hide the stickers on every node. The memo count next to each node stays': '메모 모두 접기: 모든 노드의 스티커를 감춥니다. 노드 옆 메모 수는 그대로 보입니다',
358
+ 'Expand all nodes': '모든 노드 펼치기',
359
+ 'Collapse all nodes': '모든 노드 접기',
360
+ 'Tree': '트리',
361
+ 'Write the topic for the top, then split it into nodes below. You can also just tell the AI.': '맨 위에 둘 주제를 적으면 그 아래로 노드를 나눌 수 있습니다. AI 에게 말로 해도 됩니다.',
362
+ 'Topic': '주제',
363
+ 'Root': '루트',
364
+ 'Create': '만들기',
365
+ 'Add root': '루트 추가',
366
+ 'Write a topic': '주제를 적어 주세요',
367
+ 'Changes': '바뀐 기록',
368
+ 'Nothing yet.': '아직 없습니다.',
369
+ 'Read the other {n} with read_history.': '그 밖에 {n}개는 read_history 로 읽습니다.',
370
+ ' by you': ' 내가 함',
371
+ ' by the AI': ' AI 가 함',
372
+ 'not confirmed': '확정 전',
373
+ 'Show {n} older': '이전 기록 {n}개 더 보기',
374
+ 'Show older': '이전 기록 더 보기',
375
+ 'Stickers on removed nodes': '지워진 노드의 스티커',
376
+ 'Stickers stay when a node is removed. Move them to another node or remove them.': '노드를 지워도 스티커는 남습니다. 다른 노드로 옮기거나 뗍니다.',
377
+ 'Removed by the AI': 'AI 가 지운 것',
378
+ 'Conflicts': '부딪힌 것',
379
+ 'Notices': '알림',
380
+ 'This is not the screen being edited, so it is read only. To make changes, switch to this screen in the bar above.': '지금 편집하는 화면이 아니라 읽기만 합니다. 고치려면 위쪽 줄에서 이 화면으로 옮깁니다.',
381
+ '{n} nodes': '노드 {n}개',
382
+ 'Write what you want to tell the AI': 'AI 에게 할 말을 적어 주세요',
383
+ 'Could not send the selection': '고른 것을 보내지 못했습니다',
384
+ 'Sent to the AI ({id})': 'AI 에게 보냈습니다({id})',
385
+ 'What to tell the AI about the selected nodes': '고른 노드에 대해 AI 에게 할 말',
386
+ 'Tell the AI about the selected nodes': '고른 노드에 대해 AI 에게 말하기',
387
+ 'Send the selected nodes and your words to the AI': '고른 노드와 할 말을 AI 에게 보냅니다',
388
+ 'Send': '보내기',
389
+ };
390
+ function tr(en, vars) {
391
+ const s = lang === 'ko' && Object.prototype.hasOwnProperty.call(KO, en) ? KO[en] : en;
392
+ return vars ? s.replace(/\{(\w+)\}/g, (all, k) => (k in vars ? String(vars[k]) : all)) : s;
393
+ }
394
+ /** index.html 에 고정으로 적은 글. 한국어일 때 처음 한 번 바꾼다 */
395
+ function translateStatic() {
396
+ if (document.documentElement) document.documentElement.lang = lang;
397
+ if (lang === 'en') return;
398
+ document.title = tr('Tree');
399
+ const said = document.getElementById('quickSaid');
400
+ said.setAttribute('aria-label', tr('What to tell the AI about the selected nodes'));
401
+ said.setAttribute('placeholder', tr('Tell the AI about the selected nodes'));
402
+ const sendBtn = document.getElementById('quickSend');
403
+ sendBtn.setAttribute('title', tr('Send the selected nodes and your words to the AI'));
404
+ sendBtn.textContent = tr('Send');
405
+ }
406
+
407
+ function call(method, params) {
408
+ return new Promise((resolve, reject) => {
409
+ const id = nextId++;
410
+ waiting.set(id, { resolve, reject });
411
+ parent.postMessage({ aic: 1, id, method, params }, '*');
412
+ });
413
+ }
414
+
415
+ window.addEventListener('message', (e) => {
416
+ if (e.source !== parent) return;
417
+ const d = e.data;
418
+ if (typeof d !== 'object' || d === null || d.aic !== 1) return;
419
+ if (d.event === 'change') {
420
+ refresh(typeof d.rev === 'string' ? d.rev : null);
421
+ return;
422
+ }
423
+ if (d.event === 'focus') {
424
+ focused = new Set(Array.isArray(d.targets) ? d.targets.filter((x) => typeof x === 'string') : []);
425
+ if (concept) for (const id of focused) openPathTo(id);
426
+ render();
427
+ return;
428
+ }
429
+ const w = waiting.get(d.id);
430
+ if (!w) return;
431
+ waiting.delete(d.id);
432
+ if (d.error) w.reject(new Error(d.error));
433
+ else w.resolve(d.result);
434
+ });
435
+
436
+ let inflight = null;
437
+ let queued = null;
438
+ let queuedRevs = null;
439
+ function refresh(rev = null) {
440
+ if (inflight) {
441
+ (queuedRevs ??= []).push(rev);
442
+ queued ??= inflight.then(() => {
443
+ queued = null;
444
+ const revs = queuedRevs ?? [];
445
+ queuedRevs = null;
446
+ if (revs.length > 0 && concept && revs.every((r) => r !== null && seq(r) <= seq(concept.base))) return undefined;
447
+ return refresh();
448
+ });
449
+ return queued;
450
+ }
451
+ inflight = (async () => {
452
+ try {
453
+ let c;
454
+ let changes;
455
+ let memos;
456
+ // 스티커의 메모를 메모함에 묻고, 같은 기준 revision 의 응답만 쓴다(029 5.2절, 스토리 화면과 같다)
457
+ for (let tries = 0; ; tries += 1) {
458
+ [c, changes] = await Promise.all([call('readConcept'), call('readChanges', changesParams())]);
459
+ const ids = [...new Set(((c.withOthers ?? c.body).stickers ?? []).map((x) => x.memo))];
460
+ memos = ids.length ? await call('readMemos', { ids }) : { base: c.base, memos: [] };
461
+ if (memos.base === c.base || tries >= 2) break;
462
+ }
463
+ errorEl.hidden = true;
464
+ concept = c;
465
+ memoById = new Map(memos.base === c.base ? memos.memos.map((m) => [m.id, m]) : []);
466
+ feed = changes.newChanges ?? [];
467
+ // 메모가 같은 기준으로 오지 않았으면 스티커를 다 그리지 못하므로 그렸다고 알리지 않는다
468
+ drawPending = memos.base === c.base && typeof c.renderToken === 'string';
469
+ render();
470
+ } catch (err) {
471
+ errorEl.textContent = err.message;
472
+ errorEl.hidden = false;
473
+ }
474
+ })().finally(() => {
475
+ inflight = null;
476
+ });
477
+ return inflight;
478
+ }
479
+
480
+ let toastTimer = null;
481
+ function toast(text, bad = false) {
482
+ toastEl.textContent = text;
483
+ toastEl.classList.toggle('bad', bad);
484
+ toastEl.hidden = false;
485
+ clearTimeout(toastTimer);
486
+ toastTimer = setTimeout(() => { toastEl.hidden = true; }, bad ? 7000 : 3500);
487
+ }
488
+
489
+ let lastOwn = null;
490
+ const seq = (rev) => Number(String(rev).slice(1));
491
+ async function send(steps, opts = {}) {
492
+ let base = opts.base ?? concept.base;
493
+ if (lastOwn && seq(lastOwn) > seq(base)) base = lastOwn;
494
+ const req = { base, steps, ...(opts.resolves ? { resolves: opts.resolves } : {}), ...(opts.take ? { take: opts.take } : {}) };
495
+ let res;
496
+ try {
497
+ res = await call('applyOperation', req);
498
+ } catch (err) {
499
+ toast(err.message, true);
500
+ return null;
501
+ }
502
+ if (!res.ok) {
503
+ toast(res.summary ?? res.error, true);
504
+ await refresh();
505
+ return null;
506
+ }
507
+ lastOwn = res.revision;
508
+ if (res.withdrawn?.length) toast(tr('Changes withdrawn: {list}', { list: res.withdrawn.join(', ') }));
509
+ await refresh(res.revision);
510
+ return res;
511
+ }
512
+
513
+ function el(tag, props, ...children) {
514
+ const n = document.createElement(tag);
515
+ for (const [k, v] of Object.entries(props ?? {})) {
516
+ if (k === 'class') n.className = v;
517
+ else if (k === 'on') for (const [ev, fn] of Object.entries(v)) n.addEventListener(ev, fn);
518
+ else if (k === 'value') n.value = v;
519
+ else if (v !== false && v !== null && v !== undefined) n.setAttribute(k, v === true ? '' : v);
520
+ }
521
+ for (const c of children.flat(Infinity)) {
522
+ if (c === null || c === undefined || c === false) continue;
523
+ n.append(c instanceof Node ? c : String(c));
524
+ }
525
+ return n;
526
+ }
527
+ const btn = (label, onClick, cls = 'btn', extra = {}) => el('button', { type: 'button', class: cls, on: { click: onClick }, ...extra }, label);
528
+ // 도구 줄의 아이콘(코어 위쪽 줄과 같은 선 아이콘). 이름은 title 과 aria-label 에 둔다
529
+ const ICON = {
530
+ memo: 'M4 4h16v11l-5 5H4z M15 20v-5h5 M8 9h8 M8 13h5',
531
+ expand: 'M7 6l5 5 5-5 M7 13l5 5 5-5',
532
+ collapse: 'M7 11l5-5 5 5 M7 18l5-5 5 5',
533
+ help: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.6.3-1 .9-1 1.6v.4 M12 17h.01',
534
+ side: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z M12 7v5l3 2',
535
+ };
536
+ function svgIcon(name) {
537
+ const s = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
538
+ s.setAttribute('viewBox', '0 0 24 24');
539
+ s.setAttribute('aria-hidden', 'true');
540
+ const p = document.createElementNS('http://www.w3.org/2000/svg', 'path');
541
+ p.setAttribute('d', ICON[name]);
542
+ s.append(p);
543
+ return s;
544
+ }
545
+ const iconBtn = (name, label, onClick, extra = {}, ...more) => el('button', { type: 'button', class: 'icon-btn', 'aria-label': label, title: extra.title ?? label, on: onClick ? { click: onClick } : {}, ...extra }, svgIcon(name), ...more);
546
+
547
+ function deleteButton(key, label, onConfirm) {
548
+ const on = armed.get(key);
549
+ return el('button', {
550
+ type: 'button', class: `icon${on ? ' armed' : ''}`, 'aria-label': label, title: label,
551
+ on: { click: () => {
552
+ if (armed.get(key)) { armed.delete(key); onConfirm(); return; }
553
+ armed.set(key, true);
554
+ setTimeout(() => { if (armed.delete(key)) render(); }, 3000);
555
+ render();
556
+ } },
557
+ }, on ? tr('Remove?') : '×');
558
+ }
559
+
560
+ const actionLabel = (a) => ({ add: tr('new'), update: tr('changed'), move: tr('moved'), remove: tr('removed') })[a] ?? a;
561
+ const feedKind = (type, n = 1) => ({
562
+ node: n === 1 ? tr('node') : tr('nodes'), sticker: n === 1 ? tr('sticker') : tr('stickers'),
563
+ memo: n === 1 ? tr('memo') : tr('memos'), instance: n === 1 ? tr('screen') : tr('screens'),
564
+ })[type] ?? type;
565
+ const feedVerb = (a) => ({ add: tr('added'), update: tr('changed'), move: tr('moved'), remove: tr('removed') })[a] ?? a;
566
+ const FEED_ORDER = ['node', 'sticker', 'memo', 'instance'];
567
+ const FEED_PAGE = 10;
568
+ const FEED_DETAIL_MAX = 30;
569
+ const openFeed = new Set();
570
+ let feedShown = FEED_PAGE;
571
+ let feedFrom = null;
572
+ const changesParams = () => {
573
+ const from = concept?.base ? seq(concept.base) - (feedShown * 3 + 20) : 0;
574
+ feedFrom = from >= 1 ? `h${from}` : null;
575
+ return feedFrom ? { since: feedFrom } : {};
576
+ };
577
+
578
+ /** 읽은 JSON 을 찾기 쉬운 모양으로 */
579
+ function model() {
580
+ const b = concept.withOthers ?? concept.body;
581
+ const m = { root: b.root, node: new Map(b.nodes.map((t) => [t.id, t])), kids: new Map(), stickers: new Map(), sticker: new Map(b.stickers.map((x) => [x.id, x])), orphans: [] };
582
+ const push = (map, k, v) => { if (!map.has(k)) map.set(k, []); map.get(k).push(v); };
583
+ for (const t of b.nodes) if (t.parent !== null) push(m.kids, t.parent, t);
584
+ for (const x of b.stickers) {
585
+ // 지워진 메모의 스티커는 그리지 않는다(999 2.1절)
586
+ if (memoById.get(x.memo)?.deleted) continue;
587
+ if (m.node.has(x.node)) push(m.stickers, x.node, x);
588
+ else m.orphans.push(x);
589
+ }
590
+ return m;
591
+ }
592
+
593
+ function ancestorsOf(m, id) {
594
+ const out = [];
595
+ const seen = new Set([id]);
596
+ let p = m.node.get(id)?.parent ?? null;
597
+ while (p !== null && m.node.has(p) && !seen.has(p)) { out.unshift(p); seen.add(p); p = m.node.get(p).parent; }
598
+ return out;
599
+ }
600
+ function subtreeOf(m, id) {
601
+ const out = [id];
602
+ 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);
603
+ return out;
604
+ }
605
+ function nodeOfRecord(m, id) {
606
+ if (m.node.has(id)) return id;
607
+ const st = m.sticker.get(id);
608
+ return st && m.node.has(st.node) ? st.node : null;
609
+ }
610
+ function openPathTo(id) {
611
+ const m = model();
612
+ const t = nodeOfRecord(m, id);
613
+ if (!t) return;
614
+ for (const a of ancestorsOf(m, t)) expanded.add(a);
615
+ }
616
+
617
+ /** 처음 보는 노드만 펼칠지 정한다. 뿌리 아래 첫 단계만 펼친다 */
618
+ function autoExpand(m) {
619
+ for (const t of m.node.values()) {
620
+ if (seenNodes.has(t.id)) continue;
621
+ seenNodes.add(t.id);
622
+ if (t.parent === null) expanded.add(t.id);
623
+ }
624
+ }
625
+
626
+ function computeMarks() {
627
+ const marks = new Map();
628
+ const removed = [];
629
+ const c = concept;
630
+ const latest = c.othersPending.length ? c.othersPending[c.othersPending.length - 1].revision : null;
631
+ for (const p of c.othersPending) {
632
+ for (const ch of p.changes) {
633
+ const prev = marks.get(ch.record);
634
+ marks.set(ch.record, {
635
+ action: prev && prev.action === 'add' && ch.after !== null ? 'add' : ch.action,
636
+ before: prev ? prev.before : ch.before,
637
+ type: ch.type, owner: ch.owner, revision: p.revision, recent: p.revision === latest,
638
+ });
639
+ }
640
+ }
641
+ const held = new Set(c.conflicts.map((x) => x.record));
642
+ for (const id of held) marks.delete(id);
643
+ for (const [id, mk] of marks) {
644
+ if (mk.action === 'remove' && mk.before !== null) removed.push({ id, ...mk });
645
+ if (mk.action === 'remove') marks.delete(id);
646
+ }
647
+ return { marks, removed, held };
648
+ }
649
+
650
+ /** 메모의 글. 코어의 글 조각은 글이거나 { ref, text } 다 */
651
+ function memoText(memo) {
652
+ if (!memo) return el('span', { class: 'mid' }, tr('Reading the memo'));
653
+ if (memo.external) return memo.display ?? tr('[External result: {tool}]', { tool: memo.external.tool });
654
+ const gone = new Map((memo.targets ?? []).map((t) => [t.id, t]));
655
+ return (memo.text ?? []).map((s) => {
656
+ if (typeof s === 'string') return s;
657
+ const g = gone.get(s.ref);
658
+ return g?.deleted ? el('span', { class: 'gone', title: tr('Removed target') }, tr('{text} (removed {type})', { text: s.text, type: g.type ?? tr('target') })) : s.text;
659
+ });
660
+ }
661
+
662
+ function describeContent(content) {
663
+ if (content === null || content === undefined) return tr('Removed');
664
+ if (typeof content === 'object') {
665
+ if (typeof content.title === 'string') return content.title;
666
+ if ('memo' in content && 'node' in content) {
667
+ const memo = memoById.get(content.memo);
668
+ const text = memo && Array.isArray(memo.text) ? memo.text.map((s) => (typeof s === 'string' ? s : s.text)).join('') : content.memo;
669
+ return tr('Sticker: {text}', { text });
670
+ }
671
+ if (Array.isArray(content.text)) return content.text.map((s) => (typeof s === 'string' ? s : s.text)).join('');
672
+ if (typeof content.text === 'string') return content.text;
673
+ }
674
+ return JSON.stringify(content);
675
+ }
676
+
677
+ function conflictCard(c) {
678
+ const me = concept.me;
679
+ const group = [c, ...concept.conflicts.filter((x) => x !== c && x.sides.some((s) => c.sides.some((y) => y.revision === s.revision)))];
680
+ const ids = group.map((x) => x.id);
681
+ const mine = c.sides.find((s) => s.participant === me);
682
+ const theirs = c.sides.find((s) => s.participant !== me);
683
+ const summaryOf = (rev) => [...concept.othersPending, ...concept.myPending].find((p) => p.revision === rev)?.summary;
684
+ const theirSummary = theirs ? summaryOf(theirs.revision) : null;
685
+ const mySummary = mine ? summaryOf(mine.revision) : null;
686
+ return el('div', { class: 'conflict', 'data-conflict': c.id },
687
+ el('h3', {}, c.reason === 'same_record' ? tr('The same thing was changed in two ways') : tr('What this points to was removed'), group.length > 1 ? tr(' (resolves {n} together)', { n: group.length }) : ''),
688
+ el('div', { class: 'sides' }, [mine, theirs].filter(Boolean).map((s) =>
689
+ el('div', { class: 'side' }, el('b', {}, s === mine ? tr('Yours') : (s.name ?? tr('Theirs'))), describeContent(s.content)))),
690
+ theirSummary ? el('p', { class: 'warn' }, tr('If you keep yours, this whole change by {name} is canceled: {summary}', { name: theirs.name ?? tr('the other participant'), summary: theirSummary })) : null,
691
+ mySummary ? el('p', { class: 'warn' }, tr('If you keep theirs, this whole change of yours is canceled: {summary}', { summary: mySummary })) : null,
692
+ el('div', { class: 'actions' },
693
+ btn(tr('Keep yours'), () => send([], { resolves: ids, take: 'mine' }), 'btn primary'),
694
+ theirs ? btn(theirs.name ? tr('Keep {name}', { name: theirs.name }) : tr('Keep theirs'), () => send([], { resolves: ids, take: 'theirs' })) : null),
695
+ );
696
+ }
697
+
698
+ // 쓰는 칸. 칸마다 data-field 를 달아 다시 그려도 글과 커서를 잃지 않는다.
699
+ function startEdit(e) {
700
+ armed.clear();
701
+ editor = { base: concept.base, values: {}, ...e };
702
+ render();
703
+ }
704
+ function closeEditor() {
705
+ editor = null;
706
+ render();
707
+ }
708
+ async function saveEditor() {
709
+ const e = editor;
710
+ if (!e || committing) return;
711
+ const steps = e.build(e.values);
712
+ if (steps === null) return; // build 가 까닭을 알렸다
713
+ if (!steps.length) { closeEditor(); return; }
714
+ committing = true;
715
+ const res = await send(steps, { base: e.base });
716
+ committing = false;
717
+ if (editor === e) {
718
+ if (res) editor = null;
719
+ else e.base = concept.base;
720
+ }
721
+ render();
722
+ }
723
+
724
+ function input(name, placeholder, opts = {}) {
725
+ const e = editor;
726
+ const tag = opts.rows ? 'textarea' : 'input';
727
+ const box = el(tag, {
728
+ ...(opts.rows ? { rows: opts.rows } : { type: 'text' }),
729
+ placeholder, 'aria-label': opts.label ?? placeholder, 'data-field': name, value: e.values[name] ?? '',
730
+ on: {
731
+ input: (ev) => { e.values[name] = ev.target.value; },
732
+ compositionstart: () => { composing = true; },
733
+ compositionend: (ev) => { composing = false; e.values[name] = ev.target.value; if (renderWanted) render(); },
734
+ keydown: (ev) => {
735
+ if (ev.isComposing) return;
736
+ if (ev.key === 'Escape') { ev.preventDefault(); closeEditor(); }
737
+ // 여러 줄 칸(메모 글)은 Enter 가 줄 바꿈이고, Ctrl+Enter(맥은 Cmd+Enter)로 저장한다(rawdev 2026-11-14). 한 줄 칸은 Enter 로 저장한다
738
+ const save = opts.rows ? ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey) : ev.key === 'Enter';
739
+ if (save) { ev.preventDefault(); e.values[name] = ev.target.value; saveEditor(); }
740
+ },
741
+ },
742
+ });
743
+ return opts.label ? el('label', {}, el('span', {}, opts.label), box) : box;
744
+ }
745
+ const saveRow = (label = tr('Save'), hint = tr('Enter to save, Esc to cancel')) => el('div', { class: 'actions' }, btn(label, saveEditor, 'btn primary'), btn(tr('Cancel'), closeEditor), el('span', { class: 'hint' }, hint));
746
+
747
+ /**
748
+ * 메모의 글을 고칠 수 있는 글로 바꾼다. 호스트 메모함의 toEditableMemo 와 같은 모양이다. 대괄호와 역빗금은 앞에 역빗금을 붙이고,
749
+ * 표시는 [글](id) 로, 지워진 대상의 표시는 [글](id, 지워진 종류) 로 적는다. core.memo.update 가 이 글을 다시 읽는다.
750
+ */
751
+ function toEditableMemo(memo) {
752
+ const deleted = new Map((memo.targets ?? []).filter((t) => t.deleted).map((t) => [t.id, t.type ?? 'target']));
753
+ const esc = (x) => x.replace(/[\\[\]]/g, (c) => `\\${c}`);
754
+ return (memo.text ?? []).map((s) => {
755
+ if (typeof s === 'string') return esc(s);
756
+ const gone = deleted.get(s.ref);
757
+ return `[${esc(s.text)}](${s.ref}${gone ? `, removed ${gone}` : ''})`;
758
+ }).join('');
759
+ }
760
+
761
+ /**
762
+ * 스티커 안에서 메모의 글을 고친다(rawdev 2026-11-14, "그냥 tree에서 수정하게 하자"). 다른 조작과 같은 그린 기준으로
763
+ * core.memo.update 를 보낸다. 거절되면 saveEditor 가 고치던 글을 그대로 두고 까닭을 알린다.
764
+ */
765
+ function startMemoEdit(st, memo) {
766
+ stickerOpen = st.id;
767
+ startEdit({ key: `memo-${st.id}`, memo: st.memo, values: { text: toEditableMemo(memo) }, build: (v) => {
768
+ const text = (v.text ?? '').trim();
769
+ if (!text && !memo.external) { toast(tr('The memo text is empty. To remove the memo, remove it in the memo box'), true); return null; }
770
+ return text === toEditableMemo(memo).trim() ? [] : [{ op: 'core.memo.update', input: { memo: st.memo, text } }];
771
+ } });
772
+ }
773
+ /** 지금 글을 고치는 스티커의 노드. 고치는 동안은 접기와 [메모 모두 접기] 가 그 칸을 닫지 않는다. */
774
+ const memoEditingIn = (m) => {
775
+ const k = editor?.key;
776
+ if (!k || !k.startsWith('memo-')) return null;
777
+ return m.sticker.get(k.slice(5)) ?? null;
778
+ };
779
+
780
+ /** 노드에 스티커를 붙이는 요청. 본체가 될 새 메모를 같은 요청에서 만든다(999 2.1절, tree.md). */
781
+
782
+ /** 노드 옆에 늘 나오는 "메모 N개". 누르면 그 노드의 스티커를 감추거나 다시 보인다. */
783
+ function memoCount(nodeId, n) {
784
+ const shown = stickersVisible(nodeId);
785
+ return el('button', {
786
+ type: 'button', class: 'badge note memo-count', 'aria-expanded': String(shown),
787
+ title: shown ? tr('Hide the stickers on this node') : tr('Show the stickers on this node'),
788
+ on: { click: () => {
789
+ if (stickersFlipped.has(nodeId)) stickersFlipped.delete(nodeId); else stickersFlipped.add(nodeId);
790
+ render();
791
+ } },
792
+ }, n === 1 ? tr('{n} memo', { n }) : tr('{n} memos', { n }));
793
+ }
794
+
795
+ /**
796
+ * [+ 스티커] 를 누르면 먼저 새 메모를 적을지 메모함의 메모를 붙일지 묻는다(rawdev 2026-11-22). 두 방법이 한 칸에 함께 있을 때
797
+ * 아래쪽의 메모함 목록이 눈에 띄지 않아 이미 있는 글을 새 메모로 또 만들었다.
798
+ */
799
+ function askSticker(nodeId, key, title) {
800
+ if (editor) editor = null;
801
+ stickerAsk = { nodeId, key, title };
802
+ render();
803
+ }
804
+ function closeStickerAsk() {
805
+ stickerAsk = null;
806
+ render();
807
+ }
808
+ function stickerAskView() {
809
+ if (!stickerAsk) return null;
810
+ const { nodeId, key, title } = stickerAsk;
811
+ const pick = (mode) => { stickerAsk = null; openStickerForm(nodeId, key, mode); };
812
+ return el('div', { class: 'modal-back', on: { click: (ev) => { if (ev.target === ev.currentTarget) closeStickerAsk(); } } },
813
+ el('div', { class: 'modal', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'sticker-ask-title',
814
+ on: { keydown: (ev) => { if (ev.key === 'Escape') { ev.preventDefault(); closeStickerAsk(); } } } },
815
+ el('h3', { id: 'sticker-ask-title' }, tr('Which memo do you want to add as a sticker?')),
816
+ el('p', { class: 'hint' }, tr('Node: {title}', { title })),
817
+ el('div', { class: 'actions' },
818
+ btn(tr('Write a new memo'), () => pick('new'), 'btn primary', { 'data-ask': 'new', title: tr('What you write is kept as a new memo in the memo box and added to this node') }),
819
+ btn(tr('Pick from the memo box'), () => pick('existing'), 'btn', { 'data-ask': 'existing', title: tr('Adds a memo already in the memo box to this node. No new memo is made') }),
820
+ btn(tr('Cancel'), closeStickerAsk))));
821
+ }
822
+
823
+ /** 스티커 칸을 연다. mode 가 existing 이면 메모함 전체를 읽어 고르게 한다. */
824
+ async function openStickerForm(nodeId, key, mode = 'new') {
825
+ memoChoices = null;
826
+ startEdit({ key, mode, values: {}, build: (v) => stickerSteps(nodeId, v) });
827
+ if (mode !== 'existing') return;
828
+ try {
829
+ const res = await call('readMemos', {});
830
+ if (editor?.key === key) { memoChoices = res.memos.filter((m) => !m.deleted); render(); }
831
+ } catch (err) {
832
+ toast(err.message, true);
833
+ }
834
+ }
835
+
836
+ const memoLine = (m) => {
837
+ const text = m.external ? (m.display ?? tr('[External result: {tool}]', { tool: m.external.tool })) : (m.text ?? []).map((s) => (typeof s === 'string' ? s : s.text)).join('');
838
+ const one = text.replace(/\s+/g, ' ').trim();
839
+ return `${m.id}: ${[...one].length > 60 ? `${[...one].slice(0, 60).join('')}...` : one}`;
840
+ };
841
+
842
+ /** 메모함에 있는 메모를 이 노드에 붙인다. 메모를 새로 만들지 않는다. 이미 이 노드에 붙은 메모는 빼고 보인다. */
843
+ function memoPicker(nodeId, stuck) {
844
+ if (memoChoices === null) return el('p', { class: 'hint' }, tr('Reading the memo box'));
845
+ const here = new Set(stuck.map((x) => x.memo));
846
+ const choices = memoChoices.filter((m) => !here.has(m.id));
847
+ if (!choices.length) return el('p', { class: 'hint' }, tr('There are no other memos in the memo box to add'));
848
+ return el('label', {}, el('span', {}, tr('Pick from the memo box')),
849
+ el('select', { 'aria-label': tr('Add a memo from the memo box'), on: { change: (ev) => {
850
+ const v = ev.target.value;
851
+ if (!v) return;
852
+ closeEditor();
853
+ send([{ op: 'sticker.add', input: { memo: v, node: nodeId } }]);
854
+ } } }, el('option', { value: '' }, choices.length === 1 ? tr('Pick one of {n} memo', { n: 1 }) : tr('Pick one of {n} memos', { n: choices.length })), choices.map((m) => el('option', { value: m.id }, memoLine(m)))));
855
+ }
856
+
857
+ function stickerSteps(nodeId, v) {
858
+ const text = (v.text ?? '').trim();
859
+ if (!text) { toast(tr('Write the text for the sticker'), true); return null; }
860
+ return [{ op: 'core.memo.add', as: '$memo', input: { text } }, { op: 'sticker.add', input: { memo: '$memo', node: nodeId } }];
861
+ }
862
+
863
+ function render() {
864
+ if (!concept) return;
865
+ if (composing || dragging || committing) { renderWanted = true; return; }
866
+ renderWanted = false;
867
+ const active = document.activeElement;
868
+ const field = active?.dataset?.field;
869
+ const sel = field && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
870
+
871
+ const c = concept;
872
+ const m = model();
873
+ picked = picked.filter((id) => m.node.has(id));
874
+ const { marks, removed, held } = computeMarks();
875
+ autoExpand(m);
876
+ // 편집 인스턴스가 아니거나 읽기만 하는 보조 보기(capabilities().edit 가 거짓)면 고치는 도구를 숨긴다
877
+ const readOnly = !canEdit || Boolean(c.editing && c.instance && c.editing.id !== c.instance);
878
+ const conflictsOn = (id) => c.conflicts.filter((x) => x.record === id);
879
+ const markClass = (id) => {
880
+ const mk = marks.get(id);
881
+ return mk ? ` m-${mk.action}${mk.recent ? '' : ' old'}` : '';
882
+ };
883
+ const tag = (id) => {
884
+ if (held.has(id)) return el('span', { class: 'tag remove' }, tr('conflict'));
885
+ const mk = marks.get(id);
886
+ return mk ? el('span', { class: `tag ${mk.action}` }, actionLabel(mk.action)) : null;
887
+ };
888
+ const beforeToggle = (id) => {
889
+ const mk = marks.get(id);
890
+ if (!(mk && mk.action === 'update' && mk.before)) return tag(id);
891
+ return el('button', { type: 'button', class: 'tag update', 'aria-expanded': openBefore.has(id) ? 'true' : 'false', title: tr('Show before the change'), on: { click: (ev) => {
892
+ ev.stopPropagation();
893
+ if (openBefore.has(id)) openBefore.delete(id); else openBefore.add(id);
894
+ render();
895
+ } } }, actionLabel('update'));
896
+ };
897
+ const beforeView = (id) => {
898
+ const mk = marks.get(id);
899
+ return mk && mk.action === 'update' && mk.before && openBefore.has(id) ? el('div', { class: 'before' }, tr('Before: '), describeContent(mk.before)) : null;
900
+ };
901
+ const allNodes = [...m.node.values()];
902
+
903
+ // 스티커 하나. 글은 메모함의 메모이고, 고치는 것은 메모함에서 한다
904
+ const stickerView = (st) => {
905
+ const moving = editor?.key === `attach-${st.id}`;
906
+ const memo = memoById.get(st.memo);
907
+ // 옮길 노드를 고르는 중이면 펼쳐 둔다
908
+ const editingMemo = editor?.key === `memo-${st.id}`;
909
+ // 옮길 노드를 고르거나 글을 고치는 중이면 펼쳐 둔다
910
+ const open = stickerOpen === st.id || moving || editingMemo;
911
+ // 한 번 더 누르면 접힌다. 안의 버튼이나 목록을 누른 때와, 펼친 글을 끌어 고르는 중일 때는 그대로 둔다
912
+ const toggle = (ev) => {
913
+ if (editingMemo) return; // 고치는 동안은 접지 않는다
914
+ if (ev.target?.closest?.('button, a, select, textarea, input')) return;
915
+ if (open && String(window.getSelection?.() ?? '') !== '') return;
916
+ stickerOpen = open ? null : st.id;
917
+ render();
918
+ };
919
+ return el('div', {
920
+ class: `sticker has-mini${open ? ' open' : ' closed'}${markClass(st.id)}`, 'data-sticker': st.id, 'data-target': st.id,
921
+ tabindex: '0', role: 'button', 'aria-expanded': String(open), 'aria-label': open ? tr('Collapse memo') : tr('Expand memo'),
922
+ on: { click: toggle, keydown: (ev) => { if (ev.target === ev.currentTarget && (ev.key === 'Enter' || ev.key === ' ')) { ev.preventDefault(); toggle(ev); } } },
923
+ },
924
+ editingMemo
925
+ ? el('div', { class: 'form bare' }, input('text', tr('Memo text'), { rows: 4, label: tr('Edit memo') }), saveRow(tr('Save'), tr('Enter for a new line, Ctrl+Enter to save, Esc to cancel. Marks written like [name](n3) are kept')))
926
+ : el('div', { class: 'memo-text', title: canEdit ? tr('Use [Edit] to change the text here. The memo in the memo box changes too') : tr('A memo in the memo box') }, memoText(memo)),
927
+ el('div', { class: 'bar' },
928
+ el('span', { class: 'mid ref' }, st.memo),
929
+ m.node.has(st.node) ? null : el('span', { class: 'mid' }, tr('removed node {id}', { id: st.node })),
930
+ tag(st.id),
931
+ el('span', { style: 'margin-left:auto;display:inline-flex' },
932
+ // 메모 글은 이 스티커 안에서 고친다. 접혀 있어도 누를 수 있고, 누른 것은 접고 펴는 동작으로 치지 않는다(rawdev 2026-11-14)
933
+ canEdit && memo && !editingMemo ? btn(tr('Edit'), () => startMemoEdit(st, memo), 'icon edit-memo', { title: tr('Change the memo text here') }) : null,
934
+ el('span', { class: 'mini', style: 'display:inline-flex' },
935
+ editingMemo ? null : btn(tr('Collapse'), () => { stickerOpen = null; if (moving) closeEditor(); else render(); }, 'icon', { title: tr('Collapse the sticker') }),
936
+ readOnly ? null : btn(tr('Move'), () => { stickerOpen = st.id; startEdit({ key: `attach-${st.id}`, values: {}, build: () => [] }); }, 'icon', { title: tr('Move to another node') }),
937
+ readOnly ? null : btn(tr('Remove'), () => send([{ op: 'sticker.remove', input: { sticker: st.id } }]), 'icon', { title: tr('Remove the sticker. The memo stays in the memo box') })))),
938
+ moving ? el('div', { class: 'form bare' }, el('select', { 'aria-label': tr('Node to move it to'), on: { change: (ev) => {
939
+ const v = ev.target.value;
940
+ if (v) { closeEditor(); send([{ op: 'sticker.attach', input: { sticker: st.id, node: v } }]); }
941
+ } } }, el('option', { value: '' }, tr('Which node?')), allNodes.filter((x) => x.id !== st.node).map((x) => el('option', { value: x.id }, x.title))), btn(tr('Cancel'), closeEditor)) : null,
942
+ conflictsOn(st.id).map(conflictCard),
943
+ );
944
+ };
945
+
946
+ // 노드 하나
947
+ // 글을 고치는 스티커가 붙은 노드. [메모 모두 접기] 중에도 그 노드의 스티커는 보여 고치던 글을 잃지 않게 한다
948
+ const editNode = memoEditingIn(m)?.node ?? null;
949
+ const nodeView = (t, siblings) => {
950
+ const kids = m.kids.get(t.id) ?? [];
951
+ const stickers = m.stickers.get(t.id) ?? [];
952
+ const isRoot = t.parent === null;
953
+ const open = expanded.has(t.id);
954
+ const i = siblings.indexOf(t);
955
+ const key = (k) => `${k}-${t.id}`;
956
+ // 접힌 노드 안의 스티커와 다른 참여자의 변경
957
+ let hiddenStickers = 0;
958
+ let hiddenChange = false;
959
+ if (!open) {
960
+ for (const id of subtreeOf(m, t.id)) {
961
+ if (id === t.id) continue;
962
+ const sts = m.stickers.get(id) ?? [];
963
+ hiddenStickers += sts.length;
964
+ if (marks.has(id) || sts.some((x) => marks.has(x.id))) hiddenChange = true;
965
+ }
966
+ }
967
+ const renaming = editor?.key === key('rename');
968
+ const adding = editor?.key === key('child');
969
+ const sticking = editor?.key === key('sticker');
970
+ const canOpen = kids.length > 0;
971
+ const row = el('div', {
972
+ class: `row${isRoot ? ' root' : ''}${focused.has(t.id) ? ' focus' : ''}${picked.includes(t.id) ? ' picked' : ''}${markClass(t.id)}`,
973
+ title: readOnly || !caps.conceptSelection ? null : tr('Click an empty part of the row to select the node and tell the AI about it. Ctrl+click selects more than one'),
974
+ 'data-node': t.id, 'data-target': t.id,
975
+ on: readOnly ? {} : {
976
+ click: (ev) => pickRow(ev, t.id),
977
+ dragover: (ev) => {
978
+ if (dragging?.kind !== 'node' || subtreeOf(m, dragging.id).includes(t.id)) return;
979
+ ev.preventDefault();
980
+ const r = ev.currentTarget.getBoundingClientRect();
981
+ const y = (ev.clientY - r.top) / r.height;
982
+ clearDrop();
983
+ // 뿌리 앞뒤로는 옮기지 못한다. 뿌리에는 가운데로만 넣는다
984
+ ev.currentTarget.classList.add(isRoot ? 'drop-in' : y < 0.25 ? 'drop-before' : y > 0.75 ? 'drop-after' : 'drop-in');
985
+ },
986
+ dragleave: (ev) => ev.currentTarget.classList.remove('drop-before', 'drop-after', 'drop-in'),
987
+ drop: (ev) => {
988
+ const d = dragging;
989
+ if (d?.kind !== 'node') return;
990
+ ev.preventDefault();
991
+ const cl = ev.currentTarget.classList;
992
+ const where = cl.contains('drop-in') ? 'in' : cl.contains('drop-before') ? 'before' : 'after';
993
+ endDrag();
994
+ if (where === 'in') {
995
+ expanded.add(t.id);
996
+ send([{ op: 'node.move', input: { node: d.id, parent: t.id } }]);
997
+ return;
998
+ }
999
+ const others = siblings.filter((x) => x.id !== d.id);
1000
+ const at = others.findIndex((x) => x.id === t.id);
1001
+ const after = where === 'before' ? (at > 0 ? others[at - 1].id : null) : t.id;
1002
+ send([{ op: 'node.move', input: { node: d.id, parent: t.parent, after } }]);
1003
+ },
1004
+ },
1005
+ },
1006
+ el('button', { type: 'button', class: 'toggle', 'aria-expanded': open ? 'true' : 'false', 'aria-label': open ? tr('Collapse') : tr('Expand'), disabled: !canOpen, on: { click: () => {
1007
+ if (open) expanded.delete(t.id); else expanded.add(t.id);
1008
+ render();
1009
+ } } }, canOpen ? (open ? '▾' : '▸') : '·'),
1010
+ // 읽기만 할 때도 끌기 손잡이 자리를 비워 두어 이름과 스티커가 주 화면과 같은 곳에 놓이게 한다
1011
+ readOnly && !isRoot ? el('span', { class: 'grip', 'aria-hidden': 'true', style: 'visibility:hidden' }, '⠿') : null,
1012
+ readOnly || isRoot ? null : el('button', { type: 'button', class: 'grip', draggable: 'true', title: tr('Drag to move. Drop on the middle of a node to put it under that node'), 'aria-label': tr('Drag to move {name}', { name: t.title }), on: {
1013
+ dragstart: (ev) => {
1014
+ dragging = { kind: 'node', id: t.id };
1015
+ document.getElementById('quickTalk').hidden = true;
1016
+ ev.dataTransfer.effectAllowed = 'move';
1017
+ ev.dataTransfer.setData('text/plain', t.id);
1018
+ ev.currentTarget.closest('.row').classList.add('dragging');
1019
+ },
1020
+ dragend: () => endDrag(),
1021
+ } }, '⠿'),
1022
+ el('div', { class: 'row-main' },
1023
+ renaming
1024
+ ? el('div', { class: 'inline' }, input('title', tr('Node name')))
1025
+ : el('span', { class: 'title', tabindex: readOnly ? null : 0, role: readOnly ? null : 'button', 'aria-label': readOnly ? null : tr('Rename: {name}', { name: t.title }), on: readOnly ? {} : {
1026
+ click: () => startRename(t),
1027
+ keydown: (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); startRename(t); } },
1028
+ } }, t.title),
1029
+ stickers.length ? memoCount(t.id, stickers.length) : null,
1030
+ hiddenStickers ? el('span', { class: 'badge note', title: tr('Stickers on collapsed nodes below') }, hiddenStickers === 1 ? tr('{n} sticker collapsed', { n: 1 }) : tr('{n} stickers collapsed', { n: hiddenStickers })) : null,
1031
+ hiddenChange ? el('span', { class: 'badge hidden-change', title: tr('Collapsed nodes or stickers below have changes that are not confirmed yet') }, tr('changed below')) : null,
1032
+ beforeToggle(t.id),
1033
+ ),
1034
+ el('span', { class: 'nid' }, t.id),
1035
+ el('div', { class: 'tools' },
1036
+ readOnly ? null : btn(tr('+ Node'), () => { expanded.add(t.id); startEdit({ key: key('child'), values: {}, build: (v) => {
1037
+ const title = (v.title ?? '').trim();
1038
+ return title ? [{ op: 'node.add', input: { parent: t.id, title } }] : [];
1039
+ } }); }, 'icon', { title: tr('Add a node below') }),
1040
+ readOnly ? null : btn(tr('+ Sticker'), () => askSticker(t.id, key('sticker'), t.title), 'icon', { title: tr('Add a sticker to this node. You are asked first whether to write a new memo or pick one from the memo box') }),
1041
+ !readOnly && !isRoot && i > 0 ? btn('↑', () => send([{ op: 'node.move', input: { node: t.id, parent: t.parent, after: i > 1 ? siblings[i - 2].id : null } }]), 'icon', { 'aria-label': tr('Move up'), title: tr('Move up') }) : null,
1042
+ !readOnly && !isRoot && i < siblings.length - 1 ? btn('↓', () => send([{ op: 'node.move', input: { node: t.id, parent: t.parent, after: siblings[i + 1].id } }]), 'icon', { 'aria-label': tr('Move down'), title: tr('Move down') }) : null,
1043
+ !readOnly && !isRoot && m.node.get(t.parent)?.parent !== null && m.node.get(t.parent)?.parent !== undefined
1044
+ ? btn('←', () => send([{ op: 'node.move', input: { node: t.id, parent: m.node.get(t.parent).parent, after: t.parent } }]), 'icon', { 'aria-label': tr('Move out one level'), title: tr('Move out one level') }) : null,
1045
+ readOnly || isRoot ? null : deleteButton(key('del'), tr('Remove node'), () => send([{ op: 'node.remove', input: { node: t.id } }])),
1046
+ ),
1047
+ );
1048
+ return el('li', { class: 'node', 'data-li': t.id },
1049
+ row,
1050
+ beforeView(t.id),
1051
+ conflictsOn(t.id).map(conflictCard),
1052
+ stickers.length && (stickersVisible(t.id) || editNode === t.id) ? el('div', { class: 'stickers' }, stickers.map(stickerView)) : null,
1053
+ sticking && editor.mode === 'existing' ? el('div', { class: 'form' },
1054
+ memoPicker(t.id, stickers),
1055
+ el('div', { class: 'actions' }, btn(tr('Cancel'), closeEditor), el('span', { class: 'hint' }, tr('It is added as soon as you pick. No new memo is made')))) : null,
1056
+ sticking && editor.mode !== 'existing' ? el('div', { class: 'form' },
1057
+ input('text', tr('Sticker text'), { rows: 2, label: tr('Add as a new memo') }),
1058
+ saveRow(tr('Add'), tr('The text is kept as a new memo in the memo box. Enter for a new line, Ctrl+Enter to add, Esc to cancel'))) : null,
1059
+ open && (kids.length || adding) ? el('ul', { class: 'children' }, kids.map((k) => nodeView(k, kids)), adding ? el('li', {}, el('div', { class: 'row' }, el('span', { class: 'toggle' }, '·'), el('div', { class: 'inline' }, input('title', tr('New node name'))))) : null) : null,
1060
+ );
1061
+ };
1062
+
1063
+ const root = m.root ? m.node.get(m.root) : null;
1064
+ const shownTargets = new Set([...m.node.keys(), ...m.sticker.keys()]);
1065
+ const restConflicts = c.conflicts.filter((x) => !shownTargets.has(x.record));
1066
+ const aiRemoved = removed.filter((x) => x.owner !== null);
1067
+ // 오른쪽 칸을 숨긴 동안에도 손볼 것이 있으면 아이콘에 그 수를 붙인다
1068
+ const attention = m.orphans.length + restConflicts.length + c.notices.length;
1069
+ if (attention > lastAttention) sideOpen = true;
1070
+ lastAttention = attention;
1071
+ const newest = feed.filter((x) => x.changes.length || x.summary).at(-1) ?? null;
1072
+ // 처음 그릴 때 있던 기록은 새로 온 것으로 치지 않는다
1073
+ if (sideOpen || seenFeed === null) seenFeed = newest?.revision ?? '';
1074
+ const unseen = !sideOpen && newest && !newest.mine && newest.revision !== seenFeed;
1075
+ const sideTitle = [tr('Changes and notices'), attention ? tr('{n} to look at', { n: attention }) : null, unseen ? tr('New changes from the AI') : null].filter(Boolean).join('. ');
1076
+ const sideButton = iconBtn('side', tr('Changes and notices'), () => { sideOpen = !sideOpen; render(); },
1077
+ { 'aria-expanded': String(sideOpen), title: sideTitle },
1078
+ attention ? el('span', { class: 'count', 'aria-hidden': 'true' }, String(attention)) : null,
1079
+ unseen ? el('span', { class: attention ? 'dot low' : 'dot', 'aria-hidden': 'true' }) : null);
1080
+ const toolbar = el('div', { class: 'toolbar', role: 'toolbar', 'aria-label': tr('Tree tools') },
1081
+ root && c.othersPending.length ? iconBtn('help', tr('Things the AI changed that are not confirmed yet carry a mark. Your next operation confirms everything shown now.'), null, { class: 'icon-btn help' }) : null,
1082
+ root ? iconBtn('memo', stickersHidden ? tr('Expand all memos') : tr('Collapse all memos'), () => {
1083
+ stickersHidden = !stickersHidden;
1084
+ stickersFlipped.clear();
1085
+ stickerOpen = null;
1086
+ render();
1087
+ }, { 'aria-pressed': String(stickersHidden), title: stickersHidden ? tr('Expand all memos: show the stickers on every node again') : tr('Collapse all memos: hide the stickers on every node. The memo count next to each node stays') }) : null,
1088
+ root ? iconBtn('expand', tr('Expand all nodes'), () => { for (const t of m.node.values()) expanded.add(t.id); render(); }) : null,
1089
+ root ? iconBtn('collapse', tr('Collapse all nodes'), () => { expanded.clear(); expanded.add(root.id); render(); }) : null,
1090
+ sideButton);
1091
+ const treeSection = root
1092
+ ? el('section', { 'aria-label': tr('Tree'), class: 'tree' },
1093
+ toolbar,
1094
+ el('ul', {}, nodeView(root, [root])))
1095
+ : el('section', { 'aria-label': tr('Tree'), class: 'tree' },
1096
+ toolbar,
1097
+ el('p', { class: 'empty' }, tr('Write the topic for the top, then split it into nodes below. You can also just tell the AI.')),
1098
+ readOnly ? null : editor?.key === 'newroot'
1099
+ ? el('div', { class: 'form bare' }, input('title', tr('Topic'), { label: tr('Root') }), saveRow(tr('Create')))
1100
+ : btn(tr('Add root'), () => startEdit({ key: 'newroot', values: {}, build: (v) => {
1101
+ const title = (v.title ?? '').trim();
1102
+ if (!title) { toast(tr('Write a topic'), true); return null; }
1103
+ return [{ op: 'node.add', input: { title } }];
1104
+ } }), 'btn primary'));
1105
+
1106
+ // 바뀐 기록. 한 줄 요약만 보이고, 누르면 바뀐 것을 하나씩 보여 준다.
1107
+ const feedView = () => {
1108
+ const list = feed.filter((x) => x.changes.length || x.summary);
1109
+ const shown = list.slice(-feedShown).reverse();
1110
+ const headline = (x) => {
1111
+ const counts = new Map();
1112
+ for (const ch of x.changes) {
1113
+ const key = `${ch.type}|${ch.action}`;
1114
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1115
+ }
1116
+ const rank = (key) => { const i = FEED_ORDER.indexOf(key.split('|')[0]); return i < 0 ? FEED_ORDER.length : i; };
1117
+ const parts = [...counts].sort((a, b) => rank(a[0]) - rank(b[0])).map(([key, num]) => {
1118
+ const [type, action] = key.split('|');
1119
+ return tr('{n} {kind} {verb}', { n: num, kind: feedKind(type, num), verb: feedVerb(action) });
1120
+ });
1121
+ return parts.length ? parts.join(', ') : x.summary;
1122
+ };
1123
+ const changeLine = (ch) => {
1124
+ const text = String(describeContent(ch.after ?? ch.before)).replace(/\s+/g, ' ');
1125
+ return el('li', {}, el('span', { class: 'kind-tag' }, `${feedKind(ch.type)} ${feedVerb(ch.action)}`), ' ', [...text].length > 80 ? `${[...text].slice(0, 80).join('')}...` : text);
1126
+ };
1127
+ return el('section', { 'aria-label': tr('Changes') }, el('h2', {}, tr('Changes')),
1128
+ list.length === 0 ? el('p', { class: 'empty' }, tr('Nothing yet.')) : null,
1129
+ list.length === 0 ? null : el('ul', { class: 'feed' }, shown.map((x) => {
1130
+ const open = openFeed.has(x.revision);
1131
+ const detail = open && x.changes.length
1132
+ ? el('ul', { class: 'feed-detail' }, x.changes.slice(0, FEED_DETAIL_MAX).map(changeLine),
1133
+ x.changes.length > FEED_DETAIL_MAX ? el('li', { class: 'legend' }, tr('Read the other {n} with read_history.', { n: x.changes.length - FEED_DETAIL_MAX })) : null)
1134
+ : null;
1135
+ const toggle = () => { if (open) openFeed.delete(x.revision); else openFeed.add(x.revision); render(); };
1136
+ return el('li', { class: `feed-item${open ? ' open' : ''}` },
1137
+ el('button', { type: 'button', class: 'feed-head', 'aria-expanded': open ? 'true' : 'false', on: { click: toggle } },
1138
+ el('span', { class: 'who' }, el('b', {}, x.revision), x.mine ? tr(' by you') : tr(' by the AI'), x.inCommon ? null : el('span', { class: 'pending-chip' }, tr('not confirmed'))),
1139
+ el('span', { class: 'headline' }, headline(x))),
1140
+ detail);
1141
+ })),
1142
+ list.length > feedShown || feedFrom
1143
+ ? btn(list.length > feedShown ? tr('Show {n} older', { n: Math.min(FEED_PAGE, list.length - feedShown) }) : tr('Show older'), () => {
1144
+ feedShown += FEED_PAGE;
1145
+ if (list.length < feedShown && feedFrom) refresh();
1146
+ else render();
1147
+ }, 'btn')
1148
+ : null);
1149
+ };
1150
+
1151
+ // 숨긴 동안에도 그려 두고 hidden 으로만 감춘다. 열면 다시 읽지 않고 바로 보인다
1152
+ const side = el('div', { id: 'side', hidden: !sideOpen },
1153
+ // 스티커는 자동으로 떨어지지 않는다. 지운 노드에 붙어 있던 스티커는 여기 남는다(999 2.1절)
1154
+ m.orphans.length
1155
+ ? el('section', { 'aria-label': tr('Stickers on removed nodes'), class: 'side-stickers' },
1156
+ el('h2', { title: tr('Stickers stay when a node is removed. Move them to another node or remove them.') }, tr('Stickers on removed nodes')),
1157
+ el('div', { class: 'stickers' }, m.orphans.map(stickerView)))
1158
+ : null,
1159
+ aiRemoved.length
1160
+ ? el('section', { 'aria-label': tr('Removed by the AI') }, el('h2', {}, tr('Removed by the AI')),
1161
+ el('ul', {}, aiRemoved.map((x) => el('li', { class: 'item' }, describeContent(x.before), el('span', { class: 'tag remove' }, actionLabel('remove'))))))
1162
+ : null,
1163
+ restConflicts.length ? el('section', { 'aria-label': tr('Conflicts') }, el('h2', {}, tr('Conflicts')), restConflicts.map(conflictCard)) : null,
1164
+ c.notices.length ? el('section', { 'aria-label': tr('Notices') }, el('h2', {}, tr('Notices')), c.notices.map((x) => el('div', { class: 'item' }, x.message ?? x.kind))) : null,
1165
+ feedView(),
1166
+ );
1167
+
1168
+ const main = el('div', { id: 'main' },
1169
+ // 보기 탭(canEdit 거짓)은 호스트가 머리에 "보기만 합니다" 를 이미 적으므로 겹쳐 적지 않는다
1170
+ readOnly && canEdit ? el('div', { class: 'readonly' }, tr('This is not the screen being edited, so it is read only. To make changes, switch to this screen in the bar above.')) : null,
1171
+ treeSection);
1172
+ const ask = readOnly ? null : stickerAskView();
1173
+ if (!ask) stickerAsk = null;
1174
+ stage.classList.toggle('with-side', sideOpen);
1175
+ stage.replaceChildren(...[main, side, ask].filter(Boolean));
1176
+ if (ask) {
1177
+ // 창이 떠 있는 동안은 창 안에 초점을 둔다. 다시 그려도 누르던 버튼을 잃지 않게 같은 버튼으로 돌려놓는다
1178
+ const was = document.activeElement?.dataset?.ask;
1179
+ (ask.querySelector(`[data-ask="${was ?? 'new'}"]`) ?? ask.querySelector('button'))?.focus({ preventScroll: true });
1180
+ }
1181
+
1182
+ const back = field ? stage.querySelector(`[data-field="${CSS.escape(field)}"]`) : stage.querySelector('[data-field]');
1183
+ if (back && editor) {
1184
+ back.focus({ preventScroll: true });
1185
+ if (sel && 'setSelectionRange' in back) back.setSelectionRange(sel[0], sel[1]);
1186
+ }
1187
+ showQuickTalk(readOnly, m);
1188
+ syncPick(readOnly, m);
1189
+ if (drawPending) {
1190
+ drawPending = false;
1191
+ parent.postMessage({ aic: 1, event: 'rendered', token: c.renderToken }, '*');
1192
+ }
1193
+ }
1194
+
1195
+ function startRename(t) {
1196
+ startEdit({ key: `rename-${t.id}`, values: { title: t.title }, build: (v) => {
1197
+ const title = (v.title ?? '').trim();
1198
+ return !title || title === t.title ? [] : [{ op: 'node.update', input: { node: t.id, title } }];
1199
+ } });
1200
+ }
1201
+
1202
+ function clearDrop() {
1203
+ for (const x of stage.querySelectorAll('.drop-before, .drop-after, .drop-in')) x.classList.remove('drop-before', 'drop-after', 'drop-in');
1204
+ }
1205
+ function endDrag() {
1206
+ dragging = null;
1207
+ clearDrop();
1208
+ for (const x of stage.querySelectorAll('.dragging')) x.classList.remove('dragging');
1209
+ render();
1210
+ }
1211
+
1212
+ // 칸 밖을 누르면 이름 칸은 저장하고, 스티커 글 칸은 그대로 둔다
1213
+ document.addEventListener('focusout', (ev) => {
1214
+ const f = ev.target?.dataset?.field;
1215
+ if (!f || !editor || !/^rename-/.test(editor.key)) return;
1216
+ const e = editor;
1217
+ setTimeout(() => {
1218
+ if (editor === e && !document.activeElement?.dataset?.field) saveEditor();
1219
+ }, 150);
1220
+ });
1221
+
1222
+ // ---- 고르기와 AI 에게 말하기 ----
1223
+
1224
+ function pickRow(ev, id) {
1225
+ if (!caps.conceptSelection) return;
1226
+ // 이름, 버튼, 입력 칸을 누른 것은 그 일을 한다. 줄의 빈 곳을 누를 때만 고른다
1227
+ if (ev.target?.closest?.('button, a, input, textarea, select, [role="button"], .form')) return;
1228
+ if (ev.ctrlKey || ev.metaKey) picked = picked.includes(id) ? picked.filter((x) => x !== id) : [...picked, id];
1229
+ else picked = picked.length === 1 && picked[0] === id ? [] : [id];
1230
+ render();
1231
+ if (picked.length) quickSaidEl.focus({ preventScroll: true });
1232
+ }
1233
+
1234
+ const quickEl = document.getElementById('quickTalk');
1235
+ const quickSaidEl = document.getElementById('quickSaid');
1236
+ // 다른 일을 하는 중(이름이나 글을 쓰는 중, 끄는 중, 스티커 고르기 창)이거나 읽기만 하는 화면이면 뜨지 않는다
1237
+ function showQuickTalk(readOnly, m) {
1238
+ const show = picked.length > 0 && Boolean(caps.conceptSelection) && !readOnly && !editor && !dragging && !stickerAsk;
1239
+ quickEl.hidden = !show;
1240
+ document.body?.classList.toggle('talking', show);
1241
+ if (show) document.getElementById('quickCount').textContent = picked.length === 1 ? m.node.get(picked[0])?.title ?? '' : tr('{n} nodes', { n: picked.length });
1242
+ }
1243
+
1244
+ function selectionPayload(m) {
1245
+ const labels = {};
1246
+ for (const id of picked) labels[id] = m.node.get(id)?.title ?? id;
1247
+ return {
1248
+ format: SELECTION_FORMAT,
1249
+ rev: concept.base,
1250
+ nodes: [...picked],
1251
+ collapsed: picked.filter((id) => !expanded.has(id) && (m.kids.get(id) ?? []).length > 0),
1252
+ labels,
1253
+ };
1254
+ }
1255
+
1256
+ async function shareSelection() {
1257
+ if (!concept || !caps.conceptSelection || picked.length === 0) return;
1258
+ const said = quickSaidEl.value.trim();
1259
+ if (said === '') { toast(tr('Write what you want to tell the AI'), true); quickSaidEl.focus(); return; }
1260
+ const p = selectionPayload(model());
1261
+ try {
1262
+ const res = await call('shareSelection', { base: p.rev, role: 'change', said, payload: p, records: [...p.nodes] });
1263
+ if (!res?.ok) { toast(res?.summary ?? res?.error ?? tr('Could not send the selection'), true); return; }
1264
+ if (quickSaidEl.value.trim() === said) quickSaidEl.value = '';
1265
+ toast(tr('Sent to the AI ({id})', { id: res.selection }));
1266
+ } catch (err) {
1267
+ toast(err.message, true);
1268
+ }
1269
+ }
1270
+ quickSaidEl.addEventListener('keydown', (ev) => {
1271
+ if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); shareSelection(); }
1272
+ else if (ev.key === 'Escape') { picked = []; render(); }
1273
+ });
1274
+ document.getElementById('quickSend').addEventListener('click', shareSelection);
1275
+ document.addEventListener('keydown', (ev) => {
1276
+ if (ev.key !== 'Escape' || picked.length === 0) return;
1277
+ if (ev.target?.closest?.('input, textarea, select, .modal')) return;
1278
+ picked = [];
1279
+ render();
1280
+ });
1281
+
1282
+ // 고르기만 하고 보내지 않은 것도 AI 가 read_selection 으로 읽게 호스트에 알린다(마인드맵과 같다). 고른 것이나 기준이 바뀔 때만 보낸다
1283
+ let pickKey = '';
1284
+ function syncPick(readOnly, m) {
1285
+ if (!caps.conceptPick || readOnly) return;
1286
+ const p = picked.length ? selectionPayload(m) : null;
1287
+ const key = p ? JSON.stringify(p) : '';
1288
+ if (key === pickKey) return;
1289
+ pickKey = key;
1290
+ call('setPick', p ? { base: p.rev, payload: p, records: [...p.nodes] } : null).catch(() => {});
1291
+ }
1292
+
1293
+ parent.postMessage({ aic: 1, event: 'ready', rendered: true }, '*');
1294
+
1295
+ // 읽기만 하는 보조 보기는 capabilities().edit 가 거짓이다. 한 화면은 편집이거나 보조 보기로 정해져 열리므로 시작할 때 한 번 읽는다(스토리 화면과 같다)
1296
+ call('capabilities', {}).then((cap) => {
1297
+ caps = cap ?? {};
1298
+ lang = caps.language === 'ko' ? 'ko' : 'en';
1299
+ translateStatic();
1300
+ if (cap && cap.edit === false) canEdit = false;
1301
+ render();
1302
+ }).catch(() => {});
1303
+ </script>
1304
+ </body>
1305
+ </html>