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,2783 @@
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>Story List</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;
12
+ --node: #17607f; --node-bg: #e2f0f6; --hit: #fff1b8; --hit-line: #c99a00;
13
+ --add: #1d7a46; --add-bg: #e3f4e9; --upd: #8f5b00; --upd-bg: #fbf0d9; --mov: #3b5bb5; --mov-bg: #e6ebfa; --del: #a8321f; --del-bg: #fae6e2;
14
+ --memo: #fff6c2; --memo-text: #453a00; --memo-line: #e6d67a; --shadow: 0 1px 3px rgba(0, 0, 0, .18);
15
+ }
16
+ @media (prefers-color-scheme: dark) {
17
+ :root {
18
+ --bg: #191b1e; --panel: #22252a; --text: #e6e8eb; --muted: #a0a8b2; --line: #383d44; --soft: #2b2f35;
19
+ --accent: #7cc0dd; --accent-text: #10222b;
20
+ --node: #8ed0ea; --node-bg: #1f3a46; --hit: #5a4c10; --hit-line: #e2c23f;
21
+ --add: #7bd6a0; --add-bg: #17392a; --upd: #eec26e; --upd-bg: #41331a; --mov: #a5b9f4; --mov-bg: #252f4f; --del: #f1a597; --del-bg: #472420;
22
+ --memo: #453d17; --memo-text: #f4e9ae; --memo-line: #6d6125; --shadow: 0 1px 3px rgba(0, 0, 0, .6);
23
+ }
24
+ }
25
+ * { box-sizing: border-box; }
26
+ html, body { height: 100%; }
27
+ body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.6 system-ui, "Malgun Gothic", sans-serif; }
28
+
29
+ /* 가운데 사실과 장면이 화면 전체를 쓴다. 왼쪽 인물과 장소 칸은 버튼으로 열고, 오른쪽 스티커 칸은 스티커가 있을 때만 열린다(011 5.6절, rawdev 2026-11-24). */
30
+ #stage { position: relative; display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; padding: 14px; align-items: start; min-height: 100%; }
31
+ #stage.with-side { grid-template-columns: 250px minmax(0, 1fr); }
32
+ #stage.with-gutter { grid-template-columns: minmax(0, 1fr) 250px; }
33
+ #stage.with-side.with-gutter { grid-template-columns: 250px minmax(0, 1fr) 250px; }
34
+ #gutter { min-height: 60px; border-left: 1px dashed var(--line); padding-left: 10px; color: var(--muted); font-size: 12px; }
35
+ /* 탭 줄 오른쪽의 칸 열기 버튼과 접힌 메뉴 */
36
+ .story-tabs .bar-tools { margin-left: auto; display: flex; gap: 4px; align-items: center; padding-bottom: 3px; }
37
+ .story-tabs .bar-tools .icon { font-size: 15px; padding: 1px 6px; }
38
+ .story-tabs .bar-tools .icon[aria-pressed="true"] { background: var(--soft); color: var(--text); }
39
+ .story-tabs .bar-tools .dot { margin-left: 1px; }
40
+ .more { position: relative; display: inline-block; }
41
+ .more > summary { list-style: none; cursor: pointer; }
42
+ .more > summary::-webkit-details-marker { display: none; }
43
+ .more-menu { position: absolute; z-index: 45; right: 0; top: calc(100% + 3px); min-width: 210px; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; box-shadow: var(--shadow); padding: 6px; display: grid; gap: 6px; justify-items: start; }
44
+ .more-menu .label { font-size: 12px; color: var(--muted); }
45
+ .view-chip { font-size: 12px; }
46
+ .head-tools { display: flex; gap: 6px; align-items: center; margin-left: auto; }
47
+ .feed-toggle { display: flex; width: 100%; align-items: center; gap: 6px; background: transparent; border: 0; padding: 0; text-align: left; }
48
+ .feed-toggle h2 { flex: 1; }
49
+
50
+ section { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px 12px; margin-bottom: 14px; }
51
+ .head { display: flex; align-items: center; justify-content: space-between; gap: 6px; margin-bottom: 6px; flex-wrap: wrap; }
52
+ h2 { font-size: 14px; margin: 0; color: var(--muted); font-weight: 600; }
53
+ ol, ul { list-style: none; margin: 0; padding: 0; }
54
+
55
+ button { font: inherit; color: inherit; cursor: pointer; }
56
+ .btn { white-space: nowrap; background: transparent; border: 1px solid var(--line); border-radius: 5px; padding: 1px 8px; font-size: 13px; line-height: 1.6; }
57
+ .btn:hover { background: var(--soft); }
58
+ .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
59
+ .btn.danger { color: var(--del); border-color: var(--del); }
60
+ .icon { background: transparent; border: 0; border-radius: 4px; padding: 0 5px; color: var(--muted); font-size: 13px; line-height: 1.6; min-width: 22px; }
61
+ .icon:hover { background: var(--soft); color: var(--text); }
62
+ .icon.armed { background: var(--del-bg); color: var(--del); font-weight: 600; }
63
+ button:focus-visible, select:focus-visible, textarea:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
64
+
65
+ .row { position: relative; display: flex; gap: 6px; padding: 5px 6px 5px 4px; margin: 0 -6px; border-radius: 6px; border-left: 3px solid transparent; }
66
+ .row + .row { margin-top: 2px; }
67
+ .row.drop-before::before, .row.drop-after::after { content: ""; position: absolute; left: 0; right: 0; height: 2px; background: var(--accent); }
68
+ .row.drop-before::before { top: -2px; }
69
+ .row.drop-after::after { bottom: -2px; }
70
+ .row.dragging { opacity: .45; }
71
+ .row.drop-into { box-shadow: inset 0 0 0 2px var(--accent); }
72
+ .group-row { align-items: baseline; }
73
+ .group-row .gtitle { font-weight: 600; cursor: pointer; }
74
+ .group-row .gcount { color: var(--muted); font-size: 12px; margin-left: 8px; }
75
+ .gtoggle { flex: none; border: 0; background: transparent; color: var(--muted); cursor: pointer; padding: 0 2px; min-width: 1.2em; }
76
+ .gpath { display: block; color: var(--muted); font-size: 11px; }
77
+ .read-group { list-style: none; font-weight: 600; color: var(--muted); margin: 14px 0 4px; }
78
+ .row.focus { background: var(--node-bg); box-shadow: inset 3px 0 0 var(--accent); }
79
+ .grip { flex: none; align-self: flex-start; cursor: grab; color: var(--muted); border: 0; background: transparent; padding: 0 2px; line-height: 1.6; }
80
+ .num { color: var(--muted); min-width: 1.5em; text-align: right; flex: none; }
81
+ .row-body { flex: 1; min-width: 0; overflow-wrap: anywhere; }
82
+ .title { font-weight: 600; }
83
+ .tools { flex: none; display: flex; gap: 1px; align-items: flex-start; }
84
+ .line { display: flex; gap: 4px; align-items: flex-start; border-radius: 4px; padding: 1px 3px; }
85
+ .line-text { flex: 1; min-width: 0; cursor: text; border: 0; background: transparent; text-align: left; padding: 0; }
86
+ .line-tools { flex: none; display: flex; }
87
+ @media (hover: hover) {
88
+ .tools, .line-tools, .mini { opacity: 0; transition: opacity .1s; }
89
+ .row:hover > .tools, .row:focus-within > .tools, .line:hover > .line-tools, .line:focus-within > .line-tools, .has-mini:hover .mini, .has-mini:focus-within .mini { opacity: 1; }
90
+ }
91
+ .empty { color: var(--muted); font-size: 14px; }
92
+
93
+ button.node { color: var(--node); background: var(--node-bg); border: 0; border-radius: 4px; padding: 0 2px; line-height: inherit; }
94
+ button.node.on { outline: 2px solid var(--node); }
95
+ .frame-mark { text-decoration: underline; text-underline-offset: 2px; color: var(--muted); }
96
+ .gone { color: var(--muted); text-decoration: line-through; text-decoration-thickness: 1px; }
97
+ .line.hit, .memo.hit { background: var(--hit); box-shadow: inset 2px 0 0 var(--hit-line); }
98
+
99
+ .m-add { border-left-color: var(--add); background: var(--add-bg); }
100
+ .m-update { border-left-color: var(--upd); background: var(--upd-bg); }
101
+ .m-move { border-left-color: var(--mov); background: var(--mov-bg); }
102
+ .line.m-add { box-shadow: inset 2px 0 0 var(--add); background: var(--add-bg); }
103
+ .line.m-update { box-shadow: inset 2px 0 0 var(--upd); background: var(--upd-bg); }
104
+ .old.m-add, .old.m-update, .old.m-move { opacity: .78; }
105
+ .tag { display: inline-block; font-size: 12px; line-height: 1.5; padding: 0 5px; border-radius: 3px; margin-left: 6px; vertical-align: 1px; border: 0; }
106
+ .tag.add { color: var(--add); background: var(--add-bg); }
107
+ .tag.update { color: var(--upd); background: var(--upd-bg); }
108
+ .tag.move { color: var(--mov); background: var(--mov-bg); }
109
+ .tag.remove { color: var(--del); background: var(--del-bg); }
110
+ .before { color: var(--muted); font-size: 13px; padding: 2px 4px 2px 8px; border-left: 2px solid var(--line); margin: 2px 0 4px; }
111
+
112
+ /* 장면 아래의 본문(novel.md 7.1절). 처음에는 접혀 있고 누르면 펼쳐진다. */
113
+ .body { margin: 4px 0 2px; padding-left: 8px; border-left: 2px solid var(--line); }
114
+ /* 장면 줄의 도구 칸은 숨어 있어도 자리를 차지하므로, 본문은 줄 아래 둘째 줄에 줄 너비 전체로 놓는다 */
115
+ .row.scene-row { flex-wrap: wrap; row-gap: 0; }
116
+ .row.scene-row > .row-body { flex-basis: 0; }
117
+ .row.scene-row > .body, .row.scene-row > .adopt { flex: 0 0 calc(100% - 2.6em); margin-left: 2.6em; }
118
+ .body-toggle { display: flex; gap: 6px; align-items: baseline; width: 100%; min-width: 0; text-align: left; background: transparent; border: 0; padding: 1px 3px; border-radius: 4px; color: var(--muted); font-size: 13px; }
119
+ .body-toggle:hover { background: var(--soft); }
120
+ .body-toggle .count { flex: none; }
121
+ .body-toggle .first { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
122
+ .para { position: relative; display: flex; gap: 4px; align-items: flex-start; border-radius: 4px; padding: 2px 3px; }
123
+ .para + .para, .para-wrap + .para-wrap { margin-top: 2px; }
124
+ .para .grip { font-size: 12px; }
125
+ .para-text { flex: 1; min-width: 0; cursor: text; line-height: 1.75; overflow-wrap: anywhere; }
126
+ .para.m-add { box-shadow: inset 2px 0 0 var(--add); background: var(--add-bg); }
127
+ .para.m-update { box-shadow: inset 2px 0 0 var(--upd); background: var(--upd-bg); }
128
+ .para.m-move { box-shadow: inset 2px 0 0 var(--mov); background: var(--mov-bg); }
129
+ .para.hit { background: var(--hit); box-shadow: inset 2px 0 0 var(--hit-line); }
130
+ .para.focus { background: var(--node-bg); }
131
+ .para.dragging { opacity: .45; }
132
+ .para.drop-before::before, .para.drop-after::after { content: ""; position: absolute; left: 0; right: 0; height: 2px; background: var(--accent); }
133
+ .para.drop-before::before { top: -2px; }
134
+ .para.drop-after::after { bottom: -2px; }
135
+ .para-tools { flex: none; display: flex; }
136
+ @media (hover: hover) {
137
+ .para-tools { opacity: 0; transition: opacity .1s; }
138
+ .para:hover > .para-tools, .para:focus-within > .para-tools { opacity: 1; }
139
+ }
140
+ .body-add { margin-top: 3px; }
141
+ /* 결과물에서 들이기(novel.md 7.3절) */
142
+ .adopt { background: var(--soft); border-radius: 6px; padding: 6px 8px; margin-top: 4px; font-size: 14px; }
143
+ .adopt .pick { display: block; width: 100%; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 5px; padding: 3px 8px; margin-top: 4px; }
144
+ .adopt .pick:hover { border-color: var(--accent); }
145
+ .adopt small { color: var(--muted); margin-left: 6px; }
146
+ .adopt .preview { white-space: pre-wrap; overflow-wrap: anywhere; background: var(--panel); border: 1px solid var(--line); border-radius: 5px; padding: 4px 8px; margin: 4px 0; max-height: 240px; overflow: auto; }
147
+ .adopt .actions { margin-top: 4px; }
148
+ /* 이어 읽기(7.2절). 글 줄을 숨기고 장면 제목과 본문만 차례로 보인다. */
149
+ /* 목록의 검색칸, 쪽 나누기, 접힌 줄(메모함과 같은 모양) */
150
+ .list-tools { display: flex; flex-direction: column; gap: 3px; margin: 0 0 6px; }
151
+ .list-tools .find { font: inherit; font-size: 13px; color: inherit; background: var(--bg); border: 1px solid var(--line); border-radius: 5px; padding: 3px 6px; width: 100%; box-sizing: border-box; }
152
+ .list-tools .find:focus { outline: none; border-color: var(--accent); }
153
+ .list-pager { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 5px; margin: 8px 0; }
154
+ .list-pager .page-now { font-size: 13px; padding: 0 4px; }
155
+ .list-pager .btn:disabled { opacity: .45; cursor: default; }
156
+ .row.row-closed { cursor: pointer; }
157
+ .row.row-closed:hover { background: var(--soft); }
158
+ .row-preview .preview-text { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden; color: var(--text); }
159
+ .row-preview .title { margin-bottom: 1px; }
160
+ .story-tabs { display: flex; gap: 2px; border-bottom: 1px solid var(--line); margin-bottom: 10px; align-items: flex-end; }
161
+ .story-tabs .tab-list { display: flex; gap: 2px; }
162
+ .story-tabs .tab-list button { border: 0; border-bottom: 2px solid transparent; background: transparent; padding: 6px 14px; font: inherit; font-weight: 600; color: var(--muted); margin-bottom: -1px; }
163
+ .story-tabs .tab-list button:hover { color: var(--text); }
164
+ .story-tabs .tab-list button[aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); }
165
+ .story-tabs .count { font-weight: 400; font-size: 12px; color: var(--muted); margin-left: 2px; }
166
+ .story-tabs .dot { color: var(--accent); font-size: 9px; margin-left: 4px; vertical-align: 1px; }
167
+ .mode { display: inline-flex; border: 1px solid var(--line); border-radius: 5px; overflow: hidden; }
168
+ .mode button { border: 0; background: transparent; padding: 1px 8px; font-size: 13px; }
169
+ .mode button[aria-pressed="true"] { background: var(--accent); color: var(--accent-text); }
170
+ .reading .row { display: block; padding: 6px 6px 8px 8px; }
171
+ .read-title { font-size: 15px; margin: 0 0 4px; font-weight: 600; }
172
+ .reading .body { border-left: 0; padding-left: 0; }
173
+
174
+ /* 시각과 메타데이터(novel.md 16절). 장면과 사실의 제목 아래 한 줄이다. */
175
+ .meta { display: flex; flex-wrap: wrap; gap: 2px 8px; align-items: center; font-size: 13px; color: var(--muted); margin: 0 0 1px; }
176
+ .meta-part { background: transparent; border: 0; border-radius: 4px; padding: 0 3px; color: var(--muted); text-align: left; }
177
+ .meta-part:hover { background: var(--soft); color: var(--text); }
178
+ .meta-part.set { color: var(--text); }
179
+ .meta-part .k { color: var(--muted); margin-right: 3px; }
180
+ .meta-sep { color: var(--line); }
181
+ .wtag { display: inline-block; font-size: 12px; line-height: 1.5; padding: 0 6px; border-radius: 9px; margin-right: 3px; color: #fff; }
182
+ .chips { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; margin: 0 0 6px; }
183
+ .chip { border: 1px solid var(--line); background: transparent; border-radius: 12px; padding: 0 9px; font-size: 13px; }
184
+ .chip[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
185
+ .picker { background: var(--soft); border-radius: 6px; padding: 6px 8px; margin: 4px 0; font-size: 14px; display: grid; gap: 4px; }
186
+ .picker label { display: flex; gap: 6px; align-items: baseline; }
187
+ .picker .when { color: var(--muted); font-size: 12px; flex: none; }
188
+ .gap-band { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 12px; height: 14px; margin: 3px 0; }
189
+ .gap-band::before, .gap-band::after { content: ""; flex: 1; border-top: 1px dashed var(--line); }
190
+ .untimed { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 12px; margin: 6px 0 3px; }
191
+ .untimed::before, .untimed::after { content: ""; flex: 1; border-top: 1px solid var(--line); }
192
+ .panel { background: var(--soft); border-radius: 6px; padding: 8px 10px; margin: 0 0 8px; font-size: 14px; display: grid; gap: 6px; }
193
+ .panel h3 { font-size: 13px; margin: 4px 0 0; color: var(--muted); font-weight: 600; }
194
+ .panel .item { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; background: var(--panel); border: 1px solid var(--line); border-radius: 5px; padding: 3px 8px; }
195
+ .panel .item small { color: var(--muted); }
196
+ /* 일어난 차례 보기(16.5.2절). 사실 세로줄 오른쪽에 장면 카드를 붙인 한 판이다. */
197
+ .occur { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 0 10px; }
198
+ .occur > .cell { padding: 3px 0; border-top: 1px solid var(--soft); min-width: 0; }
199
+ .occur > .gap-band, .occur > .untimed { grid-column: 1 / -1; }
200
+ .occur .fact-cell { font-size: 14px; overflow-wrap: anywhere; border-radius: 4px; padding: 3px 4px; }
201
+ .occur .fact-cell.drop-on { outline: 2px dashed var(--accent); outline-offset: -2px; }
202
+ .occur .fact-cell .when { color: var(--muted); font-size: 12px; display: block; }
203
+ .scard { display: block; width: 100%; text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 5px; padding: 2px 8px; margin-bottom: 3px; font-size: 14px; cursor: grab; }
204
+ .scard:hover { border-color: var(--accent); }
205
+ .scard small { color: var(--muted); margin-left: 4px; }
206
+ .scard.focus { background: var(--node-bg); }
207
+ .occur ol { margin-bottom: 4px; }
208
+
209
+ /* 읽기만 하는 보조 보기(032 10.2절). 고치는 도구를 숨긴다. 보기를 바꾸는 것(목록과 이어 읽기, 차례, 칩, 본문 펼치기)은 남는다. */
210
+ #stage.readonly .tools, #stage.readonly .line-tools, #stage.readonly .para-tools, #stage.readonly .mini,
211
+ #stage.readonly .grip, #stage.readonly .head .btn, #stage.readonly .world-btn, #stage.readonly .memo-add, #stage.readonly .body-add, #stage.readonly .conflict .actions { display: none !important; }
212
+ #stage.readonly .line-text, #stage.readonly .para-text, #stage.readonly .meta-part { cursor: default; }
213
+ #stage.readonly .meta-part:hover { background: transparent; color: inherit; }
214
+ #stage.readonly .memo-bar { cursor: default; }
215
+
216
+ /* 입력 */
217
+ textarea, input[type=text], select { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--accent); border-radius: 5px; padding: 2px 6px; }
218
+ select { border-color: var(--line); max-width: 100%; }
219
+ textarea { width: 100%; display: block; resize: vertical; min-height: 2.1em; }
220
+ input[type=text] { width: 100%; }
221
+ .edit { position: relative; flex: 1; min-width: 0; }
222
+ .hint { color: var(--muted); font-size: 12px; margin: 2px 0 0; }
223
+ .suggest { position: absolute; z-index: 30; left: 0; right: 0; top: 100%; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; box-shadow: var(--shadow); margin-top: 2px; max-height: 200px; overflow: auto; }
224
+ .suggest button { display: block; width: 100%; text-align: left; border: 0; background: transparent; padding: 2px 8px; }
225
+ .suggest button.on { background: var(--node-bg); }
226
+ .suggest small { color: var(--muted); margin-left: 6px; }
227
+ .ask { background: var(--soft); border-radius: 6px; padding: 6px 8px; margin-top: 4px; font-size: 14px; }
228
+ .ask .choices { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
229
+ .form { display: grid; gap: 5px; margin-top: 6px; }
230
+ .form .actions, .actions { display: flex; flex-wrap: wrap; gap: 5px; }
231
+
232
+ /* 인물과 장소 */
233
+ .node-row { display: flex; align-items: center; gap: 5px; padding: 1px 3px; border-radius: 4px; flex-wrap: wrap; }
234
+ .kind { color: var(--muted); font-size: 12px; }
235
+ .note { color: var(--muted); font-size: 13px; padding-left: 4px; overflow-wrap: anywhere; }
236
+ .rel { font-size: 14px; padding: 2px 3px; overflow-wrap: anywhere; border-radius: 4px; display: flex; gap: 4px; flex-wrap: wrap; align-items: center; }
237
+
238
+ /* 스티커. 메모함의 메모를 붙인 것이라 메모처럼 보인다. */
239
+ .memo { position: absolute; z-index: 10; width: 225px; background: var(--memo); color: var(--memo-text); border: 1px solid var(--memo-line); border-radius: 5px; box-shadow: var(--shadow); font-size: 14px; padding: 0 8px 6px; }
240
+ .memo.floating { z-index: 40; opacity: .92; }
241
+ .memo-bar { display: flex; align-items: center; gap: 2px; cursor: grab; touch-action: none; user-select: none; min-height: 22px; font-size: 12px; opacity: .8; }
242
+ .memo-bar .where { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
243
+ .memo .icon { color: inherit; }
244
+ .memo-text { display: block; width: 100%; text-align: left; background: transparent; border: 0; padding: 0; color: inherit; overflow-wrap: anywhere; cursor: text; }
245
+ .memo textarea { background: var(--panel); color: var(--text); }
246
+ [data-target].drop-on { outline: 2px dashed var(--accent); outline-offset: 1px; }
247
+ #memoLayer { position: absolute; inset: 0; pointer-events: none; }
248
+ #memoLayer > * { pointer-events: auto; }
249
+
250
+ /* 부딪힘 */
251
+ .conflict { border: 1px solid var(--del); border-radius: 6px; padding: 6px 8px; margin: 4px 0; background: var(--panel); }
252
+ .conflict h3 { margin: 0 0 4px; font-size: 13px; color: var(--del); font-weight: 600; }
253
+ .sides { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
254
+ .side { border: 1px solid var(--line); border-radius: 5px; padding: 3px 6px; overflow-wrap: anywhere; font-size: 14px; }
255
+ .side b { display: block; font-size: 12px; color: var(--muted); font-weight: 600; }
256
+ .warn { font-size: 12px; color: var(--muted); margin: 4px 0; overflow-wrap: anywhere; }
257
+ .conflict .actions { margin-top: 5px; }
258
+
259
+ .feed li { padding: 4px 0; border-top: 1px solid var(--line); font-size: 13px; overflow-wrap: anywhere; }
260
+ .feed li:first-child { border-top: 0; }
261
+ .who { color: var(--muted); font-size: 12px; display: block; }
262
+ .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; }
263
+ .feed-head:hover { background: var(--soft); }
264
+ .feed-head .headline { display: block; font-size: 13px; }
265
+ .feed-head .who b { color: var(--text); }
266
+ .pending-chip { margin-left: 6px; color: var(--muted); font-size: 11px; }
267
+ .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; }
268
+ .feed-detail li { border-top: 0; padding: 1px 0; font-size: 12px; }
269
+ .feed-detail .kind-tag { color: var(--muted); font-weight: 600; }
270
+ .legend { color: var(--muted); font-size: 12px; margin: 0 0 6px; }
271
+
272
+ #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); }
273
+ /* 고른 줄이나 인물이 있을 때 위쪽 가운데에 뜨는 AI 에게 말하는 칸. 아래쪽은 잘 보이지 않아 위에 둔다(rawdev 2026-11-25) */
274
+ #quickTalk { position: fixed; z-index: 40; left: 50%; top: 8px; transform: translateX(-50%); width: min(560px, calc(100% - 24px)); display: flex; gap: 4px; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 5px 6px; box-shadow: 0 2px 10px rgba(0, 0, 0, .14); }
275
+ #quickSaid { flex: 1; min-width: 0; font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--line); border-radius: 5px; padding: 3px 8px; }
276
+ body.quick #stage { padding-top: 60px; }
277
+ #toast.bad { background: var(--del); color: #fff; }
278
+ #error { color: var(--del); padding: 16px; }
279
+ [hidden] { display: none !important; }
280
+
281
+ /* 좁은 화면에서는 스티커를 끌지 않고 한 줄로 놓는다. 붙이기는 메뉴로 한다. */
282
+ @media (max-width: 1000px) {
283
+ #stage, #stage.with-side, #stage.with-gutter, #stage.with-side.with-gutter { grid-template-columns: minmax(0, 1fr); }
284
+ #middle { order: -1; }
285
+ #gutter { border: 0; padding: 0; order: 3; min-height: 0; }
286
+ #memoLayer { position: static; }
287
+ .memo { position: static; width: auto; margin-bottom: 6px; }
288
+ .memo-bar { cursor: default; }
289
+ }
290
+ </style>
291
+ </head>
292
+ <body>
293
+ <div id="error" role="alert" hidden></div>
294
+ <main id="stage"></main>
295
+ <div id="toast" role="status" hidden></div>
296
+ <div id="quickTalk" hidden>
297
+ <input id="quickSaid" type="text" autocomplete="off" aria-label="What to tell the AI about the selection" placeholder="Tell the AI about the selection">
298
+ <button type="button" class="btn primary" id="quickSend" title="Send selection and words">Send</button>
299
+ </div>
300
+ <script>
301
+ // 스토리 목록의 화면(011 3절, 017 5.3절). 호스트 연결로만 코어와 이야기한다. 글은 모두 textContent 로 넣는다.
302
+ // 사람이 화면에서 하는 일도 모두 011 6.1절의 조작으로 바뀌어 AI 와 같은 경로로 저장된다.
303
+ 'use strict';
304
+
305
+ // ---- 화면의 언어 ----
306
+ // 화면의 언어(plugin-guide 3.7절, 4.4절). 영어가 원문이고, 호스트가 capabilities().language 로 "ko" 를 줄 때만 KO 사전(영어 원문 -> 한국어)에서
307
+ // 찾는다. 다른 값이거나 없으면(옛 호스트) 영어다. 사람이 언어를 바꾸면 호스트가 화면을 다시 여므로 시작할 때 한 번만 읽는다.
308
+ // 논리가 돌려주는 글(요약, 거절 까닭, "Scene 1" 같은 이름표), 사람이 쓴 작업의 글, 파서가 읽는 시각 형식은 옮기지 않는다.
309
+ // 시험(tests/e2e/story-lang.test.ts)은 t(), tKey(), tCount() 의 글이 모두 사전에 있고 사전에 쓰지 않는 글이 없는지 본다.
310
+ let lang = 'en';
311
+ const KO = {
312
+ 'Story List': '스토리 목록',
313
+ 'What to tell the AI about the selection': '고른 것에 대해 AI 에게 할 말',
314
+ 'Tell the AI about the selection': '고른 것에 대해 AI 에게 말하기',
315
+ 'Send selection and words': '고른 것과 적은 말 보내기',
316
+ 'Send': '보내기',
317
+ 'This screen is a read-only view. To make changes, switch to the editing screen.': '이 화면은 읽기만 하는 보기입니다. 고치려면 편집 화면으로 옮깁니다.',
318
+ 'Tell the AI about {what}': '{what} 에 대해 AI 에게 말하기',
319
+ ' and ': ', ',
320
+ 'Open a row or select a character or place first': '먼저 줄을 펼치거나 인물이나 장소를 고르세요',
321
+ 'Write what you want to tell the AI': 'AI 에게 할 말을 적어 주세요',
322
+ 'Could not send the selection': '고른 것을 보내지 못했습니다',
323
+ 'Sent to the AI ({selection})': 'AI 에게 보냈습니다({selection})',
324
+ 'Withdrawn changes: {list}': '철회한 변경: {list}',
325
+ 'Remove {what}': '{what} 지우기',
326
+ 'Remove?': '지울까요?',
327
+ 'New': '새로 생김',
328
+ 'Changed': '고침',
329
+ 'Moved': '옮김',
330
+ 'Removed': '지움',
331
+ 'Group': '묶음',
332
+ 'Line': '글 줄',
333
+ 'Memo': '메모',
334
+ 'Character or place': '인물과 장소',
335
+ 'Relation': '관계',
336
+ 'World line': '세계선',
337
+ 'Calendar': '달력',
338
+ 'Screen': '화면',
339
+ 'Sticker': '스티커',
340
+ 'added': '더함',
341
+ 'changed': '고침',
342
+ 'moved': '옮김',
343
+ 'removed': '지움',
344
+ 'row': '줄',
345
+ 'new name': '새 이름',
346
+ 'Enter to save, Esc to cancel. Type [ to pick a character or place.': 'Enter 로 저장, Esc 로 취소. [ 를 치면 인물과 장소를 고릅니다.',
347
+ 'There is more than one "{name}". Which one?': '"{name}" 이 둘 이상입니다. 어느 쪽인가요?',
348
+ 'There is no "{name}" yet.': '"{name}" 은 아직 없는 이름입니다.',
349
+ 'Make a character': '인물로 만들기',
350
+ 'Make a place': '장소로 만들기',
351
+ 'Keep as plain text': '보통 글로 두기',
352
+ 'Fact row': '사실 줄',
353
+ 'Scene row': '장면 줄',
354
+ 'Sticker attached to {target}': '스티커를 {target} 에 붙임',
355
+ 'Sticker placed in the work area': '스티커를 작업 영역에 둠',
356
+ 'The same place was changed in different ways': '같은 곳을 다르게 바꿨습니다',
357
+ 'What this points to was removed': '가리키는 것이 지워졌습니다',
358
+ ' ({count} conflicts are resolved together)': ' ({count}건을 함께 풉니다)',
359
+ 'Mine': '내 것',
360
+ "{name}'s": '{name} 것',
361
+ 'The other participant': '상대',
362
+ 'If you take mine, this whole change by {name} is cancelled: {summary}': '내 것을 고르면 {name} 의 이 변경이 통째로 취소됩니다: {summary}',
363
+ 'the other participant': '상대',
364
+ 'If you take theirs, this whole change of yours is cancelled: {summary}': '상대 것을 고르면 내 이 변경이 통째로 취소됩니다: {summary}',
365
+ 'Take mine': '내 것으로',
366
+ "Take {name}'s": '{name} 것으로',
367
+ 'Merge both': '둘을 합쳐 쓰기',
368
+ 'Conflict': '부딪힘',
369
+ 'The AI changed this and it is not confirmed yet. Your next operation confirms everything shown up to now.': 'AI 가 바꾸었고 아직 확정되지 않았습니다. 다음 조작을 하면 지금 보이는 데까지 확정됩니다.',
370
+ 'Edit line: {text}': '글 줄 고치기: {text}',
371
+ 'Show the text before the change': '바뀌기 전 글 보기',
372
+ 'line': '글 줄',
373
+ 'Before: ': '바뀌기 전: ',
374
+ 'Paragraph': '문단',
375
+ 'Drag to change the paragraph order': '끌어서 문단 순서 바꾸기',
376
+ 'Drag to move the paragraph': '문단 끌어서 옮기기',
377
+ 'Edit paragraph: {text}': '문단 고치기: {text}',
378
+ 'paragraph': '문단',
379
+ '+ Paragraph': '+ 문단',
380
+ '(no body text)': '(본문 없음)',
381
+ '{arrow} Body text: {n} paragraph': '{arrow} 본문 {n}개 문단',
382
+ '{arrow} Body text: {n} paragraphs': '{arrow} 본문 {n}개 문단',
383
+ 'New paragraph': '새 문단',
384
+ 'Save': '저장',
385
+ 'Cancel': '취소',
386
+ 'Time (for example: {example}). Leave it empty to remove the time': '시각(예: {example}). 비우면 지웁니다',
387
+ 'Write it in the calendar of': '어느 세계선의 달력으로',
388
+ 'Default calendar': '기본 달력',
389
+ 'No time': '시각 없음',
390
+ 'There are no facts yet.': '사실이 아직 없습니다.',
391
+ 'Point of view character': '시점 인물',
392
+ 'No point of view': '시점 없음',
393
+ 'Time': '시각',
394
+ 'none': '없음',
395
+ ' ~ until {fact}': ' ~ {fact} 까지',
396
+ ' (from facts)': '(사실에서)',
397
+ 'Facts': '사실',
398
+ 'Point of view': '시점',
399
+ 'Filter by world line': '세계선으로 거르기',
400
+ 'All': '모두',
401
+ 'World line name': '세계선 이름',
402
+ 'Short note': '짧은 설명',
403
+ 'Name': '이름',
404
+ 'Epoch (the first day of year 1 of this calendar, written in the Earth calendar)': '원년(이 달력의 1년 1월 1일을 지구 달력으로)',
405
+ 'Months of a year (one per line: "name days")': '1년의 달(줄마다 "이름 날 수")',
406
+ 'Units within a day (largest first, one per line: "name count". The last one is the second)': '하루 안의 단위(큰 것부터, 줄마다 "이름 수". 마지막이 초)',
407
+ 'Length of one second (nanoseconds)': '1초의 길이(나노초)',
408
+ 'This calendar has more than one leap year rule, so they are kept as they are here.': '윤년 규칙이 여럿이라 여기서는 그대로 둡니다.',
409
+ 'Leap year rule (for example 4,!100,400. Leave it empty for no leap years)': '윤년 규칙(예: 4,!100,400. 비우면 윤년 없음)',
410
+ 'Number of the month that gets the leap day': '윤일을 더할 달의 번호',
411
+ 'The eras are not in a shape this form can edit, so they are kept as they are. To change the eras, ask the AI.': '연호가 여기서 고치는 모양이 아니라 그대로 둡니다. 연호는 AI 에게 말해 고칩니다.',
412
+ 'Era (counted from the epoch. Leave it empty for year numbers only)': '연호(원년에 시작. 비우면 연도만)',
413
+ 'Era before the epoch (leave it empty for year 0, year -1)': '원년 이전의 연호(비우면 0년, -1년)',
414
+ 'World lines': '세계선',
415
+ 'Without world lines, every time is written in the default calendar.': '세계선이 없으면 모든 시각이 기본 달력으로 적힙니다.',
416
+ 'Calendar of {name}': '{name} 의 달력',
417
+ 'Edit': '고침',
418
+ 'Edit {name}': '{name} 고치기',
419
+ 'world line {name}': '세계선 {name}',
420
+ '+ World line': '+ 세계선',
421
+ 'Calendars': '달력',
422
+ '{n} month, a day of {units}. Example: {example}': '{n}달, 하루 {units}. 예: {example}',
423
+ '{n} months, a day of {units}. Example: {example}': '{n}달, 하루 {units}. 예: {example}',
424
+ 'Copy': '복사',
425
+ 'Copy {name}': '{name} 복사',
426
+ 'Makes a new calendar from a copy. If you change only the epoch, each world can have a calendar with its own epoch': '복사해 새 달력을 만듭니다. 원년만 바꾸면 세계마다 원년이 다른 달력이 됩니다',
427
+ 'calendar {name}': '달력 {name}',
428
+ 'Close': '닫기',
429
+ 'Click to expand. Drag next to a fact to make this scene cover that fact': '누르면 펼치고, 사실 옆으로 끌면 그 사실을 다루는 장면이 됩니다',
430
+ 'Click to expand': '누르면 펼칩니다',
431
+ 'Point of view: {name}': '시점 {name}',
432
+ '~ until {fact}': '~ {fact} 까지',
433
+ 'There are no facts or scenes to show.': '보일 사실과 장면이 없습니다.',
434
+ 'No lines': '글 줄 없음',
435
+ 'A fact with a time is placed in the order of events': '시각이 있는 사실은 일어난 차례로 놓입니다',
436
+ 'Drag to change the order': '끌어서 순서 바꾸기',
437
+ 'Drag to move {label}': '{label} 끌어서 옮기기',
438
+ 'Title': '제목',
439
+ 'Enter to save, Esc to cancel. If you leave it empty, the title stays as it is.': 'Enter 로 저장, Esc 로 취소. 비우면 그대로 둡니다.',
440
+ 'New line': '새 글 줄',
441
+ 'Collapse': '접기',
442
+ 'Collapse row': '줄 접기',
443
+ 'Move up': '위로',
444
+ 'Move down': '아래로',
445
+ 'Add a line': '글 줄 더하기',
446
+ 'Adopt': '들이기',
447
+ 'Adopt from an output': '결과물에서 들이기',
448
+ 'Add a body paragraph': '본문 문단 더하기',
449
+ '+ Sticker': '+ 스티커',
450
+ 'Attach a memo from the memo box to this row': '메모함의 메모를 이 줄에 붙이기',
451
+ 'Edit title': '제목 고치기',
452
+ 'scene': '장면',
453
+ 'fact': '사실',
454
+ 'Drag to move': '끌어서 옮기기',
455
+ 'Drag to move group {title}': '묶음 {title} 끌어서 옮기기',
456
+ 'Collapse group {title}': '묶음 {title} 접기',
457
+ 'Expand group {title}': '묶음 {title} 펼치기',
458
+ 'Group name': '묶음 이름',
459
+ 'Enter to save, Esc to cancel.': 'Enter 로 저장, Esc 로 취소.',
460
+ '{shown} of {n} scene': '장면 {shown}개 (전체 {n}개)',
461
+ '{shown} of {n} scenes': '장면 {shown}개 (전체 {n}개)',
462
+ '{n} scene': '장면 {n}개',
463
+ '{n} scenes': '장면 {n}개',
464
+ 'New scene at the end of this group': '이 묶음의 맨 뒤에 넣을 새 장면',
465
+ 'Name of the new group inside this group': '이 묶음 안에 만들 묶음의 이름',
466
+ '+ Scene': '+ 장면',
467
+ 'Add a scene to this group': '이 묶음에 장면 더하기',
468
+ '+ Group': '+ 묶음',
469
+ 'Make a group inside this group': '이 묶음 안에 묶음 만들기',
470
+ 'Rename': '이름',
471
+ 'Rename group': '묶음 이름 고치기',
472
+ 'group (the scenes inside stay)': '묶음(안의 장면은 남음)',
473
+ 'Scene view': '장면 보기',
474
+ 'List': '목록',
475
+ 'Read through': '이어 읽기',
476
+ 'Scene order': '장면의 차례',
477
+ 'Reading order': '읽는 차례',
478
+ 'Order of events': '일어난 차례',
479
+ 'Search': '검색',
480
+ 'Separate words with spaces to show only the items that contain all of them': '단어를 공백으로 나눠 쓰면 모두 든 것만 보입니다',
481
+ '{n} item': '{n}개',
482
+ '{n} items': '{n}개',
483
+ '{found} found (of {total})': '검색 결과 {found}개 (전체 {total}개)',
484
+ 'Pages': '쪽 나누기',
485
+ 'First': '처음',
486
+ 'Previous': '이전',
487
+ 'Page {page} / {pages}': '{page} / {pages} 쪽',
488
+ 'Next': '다음',
489
+ 'Last': '끝',
490
+ 'Showing only the scenes of world line {name}. ': '세계선 {name} 의 장면만 보입니다. ',
491
+ 'Show all': '모두 보기',
492
+ 'Back to the list view': '목록 보기로 돌아갑니다',
493
+ 'Scene views and tools': '장면 보기와 도구',
494
+ 'View': '보기',
495
+ 'Adopt all from the latest output': '최근 결과물 전체 들이기',
496
+ 'Makes a group for scenes. Drag a scene onto a group name to put it inside': '장면을 묶을 묶음을 만듭니다. 장면을 묶음 이름 위로 끌면 그 안에 들어갑니다',
497
+ 'Collapse all groups': '묶음 모두 접기',
498
+ 'Expand all groups': '묶음 모두 펼치기',
499
+ 'World lines and calendars': '세계선과 달력',
500
+ 'Make and edit world lines and calendars': '세계선과 달력을 만들고 고칩니다',
501
+ '+ Fact': '+ 사실',
502
+ 'Write here what applies to the whole story. There is nothing yet.': '이야기 전체에 적용되는 것을 적습니다. 아직 없습니다.',
503
+ 'Place the scenes in the order the story shows them. There are none yet.': '이야기가 보여 주는 순서대로 장면을 놓습니다. 아직 없습니다.',
504
+ 'Search facts': '사실 검색',
505
+ 'Search scenes': '장면 검색',
506
+ 'New fact': '새 사실',
507
+ 'New scene': '새 장면',
508
+ 'New group name': '새 묶음 이름',
509
+ 'There are changes not confirmed yet, or conflicts': '아직 확정되지 않은 변경이나 부딪힘이 있습니다',
510
+ 'Has unconfirmed changes': '확정되지 않은 변경 있음',
511
+ 'conflicts': '부딪힌 것',
512
+ 'characters, places or relations the AI changed': 'AI 가 바꾼 인물, 장소, 관계',
513
+ 'things the AI removed': 'AI 가 지운 것',
514
+ 'Facts and scenes': '사실과 장면',
515
+ 'Scenes': '장면',
516
+ 'Characters and places panel. New: {list}': '인물과 장소 칸. 새로 온 것: {list}',
517
+ 'Characters and places panel': '인물과 장소 칸',
518
+ 'Close the characters and places panel': '인물과 장소 칸을 닫습니다',
519
+ 'Open the panel with characters and places, relations and the change log. New: {list}': '인물과 장소, 관계, 바뀐 기록 칸을 엽니다. 새로 온 것: {list}',
520
+ 'Open the panel with characters and places, relations and the change log': '인물과 장소, 관계, 바뀐 기록 칸을 엽니다',
521
+ '+ Memo': '+ 메모',
522
+ 'Makes a new memo and attaches it to this screen as a sticker. Drag the sticker onto a row to attach it there': '새 메모를 만들어 이 화면에 스티커로 붙입니다. 스티커는 끌어서 줄에 붙입니다',
523
+ 'Notices': '알림',
524
+ 'Conflicts': '부딪힌 것',
525
+ 'Scene': '장면',
526
+ 'Fact': '사실',
527
+ '{kind}: {num} {verb}': '{kind} {num}개 {verb}',
528
+ '{kind} {verb}': '{kind} {verb}',
529
+ 'Change log': '바뀐 기록',
530
+ '{n} {arrow}': '{n}개 {arrow}',
531
+ '{count} more can be read with read_history.': '그 밖에 {count}개는 read_history 로 읽습니다.',
532
+ ' by me': ' 내가 함',
533
+ ' by the AI': ' AI 가 함',
534
+ 'not confirmed': '확정 전',
535
+ 'Show {count} earlier entries': '이전 기록 {count}개 더 보기',
536
+ 'Show earlier entries': '이전 기록 더 보기',
537
+ 'Characters and places': '인물과 장소',
538
+ '+ Add': '+ 더하기',
539
+ 'None yet. You can make one by writing [name] in a line.': '아직 없습니다. 글에 [이름] 을 쓰면 만들 수 있습니다.',
540
+ 'Search characters and places': '인물과 장소 검색',
541
+ 'Relations': '관계',
542
+ '+ Link': '+ 잇기',
543
+ 'Links two characters or places.': '두 인물이나 장소를 잇습니다.',
544
+ 'Search relations': '관계 검색',
545
+ 'Relation name': '관계의 이름',
546
+ 'Rename relation': '관계 이름 고치기',
547
+ 'relation': '관계',
548
+ 'Removed by the AI': 'AI 가 지운 것',
549
+ 'New memo': '새 메모',
550
+ 'Copy of {name}': '{name} 복사',
551
+ 'Please write a name': '이름을 적어 주세요',
552
+ 'Write the months and the units of a day one per line, as "name number"': '달과 하루의 단위는 줄마다 "이름 수" 로 적어 주세요',
553
+ 'Please pick two different ones': '서로 다른 둘을 골라 주세요',
554
+ 'Kind (any word, such as character or place)': '갈래(인물, 장소처럼 자유롭게)',
555
+ 'One': '하나',
556
+ 'The other': '다른 하나',
557
+ 'Name (any words)': '이름(자유 낱말)',
558
+ 'Link': '잇기',
559
+ '{row}, paragraph {n}': '{row} 의 문단 {n}',
560
+ 'Line of {row}': '{row} 의 글 줄',
561
+ 'Work area': '작업 영역',
562
+ 'Removed target': '지워진 대상',
563
+ '{text} (removed {type})': '{text}(지워진 {type})',
564
+ 'target': '대상',
565
+ 'Attach': '붙이기',
566
+ 'Attach somewhere else': '다른 곳에 붙이기',
567
+ 'Detach': '떼기',
568
+ 'Detach the sticker. The memo stays in the memo box': '스티커 떼기. 메모는 메모함에 남습니다',
569
+ 'Where to attach': '붙일 곳',
570
+ 'Where should it go?': '어디에 붙일까요?',
571
+ 'Edit the memo text in the memo box': '메모의 글은 메모함에서 고칩니다',
572
+ 'The memo box is empty. You can attach a new memo with + Memo on the right.': '메모함이 비어 있습니다. 오른쪽의 + 메모로 새 메모를 붙일 수 있습니다.',
573
+ 'No output contains this scene. The AI makes outputs by generating them.': '이 장면이 든 결과물이 없습니다. 결과물은 AI 가 생성으로 만듭니다.',
574
+ 'Adopted': '들였습니다',
575
+ 'Output {id}': '결과물 {id}',
576
+ ', made from unconfirmed changes': ', 확정 안 된 변경이 든 결과물',
577
+ "Which output should this scene's text be adopted from? The newest is at the top.": '어느 결과물의 이 장면 글을 들일까요? 새것이 위에 있습니다.',
578
+ 'Output {id} has no text for this scene.': '결과물 {id} 의 본문에는 이 장면의 글이 없습니다.',
579
+ 'Other output': '다른 결과물',
580
+ 'Replace removes the current body text ({n} paragraph) and puts this text in its place. Append adds this text after the current body text.': '바꾸기는 지금 본문 {n}개 문단을 지우고 이 글로 바꿉니다. 뒤에 붙이기는 지금 본문 뒤에 붙입니다.',
581
+ 'Replace removes the current body text ({n} paragraphs) and puts this text in its place. Append adds this text after the current body text.': '바꾸기는 지금 본문 {n}개 문단을 지우고 이 글로 바꿉니다. 뒤에 붙이기는 지금 본문 뒤에 붙입니다.',
582
+ 'Replace': '바꾸기',
583
+ 'Append': '뒤에 붙이기',
584
+ 'This screen has no outputs. The AI makes outputs by generating them.': '이 화면의 결과물이 없습니다. 결과물은 AI 가 생성으로 만듭니다.',
585
+ 'Adopts all {n} scene of this output with Replace.': '이 결과물의 장면 {n}개를 모두 바꾸기로 들입니다.',
586
+ 'Adopts all {n} scenes of this output with Replace.': '이 결과물의 장면 {n}개를 모두 바꾸기로 들입니다.',
587
+ 'In {n} scene with body text, the current body text is removed and replaced by the text of this output.': '본문이 있는 장면 {n}개는 지금 본문이 지워지고 이 결과물의 글로 바뀝니다.',
588
+ 'In {n} scenes with body text, the current body text is removed and replaced by the text of this output.': '본문이 있는 장면 {n}개는 지금 본문이 지워지고 이 결과물의 글로 바뀝니다.',
589
+ 'Adopt all': '모두 들이기',
590
+ 'Memo to attach': '붙일 메모',
591
+ 'Which memo should be attached?': '어느 메모를 붙일까요?',
592
+ };
593
+
594
+ /** 사람이 읽는 화면 글. text 는 영어 원문이고 vars 의 값이 {이름} 자리에 들어간다. 사전에 없으면 영어로 둔다. */
595
+ function t(text, vars) {
596
+ const out = lang === 'ko' && Object.prototype.hasOwnProperty.call(KO, text) ? KO[text] : text;
597
+ if (!vars) return out;
598
+ return out.replace(/\{(\w+)\}/g, (whole, name) => (Object.prototype.hasOwnProperty.call(vars, name) ? String(vars[name]) : whole));
599
+ }
600
+
601
+ /** 미리 정해 두는 표의 글. 옮기지 않고 그대로 돌려준다. 보일 때 t() 로 옮긴다(시험이 사전과 맞추려고 표시만 한다). */
602
+ function tKey(text) {
603
+ return text;
604
+ }
605
+
606
+ /** 수가 든 글. 영어는 하나면 one, 아니면 many 를 쓴다. 한국어 사전에는 둘 다 같은 글로 둔다. 수는 {n} 자리에 들어간다. */
607
+ function tCount(n, one, many, vars) {
608
+ return t(n === 1 ? one : many, { n, ...vars });
609
+ }
610
+
611
+ /** capabilities() 의 language 로 화면의 언어를 정하고, HTML 에 바로 적힌 글을 옮긴다. */
612
+ function setLanguage(language) {
613
+ lang = language === 'ko' ? 'ko' : 'en';
614
+ if (document.documentElement) document.documentElement.lang = lang;
615
+ document.title = t('Story List');
616
+ const said = document.getElementById('quickSaid');
617
+ said.setAttribute('aria-label', t('What to tell the AI about the selection'));
618
+ said.placeholder = t('Tell the AI about the selection');
619
+ const sendEl = document.getElementById('quickSend');
620
+ sendEl.title = t('Send selection and words');
621
+ sendEl.textContent = t('Send');
622
+ }
623
+ // ---- 화면의 언어 끝 ----
624
+
625
+ const stage = document.getElementById('stage');
626
+ const errorEl = document.getElementById('error');
627
+ const toastEl = document.getElementById('toast');
628
+
629
+ let nextId = 1;
630
+ const waiting = new Map();
631
+ let concept = null;
632
+ let memoById = new Map(); // 스티커가 가리키는 메모. 코어의 메모함에서 읽는다.
633
+ let memoChoices = null; // "+ 스티커" 를 누르면 메모함 전체를 읽어 둔다
634
+ let feed = [];
635
+ let selectedNode = null;
636
+ let focused = new Set(); // 결과물에서 고른 장면
637
+ const openBefore = new Set();
638
+ const openBodies = new Set(); // 본문을 펼친 장면. 화면 상태라 저장하지 않는다(novel.md 7.1절)
639
+ let reading = false; // 이어 읽기(7.2절). 화면 상태다
640
+ // 시각과 세계선(novel.md 16절). 모두 화면 상태라 저장하지 않는다
641
+ const READ_ONLY = tKey('This screen is a read-only view. To make changes, switch to the editing screen.');
642
+ let canEdit = true; // 읽기만 하는 보조 보기면 거짓. 고치는 도구를 숨기고 보내지 않는다(032 10.2절)
643
+ let worldFilter = null; // 고른 세계선 칩. 없으면 모든 사실이다(16.3.5절)
644
+ let occurred = false; // 장면 목록의 "일어난 차례" 보기(16.5.2절)
645
+ let worldPanel = false; // 세계선과 달력을 고치는 작은 판
646
+ let sideOpen = false; // 왼쪽 인물과 장소 칸. 처음에는 닫혀 있다. 화면 상태라 저장하지 않는다(rawdev 2026-11-24)
647
+ const sideConflictSeen = new Set(); // 왼쪽 칸을 열어 보인 부딪힘
648
+ let feedOpen = false; // 왼쪽 칸의 바뀐 기록. 처음에는 접혀 있다
649
+ let moreOpen = false; // 장면 목록의 [⋯] 메뉴. 다시 그려도 열린 채로 둔다
650
+ // 메뉴 밖을 누르면 메뉴를 닫는다
651
+ document.addEventListener?.('pointerdown', (ev) => {
652
+ if (!moreOpen || ev.target.closest?.('.more')) return;
653
+ moreOpen = false;
654
+ for (const d of document.querySelectorAll('details.more[open]')) d.open = false;
655
+ });
656
+ let storyTab = 'scene'; // 가운데 칸에 보이는 탭. 'fact' 사실, 'scene' 장면. 화면 상태라 저장하지 않는다
657
+ // 사실과 장면 목록의 검색, 쪽 나누기, 펼친 줄. 모두 화면 상태라 저장하지 않는다
658
+ const LIST_PAGE = 20; // 한 쪽에 보이는 줄 수
659
+ const listQuery = { fact: '', scene: '', node: '', relation: '' }; // 검색 단어. 공백으로 나눈 단어가 모두 든 것만 보인다
660
+ const listPage = { fact: 0, scene: 0, node: 0, relation: 0, removed: 0 }; // 지금 쪽(0부터)
661
+ let openRow = null; // 펼친 줄의 id. 한 번에 하나만 펼친다. 나머지는 앞 세 줄만 보인다
662
+ const openCards = new Set(); // 일어난 차례 보기에서 펼친 장면 카드
663
+ const openGroups = new Set(); // 펼친 장면 묶음. 처음에는 접혀 있다. 화면 상태라 저장하지 않는다(novel.md 18.5절)
664
+ let editor = null; // 지금 고치는 것 하나. { key, draft, base, ... }
665
+ let composing = false; // 한글 조합 중에는 다시 그리지 않는다
666
+ let dragging = null; // 끄는 중에도 다시 그리지 않는다
667
+ let renderWanted = false;
668
+ // 그린 기준 알림(032 10.3절). 새로 읽은 개념을 실제로 다 그린 뒤에 호스트가 그 읽기에 붙인 표(renderToken)를 돌려준다.
669
+ // 호스트는 표로 그 읽기의 기준을 찾는다. base 를 보내지 않는 것은 revision 번호가 작업마다 h1 부터라 다른 작업의 늦은 알림과 섞이기 때문이다.
670
+ // render 는 한글 조합, 끌기, 저장 중에는 미루므로 refresh 가 아니라 render 가 그리기를 마칠 때 보낸다.
671
+ let drawPending = false;
672
+ let suppressBlur = false;
673
+ const armed = new Map(); // 두 번 눌러야 지운다
674
+
675
+ // 호스트 연결
676
+ function call(method, params) {
677
+ return new Promise((resolve, reject) => {
678
+ const id = nextId++;
679
+ waiting.set(id, { resolve, reject });
680
+ parent.postMessage({ aic: 1, id, method, params }, '*');
681
+ });
682
+ }
683
+
684
+ window.addEventListener('message', (e) => {
685
+ if (e.source !== parent) return;
686
+ const d = e.data;
687
+ if (typeof d !== 'object' || d === null || d.aic !== 1) return;
688
+ if (d.event === 'change') {
689
+ refresh(typeof d.rev === 'string' ? d.rev : null);
690
+ return;
691
+ }
692
+ // 호스트의 결과물 탭에서 장면을 누르거나 고르면 그 장면 줄을 강조한다(030 7.2절). 화면 상태라 저장하지 않는다.
693
+ if (d.event === 'focus') {
694
+ focused = new Set(Array.isArray(d.targets) ? d.targets.filter((x) => typeof x === 'string') : []);
695
+ // 고른 장면의 본문을 펼친다. 견준 뒤에는 사람이 접을 수 있다(novel.md 7.5절)
696
+ for (const id of focused) openBodies.add(id);
697
+ // 고른 것은 장면이다. 사실 탭을 보고 있었다면 장면 탭으로 옮긴다.
698
+ if (focused.size > 0) storyTab = 'scene';
699
+ render();
700
+ const first = [...focused].map((id) => stage.querySelector(`[data-row="${CSS.escape(id)}"]`)).find(Boolean);
701
+ first?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
702
+ return;
703
+ }
704
+ const w = waiting.get(d.id);
705
+ if (!w) return;
706
+ waiting.delete(d.id);
707
+ if (d.error) w.reject(new Error(d.error));
708
+ else w.resolve(d.result);
709
+ });
710
+
711
+ // 돌려주는 약속은 부른 뒤에 시작한 읽기가 끝날 때 풀린다. 내 조작 뒤에 부르면 그 조작이 담긴 상태를 받는다.
712
+ let inflight = null;
713
+ let queued = null;
714
+ // 읽는 동안 온 알림의 revision 들. 이름 없이 부른 것(null)이 하나라도 있으면 반드시 다시 읽는다
715
+ let queuedRevs = null;
716
+ function refresh(rev = null) {
717
+ if (inflight) {
718
+ (queuedRevs ??= []).push(rev);
719
+ queued ??= inflight.then(() => {
720
+ queued = null;
721
+ const revs = queuedRevs ?? [];
722
+ queuedRevs = null;
723
+ // 내 조작의 알림처럼 방금 읽은 기준 안에 든 revision 의 알림뿐이면 같은 것을 다시 읽지 않는다
724
+ if (revs.length > 0 && concept && revs.every((r) => r !== null && seq(r) <= seq(concept.base))) return undefined;
725
+ return refresh();
726
+ });
727
+ return queued;
728
+ }
729
+ inflight = (async () => {
730
+ try {
731
+ let c;
732
+ let changes;
733
+ let memos;
734
+ // 스티커에는 메모의 글이 없다. 메모함에 물어 가져오고, 같은 기준 revision 의 응답만 쓴다(029 5.2절).
735
+ for (let tries = 0; ; tries += 1) {
736
+ [c, changes] = await Promise.all([call('readConcept'), call('readChanges', changesParams())]);
737
+ const ids = [...new Set(((c.withOthers ?? c.body).stickers ?? []).map((x) => x.memo))];
738
+ memos = ids.length ? await call('readMemos', { ids }) : { base: c.base, memos: [] };
739
+ if (memos.base === c.base || tries >= 2) break;
740
+ }
741
+ errorEl.hidden = true;
742
+ concept = c;
743
+ memoById = new Map(memos.base === c.base ? memos.memos.map((m) => [m.id, m]) : []);
744
+ feed = changes.newChanges ?? [];
745
+ // 메모가 같은 기준으로 오지 않았으면 스티커를 다 그리지 못하므로 그렸다고 알리지 않는다. 표가 없는 응답(지난 화면 세대의 것)도 알리지 않는다
746
+ drawPending = memos.base === c.base && typeof c.renderToken === 'string';
747
+ render();
748
+ } catch (err) {
749
+ errorEl.textContent = err.message;
750
+ errorEl.hidden = false;
751
+ }
752
+ })().finally(() => {
753
+ inflight = null;
754
+ });
755
+ return inflight;
756
+ }
757
+
758
+ let toastTimer = null;
759
+ function toast(text, bad = false) {
760
+ toastEl.textContent = text;
761
+ toastEl.classList.toggle('bad', bad);
762
+ toastEl.hidden = false;
763
+ clearTimeout(toastTimer);
764
+ toastTimer = setTimeout(() => { toastEl.hidden = true; }, bad ? 7000 : 3500);
765
+ }
766
+
767
+ // ---- 고른 것을 AI 에게 보내기(032 30절, rawdev 2026-11-25) ----
768
+ // 펼친 줄(사실이나 장면) 하나와 왼쪽 칸에서 고른 인물이나 장소 하나가 고른 것이다. 고른 것이 있으면 위쪽 가운데에 칸이 뜨고(작업 내용은 그만큼 아래로 내린다),
769
+ // 글을 적어 Enter 나 Send 를 누르면 고른 것과 글이 shareSelection 으로 간다. 보내는 내용은 논리의 describeSelection 이 읽는다
770
+ const SELECTION_FORMAT = 'aic.story/selection-1';
771
+ const quickEl = document.getElementById('quickTalk');
772
+ const quickSaidEl = document.getElementById('quickSaid');
773
+ let caps = { edit: true }; // capabilities(). conceptSelection 이 참일 때만 보낸다
774
+ function pickedRecords() {
775
+ if (!concept) return [];
776
+ const n = names();
777
+ const out = [];
778
+ // 다른 참여자의 아직 확정하지 않은 줄($ 로 시작하는 임시 id)은 코어가 모르므로 보내지 않는다
779
+ const real = (id) => typeof id === 'string' && !id.startsWith('$');
780
+ if (real(openRow) && n.row.has(openRow)) out.push(openRow);
781
+ if (real(selectedNode) && n.node.has(selectedNode)) out.push(selectedNode);
782
+ return out;
783
+ }
784
+ function selectionPayload(ids) {
785
+ const n = names();
786
+ const labels = {};
787
+ for (const id of ids) labels[id] = n.row.get(id) ?? n.node.get(id) ?? id;
788
+ return { format: SELECTION_FORMAT, rev: concept.base, records: ids, labels };
789
+ }
790
+ const canShare = () => Boolean(caps.conceptSelection) && canEdit;
791
+ function updateQuick() {
792
+ const ids = canShare() && !dragging ? pickedRecords() : [];
793
+ quickEl.hidden = ids.length === 0;
794
+ document.body?.classList.toggle('quick', ids.length > 0);
795
+ if (ids.length) {
796
+ const n = names();
797
+ quickSaidEl.placeholder = t('Tell the AI about {what}', { what: ids.map((id) => n.row.get(id) ?? n.node.get(id) ?? id).join(t(' and ')) });
798
+ }
799
+ }
800
+ let sharing = false;
801
+ async function shareQuick() {
802
+ if (!canShare() || sharing) return;
803
+ const ids = pickedRecords();
804
+ const said = quickSaidEl.value.trim();
805
+ if (!ids.length) { toast(t('Open a row or select a character or place first'), true); return; }
806
+ if (!said) { toast(t('Write what you want to tell the AI'), true); quickSaidEl.focus(); return; }
807
+ const p = selectionPayload(ids);
808
+ sharing = true;
809
+ try {
810
+ const res = await call('shareSelection', { base: p.rev, role: 'change', said, payload: p, records: ids });
811
+ if (!res?.ok) { toast(res?.summary ?? res?.error ?? t('Could not send the selection'), true); return; }
812
+ if (quickSaidEl.value.trim() === said) quickSaidEl.value = '';
813
+ toast(t('Sent to the AI ({selection})', { selection: res.selection }));
814
+ } catch (err) {
815
+ toast(err.message, true);
816
+ } finally {
817
+ sharing = false;
818
+ }
819
+ }
820
+ quickSaidEl.addEventListener('keydown', (ev) => {
821
+ if (ev.key === 'Enter' && !ev.isComposing) { ev.preventDefault(); shareQuick(); }
822
+ else if (ev.key === 'Escape') quickSaidEl.blur();
823
+ });
824
+ document.getElementById('quickSend').addEventListener('click', shareQuick);
825
+ // 줄이나 장면을 끌어 옮기는 동안에는 칸을 숨긴다. 놓으면 다시 그리면서 돌아온다
826
+ document.addEventListener?.('dragstart', () => { quickEl.hidden = true; });
827
+ document.addEventListener?.('dragend', () => { updateQuick(); });
828
+
829
+ /** 조작을 보낸다. 거절되면 그 까닭을 보여 주고 null 을 돌려준다. */
830
+ let lastOwn = null;
831
+ const seq = (rev) => Number(String(rev).slice(1));
832
+ async function send(steps, opts = {}) {
833
+ if (!canEdit) {
834
+ toast(t(READ_ONLY), true);
835
+ return null;
836
+ }
837
+ // 편집이 출발한 기준을 쓴다. 그사이 내가 다른 조작을 했으면 그 응답까지는 본 것이다.
838
+ let base = opts.base ?? concept.base;
839
+ if (lastOwn && seq(lastOwn) > seq(base)) base = lastOwn;
840
+ const req = { base, steps, ...(opts.resolves ? { resolves: opts.resolves } : {}), ...(opts.take ? { take: opts.take } : {}), ...(opts.artifact ? { artifact: opts.artifact } : {}) };
841
+ let res;
842
+ try {
843
+ res = await call('applyOperation', req);
844
+ } catch (err) {
845
+ toast(err.message, true);
846
+ return null;
847
+ }
848
+ if (!res.ok) {
849
+ toast(res.summary ?? res.error, true);
850
+ await refresh();
851
+ return null;
852
+ }
853
+ lastOwn = res.revision;
854
+ if (res.withdrawn?.length) toast(t('Withdrawn changes: {list}', { list: res.withdrawn.join(', ') }));
855
+ // 내 조작이 담긴 상태면 된다. 알림을 먼저 받아 이미 읽고 있는 것이 그 revision 을 담으면 한 번 더 읽지 않는다
856
+ await refresh(res.revision);
857
+ return res;
858
+ }
859
+
860
+ function el(tag, props, ...children) {
861
+ const n = document.createElement(tag);
862
+ for (const [k, v] of Object.entries(props ?? {})) {
863
+ if (k === 'class') n.className = v;
864
+ else if (k === 'on') for (const [ev, fn] of Object.entries(v)) n.addEventListener(ev, fn);
865
+ else if (k === 'value') n.value = v;
866
+ else if (v !== false && v !== null && v !== undefined) n.setAttribute(k, v === true ? '' : v);
867
+ }
868
+ for (const c of children.flat(Infinity)) {
869
+ if (c === null || c === undefined || c === false) continue;
870
+ n.append(c instanceof Node ? c : String(c));
871
+ }
872
+ return n;
873
+ }
874
+
875
+ const btn = (label, onClick, cls = 'btn', extra = {}) => el('button', { type: 'button', class: cls, on: { click: onClick }, ...extra }, label);
876
+ /** 잘못 누르기 쉬운 것은 두 번 눌러야 지운다. 되돌리는 기능이 아직 화면에 없기 때문이다. */
877
+ function deleteButton(key, what, onConfirm) {
878
+ const on = armed.get(key);
879
+ return el('button', {
880
+ type: 'button',
881
+ class: `icon${on ? ' armed' : ''}`,
882
+ 'aria-label': t('Remove {what}', { what }),
883
+ title: t('Remove {what}', { what }),
884
+ on: {
885
+ click: () => {
886
+ if (armed.get(key)) {
887
+ armed.delete(key);
888
+ onConfirm();
889
+ return;
890
+ }
891
+ armed.set(key, true);
892
+ setTimeout(() => { if (armed.delete(key)) render(); }, 3000);
893
+ render();
894
+ },
895
+ },
896
+ }, on ? t('Remove?') : '×');
897
+ }
898
+
899
+ const ACTION = { add: tKey('New'), update: tKey('Changed'), move: tKey('Moved'), remove: tKey('Removed') };
900
+ // 바뀐 기록의 요약. 종류의 이름, 한 일의 말, 보이는 차례(중요한 것부터)
901
+ // 이름과 말은 영어 원문으로 두고(FEED_ORDER 가 견준다), 보일 때 t() 로 옮긴다
902
+ const FEED_KIND = { group: tKey('Group'), line: tKey('Line'), memo: tKey('Memo'), node: tKey('Character or place'), relation: tKey('Relation'), world: tKey('World line'), calendar: tKey('Calendar'), instance: tKey('Screen'), sticker: tKey('Sticker') };
903
+ const FEED_VERB = { add: tKey('added'), update: tKey('changed'), move: tKey('moved'), remove: tKey('removed') };
904
+ const FEED_ORDER = ['Scene', 'Group', 'Fact', 'Character or place', 'Relation', 'World line', 'Calendar', 'Line', 'Memo', 'Sticker', 'Screen'];
905
+ const FEED_PAGE = 10; // 처음에 보이는 기록 수와, 더 보기 한 번에 늘어나는 수
906
+ const FEED_DETAIL_MAX = 30; // 펼쳤을 때 하나씩 보이는 바뀐 것의 수
907
+ const openFeed = new Set(); // 펼친 기록의 revision. 화면 상태라 저장하지 않는다
908
+ let feedShown = FEED_PAGE;
909
+ // 바뀐 기록은 보이는 만큼만 읽는다. 기록 한 줄에 revision 이 둘쯤 들므로 보이는 줄 수의 세 배에 여유를 더한 만큼 앞에서부터 받는다.
910
+ // 처음 읽을 때는 기준을 모르니 전부 읽는다. feedFrom 이 있으면 그보다 앞의 기록은 아직 읽지 않은 것이다.
911
+ let feedFrom = null;
912
+ const changesParams = () => {
913
+ const from = concept?.base ? seq(concept.base) - (feedShown * 3 + 20) : 0;
914
+ feedFrom = from >= 1 ? `h${from}` : null;
915
+ return feedFrom ? { since: feedFrom } : {};
916
+ };
917
+ const LINE_HEIGHT = 24;
918
+
919
+ // 글 속 표시와 고치는 글을 오간다. 사람은 [철수] 로 쓰고, 같은 이름이 둘이거나 표시 글자가 다르면 id 를 함께 쓴다.
920
+ function names() {
921
+ const body = concept.withOthers ?? concept.body;
922
+ const nodes = body.nodes;
923
+ const rows = [...body.facts, ...body.scenes];
924
+ return {
925
+ nodes,
926
+ rows,
927
+ node: new Map(nodes.map((n) => [n.id, n.name])),
928
+ row: new Map(rows.map((r) => [r.id, r.label])),
929
+ };
930
+ }
931
+
932
+ function plain(segs) {
933
+ const n = names();
934
+ return (segs ?? []).map((s) => {
935
+ if (typeof s === 'string') return s;
936
+ if ('ref' in s) return s.text; // 코어 메모의 표시
937
+ return 'node' in s ? (s.text ?? n.node.get(s.node) ?? s.node) : (n.row.get(s.row) ?? s.row);
938
+ }).join('');
939
+ }
940
+
941
+ function toEditable(segs) {
942
+ const n = names();
943
+ const count = new Map();
944
+ for (const x of n.nodes) count.set(x.name, (count.get(x.name) ?? 0) + 1);
945
+ return (segs ?? []).map((s) => {
946
+ if (typeof s === 'string') return s;
947
+ if ('node' in s) {
948
+ const name = n.node.get(s.node);
949
+ if (s.text !== undefined || (count.get(name) ?? 0) > 1) return `[${s.text ?? name ?? s.node}](${s.node})`;
950
+ return `[${name ?? s.node}]`;
951
+ }
952
+ return `[${n.row.get(s.row) ?? s.row}]`;
953
+ }).join('');
954
+ }
955
+
956
+ /** [이름] 을 찾아 id 를 붙인다. 모르는 이름은 물어볼 목록으로 돌려준다. */
957
+ function fromEditable(draft, choices) {
958
+ const n = names();
959
+ const unknown = [];
960
+ const steps = [];
961
+ const made = new Map();
962
+ const text = draft.replace(/\[([^\[\]]*)\](\(([^()\s]*)\))?/g, (whole, name, withId) => {
963
+ if (withId) return whole;
964
+ const nodes = n.nodes.filter((x) => x.name === name);
965
+ if (nodes.length === 1) return `[${name}](${nodes[0].id})`;
966
+ const row = n.rows.find((r) => r.label === name);
967
+ if (row && nodes.length === 0) return `[${name}](${row.id})`;
968
+ if (nodes.length > 1) {
969
+ const pick = choices?.[name];
970
+ if (pick && pick.startsWith('id:')) return `[${name}](${pick.slice(3)})`;
971
+ if (!unknown.some((u) => u.name === name)) unknown.push({ name, same: nodes });
972
+ return whole;
973
+ }
974
+ const choice = choices?.[name];
975
+ if (choice === 'plain') return name;
976
+ if (!choice) {
977
+ if (!unknown.some((u) => u.name === name)) unknown.push({ name, same: [] });
978
+ return whole;
979
+ }
980
+ if (!made.has(name)) {
981
+ const temp = `$new${made.size + 1}`;
982
+ made.set(name, temp);
983
+ steps.push({ op: 'node.add', as: temp, input: { name, kind: choice } });
984
+ }
985
+ return `[${name}](${made.get(name)})`;
986
+ });
987
+ return { text, steps, unknown };
988
+ }
989
+
990
+ // 고치는 칸. 11.2절대로 편집이 출발한 상태의 기준을 조작에 붙인다.
991
+ function startEdit(e) {
992
+ if (!canEdit) {
993
+ toast(t(READ_ONLY), true);
994
+ return;
995
+ }
996
+ if (editor) commitEditor();
997
+ armed.clear();
998
+ editor = { base: concept.base, choices: {}, unknown: [], suggest: null, ...e };
999
+ render();
1000
+ }
1001
+
1002
+ function closeEditor() {
1003
+ editor = null;
1004
+ render();
1005
+ }
1006
+
1007
+ let committing = false;
1008
+ async function commitEditor() {
1009
+ const e = editor;
1010
+ if (!e || committing) return;
1011
+ if (e.form) {
1012
+ // 입력 칸이 여럿인 것은 저장 버튼으로만 저장한다
1013
+ closeEditor();
1014
+ return;
1015
+ }
1016
+ const draft = (e.draft ?? '').trim();
1017
+ if (e.needsText !== false && draft === '') {
1018
+ closeEditor();
1019
+ return;
1020
+ }
1021
+ if (e.unchanged !== undefined && draft === e.unchanged.trim()) {
1022
+ closeEditor();
1023
+ return;
1024
+ }
1025
+ const parsed = e.plain ? { text: draft, steps: [], unknown: [] } : fromEditable(draft, e.choices);
1026
+ if (parsed.unknown.length) {
1027
+ e.unknown = parsed.unknown;
1028
+ render();
1029
+ return;
1030
+ }
1031
+ committing = true;
1032
+ const res = await send([...parsed.steps, ...e.build(parsed.text)], { base: e.base, ...(e.resolves ? { resolves: e.resolves } : {}) });
1033
+ committing = false;
1034
+ if (editor === e) {
1035
+ if (res) {
1036
+ editor = null;
1037
+ } else {
1038
+ // 기준이 낡았으면 지금 화면을 기준으로 다시 보낼 수 있게 글을 남겨 둔다
1039
+ e.base = concept.base;
1040
+ }
1041
+ }
1042
+ render();
1043
+ }
1044
+
1045
+ function caretQuery(ta) {
1046
+ const before = ta.value.slice(0, ta.selectionStart);
1047
+ const open = before.lastIndexOf('[');
1048
+ if (open < 0 || before.indexOf(']', open) >= 0) return null;
1049
+ return { start: open, query: before.slice(open + 1) };
1050
+ }
1051
+
1052
+ function refreshSuggest(ta) {
1053
+ const e = editor;
1054
+ if (!e || e.plain) return;
1055
+ const q = caretQuery(ta);
1056
+ if (!q) {
1057
+ e.suggest = null;
1058
+ } else {
1059
+ const n = names();
1060
+ const items = [
1061
+ ...n.nodes.filter((x) => x.name.includes(q.query)).map((x) => ({ label: x.name, note: x.kind })),
1062
+ ...n.rows.filter((r) => r.label && r.label.includes(q.query)).map((r) => ({ label: r.label, note: t('row') })),
1063
+ ].slice(0, 8);
1064
+ if (q.query && !n.nodes.some((x) => x.name === q.query)) items.push({ label: q.query, note: t('new name') });
1065
+ e.suggest = items.length ? { items, at: 0, start: q.start } : null;
1066
+ }
1067
+ drawSuggest(ta);
1068
+ }
1069
+
1070
+ function drawSuggest(ta) {
1071
+ const box = ta.parentElement.querySelector('.suggest');
1072
+ const s = editor?.suggest;
1073
+ if (!box) return;
1074
+ box.hidden = !s;
1075
+ box.replaceChildren(...(s ? s.items.map((item, i) =>
1076
+ el('button', { type: 'button', class: i === s.at ? 'on' : '', on: {
1077
+ mousedown: (ev) => { ev.preventDefault(); applySuggest(ta, item); },
1078
+ } }, item.label, el('small', {}, item.note))) : []));
1079
+ }
1080
+
1081
+ function applySuggest(ta, item) {
1082
+ const s = editor.suggest;
1083
+ const end = ta.selectionStart;
1084
+ const inserted = `[${item.label}]`;
1085
+ ta.value = ta.value.slice(0, s.start) + inserted + ta.value.slice(end);
1086
+ ta.selectionStart = ta.selectionEnd = s.start + inserted.length;
1087
+ editor.draft = ta.value;
1088
+ editor.suggest = null;
1089
+ drawSuggest(ta);
1090
+ }
1091
+
1092
+ /** 고치는 칸 하나. 다시 그려도 글과 커서를 잃지 않는다. */
1093
+ function editBox(placeholder, opts = {}) {
1094
+ const e = editor;
1095
+ const ta = el('textarea', {
1096
+ rows: opts.rows ?? 1,
1097
+ placeholder,
1098
+ 'aria-label': placeholder,
1099
+ 'data-editor': e.key,
1100
+ value: e.draft ?? '',
1101
+ on: {
1102
+ input: () => { e.draft = ta.value; e.selection = [ta.selectionStart, ta.selectionEnd]; refreshSuggest(ta); autosize(ta); },
1103
+ compositionstart: () => { composing = true; },
1104
+ compositionend: () => {
1105
+ composing = false;
1106
+ e.draft = ta.value;
1107
+ refreshSuggest(ta);
1108
+ if (renderWanted) render();
1109
+ },
1110
+ keydown: (ev) => {
1111
+ if (ev.isComposing) return;
1112
+ const s = e.suggest;
1113
+ if (s && (ev.key === 'ArrowDown' || ev.key === 'ArrowUp')) {
1114
+ ev.preventDefault();
1115
+ s.at = (s.at + (ev.key === 'ArrowDown' ? 1 : s.items.length - 1)) % s.items.length;
1116
+ drawSuggest(ta);
1117
+ return;
1118
+ }
1119
+ if (s && (ev.key === 'Enter' || ev.key === 'Tab')) {
1120
+ ev.preventDefault();
1121
+ applySuggest(ta, s.items[s.at]);
1122
+ return;
1123
+ }
1124
+ if (ev.key === 'Escape') {
1125
+ ev.preventDefault();
1126
+ if (s) { e.suggest = null; drawSuggest(ta); } else closeEditor();
1127
+ return;
1128
+ }
1129
+ if (ev.key === 'Enter' && !ev.shiftKey) {
1130
+ ev.preventDefault();
1131
+ e.draft = ta.value;
1132
+ commitEditor();
1133
+ }
1134
+ },
1135
+ blur: () => {
1136
+ if (suppressBlur) return;
1137
+ e.selection = [ta.selectionStart, ta.selectionEnd];
1138
+ e.draft = ta.value;
1139
+ // 물어보는 칸의 버튼으로 옮겨 갈 수 있으니 조금 뒤에 본다
1140
+ setTimeout(() => {
1141
+ if (editor === e && !stage.contains(document.activeElement?.closest?.('[data-keep-editor]') ?? null)) commitEditor();
1142
+ }, 120);
1143
+ },
1144
+ },
1145
+ });
1146
+ const wrap = el('div', { class: 'edit' }, ta, el('div', { class: 'suggest', hidden: true }));
1147
+ return el('div', { class: 'edit' }, wrap, opts.hint === false ? null : el('p', { class: 'hint' }, opts.hint ?? t('Enter to save, Esc to cancel. Type [ to pick a character or place.')), askView());
1148
+ }
1149
+
1150
+ function autosize(ta) {
1151
+ ta.style.height = 'auto';
1152
+ ta.style.height = `${ta.scrollHeight + 2}px`;
1153
+ }
1154
+
1155
+ /** 모르는 이름을 어떻게 할지 묻는다(011 3.1절). 브라우저의 확인 창은 sandbox 안에서 쓸 수 없다. */
1156
+ function askView() {
1157
+ const e = editor;
1158
+ if (!e || !e.unknown.length) return null;
1159
+ return e.unknown.map((u) =>
1160
+ el('div', { class: 'ask', 'data-keep-editor': true },
1161
+ u.same.length ? t('There is more than one "{name}". Which one?', { name: u.name }) : t('There is no "{name}" yet.', { name: u.name }),
1162
+ el('div', { class: 'choices' },
1163
+ u.same.length
1164
+ ? u.same.map((x) => choiceButton(u.name, `id:${x.id}`, `${x.name} (${x.kind}${x.note ? `, ${x.note}` : ''})`))
1165
+ : [choiceButton(u.name, 'character', t('Make a character')), choiceButton(u.name, 'place', t('Make a place')), choiceButton(u.name, 'plain', t('Keep as plain text'))],
1166
+ )));
1167
+ }
1168
+
1169
+ function choiceButton(name, value, label) {
1170
+ return el('button', { type: 'button', class: 'btn', on: {
1171
+ mousedown: (ev) => ev.preventDefault(),
1172
+ click: () => {
1173
+ editor.choices[name] = value;
1174
+ editor.unknown = [];
1175
+ commitEditor();
1176
+ },
1177
+ } }, label);
1178
+ }
1179
+
1180
+ // 표시. 다른 참여자의 변경에 표시를 단다. 같은 record 는 뒤의 변경이 이긴다(011 3.2절).
1181
+ function computeMarks() {
1182
+ const marks = new Map();
1183
+ const removed = [];
1184
+ const c = concept;
1185
+ const latest = c.othersPending.length ? c.othersPending[c.othersPending.length - 1].revision : null;
1186
+ for (const p of c.othersPending) {
1187
+ for (const ch of p.changes) {
1188
+ const prev = marks.get(ch.record);
1189
+ marks.set(ch.record, {
1190
+ action: prev && prev.action === 'add' && ch.after !== null ? 'add' : ch.action,
1191
+ before: prev ? prev.before : ch.before,
1192
+ type: ch.type,
1193
+ owner: ch.owner,
1194
+ revision: p.revision,
1195
+ recent: p.revision === latest,
1196
+ });
1197
+ }
1198
+ }
1199
+ const held = new Set(c.conflicts.map((x) => x.record));
1200
+ for (const id of held) marks.delete(id);
1201
+ for (const [id, m] of marks) {
1202
+ if (m.action === 'remove' && m.before !== null) removed.push({ id, ...m });
1203
+ if (m.action === 'remove') marks.delete(id);
1204
+ }
1205
+ return { marks, removed, held };
1206
+ }
1207
+
1208
+ /** 같은 revision 에 걸린 부딪힘은 함께 풀어야 한다. */
1209
+ function conflictGroup(first) {
1210
+ const group = [first];
1211
+ let grew = true;
1212
+ while (grew) {
1213
+ grew = false;
1214
+ for (const c of concept.conflicts) {
1215
+ if (group.includes(c)) continue;
1216
+ if (c.sides.some((s) => group.some((g) => g.sides.some((x) => x.revision === s.revision)))) {
1217
+ group.push(c);
1218
+ grew = true;
1219
+ }
1220
+ }
1221
+ }
1222
+ return group;
1223
+ }
1224
+
1225
+ function describeContent(content) {
1226
+ if (content === null || content === undefined) return t('Removed');
1227
+ if (typeof content === 'object') {
1228
+ if (Array.isArray(content.text)) return plain(content.text);
1229
+ if (typeof content.name === 'string') return content.note ? `${content.name}, ${content.note}` : content.name;
1230
+ if (typeof content.title === 'string') return content.title;
1231
+ if (content.list === 'fact') return t('Fact row');
1232
+ if (content.list === 'scene') return t('Scene row');
1233
+ if ('memo' in content) {
1234
+ if (content.target) return t('Sticker attached to {target}', { target: names().row.get(content.target) ?? names().node.get(content.target) ?? content.target });
1235
+ return t('Sticker placed in the work area');
1236
+ }
1237
+ }
1238
+ return JSON.stringify(content);
1239
+ }
1240
+
1241
+ function conflictCard(c) {
1242
+ const me = concept.me;
1243
+ const group = conflictGroup(c);
1244
+ const ids = group.map((x) => x.id);
1245
+ const mine = c.sides.find((s) => s.participant === me);
1246
+ const theirs = c.sides.find((s) => s.participant !== me);
1247
+ const summaryOf = (rev) => [...concept.othersPending, ...concept.myPending].find((p) => p.revision === rev)?.summary;
1248
+ const theirSummary = theirs ? summaryOf(theirs.revision) : null;
1249
+ const mySummary = mine ? summaryOf(mine.revision) : null;
1250
+ const rowsNow = [...(concept.withOthers ?? concept.body).facts, ...(concept.withOthers ?? concept.body).scenes];
1251
+ const isLine = rowsNow.some((r) => r.lines.some((l) => l.id === c.record));
1252
+ const isPara = rowsNow.some((r) => (r.body ?? []).some((b) => b.id === c.record));
1253
+ const canWrite = c.reason === 'same_record' && (isLine || isPara) && mine && mine.content && Array.isArray(mine.content.text) && !editor;
1254
+ return el('div', { class: 'conflict', 'data-conflict': c.id },
1255
+ el('h3', {}, c.reason === 'same_record' ? t('The same place was changed in different ways') : t('What this points to was removed'), group.length > 1 ? t(' ({count} conflicts are resolved together)', { count: group.length }) : ''),
1256
+ el('div', { class: 'sides' }, [mine, theirs].filter(Boolean).map((s) =>
1257
+ el('div', { class: 'side' }, el('b', {}, s === mine ? t('Mine') : t("{name}'s", { name: s.name ?? t('The other participant') })), describeContent(s.content)))),
1258
+ theirSummary ? el('p', { class: 'warn' }, t('If you take mine, this whole change by {name} is cancelled: {summary}', { name: theirs.name ?? t('the other participant'), summary: theirSummary })) : null,
1259
+ mySummary ? el('p', { class: 'warn' }, t('If you take theirs, this whole change of yours is cancelled: {summary}', { summary: mySummary })) : null,
1260
+ el('div', { class: 'actions' },
1261
+ btn(t('Take mine'), () => send([], { resolves: ids, take: 'mine' }), 'btn primary'),
1262
+ theirs ? btn(t("Take {name}'s", { name: theirs.name ?? t('the other participant') }), () => send([], { resolves: ids, take: 'theirs' })) : null,
1263
+ canWrite ? btn(t('Merge both'), () => startEdit({
1264
+ key: `resolve-${c.record}`,
1265
+ draft: toEditable(mine.content.text),
1266
+ resolves: ids,
1267
+ record: c.record,
1268
+ build: (text) => [isPara ? { op: 'para.update', input: { para: c.record, text } } : { op: 'line.update', input: { line: c.record, text } }],
1269
+ })) : null,
1270
+ ),
1271
+ );
1272
+ }
1273
+
1274
+ function render() {
1275
+ if (!concept) return;
1276
+ if (composing || dragging || committing) {
1277
+ renderWanted = true;
1278
+ return;
1279
+ }
1280
+ renderWanted = false;
1281
+ // 고치던 칸의 커서를 기억해 둔다
1282
+ const active = document.activeElement;
1283
+ const editing = active && active.dataset && active.dataset.editor;
1284
+ if (editing && editor) {
1285
+ editor.draft = active.value;
1286
+ editor.selection = [active.selectionStart, active.selectionEnd];
1287
+ }
1288
+ const keepInputs = captureForms();
1289
+ suppressBlur = true;
1290
+
1291
+ const c = concept;
1292
+ const body = c.withOthers ?? c.body;
1293
+ const { marks, removed, held } = computeMarks();
1294
+ const n = names();
1295
+ const conflictsOn = (id) => c.conflicts.filter((x) => x.record === id);
1296
+
1297
+ const markClass = (id) => {
1298
+ const m = marks.get(id);
1299
+ if (!m) return '';
1300
+ return ` m-${m.action}${m.recent ? '' : ' old'}`;
1301
+ };
1302
+ const tag = (id) => {
1303
+ if (held.has(id)) return el('span', { class: 'tag remove' }, t('Conflict'));
1304
+ const m = marks.get(id);
1305
+ return m ? el('span', { class: `tag ${m.action}`, title: t('The AI changed this and it is not confirmed yet. Your next operation confirms everything shown up to now.') }, t(ACTION[m.action])) : null;
1306
+ };
1307
+ const mentions = (segs) => selectedNode !== null && (segs ?? []).some((s) => typeof s !== 'string' && (s.node ?? s.ref) === selectedNode);
1308
+
1309
+ function nodeButton(id, label) {
1310
+ return el('button', {
1311
+ type: 'button',
1312
+ class: `node${selectedNode === id ? ' on' : ''}`,
1313
+ 'aria-pressed': selectedNode === id ? 'true' : 'false',
1314
+ on: { click: (ev) => {
1315
+ ev.stopPropagation();
1316
+ selectedNode = selectedNode === id ? null : id;
1317
+ // 이름을 고르면 그 인물이나 장소가 보이게 왼쪽 칸을 연다
1318
+ if (selectedNode !== null) sideOpen = true;
1319
+ render();
1320
+ } },
1321
+ }, label);
1322
+ }
1323
+
1324
+ const textView = (segs) => (segs ?? []).map((s) => {
1325
+ if (typeof s === 'string') return s;
1326
+ if ('node' in s) return nodeButton(s.node, s.text ?? n.node.get(s.node) ?? s.node);
1327
+ return el('span', { class: 'frame-mark' }, n.row.get(s.row) ?? s.row);
1328
+ });
1329
+
1330
+ const lineView = (l, row) => {
1331
+ const key = `line-${l.id}`;
1332
+ if (editor?.key === key || editor?.key === `resolve-${l.id}`) {
1333
+ return el('div', { class: 'line', 'data-target': l.id }, editBox(t('Line')));
1334
+ }
1335
+ const m = marks.get(l.id);
1336
+ const canToggle = m && m.action === 'update' && m.before;
1337
+ const showing = canToggle && openBefore.has(l.id);
1338
+ return el('div', {},
1339
+ el('div', { class: `line${markClass(l.id)}${mentions(l.text) ? ' hit' : ''}`, 'data-target': l.id },
1340
+ el('div', { class: 'line-text', tabindex: 0, role: 'button', 'aria-label': t('Edit line: {text}', { text: l.display }), on: {
1341
+ click: (ev) => {
1342
+ if (ev.target.closest('button')) return;
1343
+ startEdit({ key, draft: toEditable(l.text), unchanged: toEditable(l.text), build: (text) => [{ op: 'line.update', input: { line: l.id, text } }] });
1344
+ },
1345
+ keydown: (ev) => {
1346
+ if (ev.key === 'Enter' && ev.target === ev.currentTarget) {
1347
+ ev.preventDefault();
1348
+ startEdit({ key, draft: toEditable(l.text), unchanged: toEditable(l.text), build: (text) => [{ op: 'line.update', input: { line: l.id, text } }] });
1349
+ }
1350
+ },
1351
+ } },
1352
+ textView(l.text),
1353
+ canToggle
1354
+ ? el('button', { type: 'button', class: 'tag update', 'aria-expanded': showing ? 'true' : 'false', title: t('Show the text before the change'), on: { click: (ev) => {
1355
+ ev.stopPropagation();
1356
+ if (openBefore.has(l.id)) openBefore.delete(l.id);
1357
+ else openBefore.add(l.id);
1358
+ render();
1359
+ } } }, t(ACTION.update))
1360
+ : tag(l.id),
1361
+ ),
1362
+ el('div', { class: 'line-tools' }, deleteButton(key, t('line'), () => send([{ op: 'line.remove', input: { line: l.id } }]))),
1363
+ ),
1364
+ showing ? el('div', { class: 'before' }, t('Before: '), plain(m.before.text)) : null,
1365
+ conflictsOn(l.id).map(conflictCard),
1366
+ );
1367
+ };
1368
+
1369
+ // 본문 문단(novel.md 7.1절). 글 줄과 같은 방식으로 고치고, 표시와 AI 변경 표시도 같다.
1370
+ // 문단을 고치거나 더하기 시작하면 그 본문을 펼친 채 둔다. 저장하면 AI 표시가 사라져도 접히지 않는다.
1371
+ const paraEdit = (b) => ({ key: `para-${b.id}`, draft: toEditable(b.text), unchanged: toEditable(b.text), build: (text) => [{ op: 'para.update', input: { para: b.id, text } }] });
1372
+ const newParaKey = (r) => `newpara-${r.id}`;
1373
+ const paraView = (b, r) => {
1374
+ const key = `para-${b.id}`;
1375
+ if (editor?.key === key || editor?.key === `resolve-${b.id}`) {
1376
+ return el('div', { class: 'para', 'data-target': b.id, 'data-para': b.id }, editBox(t('Paragraph'), { rows: 3 }));
1377
+ }
1378
+ const m = marks.get(b.id);
1379
+ const canToggle = m && m.action === 'update' && m.before;
1380
+ const showing = canToggle && openBefore.has(b.id);
1381
+ const paras = r.body ?? [];
1382
+ return el('div', { class: 'para-wrap' },
1383
+ el('div', {
1384
+ class: `para${markClass(b.id)}${mentions(b.text) ? ' hit' : ''}${focused.has(r.id) ? ' focus' : ''}`,
1385
+ 'data-target': b.id,
1386
+ 'data-para': b.id,
1387
+ on: {
1388
+ dragover: (ev) => {
1389
+ if (dragging?.kind !== 'para' || dragging.scene !== r.id || dragging.id === b.id) return;
1390
+ ev.preventDefault();
1391
+ ev.stopPropagation();
1392
+ const rect = ev.currentTarget.getBoundingClientRect();
1393
+ clearDropMarks();
1394
+ ev.currentTarget.classList.add(ev.clientY < rect.top + rect.height / 2 ? 'drop-before' : 'drop-after');
1395
+ },
1396
+ dragleave: (ev) => ev.currentTarget.classList.remove('drop-before', 'drop-after'),
1397
+ drop: (ev) => {
1398
+ const d = dragging;
1399
+ if (d?.kind !== 'para') return;
1400
+ ev.preventDefault();
1401
+ ev.stopPropagation();
1402
+ const before = ev.currentTarget.classList.contains('drop-before');
1403
+ const others = paras.filter((x) => x.id !== d.id);
1404
+ const at = others.findIndex((x) => x.id === b.id);
1405
+ const after = before ? (at > 0 ? others[at - 1].id : null) : b.id;
1406
+ endDrag();
1407
+ send([{ op: 'para.move', input: { para: d.id, after } }]);
1408
+ },
1409
+ },
1410
+ },
1411
+ el('button', {
1412
+ type: 'button', class: 'grip', draggable: 'true', title: t('Drag to change the paragraph order'), 'aria-label': t('Drag to move the paragraph'),
1413
+ on: {
1414
+ dragstart: (ev) => {
1415
+ ev.stopPropagation();
1416
+ dragging = { kind: 'para', id: b.id, scene: r.id };
1417
+ ev.dataTransfer.effectAllowed = 'move';
1418
+ ev.dataTransfer.setData('text/plain', b.id);
1419
+ ev.currentTarget.closest('.para').classList.add('dragging');
1420
+ },
1421
+ dragend: () => endDrag(),
1422
+ },
1423
+ }, '⠿'),
1424
+ el('div', { class: 'para-text', tabindex: 0, role: 'button', 'aria-label': t('Edit paragraph: {text}', { text: b.display }), on: {
1425
+ click: (ev) => {
1426
+ if (ev.target.closest('button')) return;
1427
+ openBodies.add(r.id);
1428
+ startEdit(paraEdit(b));
1429
+ },
1430
+ keydown: (ev) => {
1431
+ if (ev.key === 'Enter' && ev.target === ev.currentTarget) {
1432
+ ev.preventDefault();
1433
+ openBodies.add(r.id);
1434
+ startEdit(paraEdit(b));
1435
+ }
1436
+ },
1437
+ } },
1438
+ textView(b.text),
1439
+ canToggle
1440
+ ? el('button', { type: 'button', class: 'tag update', 'aria-expanded': showing ? 'true' : 'false', title: t('Show the text before the change'), on: { click: (ev) => {
1441
+ ev.stopPropagation();
1442
+ if (openBefore.has(b.id)) openBefore.delete(b.id);
1443
+ else openBefore.add(b.id);
1444
+ render();
1445
+ } } }, t(ACTION.update))
1446
+ : tag(b.id),
1447
+ ),
1448
+ el('div', { class: 'para-tools' }, deleteButton(key, t('paragraph'), () => send([{ op: 'para.remove', input: { para: b.id } }]))),
1449
+ ),
1450
+ showing ? el('div', { class: 'before' }, t('Before: '), plain(m.before.text)) : null,
1451
+ conflictsOn(b.id).map(conflictCard),
1452
+ );
1453
+ };
1454
+ const addParaButton = (r) => btn(t('+ Paragraph'), () => openBodies.add(r.id) && startEdit({ key: newParaKey(r), draft: '', build: (text) => [{ op: 'para.add', input: { scene: r.id, text } }] }), 'btn body-add');
1455
+ /**
1456
+ * 장면의 본문. 접혀 있으면 문단 수와 첫 문단의 첫 줄만 보인다. 결과물 탭에서 이 장면을 고르면(focus) 펼쳐 강조한다(7.5절, 메시지 받기).
1457
+ * 고치는 칸이 본문 안에 있거나 AI 가 바꾼 문단이 있으면 펼친다. 화면이 그린 것까지가 사람이 본 것이기 때문이다(032 10.3절).
1458
+ */
1459
+ const bodyView = (r, open) => {
1460
+ const paras = r.body ?? [];
1461
+ const adding = editor?.key === newParaKey(r);
1462
+ if (!paras.length && !adding) return open ? el('div', { class: 'body' }, el('span', { class: 'empty' }, t('(no body text)')), ' ', addParaButton(r)) : null;
1463
+ const changed = paras.some((b) => marks.has(b.id) || held.has(b.id));
1464
+ const editing = paras.some((b) => editor?.key === `para-${b.id}` || editor?.key === `resolve-${b.id}`);
1465
+ const shown = open || openBodies.has(r.id) || adding || editing || changed;
1466
+ const toggle = reading ? null : el('button', {
1467
+ type: 'button', class: 'body-toggle', 'aria-expanded': shown ? 'true' : 'false',
1468
+ // 접힌 문단에 붙은 스티커는 이 줄 옆에 놓는다
1469
+ 'data-hidden-paras': shown ? null : paras.map((b) => b.id).join(' '),
1470
+ on: { click: () => {
1471
+ if (openBodies.has(r.id)) openBodies.delete(r.id);
1472
+ else openBodies.add(r.id);
1473
+ render();
1474
+ } },
1475
+ }, el('span', { class: 'count' }, tCount(paras.length, '{arrow} Body text: {n} paragraph', '{arrow} Body text: {n} paragraphs', { arrow: shown ? '▾' : '▸' })), shown ? null : el('span', { class: 'first' }, paras[0]?.display ?? ''));
1476
+ return el('div', { class: 'body', 'data-body': r.id },
1477
+ toggle,
1478
+ shown ? paras.map((b) => paraView(b, r)) : null,
1479
+ adding ? el('div', { class: 'para' }, editBox(t('New paragraph'), { rows: 3 })) : null,
1480
+ shown && !adding ? addParaButton(r) : null,
1481
+ );
1482
+ };
1483
+
1484
+ // ── 시각, 세계선, 메타데이터(novel.md 16절) ──
1485
+ const worlds = body.worlds ?? [];
1486
+ const calendars = body.calendars ?? [];
1487
+ const worldIndex = new Map(worlds.map((w, i) => [w.id, i]));
1488
+ if (worldFilter && !worldIndex.has(worldFilter)) worldFilter = null;
1489
+ const worldTag = (id) => el('span', { class: 'wtag', style: `background:${WORLD_COLORS[(worldIndex.get(id) ?? 0) % WORLD_COLORS.length]}` }, worlds.find((w) => w.id === id)?.name ?? id);
1490
+ const factById = new Map((body.facts ?? []).map((f) => [f.id, f]));
1491
+ // 세계선 하나를 고르면 모든 시각이 그 세계선의 달력으로 보인다(16.3.5절)
1492
+ const factShown = (f) => (f?.time ? (worldFilter && f.time.shownIn?.[worldFilter]) || f.time.shown : null);
1493
+ const factLabel = (f) => (f ? f.title ?? f.lines[0]?.display ?? f.id : '');
1494
+ const inFilter = (f) => !worldFilter || (f.meta?.worlds ?? []).includes(worldFilter);
1495
+ // 장면은 적은 세계선이, 없으면 다루는 사실의 세계선이 로직의 worlds 에 온다(16.13절)
1496
+ const sceneInFilter = (r) => !worldFilter || (r.worlds ?? []).includes(worldFilter);
1497
+ // 장면 묶음(novel.md 18.5절). 옛 버전의 읽기에는 groups 가 없으니 묶음 없는 목록으로 그린다
1498
+ const groups = body.groups ?? [];
1499
+ const groupById = new Map(groups.map((g) => [g.id, g]));
1500
+ const sceneById = new Map(body.scenes.map((r) => [r.id, r]));
1501
+ const sceneNum = new Map(body.scenes.map((r, i) => [r.id, i + 1]));
1502
+ const sceneRoot = body.sceneRoot ?? body.scenes.map((r) => r.id);
1503
+ const itemsOf = (gid) => (gid ? groupById.get(gid)?.items ?? [] : sceneRoot);
1504
+ // 같은 곳에 든 장면과 묶음. 순서를 바꾸는 조작은 검색이나 쪽과 상관없이 이 차례로 보낸다
1505
+ const sibsOf = (gid) => itemsOf(gid).map((id) => sceneById.get(id) ?? groupById.get(id)).filter(Boolean);
1506
+ const groupScenes = (gid) => itemsOf(gid).flatMap((id) => (groupById.has(id) ? groupScenes(id) : sceneById.has(id) ? [sceneById.get(id)] : []));
1507
+ const insideOf = (gid, container) => {
1508
+ for (let g = container; g; g = groupById.get(g)?.parent ?? null) if (g === gid) return true;
1509
+ return false;
1510
+ };
1511
+ const groupPath = (r) => {
1512
+ const names = [];
1513
+ for (let g = r.group; g && groupById.has(g); g = groupById.get(g).parent) names.unshift(groupById.get(g).title);
1514
+ return names.length ? names.join(' / ') : null;
1515
+ };
1516
+ const editingKey = () => String(editor?.key ?? '');
1517
+ // 안에 AI 가 바꾼 것, 부딪힘, 고른 장면, 고치는 칸이 있으면 펼친다. 사람이 확인하는 것은 그린 것까지라 접힌 채로 넘기지 않는다(novel.md 7.1절)
1518
+ const sceneBusy = (r) => !!r && (held.has(r.id) || marks.has(r.id) || (r.lines ?? []).some((l) => held.has(l.id) || marks.has(l.id)) || (r.body ?? []).some((b) => held.has(b.id) || marks.has(b.id)) || focused.has(r.id) || conflictsOn(r.id).length > 0 || (editor !== null && editingKey().endsWith(`-${r.id}`)));
1519
+ const groupBusy = (gid) => marks.has(gid) || conflictsOn(gid).length > 0 || (editor !== null && editingKey().endsWith(`-${gid}`)) || itemsOf(gid).some((id) => (groupById.has(id) ? groupBusy(id) : sceneBusy(sceneById.get(id))));
1520
+ const isGroupOpen = (gid) => openGroups.has(gid) || groupBusy(gid);
1521
+ const gapsOf = () => new Map((body.timeline?.[worldFilter ?? ''] ?? []).filter((x) => x.gap).map((x) => [x.fact, x.gap]));
1522
+ const calOptions = (sel) => calendars.map((c) => el('option', { value: c.id, ...(c.id === sel ? { selected: true } : {}) }, c.name));
1523
+ const metaPart = (key, label, value, set, onClick) =>
1524
+ el('button', { type: 'button', class: `meta-part${set ? ' set' : ''}`, 'data-meta': key, on: { click: onClick } }, el('span', { class: 'k' }, label), value);
1525
+ const formActions = (save) => el('div', { class: 'actions' }, btn(t('Save'), save, 'btn primary'), btn(t('Cancel'), closeEditor));
1526
+
1527
+ // 시각 칸. 사실이면 row.update 의 time, 장면이면 meta.time 으로 보낸다(16.2.3절, 16.4.2절)
1528
+ const timeForm = () => {
1529
+ const e = editor;
1530
+ const calId = e.world ? worlds.find((w) => w.id === e.world)?.calendar : body.defaultCalendar;
1531
+ const example = calendars.find((x) => x.id === calId)?.example ?? '1999년 3월 4일';
1532
+ return el('div', { class: 'form picker', 'data-time-form': e.row },
1533
+ field('text', t('Time (for example: {example}). Leave it empty to remove the time', { example }), e.text),
1534
+ worlds.length
1535
+ ? el('label', {}, el('span', { class: 'kind' }, t('Write it in the calendar of')),
1536
+ el('select', { 'data-form-field': 'world', on: { change: (ev) => { editor.world = ev.target.value; render(); } } },
1537
+ el('option', { value: '', ...(e.world ? {} : { selected: true }) }, t('Default calendar')),
1538
+ worlds.map((w) => el('option', { value: w.id, ...(e.world === w.id ? { selected: true } : {}) }, w.name))))
1539
+ : null,
1540
+ formActions(saveForm));
1541
+ };
1542
+ const checkList = (items) => items.map(([id, ...label]) => el('label', {},
1543
+ el('input', { type: 'checkbox', 'data-pick': id, ...(editor.picked.includes(id) ? { checked: true } : {}), on: { change: (ev) => {
1544
+ const p = new Set(editor.picked);
1545
+ if (ev.target.checked) p.add(id);
1546
+ else p.delete(id);
1547
+ editor.picked = [...p];
1548
+ } } }), ...label));
1549
+ const worldsPicker = (r) => el('div', { class: 'picker', 'data-picker': 'worlds' },
1550
+ checkList(worlds.map((w) => [w.id, worldTag(w.id)])),
1551
+ formActions(() => saveMeta(r.id, { worlds: editor.picked.length ? editor.picked : null })));
1552
+ const factsPicker = (r) => el('div', { class: 'picker', 'data-picker': 'facts' },
1553
+ (body.facts ?? []).length ? checkList((body.facts ?? []).map((f) => [f.id, el('span', { class: 'when' }, factShown(f) ?? t('No time')), factLabel(f)])) : el('span', { class: 'empty' }, t('There are no facts yet.')),
1554
+ formActions(() => saveMeta(r.id, { facts: editor.picked.length ? editor.picked : null })));
1555
+ const povPicker = (r) => el('div', { class: 'picker', 'data-picker': 'pov' },
1556
+ el('select', { 'aria-label': t('Point of view character'), on: { change: (ev) => saveMeta(r.id, { pov: ev.target.value || null }) } },
1557
+ el('option', { value: '', ...(r.meta?.pov ? {} : { selected: true }) }, t('No point of view')),
1558
+ body.nodes.map((nd) => el('option', { value: nd.id, ...(r.meta?.pov === nd.id ? { selected: true } : {}) }, nd.name))),
1559
+ el('div', { class: 'actions' }, btn(t('Cancel'), closeEditor)));
1560
+
1561
+ const timeEdit = (r, t, scene) => ({
1562
+ key: `time-${r.id}`, form: 'time', row: r.id, scene, needsText: false,
1563
+ text: t?.written.text ?? '',
1564
+ world: t ? (worldIndex.has(t.written.world) ? t.written.world : '') : scene ? '' : (r.meta?.worlds?.[0] ?? ''),
1565
+ });
1566
+ // 사실의 메타데이터 한 줄: 시각과 세계선. 세계선이 하나도 없으면 시각만 보인다(16.3.1절)
1567
+ const factMetaView = (r) => {
1568
+ if (editor?.key === `time-${r.id}`) return timeForm();
1569
+ if (editor?.key === `worlds-${r.id}`) return worldsPicker(r);
1570
+ const shown = factShown(r);
1571
+ const ws = r.meta?.worlds ?? [];
1572
+ return el('div', { class: 'meta', 'data-meta-of': r.id },
1573
+ metaPart('time', t('Time'), shown ?? t('none'), !!shown, () => startEdit(timeEdit(r, r.time, false))),
1574
+ worlds.length ? metaPart('worlds', t('World line'), ws.length ? ws.map(worldTag) : t('none'), ws.length > 0, () => startEdit({ key: `worlds-${r.id}`, form: 'worlds', row: r.id, picked: [...ws], needsText: false })) : null);
1575
+ };
1576
+ // 장면의 메타데이터 한 줄: "사실: 황제의 죽음, 즉위 | 시점: 철수 | 시각: 제국력 65300년(사실에서)"(16.4.2절)
1577
+ const sceneMetaView = (r) => {
1578
+ if (editor?.key === `facts-${r.id}`) return factsPicker(r);
1579
+ if (editor?.key === `pov-${r.id}`) return povPicker(r);
1580
+ if (editor?.key === `time-${r.id}`) return timeForm();
1581
+ if (editor?.key === `worlds-${r.id}`) return worldsPicker(r);
1582
+ const m = r.meta ?? { facts: [], pov: null, time: null };
1583
+ const ownWorlds = m.worlds ?? [];
1584
+ const facts = m.facts.map((id) => factById.get(id)).filter(Boolean);
1585
+ const when = r.time ? `${r.time.shown}${r.timeTo ? t(' ~ until {fact}', { fact: factLabel(factById.get(r.timeTo)) }) : ''}${r.timeFrom === 'facts' ? t(' (from facts)') : ''}` : t('none');
1586
+ return el('div', { class: 'meta', 'data-meta-of': r.id },
1587
+ metaPart('facts', t('Facts'), facts.length ? facts.map(factLabel).join(', ') : t('none'), facts.length > 0, () => startEdit({ key: `facts-${r.id}`, form: 'facts', row: r.id, picked: [...m.facts], needsText: false })),
1588
+ el('span', { class: 'meta-sep' }, '|'),
1589
+ metaPart('pov', t('Point of view'), m.pov ? (n.node.get(m.pov) ?? m.pov) : t('none'), !!m.pov, () => startEdit({ key: `pov-${r.id}`, form: 'pov', row: r.id, needsText: false })),
1590
+ el('span', { class: 'meta-sep' }, '|'),
1591
+ metaPart('time', t('Time'), when, !!r.time, () => startEdit(timeEdit(r, m.time, true))),
1592
+ worlds.length ? el('span', { class: 'meta-sep' }, '|') : null,
1593
+ worlds.length
1594
+ ? metaPart('worlds', t('World line'), (r.worlds ?? []).length ? [...r.worlds.map(worldTag), r.worldsFrom === 'facts' ? t(' (from facts)') : null] : t('none'), ownWorlds.length > 0,
1595
+ () => startEdit({ key: `worlds-${r.id}`, form: 'worlds', row: r.id, picked: [...ownWorlds], needsText: false }))
1596
+ : null);
1597
+ };
1598
+
1599
+ // 사실 목록 머리의 세계선 칩. 하나를 고르면 그 세계선의 사실만 남는다(16.3.5절)
1600
+ const worldChips = () => worlds.length
1601
+ ? el('div', { class: 'chips', role: 'group', 'aria-label': t('Filter by world line') },
1602
+ el('button', { type: 'button', class: 'chip', 'data-chip': '', 'aria-pressed': worldFilter ? 'false' : 'true', on: { click: () => { worldFilter = null; render(); } } }, t('All')),
1603
+ worlds.map((w) => el('button', { type: 'button', class: 'chip', 'data-chip': w.id, 'aria-pressed': worldFilter === w.id ? 'true' : 'false', on: { click: () => { worldFilter = worldFilter === w.id ? null : w.id; render(); } } }, w.name)))
1604
+ : null;
1605
+
1606
+ const worldForm = () => {
1607
+ const e = editor;
1608
+ return el('div', { class: 'form', 'data-world-form': e.world ?? '' },
1609
+ field('name', t('World line name'), e.name),
1610
+ field('note', t('Short note'), e.note),
1611
+ e.world ? null : el('label', {}, el('span', { class: 'kind' }, t('Calendar')), el('select', { 'data-form-field': 'calendar', on: { change: (ev) => { editor.calendar = ev.target.value; } } }, calOptions(e.calendar))),
1612
+ formActions(saveForm));
1613
+ };
1614
+ const calendarForm = () => {
1615
+ const e = editor;
1616
+ return el('div', { class: 'form', 'data-calendar-form': e.calendar ?? '' },
1617
+ field('name', t('Name'), e.name),
1618
+ field('epoch', t('Epoch (the first day of year 1 of this calendar, written in the Earth calendar)'), e.epoch),
1619
+ areaField('months', t('Months of a year (one per line: "name days")'), e.months),
1620
+ areaField('day', t('Units within a day (largest first, one per line: "name count". The last one is the second)'), e.day),
1621
+ field('secondNs', t('Length of one second (nanoseconds)'), e.secondNs),
1622
+ e.leapKept
1623
+ ? el('p', { class: 'hint' }, t('This calendar has more than one leap year rule, so they are kept as they are here.'))
1624
+ : el('div', { class: 'form' }, field('leapRule', t('Leap year rule (for example 4,!100,400. Leave it empty for no leap years)'), e.leapRule), field('leapMonth', t('Number of the month that gets the leap day'), e.leapMonth)),
1625
+ e.erasKept
1626
+ ? el('p', { class: 'hint' }, t('The eras are not in a shape this form can edit, so they are kept as they are. To change the eras, ask the AI.'))
1627
+ : el('div', { class: 'form' }, field('eraForward', t('Era (counted from the epoch. Leave it empty for year numbers only)'), e.eraForward), field('eraBackward', t('Era before the epoch (leave it empty for year 0, year -1)'), e.eraBackward)),
1628
+ formActions(saveForm));
1629
+ };
1630
+ // 세계선과 달력을 만들고 고치는 작은 판(16.3.5절). 따로 화면을 두지 않는다
1631
+ const worldPanelView = () => el('div', { class: 'panel', 'data-panel': 'worlds' },
1632
+ el('h3', {}, t('World lines')),
1633
+ worlds.length ? null : el('p', { class: 'empty' }, t('Without world lines, every time is written in the default calendar.')),
1634
+ worlds.map((w) => editor?.key === `world-${w.id}` ? worldForm() : el('div', { class: 'item', 'data-world': w.id },
1635
+ worldTag(w.id),
1636
+ el('select', { 'aria-label': t('Calendar of {name}', { name: w.name }), on: { change: (ev) => send([{ op: 'world.update', input: { world: w.id, calendar: ev.target.value } }]) } }, calOptions(w.calendar)),
1637
+ btn(t('Edit'), () => startEdit({ key: `world-${w.id}`, form: 'world', world: w.id, name: w.name, note: w.note, needsText: false }), 'icon', { 'aria-label': t('Edit {name}', { name: w.name }) }),
1638
+ deleteButton(`world-${w.id}`, t('world line {name}', { name: w.name }), () => send([{ op: 'world.remove', input: { world: w.id } }])))),
1639
+ editor?.key === 'newworld' ? worldForm() : el('div', {}, btn(t('+ World line'), () => startEdit({ key: 'newworld', form: 'world', name: '', note: '', calendar: body.defaultCalendar, needsText: false }))),
1640
+ el('h3', {}, t('Calendars')),
1641
+ el('label', { class: 'item' }, t('Default calendar'), el('select', { 'aria-label': t('Default calendar'), on: { change: (ev) => send([{ op: 'calendar.setDefault', input: { calendar: ev.target.value } }]) } }, calOptions(body.defaultCalendar))),
1642
+ calendars.map((cal) => editor?.key === `cal-${cal.id}` ? calendarForm() : el('div', { class: 'item', 'data-calendar': cal.id },
1643
+ el('b', {}, cal.name),
1644
+ el('small', {}, tCount(cal.data.months.length, '{n} month, a day of {units}. Example: {example}', '{n} months, a day of {units}. Example: {example}', { units: cal.data.day.map((u) => `${u.count}${u.name}`).join(' '), example: cal.example })),
1645
+ cal.builtin ? null : btn(t('Edit'), () => startEdit(calendarEdit(cal, false)), 'icon', { 'aria-label': t('Edit {name}', { name: cal.name }) }),
1646
+ btn(t('Copy'), () => startEdit(calendarEdit(cal, true)), 'icon', { 'aria-label': t('Copy {name}', { name: cal.name }), title: t('Makes a new calendar from a copy. If you change only the epoch, each world can have a calendar with its own epoch') }),
1647
+ cal.builtin ? null : deleteButton(`cal-${cal.id}`, t('calendar {name}', { name: cal.name }), () => send([{ op: 'calendar.remove', input: { calendar: cal.id } }])))),
1648
+ editor?.key === 'newcal' ? calendarForm() : null,
1649
+ el('div', {}, btn(t('Close'), () => { worldPanel = false; render(); })));
1650
+
1651
+ // 사실 목록. 일어난 차례이고(로직이 정렬해 준다), 긴 공백은 띠로, 시각 없는 사실은 선 아래에 모은다(16.7절)
1652
+ // 한 쪽에 보이는 사실만 그린다. 시각 없는 사실의 구분선과 순서 바꾸기는 전체 목록(facts)을 기준으로 한다.
1653
+ const factItems = (pageFacts, facts) => {
1654
+ const gaps = gapsOf();
1655
+ const untimed = facts.filter((f) => !f.time);
1656
+ const out = [];
1657
+ let divided = false;
1658
+ for (const f of pageFacts) {
1659
+ if (gaps.has(f.id)) out.push(el('li', { class: 'gap-band', 'data-gap': f.id }, gaps.get(f.id)));
1660
+ if (!f.time && !divided && facts.some((x) => x.time)) {
1661
+ out.push(el('li', { class: 'untimed' }, t('No time')));
1662
+ divided = true;
1663
+ }
1664
+ out.push(rowView(f, null, untimed, 'fact'));
1665
+ }
1666
+ return out;
1667
+ };
1668
+
1669
+ // 일어난 차례 보기(16.5.2절). 장면은 다루는 사실 가운데 가장 이른 것 옆에 읽는 차례대로 쌓인다.
1670
+ // 자기 시각만 있는 장면은 그 시각의 자리에, 시각 없는 장면은 맨 아래에 온다. 고른 세계선이 있으면 그 세계선의 장면만이다(16.13절).
1671
+ const occurView = () => {
1672
+ const facts = (body.facts ?? []).filter(inFilter);
1673
+ const order = new Map(facts.map((f, i) => [f.id, i]));
1674
+ const gaps = gapsOf();
1675
+ const at = new Map();
1676
+ const own = [];
1677
+ const none = [];
1678
+ body.scenes.forEach((s, i) => {
1679
+ if (!sceneInFilter(s)) return;
1680
+ const item = { s, num: i + 1 };
1681
+ const anchor = (s.meta?.facts ?? []).filter((id) => order.has(id)).sort((a, b) => order.get(a) - order.get(b))[0];
1682
+ if (anchor) at.set(anchor, [...(at.get(anchor) ?? []), item]);
1683
+ else if (s.time) own.push(item);
1684
+ else none.push(item);
1685
+ });
1686
+ own.sort((a, b) => (BigInt(a.s.time.lo) < BigInt(b.s.time.lo) ? -1 : BigInt(a.s.time.lo) > BigInt(b.s.time.lo) ? 1 : a.num - b.num));
1687
+ const card = ({ s, num }) => {
1688
+ const open = openCards.has(s.id);
1689
+ const pov = s.meta?.pov ? n.node.get(s.meta.pov) : null;
1690
+ return el('div', {},
1691
+ el('button', {
1692
+ // 읽기만 하는 보기에서는 끌지 않는다. 놓아도 보내지 못하므로 끌리는 모양부터 없앤다.
1693
+ type: 'button', class: `scard${focused.has(s.id) ? ' focus' : ''}`, draggable: canEdit ? 'true' : 'false', 'data-card': s.id, 'aria-expanded': open ? 'true' : 'false',
1694
+ title: canEdit ? t('Click to expand. Drag next to a fact to make this scene cover that fact') : t('Click to expand'),
1695
+ on: {
1696
+ click: () => { if (open) openCards.delete(s.id); else openCards.add(s.id); render(); },
1697
+ dragstart: (ev) => { if (!canEdit) { ev.preventDefault(); return; } dragging = { kind: 'card', id: s.id }; ev.dataTransfer.effectAllowed = 'link'; ev.dataTransfer.setData('text/plain', s.id); },
1698
+ dragend: () => endDrag(),
1699
+ },
1700
+ }, `${num}. ${s.title ?? s.lines[0]?.display ?? ''}`, groupPath(s) ? el('small', { class: 'gpath' }, groupPath(s)) : null, pov ? el('small', {}, t('Point of view: {name}', { name: pov })) : null, s.timeTo ? el('small', {}, t('~ until {fact}', { fact: factLabel(factById.get(s.timeTo)) })) : null),
1701
+ open ? el('ol', {}, rowView(s, num, body.scenes, 'scene', true)) : null);
1702
+ };
1703
+ const pair = (fact, items) => [
1704
+ fact
1705
+ ? el('div', { class: 'cell fact-cell', 'data-fact-cell': fact.id, on: {
1706
+ dragover: (ev) => { if (dragging?.kind !== 'card') return; ev.preventDefault(); ev.currentTarget.classList.add('drop-on'); },
1707
+ dragleave: (ev) => ev.currentTarget.classList.remove('drop-on'),
1708
+ drop: (ev) => {
1709
+ const d = dragging;
1710
+ if (d?.kind !== 'card') return;
1711
+ ev.preventDefault();
1712
+ endDrag();
1713
+ const sc = body.scenes.find((x) => x.id === d.id);
1714
+ const has = sc?.meta?.facts ?? [];
1715
+ if (!has.includes(fact.id)) send([{ op: 'row.update', input: { row: d.id, meta: { facts: [...has, fact.id] } } }]);
1716
+ },
1717
+ } },
1718
+ el('span', { class: 'when' }, factShown(fact) ?? t('No time'), ' ', (fact.meta?.worlds ?? []).map(worldTag)), factLabel(fact))
1719
+ : el('div', { class: 'cell' }),
1720
+ el('div', { class: 'cell' }, items.map(card)),
1721
+ ];
1722
+ const out = [];
1723
+ let divided = false;
1724
+ const flushOwn = (before) => {
1725
+ while (own.length && (before === null || BigInt(own[0].s.time.lo) < before)) {
1726
+ const it = own.shift();
1727
+ out.push(...pair(null, [it]));
1728
+ }
1729
+ };
1730
+ for (const f of facts) {
1731
+ if (f.time) flushOwn(BigInt(f.time.lo));
1732
+ else flushOwn(null);
1733
+ if (gaps.has(f.id)) out.push(el('div', { class: 'gap-band' }, gaps.get(f.id)));
1734
+ if (!f.time && !divided && facts.some((x) => x.time)) {
1735
+ out.push(el('div', { class: 'untimed' }, t('No time')));
1736
+ divided = true;
1737
+ }
1738
+ out.push(...pair(f, at.get(f.id) ?? []));
1739
+ }
1740
+ flushOwn(null);
1741
+ if (none.length) {
1742
+ if (!divided) out.push(el('div', { class: 'untimed' }, t('No time')));
1743
+ out.push(...pair(null, none));
1744
+ }
1745
+ return out.length ? el('div', { class: 'occur', 'data-occur': '' }, out) : el('p', { class: 'empty' }, t('There are no facts or scenes to show.'));
1746
+ };
1747
+
1748
+ const newLineKey = (r) => `newline-${r.id}`;
1749
+ // fixed 면 순서를 바꾸는 도구를 두지 않는다. 시각이 있는 사실과 일어난 차례 보기의 장면이 그렇다(16.2.4절, 16.5.2절)
1750
+ // 줄을 접어 보이는 모양. 제목과 글 줄의 앞 세 줄만 보이고, 누르면 펼쳐 지금까지의 모든 조작이 나온다.
1751
+ // 고치는 중이거나, 결과물에서 고른 줄이거나, 부딪힘이 있는 줄은 접지 않는다.
1752
+ const isRowOpen = (r) => openRow === r.id || focused.has(r.id) || conflictsOn(r.id).length > 0 || (editor !== null && String(editor.key ?? '').includes(r.id));
1753
+ const closedBody = (r, path) => {
1754
+ const text = [...(r.lines ?? []).map((l) => plain(l.text))].filter(Boolean).join(' ');
1755
+ return el('div', { class: 'row-body row-preview' },
1756
+ path ? el('span', { class: 'gpath' }, path) : null,
1757
+ r.title ? el('div', { class: 'title' }, r.title) : null,
1758
+ el('div', { class: 'preview-text' }, text || (r.title ? '' : t('No lines'))),
1759
+ marks.get(r.id)?.action === 'add' && r.lines.length ? null : tag(r.id));
1760
+ };
1761
+ // 장면은 묶음 안에서 같은 곳에 든 장면, 묶음과 견주어 옮긴다(novel.md 18.5절). depth 는 들여 쓰는 단계, path 는 검색 결과에 보이는 묶음 이름이다
1762
+ const rowView = (r, number, list, listName, inOccur = false, depth = 0, path = null) => {
1763
+ const titleKey = `title-${r.id}`;
1764
+ const container = listName === 'scene' ? (r.group ?? null) : null;
1765
+ if (listName === 'scene') list = sibsOf(container);
1766
+ const i = list.findIndex((x) => x.id === r.id);
1767
+ const fixed = inOccur || (listName === 'fact' && !!r.time);
1768
+ const open = inOccur || isRowOpen(r);
1769
+ return el('li', {
1770
+ class: `row${listName === 'scene' ? ' scene-row' : ''}${open ? '' : ' row-closed'}${markClass(r.id)}${focused.has(r.id) ? ' focus' : ''}`,
1771
+ 'data-row': r.id,
1772
+ 'data-list': listName,
1773
+ 'data-target': r.id,
1774
+ ...(depth ? { style: `margin-left:${depth * 1.4}em` } : {}),
1775
+ ...(open ? {} : { 'aria-expanded': 'false' }),
1776
+ on: {
1777
+ click: (ev) => {
1778
+ if (open || ev.target.closest('button')) return;
1779
+ openRow = r.id;
1780
+ render();
1781
+ },
1782
+ dragover: (ev) => {
1783
+ const d = dragging;
1784
+ if (fixed || !d || d.id === r.id) return;
1785
+ // 장면 목록에는 장면과 묶음을 놓을 수 있다. 묶음은 자기 안으로 놓지 못한다
1786
+ const can = d.kind === 'row' ? d.list === listName : d.kind === 'group' && listName === 'scene' && !insideOf(d.id, container);
1787
+ if (!can) return;
1788
+ ev.preventDefault();
1789
+ const rect = ev.currentTarget.getBoundingClientRect();
1790
+ const before = ev.clientY < rect.top + rect.height / 2;
1791
+ clearDropMarks();
1792
+ ev.currentTarget.classList.add(before ? 'drop-before' : 'drop-after');
1793
+ },
1794
+ dragleave: (ev) => ev.currentTarget.classList.remove('drop-before', 'drop-after'),
1795
+ drop: (ev) => {
1796
+ ev.preventDefault();
1797
+ const d = dragging;
1798
+ if (!d || (d.kind !== 'row' && d.kind !== 'group')) return;
1799
+ const cl = ev.currentTarget.classList;
1800
+ if (!cl.contains('drop-before') && !cl.contains('drop-after')) { endDrag(); return; }
1801
+ const before = cl.contains('drop-before');
1802
+ const others = list.filter((x) => x.id !== d.id);
1803
+ const at = others.findIndex((x) => x.id === r.id);
1804
+ const after = before ? (at > 0 ? others[at - 1].id : null) : r.id;
1805
+ endDrag();
1806
+ if (d.kind === 'group') send([{ op: 'group.move', input: { group: d.id, parent: container, after } }]);
1807
+ else send([{ op: 'row.move', input: listName === 'scene' ? { row: d.id, group: container, after } : { row: d.id, after } }]);
1808
+ },
1809
+ },
1810
+ },
1811
+ fixed ? el('span', { class: 'grip', 'aria-hidden': 'true', title: listName === 'fact' ? t('A fact with a time is placed in the order of events') : '' }, ' ') : el('button', {
1812
+ type: 'button', class: 'grip', draggable: 'true', title: t('Drag to change the order'), 'aria-label': t('Drag to move {label}', { label: r.label ?? t('row') }),
1813
+ on: {
1814
+ dragstart: (ev) => {
1815
+ dragging = { kind: 'row', id: r.id, list: listName };
1816
+ ev.dataTransfer.effectAllowed = 'move';
1817
+ ev.dataTransfer.setData('text/plain', r.id);
1818
+ ev.currentTarget.closest('.row').classList.add('dragging');
1819
+ },
1820
+ dragend: () => endDrag(),
1821
+ },
1822
+ }, '⠿'),
1823
+ number !== null ? el('span', { class: 'num' }, `${number}.`) : null,
1824
+ !open ? closedBody(r, path) : el('div', { class: 'row-body' },
1825
+ path ? el('span', { class: 'gpath' }, path) : null,
1826
+ editor?.key === titleKey
1827
+ ? el('div', {}, editBox(t('Title'), { hint: t('Enter to save, Esc to cancel. If you leave it empty, the title stays as it is.') }))
1828
+ : r.title ? el('div', { class: 'title' }, r.title) : null,
1829
+ listName === 'fact' ? factMetaView(r) : sceneMetaView(r),
1830
+ r.lines.length || editor?.key === newLineKey(r) ? r.lines.map((l) => lineView(l, r)) : el('span', { class: 'empty' }, t('No lines')),
1831
+ editor?.key === newLineKey(r) ? el('div', { class: 'line' }, editBox(t('New line'))) : null,
1832
+ editor?.key === `stick-${r.id}` ? stickPicker(r.id) : null,
1833
+ marks.get(r.id)?.action === 'add' && r.lines.length ? null : tag(r.id),
1834
+ conflictsOn(r.id).map(conflictCard),
1835
+ ),
1836
+ !open ? null : el('div', { class: 'tools' },
1837
+ !inOccur && openRow === r.id ? btn(t('Collapse'), () => { openRow = null; render(); }, 'icon', { 'aria-label': t('Collapse row'), title: t('Collapse') }) : null,
1838
+ !fixed && i > 0 ? btn('↑', () => send([{ op: 'row.move', input: { row: r.id, after: i > 1 ? list[i - 2].id : null } }]), 'icon', { 'aria-label': t('Move up'), title: t('Move up') }) : null,
1839
+ !fixed && i < list.length - 1 ? btn('↓', () => send([{ op: 'row.move', input: { row: r.id, after: list[i + 1].id } }]), 'icon', { 'aria-label': t('Move down'), title: t('Move down') }) : null,
1840
+ btn('+', () => startEdit({ key: newLineKey(r), draft: '', build: (text) => [{ op: 'line.add', input: { parent: r.id, text } }] }), 'icon', { 'aria-label': t('Add a line'), title: t('Add a line') }),
1841
+ listName === 'scene' ? btn(t('Adopt'), () => openAdopt(r.id), 'icon', { 'aria-label': t('Adopt from an output'), title: t('Adopt from an output') }) : null,
1842
+ listName === 'scene' ? btn(t('+ Paragraph'), () => openBodies.add(r.id) && startEdit({ key: newParaKey(r), draft: '', build: (text) => [{ op: 'para.add', input: { scene: r.id, text } }] }), 'icon', { 'aria-label': t('Add a body paragraph'), title: t('Add a body paragraph') }) : null,
1843
+ btn(t('+ Sticker'), () => openStickPicker(r.id), 'icon', { 'aria-label': t('Attach a memo from the memo box to this row'), title: t('Attach a memo from the memo box to this row') }),
1844
+ listName === 'scene' ? btn(t('Title'), () => startEdit({ key: titleKey, draft: r.title ?? '', plain: true, unchanged: r.title ?? '', build: (title) => [{ op: 'row.update', input: { row: r.id, title } }] }), 'icon', { 'aria-label': t('Edit title'), title: t('Edit title') }) : null,
1845
+ deleteButton(`row-${r.id}`, listName === 'scene' ? t('scene') : t('fact'), () => send([{ op: 'row.remove', input: { row: r.id } }])),
1846
+ ),
1847
+ open && listName === 'scene' && editor?.key === `adopt-${r.id}` ? adoptPanel(r) : null,
1848
+ open && listName === 'scene' ? bodyView(r, false) : null,
1849
+ );
1850
+ };
1851
+
1852
+ // 묶음의 머리 줄. 누르면 접고 펼친다. 위 30% 에 놓으면 앞, 아래 30% 에 놓으면 뒤(접혔을 때), 가운데에 놓으면 그 안의 맨 뒤로 간다
1853
+ const groupView = (g, depth, open) => {
1854
+ const sibs = sibsOf(g.parent ?? null);
1855
+ const i = sibs.findIndex((x) => x.id === g.id);
1856
+ const shown = worldFilter ? groupScenes(g.id).filter(sceneInFilter).length : g.scenes;
1857
+ const titleKey = `gtitle-${g.id}`;
1858
+ const sceneKey = `gscene-${g.id}`;
1859
+ const subKey = `gsub-${g.id}`;
1860
+ const toggle = () => { if (open) openGroups.delete(g.id); else openGroups.add(g.id); render(); };
1861
+ const zone = (ev) => {
1862
+ const rect = ev.currentTarget.getBoundingClientRect();
1863
+ const y = (ev.clientY - rect.top) / rect.height;
1864
+ return y < 0.3 ? 'before' : y > 0.7 && !open ? 'after' : 'into';
1865
+ };
1866
+ return el('li', {
1867
+ class: `row group-row${markClass(g.id)}`,
1868
+ 'data-group': g.id,
1869
+ 'data-target': g.id,
1870
+ ...(depth ? { style: `margin-left:${depth * 1.4}em` } : {}),
1871
+ on: {
1872
+ dragover: (ev) => {
1873
+ const d = dragging;
1874
+ if (!d || d.id === g.id || !(d.kind === 'group' || (d.kind === 'row' && d.list === 'scene'))) return;
1875
+ const z = zone(ev);
1876
+ if (d.kind === 'group' && insideOf(d.id, z === 'into' ? g.id : g.parent ?? null)) return;
1877
+ ev.preventDefault();
1878
+ clearDropMarks();
1879
+ ev.currentTarget.classList.add(`drop-${z}`);
1880
+ },
1881
+ dragleave: (ev) => ev.currentTarget.classList.remove('drop-before', 'drop-after', 'drop-into'),
1882
+ drop: (ev) => {
1883
+ ev.preventDefault();
1884
+ const d = dragging;
1885
+ const cl = ev.currentTarget.classList;
1886
+ const z = cl.contains('drop-before') ? 'before' : cl.contains('drop-after') ? 'after' : cl.contains('drop-into') ? 'into' : null;
1887
+ endDrag();
1888
+ if (!d || !z) return;
1889
+ let where;
1890
+ if (z === 'into') {
1891
+ where = d.kind === 'group' ? { parent: g.id } : { group: g.id };
1892
+ openGroups.add(g.id);
1893
+ } else {
1894
+ const others = sibs.filter((x) => x.id !== d.id);
1895
+ const at = others.findIndex((x) => x.id === g.id);
1896
+ const after = z === 'before' ? (at > 0 ? others[at - 1].id : null) : g.id;
1897
+ where = d.kind === 'group' ? { parent: g.parent ?? null, after } : { group: g.parent ?? null, after };
1898
+ }
1899
+ send([d.kind === 'group' ? { op: 'group.move', input: { group: d.id, ...where } } : { op: 'row.move', input: { row: d.id, ...where } }]);
1900
+ },
1901
+ },
1902
+ },
1903
+ canEdit ? el('button', {
1904
+ type: 'button', class: 'grip', draggable: 'true', title: t('Drag to move'), 'aria-label': t('Drag to move group {title}', { title: g.title }),
1905
+ on: {
1906
+ dragstart: (ev) => {
1907
+ dragging = { kind: 'group', id: g.id };
1908
+ ev.dataTransfer.effectAllowed = 'move';
1909
+ ev.dataTransfer.setData('text/plain', g.id);
1910
+ ev.currentTarget.closest('.row').classList.add('dragging');
1911
+ },
1912
+ dragend: () => endDrag(),
1913
+ },
1914
+ }, '⠿') : el('span', { class: 'grip', 'aria-hidden': 'true' }, ' '),
1915
+ el('button', { type: 'button', class: 'gtoggle', 'aria-expanded': open ? 'true' : 'false', 'aria-label': open ? t('Collapse group {title}', { title: g.title }) : t('Expand group {title}', { title: g.title }), on: { click: toggle } }, open ? '▾' : '▸'),
1916
+ el('div', { class: 'row-body' },
1917
+ editor?.key === titleKey
1918
+ ? editBox(t('Group name'), { hint: t('Enter to save, Esc to cancel.') })
1919
+ : el('span', { class: 'gtitle', on: { click: toggle } }, g.title),
1920
+ editor?.key === titleKey ? null : el('span', { class: 'gcount' }, worldFilter ? tCount(g.scenes, '{shown} of {n} scene', '{shown} of {n} scenes', { shown }) : tCount(g.scenes, '{n} scene', '{n} scenes')),
1921
+ tag(g.id),
1922
+ conflictsOn(g.id).map(conflictCard),
1923
+ editor?.key === sceneKey ? el('div', {}, editBox(t('New scene at the end of this group'))) : null,
1924
+ editor?.key === subKey ? el('div', {}, editBox(t('Name of the new group inside this group'))) : null,
1925
+ ),
1926
+ canEdit ? el('div', { class: 'tools' },
1927
+ i > 0 ? btn('↑', () => send([{ op: 'group.move', input: { group: g.id, after: i > 1 ? sibs[i - 2].id : null } }]), 'icon', { 'aria-label': t('Move up'), title: t('Move up') }) : null,
1928
+ i >= 0 && i < sibs.length - 1 ? btn('↓', () => send([{ op: 'group.move', input: { group: g.id, after: sibs[i + 1].id } }]), 'icon', { 'aria-label': t('Move down'), title: t('Move down') }) : null,
1929
+ btn(t('+ Scene'), () => startEdit({ key: sceneKey, draft: '', build: (text) => [{ op: 'row.add', input: { list: 'scene', group: g.id, lines: [text] } }] }), 'icon', { 'aria-label': t('Add a scene to this group'), title: t('Add a scene to this group') }),
1930
+ btn(t('+ Group'), () => startEdit({ key: subKey, draft: '', plain: true, build: (title) => [{ op: 'group.add', input: { title, parent: g.id } }] }), 'icon', { 'aria-label': t('Make a group inside this group'), title: t('Make a group inside this group') }),
1931
+ btn(t('Rename'), () => startEdit({ key: titleKey, draft: g.title, plain: true, unchanged: g.title, build: (title) => [{ op: 'group.update', input: { group: g.id, title } }] }), 'icon', { 'aria-label': t('Rename group'), title: t('Rename group') }),
1932
+ deleteButton(`group-${g.id}`, t('group (the scenes inside stay)'), () => send([{ op: 'group.remove', input: { group: g.id } }])),
1933
+ ) : null,
1934
+ );
1935
+ };
1936
+ // 펼친 차례의 장면과 묶음. all 이면 접힘을 무시한다. 세계선으로 거르면 보이는 장면이 없는 묶음은 숨긴다
1937
+ const sceneEntries = (all) => {
1938
+ const out = [];
1939
+ const walk = (ids, depth) => {
1940
+ for (const id of ids) {
1941
+ const g = groupById.get(id);
1942
+ if (g) {
1943
+ if (worldFilter && !groupScenes(id).some(sceneInFilter)) continue;
1944
+ const open = all || isGroupOpen(id);
1945
+ out.push({ g, depth, open });
1946
+ if (open) walk(g.items, depth + 1);
1947
+ } else {
1948
+ const r = sceneById.get(id);
1949
+ if (r && sceneInFilter(r)) out.push({ r, depth });
1950
+ }
1951
+ }
1952
+ };
1953
+ walk(sceneRoot, 0);
1954
+ return out;
1955
+ };
1956
+
1957
+ // 이어 읽기. 장면의 글 줄을 숨기고 제목과 본문만 차례로 보인다. 문단은 여기서도 눌러 고친다(novel.md 7.2절).
1958
+ const readView = (r, number) =>
1959
+ el('li', { class: `row${markClass(r.id)}${focused.has(r.id) ? ' focus' : ''}`, 'data-row': r.id, 'data-list': 'scene', 'data-target': r.id },
1960
+ el('div', { class: 'row-body' },
1961
+ el('h3', { class: 'read-title' }, r.title ? `${number}. ${r.title}` : `${number}.`),
1962
+ bodyView(r, true),
1963
+ conflictsOn(r.id).map(conflictCard),
1964
+ ));
1965
+ const modeSwitch = () => el('span', { class: 'mode', role: 'group', 'aria-label': t('Scene view') },
1966
+ el('button', { type: 'button', 'aria-pressed': reading ? 'false' : 'true', on: { click: () => { reading = false; render(); } } }, t('List')),
1967
+ el('button', { type: 'button', 'aria-pressed': reading ? 'true' : 'false', on: { click: () => { reading = true; occurred = false; render(); } } }, t('Read through')));
1968
+ // 읽는 차례는 소설의 순서이고, 일어난 차례는 사실 세로줄 옆에 장면을 붙인 보기다(16.5.2절). 화면 상태라 저장하지 않는다
1969
+ const orderSwitch = () => el('span', { class: 'mode', role: 'group', 'aria-label': t('Scene order') },
1970
+ el('button', { type: 'button', 'aria-pressed': occurred ? 'false' : 'true', on: { click: () => { occurred = false; render(); } } }, t('Reading order')),
1971
+ el('button', { type: 'button', 'aria-pressed': occurred ? 'true' : 'false', on: { click: () => { occurred = true; reading = false; render(); } } }, t('Order of events')));
1972
+
1973
+ // 목록의 검색과 쪽 나누기(메모함과 같은 모양). 공백으로 나눈 단어가 모두 든 것만 남고, 대소문자를 가리지 않는다.
1974
+ const rowText = (r) => [r.title ?? '', ...(r.lines ?? []).map((l) => plain(l.text)), ...(r.body ?? []).map((b) => plain(b.text))].join(' ');
1975
+ const listFilter = (key, items, textOf) => {
1976
+ const words = listQuery[key].toLowerCase().split(/\s+/).filter(Boolean);
1977
+ return words.length ? items.filter((it) => { const t = textOf(it).toLowerCase(); return words.every((w) => t.includes(w)); }) : items;
1978
+ };
1979
+ const listWindow = (key, found, size = LIST_PAGE) => {
1980
+ const pages = Math.max(1, Math.ceil(found.length / size));
1981
+ listPage[key] = Math.min(Math.max(0, listPage[key]), pages - 1);
1982
+ const page = listPage[key];
1983
+ return { shown: found.slice(page * size, (page + 1) * size), pages, page, found: found.length };
1984
+ };
1985
+ let findTimer = null;
1986
+ const listTools = (key, total, win, label, minTotal = 0) => {
1987
+ // 몇 개 안 되는 목록에는 검색칸을 두지 않는다. 이미 검색 중이면 지울 수 있게 둔다.
1988
+ if (total < minTotal && listQuery[key].trim() === '') return null;
1989
+ const input = el('input', {
1990
+ type: 'search', class: 'find', 'data-form-field': `find-${key}`, 'aria-label': label, autocomplete: 'off',
1991
+ placeholder: t('Search'), title: t('Separate words with spaces to show only the items that contain all of them'), value: listQuery[key],
1992
+ on: {
1993
+ input: (ev) => {
1994
+ if (ev.isComposing) return;
1995
+ clearTimeout(findTimer);
1996
+ findTimer = setTimeout(() => { listQuery[key] = input.value; listPage[key] = 0; render(); }, 120);
1997
+ },
1998
+ compositionend: () => { clearTimeout(findTimer); findTimer = setTimeout(() => { listQuery[key] = input.value; listPage[key] = 0; render(); }, 120); },
1999
+ keydown: (ev) => { if (ev.key === 'Escape' && input.value !== '') { ev.preventDefault(); input.value = ''; listQuery[key] = ''; listPage[key] = 0; render(); } },
2000
+ },
2001
+ });
2002
+ return el('div', { class: 'list-tools' }, input,
2003
+ el('span', { class: 'meta', 'aria-live': 'polite' }, listQuery[key].trim() === '' ? tCount(total, '{n} item', '{n} items') : t('{found} found (of {total})', { found: win.found, total })));
2004
+ };
2005
+ const listPager = (key, win) => {
2006
+ if (win.pages <= 1) return null;
2007
+ const go = (page) => { listPage[key] = page; render(); };
2008
+ return el('div', { class: 'list-pager', role: 'navigation', 'aria-label': t('Pages') },
2009
+ btn(t('First'), () => go(0), 'btn', { disabled: win.page === 0 }),
2010
+ btn(t('Previous'), () => go(win.page - 1), 'btn', { disabled: win.page === 0 }),
2011
+ el('span', { class: 'page-now', 'aria-live': 'polite' }, t('Page {page} / {pages}', { page: win.page + 1, pages: win.pages })),
2012
+ btn(t('Next'), () => go(win.page + 1), 'btn', { disabled: win.page >= win.pages - 1 }),
2013
+ btn(t('Last'), () => go(win.pages - 1), 'btn', { disabled: win.page >= win.pages - 1 }));
2014
+ };
2015
+
2016
+ const newRowKey = (list) => `newrow-${list}`;
2017
+ // 세계선으로 거르면 그 세계선의 장면만 남는다. 번호는 전체 목록의 번호를 그대로 둔다(16.13절)
2018
+ const numberedScenes = (rows) => rows.map((r, i) => [r, i + 1]).filter(([r]) => sceneInFilter(r));
2019
+ const filterNote = () => worldFilter
2020
+ ? el('p', { class: 'legend', 'data-scene-filter': worldFilter }, t('Showing only the scenes of world line {name}. ', { name: worlds.find((w) => w.id === worldFilter)?.name ?? worldFilter }), btn(t('Show all'), () => { worldFilter = null; render(); }))
2021
+ : null;
2022
+ const listSection = (title, listName, rows, numbered) =>
2023
+ el('section', { 'aria-label': title },
2024
+ // 위쪽 줄에는 [+ 장면] 이나 [+ 사실] 만 글자로 두고, 보기 전환과 장면 도구는 [⋯] 메뉴에 접어 둔다(rawdev 2026-11-24)
2025
+ el('div', { class: 'head' }, el('h2', {}, title),
2026
+ listName === 'scene' && (reading || occurred)
2027
+ ? btn(`${reading ? t('Read through') : t('Order of events')} ✕`, () => { reading = false; occurred = false; render(); }, 'chip view-chip', { title: t('Back to the list view') })
2028
+ : null,
2029
+ el('span', { class: 'head-tools' },
2030
+ listName === 'scene'
2031
+ ? el('details', { class: 'more', 'data-more': 'scene', open: moreOpen, on: { toggle: (ev) => { moreOpen = ev.currentTarget.open; } } },
2032
+ el('summary', { class: 'icon', 'aria-label': t('Scene views and tools'), title: t('Scene views and tools') }, '⋯'),
2033
+ el('div', { class: 'more-menu' },
2034
+ el('span', { class: 'label' }, t('View')),
2035
+ modeSwitch(),
2036
+ orderSwitch(),
2037
+ rows.length ? btn(t('Adopt all from the latest output'), () => { moreOpen = false; openAdoptAll(); }) : null,
2038
+ canEdit && !occurred ? btn(t('+ Group'), () => { moreOpen = false; startEdit({ key: 'newgroup', draft: '', plain: true, build: (title) => [{ op: 'group.add', input: { title } }] }); }, 'btn', { title: t('Makes a group for scenes. Drag a scene onto a group name to put it inside') }) : null,
2039
+ groups.length && !reading && !occurred ? btn(openGroups.size ? t('Collapse all groups') : t('Expand all groups'), () => { if (openGroups.size) openGroups.clear(); else for (const g of groups) openGroups.add(g.id); render(); }) : null))
2040
+ : null,
2041
+ listName === 'fact' ? btn('🌐', () => { worldPanel = !worldPanel; render(); }, 'icon world-btn', { 'aria-expanded': worldPanel ? 'true' : 'false', 'aria-label': t('World lines and calendars'), title: t('Make and edit world lines and calendars') }) : null,
2042
+ btn(listName === 'fact' ? t('+ Fact') : t('+ Scene'), () => startEdit({ key: newRowKey(listName), draft: '', build: (text) => [{ op: 'row.add', input: { list: listName, lines: [text] } }] })))),
2043
+ listName === 'fact' ? worldChips() : null,
2044
+ listName === 'scene' ? filterNote() : null,
2045
+ listName === 'fact' && worldPanel ? worldPanelView() : null,
2046
+ (() => {
2047
+ const empty = el('p', { class: 'empty' }, listName === 'fact' ? t('Write here what applies to the whole story. There is nothing yet.') : t('Place the scenes in the order the story shows them. There are none yet.'));
2048
+ if (!(rows.length || editor?.key === newRowKey(listName))) return empty;
2049
+ if (listName === 'scene' && reading) {
2050
+ // 이어 읽기에서는 묶음을 모두 펼치고 묶음 이름을 머리글로 둔다
2051
+ return el('ol', { class: 'reading' }, sceneEntries(true).map((x) => x.g
2052
+ ? el('li', { class: 'read-group', 'data-group': x.g.id, style: `margin-left:${x.depth * 1.4}em;font-size:${Math.max(13, 17 - x.depth * 2)}px` }, x.g.title)
2053
+ : readView(x.r, sceneNum.get(x.r.id))));
2054
+ }
2055
+ if (listName === 'scene' && occurred) return occurView();
2056
+ // 목록 보기는 검색과 쪽 나누기를 쓴다. 순서를 바꾸는 조작은 검색과 상관없이 전체 목록의 순서로 보낸다.
2057
+ if (listName === 'fact') {
2058
+ const all = (body.facts ?? []).filter(inFilter);
2059
+ const win = listWindow('fact', listFilter('fact', all, rowText));
2060
+ return el('div', {}, listTools('fact', all.length, win, t('Search facts'), 6), el('ul', {}, factItems(win.shown, all)), listPager('fact', win));
2061
+ }
2062
+ if (listName === 'scene') {
2063
+ const all = numberedScenes(rows);
2064
+ // 검색할 때와 묶음이 없을 때는 장면만 나열한다. 검색 결과에는 든 묶음의 이름이 보인다
2065
+ if (listQuery.scene.trim() !== '' || groups.length === 0) {
2066
+ const win = listWindow('scene', listFilter('scene', all, ([r]) => rowText(r)));
2067
+ return el('div', {}, listTools('scene', all.length, win, t('Search scenes'), 6), el('ol', {}, win.shown.map(([r, num]) => rowView(r, num, null, listName, false, 0, groupPath(r)))), listPager('scene', win));
2068
+ }
2069
+ // 묶음이 있으면 펼친 차례로 그리고 쪽은 보이는 줄로 나눈다. 쪽의 첫 장면에는 든 묶음의 이름을 적는다
2070
+ const win = listWindow('scene', sceneEntries(false));
2071
+ return el('div', {}, listTools('scene', all.length, win, t('Search scenes'), 6),
2072
+ el('ol', { class: 'tree' }, win.shown.map((x, k) => (x.g ? groupView(x.g, x.depth, x.open) : rowView(x.r, sceneNum.get(x.r.id), null, listName, false, x.depth, k === 0 && x.depth > 0 ? groupPath(x.r) : null)))),
2073
+ listPager('scene', win));
2074
+ }
2075
+ return el(numbered ? 'ol' : 'ul', {}, rows.map((r, i) => rowView(r, numbered ? i + 1 : null, rows, listName)));
2076
+ })(),
2077
+ editor?.key === newRowKey(listName) ? editBox(listName === 'fact' ? t('New fact') : t('New scene')) : null,
2078
+ listName === 'scene' && editor?.key === 'newgroup' ? editBox(t('New group name')) : null,
2079
+ listName === 'scene' && editor?.key === 'adopt-all' ? adoptAllPanel() : null,
2080
+ );
2081
+
2082
+ // 사실과 장면은 탭으로 나눠 한 번에 하나만 그린다. 어느 탭인지는 화면 상태라 저장하지 않는다.
2083
+ const rowChanged = (r) => held.has(r.id) || marks.has(r.id) || (r.lines ?? []).some((l) => held.has(l.id) || marks.has(l.id)) || (r.body ?? []).some((b) => held.has(b.id) || marks.has(b.id));
2084
+ const storyTabButton = (which, label, rows) => el('button', {
2085
+ type: 'button',
2086
+ role: 'tab',
2087
+ id: `tab-${which}`,
2088
+ 'aria-selected': storyTab === which ? 'true' : 'false',
2089
+ 'aria-controls': 'storyPanel',
2090
+ on: { click: () => {
2091
+ if (storyTab === which) return;
2092
+ if (editor) commitEditor();
2093
+ storyTab = which;
2094
+ render();
2095
+ } },
2096
+ }, `${label} `, el('span', { class: 'count' }, String(rows.length)), rows.some(rowChanged) ? el('span', { class: 'dot', title: t('There are changes not confirmed yet, or conflicts'), 'aria-label': t('Has unconfirmed changes') }, '●') : null);
2097
+ // 탭 줄 오른쪽에 왼쪽 칸을 여는 버튼과 [+ 메모] 를 둔다. 왼쪽 칸에 AI 가 지운 것이나 알림이 있으면 버튼에 점이 붙는다
2098
+ // 닫힌 왼쪽 칸에 새로 온 것이 있으면 열지 않아도 알 수 있게 버튼에 점과 그 내용을 붙인다
2099
+ const sideItems = [...body.nodes, ...body.relations];
2100
+ // 인물, 장소, 관계에 부딪힘이 새로 생기면 사람이 골라야 하니 왼쪽 칸을 한 번 연다. 사람이 닫으면 그대로 둔다
2101
+ for (const x of sideItems) if (held.has(x.id) && !sideConflictSeen.has(x.id)) { sideConflictSeen.add(x.id); sideOpen = true; }
2102
+ const sideParts = [
2103
+ sideItems.some((x) => held.has(x.id)) ? t('conflicts') : null,
2104
+ sideItems.some((x) => marks.has(x.id)) ? t('characters, places or relations the AI changed') : null,
2105
+ removed.some((m) => m.owner !== null) ? t('things the AI removed') : null,
2106
+ ].filter(Boolean);
2107
+ const sideNews = sideParts.length > 0;
2108
+ const storyTabs = el('div', { class: 'story-tabs' },
2109
+ el('div', { class: 'tab-list', role: 'tablist', 'aria-label': t('Facts and scenes') },
2110
+ storyTabButton('fact', t('Facts'), body.facts),
2111
+ storyTabButton('scene', t('Scenes'), body.scenes)),
2112
+ el('div', { class: 'bar-tools' },
2113
+ btn(['👤', sideNews && !sideOpen ? el('span', { class: 'dot', 'aria-hidden': 'true' }, '●') : null], () => { sideOpen = !sideOpen; render(); }, 'icon', {
2114
+ 'data-side-toggle': '', 'aria-pressed': sideOpen ? 'true' : 'false', 'aria-label': sideNews && !sideOpen ? t('Characters and places panel. New: {list}', { list: sideParts.join(', ') }) : t('Characters and places panel'),
2115
+ title: sideOpen ? t('Close the characters and places panel')
2116
+ : sideNews ? t('Open the panel with characters and places, relations and the change log. New: {list}', { list: sideParts.join(', ') })
2117
+ : t('Open the panel with characters and places, relations and the change log'),
2118
+ }),
2119
+ btn(t('+ Memo'), () => startEdit({
2120
+ key: 'newmemo',
2121
+ draft: '',
2122
+ build: (text) => [{ op: 'core.memo.add', as: '$memo', input: { text } }, { op: 'sticker.add', input: { memo: '$memo' } }],
2123
+ }), 'btn memo-add', { title: t('Makes a new memo and attaches it to this screen as a sticker. Drag the sticker onto a row to attach it there') })));
2124
+ const middle = el('div', { id: 'middle' },
2125
+ storyTabs,
2126
+ // 알림은 사람이 손대야 하는 것이라 칸을 열지 않아도 보이게 목록 위에 둔다(rawdev 2026-11-24)
2127
+ c.notices.length ? el('section', { 'aria-label': t('Notices') }, el('h2', {}, t('Notices')), c.notices.map((x) => el('div', { class: 'rel' }, x.message ?? x.kind))) : null,
2128
+ el('div', { id: 'storyPanel', role: 'tabpanel', 'aria-labelledby': `tab-${storyTab}` },
2129
+ storyTab === 'fact' ? listSection(t('Facts'), 'fact', body.facts, false) : listSection(t('Scenes'), 'scene', body.scenes, true)),
2130
+ // 줄이 없는 곳의 부딪힘. 내 쪽에서 지운 줄처럼 화면에 놓을 곳이 없다.
2131
+ (() => {
2132
+ // 그리지 않은 탭의 줄에도 부딪힘이 있을 수 있으니 두 쪽 모두 센다.
2133
+ const shown = new Set([...[...body.facts, ...body.scenes].flatMap((r) => [r.id, ...r.lines.map((l) => l.id), ...(r.body ?? []).map((b) => b.id)]), ...groups.map((g) => g.id)]);
2134
+ const rest = c.conflicts.filter((x) => !shown.has(x.record));
2135
+ return rest.length ? el('section', { 'aria-label': t('Conflicts') }, el('h2', {}, t('Conflicts')), rest.map(conflictCard)) : null;
2136
+ })(),
2137
+ );
2138
+
2139
+ // 바뀐 기록. 한 번에 한 줄 요약(무엇을 몇 개 어떻게 했는지)만 보이고, 누르면 바뀐 것을 하나씩 보여 준다.
2140
+ const feedView = () => {
2141
+ const list = feed.filter((x) => x.changes.length || x.summary);
2142
+ const shown = list.slice(-feedShown).reverse();
2143
+ const kindOf = (ch) => {
2144
+ const rec = ch.after ?? ch.before ?? {};
2145
+ if (ch.type === 'row') return rec.list === 'scene' ? tKey('Scene') : tKey('Fact');
2146
+ return FEED_KIND[ch.type] ?? ch.type;
2147
+ };
2148
+ // 요약: "사실 30개 더함, 글 줄 30개 더함" 처럼 종류와 한 일마다 센다. 큰 것부터 보이게 순서를 둔다.
2149
+ const headline = (x) => {
2150
+ const counts = new Map();
2151
+ for (const ch of x.changes) {
2152
+ const key = `${kindOf(ch)}|${ch.action}`;
2153
+ counts.set(key, (counts.get(key) ?? 0) + 1);
2154
+ }
2155
+ const rank = (key) => { const i = FEED_ORDER.indexOf(key.split('|')[0]); return i < 0 ? FEED_ORDER.length : i; };
2156
+ const parts = [...counts].sort((a, b) => rank(a[0]) - rank(b[0])).map(([key, num]) => {
2157
+ const [kind, action] = key.split('|');
2158
+ return t('{kind}: {num} {verb}', { kind: t(kind), num, verb: t(FEED_VERB[action] ?? action) });
2159
+ });
2160
+ return parts.length ? parts.join(', ') : x.summary;
2161
+ };
2162
+ const changeLine = (ch) => {
2163
+ const rec = ch.after ?? ch.before;
2164
+ const name = ch.type === 'row' ? (n.row.get(ch.record) ?? describeContent(rec)) : ch.type === 'calendar' ? (rec?.data?.name ?? ch.record) : describeContent(rec);
2165
+ const text = String(name).replace(/\s+/g, ' ');
2166
+ return el('li', {}, el('span', { class: 'kind-tag' }, t('{kind} {verb}', { kind: t(kindOf(ch)), verb: t(FEED_VERB[ch.action] ?? ch.action) })), ' ', [...text].length > 80 ? `${[...text].slice(0, 80).join('')}...` : text);
2167
+ };
2168
+ // 처음에는 머리글만 보이고 누르면 펼친다. 같은 기록은 코어의 기록 화면에도 있다
2169
+ const head = el('button', { type: 'button', class: 'feed-toggle', 'aria-expanded': feedOpen ? 'true' : 'false', on: { click: () => { feedOpen = !feedOpen; render(); } } },
2170
+ el('h2', {}, t('Change log')), el('span', { class: 'kind' }, t('{n} {arrow}', { n: list.length, arrow: feedOpen ? '▾' : '▸' })));
2171
+ if (!feedOpen) return el('section', { 'aria-label': t('Change log') }, head);
2172
+ return el('section', { 'aria-label': t('Change log') }, head,
2173
+ el('ul', { class: 'feed' }, shown.map((x) => {
2174
+ const open = openFeed.has(x.revision);
2175
+ const detail = open && x.changes.length
2176
+ ? el('ul', { class: 'feed-detail' }, x.changes.slice(0, FEED_DETAIL_MAX).map(changeLine),
2177
+ x.changes.length > FEED_DETAIL_MAX ? el('li', { class: 'legend' }, t('{count} more can be read with read_history.', { count: x.changes.length - FEED_DETAIL_MAX })) : null)
2178
+ : null;
2179
+ const toggle = () => { if (open) openFeed.delete(x.revision); else openFeed.add(x.revision); render(); };
2180
+ return el('li', { class: `feed-item${open ? ' open' : ''}` },
2181
+ el('button', { type: 'button', class: 'feed-head', 'aria-expanded': open ? 'true' : 'false', on: { click: toggle } },
2182
+ el('span', { class: 'who' }, el('b', {}, x.revision), x.mine ? t(' by me') : t(' by the AI'), x.inCommon ? null : el('span', { class: 'pending-chip' }, t('not confirmed'))),
2183
+ el('span', { class: 'headline' }, headline(x))),
2184
+ detail);
2185
+ })),
2186
+ list.length > feedShown || feedFrom
2187
+ ? btn(list.length > feedShown ? t('Show {count} earlier entries', { count: Math.min(FEED_PAGE, list.length - feedShown) }) : t('Show earlier entries'), () => {
2188
+ feedShown += FEED_PAGE;
2189
+ // 읽어 둔 것보다 더 보려면 더 앞에서부터 다시 읽는다
2190
+ if (list.length < feedShown && feedFrom) refresh();
2191
+ else render();
2192
+ }, 'btn')
2193
+ : null);
2194
+ };
2195
+
2196
+ // 왼쪽: 인물과 장소
2197
+ const nodeEditKey = (id) => `node-${id}`;
2198
+ const nodeWin = listWindow('node', listFilter('node', body.nodes, (nd) => `${nd.name} ${nd.kind} ${nd.note ?? ''}`), 12);
2199
+ const relWin = listWindow('relation', listFilter('relation', body.relations, (r) => `${n.node.get(r.a) ?? r.a} ${n.node.get(r.b) ?? r.b} ${r.name}`), 12);
2200
+ const left = el('div', {},
2201
+ el('section', { 'aria-label': t('Characters and places') },
2202
+ el('div', { class: 'head' }, el('h2', {}, t('Characters and places')),
2203
+ btn(t('+ Add'), () => startEdit({ key: 'newnode', form: 'node', name: '', kind: 'character', note: '', needsText: false }))),
2204
+ body.nodes.length === 0 && editor?.key !== 'newnode' ? el('p', { class: 'empty' }, t('None yet. You can make one by writing [name] in a line.')) : null,
2205
+ editor?.key === 'newnode' ? nodeForm(null) : null,
2206
+ listTools('node', body.nodes.length, nodeWin, t('Search characters and places'), 6),
2207
+ nodeWin.shown.map((nd) => editor?.key === nodeEditKey(nd.id) ? nodeForm(nd) : el('div', { 'data-target': nd.id, class: 'has-mini' },
2208
+ el('div', { class: `node-row${markClass(nd.id)}` },
2209
+ nodeButton(nd.id, nd.name), el('span', { class: 'kind' }, nd.kind), tag(nd.id),
2210
+ el('span', { class: 'mini', style: 'margin-left:auto;display:inline-flex' },
2211
+ btn(t('Edit'), () => startEdit({ key: nodeEditKey(nd.id), form: 'node', name: nd.name, kind: nd.kind, note: nd.note, needsText: false }), 'icon', { 'aria-label': t('Edit {name}', { name: nd.name }), title: t('Edit') }),
2212
+ deleteButton(`node-${nd.id}`, nd.name, () => send([{ op: 'node.remove', input: { node: nd.id } }]))),
2213
+ ),
2214
+ nd.note ? el('div', { class: 'note' }, nd.note) : null,
2215
+ conflictsOn(nd.id).map(conflictCard),
2216
+ )),
2217
+ listPager('node', nodeWin),
2218
+ ),
2219
+ el('section', { 'aria-label': t('Relations') },
2220
+ el('div', { class: 'head' }, el('h2', {}, t('Relations')),
2221
+ body.nodes.length >= 2 ? btn(t('+ Link'), () => startEdit({ key: 'newrel', form: 'relation', a: selectedNode ?? body.nodes[0].id, b: body.nodes.find((x) => x.id !== selectedNode)?.id ?? body.nodes[1].id, name: 'related', needsText: false })) : null),
2222
+ editor?.key === 'newrel' ? relationForm() : null,
2223
+ body.relations.length === 0 && editor?.key !== 'newrel' ? el('p', { class: 'empty' }, t('Links two characters or places.')) : null,
2224
+ listTools('relation', body.relations.length, relWin, t('Search relations'), 6),
2225
+ relWin.shown.map((r) => editor?.key === `rel-${r.id}`
2226
+ ? el('div', { class: 'rel' }, editBox(t('Relation name'), { hint: t('Enter to save, Esc to cancel.') }))
2227
+ : el('div', { class: `rel has-mini${markClass(r.id)}` },
2228
+ nodeButton(r.a, n.node.get(r.a) ?? r.a), ', ', nodeButton(r.b, n.node.get(r.b) ?? r.b), `: ${r.name}`, tag(r.id),
2229
+ el('span', { class: 'mini', style: 'display:inline-flex' },
2230
+ btn(t('Edit'), () => startEdit({ key: `rel-${r.id}`, draft: r.name, plain: true, unchanged: r.name, build: (name) => [{ op: 'relation.update', input: { relation: r.id, name } }] }), 'icon', { 'aria-label': t('Rename relation'), title: t('Edit') }),
2231
+ deleteButton(`rel-${r.id}`, t('relation'), () => send([{ op: 'relation.remove', input: { relation: r.id } }]))))),
2232
+ listPager('relation', relWin),
2233
+ ),
2234
+ removed.length
2235
+ ? (() => {
2236
+ const gone = removed.filter((m) => m.owner !== null);
2237
+ const win = listWindow('removed', gone, 10);
2238
+ return el('section', { 'aria-label': t('Removed by the AI') }, el('h2', {}, t('Removed by the AI')),
2239
+ el('ul', {}, win.shown.map((m) => el('li', { class: 'rel' }, describeContent(m.before), el('span', { class: 'tag remove' }, t(ACTION.remove))))),
2240
+ listPager('removed', win));
2241
+ })()
2242
+ : null,
2243
+ feed.length ? feedView() : null,
2244
+ );
2245
+
2246
+ // 새 메모는 메모함에 들어가면서 이 화면에 스티커로 붙는다. 사람이 화면에서 직접 한 일이다(029 7.2절).
2247
+ // [+ 메모] 는 탭 줄에 있다. 스티커 칸은 스티커가 있거나 새 메모를 쓰는 동안만 열린다(rawdev 2026-11-24)
2248
+ const gutter = el('div', { id: 'gutter' },
2249
+ editor?.key === 'newmemo' ? el('div', { style: 'position:relative;z-index:35' }, editBox(t('New memo'), { rows: 2 })) : null,
2250
+ );
2251
+
2252
+ // 붙은 대상이 지워졌거나 메모가 지워진 스티커는 그리지 않는다(029 7.2절)
2253
+ // 그리지 않은 탭의 줄에 붙은 스티커는 그 탭을 열 때 보인다. 놓을 곳이 없어 엉뚱한 자리에 뜨지 않게 한다.
2254
+ const hiddenTargets = new Set((storyTab === 'fact' ? body.scenes : body.facts).flatMap((r) => [r.id, ...(r.lines ?? []).map((l) => l.id), ...(r.body ?? []).map((b) => b.id)]));
2255
+ const shownStickers = (body.stickers ?? []).filter((st) => !st.targetGone && !hiddenTargets.has(st.target) && memoById.get(st.memo) && !memoById.get(st.memo).deleted);
2256
+ const layer = el('div', { id: 'memoLayer' }, shownStickers.map((st) => stickerView(st, memoById.get(st.memo), { markClass, tag, mentions, conflictsOn, nodeButton })));
2257
+
2258
+ const gutterOpen = shownStickers.length > 0 || editor?.key === 'newmemo';
2259
+ stage.replaceChildren(...[sideOpen ? left : null, middle, gutterOpen ? gutter : null, layer].filter(Boolean));
2260
+ stage.classList.toggle('with-side', sideOpen);
2261
+ stage.classList.toggle('with-gutter', gutterOpen);
2262
+ stage.classList.toggle('readonly', !canEdit);
2263
+ layoutMemos();
2264
+ restoreForms(keepInputs);
2265
+
2266
+ // 고치던 칸으로 돌아간다
2267
+ const ta = stage.querySelector('[data-editor]');
2268
+ if (ta) {
2269
+ autosize(ta);
2270
+ ta.focus({ preventScroll: true });
2271
+ const sel = editor?.selection;
2272
+ if (sel) ta.setSelectionRange(sel[0], sel[1]);
2273
+ else ta.setSelectionRange(ta.value.length, ta.value.length);
2274
+ if (editor?.suggest) drawSuggest(ta);
2275
+ }
2276
+ updateQuick();
2277
+ suppressBlur = false;
2278
+ if (drawPending) {
2279
+ drawPending = false;
2280
+ parent.postMessage({ aic: 1, event: 'rendered', token: c.renderToken }, '*');
2281
+ }
2282
+ }
2283
+
2284
+ function captureForms() {
2285
+ const out = new Map();
2286
+ for (const f of stage.querySelectorAll('[data-form-field]')) out.set(f.dataset.formField, f.value);
2287
+ const a = document.activeElement;
2288
+ return { fields: out, focus: a?.dataset?.formField, sel: a?.dataset?.formField && typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd] : null };
2289
+ }
2290
+
2291
+ function restoreForms(k) {
2292
+ for (const f of stage.querySelectorAll('[data-form-field]')) {
2293
+ if (k.fields.has(f.dataset.formField)) f.value = k.fields.get(f.dataset.formField);
2294
+ if (k.focus === f.dataset.formField) {
2295
+ f.focus({ preventScroll: true });
2296
+ if (k.sel && typeof f.setSelectionRange === 'function') { try { f.setSelectionRange(k.sel[0], k.sel[1]); } catch { /* 검색칸처럼 글자 위치를 못 잡는 칸 */ } }
2297
+ }
2298
+ }
2299
+ }
2300
+
2301
+ function field(name, label, value, type = 'text') {
2302
+ return el('label', {}, el('span', { class: 'kind' }, label),
2303
+ el('input', { type, value, 'data-form-field': name, on: {
2304
+ input: (ev) => { editor[name] = ev.target.value; },
2305
+ keydown: (ev) => {
2306
+ if (ev.isComposing) return;
2307
+ if (ev.key === 'Enter') { ev.preventDefault(); saveForm(); }
2308
+ if (ev.key === 'Escape') { ev.preventDefault(); closeEditor(); }
2309
+ },
2310
+ } }));
2311
+ }
2312
+
2313
+ function areaField(name, label, value) {
2314
+ return el('label', {}, el('span', { class: 'kind' }, label),
2315
+ el('textarea', { rows: 4, value, 'data-form-field': name, on: { input: (ev) => { editor[name] = ev.target.value; } } }));
2316
+ }
2317
+
2318
+ // 세계선 꼬리표의 색. 세계선의 이름 차례로 돌려 쓴다
2319
+ const WORLD_COLORS = ['#1f6a8c', '#8f5b00', '#1d7a46', '#a8321f', '#3b5bb5', '#6b3fa0', '#00796b', '#ad1457'];
2320
+
2321
+ /** 메타데이터 칸 하나를 보낸다. 고르기가 열린 때의 기준으로 보낸다(16.4.2절). */
2322
+ async function saveMeta(row, meta) {
2323
+ const e = editor;
2324
+ const res = await send([{ op: 'row.update', input: { row, meta } }], { base: e?.base });
2325
+ if (res && editor === e) closeEditor();
2326
+ }
2327
+
2328
+ /**
2329
+ * 달력 고치기 칸의 처음 값. 연호와 윤년은 이 칸이 고칠 수 있는 모양(원년부터 세는 연호 하나와 그 이전 연호 하나, 윤년 규칙 하나)일 때만
2330
+ * 칸으로 보이고, 아니면 그대로 둔다. AI 가 만든 달력을 화면이 모르게 바꾸지 않기 위해서다.
2331
+ */
2332
+ function calendarEdit(cal, copy) {
2333
+ const d = cal.data;
2334
+ const eras = d.eras ?? [];
2335
+ const fw = eras.filter((x) => x.direction === 1);
2336
+ const bw = eras.filter((x) => x.direction === -1);
2337
+ const simple = fw.length <= 1 && bw.length <= 1 && (fw.length === 0 || fw[0].start === d.epoch) && (bw.length === 0 || bw[0].start === undefined);
2338
+ const leap = d.leap ?? [];
2339
+ return {
2340
+ key: copy ? 'newcal' : `cal-${cal.id}`, form: 'calendar', calendar: copy ? null : cal.id, needsText: false,
2341
+ name: copy ? t('Copy of {name}', { name: cal.name }) : cal.name,
2342
+ epoch: cal.epochText,
2343
+ months: d.months.map((m) => `${m.name} ${m.days}`).join('\n'),
2344
+ day: d.day.map((u) => `${u.name} ${u.count}`).join('\n'),
2345
+ secondNs: d.secondNs,
2346
+ leapRule: leap.length === 1 ? leap[0].rule : '',
2347
+ leapMonth: leap.length === 1 ? String(leap[0].month) : '',
2348
+ leapKept: leap.length > 1 ? leap : null,
2349
+ eraForward: simple ? fw[0]?.name ?? '' : '',
2350
+ eraBackward: simple ? bw[0]?.name ?? '' : '',
2351
+ erasKept: simple ? null : eras,
2352
+ };
2353
+ }
2354
+
2355
+ /** 달력 칸의 글을 calendar.set 의 자료로. 원년과 연호의 시작은 글로 보내고 플러그인이 지구 달력으로 읽는다. */
2356
+ function calendarData(e) {
2357
+ const pairs = (t) => (t ?? '').split('\n').map((x) => x.trim()).filter(Boolean).map((x) => /^(.*\S)\s+(\d+)$/.exec(x));
2358
+ const months = pairs(e.months);
2359
+ const day = pairs(e.day);
2360
+ if (!months.length || !day.length || months.some((x) => !x) || day.some((x) => !x)) return null;
2361
+ const epoch = { text: (e.epoch ?? '').trim() };
2362
+ const data = {
2363
+ name: (e.name ?? '').trim(),
2364
+ epoch,
2365
+ secondNs: String(e.secondNs ?? '').trim(),
2366
+ day: day.map((m) => ({ name: m[1], count: Number(m[2]) })),
2367
+ months: months.map((m) => ({ name: m[1], days: Number(m[2]) })),
2368
+ };
2369
+ if (e.leapKept) data.leap = e.leapKept;
2370
+ else if ((e.leapRule ?? '').trim()) data.leap = [{ rule: e.leapRule.trim(), month: Number(e.leapMonth), days: 1 }];
2371
+ if (e.erasKept) {
2372
+ if (e.erasKept.length) data.eras = e.erasKept;
2373
+ } else {
2374
+ const eras = [];
2375
+ if ((e.eraForward ?? '').trim()) eras.push({ name: e.eraForward.trim(), start: epoch, direction: 1 });
2376
+ if ((e.eraBackward ?? '').trim()) eras.push({ name: e.eraBackward.trim(), direction: -1 });
2377
+ if (eras.length) data.eras = eras;
2378
+ }
2379
+ return data;
2380
+ }
2381
+
2382
+ async function saveForm() {
2383
+ const e = editor;
2384
+ if (!e) return;
2385
+ let steps;
2386
+ if (e.form === 'time') {
2387
+ const text = (e.text ?? '').trim();
2388
+ const time = text ? { text, world: e.world || null } : null;
2389
+ steps = [{ op: 'row.update', input: e.scene ? { row: e.row, meta: { time } } : { row: e.row, time } }];
2390
+ } else if (e.form === 'world') {
2391
+ const name = (e.name ?? '').trim();
2392
+ if (!name) { toast(t('Please write a name'), true); return; }
2393
+ const note = (e.note ?? '').trim();
2394
+ steps = e.world ? [{ op: 'world.update', input: { world: e.world, name, note } }] : [{ op: 'world.add', input: { name, note, calendar: e.calendar } }];
2395
+ } else if (e.form === 'calendar') {
2396
+ const data = calendarData(e);
2397
+ if (!data) { toast(t('Write the months and the units of a day one per line, as "name number"'), true); return; }
2398
+ steps = [{ op: 'calendar.set', input: { ...(e.calendar ? { calendar: e.calendar } : {}), data } }];
2399
+ } else if (e.form === 'node') {
2400
+ const name = (e.name ?? '').trim();
2401
+ if (!name) { toast(t('Please write a name'), true); return; }
2402
+ const input = { name, kind: (e.kind ?? '').trim() || 'character', note: (e.note ?? '').trim() };
2403
+ steps = e.key === 'newnode' ? [{ op: 'node.add', input }] : [{ op: 'node.update', input: { node: e.key.slice(5), ...input } }];
2404
+ } else {
2405
+ if (e.a === e.b) { toast(t('Please pick two different ones'), true); return; }
2406
+ steps = [{ op: 'relation.add', input: { a: e.a, b: e.b, name: (e.name ?? '').trim() || 'related' } }];
2407
+ }
2408
+ const res = await send(steps, { base: e.base });
2409
+ if (res && editor === e) closeEditor();
2410
+ }
2411
+
2412
+ function nodeForm(nd) {
2413
+ const e = editor;
2414
+ return el('div', { class: 'form', 'data-target': nd?.id },
2415
+ field('name', t('Name'), e.name),
2416
+ field('kind', t('Kind (any word, such as character or place)'), e.kind),
2417
+ field('note', t('Short note'), e.note),
2418
+ el('div', { class: 'actions' }, btn(t('Save'), saveForm, 'btn primary'), btn(t('Cancel'), closeEditor)),
2419
+ );
2420
+ }
2421
+
2422
+ function relationForm() {
2423
+ const e = editor;
2424
+ const body = concept.withOthers ?? concept.body;
2425
+ const pick = (name, label) => el('label', {}, el('span', { class: 'kind' }, label),
2426
+ el('select', { 'data-form-field': name, on: { change: (ev) => { editor[name] = ev.target.value; } } },
2427
+ body.nodes.map((n) => el('option', { value: n.id, ...(e[name] === n.id ? { selected: true } : {}) }, n.name))));
2428
+ return el('div', { class: 'form' }, pick('a', t('One')), pick('b', t('The other')), field('name', t('Name (any words)'), e.name),
2429
+ el('div', { class: 'actions' }, btn(t('Link'), saveForm, 'btn primary'), btn(t('Cancel'), closeEditor)));
2430
+ }
2431
+
2432
+ // 스티커. 메모함의 메모를 이 화면에 붙인 것이다. 붙은 대상이 있으면 그 옆에, 없으면 작업 영역의 비율로 놓는다(011 5.6절).
2433
+ // 메모의 글은 코어에 물어 가져오고, 고치거나 지우는 일은 호스트 화면의 메모함에서 한다(029 7절).
2434
+ function stickerView(st, memo, h) {
2435
+ const n = names();
2436
+ const ownerRow = n.rows.find((r) => r.lines.some((l) => l.id === st.target));
2437
+ const paraRow = n.rows.find((r) => (r.body ?? []).some((b) => b.id === st.target));
2438
+ const paraNo = paraRow ? paraRow.body.findIndex((b) => b.id === st.target) + 1 : 0;
2439
+ const where = st.target
2440
+ ? (n.row.get(st.target) ?? n.node.get(st.target) ?? (paraRow ? t('{row}, paragraph {n}', { row: paraRow.label.split(':')[0], n: paraNo }) : ownerRow ? t('Line of {row}', { row: ownerRow.label }) : t('Line')))
2441
+ : t('Work area');
2442
+ const targets = [
2443
+ ...n.rows.flatMap((r) => [{ id: r.id, label: r.label }, ...(r.body ?? []).map((b, i) => ({ id: b.id, label: t('{row}, paragraph {n}', { row: r.label, n: i + 1 }) }))]),
2444
+ ...n.nodes.map((x) => ({ id: x.id, label: x.name })),
2445
+ ];
2446
+ const attaching = editor?.key === `attach-${st.id}`;
2447
+ const gone = new Map((memo.targets ?? []).map((t) => [t.id, t]));
2448
+ const memoText = (memo.text ?? []).map((s) => {
2449
+ if (typeof s === 'string') return s;
2450
+ const g = gone.get(s.ref);
2451
+ if (g?.deleted) return el('span', { class: 'gone', title: t('Removed target') }, t('{text} (removed {type})', { text: s.text, type: g.type ?? t('target') }));
2452
+ if (n.node.has(s.ref)) return h.nodeButton(s.ref, s.text);
2453
+ return el('span', { class: 'frame-mark' }, s.text);
2454
+ });
2455
+ return el('div', {
2456
+ class: `memo has-mini${h.markClass(st.id)}${h.mentions(memo.text) ? ' hit' : ''}`,
2457
+ 'data-memo': st.id,
2458
+ 'data-memo-target': st.target ?? '',
2459
+ 'data-memo-basis': st.basis ?? 'canvas',
2460
+ 'data-pos': JSON.stringify(st.pos ?? [0.95, 0.05]),
2461
+ },
2462
+ el('div', { class: 'memo-bar', on: { pointerdown: (ev) => startMemoDrag(ev, st) } },
2463
+ el('span', { class: 'where' }, where),
2464
+ el('span', { class: 'mini', style: 'display:inline-flex' },
2465
+ btn(t('Attach'), () => { startEdit({ key: `attach-${st.id}`, form: 'attach', needsText: false }); }, 'icon', { title: t('Attach somewhere else') }),
2466
+ btn(t('Detach'), () => send([{ op: 'sticker.remove', input: { sticker: st.id } }]), 'icon', { title: t('Detach the sticker. The memo stays in the memo box') })),
2467
+ ),
2468
+ attaching
2469
+ ? el('div', { class: 'form' }, el('select', { 'aria-label': t('Where to attach'), on: { change: (ev) => {
2470
+ const v = ev.target.value;
2471
+ if (v) { closeEditor(); send([{ op: 'sticker.attach', input: { sticker: st.id, target: v } }]); }
2472
+ } } }, el('option', { value: '' }, t('Where should it go?')), targets.map((t) => el('option', { value: t.id }, t.label))), btn(t('Cancel'), closeEditor))
2473
+ : el('div', { class: 'memo-text', title: t('Edit the memo text in the memo box') }, memoText, h.tag(st.id)),
2474
+ h.conflictsOn(st.id).map(conflictCard),
2475
+ );
2476
+ }
2477
+
2478
+ /** "+ 스티커": 메모함 전체를 읽어 고르게 한다. 사람이 화면에서 직접 하는 일이다(029 7.2절). */
2479
+ async function openStickPicker(rowId) {
2480
+ try {
2481
+ memoChoices = (await call('readMemos', {})).memos.filter((m) => !m.deleted);
2482
+ } catch (err) {
2483
+ toast(err.message, true);
2484
+ return;
2485
+ }
2486
+ if (memoChoices.length === 0) {
2487
+ toast(t('The memo box is empty. You can attach a new memo with + Memo on the right.'));
2488
+ return;
2489
+ }
2490
+ startEdit({ key: `stick-${rowId}`, form: 'stick', needsText: false });
2491
+ }
2492
+
2493
+ // 결과물에서 들이기(novel.md 7.3절). 결과물은 호스트의 readArtifacts 로 읽고, 들이기는 보통의 조작 요청에 결과물 칸을 붙여 보낸다.
2494
+ // 화면은 장면 단위로만 들인다. 들이기도 플러그인 조작이라 편집 인스턴스가 아니면 코어의 거절 까닭을 그대로 보인다.
2495
+ const whenText = (iso) => {
2496
+ const d = new Date(iso);
2497
+ return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(lang === 'ko' ? 'ko-KR' : 'en-US', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
2498
+ };
2499
+ const newestFirst = (a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : Number(b.id.replace(/\D/g, '')) - Number(a.id.replace(/\D/g, '')));
2500
+
2501
+ async function readArtifactList() {
2502
+ let out;
2503
+ try {
2504
+ out = await call('readArtifacts');
2505
+ } catch (err) {
2506
+ toast(err.message, true);
2507
+ return null;
2508
+ }
2509
+ if (!out.ok) {
2510
+ toast(out.summary ?? out.error, true);
2511
+ return null;
2512
+ }
2513
+ return out.artifacts.slice().sort(newestFirst);
2514
+ }
2515
+
2516
+ async function openAdopt(sceneId) {
2517
+ const list = await readArtifactList();
2518
+ if (!list) return;
2519
+ const mine = list.filter((a) => (a.scenes ?? []).some((x) => x.key === sceneId));
2520
+ if (mine.length === 0) {
2521
+ toast(t('No output contains this scene. The AI makes outputs by generating them.'));
2522
+ return;
2523
+ }
2524
+ startEdit({ key: `adopt-${sceneId}`, form: 'adopt', needsText: false, list: mine, chosen: null });
2525
+ }
2526
+
2527
+ async function chooseArtifact(sceneId, a) {
2528
+ const e = editor;
2529
+ let out;
2530
+ try {
2531
+ out = await call('readArtifacts', { artifact: a.id });
2532
+ } catch (err) {
2533
+ toast(err.message, true);
2534
+ return;
2535
+ }
2536
+ if (!out.ok) {
2537
+ toast(out.summary ?? out.error, true);
2538
+ return;
2539
+ }
2540
+ if (editor !== e) return;
2541
+ const section = (out.sections ?? []).find((x) => x.key === sceneId) ?? null;
2542
+ e.chosen = { id: out.id, unconfirmed: out.unconfirmed, createdBy: out.createdBy, createdAt: out.createdAt, section };
2543
+ render();
2544
+ }
2545
+
2546
+ async function adoptInto(sceneId, artifact, mode) {
2547
+ closeEditor();
2548
+ const res = await send([{ op: 'body.adopt', input: { mode } }], { artifact: { id: artifact, keys: [sceneId] } });
2549
+ if (res) {
2550
+ openBodies.add(sceneId);
2551
+ toast(res.summary ?? t('Adopted'));
2552
+ render();
2553
+ }
2554
+ }
2555
+
2556
+ const artifactLine = (a) => [
2557
+ t('Output {id}', { id: a.id }),
2558
+ el('small', {}, `${whenText(a.createdAt)}, ${a.createdBy}${a.unconfirmed ? t(', made from unconfirmed changes') : ''}`),
2559
+ ];
2560
+
2561
+ function adoptPanel(r) {
2562
+ const e = editor;
2563
+ const paras = r.body ?? [];
2564
+ if (!e.chosen) {
2565
+ return el('div', { class: 'adopt', 'data-adopt': r.id },
2566
+ t("Which output should this scene's text be adopted from? The newest is at the top."),
2567
+ e.list.map((a) => el('button', { type: 'button', class: 'pick', on: { click: () => chooseArtifact(r.id, a) } }, artifactLine(a))),
2568
+ el('div', { class: 'actions' }, btn(t('Cancel'), closeEditor)));
2569
+ }
2570
+ const c = e.chosen;
2571
+ const back = () => { e.chosen = null; render(); };
2572
+ if (!c.section) {
2573
+ return el('div', { class: 'adopt', 'data-adopt': r.id },
2574
+ t('Output {id} has no text for this scene.', { id: c.id }),
2575
+ el('div', { class: 'actions' }, btn(t('Other output'), back), btn(t('Cancel'), closeEditor)));
2576
+ }
2577
+ return el('div', { class: 'adopt', 'data-adopt': r.id },
2578
+ el('div', {}, artifactLine(c)),
2579
+ el('div', { class: 'preview' }, c.section.text),
2580
+ paras.length ? el('p', { class: 'warn' }, tCount(paras.length, 'Replace removes the current body text ({n} paragraph) and puts this text in its place. Append adds this text after the current body text.', 'Replace removes the current body text ({n} paragraphs) and puts this text in its place. Append adds this text after the current body text.')) : null,
2581
+ el('div', { class: 'actions' },
2582
+ btn(t('Replace'), () => adoptInto(r.id, c.id, 'replace'), 'btn primary'),
2583
+ paras.length ? btn(t('Append'), () => adoptInto(r.id, c.id, 'append')) : null,
2584
+ btn(t('Other output'), back),
2585
+ btn(t('Cancel'), closeEditor)));
2586
+ }
2587
+
2588
+ /** 이 인스턴스의 가장 새 결과물의 장면 전체를 바꾸기로 들인다. 결과물 하나로 소설 전체 초안을 받은 뒤 한 번에 들일 때 쓴다. */
2589
+ async function openAdoptAll() {
2590
+ const list = await readArtifactList();
2591
+ if (!list) return;
2592
+ const newest = list.find((a) => !concept.instance || a.instance === concept.instance);
2593
+ if (!newest) {
2594
+ toast(t('This screen has no outputs. The AI makes outputs by generating them.'));
2595
+ return;
2596
+ }
2597
+ startEdit({ key: 'adopt-all', form: 'adopt', needsText: false, newest });
2598
+ }
2599
+
2600
+ function adoptAllPanel() {
2601
+ const a = editor.newest;
2602
+ const body = concept.withOthers ?? concept.body;
2603
+ const keys = new Set((a.scenes ?? []).map((x) => x.key));
2604
+ const withBody = body.scenes.filter((r) => keys.has(r.id) && (r.body ?? []).length).length;
2605
+ return el('div', { class: 'adopt', 'data-adopt': 'all' },
2606
+ el('div', {}, artifactLine(a)),
2607
+ tCount(keys.size, 'Adopts all {n} scene of this output with Replace.', 'Adopts all {n} scenes of this output with Replace.'),
2608
+ withBody ? el('p', { class: 'warn' }, tCount(withBody, 'In {n} scene with body text, the current body text is removed and replaced by the text of this output.', 'In {n} scenes with body text, the current body text is removed and replaced by the text of this output.')) : null,
2609
+ el('div', { class: 'actions' },
2610
+ btn(t('Adopt all'), async () => {
2611
+ closeEditor();
2612
+ const res = await send([{ op: 'body.adopt', input: { mode: 'replace' } }], { artifact: { id: a.id } });
2613
+ if (res) {
2614
+ for (const k of keys) openBodies.add(k);
2615
+ toast(res.summary ?? t('Adopted'));
2616
+ render();
2617
+ }
2618
+ }, 'btn primary'),
2619
+ btn(t('Cancel'), closeEditor)));
2620
+ }
2621
+
2622
+ function stickPicker(rowId) {
2623
+ return el('div', { class: 'form' },
2624
+ el('select', { 'aria-label': t('Memo to attach'), on: { change: (ev) => {
2625
+ const v = ev.target.value;
2626
+ if (v) { closeEditor(); send([{ op: 'sticker.add', input: { memo: v, target: rowId } }]); }
2627
+ } } }, el('option', { value: '' }, t('Which memo should be attached?')), (memoChoices ?? []).map((m) => el('option', { value: m.id }, m.display))),
2628
+ btn(t('Cancel'), closeEditor));
2629
+ }
2630
+
2631
+ const narrow = () => window.matchMedia('(max-width: 1000px)').matches;
2632
+
2633
+ function targetElement(id) {
2634
+ return stage.querySelector(`[data-target="${CSS.escape(id)}"]`) ?? stage.querySelector(`[data-hidden-paras~="${CSS.escape(id)}"]`);
2635
+ }
2636
+
2637
+ function layoutMemos() {
2638
+ if (narrow()) return;
2639
+ const box = stage.getBoundingClientRect();
2640
+ const placed = [];
2641
+ let bottom = 0;
2642
+ for (const memo of stage.querySelectorAll('[data-memo]')) {
2643
+ const pos = JSON.parse(memo.dataset.pos);
2644
+ const target = memo.dataset.memoTarget && targetElement(memo.dataset.memoTarget);
2645
+ let x;
2646
+ let y;
2647
+ if (target) {
2648
+ // 대상 옆에 놓는다. 대상이 넓으면 메모 칸까지만 민다.
2649
+ const r = (target.closest('.row') ?? target).getBoundingClientRect();
2650
+ const t = target.getBoundingClientRect();
2651
+ x = r.right - box.left + pos[0] * LINE_HEIGHT;
2652
+ y = t.top - box.top + pos[1] * LINE_HEIGHT;
2653
+ } else {
2654
+ x = pos[0] * box.width;
2655
+ y = pos[1] * box.height;
2656
+ }
2657
+ x = Math.max(0, Math.min(x, box.width - memo.offsetWidth - 4));
2658
+ y = Math.max(0, y);
2659
+ // 기본 위치에 겹치면 보기에만 아래로 민다. 저장된 위치는 그대로다.
2660
+ const isDefault = (target && pos[0] === 1 && pos[1] === 0) || (!target && pos[0] === 0.95 && pos[1] === 0.05);
2661
+ if (isDefault) {
2662
+ if (!target) y = Math.max(y, 44);
2663
+ let moved = true;
2664
+ while (moved) {
2665
+ moved = false;
2666
+ for (const p of placed) {
2667
+ if (Math.abs(p.x - x) < memo.offsetWidth && y < p.y + p.h + 6 && y + memo.offsetHeight > p.y) {
2668
+ y = p.y + p.h + 6;
2669
+ moved = true;
2670
+ }
2671
+ }
2672
+ }
2673
+ }
2674
+ memo.style.left = `${x}px`;
2675
+ memo.style.top = `${y}px`;
2676
+ placed.push({ x, y, h: memo.offsetHeight });
2677
+ bottom = Math.max(bottom, y + memo.offsetHeight + 16);
2678
+ }
2679
+ stage.style.minHeight = bottom ? `${bottom}px` : '';
2680
+ }
2681
+
2682
+ function startMemoDrag(ev, m) {
2683
+ if (!canEdit || ev.target.closest('button') || narrow() || ev.button !== 0) return;
2684
+ ev.preventDefault();
2685
+ const memo = ev.currentTarget.closest('[data-memo]');
2686
+ const box = stage.getBoundingClientRect();
2687
+ const r = memo.getBoundingClientRect();
2688
+ const dx = ev.clientX - r.left;
2689
+ const dy = ev.clientY - r.top;
2690
+ const bar = ev.currentTarget;
2691
+ bar.setPointerCapture(ev.pointerId);
2692
+ dragging = { kind: 'memo', id: m.id };
2693
+ quickEl.hidden = true;
2694
+ memo.classList.add('floating');
2695
+ let over = null;
2696
+ const hit = (e) => {
2697
+ memo.style.pointerEvents = 'none';
2698
+ const under = document.elementFromPoint(e.clientX, e.clientY);
2699
+ memo.style.pointerEvents = '';
2700
+ return under?.closest?.('[data-target]') ?? null;
2701
+ };
2702
+ const move = (e) => {
2703
+ memo.style.left = `${e.clientX - box.left - dx}px`;
2704
+ memo.style.top = `${e.clientY - box.top - dy}px`;
2705
+ const t = hit(e);
2706
+ if (t !== over) {
2707
+ over?.classList.remove('drop-on');
2708
+ t?.classList.add('drop-on');
2709
+ over = t;
2710
+ }
2711
+ };
2712
+ const up = (e) => {
2713
+ bar.removeEventListener('pointermove', move);
2714
+ bar.removeEventListener('pointerup', up);
2715
+ bar.removeEventListener('pointercancel', cancel);
2716
+ over?.classList.remove('drop-on');
2717
+ memo.classList.remove('floating');
2718
+ dragging = null;
2719
+ const left = e.clientX - dx;
2720
+ const top = e.clientY - dy;
2721
+ if (Math.abs(e.clientX - (r.left + dx)) < 4 && Math.abs(e.clientY - (r.top + dy)) < 4) {
2722
+ if (renderWanted) render();
2723
+ else layoutMemos();
2724
+ return;
2725
+ }
2726
+ const target = over?.dataset.target ?? null;
2727
+ const round = (v) => Math.round(v * 100) / 100;
2728
+ if (target) {
2729
+ // 다른 대상에 놓으면 그 옆의 기본 위치로 간다(011 5.6절). 같은 대상 안에서만 놓은 곳을 지킨다.
2730
+ if (target !== m.target) {
2731
+ send([{ op: 'sticker.attach', input: { sticker: m.id, target } }]);
2732
+ } else {
2733
+ const t = over.getBoundingClientRect();
2734
+ const rowRight = (over.closest('.row') ?? over).getBoundingClientRect().right;
2735
+ send([{ op: 'sticker.move', input: { sticker: m.id, position: [round((left - rowRight) / LINE_HEIGHT), round((top - t.top) / LINE_HEIGHT)] } }]);
2736
+ }
2737
+ } else {
2738
+ const position = [round((left - box.left) / box.width), round((top - box.top) / box.height)];
2739
+ if (m.target) send([{ op: 'sticker.attach', input: { sticker: m.id, target: null, position } }]);
2740
+ else send([{ op: 'sticker.move', input: { sticker: m.id, position } }]);
2741
+ }
2742
+ };
2743
+ const cancel = () => {
2744
+ bar.removeEventListener('pointermove', move);
2745
+ bar.removeEventListener('pointerup', up);
2746
+ bar.removeEventListener('pointercancel', cancel);
2747
+ over?.classList.remove('drop-on');
2748
+ memo.classList.remove('floating');
2749
+ dragging = null;
2750
+ render();
2751
+ };
2752
+ bar.addEventListener('pointermove', move);
2753
+ bar.addEventListener('pointerup', up);
2754
+ bar.addEventListener('pointercancel', cancel);
2755
+ }
2756
+
2757
+ function clearDropMarks() {
2758
+ for (const x of stage.querySelectorAll('.drop-before, .drop-after, .drop-into')) x.classList.remove('drop-before', 'drop-after', 'drop-into');
2759
+ for (const x of stage.querySelectorAll('.fact-cell.drop-on')) x.classList.remove('drop-on');
2760
+ }
2761
+
2762
+ function endDrag() {
2763
+ dragging = null;
2764
+ clearDropMarks();
2765
+ for (const x of stage.querySelectorAll('.dragging')) x.classList.remove('dragging');
2766
+ if (renderWanted) render();
2767
+ }
2768
+
2769
+ window.addEventListener('resize', () => { if (concept && !dragging) layoutMemos(); });
2770
+
2771
+ parent.postMessage({ aic: 1, event: 'ready', rendered: true }, '*');
2772
+
2773
+ // 읽기만 하는 보조 보기(999 3.1절, 032 10.2절)는 capabilities().edit 가 거짓이다. 한 화면은 편집이거나 보조 보기로 정해져 열리므로
2774
+ // 시작할 때 한 번 읽는다(코어 세션과 맞춤, 2026-11-09). 지금 코어는 늘 참을 주므로 바뀌는 것이 없다.
2775
+ call('capabilities', {}).then((cap) => {
2776
+ if (cap && typeof cap === 'object') caps = cap;
2777
+ if (cap && cap.edit === false) canEdit = false;
2778
+ setLanguage(cap?.language);
2779
+ render();
2780
+ }).catch(() => {});
2781
+ </script>
2782
+ </body>
2783
+ </html>