@eliceio/cdk-cli 1.2.1 → 1.3.0-contenttypes.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 (104) hide show
  1. package/README.md +59 -50
  2. package/es/cli.js +11 -2
  3. package/es/commands/build/index.js +12 -0
  4. package/es/commands/create/index.js +1 -0
  5. package/es/commands/create/scaffold.d.ts +2 -2
  6. package/es/commands/create/scaffold.js +3 -3
  7. package/es/commands/dev/index.d.ts +10 -1
  8. package/es/commands/dev/index.js +47 -7
  9. package/es/core/config.d.ts +20 -9
  10. package/es/core/config.js +53 -12
  11. package/es/core/project-check.d.ts +3 -2
  12. package/es/core/project-check.js +14 -3
  13. package/es/core/regex.d.ts +11 -0
  14. package/es/core/regex.js +41 -0
  15. package/es/core/sandbox.d.ts +26 -0
  16. package/es/core/sandbox.js +240 -30
  17. package/es/dev/check.d.ts +30 -0
  18. package/es/dev/check.js +224 -34
  19. package/es/dev/grading.d.ts +20 -1
  20. package/es/dev/grading.js +38 -7
  21. package/es/dev/host-page.js +1 -1
  22. package/es/dev/mock-api.d.ts +3 -1
  23. package/es/dev/mock-api.js +20 -11
  24. package/es/engines/vite/index.js +1 -1
  25. package/es/engines/vite/plugin.d.ts +2 -0
  26. package/es/engines/vite/plugin.js +33 -5
  27. package/es/rules/answers.d.ts +13 -0
  28. package/es/rules/answers.js +94 -0
  29. package/es/rules/check.js +70 -1
  30. package/es/rules/index.d.ts +1 -0
  31. package/es/rules/index.js +1 -0
  32. package/es/rules/size.d.ts +31 -0
  33. package/es/rules/size.js +58 -0
  34. package/es/rules/types.d.ts +12 -0
  35. package/es/rules.json.js +2 -2
  36. package/package.json +2 -2
  37. package/rules.json +32 -3
  38. package/skills/_shared/always.md +3 -3
  39. package/skills/_shared/references/00-what-the-person-decides.md +1 -1
  40. package/skills/_shared/references/02-design-the-material.md +10 -7
  41. package/skills/_shared/references/03-create-the-project.md +2 -1
  42. package/skills/_shared/references/05-screen-code.md +49 -22
  43. package/skills/_shared/references/06-using-the-quiz-template.md +7 -6
  44. package/skills/_shared/references/08-fix-check-errors.md +23 -22
  45. package/skills/_shared/references/09-check.md +7 -6
  46. package/skills/_shared/references/12-upload-with-the-material-mcp.md +13 -13
  47. package/skills/_shared/references/13-edit-screen-design.md +122 -0
  48. package/skills/_shared/references/14-layouts.md +96 -0
  49. package/skills/elice-content-check/SKILL.md +2 -2
  50. package/skills/elice-content-create/SKILL.md +1 -1
  51. package/skills/elice-content-migrate/SKILL.md +1 -1
  52. package/templates/_shared/lib/cdk-mock.d.ts +30 -3
  53. package/templates/_shared/lib/cdk-mock.js +88 -15
  54. package/templates/_shared/lib/elice-content-editor.js +89 -58
  55. package/templates/_shared/lib/elice-content.css +1313 -126
  56. package/templates/_shared/lib/elice-content.d.ts +162 -23
  57. package/templates/_shared/lib/elice-content.js +863 -82
  58. package/templates/_shared/lib/icons/empty-content.d.ts +2 -0
  59. package/templates/_shared/lib/icons/empty-content.js +11 -0
  60. package/templates/_shared/lib/icons/file-video.d.ts +2 -0
  61. package/templates/_shared/lib/icons/file-video.js +11 -0
  62. package/templates/_shared/lib/icons/file.d.ts +2 -0
  63. package/templates/_shared/lib/icons/file.js +11 -0
  64. package/templates/blank/README.md +5 -3
  65. package/templates/blank/edit.html +8 -2
  66. package/templates/blank/index.html +6 -1
  67. package/templates/blank/instructor.html +6 -1
  68. package/templates/blank/template.json +1 -1
  69. package/templates/quiz/README.md +28 -12
  70. package/templates/quiz/core/behaviors.d.ts +13 -7
  71. package/templates/quiz/core/behaviors.js +36 -51
  72. package/templates/quiz/core/editor.d.ts +10 -0
  73. package/templates/quiz/core/editor.js +334 -8
  74. package/templates/quiz/core/markdown.d.ts +4 -0
  75. package/templates/quiz/core/markdown.js +65 -11
  76. package/templates/quiz/core/model.d.ts +34 -1
  77. package/templates/quiz/core/model.js +86 -5
  78. package/templates/quiz/core/rich-text.d.ts +19 -0
  79. package/templates/quiz/core/rich-text.js +521 -0
  80. package/templates/quiz/edit.html +12 -3
  81. package/templates/quiz/index.html +12 -3
  82. package/templates/quiz/screens/edit.js +217 -48
  83. package/templates/quiz/screens/learn.js +90 -14
  84. package/templates/quiz/styles.css +840 -678
  85. package/templates/quiz/template.json +9 -2
  86. package/templates/quiz/ui/templates/edit.d.ts +18 -5
  87. package/templates/quiz/ui/templates/edit.js +309 -71
  88. package/templates/quiz/ui/templates/group.js +19 -8
  89. package/templates/quiz/ui/templates/order.js +25 -24
  90. package/templates/quiz/ui/templates/page.js +19 -8
  91. package/templates/quiz/ui/templates/question.js +2 -2
  92. package/templates/quiz/ui/texts.js +72 -25
  93. package/templates/quiz/ui/theme.css +8 -9
  94. package/templates/steps/README.md +77 -0
  95. package/templates/steps/commentary.txt +7 -0
  96. package/templates/steps/edit.html +21 -0
  97. package/templates/steps/gitignore +4 -0
  98. package/templates/steps/index.html +69 -0
  99. package/templates/steps/metadata.json +9 -0
  100. package/templates/steps/package.json +13 -0
  101. package/templates/steps/screens/edit.js +32 -0
  102. package/templates/steps/screens/learn.js +108 -0
  103. package/templates/steps/styles.css +54 -0
  104. package/templates/steps/template.json +6 -0
@@ -2,7 +2,9 @@
2
2
  // 마크업은 ui/templates/edit.js가 만들고, 여기서는 data-role로만 요소를 찾는다.
3
3
  // ui/를 직접 불러오지 않는다: 템플릿과 문구는 화면(screens/edit.js)이 넘겨 준다.
4
4
  import { part, parts } from './dom.js';
5
+ import { imageSrc } from './markdown.js';
5
6
  import { LIMITS, nextId } from './model.js';
7
+ import { joinBlocks, richText, splitBlocks } from './rich-text.js';
6
8
 
7
9
  /**
8
10
  * 편집 폼 도우미. rerender: 데이터를 바꾼 뒤 폼을 다시 그리는 함수 · root: 폼이 놓인 요소(키보드로 옮긴 뒤 초점 찾기)
@@ -94,14 +96,22 @@ export function createEditor({ rerender, root, templates, labels }) {
94
96
  * 비운 채 칸을 벗어나면 다시 닫는다. 여닫는 것만으로는 다시 그리거나 "변경" 표시를 만들지 않는다
95
97
  * @param {string} label 열기 버튼 글
96
98
  * @param {Element} node 칸 (inlineField가 만든 요소)
97
- * @param {{ open?: boolean, onOpen?: () => void, onClose?: () => void, title?: string, icon?: string, hint?: string }} [opts]
98
- * title가 있으면 열린 칸을 머리줄(아이콘 · 제목 · 지우기)이 있는 카드로 보인다
99
+ * @param {{ open?: boolean, onOpen?: () => void, onClose?: () => void, title?: string, icon?: string, hint?: string,
100
+ * tools?: object, images?: { add: (file: File) => Promise<string>, fail: (error: Error & { code?: string }) => void } }} [opts]
101
+ * title가 있으면 열린 칸을 머리줄(아이콘 · 제목 · 지우기)이 있는 카드로 보인다.
102
+ * tools(서식 도구 문구 texts.edit.md)를 주면 richField 칸에 서식 도구를 붙이고, images도 주면 그림 올리기 버튼을 보인다
99
103
  */
100
- function revealable(label, node, { open = false, onOpen, onClose, title, icon, hint } = {}) {
104
+ function revealable(
105
+ label,
106
+ node,
107
+ { open = false, onOpen, onClose, onRemoved, title, icon, hint, tools, images } = {},
108
+ ) {
101
109
  const wrap = ui.reveal({ label, field: node, title, icon, hint });
102
110
  const button = part(wrap, 'reveal');
103
111
  const body = part(wrap, 'reveal-body');
104
112
  const input = part(node, 'input');
113
+ // 서식 도구: richField 칸 아래에 (칸에 초점이 있을 때만 보임)
114
+ if (tools) formatTools(node, tools, images);
105
115
  const fit = () => {
106
116
  if (input.tagName !== 'TEXTAREA') return;
107
117
  input.style.height = 'auto';
@@ -128,18 +138,212 @@ export function createEditor({ rerender, root, templates, labels }) {
128
138
  onClose?.();
129
139
  });
130
140
  // 내용이 있어도 지우고 닫는다 (비우는 입력을 흘려 보내 데이터에도 반영)
141
+ // 글이 있었으면 onRemoved(지운 글) — 화면이 되돌리기 알림을 띄운다
131
142
  part(wrap, 'reveal-close').addEventListener('click', () => {
143
+ const removed = input.value;
132
144
  input.value = '';
133
145
  input.dispatchEvent(new Event('input', { bubbles: true }));
134
146
  hide();
135
147
  onClose?.();
136
148
  button.focus();
149
+ if (removed.trim()) onRemoved?.(removed);
137
150
  });
138
151
  if (open) button.hidden = true;
139
152
  else body.hidden = true;
140
153
  return wrap;
141
154
  }
142
155
 
156
+ /**
157
+ * 지문 · 해설 칸: 보이는 그대로 고치는 글 칸(core/rich-text.js)과 올린 그림 칸이 차례로 놓인다. 값은 마크다운.
158
+ * 숨은 textarea(data-role="input")가 값을 들고 있어 revealable이 다른 칸처럼 다룬다 (비우고 닫기 · 칸을 벗어나면 blur)
159
+ * @param {{ placeholder?: string, images?: { removeLabel: string, onRemoved?: (undo: () => void) => void } }} [opts]
160
+ * images.onRemoved: 그림 칸을 지운 뒤 (되돌리기 함수를 받아 알림)
161
+ */
162
+ function richField(label, value, onInput, { placeholder, images } = {}) {
163
+ const node = ui.richField({ label });
164
+ const input = part(node, 'input');
165
+ const list = part(node, 'blocks');
166
+ let items = [];
167
+ let editors = [];
168
+ let active = null;
169
+ let drawing = false;
170
+ let writing = false;
171
+ const write = () => {
172
+ input.value = joinBlocks(items);
173
+ writing = true;
174
+ input.dispatchEvent(new Event('input'));
175
+ writing = false;
176
+ };
177
+ function draw(focusAt) {
178
+ drawing = true;
179
+ editors = [];
180
+ const only = items.length === 1;
181
+ list.replaceChildren(
182
+ ...items.map((item, i) => {
183
+ if (item.type === 'image') {
184
+ const figure = ui.blockImage({
185
+ alt: item.alt,
186
+ src: imageSrc(item.id),
187
+ removeLabel: images?.removeLabel ?? '',
188
+ });
189
+ part(figure, 'block-remove').addEventListener('click', () => removeImage(i));
190
+ return figure;
191
+ }
192
+ // 안내 글은 글 칸이 하나뿐일 때만 (그림 사이 칸마다 보이지 않게)
193
+ const box = ui.blockText({ label, placeholder: only ? placeholder : '' });
194
+ const editor = richText(box, {
195
+ onChange: (markdown) => {
196
+ item.text = markdown;
197
+ write();
198
+ },
199
+ });
200
+ editor.set(item.text);
201
+ box.addEventListener('focus', () => (active = i));
202
+ editors[i] = editor;
203
+ return box;
204
+ }),
205
+ );
206
+ if (focusAt) editors[focusAt.index]?.focus(focusAt.end);
207
+ drawing = false;
208
+ }
209
+ function load(markdown) {
210
+ items = splitBlocks(markdown);
211
+ active = null;
212
+ draw();
213
+ }
214
+ // 그림 칸을 지우면 앞뒤 글 칸을 하나로
215
+ function removeImage(i) {
216
+ const before = input.value;
217
+ const prev = items[i - 1];
218
+ const next = items[i + 1];
219
+ const text = prev.text && next.text ? `${prev.text}\n\n${next.text}` : prev.text || next.text;
220
+ items.splice(i - 1, 3, { type: 'text', text });
221
+ write();
222
+ draw({ index: i - 1, end: true });
223
+ images?.onRemoved?.(() => {
224
+ input.value = before;
225
+ input.dispatchEvent(new Event('input'));
226
+ });
227
+ }
228
+ // 커서 자리(없으면 마지막 글 칸 끝)에서 글 칸을 나누고 그 사이에 그림 칸
229
+ function insertImage(id) {
230
+ const at = active ?? items.findLastIndex((b) => b.type === 'text');
231
+ const { before, after } = editors[at].split();
232
+ items.splice(
233
+ at,
234
+ 1,
235
+ { type: 'text', text: before },
236
+ { type: 'image', alt: '', id },
237
+ { type: 'text', text: after },
238
+ );
239
+ write();
240
+ draw({ index: at + 2, end: false });
241
+ }
242
+ input.value = value ?? '';
243
+ input.addEventListener('input', () => {
244
+ onInput(input.value);
245
+ // 바깥(되돌리기 · 비우고 닫기)에서 값을 바꿨으면 다시 그린다
246
+ if (!writing) load(input.value);
247
+ });
248
+ input.focus = () => editors.find(Boolean)?.focus();
249
+ node.addEventListener('focusout', (e) => {
250
+ if (drawing || node.rich.hold) return;
251
+ if (node.contains(e.relatedTarget) || node.contains(document.activeElement)) return;
252
+ input.dispatchEvent(new Event('blur'));
253
+ });
254
+ node.rich = {
255
+ active: () => editors[active] ?? editors.find(Boolean),
256
+ insert: insertImage,
257
+ /** 파일 고르기 창이 열린 동안은 칸을 벗어난 것으로 보지 않는다 */
258
+ hold: false,
259
+ };
260
+ load(input.value);
261
+ return node;
262
+ }
263
+
264
+ /** richField 아래 서식 도구 (굵게 · 기울임 · 취소선 · 목록 · 코드 · 그림) */
265
+ function formatTools(field, texts, images) {
266
+ const bar = ui.mdTools();
267
+ field.after(bar);
268
+ const editor = () => field.rich.active();
269
+ const pressed = {
270
+ 'md-bold': 'bold',
271
+ 'md-italic': 'italic',
272
+ 'md-strike': 'strike',
273
+ 'md-ul': 'ul',
274
+ 'md-ol': 'ol',
275
+ 'md-code': 'code',
276
+ };
277
+ const refresh = () => {
278
+ const state = editor()?.state() ?? {};
279
+ for (const [role, key] of Object.entries(pressed))
280
+ part(bar, role).setAttribute('aria-pressed', String(Boolean(state[key])));
281
+ // 코드 안에서는 다른 서식을 쓰지 않는다
282
+ for (const role of ['md-bold', 'md-italic', 'md-strike', 'md-ul', 'md-ol'])
283
+ part(bar, role).disabled = Boolean(state.code);
284
+ };
285
+ const bind = (role, run) => {
286
+ const button = part(bar, role);
287
+ // 눌러도 글 칸의 선택이 풀리지 않게
288
+ button.addEventListener('mousedown', (e) => e.preventDefault());
289
+ button.addEventListener('click', () => {
290
+ run(editor());
291
+ refresh();
292
+ });
293
+ };
294
+ bind('md-bold', (e) => e.bold());
295
+ bind('md-italic', (e) => e.italic());
296
+ bind('md-code', (e) => e.code(texts.codeSample));
297
+ bind('md-strike', (e) => e.strike());
298
+ bind('md-ul', (e) => e.list('ul'));
299
+ bind('md-ol', (e) => e.list('ol'));
300
+ for (const type of ['keyup', 'mouseup', 'focusin']) field.addEventListener(type, refresh);
301
+
302
+ const imageButton = part(bar, 'md-image');
303
+ if (!images) {
304
+ imageButton.hidden = true;
305
+ return;
306
+ }
307
+ const file = document.createElement('input');
308
+ file.type = 'file';
309
+ file.accept = 'image/*';
310
+ file.hidden = true;
311
+ bar.append(file);
312
+ imageButton.addEventListener('mousedown', (e) => e.preventDefault());
313
+ imageButton.addEventListener('click', () => {
314
+ // 파일 고르기 창이 닫히고 창이 초점을 되찾을 때까지 칸 · 도구를 열어 둔다
315
+ field.rich.hold = true;
316
+ bar.dataset.hold = '1';
317
+ window.addEventListener(
318
+ 'focus',
319
+ () =>
320
+ setTimeout(() => {
321
+ field.rich.hold = false;
322
+ delete bar.dataset.hold;
323
+ }, 600),
324
+ { once: true },
325
+ );
326
+ file.click();
327
+ });
328
+ file.addEventListener('change', async () => {
329
+ const picked = file.files?.[0];
330
+ file.value = '';
331
+ if (!picked) return;
332
+ imageButton.disabled = true;
333
+ imageButton.setAttribute('aria-busy', 'true');
334
+ imageButton.title = texts.imageBusy;
335
+ try {
336
+ field.rich.insert(await images.add(picked));
337
+ } catch (error) {
338
+ images.fail(error);
339
+ } finally {
340
+ imageButton.disabled = false;
341
+ imageButton.removeAttribute('aria-busy');
342
+ imageButton.title = texts.image;
343
+ }
344
+ });
345
+ }
346
+
143
347
  /**
144
348
  * 보기 · 그룹 목록 (단일 · 복수 · 순서 · 그룹 공통). 손잡이를 끌어 순서 바꾸기
145
349
  * answer가 있으면 줄마다 정답 칸(data-role="answer")을 둔다: radio(단일) · checkbox(복수) · select(그룹 고르기).
@@ -149,12 +353,19 @@ export function createEditor({ rerender, root, templates, labels }) {
149
353
  * @param {string} key 키보드로 옮긴 뒤 초점을 찾을 이름 (화면에서 겹치지 않게)
150
354
  * 정답으로 고른 줄에는 data-correct를 붙인다 (그룹은 그룹에 넣은 보기)
151
355
  * @param {{ onAdd?: () => void, onDelete?: () => void, onInput?: (item: object) => void,
356
+ * snapshot?: () => (() => void), onRemoved?: (undo: () => void) => void,
152
357
  * answer?: { type: 'radio' | 'checkbox' | 'select', name: string, choices?: [string, string][],
153
358
  * get: (item: object) => boolean | string, set: (item: object, value: boolean | string) => void } }} [opts]
154
359
  * onAdd: 추가한 뒤 할 일 (예: 순서 맞추기 칸 수 늘리기) ·
155
- * onDelete: 지운 뒤 할 일 (예: 순서 맞추기 칸 수 줄이기, 정답에서 빼기) · onInput: 글을 고친 뒤 할 일
360
+ * onDelete: 지운 뒤 할 일 (예: 순서 맞추기 칸 수 줄이기, 정답에서 빼기) · onInput: 글을 고친 뒤 할 일 ·
361
+ * snapshot: 지우기 직전에 불러 되돌릴 함수를 받음 · onRemoved: 글이 있던 줄을 지운 뒤 (되돌리기 함수를 받아 알림)
156
362
  */
157
- function itemList(kind, items, key, { onAdd, onDelete, onInput, answer, numbered = true } = {}) {
363
+ function itemList(
364
+ kind,
365
+ items,
366
+ key,
367
+ { onAdd, onDelete, onInput, snapshot, onRemoved, answer, numbered = true } = {},
368
+ ) {
158
369
  const isGroup = kind === 'group';
159
370
  const text = isGroup ? 'name' : 'text';
160
371
  const min = isGroup ? LIMITS.groupsMin : LIMITS.optionsMin;
@@ -187,10 +398,18 @@ export function createEditor({ rerender, root, templates, labels }) {
187
398
  });
188
399
  }
189
400
  markCorrect(row, item);
401
+ // 글이 있던 줄을 지우면 onRemoved(되돌리기): 같은 자리에 다시 넣고 snapshot()이 돌려준 복원도 부른다 (정답 등)
190
402
  part(row, 'delete').addEventListener('click', () => {
191
- items.splice(i, 1);
403
+ const restore = snapshot?.();
404
+ const [removed] = items.splice(i, 1);
192
405
  onDelete?.();
193
406
  rerender();
407
+ if (!(removed.text ?? removed.name ?? '').trim()) return;
408
+ onRemoved?.(() => {
409
+ items.splice(i, 0, removed);
410
+ restore?.();
411
+ rerender();
412
+ });
194
413
  });
195
414
  sortHandle(part(row, 'handle'), items, i, key);
196
415
  return row;
@@ -329,18 +548,119 @@ export function createEditor({ rerender, root, templates, labels }) {
329
548
  /**
330
549
  * 문항 카드: 유형 바꾸기 · 위로 · 아래로 · 삭제를 붙인다. on: { type(값), up(), down(), remove() }
331
550
  */
551
+ /** 열린 유형 목록 하나 ({ button, close }) */
552
+ let menu = null;
553
+ function closeMenu() {
554
+ menu?.close();
555
+ menu = null;
556
+ }
557
+
332
558
  function card(props, on) {
333
559
  const node = ui.card(props);
334
560
  node.dataset.role = 'card';
335
561
  node.dataset.index = String(props.index);
336
562
  const type = part(node, 'type');
337
- type.addEventListener('change', () => on.type(type.value));
563
+ if (type.tagName === 'SELECT') type.addEventListener('change', () => on.type(type.value));
564
+ else {
565
+ // 유형 버튼 → 목록 (ui.typeMenu). 고르면 on.type, 다시 그린 뒤 같은 카드의 유형 버튼으로 초점을 돌린다
566
+ const choose = (value) => {
567
+ if (value !== props.q.type) on.type(value);
568
+ cardAt(props.index)?.querySelector('[data-role="type"]')?.focus();
569
+ };
570
+ const open = () => openMenu(type, props, choose);
571
+ type.addEventListener('click', open);
572
+ type.addEventListener('keydown', (e) => {
573
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
574
+ e.preventDefault();
575
+ open();
576
+ });
577
+ }
338
578
  part(node, 'up').addEventListener('click', on.up);
339
579
  part(node, 'down').addEventListener('click', on.down);
340
580
  part(node, 'delete').addEventListener('click', on.remove);
341
581
  return node;
342
582
  }
343
583
 
584
+ /**
585
+ * 유형 목록 열기 (listbox · option, 고른 항목에 초점). 버튼을 다시 누르면 닫힘.
586
+ * ↑ · ↓ · Home · End 이동, Enter · Space 고르기, Esc 닫고 버튼으로 초점, Tab · 바깥 누르기 · 스크롤 · 창 크기 바꾸기는 닫기
587
+ */
588
+ function openMenu(button, props, choose) {
589
+ if (menu?.button === button) return closeMenu();
590
+ closeMenu();
591
+ const list = ui.typeMenu({
592
+ label: button.getAttribute('aria-label') ?? '',
593
+ types: props.types,
594
+ value: props.q.type,
595
+ });
596
+ const items = [...list.querySelectorAll('[role="option"]')];
597
+ document.body.append(list);
598
+ button.setAttribute('aria-expanded', 'true');
599
+ // 버튼 아래(자리가 없으면 위)에, 화면 밖으로 나가지 않게
600
+ const r = button.getBoundingClientRect();
601
+ list.style.minWidth = `${Math.max(r.width, 160)}px`;
602
+ const below = window.innerHeight - r.bottom;
603
+ const top = below >= list.offsetHeight + 8 || below >= r.top ? r.bottom + 4 : r.top - list.offsetHeight - 4;
604
+ list.style.top = `${Math.max(8, top)}px`;
605
+ list.style.left = `${Math.max(8, Math.min(r.left, window.innerWidth - list.offsetWidth - 8))}px`;
606
+
607
+ let at = Math.max(0, items.findIndex((i) => i.dataset.value === props.q.type));
608
+ const focusAt = (i) => {
609
+ at = (i + items.length) % items.length;
610
+ items[at].focus({ preventScroll: true });
611
+ };
612
+ const pick = (value) => {
613
+ closeMenu();
614
+ choose(value);
615
+ };
616
+ const keys = {
617
+ ArrowDown: () => focusAt(at + 1),
618
+ ArrowUp: () => focusAt(at - 1),
619
+ Home: () => focusAt(0),
620
+ End: () => focusAt(items.length - 1),
621
+ Enter: () => pick(items[at].dataset.value),
622
+ ' ': () => pick(items[at].dataset.value),
623
+ Escape: () => {
624
+ closeMenu();
625
+ button.focus();
626
+ },
627
+ };
628
+ const onKey = (e) => {
629
+ if (e.key === 'Tab') return closeMenu();
630
+ const run = keys[e.key];
631
+ if (!run) return;
632
+ e.preventDefault();
633
+ run();
634
+ };
635
+ const onOutside = (e) => {
636
+ if (!list.contains(e.target) && !button.contains(e.target)) closeMenu();
637
+ };
638
+ const onMove = (e) => {
639
+ if (!list.contains(e.target)) closeMenu();
640
+ };
641
+ items.forEach((item, i) =>
642
+ item.addEventListener('click', () => {
643
+ at = i;
644
+ pick(item.dataset.value);
645
+ }),
646
+ );
647
+ list.addEventListener('keydown', onKey);
648
+ document.addEventListener('pointerdown', onOutside, true);
649
+ window.addEventListener('scroll', onMove, true);
650
+ window.addEventListener('resize', closeMenu);
651
+ menu = {
652
+ button,
653
+ close() {
654
+ list.remove();
655
+ button.setAttribute('aria-expanded', 'false');
656
+ document.removeEventListener('pointerdown', onOutside, true);
657
+ window.removeEventListener('scroll', onMove, true);
658
+ window.removeEventListener('resize', closeMenu);
659
+ },
660
+ };
661
+ focusAt(at);
662
+ }
663
+
344
664
  /** 문항 추가 버튼 */
345
665
  function addQuestion(onClick) {
346
666
  const node = ui.addQuestion();
@@ -348,10 +668,16 @@ export function createEditor({ rerender, root, templates, labels }) {
348
668
  return node;
349
669
  }
350
670
 
671
+ /** index번째 문항 카드 */
672
+ function cardAt(index) {
673
+ return parts(root, 'card').find((c) => c.dataset.index === String(index));
674
+ }
675
+
351
676
  return {
352
677
  ui,
353
678
  field,
354
679
  inlineField,
680
+ richField,
355
681
  markEmptyRequired,
356
682
  numberField,
357
683
  toggle,
@@ -361,6 +687,6 @@ export function createEditor({ rerender, root, templates, labels }) {
361
687
  card,
362
688
  addQuestion,
363
689
  /** 검증에 걸린 문항 카드 */
364
- cardAt: (index) => parts(root, 'card').find((c) => c.dataset.index === String(index)),
690
+ cardAt,
365
691
  };
366
692
  }
@@ -1,2 +1,6 @@
1
+ export declare function setImages(next: Record<string, string> | undefined): void;
2
+ export declare const IMAGE_DATA: RegExp;
3
+ export declare function imageSrc(id: string): string | null;
4
+ export declare function lineNumbers(count: number): string;
1
5
  export declare function markdownToHtml(source: string): string;
2
6
  export declare function markdown(source: string, className?: string): HTMLElement;
@@ -1,20 +1,74 @@
1
1
  // 지문 · 해설용 작은 마크다운 (외부 라이브러리 없이). 먼저 HTML을 모두 이스케이프하므로 교육자가 쓴 태그는 그대로 글자로 보인다.
2
- // 지원: 문단 · 줄바꿈 · # 제목 · **굵게** · *기울임* · `코드` · ```코드 블록``` · - 목록 · 1. 목록 · [링크](https://…)
2
+ // 지원: 문단 · 줄바꿈 · # 제목 · **굵게** · *기울임* · ~~취소선~~ · `코드` · ```코드 블록```(3줄부터 줄 번호) · - 목록 · 1. 목록 ·
3
+ // [링크](https://…) · 그림 ![설명](image:아이디)(편집 화면에서 올려 내용 images에 둔 그림) · ![설명](img/파일)(zip 안 그림) ·
4
+ // \* 처럼 앞에 \를 붙이면 서식 기호가 아니라 글자
3
5
 
4
6
  const escape = (s) =>
5
7
  s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
6
8
 
9
+ /** 내용 images에 둔 그림 (아이디 → data: 주소). 화면이 내용을 받으면 setImages로 넣는다 */
10
+ let images = {};
11
+ /** @param {Record<string, string> | undefined} next */
12
+ export const setImages = (next) => {
13
+ images = next ?? {};
14
+ };
15
+ /** 그림으로 받는 data: 주소 (편집 화면이 줄여 만든 webp · jpeg, 옛 png) */
16
+ export const IMAGE_DATA = /^data:image\/(webp|jpeg|png);base64,[A-Za-z0-9+/=]+$/;
17
+ /** 아이디의 그림 주소 (없거나 모양이 다르면 null) */
18
+ export const imageSrc = (id) => (IMAGE_DATA.test(images[id] ?? '') ? images[id] : null);
19
+
20
+ // \로 막은 서식 기호는 잠시 쓰지 않는 글자로 바꿔 두었다가 마지막에 되돌린다
21
+ const ESCAPED = {
22
+ '\\': '',
23
+ '*': '',
24
+ '`': '',
25
+ '[': '',
26
+ ']': '',
27
+ '#': '',
28
+ '-': '',
29
+ '.': '',
30
+ '~': '',
31
+ };
32
+ const UNESCAPED = Object.fromEntries(Object.entries(ESCAPED).map(([k, v]) => [v, k]));
33
+ const restore = (s) => s.replace(/[-]/g, (c) => UNESCAPED[c]);
34
+
7
35
  function inline(s) {
8
- return s
9
- .replace(/`([^`]+)`/g, '<code>$1</code>')
10
- .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
11
- .replace(/\*([^*]+)\*/g, '<em>$1</em>')
12
- .replace(
13
- /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
14
- '<a href="$2" target="_blank" rel="noopener">$1</a>',
15
- );
36
+ // 코드 안은 서식을 풀지 않게 먼저 떼어 두었다가 마지막에 넣는다
37
+ const codes = [];
38
+ return restore(
39
+ s
40
+ .replace(/\\([\\*`[\]#\-.~])/g, (_, c) => ESCAPED[c])
41
+ .replace(/`([^`]+)`/g, (_, c) => `${codes.push(c) - 1}`)
42
+ .replace(/!\[([^\]]*)\]\(image:([\w-]+)\)/g, (_, alt, id) => {
43
+ const src = imageSrc(id);
44
+ return src
45
+ ? `<img class="qz-image" src="${src}" alt="${alt}">`
46
+ : `<span class="qz-image-missing">${alt}</span>`;
47
+ })
48
+ .replace(
49
+ /!\[([^\]]*)\]\((img\/[\w./-]+)\)/g,
50
+ '<img class="qz-image" src="$2" alt="$1" loading="lazy">',
51
+ )
52
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
53
+ .replace(/\*([^*]+)\*/g, '<em>$1</em>')
54
+ .replace(/~~([^~]+)~~/g, '<del>$1</del>')
55
+ .replace(
56
+ /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
57
+ '<a href="$2" target="_blank" rel="noopener">$1</a>',
58
+ )
59
+ .replace(/(\d+)/g, (_, i) => `<code>${codes[i]}</code>`),
60
+ );
16
61
  }
17
62
 
63
+ /** 줄 번호 글 "1\n2\n…" (코드 블록 왼쪽, CSS가 data-lines를 보인다) */
64
+ export const lineNumbers = (count) => Array.from({ length: count }, (_, i) => i + 1).join('\n');
65
+
66
+ /** 코드 블록. 3줄부터 줄 번호 */
67
+ const codeBlock = (lines) =>
68
+ lines.length >= 3
69
+ ? `<pre class="qz-lines" data-lines="${lines.map((_, i) => i + 1).join('&#10;')}"><code>${lines.join('\n')}</code></pre>`
70
+ : `<pre><code>${lines.join('\n')}</code></pre>`;
71
+
18
72
  export function markdownToHtml(source) {
19
73
  const lines = escape(String(source ?? '')).split('\n');
20
74
  const out = [];
@@ -35,7 +89,7 @@ export function markdownToHtml(source) {
35
89
  for (const line of lines) {
36
90
  if (code) {
37
91
  if (line.startsWith('```')) {
38
- out.push(`<pre><code>${code.join('\n')}</code></pre>`);
92
+ out.push(codeBlock(code));
39
93
  code = null;
40
94
  } else code.push(line);
41
95
  continue;
@@ -67,7 +121,7 @@ export function markdownToHtml(source) {
67
121
  para.push(line);
68
122
  }
69
123
  }
70
- if (code) out.push(`<pre><code>${code.join('\n')}</code></pre>`);
124
+ if (code) out.push(codeBlock(code));
71
125
  flushPara();
72
126
  flushList();
73
127
  return out.join('');
@@ -38,7 +38,11 @@ export declare function validateAnswerKey(
38
38
  /** 보기 줄에서 정답을 고르는 유형 (단일 · 복수 · 그룹) */
39
39
  export declare const INLINE_ANSWER_TYPES: string[];
40
40
  /** 보기 하나의 정답 표시: 단일 · 복수는 true/false, 그룹은 속한 그룹 id('' = 없음) */
41
- export declare function optionAnswer(q: any, value: any, optionId: string): boolean | string | undefined;
41
+ export declare function optionAnswer(
42
+ q: any,
43
+ value: any,
44
+ optionId: string
45
+ ): boolean | string | undefined;
42
46
  /** 보기 하나의 정답 표시를 바꾼 새 정답 (화면 값 모양 그대로) */
43
47
  export declare function withOptionAnswer(
44
48
  q: any,
@@ -58,3 +62,32 @@ export declare function checkAnswerKey(
58
62
  messages: Record<string, any>
59
63
  ): { questionIndex: number; message: string } | null;
60
64
  export declare function shuffled<T>(items: T[], seed: string): T[];
65
+ /** 문항별 부분 점수 채점 방식 이름 */
66
+ export declare const PARTIAL: 'partial_pattern';
67
+ /** 채점 방식: 저장된 grading.type → 공개 값 settings.gradingType → pattern */
68
+ export declare function gradingTypeOf(
69
+ content: unknown,
70
+ grading: unknown
71
+ ): 'pattern' | 'partial_pattern';
72
+ /** 문항별 답 → 제출할 문자열 배열 (partial_pattern) */
73
+ export declare function joinAnswerList(questions: any[], values: unknown[]): string[];
74
+ /** 문항별 정답 → 문항마다 정답 정규식 (partial_pattern) */
75
+ export declare function buildAnswerKeys(questions: any[], key: Record<string, any>): string[];
76
+ /** buildAnswerKeys가 만든 정규식 배열 → 문항별 정답. 다른 모양이면 null */
77
+ export declare function parseAnswerKeys(
78
+ questions: any[],
79
+ keys: unknown
80
+ ): Record<string, any> | null;
81
+ /** 정답 검증 2 (문항별) */
82
+ export declare function checkAnswerKeys(
83
+ questions: any[],
84
+ key: Record<string, any>,
85
+ keys: string[],
86
+ messages: Record<string, any>
87
+ ): { questionIndex: number; message: string } | null;
88
+ /** 저장할 문항별 점수: 저장된 정규식의 문제 id로 맞춰 지금 순서로, 문제 id가 다르면 split으로 다시 나눔 */
89
+ export declare function scoresFor(
90
+ questions: any[],
91
+ saved: { answer_key?: unknown; scores?: unknown } | undefined,
92
+ split: (n: number) => number[]
93
+ ): { scores: number[]; resplit: boolean };