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,721 @@
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>Process Log</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; --over: #a8321f;
12
+ --add: #1d7a46; --add-bg: #e3f4e9; --upd: #8f5b00; --upd-bg: #fbf0d9; --mov: #3b5bb5; --mov-bg: #e6ebfa; --del: #a8321f; --del-bg: #fae6e2;
13
+ }
14
+ @media (prefers-color-scheme: dark) {
15
+ :root {
16
+ --bg: #191b1e; --panel: #22252a; --text: #e6e8eb; --muted: #a0a8b2; --line: #383d44; --soft: #2b2f35;
17
+ --accent: #7cc0dd; --accent-text: #10222b; --focus-bg: #1f3a46; --over: #f1a597;
18
+ --add: #7bd6a0; --add-bg: #17392a; --upd: #eec26e; --upd-bg: #41331a; --mov: #a5b9f4; --mov-bg: #252f4f; --del: #f1a597; --del-bg: #472420;
19
+ }
20
+ }
21
+ * { box-sizing: border-box; }
22
+ html, body { height: 100%; }
23
+ body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.6 system-ui, "Malgun Gothic", sans-serif; }
24
+
25
+ #stage { padding: 14px; }
26
+ section { margin-bottom: 14px; }
27
+ .head { display: flex; align-items: center; justify-content: space-between; gap: 6px; margin-bottom: 4px; flex-wrap: wrap; }
28
+ h2 { font-size: 14px; margin: 0; color: var(--muted); font-weight: 600; }
29
+ ol, ul { list-style: none; margin: 0; padding: 0; }
30
+ .empty { color: var(--muted); font-size: 14px; background: var(--panel); border: 1px dashed var(--line); border-radius: 8px; padding: 12px; }
31
+ .readonly { background: var(--soft); border-radius: 6px; padding: 6px 10px; font-size: 14px; margin-bottom: 10px; }
32
+
33
+ button { font: inherit; color: inherit; cursor: pointer; }
34
+ .btn { white-space: nowrap; background: transparent; border: 1px solid var(--line); border-radius: 5px; padding: 1px 8px; font-size: 13px; line-height: 1.6; }
35
+ .btn:hover { background: var(--soft); }
36
+ .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
37
+ .icon { background: transparent; border: 0; border-radius: 4px; padding: 0 5px; color: var(--muted); font-size: 13px; line-height: 1.6; min-width: 22px; }
38
+ .icon:hover { background: var(--soft); color: var(--text); }
39
+ .icon.armed { background: var(--del-bg); color: var(--del); font-weight: 600; }
40
+ button:focus-visible, textarea:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
41
+
42
+ /* 메모 하나 */
43
+ .card { position: relative; background: var(--panel); border: 1px solid var(--line); border-left: 3px solid var(--line); border-radius: 8px; padding: 8px 12px 10px; margin-bottom: 10px; }
44
+ .card.focus { outline: 2px solid var(--accent); background: var(--focus-bg); }
45
+ .card-head { display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap; }
46
+ .num { flex: none; color: var(--muted); font-size: 13px; min-width: 1.6em; }
47
+ .title { flex: 1; min-width: 10em; font-weight: 650; overflow-wrap: anywhere; }
48
+ .tools { flex: none; display: flex; gap: 1px; align-items: baseline; }
49
+ @media (hover: hover) {
50
+ .tools { opacity: 0; transition: opacity .1s; }
51
+ .card:hover .tools, .card:focus-within .tools { opacity: 1; }
52
+ }
53
+ .field { margin-top: 6px; }
54
+ .field > .label { display: block; color: var(--muted); font-size: 12px; }
55
+ .card-head + .field { margin-top: 2px; }
56
+ .field .text { white-space: pre-wrap; overflow-wrap: anywhere; }
57
+ pre.code { margin: 2px 0 0; padding: 6px 8px; background: var(--soft); border-radius: 5px; overflow: auto; font: 13px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace; white-space: pre; }
58
+
59
+ /* 변경 표시는 트리 화면과 같다 */
60
+ .m-add { border-left-color: var(--add); }
61
+ .m-update { border-left-color: var(--upd); }
62
+ .m-move { border-left-color: var(--mov); }
63
+ .tag { display: inline-block; font-size: 12px; line-height: 1.5; padding: 0 5px; border-radius: 3px; border: 0; }
64
+ .tag.add { color: var(--add); background: var(--add-bg); }
65
+ .tag.update { color: var(--upd); background: var(--upd-bg); }
66
+ .tag.move { color: var(--mov); background: var(--mov-bg); }
67
+ .tag.remove { color: var(--del); background: var(--del-bg); }
68
+ .before { color: var(--muted); font-size: 13px; padding: 2px 4px 2px 8px; border-left: 2px solid var(--line); margin: 6px 0 2px; overflow-wrap: anywhere; white-space: pre-wrap; }
69
+
70
+ /* 쓰는 칸 */
71
+ textarea, input[type=text] { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--accent); border-radius: 5px; padding: 2px 6px; width: 100%; }
72
+ textarea { display: block; resize: vertical; min-height: 2.1em; }
73
+ textarea.mono { font: 13px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace; }
74
+ .form { display: grid; gap: 6px; margin-top: 6px; }
75
+ .form label > span { display: flex; justify-content: space-between; color: var(--muted); font-size: 12px; }
76
+ .count.over { color: var(--over); font-weight: 600; }
77
+ .actions { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; }
78
+ .new { background: var(--panel); border: 1px solid var(--accent); border-radius: 8px; padding: 8px 12px 10px; }
79
+
80
+ /* 부딪힘 */
81
+ .conflict { border: 1px solid var(--del); border-radius: 6px; padding: 6px 8px; margin-top: 6px; background: var(--panel); font-size: 14px; }
82
+ .conflict h3 { margin: 0 0 4px; font-size: 13px; color: var(--del); font-weight: 600; }
83
+ .sides { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
84
+ .side { border: 1px solid var(--line); border-radius: 5px; padding: 3px 6px; overflow-wrap: anywhere; }
85
+ .side b { display: block; font-size: 12px; color: var(--muted); font-weight: 600; }
86
+ .warn { font-size: 12px; color: var(--muted); margin: 4px 0; overflow-wrap: anywhere; }
87
+ .item { display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; padding: 1px 0; overflow-wrap: anywhere; font-size: 14px; }
88
+
89
+ /* 고른 메모와 그때만 뜨는 위쪽 칸. 눈에 먼저 들어오게 화면 위에 둔다(rawdev 2026-11-25 "가능하면 상단에 둬") */
90
+ .pickable .card { cursor: pointer; }
91
+ .pickable .card :is(input, textarea, button) { cursor: auto; }
92
+ .card.picked { outline: 2px solid var(--accent); outline-offset: 1px; }
93
+ #quickTalk { position: fixed; left: 50%; top: 8px; transform: translateX(-50%); width: min(520px, calc(100% - 16px)); display: flex; gap: 4px; align-items: center; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 5px 6px; z-index: 40; box-shadow: 0 2px 10px rgba(0, 0, 0, .14); }
94
+ #quickTalk input { flex: 1; min-width: 0; border-color: var(--line); }
95
+ #quickCount { flex: none; color: var(--muted); font-size: 12px; white-space: nowrap; }
96
+ body.talking #stage { padding-top: 60px; }
97
+
98
+ #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); }
99
+ #toast.bad { background: var(--del); color: #fff; }
100
+ #error { color: var(--del); padding: 16px; }
101
+ [hidden] { display: none !important; }
102
+
103
+ @media (max-width: 420px) {
104
+ #stage { padding: 10px; }
105
+ .sides { grid-template-columns: 1fr; }
106
+ }
107
+ </style>
108
+ </head>
109
+ <body>
110
+ <div id="error" role="alert" hidden></div>
111
+ <main id="stage"></main>
112
+ <div id="quickTalk" hidden>
113
+ <span id="quickCount" title="Click a memo to select it. Ctrl+click (Cmd+click on Mac) adds or removes a memo. Esc clears the selection"></span>
114
+ <input id="quickSaid" type="text" autocomplete="off" aria-label="What to tell the AI about the selected memos" placeholder="Tell the AI about the selected memos">
115
+ <button type="button" class="btn primary" id="quickSend" title="Send the selected memos and your words to the AI">Send</button>
116
+ </div>
117
+ <div id="toast" role="status" hidden></div>
118
+ <script>
119
+ // 작업 과정 기록의 화면(plugin-design/aiakiv-process-log.md 3.4절). 호스트 연결로만 코어와 이야기한다. 글은 모두 textContent 로 넣는다.
120
+ // 사람이 메모를 쓰고 고치고 옮기고 지우는 것도 모두 조작으로 바뀌어 AI 와 같은 경로로 저장된다.
121
+ // 이 화면은 어느 메모를 AiAkiv 에 남겼는지 모른다. 그것은 외부 연결의 기록이다.
122
+ 'use strict';
123
+ const stage = document.getElementById('stage');
124
+ const errorEl = document.getElementById('error');
125
+ const toastEl = document.getElementById('toast');
126
+ const quickEl = document.getElementById('quickTalk');
127
+ const quickSaidEl = document.getElementById('quickSaid');
128
+ const quickCountEl = document.getElementById('quickCount');
129
+ const quickSendEl = document.getElementById('quickSend');
130
+ // 화면이 고른 메모를 보낼 때의 모양. 논리의 SELECTION_FORMAT 과 같다
131
+ const SELECTION_FORMAT = 'aic.process-log/selection-1';
132
+
133
+ // ---- 화면 글의 언어(plugin-guide 3.7절과 4.4절, rawdev 2026-11-25) ----
134
+ // 영어 글이 원문이다. 호스트가 capabilities().language 로 "ko" 를 주면 이 사전에서 한국어를 찾아 보인다. 다른 값이거나 없으면 영어다.
135
+ // 화면 글만 바꾼다. 논리가 낸 글(요약, 거절 문장)과 호스트가 준 오류 글은 받은 그대로 보인다. t() 에는 글자 그대로의 영어 원문만 준다(src/lang.test.ts 가 사전과 맞춰 본다).
136
+ const KO = {
137
+ 'Click a memo to select it. Ctrl+click (Cmd+click on Mac) adds or removes a memo. Esc clears the selection': '메모를 누르면 고릅니다. Ctrl+클릭(맥은 Cmd+클릭)으로 메모를 더하거나 뺍니다. Esc 를 누르면 고른 것을 풉니다',
138
+ 'What to tell the AI about the selected memos': '고른 메모에 대해 AI 에게 할 말',
139
+ 'Tell the AI about the selected memos': '고른 메모에 대해 AI 에게 말하기',
140
+ 'Tell the AI about this memo': '이 메모에 대해 AI 에게 말하기',
141
+ 'Tell the AI about these {n} memos': '이 메모 {n}개에 대해 AI 에게 말하기',
142
+ 'Send the selected memos and your words to the AI': '고른 메모와 적은 말을 AI 에게 보냅니다',
143
+ 'Send': '보내기',
144
+ '1 memo': '메모 1개',
145
+ '{n} memos': '메모 {n}개',
146
+ 'Could not send the selection': '고른 것을 보내지 못했습니다',
147
+ 'Sent 1 memo to the AI (selection {id})': '메모 1개를 AI 에게 보냈습니다(선택 {id})',
148
+ 'Sent {n} memos to the AI (selection {id})': '메모 {n}개를 AI 에게 보냈습니다(선택 {id})',
149
+ 'Withdrawn changes: {list}': '철회한 변경: {list}',
150
+ 'Remove memo': '메모 지우기',
151
+ 'Remove?': '지울까요?',
152
+ 'New': '새로 생김',
153
+ 'Edited': '고침',
154
+ 'Moved': '옮김',
155
+ 'Removed': '지움',
156
+ 'Another participant changed this memo, and the change is not final yet. When you do your next operation, everything you see now becomes final.': '다른 참여자가 바꾸었고 아직 확정되지 않은 메모입니다. 다음 조작을 하면 지금 보이는 데까지 확정됩니다.',
157
+ 'The same memo was changed in two different ways': '같은 메모를 다르게 바꿨습니다',
158
+ 'What it points to was removed': '가리키는 것이 지워졌습니다',
159
+ ' (resolves {n} together)': ' ({n}건을 함께 풉니다)',
160
+ 'Mine': '내 것',
161
+ "{name}'s": '{name} 것',
162
+ 'Theirs': '상대 것',
163
+ 'the other participant': '상대',
164
+ 'If you pick yours, this whole change by {name} is canceled: {summary}': '내 것을 고르면 {name} 의 이 변경이 통째로 취소됩니다: {summary}',
165
+ 'If you pick theirs, this whole change of yours is canceled: {summary}': '상대 것을 고르면 내 이 변경이 통째로 취소됩니다: {summary}',
166
+ 'Keep mine': '내 것으로',
167
+ "Keep {name}'s": '{name} 것으로',
168
+ 'Keep theirs': '상대 것으로',
169
+ 'Title': '제목',
170
+ 'The decision in one line': '정한 것을 한 줄로',
171
+ 'Decision': '정한 것',
172
+ 'What was decided or done': '정한 것이나 한 일',
173
+ 'Reason (optional)': '까닭(없어도 됩니다)',
174
+ 'Why it was decided this way': '그렇게 정한 까닭',
175
+ 'Code or commands (optional)': '코드나 명령(없어도 됩니다)',
176
+ 'Code or commands to keep with it. Do not write secrets such as keys, tokens or passwords': '함께 남길 코드나 명령. 키, 토큰, 비밀번호 같은 비밀값은 적지 않습니다',
177
+ 'To save, press Enter in the title field, or Ctrl+Enter (Cmd+Enter on Mac) in the other fields': '제목 칸은 Enter, 여러 줄 칸은 Ctrl+Enter(맥은 Cmd+Enter)로 저장합니다',
178
+ 'Cancel': '취소',
179
+ 'You can also press Esc to cancel': 'Esc 로도 취소합니다',
180
+ 'Save': '저장',
181
+ 'Add': '더하기',
182
+ 'Write a title and a decision': '제목과 정한 것을 적어 주세요',
183
+ 'Title cannot be empty': '제목은 비울 수 없습니다',
184
+ 'Decision cannot be empty': '정한 것은 비울 수 없습니다',
185
+ 'You and another participant changed the same memo in different ways. Pick one below': '같은 메모를 나와 다른 참여자가 다르게 바꿨습니다. 아래에서 하나를 고릅니다',
186
+ 'Conflict': '부딪힘',
187
+ 'Click to see the memo before the change. {note}': '누르면 바뀌기 전을 봅니다. {note}',
188
+ 'Code, 1 line': '코드 1줄',
189
+ 'Code, {n} lines': '코드 {n}줄',
190
+ 'Fold code': '코드 접기',
191
+ 'Show all {n} lines of code': '코드 {n}줄 모두 보기',
192
+ 'Memo id {id}': '메모 id {id}',
193
+ 'Move up': '위로',
194
+ 'Move down': '아래로',
195
+ 'Edit memo': '메모 고치기',
196
+ 'Before: ': '바뀌기 전: ',
197
+ 'Reason': '까닭',
198
+ 'Process memos': '과정 메모',
199
+ 'Process memos ({n})': '과정 메모 {n}개',
200
+ '+ Memo': '+ 메모',
201
+ 'Write a decision as a memo': '정한 것을 메모로 적습니다',
202
+ 'No process memos yet. Tell the AI what you decide to keep while working, or write it with [+ Memo].': '아직 과정 메모가 없습니다. 일하다 남기기로 정한 것을 AI 에게 말하거나 [+ 메모] 로 적습니다.',
203
+ 'New memo': '새 메모',
204
+ 'This is not the screen being edited, so you can only read it. To edit, switch to this screen from the row at the top.': '지금 편집하는 화면이 아니라 읽기만 합니다. 고치려면 위쪽 줄에서 이 화면으로 옮깁니다.',
205
+ 'Removed by the AI': 'AI 가 지운 것',
206
+ 'Memos the AI removed': 'AI 가 지운 메모',
207
+ 'Conflicts': '부딪힌 것',
208
+ 'Notices': '알림',
209
+ };
210
+ let ko = false;
211
+ /** 영어 원문을 지금 언어로 바꾸고 {name} 에 값을 넣는다 */
212
+ function t(text, vals) {
213
+ let s = ko && Object.prototype.hasOwnProperty.call(KO, text) ? KO[text] : text;
214
+ if (vals) s = s.replace(/\{(\w+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(vals, k) ? String(vals[k]) : m));
215
+ return s;
216
+ }
217
+ /** 언어를 정하고 index.html 에 고정으로 적힌 글을 바꾼다. 사람이 언어를 바꾸면 호스트가 화면을 다시 열므로 처음 한 번만 부른다 */
218
+ function applyLanguage(language) {
219
+ ko = language === 'ko';
220
+ document.documentElement.lang = ko ? 'ko' : 'en';
221
+ quickCountEl.title = t('Click a memo to select it. Ctrl+click (Cmd+click on Mac) adds or removes a memo. Esc clears the selection');
222
+ quickSaidEl.setAttribute('aria-label', t('What to tell the AI about the selected memos'));
223
+ quickSaidEl.setAttribute('placeholder', t('Tell the AI about the selected memos'));
224
+ quickSendEl.title = t('Send the selected memos and your words to the AI');
225
+ quickSendEl.textContent = t('Send');
226
+ }
227
+
228
+ // 칸마다 글자(코드 포인트) 한도. 논리의 LIMITS 와 같다. 넘으면 저장할 때 논리가 고치는 방법을 적어 거절한다
229
+ const LIMITS = { title: 200, decided: 4000, why: 4000, code: 20000 };
230
+ // 코드가 이보다 길면 앞부분만 보이고 펼친다
231
+ const CODE_LINES = 6;
232
+
233
+ let nextId = 1;
234
+ const waiting = new Map();
235
+ let concept = null;
236
+ let canEdit = true; // 읽기만 하는 보조 보기면 거짓(032 10.2절)
237
+ let caps = {}; // capabilities(). conceptSelection 이 있으면 고른 메모를 보내고, conceptPick 이 있으면 고르기만 한 것도 알린다
238
+ let pickOn = false; // 지금 메모를 고를 수 있는지. 편집 화면이고 호스트가 선택을 받을 때만
239
+ let picked = []; // 고른 메모 id. 고른 차례대로. 화면 상태라 저장하지 않는다
240
+ let editor = null; // 지금 쓰는 칸 하나. { key, values, build, base }
241
+ let composing = false;
242
+ let committing = false;
243
+ let renderWanted = false;
244
+ // 그린 기준 알림(032 10.3절). 호스트가 읽기 응답에 붙인 표를, 그 응답을 다 그린 뒤 그대로 돌려보낸다.
245
+ let drawPending = false;
246
+ let focused = new Set();
247
+ const armed = new Map();
248
+ const openCode = new Set(); // 코드를 다 펼친 메모. 화면 상태라 저장하지 않는다
249
+ const openBefore = new Set();
250
+
251
+ function call(method, params) {
252
+ return new Promise((resolve, reject) => {
253
+ const id = nextId++;
254
+ waiting.set(id, { resolve, reject });
255
+ parent.postMessage({ aic: 1, id, method, params }, '*');
256
+ });
257
+ }
258
+
259
+ window.addEventListener('message', (e) => {
260
+ if (e.source !== parent) return;
261
+ const d = e.data;
262
+ if (typeof d !== 'object' || d === null || d.aic !== 1) return;
263
+ if (d.event === 'change') {
264
+ refresh(typeof d.rev === 'string' ? d.rev : null);
265
+ return;
266
+ }
267
+ // 사람이 결과물 글에서 구간을 누르면 그 구간의 메모를 눈에 띄게 한다
268
+ if (d.event === 'focus') {
269
+ focused = new Set(Array.isArray(d.targets) ? d.targets.filter((x) => typeof x === 'string') : []);
270
+ render();
271
+ const first = [...focused][0];
272
+ if (first) stage.querySelector(`[data-log="${CSS.escape(first)}"]`)?.scrollIntoView({ block: 'nearest' });
273
+ return;
274
+ }
275
+ const w = waiting.get(d.id);
276
+ if (!w) return;
277
+ waiting.delete(d.id);
278
+ if (d.error) w.reject(new Error(d.error));
279
+ else w.resolve(d.result);
280
+ });
281
+
282
+ // 읽는 중에 온 change 는 모아 두었다가 읽기가 끝난 뒤 한 번만 다시 읽는다(plugin-guide 4.3절)
283
+ let inflight = null;
284
+ let queued = null;
285
+ let queuedRevs = null;
286
+ const seq = (rev) => Number(String(rev).slice(1));
287
+ function refresh(rev = null) {
288
+ if (inflight) {
289
+ (queuedRevs ??= []).push(rev);
290
+ queued ??= inflight.then(() => {
291
+ queued = null;
292
+ const revs = queuedRevs ?? [];
293
+ queuedRevs = null;
294
+ if (revs.length > 0 && concept && revs.every((r) => r !== null && seq(r) <= seq(concept.base))) return undefined;
295
+ return refresh();
296
+ });
297
+ return queued;
298
+ }
299
+ inflight = (async () => {
300
+ try {
301
+ const c = await call('readConcept');
302
+ errorEl.hidden = true;
303
+ concept = c;
304
+ drawPending = typeof c.renderToken === 'string';
305
+ render();
306
+ } catch (err) {
307
+ errorEl.textContent = err.message;
308
+ errorEl.hidden = false;
309
+ }
310
+ })().finally(() => {
311
+ inflight = null;
312
+ });
313
+ return inflight;
314
+ }
315
+
316
+ let toastTimer = null;
317
+ function toast(text, bad = false) {
318
+ toastEl.textContent = text;
319
+ toastEl.classList.toggle('bad', bad);
320
+ toastEl.hidden = false;
321
+ clearTimeout(toastTimer);
322
+ toastTimer = setTimeout(() => { toastEl.hidden = true; }, bad ? 7000 : 3500);
323
+ }
324
+
325
+ let lastOwn = null;
326
+ async function send(steps, opts = {}) {
327
+ let base = opts.base ?? concept.base;
328
+ if (lastOwn && seq(lastOwn) > seq(base)) base = lastOwn;
329
+ const req = { base, steps, ...(opts.resolves ? { resolves: opts.resolves } : {}), ...(opts.take ? { take: opts.take } : {}) };
330
+ let res;
331
+ try {
332
+ res = await call('applyOperation', req);
333
+ } catch (err) {
334
+ toast(err.message, true);
335
+ return null;
336
+ }
337
+ if (!res.ok) {
338
+ toast(res.summary ?? res.error, true);
339
+ await refresh();
340
+ return null;
341
+ }
342
+ lastOwn = res.revision;
343
+ if (res.withdrawn?.length) toast(t('Withdrawn changes: {list}', { list: res.withdrawn.join(', ') }));
344
+ await refresh(res.revision);
345
+ return res;
346
+ }
347
+
348
+ function el(tag, props, ...children) {
349
+ const n = document.createElement(tag);
350
+ for (const [k, v] of Object.entries(props ?? {})) {
351
+ if (k === 'class') n.className = v;
352
+ else if (k === 'on') for (const [ev, fn] of Object.entries(v)) n.addEventListener(ev, fn);
353
+ else if (k === 'value') n.value = v;
354
+ else if (v !== false && v !== null && v !== undefined) n.setAttribute(k, v === true ? '' : v);
355
+ }
356
+ for (const c of children.flat(Infinity)) {
357
+ if (c === null || c === undefined || c === false) continue;
358
+ n.append(c instanceof Node ? c : String(c));
359
+ }
360
+ return n;
361
+ }
362
+ const btn = (label, onClick, cls = 'btn', extra = {}) => el('button', { type: 'button', class: cls, on: { click: onClick }, ...extra }, label);
363
+
364
+ function deleteButton(key, onConfirm) {
365
+ const on = armed.get(key);
366
+ return el('button', {
367
+ type: 'button', class: `icon${on ? ' armed' : ''}`, 'aria-label': t('Remove memo'), title: t('Remove memo'),
368
+ on: { click: () => {
369
+ if (armed.get(key)) { armed.delete(key); onConfirm(); return; }
370
+ armed.set(key, true);
371
+ setTimeout(() => { if (armed.delete(key)) render(); }, 3000);
372
+ render();
373
+ } },
374
+ }, on ? t('Remove?') : '×');
375
+ }
376
+
377
+ const actionLabel = (a) => ({ add: t('New'), update: t('Edited'), move: t('Moved'), remove: t('Removed') })[a];
378
+ // 표시에 마우스를 올리면 보이는 글. 늘 보이던 설명 줄을 옮겼다
379
+ const pendingNote = () => t('Another participant changed this memo, and the change is not final yet. When you do your next operation, everything you see now becomes final.');
380
+ const chars = (s) => [...String(s ?? '')].length;
381
+
382
+ function describeContent(content) {
383
+ if (content === null || content === undefined) return t('Removed');
384
+ if (typeof content === 'object' && typeof content.title === 'string') {
385
+ const one = String(content.decided ?? '').replace(/\s+/g, ' ').trim();
386
+ return `${content.title}: ${chars(one) > 80 ? `${[...one].slice(0, 80).join('')}...` : one}`;
387
+ }
388
+ return JSON.stringify(content);
389
+ }
390
+
391
+ /** 다른 참여자의 아직 확정되지 않은 변경 표시. 트리 화면과 같다 */
392
+ function computeMarks() {
393
+ const marks = new Map();
394
+ const removed = [];
395
+ const c = concept;
396
+ const latest = c.othersPending.length ? c.othersPending[c.othersPending.length - 1].revision : null;
397
+ for (const p of c.othersPending) {
398
+ for (const ch of p.changes) {
399
+ const prev = marks.get(ch.record);
400
+ marks.set(ch.record, {
401
+ action: prev && prev.action === 'add' && ch.after !== null ? 'add' : ch.action,
402
+ before: prev ? prev.before : ch.before,
403
+ type: ch.type, owner: ch.owner, revision: p.revision, recent: p.revision === latest,
404
+ });
405
+ }
406
+ }
407
+ const held = new Set(c.conflicts.map((x) => x.record));
408
+ for (const id of held) marks.delete(id);
409
+ for (const [id, mk] of marks) {
410
+ if (mk.action === 'remove' && mk.before !== null) removed.push({ id, ...mk });
411
+ if (mk.action === 'remove') marks.delete(id);
412
+ }
413
+ return { marks, removed, held };
414
+ }
415
+
416
+ function conflictCard(c) {
417
+ const me = concept.me;
418
+ const group = [c, ...concept.conflicts.filter((x) => x !== c && x.sides.some((s) => c.sides.some((y) => y.revision === s.revision)))];
419
+ const ids = group.map((x) => x.id);
420
+ const mine = c.sides.find((s) => s.participant === me);
421
+ const theirs = c.sides.find((s) => s.participant !== me);
422
+ const summaryOf = (rev) => [...concept.othersPending, ...concept.myPending].find((p) => p.revision === rev)?.summary;
423
+ const theirSummary = theirs ? summaryOf(theirs.revision) : null;
424
+ const mySummary = mine ? summaryOf(mine.revision) : null;
425
+ return el('div', { class: 'conflict', 'data-conflict': c.id },
426
+ el('h3', {}, c.reason === 'same_record' ? t('The same memo was changed in two different ways') : t('What it points to was removed'), group.length > 1 ? t(' (resolves {n} together)', { n: group.length }) : ''),
427
+ el('div', { class: 'sides' }, [mine, theirs].filter(Boolean).map((s) =>
428
+ el('div', { class: 'side' }, el('b', {}, s === mine ? t('Mine') : s.name ? t("{name}'s", { name: s.name }) : t('Theirs')), describeContent(s.content)))),
429
+ theirSummary ? el('p', { class: 'warn' }, t('If you pick yours, this whole change by {name} is canceled: {summary}', { name: theirs.name ?? t('the other participant'), summary: theirSummary })) : null,
430
+ mySummary ? el('p', { class: 'warn' }, t('If you pick theirs, this whole change of yours is canceled: {summary}', { summary: mySummary })) : null,
431
+ el('div', { class: 'actions' },
432
+ btn(t('Keep mine'), () => send([], { resolves: ids, take: 'mine' }), 'btn primary'),
433
+ theirs ? btn(theirs.name ? t("Keep {name}'s", { name: theirs.name }) : t('Keep theirs'), () => send([], { resolves: ids, take: 'theirs' })) : null),
434
+ );
435
+ }
436
+
437
+ // 쓰는 칸. 칸마다 data-field 를 달아 다시 그려도 글과 커서를 잃지 않는다.
438
+ // ---- 메모 고르기와 보내기 ----
439
+
440
+ /** 메모를 누르면 그 메모 하나를 고르고, 다시 누르면 푼다. Ctrl(맥은 Cmd)이나 Shift 를 누른 채면 더하거나 뺀다. */
441
+ function pickCard(ev, id) {
442
+ if (!pickOn || editor) return;
443
+ if (ev.target?.closest?.('button, input, textarea, a, label')) return;
444
+ const s = window.getSelection?.();
445
+ if (s && !s.isCollapsed && String(s) !== '') return; // 글을 끌어 고르는 중이면 메모를 고르지 않는다
446
+ if (ev.ctrlKey || ev.metaKey || ev.shiftKey) picked = picked.includes(id) ? picked.filter((x) => x !== id) : [...picked, id];
447
+ else picked = picked.length === 1 && picked[0] === id ? [] : [id];
448
+ render();
449
+ }
450
+ function clearPicked() {
451
+ if (!picked.length) return;
452
+ picked = [];
453
+ render();
454
+ }
455
+ function selectionPayload() {
456
+ const logs = (concept.withOthers ?? concept.body)?.logs ?? [];
457
+ const labels = {};
458
+ for (const x of logs) if (picked.includes(x.id)) labels[x.id] = x.title;
459
+ return { format: SELECTION_FORMAT, rev: concept.base, logs: [...picked], labels };
460
+ }
461
+ const memoCount = (n) => (n === 1 ? t('1 memo') : t('{n} memos', { n }));
462
+ /** 고른 메모와 적은 말을 AI 에게 보낸다(shareSelection). 보낸 선택이 고르기만 한 것을 대신하므로 setPick 은 따로 지우지 않는다 */
463
+ async function shareSelection() {
464
+ if (!pickOn || !picked.length || !concept) return;
465
+ const p = selectionPayload();
466
+ const said = quickSaidEl.value.trim();
467
+ try {
468
+ const res = await call('shareSelection', { base: p.rev, role: 'change', said, payload: p, records: [...p.logs] });
469
+ if (!res?.ok) { toast(res?.summary ?? res?.error ?? t('Could not send the selection'), true); return; }
470
+ if (quickSaidEl.value.trim() === said) quickSaidEl.value = '';
471
+ toast(p.logs.length === 1 ? t('Sent 1 memo to the AI (selection {id})', { id: res.selection }) : t('Sent {n} memos to the AI (selection {id})', { n: p.logs.length, id: res.selection }));
472
+ } catch (err) {
473
+ toast(err.message, true);
474
+ }
475
+ }
476
+ // 고르기만 하고 보내지 않은 것도 AI 가 read_selection 으로 읽게 호스트에 알린다. 고른 것이나 기준이 바뀔 때만 보내고 답은 기다리지 않는다
477
+ let pickKey = '';
478
+ function syncPick() {
479
+ if (!caps.conceptPick || !pickOn) return;
480
+ const p = picked.length ? selectionPayload() : null;
481
+ const key = p ? JSON.stringify(p) : '';
482
+ if (key === pickKey) return;
483
+ pickKey = key;
484
+ call('setPick', p ? { base: p.rev, payload: p, records: [...p.logs] } : null).catch(() => {});
485
+ }
486
+ quickSaidEl.addEventListener('keydown', (ev) => {
487
+ if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); shareSelection(); }
488
+ else if (ev.key === 'Escape') quickSaidEl.blur?.();
489
+ });
490
+ quickSendEl.addEventListener('click', shareSelection);
491
+ document.addEventListener('keydown', (ev) => {
492
+ const tag = ev.target?.tagName;
493
+ if (tag === 'INPUT' || tag === 'TEXTAREA') return;
494
+ if (ev.key === 'Escape') clearPicked();
495
+ });
496
+
497
+ function startEdit(e) {
498
+ armed.clear();
499
+ editor = { base: concept.base, values: {}, ...e };
500
+ render();
501
+ }
502
+ function closeEditor() {
503
+ editor = null;
504
+ render();
505
+ }
506
+ async function saveEditor() {
507
+ const e = editor;
508
+ if (!e || committing) return;
509
+ const steps = e.build(e.values);
510
+ if (steps === null) return; // build 가 까닭을 알렸다
511
+ if (!steps.length) { closeEditor(); return; }
512
+ committing = true;
513
+ const res = await send(steps, { base: e.base });
514
+ committing = false;
515
+ if (editor === e) {
516
+ // 거절되면 쓰던 글을 그대로 두고 다음에는 지금 기준으로 보낸다
517
+ if (res) editor = null;
518
+ else e.base = concept.base;
519
+ }
520
+ render();
521
+ }
522
+
523
+ /** 글 칸 하나와 글자 수. 한 줄 칸은 Enter 로, 여러 줄 칸은 Ctrl+Enter(맥은 Cmd+Enter)로 저장한다(트리 화면과 같다). */
524
+ function field(name, opts = {}) {
525
+ const e = editor;
526
+ const limit = LIMITS[name];
527
+ const count = el('span', { class: `count${chars(e.values[name]) > limit ? ' over' : ''}`, 'data-count': name }, `${chars(e.values[name])}/${limit}`);
528
+ const box = el(opts.rows ? 'textarea' : 'input', {
529
+ ...(opts.rows ? { rows: opts.rows } : { type: 'text' }),
530
+ class: name === 'code' ? 'mono' : null, spellcheck: name === 'code' ? 'false' : null,
531
+ placeholder: opts.placeholder ?? '', 'aria-label': opts.label, 'data-field': name, value: e.values[name] ?? '',
532
+ on: {
533
+ input: (ev) => {
534
+ e.values[name] = ev.target.value;
535
+ const n = chars(ev.target.value);
536
+ count.textContent = `${n}/${limit}`;
537
+ count.className = `count${n > limit ? ' over' : ''}`;
538
+ },
539
+ compositionstart: () => { composing = true; },
540
+ compositionend: (ev) => { composing = false; e.values[name] = ev.target.value; if (renderWanted) render(); },
541
+ keydown: (ev) => {
542
+ if (ev.isComposing) return;
543
+ if (ev.key === 'Escape') { ev.preventDefault(); closeEditor(); return; }
544
+ const save = opts.rows ? ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey) : ev.key === 'Enter';
545
+ if (save) { ev.preventDefault(); e.values[name] = ev.target.value; saveEditor(); }
546
+ },
547
+ },
548
+ });
549
+ return el('label', {}, el('span', {}, el('span', {}, opts.label), count), box);
550
+ }
551
+
552
+ function logForm(saveLabel) {
553
+ return el('div', { class: 'form' },
554
+ field('title', { label: t('Title'), placeholder: t('The decision in one line') }),
555
+ field('decided', { label: t('Decision'), rows: 4, placeholder: t('What was decided or done') }),
556
+ field('why', { label: t('Reason (optional)'), rows: 3, placeholder: t('Why it was decided this way') }),
557
+ field('code', { label: t('Code or commands (optional)'), rows: 5, placeholder: t('Code or commands to keep with it. Do not write secrets such as keys, tokens or passwords') }),
558
+ el('div', { class: 'actions' },
559
+ btn(saveLabel, saveEditor, 'btn primary', { title: t('To save, press Enter in the title field, or Ctrl+Enter (Cmd+Enter on Mac) in the other fields') }),
560
+ btn(t('Cancel'), closeEditor, 'btn', { title: t('You can also press Esc to cancel') })));
561
+ }
562
+
563
+ /** 새 메모. 빈 까닭과 코드는 보내지 않는다 */
564
+ function startNew() {
565
+ startEdit({ key: 'new', values: { title: '', decided: '', why: '', code: '' }, build: (v) => {
566
+ const title = (v.title ?? '').trim();
567
+ const decided = (v.decided ?? '').trim();
568
+ if (!title || !decided) { toast(t('Write a title and a decision'), true); return null; }
569
+ const input = { title, decided };
570
+ if ((v.why ?? '').trim()) input.why = v.why;
571
+ if ((v.code ?? '').trim()) input.code = v.code;
572
+ return [{ op: 'log.add', input }];
573
+ } });
574
+ }
575
+
576
+ /** 메모 고치기. 바뀐 칸만 보내고, 비운 까닭과 코드는 null 로 지운다. 바뀐 것이 없으면 보내지 않는다 */
577
+ function startUpdate(item) {
578
+ const before = { title: item.title, decided: item.decided, why: item.why ?? '', code: item.code ?? '' };
579
+ startEdit({ key: `edit-${item.id}`, values: { ...before }, build: (v) => {
580
+ const input = { log: item.id };
581
+ for (const f of ['title', 'decided', 'why', 'code']) {
582
+ const now = v[f] ?? '';
583
+ if (now === before[f]) continue;
584
+ if (now.trim() === '') {
585
+ if (f === 'title' || f === 'decided') { toast(f === 'title' ? t('Title cannot be empty') : t('Decision cannot be empty'), true); return null; }
586
+ if (before[f] !== '') input[f] = null;
587
+ continue;
588
+ }
589
+ input[f] = now;
590
+ }
591
+ return Object.keys(input).length > 1 ? [{ op: 'log.update', input }] : [];
592
+ } });
593
+ }
594
+
595
+ function render() {
596
+ if (!concept) return;
597
+ if (composing || committing) { renderWanted = true; return; }
598
+ renderWanted = false;
599
+ const active = document.activeElement;
600
+ const fieldName = active?.dataset?.field;
601
+ const sel = fieldName && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
602
+
603
+ const c = concept;
604
+ const logs = (c.withOthers ?? c.body)?.logs ?? [];
605
+ const { marks, removed, held } = computeMarks();
606
+ // 편집 인스턴스가 아니거나 읽기만 하는 보조 보기(capabilities().edit 가 거짓)면 고치는 도구를 숨긴다
607
+ const readOnly = !canEdit || Boolean(c.editing && c.instance && c.editing.id !== c.instance);
608
+ if (readOnly && editor) editor = null;
609
+ // 보조 보기나 편집 화면이 아닌 화면, 선택을 받지 않는 호스트에서는 고르지 않는다. 지워진 메모는 고른 것에서 뺀다
610
+ pickOn = Boolean(caps.conceptSelection) && !readOnly;
611
+ const present = new Set(logs.map((x) => x.id));
612
+ picked = pickOn ? picked.filter((id) => present.has(id)) : [];
613
+ const conflictsOn = (id) => c.conflicts.filter((x) => x.record === id);
614
+ const tag = (id) => {
615
+ if (held.has(id)) return el('span', { class: 'tag remove', title: t('You and another participant changed the same memo in different ways. Pick one below') }, t('Conflict'));
616
+ const mk = marks.get(id);
617
+ if (!mk) return null;
618
+ if (mk.action !== 'update' || !mk.before) return el('span', { class: `tag ${mk.action}`, title: pendingNote() }, actionLabel(mk.action));
619
+ return el('button', { type: 'button', class: 'tag update', 'aria-expanded': openBefore.has(id) ? 'true' : 'false', title: t('Click to see the memo before the change. {note}', { note: pendingNote() }), on: { click: () => {
620
+ if (openBefore.has(id)) openBefore.delete(id); else openBefore.add(id);
621
+ render();
622
+ } } }, actionLabel('update'));
623
+ };
624
+
625
+ const codeView = (item) => {
626
+ const lines = item.code.split('\n');
627
+ const long = lines.length > CODE_LINES;
628
+ const open = !long || openCode.has(item.id);
629
+ return el('div', { class: 'field' },
630
+ el('span', { class: 'label' }, lines.length === 1 ? t('Code, 1 line') : t('Code, {n} lines', { n: lines.length })),
631
+ el('pre', { class: 'code' }, open ? item.code : `${lines.slice(0, CODE_LINES).join('\n')}\n...`),
632
+ long ? btn(open ? t('Fold code') : t('Show all {n} lines of code', { n: lines.length }), () => {
633
+ if (openCode.has(item.id)) openCode.delete(item.id); else openCode.add(item.id);
634
+ render();
635
+ }, 'icon') : null);
636
+ };
637
+
638
+ const card = (item, i) => {
639
+ const mk = marks.get(item.id);
640
+ const editing = editor?.key === `edit-${item.id}`;
641
+ return el('li', {
642
+ class: `card${focused.has(item.id) ? ' focus' : ''}${picked.includes(item.id) ? ' picked' : ''}${mk ? ` m-${mk.action}` : ''}`, 'data-log': item.id, 'data-target': item.id,
643
+ 'aria-selected': pickOn ? (picked.includes(item.id) ? 'true' : 'false') : null,
644
+ on: { click: (ev) => pickCard(ev, item.id) },
645
+ },
646
+ el('div', { class: 'card-head' },
647
+ el('span', { class: 'num', title: t('Memo id {id}', { id: item.id }) }, `${i + 1}.`),
648
+ el('span', { class: 'title' }, item.title),
649
+ tag(item.id),
650
+ readOnly || editing ? null : el('span', { class: 'tools' },
651
+ i > 0 ? btn('↑', () => send([{ op: 'log.move', input: { log: item.id, after: i > 1 ? logs[i - 2].id : null } }]), 'icon', { 'aria-label': t('Move up'), title: t('Move up') }) : null,
652
+ i < logs.length - 1 ? btn('↓', () => send([{ op: 'log.move', input: { log: item.id, after: logs[i + 1].id } }]), 'icon', { 'aria-label': t('Move down'), title: t('Move down') }) : null,
653
+ btn('✎', () => startUpdate(item), 'icon', { 'aria-label': t('Edit memo'), title: t('Edit memo') }),
654
+ deleteButton(`del-${item.id}`, () => send([{ op: 'log.remove', input: { log: item.id } }])))),
655
+ mk && mk.action === 'update' && mk.before && openBefore.has(item.id) ? el('div', { class: 'before' }, t('Before: '), describeContent(mk.before)) : null,
656
+ editing
657
+ ? logForm(t('Save'))
658
+ : [
659
+ el('div', { class: 'field' }, el('div', { class: 'text' }, item.decided)),
660
+ item.why ? el('div', { class: 'field' }, el('span', { class: 'label' }, t('Reason')), el('div', { class: 'text' }, item.why)) : null,
661
+ item.code ? codeView(item) : null,
662
+ ],
663
+ conflictsOn(item.id).map(conflictCard),
664
+ );
665
+ };
666
+
667
+ const listSection = el('section', { 'aria-label': t('Process memos') },
668
+ el('div', { class: 'head' }, el('h2', {}, logs.length ? t('Process memos ({n})', { n: logs.length }) : t('Process memos')),
669
+ readOnly || editor?.key === 'new' ? null : btn(t('+ Memo'), startNew, 'btn primary', { title: t('Write a decision as a memo') })),
670
+ logs.length ? el('ol', {}, logs.map(card)) : el('p', { class: 'empty' }, t('No process memos yet. Tell the AI what you decide to keep while working, or write it with [+ Memo].')),
671
+ editor?.key === 'new' ? el('div', { class: 'new', 'data-new': '' }, el('h2', {}, t('New memo')), logForm(t('Add'))) : null);
672
+
673
+ const shown = new Set(logs.map((x) => x.id));
674
+ const restConflicts = c.conflicts.filter((x) => !shown.has(x.record));
675
+ const aiRemoved = removed.filter((x) => x.owner !== null);
676
+ // replaceChildren 은 null 을 "null" 글로 넣으므로 빈 칸을 걸러 낸다
677
+ stage.replaceChildren(...[
678
+ readOnly && canEdit ? el('div', { class: 'readonly' }, t('This is not the screen being edited, so you can only read it. To edit, switch to this screen from the row at the top.')) : null,
679
+ listSection,
680
+ aiRemoved.length
681
+ ? el('section', { 'aria-label': t('Removed by the AI') }, el('h2', {}, t('Memos the AI removed')),
682
+ el('ul', {}, aiRemoved.map((x) => el('li', { class: 'item' }, describeContent(x.before), el('span', { class: 'tag remove' }, actionLabel('remove'))))))
683
+ : null,
684
+ restConflicts.length ? el('section', { 'aria-label': t('Conflicts') }, el('h2', {}, t('Conflicts')), restConflicts.map(conflictCard)) : null,
685
+ c.notices.length ? el('section', { 'aria-label': t('Notices') }, el('h2', {}, t('Notices')), c.notices.map((x) => el('div', { class: 'item' }, x.message ?? x.kind))) : null,
686
+ ].filter(Boolean));
687
+
688
+ // 고른 메모가 있을 때만 위쪽에 말을 적어 보내는 칸이 뜬다. 칸이 메모를 가리지 않게 목록을 그만큼 내린다. 메모를 쓰거나 고치는 중에는 뜨지 않는다
689
+ stage.classList.toggle('pickable', pickOn && !editor);
690
+ const talk = pickOn && picked.length > 0 && !editor;
691
+ quickEl.hidden = !talk;
692
+ document.body?.classList.toggle('talking', talk);
693
+ if (talk) {
694
+ quickCountEl.textContent = memoCount(picked.length);
695
+ quickSaidEl.setAttribute('placeholder', picked.length === 1 ? t('Tell the AI about this memo') : t('Tell the AI about these {n} memos', { n: picked.length }));
696
+ }
697
+ syncPick();
698
+
699
+ const back = fieldName ? stage.querySelector(`[data-field="${CSS.escape(fieldName)}"]`) : stage.querySelector('[data-field]');
700
+ if (back && editor) {
701
+ back.focus({ preventScroll: true });
702
+ if (sel && 'setSelectionRange' in back) back.setSelectionRange(sel[0], sel[1]);
703
+ }
704
+ if (drawPending) {
705
+ drawPending = false;
706
+ parent.postMessage({ aic: 1, event: 'rendered', token: c.renderToken }, '*');
707
+ }
708
+ }
709
+
710
+ parent.postMessage({ aic: 1, event: 'ready', rendered: true }, '*');
711
+
712
+ // 읽기만 하는 보조 보기는 capabilities().edit 가 거짓이다. 한 화면은 편집이거나 보조 보기로 정해져 열리므로 시작할 때 한 번 읽는다(트리 화면과 같다)
713
+ call('capabilities', {}).then((cap) => {
714
+ caps = cap ?? {};
715
+ applyLanguage(caps.language);
716
+ if (caps.edit === false) canEdit = false;
717
+ render();
718
+ }).catch(() => {});
719
+ </script>
720
+ </body>
721
+ </html>