@eliceio/cdk-cli 0.1.0-alpha.2 → 0.1.0-alpha.4

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 (103) hide show
  1. package/README.md +263 -191
  2. package/es/cli.js +93 -33
  3. package/es/commands/build/index.d.ts +1 -1
  4. package/es/commands/build/index.js +21 -12
  5. package/es/commands/check/index.d.ts +11 -2
  6. package/es/commands/check/index.js +51 -5
  7. package/es/commands/create/index.d.ts +6 -0
  8. package/es/commands/create/index.js +56 -8
  9. package/es/commands/create/install.d.ts +17 -0
  10. package/es/commands/create/install.js +53 -0
  11. package/es/commands/create/scaffold.d.ts +6 -1
  12. package/es/commands/create/scaffold.js +27 -17
  13. package/es/commands/dev/index.d.ts +1 -1
  14. package/es/commands/dev/index.js +6 -2
  15. package/es/commands/doctor/index.d.ts +21 -0
  16. package/es/commands/doctor/index.js +255 -38
  17. package/es/commands/mcp/index.d.ts +134 -0
  18. package/es/commands/mcp/index.js +399 -0
  19. package/es/commands/setup/index.d.ts +40 -0
  20. package/es/commands/setup/index.js +157 -0
  21. package/es/commands/skill/index.d.ts +2 -5
  22. package/es/commands/skill/index.js +1 -29
  23. package/es/core/collect.d.ts +5 -2
  24. package/es/core/config.d.ts +141 -31
  25. package/es/core/config.js +341 -59
  26. package/es/core/manifest.d.ts +2 -1
  27. package/es/core/manifest.js +2 -1
  28. package/es/core/minify.js +2 -2
  29. package/es/core/prepare.d.ts +18 -2
  30. package/es/core/prepare.js +47 -18
  31. package/es/core/project-check.d.ts +26 -0
  32. package/es/core/project-check.js +53 -0
  33. package/es/core/sandbox.js +2 -2
  34. package/es/core/sdk.d.ts +39 -0
  35. package/es/core/sdk.js +95 -0
  36. package/es/core/templates.d.ts +25 -0
  37. package/es/core/templates.js +41 -0
  38. package/es/dev/grading.d.ts +14 -7
  39. package/es/dev/grading.js +27 -13
  40. package/es/dev/host-page.d.ts +1 -1
  41. package/es/dev/host-page.js +34 -34
  42. package/es/dev/mock-api.d.ts +19 -4
  43. package/es/dev/mock-api.js +75 -9
  44. package/es/dev/server.d.ts +7 -0
  45. package/es/dev/server.js +112 -32
  46. package/es/rules/check.js +95 -10
  47. package/es/rules/index.d.ts +1 -1
  48. package/es/rules/index.js +1 -1
  49. package/es/rules/manifest.d.ts +23 -9
  50. package/es/rules/manifest.js +60 -35
  51. package/es/rules/node.js +3 -1
  52. package/es/rules/semver.d.ts +5 -0
  53. package/es/rules/semver.js +32 -0
  54. package/es/rules/types.d.ts +38 -7
  55. package/es/rules.json.js +2 -2
  56. package/es/test-packages.d.ts +7 -0
  57. package/guides/content-development.md +150 -55
  58. package/package.json +3 -3
  59. package/rules.json +77 -7
  60. package/skills/_shared/always.md +4 -2
  61. package/skills/elice-content-check/SKILL.md +3 -1
  62. package/skills/elice-content-create/SKILL.md +5 -4
  63. package/skills/elice-content-migrate/SKILL.md +2 -2
  64. package/skills/elice-content-publish/SKILL.md +23 -0
  65. package/templates/_shared/lib/cdk-mock.d.ts +21 -3
  66. package/templates/_shared/lib/cdk-mock.js +241 -82
  67. package/templates/_shared/lib/elice-content.css +204 -0
  68. package/templates/_shared/lib/elice-content.d.ts +115 -6
  69. package/templates/_shared/lib/elice-content.js +656 -43
  70. package/templates/blank/README.md +19 -7
  71. package/templates/blank/completion.html +15 -0
  72. package/templates/blank/gitignore +1 -0
  73. package/templates/blank/metadata.json +11 -0
  74. package/templates/blank/package.json +13 -0
  75. package/templates/blank/screens/completion.js +7 -0
  76. package/templates/blank/screens/edit.js +3 -0
  77. package/templates/blank/screens/instructor.js +12 -5
  78. package/templates/blank/screens/learn.js +16 -11
  79. package/templates/blank/template.json +6 -0
  80. package/templates/quiz/README.md +41 -31
  81. package/templates/quiz/core/behaviors.d.ts +5 -0
  82. package/templates/quiz/core/behaviors.js +12 -0
  83. package/templates/quiz/core/editor.d.ts +12 -1
  84. package/templates/quiz/core/editor.js +28 -5
  85. package/templates/quiz/core/model.d.ts +41 -1
  86. package/templates/quiz/core/model.js +272 -5
  87. package/templates/quiz/gitignore +1 -0
  88. package/templates/quiz/metadata.json +11 -0
  89. package/templates/quiz/package.json +13 -0
  90. package/templates/quiz/screens/edit.js +176 -46
  91. package/templates/quiz/screens/instructor.js +18 -12
  92. package/templates/quiz/screens/learn.js +43 -38
  93. package/templates/quiz/styles.css +47 -0
  94. package/templates/quiz/template.json +6 -0
  95. package/templates/quiz/ui/templates/edit.d.ts +3 -0
  96. package/templates/quiz/ui/templates/edit.js +53 -14
  97. package/templates/quiz/ui/texts.js +56 -29
  98. package/templates/_shared/lib/cdk.js +0 -3
  99. package/templates/blank/content.json +0 -4
  100. package/templates/blank/elice.config.json +0 -12
  101. package/templates/quiz/content.json +0 -81
  102. package/templates/quiz/elice.config.json +0 -14
  103. package/templates/quiz/grading.json +0 -13
@@ -1,10 +1,12 @@
1
1
  // 퀴즈 데이터 모델. 학생 · 교육자 · 편집 화면이 같이 씁니다. (기존 퀴즈 material 명세: docs/quiz-spec.md)
2
2
  //
3
- // content.json / 편집 화면이 저장하는 settings (학생에게 공개, 정답 없음)
3
+ // 편집 화면이 저장하는 settings (학생에게 공개, 정답 없음)
4
4
  // { title, description, questions: [{ id, type, title, description, options?, groups?, slots?,
5
5
  // shuffle?, placeholder?, explanation: { enabled, text } }] }
6
- // 제출하는 답 (문항마다 정해진 모양의 문자열, 채점은 서버가 답 묶음 전체를 비교: pattern)
7
- // { answers: { q1: "b", q2: "a,d", q3: "c,a,b", q4: "가중치", q5: "g1:a|g2:b,c" } }
6
+ // 제출하는 답: 문자열 하나 (ADR 0008). 문항 순서대로 `문항id=답`을 `;`로 잇고, 주관식 답은 encodeURIComponent
7
+ // "q1=b;q2=a,d;q3=c,a,b;q4=%EA%B0%80%EC%A4%91%EC%B9%98;q5=g1:a|g2:b,c"
8
+ // 퀴즈는 완료 정책 on_graded + 채점 방식 pattern 고정 (ADR 0009, completionPolicies ["on_graded"]). 정답(settings.grading)은 편집 화면이 문항마다 고른 답으로
9
+ // 만든 정규식 하나: { type: 'pattern', answer_key: '^q1=b;…$' }
8
10
 
9
11
  // 화면에 보이는 문구는 여기 두지 않습니다 (ui/texts.js). 문구가 필요한 함수는 화면(screens/)이 문구를 넘겨 줍니다.
10
12
 
@@ -16,8 +18,13 @@ export const LIMITS = {
16
18
  optionsMax: 20,
17
19
  groupsMin: 2,
18
20
  groupsMax: 6,
21
+ // 퀴즈 하나에 문항 하나 (기존 LXP처럼). 여러 문항은 퀴즈 페이지를 여러 개로 → 부분 점수가 필요 없음
22
+ questionsMax: 1,
19
23
  };
20
24
 
25
+ /** 편집 화면에서 문항을 더 넣을 수 있는지. 이미 여러 문항으로 저장된 퀴즈도 그대로 보이고 저장되며, 더 넣는 것만 막는다 */
26
+ export const canAddQuestion = (questions) => (questions?.length ?? 0) < LIMITS.questionsMax;
27
+
21
28
  const hasOptions = (type) => type !== 'text';
22
29
 
23
30
  /** 보기·그룹 id는 답 문자열에 그대로 들어가므로 영문 소문자·숫자만 (구분자 , | : 를 쓰지 않음) */
@@ -46,7 +53,7 @@ export function newQuestion(type, usedIds, names) {
46
53
 
47
54
  /**
48
55
  * 유형을 바꿀 때 데이터 변환 (기존 편집 화면처럼 보기 텍스트는 최대한 살림).
49
- * 정답은 LXP 채점 설정에 있으므로 여기서는 다루지 않는다. names: newQuestion과 같음
56
+ * 정답은 편집 화면이 따로 모아 settings.grading에 저장하므로 여기서는 다루지 않는다. names: newQuestion과 같음
50
57
  */
51
58
  export function convertType(q, type, names) {
52
59
  const next = { ...q, type };
@@ -109,7 +116,7 @@ export function validateQuiz(content, v) {
109
116
  return null;
110
117
  }
111
118
 
112
- // ---------- 답 문자열 (LXP 채점 설정이 같은 모양으로 정답을 만든다) ----------
119
+ // ---------- 답 문자열 (편집 화면이 같은 모양으로 정답 정규식을 만든다) ----------
113
120
 
114
121
  /**
115
122
  * 화면의 답 → 문항의 답 문자열
@@ -160,6 +167,266 @@ export function decodeAnswer(q, text) {
160
167
  }
161
168
  }
162
169
 
170
+ // ---------- 제출 답 하나로 잇기 · 풀기 (ADR 0008) ----------
171
+
172
+ /** 문항별 답 문자열 → 제출할 답 문자열 하나. 주관식 답은 encodeURIComponent (`;` · `=` · `|`가 들어가도 경계가 그대로) */
173
+ export function joinAnswers(questions, values) {
174
+ return questions
175
+ .map((q, i) => {
176
+ const a = encodeAnswer(q, values[i]);
177
+ return `${q.id}=${q.type === 'text' ? encodeURIComponent(a) : a}`;
178
+ })
179
+ .join(';');
180
+ }
181
+
182
+ /**
183
+ * 제출한 답 → 문항 id별 답 문자열 (다시 열기 · 튜터링). 옛 답 `{ answers: { q1: "b" } }`도 받는다.
184
+ * `;`로 나누고 첫 `=`에서 문항 id와 답을 나눈 뒤, 주관식은 decodeURIComponent
185
+ */
186
+ export function splitAnswers(questions, answer) {
187
+ if (answer && typeof answer === 'object') return { ...(answer.answers ?? {}) };
188
+ if (typeof answer !== 'string') return {};
189
+ const byId = Object.fromEntries(questions.map((q) => [q.id, q]));
190
+ const out = {};
191
+ for (const part of answer.split(';')) {
192
+ const at = part.indexOf('=');
193
+ if (at < 0) continue;
194
+ const id = part.slice(0, at);
195
+ let value = part.slice(at + 1);
196
+ if (byId[id]?.type === 'text') {
197
+ try {
198
+ value = decodeURIComponent(value);
199
+ } catch {
200
+ // 잘못된 인코딩은 그대로 둔다
201
+ }
202
+ }
203
+ out[id] = value;
204
+ }
205
+ return out;
206
+ }
207
+
208
+ // ---------- 정답 정규식 (편집 화면, ADR 0009) ----------
209
+
210
+ const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
211
+ const unescapeRegex = (text) => text.replace(/\\(.)/g, '$1');
212
+
213
+ /** 정답 하나(화면 값) → 문항 정규식 조각. 주관식은 허용 답 여러 개를 (?:…|…)로 */
214
+ function keyPart(q, value) {
215
+ if (q.type === 'text') {
216
+ const alts = (value ?? []).map((t) => String(t).trim()).filter(Boolean);
217
+ return `(?:${alts.map((t) => escapeRegex(encodeURIComponent(t))).join('|')})`;
218
+ }
219
+ return escapeRegex(encodeAnswer(q, value));
220
+ }
221
+
222
+ /**
223
+ * 문항별 정답(화면 값: 주관식은 허용 답 배열) → regex 정답 정규식 하나.
224
+ * 인코딩 → 정규식 이스케이프 → `|`로 묶기 → 전체를 `^…$` (ADR 0008 §4)
225
+ */
226
+ export function buildAnswerKey(questions, key) {
227
+ return `^${questions.map((q) => `${escapeRegex(q.id)}=${keyPart(q, key[q.id])}`).join(';')}$`;
228
+ }
229
+
230
+ /**
231
+ * buildAnswerKey가 만든 정규식 → 문항별 정답(화면 값). 다른 모양(손으로 쓴 정규식)이면 null.
232
+ * 문항이 바뀌었으면 있는 문항만 돌려준다 (없는 문항은 validateAnswerKey가 알려 줌)
233
+ */
234
+ export function parseAnswerKey(questions, regex) {
235
+ if (typeof regex !== 'string' || !regex.startsWith('^') || !regex.endsWith('$')) return null;
236
+ const byId = Object.fromEntries(questions.map((q) => [q.id, q]));
237
+ const out = {};
238
+ // 정답 조각 안의 `;`는 주관식 인코딩(%3B)이라 나오지 않는다
239
+ for (const part of regex.slice(1, -1).split(';')) {
240
+ const at = part.indexOf('=');
241
+ if (at < 0) return null;
242
+ const id = unescapeRegex(part.slice(0, at));
243
+ const body = part.slice(at + 1);
244
+ const q = byId[id];
245
+ if (!q) continue;
246
+ if (q.type === 'text') {
247
+ if (!body.startsWith('(?:') || !body.endsWith(')')) return null;
248
+ try {
249
+ out[id] = body
250
+ .slice(3, -1)
251
+ .split(/(?<!\\)\|/)
252
+ .map((t) => decodeURIComponent(unescapeRegex(t)))
253
+ .filter(Boolean);
254
+ } catch {
255
+ return null;
256
+ }
257
+ } else out[id] = decodeAnswer(q, unescapeRegex(body));
258
+ }
259
+ return out;
260
+ }
261
+
262
+ /**
263
+ * 정답 검증 1: 모든 문항에 정답이 있고, 정답이 지금 있는 보기 · 그룹을 가리키는지 (G63).
264
+ * 문제가 없으면 null, 있으면 { questionIndex, message }
265
+ * @param {object} v 검증 문구 (ui/texts.js의 answers.validation)
266
+ */
267
+ export function validateAnswerKey(questions, key, v) {
268
+ for (const [i, q] of questions.entries()) {
269
+ const at = (message) => ({ questionIndex: i, message: v.at(i + 1, message) });
270
+ const value = key[q.id];
271
+ if (q.type === 'text') {
272
+ if (!(value ?? []).some((t) => String(t).trim())) return at(v.noAnswer);
273
+ continue;
274
+ }
275
+ if (!isAnswered(q, value)) return at(v.noAnswer);
276
+ const ids = new Set((q.options ?? []).map((o) => o.id));
277
+ const chosen =
278
+ q.type === 'group'
279
+ ? Object.values(value ?? {}).flat()
280
+ : q.type === 'select_one'
281
+ ? [value]
282
+ : (value ?? []);
283
+ if (chosen.some((id) => !ids.has(id))) return at(v.missingOption);
284
+ if (q.type === 'group' && Object.keys(value ?? {}).some((g) => !q.groups.some((x) => x.id === g)))
285
+ return at(v.missingOption);
286
+ }
287
+ return null;
288
+ }
289
+
290
+ // ---------- 편집 화면: 보기 줄에서 바로 고르는 정답 (단일 · 복수 · 그룹) ----------
291
+
292
+ /** 보기 줄에서 정답을 고르는 유형. 순서 · 주관식은 따로 고른다 */
293
+ export const INLINE_ANSWER_TYPES = ['select_one', 'select_multiple', 'group'];
294
+
295
+ /**
296
+ * 보기 하나의 정답 표시: 단일 · 복수는 정답인지(true/false), 그룹은 속한 그룹 id(없으면 '')
297
+ */
298
+ export function optionAnswer(q, value, optionId) {
299
+ switch (q.type) {
300
+ case 'select_one':
301
+ return value === optionId;
302
+ case 'select_multiple':
303
+ return (value ?? []).includes(optionId);
304
+ case 'group':
305
+ return (q.groups ?? []).find((g) => (value?.[g.id] ?? []).includes(optionId))?.id ?? '';
306
+ default:
307
+ return undefined;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * 보기 하나의 정답 표시를 바꾼 새 정답 (화면 값 모양 그대로).
313
+ * 단일: on이면 그 보기 · 복수: on/off · 그룹: choice 그룹으로 옮김('' = 어느 그룹에도 넣지 않음)
314
+ */
315
+ export function withOptionAnswer(q, value, optionId, choice) {
316
+ switch (q.type) {
317
+ case 'select_one':
318
+ return choice ? optionId : value === optionId ? null : value;
319
+ case 'select_multiple': {
320
+ const rest = (value ?? []).filter((id) => id !== optionId);
321
+ if (!choice) return rest;
322
+ // 보기 순서대로 둔다 (저장하는 답 문자열은 어차피 정렬)
323
+ const set = new Set([...rest, optionId]);
324
+ return q.options.map((o) => o.id).filter((id) => set.has(id));
325
+ }
326
+ case 'group': {
327
+ const out = Object.fromEntries(
328
+ q.groups.map((g) => [g.id, (value?.[g.id] ?? []).filter((id) => id !== optionId)]),
329
+ );
330
+ if (choice && choice in out) out[choice].push(optionId);
331
+ return out;
332
+ }
333
+ default:
334
+ return value;
335
+ }
336
+ }
337
+
338
+ /**
339
+ * 보기 · 그룹을 지운 뒤 정답에서 지금 없는 보기 · 그룹을 뺀다 (단일 · 복수 · 그룹).
340
+ * 보기 순서를 바꿔도 id가 그대로라 정답은 그대로다. 다른 유형은 그대로 돌려준다
341
+ */
342
+ export function pruneAnswer(q, value) {
343
+ if (value === undefined || !INLINE_ANSWER_TYPES.includes(q.type)) return value;
344
+ const ids = new Set((q.options ?? []).map((o) => o.id));
345
+ switch (q.type) {
346
+ case 'select_one':
347
+ return ids.has(value) ? value : null;
348
+ case 'select_multiple':
349
+ return (value ?? []).filter((id) => ids.has(id));
350
+ default:
351
+ return Object.fromEntries(
352
+ q.groups.map((g) => [g.id, (value?.[g.id] ?? []).filter((id) => ids.has(id))]),
353
+ );
354
+ }
355
+ }
356
+
357
+ /** 정답(화면 값)을 다른 답으로 하나 바꾼 값. 바꿀 수 없으면 undefined (오답 검증용) */
358
+ export function wrongValue(q, value) {
359
+ const ids = (q.options ?? []).map((o) => o.id);
360
+ switch (q.type) {
361
+ case 'select_one':
362
+ return ids.find((id) => id !== value);
363
+ case 'select_multiple': {
364
+ const set = new Set(value ?? []);
365
+ const flip = ids[0];
366
+ if (flip === undefined) return undefined;
367
+ if (set.has(flip)) set.delete(flip);
368
+ else set.add(flip);
369
+ return [...set];
370
+ }
371
+ case 'order': {
372
+ const list = [...(value ?? [])];
373
+ if (list.length >= 2) {
374
+ [list[0], list[1]] = [list[1], list[0]];
375
+ return list;
376
+ }
377
+ const other = ids.find((id) => !list.includes(id));
378
+ return other === undefined ? undefined : [other];
379
+ }
380
+ case 'group': {
381
+ const groups = q.groups.map((g) => g.id);
382
+ const out = Object.fromEntries(groups.map((g) => [g, [...(value?.[g] ?? [])]]));
383
+ const from = groups.find((g) => out[g].length > 0);
384
+ const to = groups.find((g) => g !== from);
385
+ if (!from || !to) return undefined;
386
+ out[to].push(out[from].shift());
387
+ return out;
388
+ }
389
+ case 'text':
390
+ return ['\u0000오답'];
391
+ default:
392
+ return undefined;
393
+ }
394
+ }
395
+
396
+ /**
397
+ * 정답 검증 2 (ADR 0009 §3): 만든 정규식이 학생 화면이 제출할 문자열과 맞는지.
398
+ * - 왕복: 정답을 학생 화면과 같은 joinAnswers로 이은 문자열이 맞아야 한다 (주관식 허용 답은 하나씩 모두)
399
+ * - 오답: 문항 하나를 다른 답으로 바꾼 문자열은 맞지 않아야 한다 (너무 넓은 정규식 방지)
400
+ * 문제가 없으면 null, 있으면 { questionIndex, message }
401
+ * @param {object} v 검증 문구 (ui/texts.js의 answers.validation)
402
+ */
403
+ export function checkAnswerKey(questions, key, regex, v) {
404
+ let re;
405
+ try {
406
+ re = new RegExp(regex);
407
+ } catch {
408
+ return { questionIndex: -1, message: v.badRegex };
409
+ }
410
+ // 화면 값으로: 주관식은 허용 답 중 하나
411
+ const base = questions.map((q) => (q.type === 'text' ? (key[q.id] ?? [])[0] : key[q.id]));
412
+ if (!re.test(joinAnswers(questions, base))) return { questionIndex: -1, message: v.roundTrip };
413
+ for (const [i, q] of questions.entries()) {
414
+ const at = (message) => ({ questionIndex: i, message: v.at(i + 1, message) });
415
+ if (q.type === 'text')
416
+ for (const alt of key[q.id] ?? []) {
417
+ const values = [...base];
418
+ values[i] = alt;
419
+ if (!re.test(joinAnswers(questions, values))) return at(v.roundTrip);
420
+ }
421
+ const wrong = wrongValue(q, key[q.id]);
422
+ if (wrong === undefined) continue;
423
+ const values = [...base];
424
+ values[i] = q.type === 'text' ? wrong[0] : wrong;
425
+ if (re.test(joinAnswers(questions, values))) return at(v.tooWide);
426
+ }
427
+ return null;
428
+ }
429
+
163
430
  /** 이 문항에 답했는지 (기존 규칙: 순서는 칸을 모두 채움, 그룹은 하나라도 배치, 나머지는 비어 있지 않음) */
164
431
  export function isAnswered(q, value) {
165
432
  switch (q.type) {
@@ -1,3 +1,4 @@
1
1
  dist/
2
2
  node_modules/
3
3
  .env
4
+ .ecdk/
@@ -0,0 +1,11 @@
1
+ {
2
+ "kind": "material",
3
+ "screens": {
4
+ "learn": { "enabled": true, "entry": "index.html" },
5
+ "instructor": { "enabled": true, "entry": "instructor.html" },
6
+ "edit": { "enabled": true, "entry": "edit.html" },
7
+ "completionPolicy": { "enabled": false }
8
+ },
9
+ "completionPolicies": ["on_graded"],
10
+ "commentary": "commentary.txt"
11
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "private": true,
3
+ "type": "module",
4
+ "scripts": {
5
+ "dev": "ecdk dev",
6
+ "build": "ecdk build",
7
+ "check": "ecdk check"
8
+ },
9
+ "dependencies": {
10
+ "@eliceio/cdk": "workspace:^1.0.0-alpha.3"
11
+ },
12
+ "ecdk": {}
13
+ }
@@ -1,21 +1,48 @@
1
1
  // 내용 편집 화면(CMS). 기존 퀴즈 편집 폼을 옮김 (docs/quiz-spec.md §3). 저장 버튼 · 변경 표시는 키트(useSave)가 합니다.
2
- // 정답은 여기서 다루지 않습니다: LXP 편집 화면의 채점 설정에서 정답(문항 id별 답 묶음)을 지정합니다.
3
- // 저장한 내용은 학생에게도 내려가므로 정답을 넣지 않습니다.
4
- // 여기서는 어떤 칸을 어떤 순서로 놓을지만 정합니다. 모양은 ui/(templates/edit.js · texts · theme.css), 동작은 core/editor.js.
5
- import { start } from '../lib/elice-content.js';
2
+ // 퀴즈는 완료 정책 on_graded + 채점 방식 pattern 고정 (ADR 0009, metadata.json completionPolicies ["on_graded"]): 문항 카드마다 정답을
3
+ // 고르고 (단일 · 복수 · 그룹은 보기 줄에서 바로, 순서 · 주관식은 아래 "정답"에서), 저장할 때 고른 답으로 정답 정규식 하나를 만들어 검증한 뒤 settings.grading에 함께 저장합니다.
4
+ // 문제 내용(content)은 학생에게도 내려가므로 정답을 넣지 않습니다 (정답은 grading에만, 서버가 학생에게 내려주지 않음).
5
+ // 여기서는 어떤 칸을 어떤 순서로 놓을지만 정합니다. 모양은 ui/(templates/edit.js · texts · theme.css), 동작은 core/.
6
+ import { start, validateAnswerRegex } from '../lib/elice-content.js';
7
+ import { renderAnswerBody } from '../core/behaviors.js';
6
8
  import { createEditor } from '../core/editor.js';
7
- import { convertType, LIMITS, newQuestion, validateQuiz } from '../core/model.js';
9
+ import {
10
+ buildAnswerKey,
11
+ canAddQuestion,
12
+ checkAnswerKey,
13
+ convertType,
14
+ INLINE_ANSWER_TYPES,
15
+ joinAnswers,
16
+ LIMITS,
17
+ newQuestion,
18
+ optionAnswer,
19
+ parseAnswerKey,
20
+ pruneAnswer,
21
+ validateAnswerKey,
22
+ validateQuiz,
23
+ withOptionAnswer,
24
+ } from '../core/model.js';
8
25
  import * as templates from '../ui/templates/edit.js';
26
+ import { templates as quizTemplates } from '../ui/templates/index.js';
9
27
  import { loading } from '../ui/templates/page.js';
10
28
  import { texts } from '../ui/texts.js';
11
29
 
12
30
  const t = texts.edit;
31
+ const a = texts.answers;
13
32
  const root = document.getElementById('app');
14
33
  document.title = texts.page.edit;
15
34
  root.replaceChildren(loading());
16
35
  const app = await start({ screen: 'edit' });
17
36
  const draft = structuredClone(app.content);
18
37
  draft.questions ??= [];
38
+
39
+ // 문항 id → 정답(화면 값: 선택 id · id 목록 · 그룹별 목록, 주관식은 허용 답 목록). 저장된 정규식을 읽어 채운다
40
+ const savedKey = app.grading?.answer_key;
41
+ const parsed = savedKey ? parseAnswerKey(draft.questions, savedKey) : {};
42
+ /** @type {Record<string, unknown>} */
43
+ const answers = parsed ?? {};
44
+ const unreadable = Boolean(savedKey) && parsed === null;
45
+
19
46
  const form = createEditor({
20
47
  rerender: render,
21
48
  root,
@@ -35,51 +62,124 @@ const swap = (list, i, j) => {
35
62
  render();
36
63
  };
37
64
 
65
+ /** 순서 · 주관식 문항 카드의 "정답": 학생 화면과 같은 보기 · 칸으로 고른다 (주관식은 허용 답 여러 개) */
66
+ function answerField(q) {
67
+ if (q.type === 'text') {
68
+ const node = templates.textAnswers({ placeholder: a.textPlaceholder });
69
+ // 조각이 칸 자체이거나 칸을 감싼 요소여도 된다
70
+ const input = node.matches('[data-role="input"]') ? node : node.querySelector('[data-role="input"]');
71
+ input.value = (answers[q.id] ?? []).join('\n');
72
+ input.addEventListener('input', () => {
73
+ answers[q.id] = input.value
74
+ .split('\n')
75
+ .map(s => s.trim())
76
+ .filter(Boolean);
77
+ });
78
+ return form.ui.section({ label: a.label, hint: a.hint.text, body: node });
79
+ }
80
+ const view = renderAnswerBody(q, { templates: quizTemplates });
81
+ if (answers[q.id] !== undefined) view.setValue(answers[q.id]);
82
+ // 누르기 · 끌어 놓기가 끝난 뒤 값을 읽는다
83
+ const read = () => queueMicrotask(() => (answers[q.id] = view.getValue()));
84
+ for (const type of ['input', 'change', 'click', 'pointerup'])
85
+ view.el.addEventListener(type, read);
86
+ return form.ui.section({ label: a.label, hint: a.hint[q.type], body: view.el });
87
+ }
88
+
89
+ /**
90
+ * 단일 · 복수 · 그룹 문항의 보기 줄 정답 칸 (radio · checkbox · 그룹 select). 정답은 보기 id로 두므로
91
+ * 순서를 바꿔도 그대로이고, 보기를 지우면 정답에서 뺀다 (optionsOpts의 onDelete)
92
+ */
93
+ function inlineAnswer(q) {
94
+ const types = { select_one: 'radio', select_multiple: 'checkbox', group: 'select' };
95
+ return {
96
+ type: types[q.type],
97
+ // 문항마다 다른 이름 (같은 문항의 radio끼리만 묶임)
98
+ name: `answer-${q.id}`,
99
+ choices: q.type === 'group' ? q.groups.map(g => [g.id, g.name]) : undefined,
100
+ get: option => optionAnswer(q, answers[q.id], option.id),
101
+ set: (option, value) => (answers[q.id] = withOptionAnswer(q, answers[q.id], option.id, value)),
102
+ };
103
+ }
104
+
105
+ /** 보기 목록 옵션: 지우면 정답에서 빼고, 단일 · 복수 · 그룹은 줄마다 정답 칸 */
106
+ function optionsOpts(q) {
107
+ const inline = INLINE_ANSWER_TYPES.includes(q.type);
108
+ return {
109
+ onDelete: () => {
110
+ if (q.type === 'order') q.slots = Math.min(q.slots, q.options.length);
111
+ if (answers[q.id] !== undefined) answers[q.id] = pruneAnswer(q, answers[q.id]);
112
+ },
113
+ answer: inline ? inlineAnswer(q) : undefined,
114
+ };
115
+ }
116
+
38
117
  /** 문항 카드 안의 칸들. 유형마다 보이는 칸이 다르다 */
39
118
  function questionFields(q, i) {
40
119
  const body = [
41
- form.field(t.title, q.title, (v) => (q.title = v), { required: true, max: LIMITS.titleMax }),
42
- form.markdownField(t.description, q.description, (v) => (q.description = v)),
120
+ form.field(t.title, q.title, v => (q.title = v), { required: true, max: LIMITS.titleMax }),
121
+ form.markdownField(t.description, q.description, v => (q.description = v)),
43
122
  ];
44
123
  if (q.type === 'select_one' || q.type === 'select_multiple' || q.type === 'order') {
45
- const options = form.itemList('option', q.options, `${i}o`, {
124
+ const options = form.itemList('option', q.options, `${i}o`, optionsOpts(q));
125
+ body.push(
126
+ form.ui.section({
127
+ label: t.options,
128
+ hint: q.type === 'order' ? undefined : a.hint[q.type],
129
+ body: options,
130
+ })
131
+ );
132
+ }
133
+ if (q.type === 'order') {
134
+ const slots = form.numberField(
135
+ t.slots,
136
+ t.slotsHint,
137
+ q.slots,
138
+ q.options.length,
139
+ v => (q.slots = v)
140
+ );
141
+ // 칸 수가 바뀌면 정답 칸도 다시 그린다 (입력하는 동안이 아니라 확정했을 때)
142
+ slots.querySelector('[data-role="input"]')?.addEventListener('change', render);
143
+ body.push(slots);
144
+ }
145
+ if (q.type === 'group') {
146
+ const groups = form.itemList('group', q.groups, `${i}g`, {
147
+ // 지운 그룹에 넣은 보기는 "그룹 없음"으로
46
148
  onDelete: () => {
47
- if (q.type === 'order') q.slots = Math.min(q.slots, q.options.length);
149
+ if (answers[q.id] !== undefined) answers[q.id] = pruneAnswer(q, answers[q.id]);
150
+ },
151
+ // 그룹 이름을 고치면 보기 줄의 그룹 고르기 이름도 바로 바꾼다 (다시 그리면 입력 중 초점을 잃음)
152
+ onInput: g => {
153
+ for (const select of root.querySelectorAll(`select[name="answer-${q.id}"]`))
154
+ for (const option of select.options) if (option.value === g.id) option.textContent = g.name;
48
155
  },
49
156
  });
50
- body.push(form.ui.section({ label: t.options, body: options }));
51
- }
52
- if (q.type === 'order')
53
- body.push(
54
- form.numberField(t.slots, t.slotsHint, q.slots, q.options.length, (v) => (q.slots = v)),
55
- );
56
- if (q.type === 'group')
57
157
  body.push(
58
- form.ui.section({ label: t.groups, body: form.itemList('group', q.groups, `${i}g`) }),
158
+ form.ui.section({ label: t.groups, body: groups }),
59
159
  form.ui.section({
60
160
  label: t.options,
61
- hint: t.groupOptionsHint,
62
- body: form.itemList('option', q.options, `${i}o`),
63
- }),
161
+ hint: a.hint.group,
162
+ body: form.itemList('option', q.options, `${i}o`, optionsOpts(q)),
163
+ })
64
164
  );
165
+ }
65
166
  if (q.type === 'text')
66
167
  body.push(
67
- form.field(t.placeholder, q.placeholder, (v) => (q.placeholder = v), {
168
+ form.field(t.placeholder, q.placeholder, v => (q.placeholder = v), {
68
169
  max: LIMITS.placeholderMax,
69
170
  hint: t.placeholderHint,
70
- }),
171
+ })
71
172
  );
72
- if (q.type !== 'text') body.push(form.toggle(t.shuffle, q.shuffle, (v) => (q.shuffle = v)));
173
+ if (!INLINE_ANSWER_TYPES.includes(q.type)) body.push(answerField(q));
174
+ if (q.type !== 'text') body.push(form.toggle(t.shuffle, q.shuffle, v => (q.shuffle = v)));
73
175
  body.push(
74
- form.toggle(t.explanationOn, q.explanation?.enabled, (v) => {
176
+ form.toggle(t.explanationOn, q.explanation?.enabled, v => {
75
177
  q.explanation = { ...(q.explanation ?? { text: '' }), enabled: v };
76
178
  render();
77
- }),
179
+ })
78
180
  );
79
181
  if (q.explanation?.enabled)
80
- body.push(
81
- form.markdownField(t.explanation, q.explanation.text, (v) => (q.explanation.text = v)),
82
- );
182
+ body.push(form.markdownField(t.explanation, q.explanation.text, v => (q.explanation.text = v)));
83
183
  return body;
84
184
  }
85
185
 
@@ -93,47 +193,77 @@ function questionCard(q, i) {
93
193
  body: questionFields(q, i),
94
194
  },
95
195
  {
96
- type: (type) => {
196
+ type: type => {
97
197
  draft.questions[i] = convertType(q, type, texts.defaults);
198
+ // 유형이 바뀌면 답 모양이 달라지므로 정답을 다시 고른다
199
+ delete answers[q.id];
98
200
  render();
99
201
  },
100
202
  up: () => swap(draft.questions, i, i - 1),
101
203
  down: () => swap(draft.questions, i, i + 1),
102
204
  remove: () => {
103
205
  draft.questions.splice(i, 1);
206
+ delete answers[q.id];
104
207
  render();
105
208
  },
106
- },
209
+ }
107
210
  );
108
211
  }
109
212
 
110
213
  function render() {
111
214
  root.replaceChildren(
112
- form.field(t.quizTitle, draft.title, (v) => (draft.title = v), { required: true }),
113
- form.markdownField(t.quizDescription, draft.description, (v) => (draft.description = v)),
215
+ templates.answersIntro({ text: unreadable ? `${a.unreadable} ${a.intro}` : a.intro }),
216
+ form.field(t.quizTitle, draft.title, v => (draft.title = v), { required: true }),
217
+ form.markdownField(t.quizDescription, draft.description, v => (draft.description = v)),
114
218
  ...draft.questions.map(questionCard),
115
- form.addQuestion(() => {
116
- draft.questions.push(
117
- newQuestion(
118
- 'select_one',
119
- draft.questions.map((q) => q.id),
120
- texts.defaults,
121
- ),
122
- );
123
- render();
124
- }),
219
+ // 퀴즈 하나에 문항 하나: 문항이 있으면 "문항 추가" 대신 안내 (이미 여러 문항으로 저장된 퀴즈도 편집 · 저장은 됨)
220
+ canAddQuestion(draft.questions)
221
+ ? form.addQuestion(() => {
222
+ draft.questions.push(
223
+ newQuestion(
224
+ 'select_one',
225
+ draft.questions.map(q => q.id),
226
+ texts.defaults
227
+ )
228
+ );
229
+ render();
230
+ })
231
+ : templates.singleQuestion({ text: t.singleQuestion })
125
232
  );
126
233
  save?.markDirty();
127
234
  }
128
235
 
236
+ /**
237
+ * 문제가 있는 문항 카드로 옮기고 문장을 돌려준다.
238
+ * 정답 문제(answer)면 보기 줄에서 고르는 문항은 보기 목록의 첫 정답 칸으로 옮겨 초점을 둔다
239
+ */
240
+ const problemAt = (problem, { answer = false } = {}) => {
241
+ const card = form.cardAt(problem.questionIndex);
242
+ const pick = answer ? card?.querySelector('[data-role="answer"]') : null;
243
+ (pick ?? card)?.scrollIntoView({ block: 'center' });
244
+ pick?.focus({ preventScroll: true });
245
+ return problem.message;
246
+ };
247
+
129
248
  render();
130
249
  save = app.useSave({
131
250
  label: t.done,
132
251
  getContent: () => structuredClone(draft),
133
- validate: (content) => {
252
+ validate: content => {
134
253
  const problem = validateQuiz(content, texts.validation);
135
- if (!problem) return true;
136
- form.cardAt(problem.questionIndex)?.scrollIntoView({ block: 'center' });
137
- return problem.message;
254
+ return problem ? problemAt(problem) : true;
255
+ },
256
+ // 정답 → 정답 정규식. 검증(정답 · 지운 보기 → 정규식 공통 검사 → 왕복 · 오답)을 통과해야 저장한다
257
+ getGrading: () => {
258
+ const { questions } = draft;
259
+ const missing = validateAnswerKey(questions, answers, a.validation);
260
+ if (missing) return problemAt(missing, { answer: true });
261
+ const answerKey = buildAnswerKey(questions, answers);
262
+ const base = questions.map(q => (q.type === 'text' ? (answers[q.id] ?? [])[0] : answers[q.id]));
263
+ const regexProblem = validateAnswerRegex(answerKey, [joinAnswers(questions, base)]);
264
+ if (regexProblem) return regexProblem;
265
+ const keyProblem = checkAnswerKey(questions, answers, answerKey, a.validation);
266
+ if (keyProblem) return problemAt(keyProblem, { answer: true });
267
+ return { type: 'pattern', answer_key: answerKey };
138
268
  },
139
269
  });