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

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 (81) hide show
  1. package/README.md +158 -138
  2. package/es/cli.js +88 -33
  3. package/es/commands/build/index.d.ts +1 -1
  4. package/es/commands/build/index.js +16 -6
  5. package/es/commands/check/index.d.ts +8 -2
  6. package/es/commands/check/index.js +45 -5
  7. package/es/commands/create/index.d.ts +2 -0
  8. package/es/commands/create/index.js +28 -3
  9. package/es/commands/create/scaffold.d.ts +2 -0
  10. package/es/commands/create/scaffold.js +10 -6
  11. package/es/commands/dev/index.d.ts +1 -1
  12. package/es/commands/dev/index.js +6 -2
  13. package/es/commands/doctor/index.d.ts +11 -0
  14. package/es/commands/doctor/index.js +155 -26
  15. package/es/commands/mcp/index.d.ts +134 -0
  16. package/es/commands/mcp/index.js +399 -0
  17. package/es/commands/setup/index.d.ts +40 -0
  18. package/es/commands/setup/index.js +157 -0
  19. package/es/commands/skill/index.d.ts +2 -5
  20. package/es/commands/skill/index.js +1 -29
  21. package/es/core/config.d.ts +63 -19
  22. package/es/core/config.js +108 -32
  23. package/es/core/prepare.js +3 -5
  24. package/es/core/project-check.d.ts +15 -0
  25. package/es/core/project-check.js +26 -0
  26. package/es/core/templates.d.ts +25 -0
  27. package/es/core/templates.js +41 -0
  28. package/es/dev/grading.d.ts +14 -7
  29. package/es/dev/grading.js +27 -13
  30. package/es/dev/host-page.d.ts +1 -1
  31. package/es/dev/host-page.js +33 -33
  32. package/es/dev/mock-api.d.ts +20 -4
  33. package/es/dev/mock-api.js +70 -9
  34. package/es/dev/server.d.ts +7 -0
  35. package/es/dev/server.js +84 -23
  36. package/es/rules/check.js +56 -7
  37. package/es/rules/index.d.ts +1 -1
  38. package/es/rules/index.js +1 -1
  39. package/es/rules/manifest.d.ts +23 -9
  40. package/es/rules/manifest.js +60 -35
  41. package/es/rules/node.js +3 -1
  42. package/es/rules/semver.d.ts +5 -0
  43. package/es/rules/semver.js +32 -0
  44. package/es/rules/types.d.ts +27 -6
  45. package/es/rules.json.js +1 -1
  46. package/guides/content-development.md +136 -49
  47. package/package.json +2 -2
  48. package/rules.json +62 -7
  49. package/skills/_shared/always.md +3 -1
  50. package/skills/elice-content-check/SKILL.md +1 -1
  51. package/skills/elice-content-create/SKILL.md +4 -4
  52. package/skills/elice-content-migrate/SKILL.md +1 -1
  53. package/skills/elice-content-publish/SKILL.md +22 -0
  54. package/templates/_shared/lib/cdk-mock.d.ts +21 -3
  55. package/templates/_shared/lib/cdk-mock.js +239 -80
  56. package/templates/_shared/lib/cdk.js +2 -2
  57. package/templates/_shared/lib/elice-content.css +196 -0
  58. package/templates/_shared/lib/elice-content.d.ts +110 -5
  59. package/templates/_shared/lib/elice-content.js +643 -38
  60. package/templates/blank/README.md +12 -3
  61. package/templates/blank/completion.html +15 -0
  62. package/templates/blank/elice.config.json +3 -5
  63. package/templates/blank/gitignore +1 -0
  64. package/templates/blank/screens/completion.js +7 -0
  65. package/templates/blank/screens/edit.js +3 -0
  66. package/templates/blank/template.json +6 -0
  67. package/templates/quiz/README.md +35 -28
  68. package/templates/quiz/content.json +17 -63
  69. package/templates/quiz/core/behaviors.d.ts +5 -0
  70. package/templates/quiz/core/behaviors.js +12 -0
  71. package/templates/quiz/core/model.d.ts +27 -1
  72. package/templates/quiz/core/model.js +199 -4
  73. package/templates/quiz/elice.config.json +1 -6
  74. package/templates/quiz/gitignore +1 -0
  75. package/templates/quiz/grading.json +1 -10
  76. package/templates/quiz/screens/edit.js +105 -31
  77. package/templates/quiz/screens/learn.js +7 -8
  78. package/templates/quiz/template.json +6 -0
  79. package/templates/quiz/ui/templates/edit.d.ts +2 -0
  80. package/templates/quiz/ui/templates/edit.js +16 -9
  81. package/templates/quiz/ui/texts.js +52 -27
@@ -3,24 +3,32 @@
3
3
  *
4
4
  * 화면은 누가 보는지(학생 · 교육자 · 튜터)나 미리보기인지 몰라도 됩니다.
5
5
  * 학생 화면: app.useSubmit({ getAnswer, setAnswer, validate })
6
- * 편집 화면: app.useSave({ getContent, validate })
6
+ * 편집 화면: app.useSave({ getContent, getGrading, validate }) · 채점 방식과 답: app.useGradingBlock() (퀴즈가 아닌 자료)
7
+ * 완료 정책 화면: app.useCompletion() (metadata completionPolicies 안에서 고르고 SDK saveCompletionPolicy로 저장)
8
+ * 여러 단계: app.usePaging({ count, onChange }) (옆 화살표 · n / N, 첫 · 마지막 단계에서 이전 · 다음 자료)
7
9
  * 읽기 전용 잠금, 답 복원, 결과·오류 안내, 저장 문구, 로컬 mock 표시는 키트가 합니다.
8
10
  *
9
11
  * 화면(screens/*.js)은 이 키트만 부릅니다. 키트가 SDK로 인증 · 화면 확인 · 내용 불러오기 ·
10
12
  * 제출 · 저장 · 오류 안내를 처리합니다. SDK는 둘 중 하나를 자동으로 고릅니다.
11
13
  *
12
14
  * real lib/cdk.js (@eliceio/cdk 1.x) 플랫폼에서 열 때 (#token=, 편집기 #preview=1 · #edit=1)
15
+ * 편집 화면은 edit 토큰으로 열려 '저장'이 서버에 바로 저장
13
16
  * mock lib/cdk-mock.js (같은 인터페이스) 그 밖 (로컬): 로컬 채점, 화면 사이 저장 공유
14
17
  *
15
18
  * 바꾸기: 주소에 ?sdk=mock 또는 ?sdk=real, 또는 start({ screen, sdk: 'mock' })
16
- * 로컬에서 보는 사람 바꾸기 (mock): #viewer=tutor (student · instructor · tutor), 미리보기: #preview=1
19
+ * 로컬에서 보는 사람 바꾸기 (mock): #viewer=tutor (student · instructor · tutor), 미리보기: #preview=1,
20
+ * 편집 화면: #scope=edit (저장되는 편집 화면) · #edit=1 (저장 전 업로드라 저장 안 됨)
17
21
  *
18
22
  * import { start } from '../lib/elice-content.js';
19
23
  * const app = await start({ screen: 'learn' });
20
24
  * app.content // 편집 화면(CMS)이 저장한 내용, 없으면 content.json
21
25
  * await app.submit(answer)
22
26
  *
23
- * 정답은 콘텐츠에 넣지 않습니다. 채점은 서버가 편집 화면의 채점 설정으로 합니다.
27
+ * 정답은 콘텐츠(zip)에 넣지 않습니다. 채점은 서버가 채점 설정(settings.grading)으로 합니다 (ADR 0009).
28
+ * 채점 설정 { type: pattern | rubric, answer_key | rubric }은 편집 화면이 edit 토큰으로 저장하고, 서버는 학생에게
29
+ * settings.grading을 내려주지 않습니다. 완료 정책(on_access · on_submit · on_graded)은 settings가 아니라
30
+ * material_version.completion_policy입니다: 자료가 지원하는 정책은 metadata completionPolicies(서버가 첫 값으로 정함)이고,
31
+ * 완료 정책 화면이 그 안에서 SDK saveCompletionPolicy로 바꿉니다 (키트 app.completion.get() · set()).
24
32
  */
25
33
 
26
34
  /**
@@ -29,10 +37,11 @@
29
37
  * 파일 하나로 두 화면을 같이 쓸 수도 있다. 교육자 화면은 교육자만 본다.
30
38
  */
31
39
  const SCREEN_ALLOWED = {
32
- learn: (sdk) => sdk.screen === 'learn' || sdk.screen === 'instructor',
33
- instructor: (sdk) =>
40
+ learn: sdk => sdk.screen === 'learn' || sdk.screen === 'instructor',
41
+ instructor: sdk =>
34
42
  (sdk.screen === 'learn' || sdk.screen === 'instructor') && sdk.viewer === 'instructor',
35
- edit: (sdk) => sdk.screen === 'edit',
43
+ edit: sdk => sdk.screen === 'edit',
44
+ completionPolicy: sdk => sdk.screen === 'completionPolicy',
36
45
  };
37
46
 
38
47
  const MESSAGES = {
@@ -46,6 +55,12 @@ const MESSAGES = {
46
55
  screen_not_supported: '이 화면에서는 할 수 없는 일입니다.',
47
56
  navigation_timeout: '수업 페이지 정보를 받지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
48
57
  permission_denied: '권한이 없습니다.',
58
+ draft_not_saved: '업로드한 자료를 먼저 저장해야 내용을 편집해 저장할 수 있어요.',
59
+ // 서버 코드: 채점 설정(settings.grading) 없이 채점해 완료(on_graded)를 고름
60
+ material_grading_required:
61
+ '채점 방식과 답이 아직 없어 채점해 통과하면 완료로 바꿀 수 없어요. 내용 편집에서 답을 먼저 저장해 주세요.',
62
+ // 서버 코드 (SDK request_failed의 cause): 편집하는 사이 다른 곳에서 자료를 저장함
63
+ material_changed: '그 사이 다른 곳에서 자료가 저장됐어요. 새로고침한 뒤 다시 편집해 주세요.',
49
64
  not_initialized: '아직 준비되지 않았습니다.',
50
65
  request_failed: '서버와 연결하지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
51
66
  // 키트만의 코드: 자료 주소인데 접속 토큰이 없음 (새로고침 · 다른 HTML로 이동하면 SDK가 지운 토큰이 남지 않는다)
@@ -69,20 +84,84 @@ export class ContentError extends Error {
69
84
  /** SDK 오류를 화면이 그대로 보여 줄 수 있는 한국어 메시지로 */
70
85
  function toContentError(err) {
71
86
  if (err instanceof ContentError) return err;
87
+ // 서버 오류 코드는 SDK 오류(request_failed)의 cause.cause.code에 있다 (예: 409 MATERIAL_CHANGED)
88
+ const serverCode = err?.cause?.cause?.code;
89
+ if (serverCode === 'MATERIAL_CHANGED')
90
+ return new ContentError('material_changed', MESSAGES.material_changed, err);
91
+ if (serverCode === 'MATERIAL_GRADING_REQUIRED')
92
+ return new ContentError('material_grading_required', MESSAGES.material_grading_required, err);
72
93
  const code = typeof err?.code === 'string' ? err.code : 'request_failed';
73
94
  return new ContentError(code, MESSAGES[code] ?? MESSAGES.request_failed, err);
74
95
  }
75
96
 
76
97
  const MATERIAL_PATH = /\/materials\/[0-9a-f-]{36}\//i;
77
98
 
99
+ /**
100
+ * 저장된 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }`.
101
+ * 실제 SDK는 응답 키를 camelCase로 바꿔 answer_key가 answerKey로 온다 (보낼 때는 snake_case로, progress G129).
102
+ * 채점 방식이 아닌 값(옛 on_access · on_submit 등)이면 null
103
+ */
104
+ export function normalizeGrading(grading) {
105
+ if (!grading || typeof grading !== 'object') return null;
106
+ if (grading.type === 'pattern') {
107
+ const answerKey = grading.answer_key ?? grading.answerKey;
108
+ return { type: 'pattern', ...(typeof answerKey === 'string' ? { answer_key: answerKey } : {}) };
109
+ }
110
+ if (grading.type === 'rubric')
111
+ return { type: 'rubric', ...(typeof grading.rubric === 'string' ? { rubric: grading.rubric } : {}) };
112
+ return null;
113
+ }
114
+
115
+ /** 완료 정책 값 (서버 material_version.completion_policy) */
116
+ const POLICY_VALUES = Object.freeze(['on_access', 'on_submit', 'on_graded']);
117
+
118
+ /**
119
+ * 완료 정책 읽기 · 바꾸기. 지금 값은 SDK material.completionPolicy, 지원하는 정책은 material.completionPolicies
120
+ * (metadata completionPolicies. 서버가 아직 돌려주지 않으면 null, G132), 저장은 SDK saveCompletionPolicy
121
+ * (PATCH completion_policy, 완료 정책 화면에서만). 값 이름은 서버와 같은 completion_policy
122
+ * @returns {{ readonly policies: string[] | null, get(): Promise<{ completion_policy: string | null, policies: string[] | null }>, set(policy: string): Promise<void> }}
123
+ */
124
+ function completionApi(sdk) {
125
+ const listed = () => {
126
+ const policies = sdk.material?.completionPolicies;
127
+ return Array.isArray(policies) && policies.length > 0 ? policies : null;
128
+ };
129
+ return {
130
+ get policies() {
131
+ return listed();
132
+ },
133
+ async get() {
134
+ return { completion_policy: sdk.material?.completionPolicy ?? null, policies: listed() };
135
+ },
136
+ async set(policy) {
137
+ const policies = listed() ?? POLICY_VALUES;
138
+ if (!policies.includes(policy))
139
+ throw new ContentError(
140
+ 'invalid_input',
141
+ `이 자료가 지원하지 않는 완료 정책입니다: ${policy} (가능: ${policies.join(', ')})`
142
+ );
143
+ try {
144
+ await sdk.saveCompletionPolicy(policy);
145
+ } catch (err) {
146
+ throw toContentError(err);
147
+ }
148
+ },
149
+ };
150
+ }
151
+
78
152
  /** 로컬 mock에서 화면별 기본 fragment (보는 사람 · 설정 화면) */
79
- const LOCAL_MOCK_HASH = { learn: '', instructor: 'viewer=instructor', edit: 'edit=1' };
153
+ const LOCAL_MOCK_HASH = {
154
+ learn: '',
155
+ instructor: 'viewer=instructor',
156
+ edit: 'scope=edit',
157
+ completionPolicy: 'scope=edit&screen=completionPolicy',
158
+ };
80
159
 
81
- /** 토큰 없는 draft: 편집기 미리보기 · 설정 화면 */
82
- const DRAFT_HASH = /(?:^#|&)(?:preview|edit)=1/;
83
- const LAUNCH_HASH = /(?:^#|&)(?:token|preview|edit)=/;
160
+ /** 토큰 없는 draft: 편집기 미리보기 · 편집 화면 · 완료 정책 화면 */
161
+ const DRAFT_HASH = /(?:^#|&)(?:preview|edit|completionPolicy)=1/;
162
+ const LAUNCH_HASH = /(?:^#|&)(?:token|preview|edit|completionPolicy)=/;
84
163
 
85
- const isLoopback = (h) => h === 'localhost' || h === '127.0.0.1' || h === '[::1]';
164
+ const isLoopback = h => h === 'localhost' || h === '127.0.0.1' || h === '[::1]';
86
165
 
87
166
  /**
88
167
  * 어떤 SDK를 쓸지. ?sdk=가 있으면 그대로, 플랫폼 주소(토큰 · 편집기 미리보기)면 real, 그 밖은 mock.
@@ -103,7 +182,8 @@ export function pickSdk({ hash, pathname, search, hostname = '' }) {
103
182
 
104
183
  /** mock: 주소에 보는 사람 · 미리보기 · 설정 화면이 없으면 화면에 맞게 */
105
184
  function mockLaunch(hash, screen) {
106
- if (/(?:^#|&)(?:viewer|preview|edit)=/.test(hash)) return { hash, pathname: '/', local: true };
185
+ if (/(?:^#|&)(?:viewer|preview|edit|completionPolicy|scope)=/.test(hash))
186
+ return { hash, pathname: '/', local: true };
107
187
  const parts = [LOCAL_MOCK_HASH[screen], hash.replace(/^#/, '')].filter(Boolean);
108
188
  return { hash: parts.length ? `#${parts.join('&')}` : '', pathname: '/', local: true };
109
189
  }
@@ -131,9 +211,7 @@ async function loadRealSdk() {
131
211
  script.src = new URL('./cdk.js', import.meta.url).href;
132
212
  script.onload = resolve;
133
213
  script.onerror = () =>
134
- reject(
135
- new ContentError('request_failed', 'SDK 파일(lib/cdk.js)을 불러오지 못했습니다.'),
136
- );
214
+ reject(new ContentError('request_failed', 'SDK 파일(lib/cdk.js)을 불러오지 못했습니다.'));
137
215
  document.head.append(script);
138
216
  });
139
217
  return globalThis.elice.EliceCDK;
@@ -157,7 +235,12 @@ export function resolveLaunch(hash, pathname, screen) {
157
235
  return { hash, pathname: local ? LOCAL_MATERIAL_PATH : pathname, local };
158
236
  }
159
237
  return {
160
- hash: screen === 'edit' ? '#edit=1' : '#preview=1',
238
+ hash:
239
+ screen === 'edit'
240
+ ? '#edit=1'
241
+ : screen === 'completionPolicy'
242
+ ? '#completionPolicy=1'
243
+ : '#preview=1',
161
244
  pathname: LOCAL_MATERIAL_PATH,
162
245
  local: true,
163
246
  };
@@ -165,7 +248,7 @@ export function resolveLaunch(hash, pathname, screen) {
165
248
 
166
249
  /**
167
250
  * @typedef {object} StartOptions
168
- * @property {'learn' | 'instructor' | 'edit'} screen 이 HTML이 어떤 화면인지
251
+ * @property {'learn' | 'instructor' | 'edit' | 'completionPolicy'} screen 이 HTML이 어떤 화면인지
169
252
  * @property {string} [defaults] 저장된 내용이 없을 때 쓸 내용 파일 (기본 'content.json')
170
253
  * @property {(error: ContentError) => void} [onError] 화면 밖 오류(세션 만료 등)를 받을 함수. 기본은 상단 알림
171
254
  * @property {'real' | 'mock' | object} [sdk] SDK 고르기 (기본: pickSdk). 객체면 그대로 씀 (테스트)
@@ -214,7 +297,7 @@ export async function start(options) {
214
297
  } else sdk = new (await loadRealSdk())({ onSessionExpired, ...devApi() });
215
298
  if (kind === 'mock' && typeof console !== 'undefined')
216
299
  console.info(
217
- '[elice-content] mock SDK 사용 중 (실제 서버에 저장되지 않음). 실제 SDK: ?sdk=real',
300
+ '[elice-content] mock SDK 사용 중 (실제 서버에 저장되지 않음). 실제 SDK: ?sdk=real'
218
301
  );
219
302
  } catch (err) {
220
303
  const e = toContentError(err);
@@ -237,16 +320,21 @@ export async function start(options) {
237
320
  if (!SCREEN_ALLOWED[screen](sdk)) {
238
321
  const e = new ContentError(
239
322
  'screen_not_supported',
240
- `이 파일은 ${screen} 화면인데 ${sdk.screen} 화면(보는 사람 ${viewer})으로 열렸습니다. metadata.json의 진입 파일을 확인해 주세요.`,
323
+ `이 파일은 ${screen} 화면인데 ${sdk.screen} 화면(보는 사람 ${viewer})으로 열렸습니다. metadata.json의 진입 파일을 확인해 주세요.`
241
324
  );
242
325
  notify(e);
243
326
  throw e;
244
327
  }
245
328
 
246
- const saved = sdk.material?.settings;
247
- const loadJson = options.loadJson ?? ((url) => fetch(url).then((r) => (r.ok ? r.json() : {})));
248
- let content =
249
- saved && Object.keys(saved).length > 0 ? saved : await loadJson(defaults).catch(() => ({}));
329
+ // 저장된 settings에서 채점 설정(grading, edit 범위에만 옴)을 떼어 둔다: 화면 내용(content)은 grading 없이,
330
+ // grading만 저장된 자료는 내용이 없는 것으로 보고 content.json을 쓴다
331
+ const { grading: rawGrading = null, ...saved } = sdk.material?.settings ?? {};
332
+ const savedGrading = normalizeGrading(rawGrading);
333
+ const loadJson = options.loadJson ?? (url => fetch(url).then(r => (r.ok ? r.json() : {})));
334
+ let content = Object.keys(saved).length > 0 ? saved : await loadJson(defaults).catch(() => ({}));
335
+ let grading = savedGrading;
336
+ /** 다음 저장의 바탕: 서버에 저장된 settings 그대로 (content.json 기본값은 넣지 않음) */
337
+ let savedSettings = sdk.material?.settings ?? {};
250
338
 
251
339
  const readOnly = viewer === 'tutor';
252
340
  const app = {
@@ -278,6 +366,13 @@ export async function start(options) {
278
366
  get content() {
279
367
  return content;
280
368
  },
369
+ /**
370
+ * 저장된 채점 설정 `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }` 또는 null.
371
+ * edit 범위(편집 · 완료 정책 화면)에서만 오고, 학생 · 튜터 · 교육자 화면에는 서버가 내려주지 않는다
372
+ */
373
+ get grading() {
374
+ return grading;
375
+ },
281
376
 
282
377
  /** 답 제출 → 서버 채점 결과 { isCorrect, score } (점수 없는 채점이면 둘 다 null). 보통은 useSubmit을 쓴다 */
283
378
  async submit(answer) {
@@ -306,18 +401,35 @@ export async function start(options) {
306
401
  }
307
402
  },
308
403
 
309
- /** 내용 저장 (편집 화면): SDK saveSettings로 편집 페이지에 넘긴다. 보통은 useSave를 쓴다 */
310
- async saveContent(next) {
404
+ /**
405
+ * 내용 저장 (편집 화면): SDK saveSettings가 edit 토큰으로 서버에 바로 저장한다. 보통은 useSave를 쓴다.
406
+ * nextGrading(채점 설정 `{ type, answer_key | rubric }`)을 주면 settings.grading으로 같이 저장하고,
407
+ * 주지 않으면 저장된 채점 설정을 그대로 둔다
408
+ * @param {Record<string, unknown>} next
409
+ * @param {{ type: 'pattern' | 'rubric', answer_key?: string, rubric?: string }} [nextGrading]
410
+ */
411
+ async saveContent(next, nextGrading) {
311
412
  if (screen !== 'edit')
312
413
  throw new ContentError('screen_not_supported', '내용은 편집 화면에서만 저장합니다.');
313
414
  try {
314
- await sdk.saveSettings(next);
415
+ const g = nextGrading ?? grading;
416
+ const settings = g ? { ...next, grading: g } : next;
417
+ await sdk.saveSettings(settings);
315
418
  content = next;
419
+ grading = g;
420
+ savedSettings = settings;
316
421
  } catch (err) {
317
422
  throw toContentError(err);
318
423
  }
319
424
  },
320
425
 
426
+ /**
427
+ * 완료 정책 (on_access · on_submit · on_graded). settings가 아니라 material_version.completion_policy:
428
+ * policies는 metadata completionPolicies, set은 SDK saveCompletionPolicy (완료 정책 화면에서만).
429
+ * 보통은 완료 정책 화면에서 useCompletion을 쓴다
430
+ */
431
+ completion: completionApi(sdk),
432
+
321
433
  /**
322
434
  * 학생 화면의 제출 영역. 화면은 답을 모으고 채우는 방법만 알려 주면, 보는 사람별 처리는 키트가 한다.
323
435
  * - 튜터링: 화면을 읽기 전용으로 잠그고 학생 답을 채움, 제출 버튼 없음
@@ -336,6 +448,36 @@ export async function start(options) {
336
448
  useSave(opts) {
337
449
  return mountSave(app, opts);
338
450
  },
451
+
452
+ /**
453
+ * 편집 화면의 채점 방식 · 답 블록 (퀴즈가 아닌 자료, ADR 0009). LXP 설정 탭과 같은 문구로 채점 방식(기준 답안 정규식 ·
454
+ * 평가 기준)을 고르고 입력한다. 돌려준 getGrading을 useSave({ getGrading })에 넘기면 내용과 함께 저장된다.
455
+ * 퀴즈처럼 문항 구조가 있는 화면은 이 블록 대신 문항별로 답을 받아 정규식을 만든다
456
+ * @param {GradingBlockOptions} [opts]
457
+ */
458
+ useGradingBlock(opts) {
459
+ return mountGradingBlock(app, opts ?? {});
460
+ },
461
+
462
+ /**
463
+ * 완료 정책 화면 (LXP 설정 탭의 완료 정책 영역, ADR 0009). 정책 라디오 · 저장 버튼 · 변경 표시를 키트가 한다.
464
+ * metadata completionPolicies 안의 정책만 보이고, 저장은 app.completion.set (SDK saveCompletionPolicy).
465
+ * completionPolicies가 하나(고정)인 자료는 이 화면을 두지 않는다
466
+ * @param {CompletionOptions} [opts]
467
+ */
468
+ useCompletion(opts) {
469
+ return mountCompletion(app, opts ?? {});
470
+ },
471
+
472
+ /**
473
+ * 자료 안 여러 단계 이동. 내용 양옆 동그란 화살표 + 안쪽 `n / N` 표시.
474
+ * 첫 단계의 왼쪽 · 마지막 단계의 오른쪽은 LXP 이전 · 다음 수업 자료로 가는 버튼(모양이 다름)이 되고,
475
+ * 그쪽 수업 자료가 없거나 LXP 밖이면 숨긴다. LXP 아래 이전 · 다음 막대와 헷갈리지 않게 아래 막대는 만들지 않는다.
476
+ * @param {PagingOptions} opts
477
+ */
478
+ usePaging(opts) {
479
+ return mountPaging(app, opts);
480
+ },
339
481
  };
340
482
  if (options.status !== false) showStatus(app);
341
483
  return app;
@@ -351,16 +493,26 @@ export async function start(options) {
351
493
  * @property {string} [label] 버튼 글자 (기본 '제출')
352
494
  */
353
495
 
496
+ /**
497
+ * @typedef {object} PagingOptions
498
+ * @property {number} count 단계 수 (1 이상)
499
+ * @property {(step: number) => void} onChange 단계가 바뀔 때 (0부터). 시작할 때도 한 번
500
+ * @property {number} [start] 처음 단계 (기본 0)
501
+ * @property {Element} [root] 화살표를 붙일 영역 (기본 #app)
502
+ */
503
+
354
504
  /**
355
505
  * @typedef {object} SaveOptions
356
506
  * @property {() => Record<string, unknown>} getContent 저장할 내용 (학생에게 공개, 정답 넣지 않음)
507
+ * @property {() => object | string | undefined} [getGrading] 같이 저장할 채점 방식 · 답 (settings.grading에 합침, 학생에게 안 감).
508
+ * 문장이면 저장을 막고 보여 줌, undefined면 채점 설정은 그대로 (ADR 0009)
357
509
  * @property {(content: Record<string, unknown>) => true | string} [validate]
358
510
  * @property {Element} [root] 변경을 지켜볼 화면 영역 (기본 #app)
359
511
  * @property {string} [label] 버튼 글자 (기본 '저장')
360
512
  */
361
513
 
362
514
  const h = (tag, props = {}) => Object.assign(document.createElement(tag), props);
363
- const appRoot = (root) => root ?? document.getElementById('app') ?? document.body;
515
+ const appRoot = root => root ?? document.getElementById('app') ?? document.body;
364
516
 
365
517
  /**
366
518
  * 화면 맨 위 안내 한 줄. 로컬 개발용 mock SDK일 때만 (실제 서버에 저장되지 않는다는 것과 보는 사람).
@@ -369,6 +521,7 @@ const appRoot = (root) => root ?? document.getElementById('app') ?? document.bod
369
521
  export function statusText(app) {
370
522
  if (app.sdkKind !== 'mock') return '';
371
523
  if (app.screen === 'edit') return 'mock SDK · 저장 내용은 이 브라우저에만';
524
+ if (app.screen === 'completionPolicy') return 'mock SDK · 완료 정책은 이 브라우저에만';
372
525
  const parts = ['mock SDK · 로컬 채점, 서버에 저장되지 않음'];
373
526
  if (app.viewer === 'tutor')
374
527
  parts.push(`튜터링 · ${app.account?.fullname ?? '학생'}의 화면 (읽기 전용)`);
@@ -390,7 +543,9 @@ function showStatus(app) {
390
543
  function resultText(r) {
391
544
  // 점수 없는 채점(manual · none): 교육자가 매긴 점수는 나중에 결과로 보인다
392
545
  if (r.score === null || r.score === undefined) return '제출했어요.';
393
- return r.isCorrect ? `모두 맞았어요. ${r.score}점` : `${r.score}점이에요. 다시 풀어 볼 수 있어요.`;
546
+ return r.isCorrect
547
+ ? `모두 맞았어요. ${r.score}점`
548
+ : `${r.score}점이에요. 다시 풀어 볼 수 있어요.`;
394
549
  }
395
550
 
396
551
  function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, label = '제출' }) {
@@ -423,7 +578,7 @@ function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, labe
423
578
  setAnswer || onResult
424
579
  ? app
425
580
  .lastSubmission()
426
- .then((last) => {
581
+ .then(last => {
427
582
  if (!last) return;
428
583
  if (setAnswer && last.answer !== null && last.answer !== undefined)
429
584
  setAnswer(last.answer);
@@ -457,22 +612,127 @@ function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, labe
457
612
  return { element: bar, result, restored };
458
613
  }
459
614
 
460
- function mountSave(app, { getContent, validate, root, label = '저장' }) {
615
+ /** LXP 이전 · 다음 수업 자료가 있는지. 답이 없거나(LXP 밖 · 미리보기 · 시간 초과) 오류면 없음 */
616
+ async function hasLecturePage(app, side) {
617
+ const nav = app.navigation;
618
+ if (!nav) return false;
619
+ try {
620
+ return Boolean(await (side === 'prev' ? nav.getHasPrevious() : nav.getHasNext()));
621
+ } catch {
622
+ return false;
623
+ }
624
+ }
625
+
626
+ function mountPaging(app, { count, onChange, start = 0, root }) {
627
+ const area = appRoot(root);
628
+ const total = Math.max(1, Math.floor(count));
629
+ let step = Math.min(Math.max(0, Math.floor(start)), total - 1);
630
+ const edge = { prev: false, next: false };
631
+ const button = (side) =>
632
+ h('button', { type: 'button', className: `ec-step-nav ${side}` });
633
+ const prev = button('prev');
634
+ const next = button('next');
635
+ const counter = h('p', { className: 'ec-step-count' });
636
+ counter.setAttribute('aria-live', 'polite');
637
+ // 키트 틀(.ec-paging)이 내용 영역을 감싼다: 버튼 · n / N은 틀에, 화면 코드는 내용 영역(기본 #app)에만 그린다.
638
+ // 그래서 화면 코드가 #app을 replaceChildren · innerHTML로 다시 그려도 버튼이 지워지지 않는다
639
+ let frame;
640
+ if (area === document.body || !area.parentNode) {
641
+ // 감쌀 수 없는 영역(body)이면 그 안에 붙인다 (다시 그리면 지워짐)
642
+ frame = area;
643
+ area.append(prev, next, counter);
644
+ } else {
645
+ frame = h('div', { className: 'ec-paging-frame' });
646
+ area.before(frame);
647
+ frame.append(prev, next, area, counter);
648
+ }
649
+ frame.classList.add('ec-paging');
650
+ area.classList.add('ec-step-content');
651
+
652
+ // 단계 안: 동그란 화살표만. 끝에서 나가는 버튼: 글자 있는 알약 모양(이전 자료 · 다음 자료)
653
+ const paint = (el, side, leaving, available) => {
654
+ const arrow = side === 'prev' ? '‹' : '›';
655
+ el.classList.toggle('leave', leaving);
656
+ el.hidden = leaving && !available;
657
+ if (leaving) {
658
+ const text = side === 'prev' ? '이전 자료' : '다음 자료';
659
+ el.textContent = side === 'prev' ? `${arrow} ${text}` : `${text} ${arrow}`;
660
+ el.setAttribute('aria-label', `${text}로 이동 (이 자료를 나갑니다)`);
661
+ el.title = `LXP ${side === 'prev' ? '이전' : '다음'} 수업 자료로 이동`;
662
+ } else {
663
+ el.textContent = arrow;
664
+ el.setAttribute('aria-label', side === 'prev' ? '이전 단계' : '다음 단계');
665
+ el.removeAttribute('title');
666
+ }
667
+ };
668
+ const render = () => {
669
+ paint(prev, 'prev', step === 0, edge.prev);
670
+ paint(next, 'next', step === total - 1, edge.next);
671
+ counter.textContent = `${step + 1} / ${total}`;
672
+ };
673
+ const go = (i) => {
674
+ const to = Math.min(Math.max(0, i), total - 1);
675
+ if (to === step) return;
676
+ step = to;
677
+ render();
678
+ onChange(step, { content: area });
679
+ };
680
+ const leave = (side) => {
681
+ try {
682
+ if (side === 'prev') app.navigation?.previous();
683
+ else app.navigation?.next();
684
+ } catch {
685
+ // 화면이 이동을 지원하지 않으면(편집 화면 등) 아무것도 하지 않는다
686
+ }
687
+ };
688
+ prev.addEventListener('click', () => (step === 0 ? leave('prev') : go(step - 1)));
689
+ next.addEventListener('click', () => (step === total - 1 ? leave('next') : go(step + 1)));
690
+
691
+ render();
692
+ onChange(step, { content: area });
693
+ const ready = Promise.all([hasLecturePage(app, 'prev'), hasLecturePage(app, 'next')]).then(
694
+ ([p, n]) => {
695
+ edge.prev = p;
696
+ edge.next = n;
697
+ render();
698
+ },
699
+ );
700
+ return {
701
+ element: frame,
702
+ content: area,
703
+ ready,
704
+ go,
705
+ get step() {
706
+ return step;
707
+ },
708
+ };
709
+ }
710
+
711
+ function mountSave(app, { getContent, getGrading, validate, root, label = '저장' }) {
461
712
  if (app.screen !== 'edit') throw new Error('useSave는 편집 화면(screen: edit)에서만 씁니다.');
462
713
  const area = appRoot(root);
463
714
  const status = h('p', { className: 'ec-muted', role: 'status' });
464
715
  const button = h('button', { className: 'ec-primary', type: 'button', textContent: label });
465
716
  const bar = h('div', { className: 'ec-submitbar' });
466
717
  bar.append(status, button);
467
- area.after(bar);
718
+ // 채점 방식 블록(useGradingBlock)이 화면 영역 바로 뒤에 있으면 그 뒤에 둔다
719
+ let anchor = area;
720
+ while (anchor.nextElementSibling?.classList.contains('ec-grading')) anchor = anchor.nextElementSibling;
721
+ anchor.after(bar);
468
722
 
469
723
  let dirty = false;
470
724
  const markDirty = () => {
471
725
  dirty = true;
726
+ // 이제 이 버튼이 실제 저장이라 (LXP 하단 저장은 settings를 저장하지 않음) 저장 전 상태는 이 문구가 유일한 안내
472
727
  status.textContent = '저장하지 않은 변경이 있어요.';
473
728
  };
474
729
  area.addEventListener('input', markDirty);
475
730
  area.addEventListener('change', markDirty);
731
+ // 채점 방식 블록은 화면 영역 밖에 붙는다: 거기서 바꿔도 저장 전 표시
732
+ const scope = area.parentElement;
733
+ const inBlock = e => e.target instanceof Element && e.target.closest('.ec-grading');
734
+ scope?.addEventListener('input', e => inBlock(e) && markDirty());
735
+ scope?.addEventListener('change', e => inBlock(e) && markDirty());
476
736
  // 문항 추가 · 삭제처럼 입력 없이 화면이 바뀌는 경우
477
737
  if (typeof MutationObserver !== 'undefined') {
478
738
  let ready = false;
@@ -482,17 +742,15 @@ function mountSave(app, { getContent, validate, root, label = '저장' }) {
482
742
  subtree: true,
483
743
  });
484
744
  }
485
- globalThis.addEventListener?.('beforeunload', (e) => {
745
+ globalThis.addEventListener?.('beforeunload', e => {
486
746
  if (dirty) e.preventDefault();
487
747
  });
488
748
 
489
- // 실제 SDK의 saveSettings는 편집 페이지에 넘기기만 한다. 자료를 저장해야 학생 화면에 반영된다
749
+ // 실제 SDK의 saveSettings는 edit 토큰으로 서버에 바로 저장한다 (새 버전, 학생 화면에 바로 반영)
490
750
  const savedText = () =>
491
751
  app.sdkKind === 'mock'
492
752
  ? '저장했어요 (mock · 이 브라우저에만).'
493
- : app.isLocal
494
- ? '로컬 미리보기라 저장되지 않았어요.'
495
- : '편집 페이지에 넘겼어요. 자료를 저장하면 학생 화면에 반영됩니다.';
753
+ : '저장했어요. 학생 화면에 반영됩니다.';
496
754
 
497
755
  button.addEventListener('click', async () => {
498
756
  const next = getContent();
@@ -501,19 +759,366 @@ function mountSave(app, { getContent, validate, root, label = '저장' }) {
501
759
  status.textContent = typeof ok === 'string' ? ok : '내용을 확인해 주세요.';
502
760
  return;
503
761
  }
762
+ const gradingPart = getGrading ? getGrading() : undefined;
763
+ if (typeof gradingPart === 'string') {
764
+ status.textContent = gradingPart;
765
+ return;
766
+ }
767
+ button.disabled = true;
768
+ try {
769
+ await app.saveContent(next, gradingPart ?? undefined);
770
+ dirty = false;
771
+ status.textContent = savedText();
772
+ } catch (e) {
773
+ // 로컬에서 실제 SDK로 연 draft(#edit=1)는 저장할 곳이 없다
774
+ status.textContent =
775
+ e.code === 'draft_not_saved' && app.isLocal
776
+ ? '로컬 미리보기라 저장되지 않았어요.'
777
+ : `저장하지 못했어요: ${e.message}`;
778
+ } finally {
779
+ button.disabled = false;
780
+ }
781
+ });
782
+ return {
783
+ element: bar,
784
+ markDirty,
785
+ get dirty() {
786
+ return dirty;
787
+ },
788
+ };
789
+ }
790
+
791
+ /**
792
+ * @typedef {object} GradingBlockOptions
793
+ * @property {Array<'pattern' | 'rubric'>} [graders] 고를 수 있는 채점 방식 (기본 둘 다)
794
+ * @property {Array<[string, string]>} [examples] '작성 예시 보기'에 보일 [정규식, 뜻] (기본 GRADING_EXAMPLES)
795
+ * @property {Element} [root] 블록을 넣을 곳 (기본: 화면 영역 #app 바로 뒤)
796
+ */
797
+
798
+ /**
799
+ * @typedef {object} CompletionOptions
800
+ * @property {Array<'on_access' | 'on_submit' | 'on_graded'>} [policies] 고를 수 있는 완료 정책
801
+ * (기본 metadata completionPolicies, 서버가 주지 않으면 셋 다)
802
+ * @property {Element} [root] 넣을 곳 (기본: 화면 영역 #app을 이 영역으로 채움)
803
+ * @property {string} [label] 버튼 글자 (기본 '저장')
804
+ */
805
+
806
+ /** 완료 정책 문구 (ADR 0009). 열람 · 제출은 LXP 설정 탭 문구 그대로 (qa5 2026-11-10) */
807
+ export const COMPLETION_POLICIES = Object.freeze({
808
+ on_access: {
809
+ label: '열람 시 학습 완료',
810
+ description: "자료를 열면 학습 완료로 처리됩니다. 학생 화면에는 점수 대신 '완료'로 표시됩니다.",
811
+ },
812
+ on_submit: {
813
+ label: '제출 시 학습 완료',
814
+ description:
815
+ "답과 관계없이 제출하면 학습 완료로 처리됩니다. 학생 화면에는 점수 대신 '완료'로 표시됩니다.",
816
+ },
817
+ on_graded: {
818
+ label: '채점해 통과하면 학습 완료',
819
+ description:
820
+ '제출한 답을 편집 화면에서 정한 채점 방식으로 채점하고, 통과하면 학습 완료로 처리됩니다.',
821
+ },
822
+ });
823
+
824
+ /** 채점 방식 문구 (settings.grading.type, LXP 설정 탭 문구 그대로) */
825
+ export const GRADER_TYPES = Object.freeze({
826
+ pattern: {
827
+ label: '기준 답안과 비교해 채점',
828
+ description: '학생이 제출한 답안을 기준 답안의 패턴과 비교해 채점합니다.',
829
+ },
830
+ rubric: {
831
+ label: '입력한 평가 기준으로 채점',
832
+ description: 'AI가 학생의 답을 읽고 점수를 매깁니다.',
833
+ },
834
+ });
835
+
836
+ /** '작성 예시 보기' 기본 예시: [정규식, 뜻]. 학생 답(앞뒤 공백을 자른 문자열) 전체와 맞으면 정답 */
837
+ export const GRADING_EXAMPLES = Object.freeze([
838
+ ['^서울$', '"서울"만 정답'],
839
+ ['^서울(시|특별시)?$', '"서울" · "서울시" · "서울특별시" 정답'],
840
+ ['^(가중치|weight)$', '"가중치" 또는 "weight" 정답'],
841
+ ['^4[0-9]$', '40 ~ 49 정답'],
842
+ ]);
843
+
844
+ const GRADING_TEXT = {
845
+ heading: '채점 방식',
846
+ headingHelp: '제출한 답을 어떻게 채점할지와 기준 답안 · 평가 기준을 정합니다.',
847
+ answerKey: '기준 답안 (정규표현식)',
848
+ answerKeyPlaceholder: '예: ^서울(시|특별시)?$',
849
+ answerKeyHelp: '정답으로 인정할 답안의 패턴을 입력해 주세요.',
850
+ examples: '작성 예시 보기',
851
+ examplesClose: '작성 예시 닫기',
852
+ rubric: '평가 기준',
853
+ rubricPlaceholder: '예: 핵심 개념 2개 이상을 정확히 설명하면 만점',
854
+ emptyRubric: '평가 기준을 입력해 주세요.',
855
+ };
856
+
857
+ const COMPLETION_TEXT = {
858
+ heading: '완료 정책',
859
+ headingHelp: '학습 완료를 언제 기록할지 고릅니다: 열면, 제출하면, 채점해 통과하면.',
860
+ grader: name => `채점 방식: ${name} (편집 화면에서 정함)`,
861
+ noGrader: '채점 방식과 답이 아직 없습니다. 편집 화면에서 먼저 정해 주세요.',
862
+ loading: '완료 정책을 불러오는 중…',
863
+ };
864
+
865
+ /** 정답 정규식 길이 상한 (서버에 보내는 값, 너무 긴 정규식은 막는다) */
866
+ export const ANSWER_KEY_MAX = 5000;
867
+ /** 정답 정규식 한 번 맞춰 보는 시간 상한(ms). 넘으면 ReDoS 위험으로 막는다 */
868
+ const REGEX_TIME_LIMIT_MS = 50;
869
+
870
+ /**
871
+ * 정답 정규식 공통 검사 (ADR 0009): 비어 있지 않음 · 길이 · 컴파일 · `^…$`로 감쌈(부분 일치 방지) · 실행 시간(ReDoS).
872
+ * samples(맞춰 볼 문자열)도 같이 시간을 잰다. 문제가 없으면 null, 있으면 보여 줄 문장
873
+ * @param {string} regex
874
+ * @param {string[]} [samples]
875
+ * @returns {string | null}
876
+ */
877
+ export function validateAnswerRegex(regex, samples = []) {
878
+ const key = typeof regex === 'string' ? regex.trim() : '';
879
+ if (!key) return '기준 답안(정규표현식)을 입력해 주세요.';
880
+ if (key.length > ANSWER_KEY_MAX)
881
+ return `기준 답안이 너무 깁니다 (${key.length}자, 최대 ${ANSWER_KEY_MAX}자).`;
882
+ let re;
883
+ try {
884
+ re = new RegExp(key);
885
+ } catch (e) {
886
+ return `기준 답안이 올바른 정규표현식이 아닙니다: ${e.message}`;
887
+ }
888
+ if (!key.startsWith('^') || !key.endsWith('$') || /(^|[^\\])(\\\\)*\\\$$/.test(key))
889
+ return '기준 답안은 ^로 시작해 $로 끝나야 합니다 (답 전체와 맞춰야 부분만 맞아도 정답이 되지 않음).';
890
+ const now = () => (typeof performance === 'undefined' ? Date.now() : performance.now());
891
+ const slow = text => {
892
+ const started = now();
893
+ re.test(text);
894
+ return now() - started > REGEX_TIME_LIMIT_MS;
895
+ };
896
+ const tooSlow =
897
+ '기준 답안을 맞춰 보는 데 너무 오래 걸립니다. 반복(*, +)이 겹치지 않게 고쳐 주세요.';
898
+ if (samples.some(slow)) return tooSlow;
899
+ // 겹친 반복(예: (a+)+)은 길이가 늘수록 시간이 두 배씩 는다: 짧은 길이부터 늘려 가며 재고, 느려지면 바로 멈춘다
900
+ // (긴 문자열을 한 번에 넣으면 멈추지 않을 수 있다)
901
+ const chars = [...new Set(key.replace(/\\./g, '').match(/[A-Za-z0-9가-힣%=;,]/g) ?? ['a'])].slice(0, 4);
902
+ for (const c of chars)
903
+ for (let n = 8; n <= 28; n += 2) if (slow(`${c.repeat(n)}\u0000`)) return tooSlow;
904
+ return null;
905
+ }
906
+
907
+ /** 라디오 카드 하나 (LXP 설정 탭 모양) */
908
+ function radioCard(name, value, info, checked) {
909
+ const card = h('label', { className: 'ec-grading-type' });
910
+ const input = h('input', { type: 'radio', name, value, checked });
911
+ const text = h('span', { className: 'ec-grading-text' });
912
+ text.append(
913
+ h('span', { className: 'ec-grading-label', textContent: info.label }),
914
+ h('span', { className: 'ec-muted', textContent: info.description })
915
+ );
916
+ card.append(input, text);
917
+ return { card, input };
918
+ }
919
+
920
+ function mountGradingBlock(app, { graders = ['pattern', 'rubric'], examples = GRADING_EXAMPLES, root }) {
921
+ if (app.screen !== 'edit')
922
+ throw new Error('useGradingBlock은 편집 화면(screen: edit)에서 씁니다.');
923
+ const t = GRADING_TEXT;
924
+ const name = `ec-grader-${Math.random().toString(36).slice(2, 8)}`;
925
+ const section = h('section', { className: 'ec-grading' });
926
+ const head = h('div', { className: 'ec-grading-head' });
927
+ head.append(
928
+ h('h2', { textContent: t.heading }),
929
+ h('p', { className: 'ec-muted', textContent: t.headingHelp })
930
+ );
931
+ const group = h('div', { className: 'ec-grading-types', role: 'radiogroup' });
932
+ group.setAttribute('aria-label', t.heading);
933
+ section.append(head, group);
934
+ if (root) root.append(section);
935
+ else appRoot(undefined).after(section);
936
+
937
+ const saved = app.grading;
938
+ let current = graders.includes(saved?.type) ? saved.type : graders[0];
939
+
940
+ // 기준 답안(pattern): LXP와 같은 정규식 칸 + 작성 예시
941
+ const keyId = `${name}-key`;
942
+ const keyInput = h('input', {
943
+ id: keyId,
944
+ type: 'text',
945
+ placeholder: t.answerKeyPlaceholder,
946
+ spellcheck: false,
947
+ });
948
+ keyInput.className = 'ec-grading-key';
949
+ keyInput.value = saved?.answer_key ?? '';
950
+ const toggle = h('button', { type: 'button', className: 'ec-text-button', textContent: t.examples });
951
+ const exampleList = h('dl', { className: 'ec-grading-examples', hidden: true });
952
+ for (const [regex, meaning] of examples)
953
+ exampleList.append(h('dt', { textContent: regex }), h('dd', { textContent: meaning }));
954
+ toggle.addEventListener('click', () => {
955
+ exampleList.hidden = !exampleList.hidden;
956
+ toggle.textContent = exampleList.hidden ? t.examples : t.examplesClose;
957
+ });
958
+ const labelRow = h('div', { className: 'ec-grading-field-head' });
959
+ labelRow.append(h('label', { textContent: t.answerKey, htmlFor: keyId }), toggle);
960
+ const regexDetail = h('div', { className: 'ec-grading-detail ec-grading-field' });
961
+ regexDetail.append(
962
+ labelRow,
963
+ exampleList,
964
+ keyInput,
965
+ h('p', { className: 'ec-muted', textContent: t.answerKeyHelp })
966
+ );
967
+ // 평가 기준(rubric)
968
+ const rubricId = `${name}-rubric`;
969
+ const rubricInput = h('textarea', { id: rubricId, placeholder: t.rubricPlaceholder, rows: 4 });
970
+ rubricInput.className = 'ec-grading-rubric';
971
+ rubricInput.value = saved?.rubric ?? '';
972
+ const rubricDetail = h('div', { className: 'ec-grading-detail' });
973
+ rubricDetail.append(h('label', { textContent: t.rubric, htmlFor: rubricId }), rubricInput);
974
+ const details = { pattern: regexDetail, rubric: rubricDetail };
975
+
976
+ const cards = graders.map(type => {
977
+ const { card, input } = radioCard(name, type, GRADER_TYPES[type] ?? { label: type, description: '' }, type === current);
978
+ const wrap = h('div', { className: 'ec-grading-item' });
979
+ wrap.append(card, details[type]);
980
+ input.addEventListener('change', () => select(type));
981
+ group.append(wrap);
982
+ return { type, card };
983
+ });
984
+ function select(type) {
985
+ current = type;
986
+ for (const c of cards) c.card.classList.toggle('selected', c.type === type);
987
+ for (const [ty, detail] of Object.entries(details)) detail.hidden = ty !== type;
988
+ }
989
+ select(current);
990
+
991
+ return {
992
+ element: section,
993
+ get grader() {
994
+ return current;
995
+ },
996
+ /** 저장할 채점 설정 `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }`, 문제가 있으면 문장 (useSave getGrading에 넘김) */
997
+ getGrading() {
998
+ if (current === 'pattern') {
999
+ const key = keyInput.value.trim();
1000
+ const problem = validateAnswerRegex(key);
1001
+ return problem ?? { type: 'pattern', answer_key: key };
1002
+ }
1003
+ const rubric = rubricInput.value.trim();
1004
+ return rubric ? { type: 'rubric', rubric } : t.emptyRubric;
1005
+ },
1006
+ };
1007
+ }
1008
+
1009
+ function mountCompletion(app, { policies = app.completion.policies ?? POLICY_VALUES, root, label = '저장' }) {
1010
+ if (app.screen !== 'completionPolicy')
1011
+ throw new Error('useCompletion은 완료 정책 화면(screen: completionPolicy)에서만 씁니다.');
1012
+ const t = COMPLETION_TEXT;
1013
+ const area = appRoot(root);
1014
+ const name = `ec-completion-${Math.random().toString(36).slice(2, 8)}`;
1015
+ const section = h('section', { className: 'ec-grading' });
1016
+ const head = h('div', { className: 'ec-grading-head' });
1017
+ head.append(
1018
+ h('h2', { textContent: t.heading }),
1019
+ h('p', { className: 'ec-muted', textContent: t.headingHelp })
1020
+ );
1021
+ const group = h('div', { className: 'ec-grading-types', role: 'radiogroup' });
1022
+ group.setAttribute('aria-label', t.heading);
1023
+ section.append(head, group);
1024
+ // 완료 정책 화면은 이 영역이 화면 전부라 기본 영역(#app)의 "불러오는 중"을 비운다. root를 주면 그 뒤에 더한다
1025
+ if (root) area.append(section);
1026
+ else area.replaceChildren(section);
1027
+
1028
+ let current = policies[0];
1029
+ const graderInfo = GRADER_TYPES[app.grading?.type];
1030
+
1031
+ // 채점해 통과(on_graded): 편집 화면이 정한 채점 방식을 보여 준다
1032
+ const gradedDetail = h('div', { className: 'ec-grading-detail' });
1033
+ gradedDetail.append(
1034
+ h('p', {
1035
+ className: graderInfo ? 'ec-muted' : 'ec-error',
1036
+ textContent: graderInfo ? t.grader(graderInfo.label) : t.noGrader,
1037
+ })
1038
+ );
1039
+
1040
+ const cards = policies.map(policy => {
1041
+ const { card, input } = radioCard(name, policy, COMPLETION_POLICIES[policy] ?? { label: policy, description: '' }, policy === current);
1042
+ const wrap = h('div', { className: 'ec-grading-item' });
1043
+ wrap.append(card);
1044
+ if (policy === 'on_graded') wrap.append(gradedDetail);
1045
+ input.addEventListener('change', () => select(policy));
1046
+ group.append(wrap);
1047
+ return { policy, card, input };
1048
+ });
1049
+ function select(policy) {
1050
+ current = policy;
1051
+ for (const c of cards) {
1052
+ c.card.classList.toggle('selected', c.policy === policy);
1053
+ c.input.checked = c.policy === policy;
1054
+ }
1055
+ gradedDetail.hidden = policy !== 'on_graded';
1056
+ }
1057
+ select(current);
1058
+
1059
+ const status = h('p', { className: 'ec-muted', role: 'status', textContent: t.loading });
1060
+ const error = h('p', { className: 'ec-error', role: 'alert' });
1061
+ const button = h('button', { className: 'ec-primary', type: 'button', textContent: label, disabled: true });
1062
+ const bar = h('div', { className: 'ec-submitbar' });
1063
+ bar.append(status, error, button);
1064
+ area.after(bar);
1065
+
1066
+ let dirty = false;
1067
+ const markDirty = () => {
1068
+ dirty = true;
1069
+ status.textContent = '저장하지 않은 변경이 있어요.';
1070
+ };
1071
+ area.addEventListener('input', markDirty);
1072
+ area.addEventListener('change', markDirty);
1073
+ globalThis.addEventListener?.('beforeunload', e => {
1074
+ if (dirty) e.preventDefault();
1075
+ });
1076
+
1077
+ // 지금 완료 정책 (완료 정책 API · ecdk dev 흉내). 지원되지 않으면 저장을 막고 이유를 보여 준다
1078
+ const ready = app.completion.get().then(
1079
+ ({ completion_policy: policy }) => {
1080
+ if (policies.includes(policy)) select(policy);
1081
+ status.textContent = '';
1082
+ button.disabled = false;
1083
+ },
1084
+ e => {
1085
+ status.textContent = '';
1086
+ error.textContent = e.message;
1087
+ }
1088
+ );
1089
+
1090
+ const savedText = () =>
1091
+ app.sdkKind === 'mock'
1092
+ ? '저장했어요 (mock · 이 브라우저에만).'
1093
+ : '저장했어요. 다음 제출부터 이 완료 정책을 씁니다.';
1094
+
1095
+ button.addEventListener('click', async () => {
1096
+ if (current === 'on_graded' && !graderInfo) {
1097
+ error.textContent = t.noGrader;
1098
+ return;
1099
+ }
1100
+ error.textContent = '';
504
1101
  button.disabled = true;
1102
+ button.setAttribute('aria-busy', 'true');
505
1103
  try {
506
- await app.saveContent(next);
1104
+ await app.completion.set(current);
507
1105
  dirty = false;
508
1106
  status.textContent = savedText();
509
1107
  } catch (e) {
510
- status.textContent = `저장하지 못했어요: ${e.message}`;
1108
+ status.textContent = '';
1109
+ error.textContent = e.message;
511
1110
  } finally {
512
1111
  button.disabled = false;
1112
+ button.removeAttribute('aria-busy');
513
1113
  }
514
1114
  });
515
1115
  return {
516
1116
  element: bar,
1117
+ /** 지금 완료 정책을 불러온 뒤 끝나는 Promise */
1118
+ ready,
1119
+ get policy() {
1120
+ return current;
1121
+ },
517
1122
  markDirty,
518
1123
  get dirty() {
519
1124
  return dirty;