@eliceio/cdk-cli 1.4.1 → 1.5.1

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 (79) hide show
  1. package/README.md +17 -16
  2. package/es/cli.js +1 -1
  3. package/es/commands/create/index.js +1 -0
  4. package/es/commands/create/scaffold.d.ts +1 -1
  5. package/es/commands/create/scaffold.js +1 -1
  6. package/es/core/config.d.ts +36 -0
  7. package/es/core/config.js +234 -6
  8. package/es/core/quiz-check.js +123 -4
  9. package/es/dev/grading.d.ts +26 -4
  10. package/es/dev/grading.js +66 -11
  11. package/es/dev/mock-api.d.ts +6 -1
  12. package/es/dev/mock-api.js +45 -6
  13. package/es/rules/answers.d.ts +1 -0
  14. package/es/rules/answers.js +8 -0
  15. package/es/rules.json.js +1 -1
  16. package/package.json +2 -2
  17. package/rules.json +1 -1
  18. package/skills/_shared/always.md +1 -1
  19. package/skills/_shared/references/02-design-the-material.md +8 -7
  20. package/skills/_shared/references/03-create-the-project.md +10 -9
  21. package/skills/_shared/references/12-upload-with-the-material-mcp.md +5 -5
  22. package/skills/_shared/references/16-using-the-survey-template.md +158 -0
  23. package/skills/elice-content-create/SKILL.md +2 -2
  24. package/skills/elice-content-edit/SKILL.md +2 -2
  25. package/skills/elice-content-publish/SKILL.md +1 -1
  26. package/templates/_shared/lib/cdk-mock.d.ts +22 -3
  27. package/templates/_shared/lib/cdk-mock.js +78 -11
  28. package/templates/_shared/lib/elice-content.d.ts +17 -1
  29. package/templates/_shared/lib/elice-content.js +47 -5
  30. package/templates/blank/template.json +1 -1
  31. package/templates/document/template.json +2 -2
  32. package/templates/quiz/README.md +26 -1
  33. package/templates/quiz/core/behaviors.d.ts +5 -0
  34. package/templates/quiz/core/behaviors.js +16 -1
  35. package/templates/quiz/core/model.d.ts +78 -1
  36. package/templates/quiz/core/model.js +219 -4
  37. package/templates/quiz/screens/edit.js +244 -55
  38. package/templates/quiz/screens/learn.js +137 -27
  39. package/templates/quiz/styles.css +258 -5
  40. package/templates/quiz/template.json +1 -1
  41. package/templates/quiz/ui/templates/edit.d.ts +1 -0
  42. package/templates/quiz/ui/templates/edit.js +67 -8
  43. package/templates/quiz/ui/templates/page.js +34 -0
  44. package/templates/quiz/ui/templates/text.js +15 -2
  45. package/templates/quiz/ui/texts.js +61 -0
  46. package/templates/steps/template.json +1 -1
  47. package/templates/survey/README.md +112 -0
  48. package/templates/survey/commentary.txt +2 -0
  49. package/templates/survey/core/behaviors.d.ts +14 -0
  50. package/templates/survey/core/behaviors.js +115 -0
  51. package/templates/survey/core/dom.d.ts +13 -0
  52. package/templates/survey/core/dom.js +83 -0
  53. package/templates/survey/core/editor.d.ts +80 -0
  54. package/templates/survey/core/editor.js +720 -0
  55. package/templates/survey/core/markdown.d.ts +21 -0
  56. package/templates/survey/core/markdown.js +298 -0
  57. package/templates/survey/core/model.d.ts +83 -0
  58. package/templates/survey/core/model.js +209 -0
  59. package/templates/survey/core/rich-text.d.ts +18 -0
  60. package/templates/survey/core/rich-text.js +469 -0
  61. package/templates/survey/edit.html +26 -0
  62. package/templates/survey/gitignore +4 -0
  63. package/templates/survey/index.html +26 -0
  64. package/templates/survey/metadata.json +9 -0
  65. package/templates/survey/package.json +13 -0
  66. package/templates/survey/screens/edit.js +345 -0
  67. package/templates/survey/screens/learn.js +100 -0
  68. package/templates/survey/styles.css +1264 -0
  69. package/templates/survey/template.json +12 -0
  70. package/templates/survey/ui/templates/edit.d.ts +27 -0
  71. package/templates/survey/ui/templates/edit.js +656 -0
  72. package/templates/survey/ui/templates/index.d.ts +3 -0
  73. package/templates/survey/ui/templates/index.js +3 -0
  74. package/templates/survey/ui/templates/learn.js +147 -0
  75. package/templates/survey/ui/templates/page.js +19 -0
  76. package/templates/survey/ui/texts.d.ts +3 -0
  77. package/templates/survey/ui/texts.js +116 -0
  78. package/templates/survey/ui/theme.css +42 -0
  79. package/templates/video/template.json +1 -1
@@ -0,0 +1,720 @@
1
+ // 퀴즈 템플릿의 core/editor.js를 가져와 고르기 목록(picker) · 서식 도구(formatTools)를 밖에서도 쓰게 했습니다.
2
+ // 편집 화면 동작: 칸에 값 넣기 · 입력 반영 · 보기/그룹 목록 (추가 · 삭제 · 끌어서 순서 바꾸기).
3
+ // 마크업은 ui/templates/edit.js가 만들고, 여기서는 data-role로만 요소를 찾는다.
4
+ // ui/를 직접 불러오지 않는다: 템플릿과 문구는 화면(screens/edit.js)이 넘겨 준다.
5
+ import { part, parts } from './dom.js';
6
+ import { assetBlock, refSrc } from './markdown.js';
7
+ import { LIMITS, nextId } from './model.js';
8
+ import { joinBlocks, richText, splitBlocks } from './rich-text.js';
9
+
10
+ /**
11
+ * 편집 폼 도우미. rerender: 데이터를 바꾼 뒤 폼을 다시 그리는 함수 · root: 폼이 놓인 요소(키보드로 옮긴 뒤 초점 찾기)
12
+ * templates: HTML 조각 모음(ui/templates/edit.js) · labels: 동작이 바꾸는 문구 (글자 수 · 새 그룹 이름)
13
+ * @param {{ rerender: () => void, root: Element, templates: object,
14
+ * labels: { count: (length: number, max: number) => string, group: (letter: string) => string } }} opts
15
+ */
16
+ export function createEditor({ rerender, root, templates, labels }) {
17
+ const ui = templates;
18
+
19
+ /** 글 입력 칸. 값을 넣고, 고치면 onInput(값)과 글자 수를 갱신. showOptional: false면 "선택" 표시 없음 */
20
+ function field(
21
+ label,
22
+ value,
23
+ onInput,
24
+ { multiline = false, required = false, showOptional = true, max, hint } = {},
25
+ ) {
26
+ return bindField(
27
+ ui.field({ label, required, showOptional, hint, max, multiline }),
28
+ value,
29
+ onInput,
30
+ max,
31
+ );
32
+ }
33
+
34
+ /**
35
+ * 라벨 없는 바로 쓰는 칸 (ui.inlineField). field와 같이 값을 넣고 고치면 onInput(값).
36
+ * 여러 줄 칸은 글에 맞춰 높이가 늘고, 필수 칸은 글을 쓰면 오류 표시(aria-invalid)를 지운다
37
+ * @param {{ placeholder: string, size?: 'title' | 'question' | 'body', required?: boolean, max?: number, multiline?: boolean }} opts
38
+ */
39
+ function inlineField(label, value, onInput, opts) {
40
+ const node = bindField(ui.inlineField({ label, ...opts }), value, onInput, opts.max);
41
+ const input = part(node, 'input');
42
+ input.addEventListener('input', () => input.removeAttribute('aria-invalid'));
43
+ if (opts.multiline) {
44
+ const fit = () => {
45
+ input.style.height = 'auto';
46
+ input.style.height = `${input.scrollHeight}px`;
47
+ };
48
+ input.addEventListener('input', fit);
49
+ // 화면에 붙은 뒤에야 높이를 잴 수 있다
50
+ requestAnimationFrame(fit);
51
+ }
52
+ return node;
53
+ }
54
+
55
+ /** 비어 있는 필수 바로 쓰는 칸에 오류 표시를 붙이고 첫 칸을 돌려준다 (저장 전 검증에 걸렸을 때) */
56
+ function markEmptyRequired() {
57
+ const empty = [...root.querySelectorAll('[data-required]')].filter((i) => !i.value.trim());
58
+ for (const input of empty) input.setAttribute('aria-invalid', 'true');
59
+ return empty[0] ?? null;
60
+ }
61
+
62
+ function bindField(node, value, onInput, max) {
63
+ const input = part(node, 'input');
64
+ const count = part(node, 'count');
65
+ input.value = value ?? '';
66
+ if (max) input.maxLength = max;
67
+ const showCount = () =>
68
+ count && (count.textContent = labels.count(input.value.length, max));
69
+ showCount();
70
+ input.addEventListener('input', () => {
71
+ onInput(input.value);
72
+ showCount();
73
+ });
74
+ return node;
75
+ }
76
+
77
+ /** 숫자 칸 */
78
+ function numberField(label, hint, value, max, onInput) {
79
+ const node = ui.numberField({ label, hint, max });
80
+ const input = part(node, 'input');
81
+ input.value = value;
82
+ input.addEventListener('input', () => onInput(Number(input.value)));
83
+ return node;
84
+ }
85
+
86
+ /** 켜고 끄기. title: 마우스를 올리면 보이는 보충 설명 */
87
+ function toggle(label, checked, onChange, title, icon) {
88
+ const node = ui.toggle({ label, title, icon });
89
+ const input = part(node, 'input');
90
+ input.checked = Boolean(checked);
91
+ input.addEventListener('change', () => onChange(input.checked));
92
+ return node;
93
+ }
94
+
95
+ /**
96
+ * 필요할 때만 여는 칸. open이 아니면 "+ …" 버튼만 보이고, 누르면 칸이 열려 초점이 간다.
97
+ * 비운 채 칸을 벗어나면 다시 닫는다. 여닫는 것만으로는 다시 그리거나 "변경" 표시를 만들지 않는다
98
+ * @param {string} label 열기 버튼 글
99
+ * @param {Element} node 칸 (inlineField가 만든 요소)
100
+ * @param {{ open?: boolean, onOpen?: () => void, onClose?: () => void, title?: string, icon?: string, hint?: string,
101
+ * tools?: object, images?: { add: (file: File) => Promise<string>, fail: (error: Error & { code?: string }) => void } }} [opts]
102
+ * title가 있으면 열린 칸을 머리줄(아이콘 · 제목 · 지우기)이 있는 카드로 보인다.
103
+ * tools(서식 도구 문구 texts.edit.md)를 주면 richField 칸에 서식 도구를 붙이고, images도 주면 그림 올리기 버튼을 보인다
104
+ */
105
+ function revealable(
106
+ label,
107
+ node,
108
+ { open = false, onOpen, onClose, onRemoved, title, icon, hint, tools, images } = {},
109
+ ) {
110
+ const wrap = ui.reveal({ label, field: node, title, icon, hint });
111
+ const button = part(wrap, 'reveal');
112
+ const body = part(wrap, 'reveal-body');
113
+ const input = part(node, 'input');
114
+ // 서식 도구: richField 칸 아래에 (칸에 초점이 있을 때만 보임)
115
+ if (tools) formatTools(node, tools, images);
116
+ const fit = () => {
117
+ if (input.tagName !== 'TEXTAREA') return;
118
+ input.style.height = 'auto';
119
+ input.style.height = `${input.scrollHeight}px`;
120
+ };
121
+ const show = () => {
122
+ button.hidden = true;
123
+ body.hidden = false;
124
+ fit();
125
+ };
126
+ const hide = () => {
127
+ body.hidden = true;
128
+ button.hidden = false;
129
+ };
130
+ button.addEventListener('click', () => {
131
+ show();
132
+ onOpen?.();
133
+ input.focus();
134
+ });
135
+ input.addEventListener('blur', () => {
136
+ // 창을 옮겨 초점을 잃은 경우(초점 요소가 그대로)는 닫지 않는다
137
+ if (input.value.trim() || document.activeElement === input) return;
138
+ hide();
139
+ onClose?.();
140
+ });
141
+ // 내용이 있어도 지우고 닫는다 (비우는 입력을 흘려 보내 데이터에도 반영)
142
+ // 글이 있었으면 onRemoved(지운 글) — 화면이 되돌리기 알림을 띄운다
143
+ part(wrap, 'reveal-close').addEventListener('click', () => {
144
+ const removed = input.value;
145
+ input.value = '';
146
+ input.dispatchEvent(new Event('input', { bubbles: true }));
147
+ hide();
148
+ onClose?.();
149
+ button.focus();
150
+ if (removed.trim()) onRemoved?.(removed);
151
+ });
152
+ if (open) button.hidden = true;
153
+ else body.hidden = true;
154
+ return wrap;
155
+ }
156
+
157
+ /**
158
+ * 지문 · 해설 칸: 보이는 그대로 고치는 글 칸(core/rich-text.js)과 올린 그림 칸이 차례로 놓인다. 값은 마크다운.
159
+ * 숨은 textarea(data-role="input")가 값을 들고 있어 revealable이 다른 칸처럼 다룬다 (비우고 닫기 · 칸을 벗어나면 blur)
160
+ * @param {{ placeholder?: string, images?: { removeLabel: string, onRemoved?: (undo: () => void) => void } }} [opts]
161
+ * images.onRemoved: 그림 칸을 지운 뒤 (되돌리기 함수를 받아 알림)
162
+ */
163
+ function richField(label, value, onInput, { placeholder, images } = {}) {
164
+ const node = ui.richField({ label });
165
+ const input = part(node, 'input');
166
+ const list = part(node, 'blocks');
167
+ let items = [];
168
+ let editors = [];
169
+ let active = null;
170
+ let drawing = false;
171
+ let writing = false;
172
+ const write = () => {
173
+ input.value = joinBlocks(items);
174
+ writing = true;
175
+ input.dispatchEvent(new Event('input'));
176
+ writing = false;
177
+ };
178
+ function draw(focusAt) {
179
+ drawing = true;
180
+ editors = [];
181
+ const only = items.length === 1;
182
+ list.replaceChildren(
183
+ ...items.map((item, i) => {
184
+ if (item.type === 'image') {
185
+ const src = refSrc(item.ref);
186
+ const figure = ui.blockImage({
187
+ alt: item.alt,
188
+ src,
189
+ removeLabel: images?.removeLabel ?? '',
190
+ });
191
+ // 아직 받지 못한 올린 그림: 자리를 두고, 받으면 그 자리만 그림으로 (못 받으면 안내)
192
+ if (!src) {
193
+ const pending = assetBlock(item.ref, item.alt);
194
+ if (pending) figure.prepend(pending);
195
+ }
196
+ part(figure, 'block-remove').addEventListener('click', () => removeImage(i));
197
+ return figure;
198
+ }
199
+ // 안내 글은 글 칸이 하나뿐일 때만 (그림 사이 칸마다 보이지 않게)
200
+ const box = ui.blockText({ label, placeholder: only ? placeholder : '' });
201
+ const editor = richText(box, {
202
+ onChange: (markdown) => {
203
+ item.text = markdown;
204
+ write();
205
+ },
206
+ });
207
+ editor.set(item.text);
208
+ box.addEventListener('focus', () => (active = i));
209
+ editors[i] = editor;
210
+ return box;
211
+ }),
212
+ );
213
+ if (focusAt) editors[focusAt.index]?.focus(focusAt.end);
214
+ drawing = false;
215
+ }
216
+ function load(markdown) {
217
+ items = splitBlocks(markdown);
218
+ active = null;
219
+ draw();
220
+ }
221
+ // 그림 칸을 지우면 앞뒤 글 칸을 하나로
222
+ function removeImage(i) {
223
+ const before = input.value;
224
+ const prev = items[i - 1];
225
+ const next = items[i + 1];
226
+ const text = prev.text && next.text ? `${prev.text}\n\n${next.text}` : prev.text || next.text;
227
+ items.splice(i - 1, 3, { type: 'text', text });
228
+ write();
229
+ draw({ index: i - 1, end: true });
230
+ images?.onRemoved?.(() => {
231
+ input.value = before;
232
+ input.dispatchEvent(new Event('input'));
233
+ });
234
+ }
235
+ // 커서 자리(없으면 마지막 글 칸 끝)에서 글 칸을 나누고 그 사이에 그림 칸
236
+ function insertImage(ref) {
237
+ const at = active ?? items.findLastIndex((b) => b.type === 'text');
238
+ const { before, after } = editors[at].split();
239
+ items.splice(
240
+ at,
241
+ 1,
242
+ { type: 'text', text: before },
243
+ { type: 'image', alt: '', ref },
244
+ { type: 'text', text: after },
245
+ );
246
+ write();
247
+ draw({ index: at + 2, end: false });
248
+ }
249
+ input.value = value ?? '';
250
+ input.addEventListener('input', () => {
251
+ onInput(input.value);
252
+ // 바깥(되돌리기 · 비우고 닫기)에서 값을 바꿨으면 다시 그린다
253
+ if (!writing) load(input.value);
254
+ });
255
+ input.focus = () => editors.find(Boolean)?.focus();
256
+ node.addEventListener('focusout', (e) => {
257
+ if (drawing || node.rich.hold) return;
258
+ if (node.contains(e.relatedTarget) || node.contains(document.activeElement)) return;
259
+ input.dispatchEvent(new Event('blur'));
260
+ });
261
+ node.rich = {
262
+ active: () => editors[active] ?? editors.find(Boolean),
263
+ insert: insertImage,
264
+ /** 파일 고르기 창이 열린 동안은 칸을 벗어난 것으로 보지 않는다 */
265
+ hold: false,
266
+ };
267
+ load(input.value);
268
+ return node;
269
+ }
270
+
271
+ /** richField 아래 서식 도구 (굵게 · 기울임 · 취소선 · 목록 · 코드 · 그림) */
272
+ function formatTools(field, texts, images) {
273
+ const bar = ui.mdTools();
274
+ field.after(bar);
275
+ const editor = () => field.rich.active();
276
+ const pressed = {
277
+ 'md-bold': 'bold',
278
+ 'md-italic': 'italic',
279
+ 'md-strike': 'strike',
280
+ 'md-ul': 'ul',
281
+ 'md-ol': 'ol',
282
+ 'md-code': 'code',
283
+ };
284
+ const refresh = () => {
285
+ const state = editor()?.state() ?? {};
286
+ for (const [role, key] of Object.entries(pressed))
287
+ part(bar, role).setAttribute('aria-pressed', String(Boolean(state[key])));
288
+ // 코드 안에서는 다른 서식을 쓰지 않는다
289
+ for (const role of ['md-bold', 'md-italic', 'md-strike', 'md-ul', 'md-ol'])
290
+ part(bar, role).disabled = Boolean(state.code);
291
+ };
292
+ const bind = (role, run) => {
293
+ const button = part(bar, role);
294
+ // 눌러도 글 칸의 선택이 풀리지 않게
295
+ button.addEventListener('mousedown', (e) => e.preventDefault());
296
+ button.addEventListener('click', () => {
297
+ run(editor());
298
+ refresh();
299
+ });
300
+ };
301
+ bind('md-bold', (e) => e.bold());
302
+ bind('md-italic', (e) => e.italic());
303
+ bind('md-code', (e) => e.code(texts.codeSample));
304
+ bind('md-strike', (e) => e.strike());
305
+ bind('md-ul', (e) => e.list('ul'));
306
+ bind('md-ol', (e) => e.list('ol'));
307
+ for (const type of ['keyup', 'mouseup', 'focusin']) field.addEventListener(type, refresh);
308
+
309
+ const imageButton = part(bar, 'md-image');
310
+ if (!images) {
311
+ imageButton.hidden = true;
312
+ return;
313
+ }
314
+ const file = document.createElement('input');
315
+ file.type = 'file';
316
+ file.accept = 'image/*';
317
+ file.hidden = true;
318
+ bar.append(file);
319
+ imageButton.addEventListener('mousedown', (e) => e.preventDefault());
320
+ imageButton.addEventListener('click', () => {
321
+ // 파일 고르기 창이 닫히고 창이 초점을 되찾을 때까지 칸 · 도구를 열어 둔다
322
+ field.rich.hold = true;
323
+ bar.dataset.hold = '1';
324
+ window.addEventListener(
325
+ 'focus',
326
+ () =>
327
+ setTimeout(() => {
328
+ field.rich.hold = false;
329
+ delete bar.dataset.hold;
330
+ }, 600),
331
+ { once: true },
332
+ );
333
+ file.click();
334
+ });
335
+ file.addEventListener('change', async () => {
336
+ const picked = file.files?.[0];
337
+ file.value = '';
338
+ if (!picked) return;
339
+ imageButton.disabled = true;
340
+ imageButton.setAttribute('aria-busy', 'true');
341
+ imageButton.title = texts.imageBusy;
342
+ try {
343
+ field.rich.insert(await images.add(picked));
344
+ } catch (error) {
345
+ images.fail(error);
346
+ } finally {
347
+ imageButton.disabled = false;
348
+ imageButton.removeAttribute('aria-busy');
349
+ imageButton.title = texts.image;
350
+ }
351
+ });
352
+ }
353
+
354
+ /**
355
+ * 보기 · 그룹 목록 (단일 · 복수 · 순서 · 그룹 공통). 손잡이를 끌어 순서 바꾸기
356
+ * answer가 있으면 줄마다 정답 칸(data-role="answer")을 둔다: radio(단일) · checkbox(복수) · select(그룹 고르기).
357
+ * 정답 칸을 바꿔도 다시 그리지 않는다 (방향키로 radio를 옮기는 동안 초점이 그대로 있게)
358
+ * @param {'option' | 'group'} kind
359
+ * @param {object[]} items q.options 또는 q.groups (직접 고침)
360
+ * @param {string} key 키보드로 옮긴 뒤 초점을 찾을 이름 (화면에서 겹치지 않게)
361
+ * 정답으로 고른 줄에는 data-correct를 붙인다 (그룹은 그룹에 넣은 보기)
362
+ * @param {{ onAdd?: () => void, onDelete?: () => void, onInput?: (item: object) => void,
363
+ * snapshot?: () => (() => void), onRemoved?: (undo: () => void) => void,
364
+ * answer?: { type: 'radio' | 'checkbox' | 'select', name: string, choices?: [string, string][],
365
+ * get: (item: object) => boolean | string, set: (item: object, value: boolean | string) => void } }} [opts]
366
+ * onAdd: 추가한 뒤 할 일 (예: 순서 맞추기 칸 수 늘리기) ·
367
+ * onDelete: 지운 뒤 할 일 (예: 순서 맞추기 칸 수 줄이기, 정답에서 빼기) · onInput: 글을 고친 뒤 할 일 ·
368
+ * snapshot: 지우기 직전에 불러 되돌릴 함수를 받음 · onRemoved: 글이 있던 줄을 지운 뒤 (되돌리기 함수를 받아 알림)
369
+ */
370
+ function itemList(
371
+ kind,
372
+ items,
373
+ key,
374
+ { onAdd, onDelete, onInput, snapshot, onRemoved, answer, numbered = true } = {},
375
+ ) {
376
+ const isGroup = kind === 'group';
377
+ const text = isGroup ? 'name' : 'text';
378
+ const min = isGroup ? LIMITS.groupsMin : LIMITS.optionsMin;
379
+ const max = isGroup ? LIMITS.groupsMax : LIMITS.optionsMax;
380
+ const rows = items.map((item, i) => {
381
+ const row = ui.row({
382
+ kind,
383
+ index: i,
384
+ canDelete: items.length > min,
385
+ min,
386
+ numbered,
387
+ answer: answer && { type: answer.type, name: answer.name, choices: answer.choices },
388
+ });
389
+ row.dataset.role = 'row';
390
+ const input = part(row, 'input');
391
+ input.value = item[text];
392
+ input.addEventListener('input', () => {
393
+ item[text] = input.value;
394
+ onInput?.(item);
395
+ });
396
+ const pick = answer && part(row, 'answer');
397
+ if (pick) {
398
+ const value = answer.get(item);
399
+ if (answer.type === 'select') pick.value = String(value ?? '');
400
+ else pick.checked = Boolean(value);
401
+ pick.addEventListener('change', () => {
402
+ answer.set(item, answer.type === 'select' ? pick.value : pick.checked);
403
+ // radio는 다른 줄의 정답도 바뀌므로 줄마다 다시 표시
404
+ rows.forEach((r, j) => markCorrect(r, items[j]));
405
+ });
406
+ }
407
+ markCorrect(row, item);
408
+ // 글이 있던 줄을 지우면 onRemoved(되돌리기): 같은 자리에 다시 넣고 snapshot()이 돌려준 복원도 부른다 (정답 등)
409
+ part(row, 'delete').addEventListener('click', () => {
410
+ const restore = snapshot?.();
411
+ const [removed] = items.splice(i, 1);
412
+ onDelete?.();
413
+ rerender();
414
+ if (!(removed.text ?? removed.name ?? '').trim()) return;
415
+ onRemoved?.(() => {
416
+ items.splice(i, 0, removed);
417
+ restore?.();
418
+ rerender();
419
+ });
420
+ });
421
+ sortHandle(part(row, 'handle'), items, i, key);
422
+ return row;
423
+ });
424
+ function markCorrect(row, item) {
425
+ if (answer) row.toggleAttribute('data-correct', Boolean(answer.get(item)));
426
+ }
427
+ const full = items.length >= max;
428
+ const add = ui.addButton({ kind, full, max });
429
+ add.addEventListener('click', () => {
430
+ const ids = items.map((x) => x.id);
431
+ items.push(
432
+ isGroup
433
+ ? {
434
+ id: nextId(ids, 'g'),
435
+ name: labels.group(String.fromCharCode(65 + items.length)),
436
+ }
437
+ : { id: nextId(ids), text: '' },
438
+ );
439
+ onAdd?.();
440
+ rerender();
441
+ });
442
+ // 정답 칸이 있으면 목록 위에 "정답" 열 머리 · 최소 개수라 지울 수 없으면 목록 아래 안내
443
+ return ui.list({ kind, rows, add, answer: answer?.type, atMin: items.length <= min, min });
444
+ }
445
+
446
+ /** list[from]을 to 자리로 옮기고 다시 그린 뒤, 키보드로 옮겼으면 옮긴 손잡이에 초점을 둔다 */
447
+ function moveTo(list, from, to, key, refocus) {
448
+ if (to === from || to < 0 || to >= list.length) return;
449
+ const [item] = list.splice(from, 1);
450
+ list.splice(to, 0, item);
451
+ rerender();
452
+ if (refocus) root.querySelector(`[data-sort="${key}:${to}"]`)?.focus();
453
+ }
454
+
455
+ /**
456
+ * 끌어서 순서 바꾸는 손잡이 (마우스 · 터치 공용 Pointer Events). 끄는 동안 다른 줄이 비켜 자리를 보여 준다.
457
+ * 키보드: 손잡이에서 ↑ · ↓. 끄는 줄에는 data-dragging이 붙는다 (styles.css).
458
+ */
459
+ function sortHandle(handle, list, i, key) {
460
+ handle.dataset.sort = `${key}:${i}`;
461
+ handle.addEventListener('keydown', (e) => {
462
+ const d = { ArrowUp: -1, ArrowDown: 1 }[e.key];
463
+ if (!d) return;
464
+ e.preventDefault();
465
+ moveTo(list, i, i + d, key, true);
466
+ });
467
+ handle.addEventListener('pointerdown', (down) => {
468
+ if (down.button !== 0) return;
469
+ down.preventDefault();
470
+ const row = handle.closest('[data-role="row"]');
471
+ const rows = [...row.parentElement.querySelectorAll(':scope > [data-role="row"]')];
472
+ const rects = rows.map((r) => r.getBoundingClientRect());
473
+ const step = rects.length > 1 ? Math.abs(rects[1].top - rects[0].top) : rects[0].height;
474
+ handle.setPointerCapture(down.pointerId);
475
+ row.dataset.dragging = '';
476
+ let to = i;
477
+ const onMove = (e) => {
478
+ const dy = e.clientY - down.clientY;
479
+ row.style.transform = `translateY(${dy}px)`;
480
+ const center = rects[i].top + rects[i].height / 2 + dy;
481
+ to = rects.filter((r, j) => j !== i && r.top + r.height / 2 < center).length;
482
+ rows.forEach((r, j) => {
483
+ if (j === i) return;
484
+ const shift = j > i && j <= to ? -step : j < i && j >= to ? step : 0;
485
+ r.style.transform = shift ? `translateY(${shift}px)` : '';
486
+ });
487
+ };
488
+ const end = (e) => {
489
+ handle.removeEventListener('pointermove', onMove);
490
+ handle.removeEventListener('pointerup', end);
491
+ handle.removeEventListener('pointercancel', end);
492
+ delete row.dataset.dragging;
493
+ for (const r of rows) r.style.transform = '';
494
+ if (e.type === 'pointerup') moveTo(list, i, to, key, false);
495
+ };
496
+ handle.addEventListener('pointermove', onMove);
497
+ handle.addEventListener('pointerup', end);
498
+ handle.addEventListener('pointercancel', end);
499
+ });
500
+ }
501
+
502
+ /**
503
+ * 상자 사이로 끌어 옮기는 손잡이 (마우스 · 터치 공용 Pointer Events). 끄는 동안 놓을 수 있는 상자에 data-over가 붙고,
504
+ * 놓으면 onDrop(상자, 그 앞에 둘 행 또는 null). 키보드: 손잡이에서 ↑ · ↓ → onKey(-1 | 1)
505
+ * @param {Element} handle 끌기 손잡이
506
+ * @param {Element} row 옮기는 행 (끄는 동안 data-dragging)
507
+ * @param {{ boxSelector: string, onDrop: (box: Element, before: Element | null) => void, onKey: (dir: -1 | 1) => void }} on
508
+ */
509
+ function dragAcross(handle, row, { boxSelector, onDrop, onKey }) {
510
+ handle.addEventListener('keydown', (e) => {
511
+ const d = { ArrowUp: -1, ArrowDown: 1 }[e.key];
512
+ if (!d) return;
513
+ e.preventDefault();
514
+ onKey(d);
515
+ });
516
+ handle.addEventListener('pointerdown', (down) => {
517
+ if (down.button !== 0) return;
518
+ down.preventDefault();
519
+ handle.setPointerCapture(down.pointerId);
520
+ row.dataset.dragging = '';
521
+ let over = null;
522
+ const boxAt = (e) => {
523
+ const hit = document.elementsFromPoint(e.clientX, e.clientY).find((el) => !row.contains(el));
524
+ return hit?.closest(boxSelector) ?? null;
525
+ };
526
+ const onMove = (e) => {
527
+ row.style.transform = `translate(${e.clientX - down.clientX}px, ${e.clientY - down.clientY}px)`;
528
+ const box = boxAt(e);
529
+ if (box === over) return;
530
+ over?.removeAttribute('data-over');
531
+ over = box;
532
+ over?.setAttribute('data-over', '');
533
+ };
534
+ const end = (e) => {
535
+ handle.removeEventListener('pointermove', onMove);
536
+ handle.removeEventListener('pointerup', end);
537
+ handle.removeEventListener('pointercancel', end);
538
+ delete row.dataset.dragging;
539
+ row.style.transform = '';
540
+ over?.removeAttribute('data-over');
541
+ if (e.type !== 'pointerup' || !over) return;
542
+ const rows = [...over.querySelectorAll('[data-role="row"]')].filter((r) => r !== row);
543
+ const before = rows.find((r) => {
544
+ const b = r.getBoundingClientRect();
545
+ return e.clientY < b.top + b.height / 2;
546
+ });
547
+ onDrop(over, before ?? null);
548
+ };
549
+ handle.addEventListener('pointermove', onMove);
550
+ handle.addEventListener('pointerup', end);
551
+ handle.addEventListener('pointercancel', end);
552
+ });
553
+ }
554
+
555
+ /**
556
+ * 문항 카드: 유형 바꾸기 · 위로 · 아래로 · 삭제를 붙인다. on: { type(값), up(), down(), remove() }
557
+ */
558
+ /** 열린 유형 목록 하나 ({ button, close }) */
559
+ let menu = null;
560
+ function closeMenu() {
561
+ menu?.close();
562
+ menu = null;
563
+ }
564
+
565
+ function card(props, on) {
566
+ const node = ui.card(props);
567
+ node.dataset.role = 'card';
568
+ node.dataset.index = String(props.index);
569
+ const type = part(node, 'type');
570
+ if (type.tagName === 'SELECT') type.addEventListener('change', () => on.type(type.value));
571
+ else {
572
+ // 유형 버튼 → 목록 (ui.typeMenu). 고르면 on.type, 다시 그린 뒤 같은 카드의 유형 버튼으로 초점을 돌린다
573
+ const choose = (value) => {
574
+ if (value !== props.q.type) on.type(value);
575
+ cardAt(props.index)?.querySelector('[data-role="type"]')?.focus();
576
+ };
577
+ const open = () => openMenu(type, props.types, props.q.type, choose);
578
+ type.addEventListener('click', open);
579
+ type.addEventListener('keydown', (e) => {
580
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
581
+ e.preventDefault();
582
+ open();
583
+ });
584
+ }
585
+ part(node, 'up').addEventListener('click', on.up);
586
+ part(node, 'down').addEventListener('click', on.down);
587
+ part(node, 'delete').addEventListener('click', on.remove);
588
+ return node;
589
+ }
590
+
591
+ /**
592
+ * 유형 목록 열기 (listbox · option, 고른 항목에 초점). 버튼을 다시 누르면 닫힘.
593
+ * ↑ · ↓ · Home · End 이동, Enter · Space 고르기, Esc 닫고 버튼으로 초점, Tab · 바깥 누르기 · 스크롤 · 창 크기 바꾸기는 닫기
594
+ */
595
+ function openMenu(button, types, value, choose) {
596
+ if (menu?.button === button) return closeMenu();
597
+ closeMenu();
598
+ const list = ui.typeMenu({
599
+ label: button.getAttribute('aria-label') ?? '',
600
+ types,
601
+ value,
602
+ });
603
+ const items = [...list.querySelectorAll('[role="option"]')];
604
+ document.body.append(list);
605
+ button.setAttribute('aria-expanded', 'true');
606
+ // 버튼 아래(자리가 없으면 위)에, 화면 밖으로 나가지 않게
607
+ const r = button.getBoundingClientRect();
608
+ list.style.minWidth = `${Math.max(r.width, 160)}px`;
609
+ const below = window.innerHeight - r.bottom;
610
+ const top = below >= list.offsetHeight + 8 || below >= r.top ? r.bottom + 4 : r.top - list.offsetHeight - 4;
611
+ list.style.top = `${Math.max(8, top)}px`;
612
+ list.style.left = `${Math.max(8, Math.min(r.left, window.innerWidth - list.offsetWidth - 8))}px`;
613
+
614
+ let at = Math.max(0, items.findIndex((i) => i.dataset.value === value));
615
+ const focusAt = (i) => {
616
+ at = (i + items.length) % items.length;
617
+ items[at].focus({ preventScroll: true });
618
+ };
619
+ const pick = (value) => {
620
+ closeMenu();
621
+ choose(value);
622
+ };
623
+ const keys = {
624
+ ArrowDown: () => focusAt(at + 1),
625
+ ArrowUp: () => focusAt(at - 1),
626
+ Home: () => focusAt(0),
627
+ End: () => focusAt(items.length - 1),
628
+ Enter: () => pick(items[at].dataset.value),
629
+ ' ': () => pick(items[at].dataset.value),
630
+ Escape: () => {
631
+ closeMenu();
632
+ button.focus();
633
+ },
634
+ };
635
+ const onKey = (e) => {
636
+ if (e.key === 'Tab') return closeMenu();
637
+ const run = keys[e.key];
638
+ if (!run) return;
639
+ e.preventDefault();
640
+ run();
641
+ };
642
+ const onOutside = (e) => {
643
+ if (!list.contains(e.target) && !button.contains(e.target)) closeMenu();
644
+ };
645
+ const onMove = (e) => {
646
+ if (!list.contains(e.target)) closeMenu();
647
+ };
648
+ items.forEach((item, i) =>
649
+ item.addEventListener('click', () => {
650
+ at = i;
651
+ pick(item.dataset.value);
652
+ }),
653
+ );
654
+ list.addEventListener('keydown', onKey);
655
+ document.addEventListener('pointerdown', onOutside, true);
656
+ window.addEventListener('scroll', onMove, true);
657
+ window.addEventListener('resize', closeMenu);
658
+ menu = {
659
+ button,
660
+ close() {
661
+ list.remove();
662
+ button.setAttribute('aria-expanded', 'false');
663
+ document.removeEventListener('pointerdown', onOutside, true);
664
+ window.removeEventListener('scroll', onMove, true);
665
+ window.removeEventListener('resize', closeMenu);
666
+ },
667
+ };
668
+ focusAt(at);
669
+ }
670
+
671
+ /**
672
+ * 버튼 하나에 고르기 목록을 붙인다 (유형 버튼과 같은 목록 ui.typeMenu, 척도 시작값 · 끝값 고르기 등).
673
+ * choices: [[값, 이름], …] · value(): 지금 값 · choose(값): 다른 값을 골랐을 때
674
+ */
675
+ function picker(button, choices, value, choose) {
676
+ const open = () =>
677
+ openMenu(button, choices, value(), (v) => {
678
+ if (v !== value()) choose(v);
679
+ });
680
+ button.addEventListener('click', open);
681
+ button.addEventListener('keydown', (e) => {
682
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
683
+ e.preventDefault();
684
+ open();
685
+ });
686
+ return button;
687
+ }
688
+
689
+ /** 문항 추가 버튼 */
690
+ function addQuestion(onClick) {
691
+ const node = ui.addQuestion();
692
+ node.addEventListener('click', onClick);
693
+ return node;
694
+ }
695
+
696
+ /** index번째 문항 카드 */
697
+ function cardAt(index) {
698
+ return parts(root, 'card').find((c) => c.dataset.index === String(index));
699
+ }
700
+
701
+ return {
702
+ ui,
703
+ field,
704
+ inlineField,
705
+ richField,
706
+ markEmptyRequired,
707
+ numberField,
708
+ toggle,
709
+ revealable,
710
+ itemList,
711
+ dragAcross,
712
+ card,
713
+ picker,
714
+ /** richField 아래 서식 도구 (늘 열린 칸에: 설문 안내) */
715
+ formatTools,
716
+ addQuestion,
717
+ /** 검증에 걸린 문항 카드 */
718
+ cardAt,
719
+ };
720
+ }