@eliceio/cdk-cli 1.2.0 → 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.
- package/README.md +69 -60
- package/es/cli.js +11 -2
- package/es/commands/build/index.js +12 -0
- package/es/commands/create/index.js +2 -1
- package/es/commands/create/scaffold.d.ts +2 -2
- package/es/commands/create/scaffold.js +3 -3
- package/es/commands/dev/index.d.ts +10 -1
- package/es/commands/dev/index.js +47 -7
- package/es/core/config.d.ts +20 -9
- package/es/core/config.js +53 -12
- package/es/core/project-check.d.ts +3 -2
- package/es/core/project-check.js +14 -3
- package/es/core/regex.d.ts +11 -0
- package/es/core/regex.js +41 -0
- package/es/core/sandbox.d.ts +26 -0
- package/es/core/sandbox.js +240 -30
- package/es/dev/check.d.ts +30 -0
- package/es/dev/check.js +224 -34
- package/es/dev/grading.d.ts +20 -1
- package/es/dev/grading.js +38 -7
- package/es/dev/host-page.js +1 -1
- package/es/dev/mock-api.d.ts +3 -1
- package/es/dev/mock-api.js +20 -11
- package/es/engines/vite/index.js +1 -1
- package/es/engines/vite/plugin.d.ts +2 -0
- package/es/engines/vite/plugin.js +33 -5
- package/es/rules/answers.d.ts +13 -0
- package/es/rules/answers.js +94 -0
- package/es/rules/check.js +70 -1
- package/es/rules/index.d.ts +1 -0
- package/es/rules/index.js +1 -0
- package/es/rules/size.d.ts +31 -0
- package/es/rules/size.js +58 -0
- package/es/rules/types.d.ts +12 -0
- package/es/rules.json.js +2 -2
- package/package.json +2 -2
- package/rules.json +32 -3
- package/skills/_shared/always.md +3 -3
- package/skills/_shared/references/00-what-the-person-decides.md +1 -1
- package/skills/_shared/references/02-design-the-material.md +10 -7
- package/skills/_shared/references/03-create-the-project.md +2 -1
- package/skills/_shared/references/05-screen-code.md +49 -22
- package/skills/_shared/references/06-using-the-quiz-template.md +7 -6
- package/skills/_shared/references/08-fix-check-errors.md +23 -22
- package/skills/_shared/references/09-check.md +7 -6
- package/skills/_shared/references/12-upload-with-the-material-mcp.md +13 -13
- package/skills/_shared/references/13-edit-screen-design.md +122 -0
- package/skills/_shared/references/14-layouts.md +96 -0
- package/skills/elice-content-check/SKILL.md +2 -2
- package/skills/elice-content-create/SKILL.md +1 -1
- package/skills/elice-content-migrate/SKILL.md +1 -1
- package/templates/_shared/lib/cdk-mock.d.ts +30 -3
- package/templates/_shared/lib/cdk-mock.js +88 -15
- package/templates/_shared/lib/elice-content-editor.js +89 -58
- package/templates/_shared/lib/elice-content.css +1313 -126
- package/templates/_shared/lib/elice-content.d.ts +162 -23
- package/templates/_shared/lib/elice-content.js +865 -84
- package/templates/_shared/lib/icons/empty-content.d.ts +2 -0
- package/templates/_shared/lib/icons/empty-content.js +11 -0
- package/templates/_shared/lib/icons/file-video.d.ts +2 -0
- package/templates/_shared/lib/icons/file-video.js +11 -0
- package/templates/_shared/lib/icons/file.d.ts +2 -0
- package/templates/_shared/lib/icons/file.js +11 -0
- package/templates/blank/README.md +5 -3
- package/templates/blank/edit.html +8 -2
- package/templates/blank/index.html +6 -1
- package/templates/blank/instructor.html +6 -1
- package/templates/blank/template.json +1 -1
- package/templates/quiz/README.md +28 -12
- package/templates/quiz/core/behaviors.d.ts +13 -7
- package/templates/quiz/core/behaviors.js +36 -51
- package/templates/quiz/core/editor.d.ts +10 -0
- package/templates/quiz/core/editor.js +471 -8
- package/templates/quiz/core/markdown.d.ts +4 -0
- package/templates/quiz/core/markdown.js +65 -11
- package/templates/quiz/core/model.d.ts +34 -1
- package/templates/quiz/core/model.js +89 -7
- package/templates/quiz/core/rich-text.d.ts +19 -0
- package/templates/quiz/core/rich-text.js +521 -0
- package/templates/quiz/edit.html +12 -3
- package/templates/quiz/index.html +12 -3
- package/templates/quiz/screens/edit.js +848 -168
- package/templates/quiz/screens/learn.js +90 -14
- package/templates/quiz/styles.css +889 -213
- package/templates/quiz/template.json +9 -2
- package/templates/quiz/ui/templates/edit.d.ts +19 -6
- package/templates/quiz/ui/templates/edit.js +666 -87
- package/templates/quiz/ui/templates/group.js +19 -8
- package/templates/quiz/ui/templates/order.js +25 -24
- package/templates/quiz/ui/templates/page.js +19 -8
- package/templates/quiz/ui/templates/question.js +2 -2
- package/templates/quiz/ui/texts.js +104 -35
- package/templates/quiz/ui/theme.css +8 -9
- package/templates/steps/README.md +77 -0
- package/templates/steps/commentary.txt +7 -0
- package/templates/steps/edit.html +21 -0
- package/templates/steps/gitignore +4 -0
- package/templates/steps/index.html +69 -0
- package/templates/steps/metadata.json +9 -0
- package/templates/steps/package.json +13 -0
- package/templates/steps/screens/edit.js +32 -0
- package/templates/steps/screens/learn.js +108 -0
- package/templates/steps/styles.css +54 -0
- package/templates/steps/template.json +6 -0
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* 학생 화면: app.useSubmit({ getAnswer, setAnswer, validate })
|
|
6
6
|
* 편집 화면: app.useSave({ getContent, getGrading, validate }) · 채점 방식과 답: app.useGradingBlock() (퀴즈가 아닌 자료)
|
|
7
7
|
* 내용(JSON)을 폼 · 코드로 고치는 편집기: lib/elice-content-editor.js의 useContentEditor(app, { initial, schema })
|
|
8
|
-
* 여러 단계: app.
|
|
8
|
+
* 여러 단계: app.useStepper() (<section data-ec-step>마다 한 단계, 또는 { count, onChange }. 옛 이름 usePaging)
|
|
9
|
+
* 화면 틀: data-ec-layout="single | split | stage | media" + data-ec-region (CSS만, lib/elice-content.css "레이아웃" 절)
|
|
9
10
|
* 읽기 전용 잠금, 답 복원, 결과·오류 안내, 저장 문구, 로컬 mock 표시는 키트가 합니다.
|
|
10
11
|
*
|
|
11
12
|
* 화면(screens/*.js)은 이 키트만 부릅니다. 키트가 SDK로 인증 · 화면 확인 · 내용 불러오기 ·
|
|
@@ -28,10 +29,11 @@
|
|
|
28
29
|
* await app.submit(answer)
|
|
29
30
|
*
|
|
30
31
|
* 정답은 콘텐츠(zip)에 넣지 않습니다. 채점은 서버가 채점 설정(settings.grading)으로 합니다 (ADR 0009).
|
|
31
|
-
* 채점 설정 { type: pattern | rubric, answer_key | rubric }은 편집 화면이 edit 토큰으로 저장하고, 서버는 학생에게
|
|
32
|
+
* 채점 설정 { type: pattern | partial_pattern | rubric, answer_key (+ scores) | rubric }은 편집 화면이 edit 토큰으로 저장하고, 서버는 학생에게
|
|
32
33
|
* settings.grading을 내려주지 않습니다. 완료 정책(on_access · on_submit · on_graded)은 콘텐츠가 다루지 않습니다:
|
|
33
34
|
* LXP에 올린 뒤 자료 편집 화면의 '설정'에서 교육자가 고릅니다 (ADR 0012).
|
|
34
35
|
*/
|
|
36
|
+
import { emptyContentArt } from './icons/empty-content.js';
|
|
35
37
|
|
|
36
38
|
/**
|
|
37
39
|
* 이 HTML(metadata.json의 learn · instructor · edit)을 SDK가 알려 준 화면 · 보는 사람으로 열어도 되는지.
|
|
@@ -51,9 +53,12 @@ const MESSAGES = {
|
|
|
51
53
|
read_only_mode: '보기 전용 화면이라 제출할 수 없습니다.',
|
|
52
54
|
rate_limited: '제출이 너무 잦습니다. 잠시 뒤 다시 시도해 주세요.',
|
|
53
55
|
invalid_input: '답이 너무 크거나 형식이 올바르지 않습니다.',
|
|
56
|
+
// 키트만의 문구: 저장(settings)이 서버 크기 한도를 넘음 (invalid_input · reason too_large)
|
|
57
|
+
save_too_large: '저장할 내용이 너무 커요. 그림이나 글을 줄여 주세요.',
|
|
54
58
|
content_not_ready: '아직 저장된 자료가 없습니다.',
|
|
55
|
-
// 키트만의 문구: 편집 화면이 아직 내용을 저장하지 않음 (기본 내용 파일은 없음)
|
|
56
|
-
content_empty: '
|
|
59
|
+
// 키트만의 문구: 편집 화면이 아직 내용을 저장하지 않음 (기본 내용 파일은 없음). app.emptyState()의 제목 · 설명
|
|
60
|
+
content_empty: '학습 자료를 준비하고 있어요',
|
|
61
|
+
content_empty_description: '준비가 완료되면 이곳에서 볼 수 있어요',
|
|
57
62
|
external_service_error: '채점하지 못했어요. 제출이 저장되지 않았으니 다시 제출해 주세요.',
|
|
58
63
|
screen_not_supported: '이 화면에서는 할 수 없는 일입니다.',
|
|
59
64
|
navigation_timeout: '수업 페이지 정보를 받지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
|
|
@@ -70,6 +75,9 @@ const MESSAGES = {
|
|
|
70
75
|
// 키트만의 코드: 자료 주소인데 접속 토큰이 없음 (새로고침 · 다른 HTML로 이동하면 SDK가 지운 토큰이 남지 않는다)
|
|
71
76
|
reopen_required:
|
|
72
77
|
'자료를 다시 열어 주세요. 새로고침하거나 다른 페이지로 옮기면 다시 열어야 합니다.',
|
|
78
|
+
// 키트만의 코드: ecdk build 결과물(dist/content)을 LXP 밖에서 열었다. 운영 zip에는 흉내 SDK가 없다
|
|
79
|
+
mock_unavailable:
|
|
80
|
+
'빌드한 화면에는 로컬 흉내 SDK가 없습니다. 로컬에서는 ecdk dev로 열고, 실제 화면은 LXP에 올려 확인해 주세요.',
|
|
73
81
|
};
|
|
74
82
|
|
|
75
83
|
export class ContentError extends Error {
|
|
@@ -85,9 +93,21 @@ export class ContentError extends Error {
|
|
|
85
93
|
}
|
|
86
94
|
}
|
|
87
95
|
|
|
88
|
-
/** SDK
|
|
89
|
-
|
|
96
|
+
/** 서버 오류 detail의 ctx.reason들 (SDK 오류의 cause.cause.detail, 예: [{ ctx: { reason: 'too_large' } }]) */
|
|
97
|
+
const reasonsOf = err => {
|
|
98
|
+
const detail = err?.cause?.cause?.detail;
|
|
99
|
+
return Array.isArray(detail) ? detail.map(item => item?.ctx?.reason).filter(Boolean) : [];
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* SDK 오류를 화면이 그대로 보여 줄 수 있는 한국어 메시지로
|
|
104
|
+
* @param {unknown} err
|
|
105
|
+
* @param {'save'} [action] 무엇을 하다 났는지 (저장이면 크기 초과 문구가 다르다)
|
|
106
|
+
*/
|
|
107
|
+
function toContentError(err, action) {
|
|
90
108
|
if (err instanceof ContentError) return err;
|
|
109
|
+
if (action === 'save' && err?.code === 'invalid_input' && reasonsOf(err).includes('too_large'))
|
|
110
|
+
return new ContentError('invalid_input', MESSAGES.save_too_large, err);
|
|
91
111
|
// 서버 오류 코드는 SDK 오류의 cause.cause.code에 있다 (예: 409 MATERIAL_DRAFT_NOT_READY → SDK content_not_ready)
|
|
92
112
|
const serverCode = err?.cause?.cause?.code;
|
|
93
113
|
if (serverCode === 'MATERIAL_DRAFT_NOT_READY')
|
|
@@ -98,19 +118,41 @@ function toContentError(err) {
|
|
|
98
118
|
return new ContentError(code, MESSAGES[code] ?? MESSAGES.request_failed, err);
|
|
99
119
|
}
|
|
100
120
|
|
|
121
|
+
/**
|
|
122
|
+
* 점수를 숫자로: 서버가 "70" · "70.00"처럼 글자로 줄 때가 있다 (SDK는 그대로 넘김). null · undefined는 그대로,
|
|
123
|
+
* 숫자로 읽지 못하는 값도 그대로 둔다
|
|
124
|
+
*/
|
|
125
|
+
function toScore(value) {
|
|
126
|
+
if (typeof value !== 'string' || value.trim() === '') return value;
|
|
127
|
+
const n = Number(value);
|
|
128
|
+
return Number.isFinite(n) ? n : value;
|
|
129
|
+
}
|
|
130
|
+
/** score가 글자인 결과 객체는 score만 숫자로 바꾼 사본을, 아니면 그대로 */
|
|
131
|
+
function withNumberScore(r) {
|
|
132
|
+
if (!r || typeof r !== 'object' || typeof r.score !== 'string') return r;
|
|
133
|
+
return { ...r, score: toScore(r.score) };
|
|
134
|
+
}
|
|
135
|
+
|
|
101
136
|
const MATERIAL_PATH = /\/materials\/[0-9a-f-]{36}\//i;
|
|
102
137
|
|
|
103
138
|
/**
|
|
104
|
-
* 저장된 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` ·
|
|
105
|
-
*
|
|
139
|
+
* 저장된 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` ·
|
|
140
|
+
* `{ type: 'partial_pattern', answer_key: string[], scores: number[] }` · `{ type: 'rubric', rubric }`.
|
|
141
|
+
* 옛 SDK(G129 해결 전)는 settings 안 키까지 camelCase로 바꿔 answer_key가 answerKey로 왔다. 그 SDK로 빌드한 자료를 위해 둘 다 받는다.
|
|
142
|
+
* partial_pattern 배열은 복사해 둔다 (값은 그대로, 검사는 validatePartialGrading).
|
|
106
143
|
* 채점 방식이 아닌 값(옛 on_access · on_submit 등)이면 null
|
|
107
144
|
*/
|
|
108
145
|
export function normalizeGrading(grading) {
|
|
109
146
|
if (!grading || typeof grading !== 'object') return null;
|
|
110
|
-
|
|
111
|
-
|
|
147
|
+
const answerKey = grading.answer_key ?? grading.answerKey;
|
|
148
|
+
if (grading.type === 'pattern')
|
|
112
149
|
return { type: 'pattern', ...(typeof answerKey === 'string' ? { answer_key: answerKey } : {}) };
|
|
113
|
-
|
|
150
|
+
if (grading.type === 'partial_pattern')
|
|
151
|
+
return {
|
|
152
|
+
type: 'partial_pattern',
|
|
153
|
+
answer_key: Array.isArray(answerKey) ? [...answerKey] : [],
|
|
154
|
+
scores: Array.isArray(grading.scores) ? [...grading.scores] : [],
|
|
155
|
+
};
|
|
114
156
|
if (grading.type === 'rubric')
|
|
115
157
|
return { type: 'rubric', ...(typeof grading.rubric === 'string' ? { rubric: grading.rubric } : {}) };
|
|
116
158
|
return null;
|
|
@@ -247,8 +289,13 @@ export async function start(options) {
|
|
|
247
289
|
try {
|
|
248
290
|
if (kind === 'custom') sdk = options.sdk;
|
|
249
291
|
else if (kind === 'mock') {
|
|
250
|
-
|
|
251
|
-
|
|
292
|
+
// ecdk build는 __ECDK_MOCK_SDK__를 false로 바꿔 이 분기를 지운다: 흉내 SDK는 운영 zip에 들어가지 않는다.
|
|
293
|
+
// ecdk dev · 테스트(바꾸지 않음)에서는 그대로 흉내 SDK를 쓴다
|
|
294
|
+
// eslint-disable-next-line no-undef
|
|
295
|
+
if (typeof __ECDK_MOCK_SDK__ === 'undefined' || __ECDK_MOCK_SDK__) {
|
|
296
|
+
const { MockEliceCDK } = await import('./cdk-mock.js');
|
|
297
|
+
sdk = new MockEliceCDK({ onSessionExpired, loadJson: options.loadJson, ...options.mock });
|
|
298
|
+
} else throw new ContentError('mock_unavailable', MESSAGES.mock_unavailable);
|
|
252
299
|
} else sdk = new (await loadRealSdk())({ onSessionExpired, ...devApi() });
|
|
253
300
|
if (kind === 'mock' && typeof console !== 'undefined')
|
|
254
301
|
console.info(
|
|
@@ -309,8 +356,8 @@ export async function start(options) {
|
|
|
309
356
|
sdkKind: kind,
|
|
310
357
|
/** 보는 사람 { anonymousId, fullname } */
|
|
311
358
|
account: sdk.account,
|
|
312
|
-
/** 내 결과 { score(가장 최근
|
|
313
|
-
result: sdk.result,
|
|
359
|
+
/** 내 결과 { score(가장 최근 채점, 숫자 · null), submitCount, completedAt } 또는 null */
|
|
360
|
+
result: withNumberScore(sdk.result),
|
|
314
361
|
/** 제출이 기록되는지 (학생만, draft · mock 제외) */
|
|
315
362
|
get records() {
|
|
316
363
|
return viewer === 'student' && !app.isDraft && kind !== 'mock';
|
|
@@ -323,13 +370,17 @@ export async function start(options) {
|
|
|
323
370
|
get hasContent() {
|
|
324
371
|
return Object.keys(content).length > 0;
|
|
325
372
|
},
|
|
326
|
-
/**
|
|
327
|
-
|
|
328
|
-
|
|
373
|
+
/**
|
|
374
|
+
* 내용이 없을 때 보여 줄 안내: 가운데 그림 + 제목 "학습 자료를 준비하고 있어요" + 설명. 학생 · 교육자 화면에서
|
|
375
|
+
* app.hasContent가 false일 때. title · description으로 문구를 바꾸고(description: ''이면 설명 줄 없음),
|
|
376
|
+
* theme: 'dark'는 밝은 테마 화면 안의 어두운 바탕(예: 문서 학생 화면)에서 어두운 색으로
|
|
377
|
+
*/
|
|
378
|
+
emptyState(options) {
|
|
379
|
+
return emptyState(options);
|
|
329
380
|
},
|
|
330
381
|
/**
|
|
331
382
|
* 저장된 채점 설정 `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }` 또는 null.
|
|
332
|
-
* edit 범위(편집
|
|
383
|
+
* edit 범위(편집 화면)에서만 오고, 학생 · 튜터 · 교육자 화면에는 서버가 내려주지 않는다
|
|
333
384
|
*/
|
|
334
385
|
get grading() {
|
|
335
386
|
return grading;
|
|
@@ -339,8 +390,8 @@ export async function start(options) {
|
|
|
339
390
|
async submit(answer) {
|
|
340
391
|
if (readOnly) throw new ContentError('read_only_mode', MESSAGES.read_only_mode);
|
|
341
392
|
try {
|
|
342
|
-
const res = await sdk.submit(answer);
|
|
343
|
-
app.result = sdk.result ?? app.result;
|
|
393
|
+
const res = withNumberScore(await sdk.submit(answer));
|
|
394
|
+
app.result = withNumberScore(sdk.result) ?? app.result;
|
|
344
395
|
return res;
|
|
345
396
|
} catch (err) {
|
|
346
397
|
throw toContentError(err);
|
|
@@ -356,7 +407,7 @@ export async function start(options) {
|
|
|
356
407
|
async lastSubmission() {
|
|
357
408
|
try {
|
|
358
409
|
const [last] = await sdk.history({ limit: 1 });
|
|
359
|
-
return last ?? null;
|
|
410
|
+
return withNumberScore(last) ?? null;
|
|
360
411
|
} catch (err) {
|
|
361
412
|
throw toContentError(err);
|
|
362
413
|
}
|
|
@@ -365,10 +416,11 @@ export async function start(options) {
|
|
|
365
416
|
/**
|
|
366
417
|
* 내용 저장 (편집 화면): SDK saveSettings가 edit 토큰으로 자료의 draft에 저장한다. 학생에게는 LXP 편집 페이지에서
|
|
367
418
|
* 저장(새 버전)한 뒤 보인다. 보통은 useSave를 쓴다.
|
|
368
|
-
* nextGrading(채점 설정 `{ type, answer_key | rubric }
|
|
419
|
+
* nextGrading(채점 설정 `{ type, answer_key | rubric }`, partial_pattern은 배열 answer_key · scores)을 주면
|
|
420
|
+
* settings.grading으로 그대로(배열도 바꾸지 않고) 같이 저장하고,
|
|
369
421
|
* 주지 않으면 저장된 채점 설정을 그대로 둔다
|
|
370
422
|
* @param {Record<string, unknown>} next
|
|
371
|
-
* @param {{ type: 'pattern' | 'rubric', answer_key?: string, rubric?: string }} [nextGrading]
|
|
423
|
+
* @param {{ type: 'pattern' | 'partial_pattern' | 'rubric', answer_key?: string | string[], scores?: number[], rubric?: string }} [nextGrading]
|
|
372
424
|
*/
|
|
373
425
|
async saveContent(next, nextGrading) {
|
|
374
426
|
if (screen !== 'edit')
|
|
@@ -381,7 +433,7 @@ export async function start(options) {
|
|
|
381
433
|
grading = g;
|
|
382
434
|
savedSettings = settings;
|
|
383
435
|
} catch (err) {
|
|
384
|
-
throw toContentError(err);
|
|
436
|
+
throw toContentError(err, 'save');
|
|
385
437
|
}
|
|
386
438
|
},
|
|
387
439
|
|
|
@@ -415,13 +467,21 @@ export async function start(options) {
|
|
|
415
467
|
},
|
|
416
468
|
|
|
417
469
|
/**
|
|
418
|
-
* 자료 안 여러 단계
|
|
470
|
+
* 자료 안 여러 단계 이동 (스테퍼). 단계는 내용 영역 안 `<section data-ec-step>`들, 또는 `{ count, onChange }`로 코드가 그린다.
|
|
471
|
+
* 이전 · 다음 버튼은 양옆 거터의 화면 세로 가운데, 단계 표시 n / N은 왼쪽 아래 (모바일은 화면 아래 가운데 둥근 묶음).
|
|
472
|
+
* 버튼은 `<ec-stepper-nav>`(Shadow DOM, top layer) 안이라 작성자 CSS · z-index가 덮거나 바꾸지 못한다.
|
|
419
473
|
* 첫 단계의 왼쪽 · 마지막 단계의 오른쪽은 LXP 이전 · 다음 수업 자료로 가는 버튼(모양이 다름)이 되고,
|
|
420
474
|
* 그쪽 수업 자료가 없거나 LXP 밖이면 숨긴다. LXP 아래 이전 · 다음 막대와 헷갈리지 않게 아래 막대는 만들지 않는다.
|
|
421
|
-
*
|
|
475
|
+
* ← → 키(입력 칸 · 슬라이더 밖), 단계를 넘기면 제목에 초점 · 화면 맨 위로. 옵션: canNext(다음 막기) · remember(마지막 단계 기억)
|
|
476
|
+
* @param {StepperOptions} [opts]
|
|
422
477
|
*/
|
|
478
|
+
useStepper(opts) {
|
|
479
|
+
return mountStepper(app, opts ?? {});
|
|
480
|
+
},
|
|
481
|
+
|
|
482
|
+
/** useStepper의 옛 이름 (같은 동작) */
|
|
423
483
|
usePaging(opts) {
|
|
424
|
-
return
|
|
484
|
+
return mountStepper(app, opts ?? {});
|
|
425
485
|
},
|
|
426
486
|
};
|
|
427
487
|
if (options.status !== false) showStatus(app);
|
|
@@ -433,19 +493,25 @@ export async function start(options) {
|
|
|
433
493
|
* @property {() => unknown} getAnswer 화면에서 답 모으기
|
|
434
494
|
* @property {(answer: unknown) => void} [setAnswer] 저장된 답을 화면에 채우기 (복원 · 튜터링)
|
|
435
495
|
* @property {(answer: unknown) => true | string} [validate] 통과면 true, 아니면 보여 줄 문장
|
|
436
|
-
* @property {(result: object, info: { restored: boolean }) => void} [onResult] 채점 결과 { isCorrect, score } (제출 직후 · 다시 열었을
|
|
496
|
+
* @property {(result: object, info: { restored: boolean }) => void} [onResult] 채점 결과 { isCorrect, score, answerCorrectness } (제출 직후 · 다시 열었을 때는 마지막 제출 기록). 정답 표시 등에
|
|
497
|
+
* @property {(result: object) => string | undefined} [resultText] 결과 줄 문장을 화면이 정할 때 (undefined면 키트 기본 문장)
|
|
498
|
+
* @property {boolean} [allowUnchanged] true면 같은 답도 다시 제출할 수 있다 (기본: 제출한 답 그대로면 버튼을 끄고 고치면 켬)
|
|
437
499
|
* @property {Element} [root] 잠글 화면 영역 (기본 #app)
|
|
438
500
|
* @property {string} [label] 버튼 글자 (기본 '제출')
|
|
439
501
|
*/
|
|
440
502
|
|
|
441
503
|
/**
|
|
442
|
-
* @typedef {object}
|
|
443
|
-
* @property {number} count 단계 수 (1 이상)
|
|
444
|
-
* @property {(step: number) => void} onChange 단계가 바뀔 때 (0부터). 시작할 때도 한 번
|
|
445
|
-
* @property {number} [start] 처음 단계 (기본 0)
|
|
446
|
-
* @property {Element} [root]
|
|
504
|
+
* @typedef {object} StepperOptions
|
|
505
|
+
* @property {number} [count] 단계 수 (1 이상). 없으면 내용 영역 안 `[data-ec-step]` 요소 수
|
|
506
|
+
* @property {(step: number, ctx: { content: Element, section: Element | null }) => void} [onChange] 단계가 바뀔 때 (0부터). 시작할 때도 한 번
|
|
507
|
+
* @property {number} [start] 처음 단계 (기본 0, remember면 기억한 단계)
|
|
508
|
+
* @property {Element} [root] 내용 영역 (기본 #app)
|
|
509
|
+
* @property {(step: number) => true | string | false} [canNext] 다음으로 가도 되는지. 문장이면 다음 버튼을 막고 그 이유를 보인다 (기본: 늘 됨)
|
|
510
|
+
* @property {boolean | string} [remember] 마지막 단계를 이 브라우저(localStorage)에만 기억, 서버에는 저장하지 않음 (기본 끔, 문자열이면 저장 이름)
|
|
447
511
|
*/
|
|
448
512
|
|
|
513
|
+
/** @typedef {StepperOptions} PagingOptions */
|
|
514
|
+
|
|
449
515
|
/**
|
|
450
516
|
* @typedef {object} SaveOptions
|
|
451
517
|
* @property {() => Record<string, unknown>} getContent 저장할 내용 (학생에게 공개, 정답 넣지 않음)
|
|
@@ -494,26 +560,61 @@ function resultText(r) {
|
|
|
494
560
|
: `${r.score}점이에요. 다시 풀어 볼 수 있어요.`;
|
|
495
561
|
}
|
|
496
562
|
|
|
497
|
-
|
|
563
|
+
const UNCHANGED_HINT = '답을 고치면 다시 제출할 수 있어요.';
|
|
564
|
+
|
|
565
|
+
function mountSubmit(
|
|
566
|
+
app,
|
|
567
|
+
{ getAnswer, setAnswer, validate, onResult, resultText: customText, allowUnchanged = false, root, label = '제출' }
|
|
568
|
+
) {
|
|
498
569
|
const area = appRoot(root);
|
|
499
570
|
const result = h('p', { className: 'ec-result', role: 'status', hidden: true });
|
|
500
571
|
const error = h('p', { className: 'ec-error', role: 'alert' });
|
|
572
|
+
const hint = h('p', { className: 'ec-submit-hint', hidden: true, textContent: UNCHANGED_HINT });
|
|
501
573
|
const button = h('button', { className: 'ec-primary', type: 'button', textContent: label });
|
|
502
574
|
const bar = h('div', { className: 'ec-submitbar' });
|
|
503
|
-
bar.append(error, button);
|
|
575
|
+
bar.append(error, hint, button);
|
|
504
576
|
area.after(result, bar);
|
|
505
577
|
|
|
578
|
+
const text = r => customText?.(r) ?? resultText(r);
|
|
506
579
|
const show = (r, past = false) => {
|
|
507
580
|
const ungraded = r.isCorrect === null || r.score === null || r.score === undefined;
|
|
508
581
|
result.textContent = past
|
|
509
582
|
? ungraded
|
|
510
583
|
? '이미 제출했어요.'
|
|
511
|
-
: `지난 점수: ${
|
|
512
|
-
:
|
|
584
|
+
: `지난 점수: ${text(r)}`
|
|
585
|
+
: text(r);
|
|
513
586
|
result.className = `ec-result ${r.isCorrect ? 'ok' : r.isCorrect === false ? 'no' : ''}`;
|
|
514
587
|
result.hidden = false;
|
|
515
588
|
};
|
|
516
589
|
|
|
590
|
+
// 같은 답 다시 제출 막기: 이 화면에서 제출한 답과 지금 답이 같으면 버튼을 끄고 안내, 고치면 다시 켠다 (다시 열어 복원한 답은 막지 않음).
|
|
591
|
+
// 답이 바뀌는 길(입력 · 고르기 · 끌어 놓기 · 키보드)이 화면마다 달라 문서의 이벤트 뒤에 지금 답을 다시 비교한다
|
|
592
|
+
let lastAnswer = null;
|
|
593
|
+
let busy = false;
|
|
594
|
+
const answerKey = () => {
|
|
595
|
+
try {
|
|
596
|
+
return JSON.stringify(getAnswer() ?? null);
|
|
597
|
+
} catch {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
const sync = () => {
|
|
602
|
+
if (allowUnchanged || app.readOnly || busy || lastAnswer === null) return;
|
|
603
|
+
const same = answerKey() === lastAnswer;
|
|
604
|
+
button.disabled = same;
|
|
605
|
+
hint.hidden = !same;
|
|
606
|
+
};
|
|
607
|
+
if (!allowUnchanged && typeof document !== 'undefined')
|
|
608
|
+
for (const type of ['input', 'change', 'click', 'pointerup', 'keyup', 'drop'])
|
|
609
|
+
document.addEventListener(type, () => setTimeout(sync, 0), true);
|
|
610
|
+
/** 방금 나온 결과를 화면 안으로. 아래 고정 제출 바(안내 줄이 붙으면 더 높음)에 가리지 않게 그 높이만큼 띄운다. 움직임 줄이기 설정이면 바로 */
|
|
611
|
+
const reveal = () => {
|
|
612
|
+
const reduce =
|
|
613
|
+
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
614
|
+
if (bar.offsetHeight) result.style.scrollMarginBottom = `${bar.offsetHeight + 16}px`;
|
|
615
|
+
result.scrollIntoView?.({ block: 'nearest', behavior: reduce ? 'auto' : 'smooth' });
|
|
616
|
+
};
|
|
617
|
+
|
|
517
618
|
if (app.readOnly) {
|
|
518
619
|
area.inert = true;
|
|
519
620
|
area.setAttribute('aria-readonly', 'true');
|
|
@@ -556,18 +657,26 @@ function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, labe
|
|
|
556
657
|
}
|
|
557
658
|
error.textContent = '';
|
|
558
659
|
submitted = true;
|
|
660
|
+
busy = true;
|
|
559
661
|
button.disabled = true;
|
|
560
662
|
button.setAttribute('aria-busy', 'true');
|
|
663
|
+
let succeeded = false;
|
|
561
664
|
try {
|
|
562
665
|
const res = await app.submit(answer);
|
|
666
|
+
lastAnswer = JSON.stringify(answer ?? null);
|
|
563
667
|
show(res);
|
|
564
668
|
onResult?.(res, { restored: false });
|
|
565
669
|
button.textContent = `다시 ${label}`;
|
|
670
|
+
succeeded = true;
|
|
566
671
|
} catch (e) {
|
|
567
672
|
error.textContent = e.message;
|
|
568
673
|
} finally {
|
|
674
|
+
busy = false;
|
|
569
675
|
button.disabled = false;
|
|
570
676
|
button.removeAttribute('aria-busy');
|
|
677
|
+
sync();
|
|
678
|
+
// 안내 줄까지 붙은 뒤의 제출 바 높이로 옮긴다
|
|
679
|
+
if (succeeded) reveal();
|
|
571
680
|
}
|
|
572
681
|
});
|
|
573
682
|
return { element: bar, result, restored };
|
|
@@ -584,88 +693,495 @@ async function hasLecturePage(app, side) {
|
|
|
584
693
|
}
|
|
585
694
|
}
|
|
586
695
|
|
|
587
|
-
|
|
696
|
+
/** 스테퍼 버튼 묶음(<ec-stepper-nav>) 안 스타일. Shadow DOM이라 작성자 CSS(button { … } · * { … })가 들어오지 않고,
|
|
697
|
+
* 색 · 간격은 상속되는 토큰(--ec-* · --eds-*)으로 받는다. :host의 !important는 바깥 CSS의 !important보다 이긴다 */
|
|
698
|
+
const STEPPER_NAV_CSS = `
|
|
699
|
+
:host {
|
|
700
|
+
display: block !important;
|
|
701
|
+
pointer-events: none !important;
|
|
702
|
+
margin: 0 !important;
|
|
703
|
+
padding: 0 !important;
|
|
704
|
+
border: 0 !important;
|
|
705
|
+
background: transparent !important;
|
|
706
|
+
overflow: visible !important;
|
|
707
|
+
opacity: 1 !important;
|
|
708
|
+
visibility: visible !important;
|
|
709
|
+
transform: none !important;
|
|
710
|
+
filter: none !important;
|
|
711
|
+
clip-path: none !important;
|
|
712
|
+
color: var(--ec-fg);
|
|
713
|
+
font-family: var(--eds-font-family);
|
|
714
|
+
}
|
|
715
|
+
/* top layer(popover): 화면 전체를 덮는 투명 막. 버튼만 누를 수 있다 */
|
|
716
|
+
:host([data-mode='top']) {
|
|
717
|
+
position: fixed !important;
|
|
718
|
+
inset: 0 !important;
|
|
719
|
+
width: auto !important;
|
|
720
|
+
height: auto !important;
|
|
721
|
+
}
|
|
722
|
+
/* popover를 못 쓰는 브라우저: 틀(.ec-stepper) 안에 겹친다 (z-index 1) */
|
|
723
|
+
:host([data-mode='inline']) {
|
|
724
|
+
position: absolute !important;
|
|
725
|
+
inset: 0 !important;
|
|
726
|
+
z-index: 1 !important;
|
|
727
|
+
}
|
|
728
|
+
[hidden] {
|
|
729
|
+
display: none !important;
|
|
730
|
+
}
|
|
731
|
+
.nav {
|
|
732
|
+
display: contents;
|
|
733
|
+
}
|
|
734
|
+
button {
|
|
735
|
+
all: unset;
|
|
736
|
+
box-sizing: border-box;
|
|
737
|
+
pointer-events: auto;
|
|
738
|
+
position: absolute;
|
|
739
|
+
top: 50%;
|
|
740
|
+
translate: 0 -50%;
|
|
741
|
+
/* 둥근 버튼: 문서 자료 학생 화면의 쪽 넘김 버튼과 같은 모양. 테두리 1px 원, 채움 · 그림자 없음(면은 바탕색),
|
|
742
|
+
꺾쇠는 16px 선 그림(svg, 글자가 아님) secondary 색 */
|
|
743
|
+
display: inline-grid;
|
|
744
|
+
place-items: center;
|
|
745
|
+
min-width: var(--ec-nav-size);
|
|
746
|
+
height: var(--ec-nav-size);
|
|
747
|
+
padding: 0;
|
|
748
|
+
border: 1px solid var(--ec-nav-border);
|
|
749
|
+
border-radius: 999px;
|
|
750
|
+
background: var(--ec-nav-bg);
|
|
751
|
+
color: var(--ec-nav-fg);
|
|
752
|
+
line-height: 1;
|
|
753
|
+
cursor: pointer;
|
|
754
|
+
}
|
|
755
|
+
svg {
|
|
756
|
+
display: block;
|
|
757
|
+
width: var(--ec-nav-icon);
|
|
758
|
+
height: var(--ec-nav-icon);
|
|
759
|
+
}
|
|
760
|
+
:host([data-mode='top']) button {
|
|
761
|
+
position: fixed;
|
|
762
|
+
}
|
|
763
|
+
@media (hover: hover) {
|
|
764
|
+
button:not([aria-disabled='true']):hover {
|
|
765
|
+
background: linear-gradient(var(--ec-nav-hover-bg), var(--ec-nav-hover-bg)), var(--ec-nav-bg);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
button:focus-visible {
|
|
769
|
+
outline: 2px solid var(--ec-accent);
|
|
770
|
+
outline-offset: 1px;
|
|
771
|
+
}
|
|
772
|
+
/* 막힌 버튼(canNext): 꺾쇠 색만 흐리게 (테두리 · 면은 그대로) */
|
|
773
|
+
button[aria-disabled='true'] {
|
|
774
|
+
color: var(--ec-nav-disabled-fg);
|
|
775
|
+
cursor: default;
|
|
776
|
+
}
|
|
777
|
+
.prev {
|
|
778
|
+
left: var(--ec-nav-inset);
|
|
779
|
+
}
|
|
780
|
+
.next {
|
|
781
|
+
right: var(--ec-nav-inset);
|
|
782
|
+
}
|
|
783
|
+
/* 끝에서 나가는 버튼: 같은 테두리 알약에 글자 (LXP 이전 · 다음 수업 자료). 강조색(보라)은 쓰지 않는다 */
|
|
784
|
+
.leave {
|
|
785
|
+
display: inline-flex;
|
|
786
|
+
align-items: center;
|
|
787
|
+
gap: 4px;
|
|
788
|
+
padding: 0 14px;
|
|
789
|
+
font-size: var(--ec-nav-count-size);
|
|
790
|
+
font-weight: var(--eds-fw-semibold);
|
|
791
|
+
white-space: nowrap;
|
|
792
|
+
}
|
|
793
|
+
.leave.prev {
|
|
794
|
+
padding-left: 10px;
|
|
795
|
+
}
|
|
796
|
+
.leave.next {
|
|
797
|
+
padding-right: 10px;
|
|
798
|
+
}
|
|
799
|
+
/* 단계 표시 "1 / 6": 테두리 알약(버튼과 같은 높이), 14px / 600 secondary. 데스크톱은 왼쪽 아래 거터
|
|
800
|
+
(오른쪽 아래 --ec-fab-safe는 비움), 모바일은 두 버튼 사이 */
|
|
801
|
+
.count {
|
|
802
|
+
pointer-events: auto;
|
|
803
|
+
position: absolute;
|
|
804
|
+
left: var(--ec-nav-inset);
|
|
805
|
+
bottom: 0;
|
|
806
|
+
box-sizing: border-box;
|
|
807
|
+
display: inline-flex;
|
|
808
|
+
align-items: center;
|
|
809
|
+
justify-content: center;
|
|
810
|
+
height: var(--ec-nav-size);
|
|
811
|
+
margin: 0;
|
|
812
|
+
padding: 0 14px;
|
|
813
|
+
border: 1px solid var(--ec-nav-border);
|
|
814
|
+
border-radius: 999px;
|
|
815
|
+
background: var(--ec-nav-bg);
|
|
816
|
+
color: var(--ec-nav-fg);
|
|
817
|
+
font-size: var(--ec-nav-count-size);
|
|
818
|
+
font-weight: var(--eds-fw-semibold);
|
|
819
|
+
line-height: 20px;
|
|
820
|
+
font-variant-numeric: tabular-nums;
|
|
821
|
+
white-space: nowrap;
|
|
822
|
+
}
|
|
823
|
+
:host([data-mode='top']) .count {
|
|
824
|
+
position: fixed;
|
|
825
|
+
bottom: 16px;
|
|
826
|
+
}
|
|
827
|
+
/* 낮은 창: LXP는 콘텐츠 iframe 높이를 (창 높이 − 112px: 위 머리 56 + 아래 막대 56)로 두되 512px 아래로는 줄이지 않는다.
|
|
828
|
+
창이 약 568px보다 낮으면 iframe(512px)이 창 밖으로 나가, 창 아래 기준인 LXP 플로팅 버튼(⊞ 위 끝 = 창 높이 − 236,
|
|
829
|
+
오른쪽 20–60px)이 세로 가운데 다음 버튼에 닿고(1440×560 실측: iframe 안 ⊞ 위 끝 약 268, 32px 버튼이면 240–272), 아래 막대가
|
|
830
|
+
iframe 아래 약 64px를 덮어 n / N이 가려진다. 그래서 iframe이 이 최소 높이일 때만 버튼을 위로 올리고(--ec-nav-short-shift,
|
|
831
|
+
512px이면 190–222), n / N은 왼쪽 버튼 바로 아래로 옮긴다 (230–262) */
|
|
832
|
+
@media (min-width: 512px) and (max-height: 520px) {
|
|
833
|
+
:host([data-mode='top']) button {
|
|
834
|
+
top: calc(50% - var(--ec-nav-short-shift, 50px));
|
|
835
|
+
}
|
|
836
|
+
:host([data-mode='top']) .count {
|
|
837
|
+
top: calc(50% - var(--ec-nav-short-shift, 50px) + var(--ec-nav-size) / 2 + 8px);
|
|
838
|
+
bottom: auto;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
.sr {
|
|
842
|
+
position: absolute;
|
|
843
|
+
width: 1px;
|
|
844
|
+
height: 1px;
|
|
845
|
+
overflow: hidden;
|
|
846
|
+
clip-path: inset(50%);
|
|
847
|
+
white-space: nowrap;
|
|
848
|
+
}
|
|
849
|
+
/* 모바일: 화면 아래 가운데에 ‹ n / N › 한 줄 (문서 자료 쪽 넘김처럼 단계 표시 알약이 두 버튼 사이, 바탕 띠 없음).
|
|
850
|
+
LXP의 화면 폭 이전 · 다음 막대와 모양이 다르다. 버튼 · 알약은 같은 테두리 모양, 크기만 --ec-nav-size-mobile(40px) */
|
|
851
|
+
@media (max-width: 511.98px) {
|
|
852
|
+
:host {
|
|
853
|
+
--ec-nav-size: var(--ec-nav-size-mobile);
|
|
854
|
+
--ec-nav-count-size: var(--eds-fs-body1);
|
|
855
|
+
}
|
|
856
|
+
/* 칸 셋(1fr · n / N · 1fr): 끝 단계 알약으로 버튼 폭이 바뀌어도 n / N과 반대쪽 버튼이 단계마다 움직이지 않는다 */
|
|
857
|
+
.nav {
|
|
858
|
+
pointer-events: none;
|
|
859
|
+
position: absolute;
|
|
860
|
+
left: 16px;
|
|
861
|
+
right: 16px;
|
|
862
|
+
bottom: 0;
|
|
863
|
+
display: grid;
|
|
864
|
+
grid-template-columns: 1fr auto 1fr;
|
|
865
|
+
align-items: center;
|
|
866
|
+
gap: 8px;
|
|
867
|
+
}
|
|
868
|
+
.nav .prev {
|
|
869
|
+
justify-self: end;
|
|
870
|
+
}
|
|
871
|
+
.nav .next {
|
|
872
|
+
justify-self: start;
|
|
873
|
+
}
|
|
874
|
+
:host([data-mode='top']) .nav {
|
|
875
|
+
position: fixed;
|
|
876
|
+
bottom: 12px;
|
|
877
|
+
}
|
|
878
|
+
.nav button,
|
|
879
|
+
:host([data-mode='top']) .nav button,
|
|
880
|
+
.nav .count,
|
|
881
|
+
:host([data-mode='top']) .nav .count {
|
|
882
|
+
position: static;
|
|
883
|
+
translate: none;
|
|
884
|
+
}
|
|
885
|
+
.count {
|
|
886
|
+
padding: 0 16px;
|
|
887
|
+
}
|
|
888
|
+
.leave {
|
|
889
|
+
padding: 0 12px;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
`;
|
|
893
|
+
|
|
894
|
+
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
895
|
+
/** 꺾쇠 그림 (24 칸 선 그림). 문서 자료 학생 화면의 쪽 넘김 꺾쇠와 같은 경로 · 굵기 */
|
|
896
|
+
const CHEVRON_PATHS = {
|
|
897
|
+
prev: "m15 18-6-6 6-6",
|
|
898
|
+
next: "m9 18 6-6-6-6",
|
|
899
|
+
};
|
|
900
|
+
function chevronIcon(side) {
|
|
901
|
+
const svg = document.createElementNS(SVG_NS, "svg");
|
|
902
|
+
svg.setAttribute("viewBox", "0 0 24 24");
|
|
903
|
+
svg.setAttribute("aria-hidden", "true");
|
|
904
|
+
svg.setAttribute("focusable", "false");
|
|
905
|
+
const path = document.createElementNS(SVG_NS, "path");
|
|
906
|
+
path.setAttribute("d", CHEVRON_PATHS[side]);
|
|
907
|
+
for (const [k, v] of [
|
|
908
|
+
["fill", "none"],
|
|
909
|
+
["stroke", "currentColor"],
|
|
910
|
+
["stroke-width", "2.6"],
|
|
911
|
+
["stroke-linecap", "round"],
|
|
912
|
+
["stroke-linejoin", "round"],
|
|
913
|
+
])
|
|
914
|
+
path.setAttribute(k, v);
|
|
915
|
+
svg.append(path);
|
|
916
|
+
return svg;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** 스테퍼 버튼 묶음 요소. 화면 코드가 직접 만들지 않는다 (app.useStepper가 만든다) */
|
|
920
|
+
function stepperNavElement() {
|
|
921
|
+
if (
|
|
922
|
+
typeof customElements !== "undefined" &&
|
|
923
|
+
!customElements.get("ec-stepper-nav")
|
|
924
|
+
)
|
|
925
|
+
customElements.define("ec-stepper-nav", class extends HTMLElement {});
|
|
926
|
+
const host = document.createElement("ec-stepper-nav");
|
|
927
|
+
const shadow = host.attachShadow({ mode: "open" });
|
|
928
|
+
const style = h("style", { textContent: STEPPER_NAV_CSS });
|
|
929
|
+
const nav = h("div", { className: "nav" });
|
|
930
|
+
nav.setAttribute("role", "group");
|
|
931
|
+
nav.setAttribute("aria-label", "단계 이동");
|
|
932
|
+
const prev = h("button", { type: "button", className: "ec-step-nav prev" });
|
|
933
|
+
const next = h("button", { type: "button", className: "ec-step-nav next" });
|
|
934
|
+
const count = h("p", { className: "ec-step-count count" });
|
|
935
|
+
// 보이는 글은 "2 / 5", 화면 읽기 프로그램에는 "5단계 중 2단계: 제목"
|
|
936
|
+
const shown = h("span");
|
|
937
|
+
shown.setAttribute("aria-hidden", "true");
|
|
938
|
+
const spoken = h("span", { className: "sr" });
|
|
939
|
+
count.setAttribute("aria-live", "polite");
|
|
940
|
+
count.append(shown, spoken);
|
|
941
|
+
nav.append(prev, count, next);
|
|
942
|
+
shadow.append(style, nav);
|
|
943
|
+
return { host, prev, next, count, shown, spoken };
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/** top layer(popover)에 올릴 수 있는지. 못 쓰면 틀 안에 겹쳐 둔다 */
|
|
947
|
+
const canPopover = (el) => typeof el.showPopover === "function";
|
|
948
|
+
|
|
949
|
+
/** ← → 키를 무시할 곳: 글 · 숫자 · 슬라이더 · 고르기 칸, 직접 고치는 글 */
|
|
950
|
+
function typingTarget(el) {
|
|
951
|
+
if (!el || el.nodeType !== 1) return false;
|
|
952
|
+
return Boolean(
|
|
953
|
+
el.closest(
|
|
954
|
+
'input, textarea, select, [contenteditable=""], [contenteditable="true"], [role="slider"], [role="textbox"]',
|
|
955
|
+
),
|
|
956
|
+
);
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/** 마지막 단계 기억 (브라우저 저장소, 막히면 아무것도 안 함). 학습 기록이 아니라 이 브라우저의 편의 */
|
|
960
|
+
function stepMemory(key) {
|
|
961
|
+
const name = `ec-step:${key}`;
|
|
962
|
+
let store = null;
|
|
963
|
+
try {
|
|
964
|
+
// ecdk-ignore-next-line api.storage (이 브라우저에만 남음. 저장소 오류는 catch: 기억하지 않음)
|
|
965
|
+
store = globalThis.localStorage ?? null;
|
|
966
|
+
} catch {
|
|
967
|
+
store = null;
|
|
968
|
+
}
|
|
969
|
+
return {
|
|
970
|
+
read() {
|
|
971
|
+
try {
|
|
972
|
+
const v = Number(store?.getItem(name));
|
|
973
|
+
return Number.isInteger(v) ? v : null;
|
|
974
|
+
} catch {
|
|
975
|
+
return null;
|
|
976
|
+
}
|
|
977
|
+
},
|
|
978
|
+
write(step) {
|
|
979
|
+
try {
|
|
980
|
+
store?.setItem(name, String(step));
|
|
981
|
+
} catch {
|
|
982
|
+
// 저장소가 막혔거나 가득 참: 기억하지 않는다
|
|
983
|
+
}
|
|
984
|
+
},
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** 단계의 제목: data-ec-step-title · 첫 제목(h1–h3) */
|
|
989
|
+
function stepTitleEl(scope) {
|
|
990
|
+
return scope?.querySelector("[data-ec-step-title], h1, h2, h3") ?? null;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
function mountStepper(
|
|
994
|
+
app,
|
|
995
|
+
{ count, onChange, start, root, canNext, remember = false } = {},
|
|
996
|
+
) {
|
|
588
997
|
const area = appRoot(root);
|
|
589
|
-
|
|
590
|
-
|
|
998
|
+
// 단계: count가 없으면 내용 영역 안 <section data-ec-step>을 차례대로. 키트가 hidden으로 하나만 보인다
|
|
999
|
+
const sections =
|
|
1000
|
+
count === undefined ? [...area.querySelectorAll("[data-ec-step]")] : [];
|
|
1001
|
+
const total = Math.max(1, Math.floor(count ?? sections.length));
|
|
1002
|
+
const memory = remember
|
|
1003
|
+
? stepMemory(
|
|
1004
|
+
`${typeof location === "undefined" ? "" : location.pathname}#${typeof remember === "string" ? remember : area.id || "app"}`,
|
|
1005
|
+
)
|
|
1006
|
+
: null;
|
|
1007
|
+
const first = start ?? memory?.read() ?? 0;
|
|
1008
|
+
let step = Math.min(Math.max(0, Math.floor(first) || 0), total - 1);
|
|
591
1009
|
const edge = { prev: false, next: false };
|
|
592
|
-
const
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
const counter = h('p', { className: 'ec-step-count' });
|
|
597
|
-
counter.setAttribute('aria-live', 'polite');
|
|
598
|
-
// 키트 틀(.ec-paging)이 내용 영역을 감싼다: 버튼 · n / N은 틀에, 화면 코드는 내용 영역(기본 #app)에만 그린다.
|
|
1010
|
+
const ui = stepperNavElement();
|
|
1011
|
+
const { prev, next } = ui;
|
|
1012
|
+
|
|
1013
|
+
// 키트 틀(.ec-stepper)이 내용 영역을 감싼다: 버튼 · n / N은 틀에, 화면 코드는 내용 영역(기본 #app)에만 그린다.
|
|
599
1014
|
// 그래서 화면 코드가 #app을 replaceChildren · innerHTML로 다시 그려도 버튼이 지워지지 않는다
|
|
600
1015
|
let frame;
|
|
601
1016
|
if (area === document.body || !area.parentNode) {
|
|
602
1017
|
// 감쌀 수 없는 영역(body)이면 그 안에 붙인다 (다시 그리면 지워짐)
|
|
603
1018
|
frame = area;
|
|
604
|
-
area.append(
|
|
1019
|
+
area.append(ui.host);
|
|
605
1020
|
} else {
|
|
606
|
-
frame = h(
|
|
1021
|
+
frame = h("div", { className: "ec-stepper-frame" });
|
|
607
1022
|
area.before(frame);
|
|
608
|
-
frame.append(
|
|
1023
|
+
frame.append(area, ui.host);
|
|
1024
|
+
}
|
|
1025
|
+
frame.classList.add("ec-stepper");
|
|
1026
|
+
area.classList.add("ec-step-content");
|
|
1027
|
+
// top layer: 작성자 요소의 z-index · position: fixed · 조상 overflow · transform이 버튼을 덮거나 자르지 못한다.
|
|
1028
|
+
// 나중에 연 <dialog> · 전체 화면은 그 위 (의도대로). 못 쓰는 브라우저는 틀 안에 겹친다
|
|
1029
|
+
let mode = "inline";
|
|
1030
|
+
if (canPopover(ui.host)) {
|
|
1031
|
+
try {
|
|
1032
|
+
ui.host.popover = "manual";
|
|
1033
|
+
ui.host.showPopover();
|
|
1034
|
+
mode = "top";
|
|
1035
|
+
} catch {
|
|
1036
|
+
ui.host.removeAttribute("popover");
|
|
1037
|
+
}
|
|
609
1038
|
}
|
|
610
|
-
|
|
611
|
-
|
|
1039
|
+
ui.host.dataset.mode = mode;
|
|
1040
|
+
frame.dataset.ecStepperMode = mode;
|
|
1041
|
+
|
|
1042
|
+
const current = () => sections[step] ?? area;
|
|
1043
|
+
/** 다음으로 가도 되는지: true면 통과, 문장이면 막고 그 이유를 보인다 */
|
|
1044
|
+
const gate = () => {
|
|
1045
|
+
if (!canNext) return true;
|
|
1046
|
+
try {
|
|
1047
|
+
const r = canNext(step);
|
|
1048
|
+
return r === true || r === undefined
|
|
1049
|
+
? true
|
|
1050
|
+
: typeof r === "string" && r
|
|
1051
|
+
? r
|
|
1052
|
+
: "아직 다음으로 갈 수 없습니다.";
|
|
1053
|
+
} catch {
|
|
1054
|
+
return true;
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
612
1057
|
|
|
613
1058
|
// 단계 안: 동그란 화살표만. 끝에서 나가는 버튼: 글자 있는 알약 모양(이전 자료 · 다음 자료)
|
|
614
|
-
const paint = (el, side, leaving, available) => {
|
|
615
|
-
const arrow = side
|
|
616
|
-
el.classList.toggle(
|
|
1059
|
+
const paint = (el, side, leaving, available, blocked) => {
|
|
1060
|
+
const arrow = chevronIcon(side);
|
|
1061
|
+
el.classList.toggle("leave", leaving);
|
|
617
1062
|
el.hidden = leaving && !available;
|
|
1063
|
+
let label;
|
|
618
1064
|
if (leaving) {
|
|
619
|
-
const text = side ===
|
|
620
|
-
el.
|
|
621
|
-
|
|
622
|
-
|
|
1065
|
+
const text = side === "prev" ? "이전 자료" : "다음 자료";
|
|
1066
|
+
el.replaceChildren(
|
|
1067
|
+
...(side === "prev"
|
|
1068
|
+
? [arrow, h("span", { textContent: text })]
|
|
1069
|
+
: [h("span", { textContent: text }), arrow]),
|
|
1070
|
+
);
|
|
1071
|
+
label = `${text}로 이동 (이 자료를 나갑니다)`;
|
|
1072
|
+
el.title = `LXP ${side === "prev" ? "이전" : "다음"} 수업 자료로 이동`;
|
|
623
1073
|
} else {
|
|
624
|
-
el.
|
|
625
|
-
|
|
626
|
-
el.removeAttribute(
|
|
1074
|
+
el.replaceChildren(arrow);
|
|
1075
|
+
label = side === "prev" ? "이전 단계" : "다음 단계";
|
|
1076
|
+
el.removeAttribute("title");
|
|
627
1077
|
}
|
|
1078
|
+
// 막힌 다음 버튼: 초점은 받고(이유를 읽게) 누르면 아무것도 안 함. 이유는 툴팁 · 이름에
|
|
1079
|
+
if (blocked) {
|
|
1080
|
+
el.setAttribute("aria-disabled", "true");
|
|
1081
|
+
el.title = blocked;
|
|
1082
|
+
label = `${label}: ${blocked}`;
|
|
1083
|
+
} else el.removeAttribute("aria-disabled");
|
|
1084
|
+
el.setAttribute("aria-label", label);
|
|
628
1085
|
};
|
|
629
1086
|
const render = () => {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
1087
|
+
sections.forEach((s, i) => (s.hidden = i !== step));
|
|
1088
|
+
const g = gate();
|
|
1089
|
+
paint(prev, "prev", step === 0, edge.prev, null);
|
|
1090
|
+
paint(next, "next", step === total - 1, edge.next, g === true ? null : g);
|
|
1091
|
+
const title = stepTitleEl(current())?.textContent?.trim() ?? "";
|
|
1092
|
+
ui.shown.replaceChildren(
|
|
1093
|
+
h("span", { className: "now", textContent: String(step + 1) }),
|
|
1094
|
+
` / ${total}`,
|
|
1095
|
+
);
|
|
1096
|
+
ui.spoken.textContent = `${total}단계 중 ${step + 1}단계${title ? `: ${title}` : ""}`;
|
|
1097
|
+
};
|
|
1098
|
+
/** 새 단계로: 화면 맨 위로, 초점은 단계 제목 (없으면 내용 영역) */
|
|
1099
|
+
const arrive = () => {
|
|
1100
|
+
if (typeof window !== "undefined") window.scrollTo?.({ top: 0 });
|
|
1101
|
+
const target = stepTitleEl(current()) ?? current();
|
|
1102
|
+
if (!target.hasAttribute("tabindex")) target.setAttribute("tabindex", "-1");
|
|
1103
|
+
target.focus?.({ preventScroll: true });
|
|
633
1104
|
};
|
|
1105
|
+
const changed = () =>
|
|
1106
|
+
onChange?.(step, { content: area, section: sections[step] ?? null });
|
|
634
1107
|
const go = (i) => {
|
|
635
|
-
const to = Math.min(Math.max(0, i), total - 1);
|
|
1108
|
+
const to = Math.min(Math.max(0, Math.floor(i)), total - 1);
|
|
636
1109
|
if (to === step) return;
|
|
637
1110
|
step = to;
|
|
638
1111
|
render();
|
|
639
|
-
|
|
1112
|
+
memory?.write(step);
|
|
1113
|
+
changed();
|
|
1114
|
+
// 화면 코드가 onChange에서 그린 제목에 초점
|
|
1115
|
+
arrive();
|
|
640
1116
|
};
|
|
641
1117
|
const leave = (side) => {
|
|
642
1118
|
try {
|
|
643
|
-
if (side ===
|
|
1119
|
+
if (side === "prev") app.navigation?.previous();
|
|
644
1120
|
else app.navigation?.next();
|
|
645
1121
|
} catch {
|
|
646
1122
|
// 화면이 이동을 지원하지 않으면(편집 화면 등) 아무것도 하지 않는다
|
|
647
1123
|
}
|
|
648
1124
|
};
|
|
649
|
-
|
|
650
|
-
|
|
1125
|
+
const forward = () => {
|
|
1126
|
+
if (gate() !== true) return render();
|
|
1127
|
+
if (step === total - 1) leave("next");
|
|
1128
|
+
else go(step + 1);
|
|
1129
|
+
};
|
|
1130
|
+
prev.addEventListener("click", () =>
|
|
1131
|
+
step === 0 ? leave("prev") : go(step - 1),
|
|
1132
|
+
);
|
|
1133
|
+
next.addEventListener("click", forward);
|
|
1134
|
+
// ← → 키: 자료 안 단계만 (끝에서 자료를 나가지는 않음). 입력 칸 · 슬라이더에 초점이 있으면 그 칸의 키
|
|
1135
|
+
const onKey = (e) => {
|
|
1136
|
+
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey)
|
|
1137
|
+
return;
|
|
1138
|
+
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
|
|
1139
|
+
if (
|
|
1140
|
+
typingTarget(e.composedPath?.()[0] ?? e.target) ||
|
|
1141
|
+
typingTarget(document.activeElement)
|
|
1142
|
+
)
|
|
1143
|
+
return;
|
|
1144
|
+
if (e.key === "ArrowLeft" && step > 0) go(step - 1);
|
|
1145
|
+
else if (e.key === "ArrowRight" && step < total - 1 && gate() === true)
|
|
1146
|
+
go(step + 1);
|
|
1147
|
+
else return;
|
|
1148
|
+
e.preventDefault();
|
|
1149
|
+
};
|
|
1150
|
+
document.addEventListener("keydown", onKey);
|
|
651
1151
|
|
|
652
1152
|
render();
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
1153
|
+
changed();
|
|
1154
|
+
// 화면 코드가 처음 그린 제목으로 다시 (n / N 옆 읽기 글)
|
|
1155
|
+
render();
|
|
1156
|
+
memory?.write(step);
|
|
1157
|
+
// 도구용 손잡이: ecdk dev --check --step이 단계를 바꿔 찍는다 (canNext와 상관없이 go)
|
|
1158
|
+
ui.host.ecStepper = {
|
|
1159
|
+
go,
|
|
1160
|
+
count: total,
|
|
1161
|
+
get step() {
|
|
1162
|
+
return step;
|
|
659
1163
|
},
|
|
660
|
-
|
|
1164
|
+
};
|
|
1165
|
+
const ready = Promise.all([
|
|
1166
|
+
hasLecturePage(app, "prev"),
|
|
1167
|
+
hasLecturePage(app, "next"),
|
|
1168
|
+
]).then(([p, n]) => {
|
|
1169
|
+
edge.prev = p;
|
|
1170
|
+
edge.next = n;
|
|
1171
|
+
render();
|
|
1172
|
+
});
|
|
661
1173
|
return {
|
|
662
1174
|
element: frame,
|
|
663
1175
|
content: area,
|
|
1176
|
+
nav: ui.host,
|
|
664
1177
|
ready,
|
|
665
1178
|
go,
|
|
1179
|
+
/** canNext를 다시 묻는다 (단계 안 상태가 바뀌었을 때) */
|
|
1180
|
+
refresh: render,
|
|
666
1181
|
get step() {
|
|
667
1182
|
return step;
|
|
668
1183
|
},
|
|
1184
|
+
count: total,
|
|
669
1185
|
};
|
|
670
1186
|
}
|
|
671
1187
|
|
|
@@ -797,8 +1313,41 @@ const GRADING_TEXT = {
|
|
|
797
1313
|
emptyRubric: '평가 기준을 입력해 주세요.',
|
|
798
1314
|
};
|
|
799
1315
|
|
|
800
|
-
/** 정답 정규식 길이
|
|
801
|
-
export const ANSWER_KEY_MAX =
|
|
1316
|
+
/** 정답 정규식 길이 상한. 서버(elice-material grading.py _REGEX_MAX_LENGTH)와 같게: 넘으면 서버가 저장을 거절한다 */
|
|
1317
|
+
export const ANSWER_KEY_MAX = 500;
|
|
1318
|
+
/** partial_pattern 문항 수 상한 (서버와 같게) */
|
|
1319
|
+
export const PARTIAL_ITEMS_MAX = 50;
|
|
1320
|
+
|
|
1321
|
+
/** 맨 앞 Python 전체 플래그 `(?i)` · `(?s)` · `(?m)` (조합 가능). JS RegExp는 이 문법을 받지 않아 플래그로 바꾼다 */
|
|
1322
|
+
const LEADING_FLAGS = /^\(\?([ims]+)\)/;
|
|
1323
|
+
|
|
1324
|
+
/**
|
|
1325
|
+
* 정답 정규식(서버는 Python re) → JS에서 같은 뜻으로 쓸 { source, flags }.
|
|
1326
|
+
* 맨 앞 `(?i)`(대소문자 무시) · `(?s)` · `(?m)`은 떼고 JS 플래그로 (Python에서도 맨 앞에서만 전체에 걸림)
|
|
1327
|
+
* @param {string} regex
|
|
1328
|
+
* @returns {{ source: string, flags: string }}
|
|
1329
|
+
*/
|
|
1330
|
+
export function toJsRegex(regex) {
|
|
1331
|
+
const m = LEADING_FLAGS.exec(regex);
|
|
1332
|
+
if (!m) return { source: regex, flags: '' };
|
|
1333
|
+
return { source: regex.slice(m[0].length), flags: [...new Set(m[1])].join('') };
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/**
|
|
1337
|
+
* 정답 정규식이 답 문자열(앞뒤 공백을 자름) 전체와 맞는지. 서버 채점(Python re.fullmatch)과 같은 판정.
|
|
1338
|
+
* 정규식이 틀리면 false
|
|
1339
|
+
* @param {string} regex
|
|
1340
|
+
* @param {string} answer
|
|
1341
|
+
*/
|
|
1342
|
+
export function matchesAnswer(regex, answer) {
|
|
1343
|
+
if (typeof regex !== 'string' || typeof answer !== 'string') return false;
|
|
1344
|
+
try {
|
|
1345
|
+
const { source, flags } = toJsRegex(regex);
|
|
1346
|
+
return new RegExp(`^(?:${source})$`, flags).test(answer.trim());
|
|
1347
|
+
} catch {
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
802
1351
|
/** 정답 정규식 한 번 맞춰 보는 시간 상한(ms). 넘으면 ReDoS 위험으로 막는다 */
|
|
803
1352
|
const REGEX_TIME_LIMIT_MS = 50;
|
|
804
1353
|
|
|
@@ -814,13 +1363,15 @@ export function validateAnswerRegex(regex, samples = []) {
|
|
|
814
1363
|
if (!key) return '기준 답안(정규표현식)을 입력해 주세요.';
|
|
815
1364
|
if (key.length > ANSWER_KEY_MAX)
|
|
816
1365
|
return `기준 답안이 너무 깁니다 (${key.length}자, 최대 ${ANSWER_KEY_MAX}자).`;
|
|
1366
|
+
// 맨 앞 (?i) 같은 Python 플래그는 JS 플래그로 바꿔 검사한다 (서버는 Python re)
|
|
1367
|
+
const { source, flags } = toJsRegex(key);
|
|
817
1368
|
let re;
|
|
818
1369
|
try {
|
|
819
|
-
re = new RegExp(
|
|
1370
|
+
re = new RegExp(source, flags);
|
|
820
1371
|
} catch (e) {
|
|
821
1372
|
return `기준 답안이 올바른 정규표현식이 아닙니다: ${e.message}`;
|
|
822
1373
|
}
|
|
823
|
-
if (!
|
|
1374
|
+
if (!source.startsWith('^') || !source.endsWith('$') || /(^|[^\\])(\\\\)*\\\$$/.test(source))
|
|
824
1375
|
return '기준 답안은 ^로 시작해 $로 끝나야 합니다 (답 전체와 맞춰야 부분만 맞아도 정답이 되지 않음).';
|
|
825
1376
|
const now = () => (typeof performance === 'undefined' ? Date.now() : performance.now());
|
|
826
1377
|
const slow = text => {
|
|
@@ -833,12 +1384,51 @@ export function validateAnswerRegex(regex, samples = []) {
|
|
|
833
1384
|
if (samples.some(slow)) return tooSlow;
|
|
834
1385
|
// 겹친 반복(예: (a+)+)은 길이가 늘수록 시간이 두 배씩 는다: 짧은 길이부터 늘려 가며 재고, 느려지면 바로 멈춘다
|
|
835
1386
|
// (긴 문자열을 한 번에 넣으면 멈추지 않을 수 있다)
|
|
836
|
-
const chars = [...new Set(
|
|
1387
|
+
const chars = [...new Set(source.replace(/\\./g, '').match(/[A-Za-z0-9가-힣%=;,]/g) ?? ['a'])].slice(0, 4);
|
|
837
1388
|
for (const c of chars)
|
|
838
1389
|
for (let n = 8; n <= 28; n += 2) if (slow(`${c.repeat(n)}\u0000`)) return tooSlow;
|
|
839
1390
|
return null;
|
|
840
1391
|
}
|
|
841
1392
|
|
|
1393
|
+
/**
|
|
1394
|
+
* partial_pattern 채점 설정 검사 (서버 저장 규칙과 같게): 문항 수 1~50 · 정답과 점수 개수가 같음 ·
|
|
1395
|
+
* 점수는 0~100 정수 · 합계 100 이상(작으면 다 맞혀도 완료되지 않음) · 문항마다 validateAnswerRegex.
|
|
1396
|
+
* 문제가 없으면 null, 있으면 보여 줄 문장
|
|
1397
|
+
* @param {{ answer_key: string[], scores: number[] }} grading
|
|
1398
|
+
* @returns {string | null}
|
|
1399
|
+
*/
|
|
1400
|
+
export function validatePartialGrading({ answer_key: answerKey, scores } = {}) {
|
|
1401
|
+
if (!Array.isArray(answerKey) || !Array.isArray(scores))
|
|
1402
|
+
return '문항별 기준 답안과 점수를 입력해 주세요.';
|
|
1403
|
+
if (answerKey.length < 1 || answerKey.length > PARTIAL_ITEMS_MAX)
|
|
1404
|
+
return `문항은 1개부터 ${PARTIAL_ITEMS_MAX}개까지 채점할 수 있습니다 (지금 ${answerKey.length}개).`;
|
|
1405
|
+
if (scores.length !== answerKey.length)
|
|
1406
|
+
return `기준 답안(${answerKey.length}개)과 점수(${scores.length}개)의 개수가 같아야 합니다.`;
|
|
1407
|
+
const badScore = scores.findIndex(n => !Number.isInteger(n) || n < 0 || n > 100);
|
|
1408
|
+
if (badScore >= 0) return `${badScore + 1}번 문항 점수는 0부터 100 사이의 정수로 입력해 주세요.`;
|
|
1409
|
+
const total = scores.reduce((sum, n) => sum + n, 0);
|
|
1410
|
+
if (total < 100)
|
|
1411
|
+
return `점수 합계가 100점 이상이어야 합니다 (지금 ${total}점). 100점보다 작으면 다 맞혀도 완료되지 않습니다.`;
|
|
1412
|
+
for (const [i, regex] of answerKey.entries()) {
|
|
1413
|
+
const problem = validateAnswerRegex(regex);
|
|
1414
|
+
if (problem) return `${i + 1}번 문항: ${problem}`;
|
|
1415
|
+
}
|
|
1416
|
+
return null;
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
/**
|
|
1420
|
+
* 문항 n개에 100점을 정수로 똑같이 나눈다. 합은 꼭 100, 나머지는 뒤 문항에 1점씩 (3 → [33, 33, 34])
|
|
1421
|
+
* @param {number} n 문항 수 (1 이상)
|
|
1422
|
+
* @returns {number[]}
|
|
1423
|
+
*/
|
|
1424
|
+
export function splitScores(n) {
|
|
1425
|
+
const count = Math.floor(n);
|
|
1426
|
+
if (!(count >= 1)) return [];
|
|
1427
|
+
const base = Math.floor(100 / count);
|
|
1428
|
+
const rest = 100 - base * count;
|
|
1429
|
+
return Array.from({ length: count }, (_, i) => base + (i >= count - rest ? 1 : 0));
|
|
1430
|
+
}
|
|
1431
|
+
|
|
842
1432
|
/** 라디오 카드 하나 (LXP 설정 모양) */
|
|
843
1433
|
function radioCard(name, value, info, checked) {
|
|
844
1434
|
const card = h('label', { className: 'ec-grading-type' });
|
|
@@ -881,7 +1471,7 @@ function mountGradingBlock(app, { graders = ['pattern', 'rubric'], examples = GR
|
|
|
881
1471
|
spellcheck: false,
|
|
882
1472
|
});
|
|
883
1473
|
keyInput.className = 'ec-grading-key';
|
|
884
|
-
keyInput.value = saved?.answer_key
|
|
1474
|
+
keyInput.value = typeof saved?.answer_key === 'string' ? saved.answer_key : '';
|
|
885
1475
|
const toggle = h('button', { type: 'button', className: 'ec-text-button', textContent: t.examples });
|
|
886
1476
|
const exampleList = h('dl', { className: 'ec-grading-examples', hidden: true });
|
|
887
1477
|
for (const [regex, meaning] of examples)
|
|
@@ -952,3 +1542,194 @@ function showBanner(error) {
|
|
|
952
1542
|
}
|
|
953
1543
|
el.textContent = error.message;
|
|
954
1544
|
}
|
|
1545
|
+
|
|
1546
|
+
/**
|
|
1547
|
+
* 빈 안내 (app.emptyState): 그림(lib/icons/empty-content.js) + 제목 + 설명, 가운데 · role=status.
|
|
1548
|
+
* 색은 lib/elice-content.css .ec-empty: 밝은 테마 = EDS 토큰, 어두운 테마(data-eds-theme="dark") · theme: 'dark' = 어두운 그림
|
|
1549
|
+
*/
|
|
1550
|
+
function emptyState({
|
|
1551
|
+
title = MESSAGES.content_empty,
|
|
1552
|
+
description = MESSAGES.content_empty_description,
|
|
1553
|
+
theme,
|
|
1554
|
+
} = {}) {
|
|
1555
|
+
const box = h('div', { className: 'ec-empty', role: 'status' });
|
|
1556
|
+
if (theme === 'dark') box.dataset.theme = 'dark';
|
|
1557
|
+
box.append(emptyContentArt(), h('p', { className: 'ec-empty-title', textContent: title }));
|
|
1558
|
+
if (description) box.append(h('p', { className: 'ec-empty-desc', textContent: description }));
|
|
1559
|
+
return box;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
/**
|
|
1563
|
+
* 불러오는 동안 보일 자리 (회색 면 + 빛, "불러오는 중…"은 화면 읽기 프로그램에만). start()를 기다리기 전에
|
|
1564
|
+
* #app에 넣는다: `root.replaceChildren(skeleton('edit'))`. 자료마다 다른 모양은 parts로 고른다.
|
|
1565
|
+
* layout 'learn': 화면을 채우는 면 하나 (parts 무시). 'edit': parts를 위에서부터 쌓는다
|
|
1566
|
+
* parts: 'bar'(파일 줄 48px) · 'media'(16:9 미리보기) — 기본은 파일 줄 + 미리보기 (동영상 · PDF/PPT)
|
|
1567
|
+
* @param {'learn' | 'edit'} [layout]
|
|
1568
|
+
* @param {{ label?: string, parts?: Array<'bar' | 'media'> }} [opts]
|
|
1569
|
+
* @returns {HTMLElement} `.ec-sk` (role="status")
|
|
1570
|
+
*/
|
|
1571
|
+
export function skeleton(layout = 'learn', { label = '불러오는 중…', parts = ['bar', 'media'] } = {}) {
|
|
1572
|
+
const learn = layout === 'learn';
|
|
1573
|
+
const el = h('div', { className: learn ? 'ec-sk ec-sk-learn ec-sk-shimmer' : 'ec-sk ec-sk-edit' });
|
|
1574
|
+
el.setAttribute('role', 'status');
|
|
1575
|
+
el.append(h('span', { className: 'ec-visually-hidden', textContent: label }));
|
|
1576
|
+
if (!learn) for (const part of parts) el.append(h('div', { className: `ec-sk-${part} ec-sk-shimmer` }));
|
|
1577
|
+
return el;
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
/**
|
|
1581
|
+
* canvas 그림 버퍼를 화면에 보이는 크기 × devicePixelRatio로 맞춘다 (흐리거나 넘치지 않게). 크기가 바뀔 때마다 다시 맞추고
|
|
1582
|
+
* onResize({ ctx, width, height, dpr })를 부른다: 그 안에서 받은 ctx로 다시 그린다 (처음 한 번은 fitCanvas 안에서 바로 부르므로
|
|
1583
|
+
* 돌려받은 값이 아니라 인자의 ctx를 쓴다). ctx는 dpr만큼 늘려 두어 CSS px 단위로 그리면 된다.
|
|
1584
|
+
* stage 칸 바로 아래 canvas는 키트 CSS가 칸 크기에 맞춘다 (elice-content.css "레이아웃")
|
|
1585
|
+
* @param {HTMLCanvasElement} canvas
|
|
1586
|
+
* @param {(size: { ctx: CanvasRenderingContext2D | null, width: number, height: number, dpr: number }) => void} [onResize]
|
|
1587
|
+
* @returns {{ ctx: CanvasRenderingContext2D | null, size: { width: number, height: number, dpr: number }, stop: () => void }}
|
|
1588
|
+
*/
|
|
1589
|
+
export function fitCanvas(canvas, onResize) {
|
|
1590
|
+
const ctx = canvas.getContext("2d");
|
|
1591
|
+
const size = { width: 0, height: 0, dpr: 1 };
|
|
1592
|
+
const apply = () => {
|
|
1593
|
+
const box = canvas.getBoundingClientRect();
|
|
1594
|
+
const dpr = Math.min(globalThis.devicePixelRatio || 1, 3);
|
|
1595
|
+
const w = Math.max(1, Math.round(box.width * dpr));
|
|
1596
|
+
const hgt = Math.max(1, Math.round(box.height * dpr));
|
|
1597
|
+
if (canvas.width !== w) canvas.width = w;
|
|
1598
|
+
if (canvas.height !== hgt) canvas.height = hgt;
|
|
1599
|
+
ctx?.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
1600
|
+
Object.assign(size, { width: box.width, height: box.height, dpr });
|
|
1601
|
+
onResize?.({ ctx, ...size });
|
|
1602
|
+
};
|
|
1603
|
+
const observer = typeof ResizeObserver === "function" ? new ResizeObserver(apply) : null;
|
|
1604
|
+
observer?.observe(canvas);
|
|
1605
|
+
apply();
|
|
1606
|
+
return { ctx, size, stop: () => observer?.disconnect() };
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
// ---------- 편집 화면 도우미 (모양은 elice-content.css의 편집 화면 절) ----------
|
|
1610
|
+
|
|
1611
|
+
/** 스낵바가 떠 있는 시간 (되돌리기를 누를 수 있는 시간) */
|
|
1612
|
+
export const SNACKBAR_MS = 6000;
|
|
1613
|
+
let snackbar = null;
|
|
1614
|
+
|
|
1615
|
+
/**
|
|
1616
|
+
* 스낵바 (EDS Snackbar · info): 지우기 · 바꾸기처럼 되돌릴 수 있는 변경 뒤에 화면 아래 가운데에 잠깐 띄운다.
|
|
1617
|
+
* 한 번에 하나만(새 것이 앞의 것을 대신), body에 붙여 화면 영역을 다시 그려도 남고 저장 전 표시(useSave)를 켜지 않는다.
|
|
1618
|
+
* 초점은 옮기지 않는다 (focus: true면 되돌리기 버튼으로: 키보드로 지웠을 때 초점이 갈 곳).
|
|
1619
|
+
* onClose(까닭)는 한 번만: 'action'(눌렀음) · 'timeout'(시간이 지남) · 'replaced'(새 스낵바) · 'close'(close())
|
|
1620
|
+
* @param {{ text: string, action?: string, onAction?: () => void, onClose?: (reason: string) => void,
|
|
1621
|
+
* ms?: number, focus?: boolean }} opts
|
|
1622
|
+
* @returns {{ element: HTMLElement, close: () => void }}
|
|
1623
|
+
*/
|
|
1624
|
+
export function showSnackbar({
|
|
1625
|
+
text,
|
|
1626
|
+
action = '되돌리기',
|
|
1627
|
+
onAction,
|
|
1628
|
+
onClose,
|
|
1629
|
+
ms = SNACKBAR_MS,
|
|
1630
|
+
focus = false,
|
|
1631
|
+
}) {
|
|
1632
|
+
snackbar?.close('replaced');
|
|
1633
|
+
const element = h('div', { className: 'ec-snackbar' });
|
|
1634
|
+
element.setAttribute('role', 'status');
|
|
1635
|
+
element.dataset.ecQuiet = '';
|
|
1636
|
+
const icon = h('span', { className: 'ec-snackbar-icon' });
|
|
1637
|
+
icon.innerHTML =
|
|
1638
|
+
'<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/></svg>';
|
|
1639
|
+
element.append(icon, h('span', { className: 'ec-snackbar-text', textContent: text }));
|
|
1640
|
+
let timer;
|
|
1641
|
+
let open = true;
|
|
1642
|
+
const close = (reason = 'close') => {
|
|
1643
|
+
if (!open) return;
|
|
1644
|
+
open = false;
|
|
1645
|
+
clearTimeout(timer);
|
|
1646
|
+
// 초점이 스낵바에 있었는지는 onClose가 볼 수 있게 지우기 전에 알린다
|
|
1647
|
+
onClose?.(reason);
|
|
1648
|
+
element.remove();
|
|
1649
|
+
if (snackbar?.element === element) snackbar = null;
|
|
1650
|
+
};
|
|
1651
|
+
if (onAction) {
|
|
1652
|
+
const button = h('button', { type: 'button', className: 'ec-snackbar-action', textContent: action });
|
|
1653
|
+
button.addEventListener('click', () => {
|
|
1654
|
+
close('action');
|
|
1655
|
+
onAction();
|
|
1656
|
+
});
|
|
1657
|
+
element.append(button);
|
|
1658
|
+
}
|
|
1659
|
+
document.body.append(element);
|
|
1660
|
+
timer = setTimeout(() => close('timeout'), ms);
|
|
1661
|
+
snackbar = { element, close };
|
|
1662
|
+
if (focus) element.querySelector('button')?.focus();
|
|
1663
|
+
return snackbar;
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
/** 파일 크기 · 길이 · 쪽 수를 "1.4MB, 8쪽" · "120MB, 08:30"처럼 (모르는 값은 뺀다) */
|
|
1667
|
+
export function formatFileMeta({ size, duration, pages } = {}) {
|
|
1668
|
+
const parts = [];
|
|
1669
|
+
if (typeof size === 'number' && size >= 0) {
|
|
1670
|
+
const units = ['B', 'KB', 'MB', 'GB'];
|
|
1671
|
+
let value = size;
|
|
1672
|
+
let unit = 0;
|
|
1673
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
1674
|
+
value /= 1024;
|
|
1675
|
+
unit += 1;
|
|
1676
|
+
}
|
|
1677
|
+
parts.push(`${unit > 0 && value < 10 ? value.toFixed(1) : Math.round(value)}${units[unit]}`);
|
|
1678
|
+
}
|
|
1679
|
+
if (typeof duration === 'number' && duration > 0) {
|
|
1680
|
+
const total = Math.round(duration);
|
|
1681
|
+
const hours = Math.floor(total / 3600);
|
|
1682
|
+
const mm = String(Math.floor((total % 3600) / 60)).padStart(2, '0');
|
|
1683
|
+
const ss = String(total % 60).padStart(2, '0');
|
|
1684
|
+
parts.push(hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`);
|
|
1685
|
+
}
|
|
1686
|
+
if (typeof pages === 'number' && pages > 0) parts.push(`${pages}쪽`);
|
|
1687
|
+
return parts.join(', ');
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
/**
|
|
1691
|
+
* 올린 파일 한 줄 (V3 시안: 동영상 · PDF/PPT 공통). 흰 줄에 파일 아이콘 · 이름(굵게) · 크기 등 · 오른쪽 "다른 파일로 변경".
|
|
1692
|
+
* 무엇을 고르고 올릴지는 템플릿이 정한다 (onChange에서 동영상은 부모 창 업로드, 문서는 파일 고르기).
|
|
1693
|
+
* icon: lib/icons/의 아이콘 — 동영상 fileVideoIcon()(icons/file-video.js) · 그 밖 fileIcon()(icons/file.js).
|
|
1694
|
+
* 쓰는 아이콘만 import하므로 zip에는 그 그림과 Font Awesome 출처 주석만 들어간다
|
|
1695
|
+
* @param {{ icon?: Element, name: string, meta?: string, changeLabel?: string, onChange?: () => void,
|
|
1696
|
+
* disabled?: boolean }} opts
|
|
1697
|
+
* @returns {HTMLElement} `.ec-file-bar` (버튼은 data-role="change")
|
|
1698
|
+
*/
|
|
1699
|
+
export function fileBar({ icon, name, meta = '', changeLabel = '다른 파일로 변경', onChange, disabled = false }) {
|
|
1700
|
+
const bar = h('div', { className: 'ec-file-bar' });
|
|
1701
|
+
if (icon) {
|
|
1702
|
+
const box = h('span', { className: 'ec-file-icon' });
|
|
1703
|
+
box.append(icon);
|
|
1704
|
+
bar.append(box);
|
|
1705
|
+
}
|
|
1706
|
+
bar.append(
|
|
1707
|
+
h('span', { className: 'ec-file-name', textContent: name, title: name }),
|
|
1708
|
+
h('span', { className: 'ec-file-meta', textContent: meta })
|
|
1709
|
+
);
|
|
1710
|
+
if (onChange) {
|
|
1711
|
+
const button = h('button', {
|
|
1712
|
+
type: 'button',
|
|
1713
|
+
className: 'ec-button-small',
|
|
1714
|
+
textContent: changeLabel,
|
|
1715
|
+
disabled,
|
|
1716
|
+
});
|
|
1717
|
+
button.dataset.role = 'change';
|
|
1718
|
+
button.addEventListener('click', () => onChange());
|
|
1719
|
+
bar.append(button);
|
|
1720
|
+
}
|
|
1721
|
+
return bar;
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/** ⓘ 안내 목록 (지원 형식 · 최대 크기처럼 칸 아래 조건들). 한 줄이면 `.ec-info-line`처럼 쓴다 */
|
|
1725
|
+
export function infoList(lines) {
|
|
1726
|
+
const list = h('ul', { className: 'ec-info-list' });
|
|
1727
|
+
for (const line of lines) {
|
|
1728
|
+
const item = h('li');
|
|
1729
|
+
item.innerHTML =
|
|
1730
|
+
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/></svg>';
|
|
1731
|
+
item.append(document.createTextNode(line));
|
|
1732
|
+
list.append(item);
|
|
1733
|
+
}
|
|
1734
|
+
return list;
|
|
1735
|
+
}
|