@eliceio/cdk-cli 1.2.1 → 1.3.0-contenttypes.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -53
- package/es/cli.js +11 -2
- package/es/commands/build/index.js +12 -0
- package/es/commands/create/index.js +2 -0
- 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/commands/doctor/index.js +6 -2
- package/es/core/config.d.ts +42 -9
- package/es/core/config.js +217 -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/assets.d.ts +80 -0
- package/es/dev/assets.js +240 -0
- package/es/dev/check.d.ts +30 -0
- package/es/dev/check.js +224 -34
- package/es/dev/grading.d.ts +49 -14
- package/es/dev/grading.js +109 -29
- package/es/dev/host-page.js +27 -3
- package/es/dev/inject.d.ts +2 -1
- package/es/dev/inject.js +10 -2
- package/es/dev/mock-api.d.ts +26 -3
- package/es/dev/mock-api.js +219 -40
- package/es/dev/server.d.ts +12 -1
- package/es/dev/server.js +115 -9
- 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 +34 -5
- 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 +10 -8
- package/skills/_shared/references/04-rules.md +1 -1
- package/skills/_shared/references/05-screen-code.md +52 -23
- 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 +8 -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/skills/elice-content-publish/SKILL.md +1 -1
- package/templates/_shared/lib/cdk-mock.d.ts +47 -3
- package/templates/_shared/lib/cdk-mock.js +293 -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 +222 -23
- package/templates/_shared/lib/elice-content.js +1176 -88
- 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 +6 -4
- package/templates/blank/edit.html +8 -2
- package/templates/blank/index.html +6 -1
- package/templates/blank/instructor.html +6 -1
- package/templates/blank/screens/instructor.js +8 -2
- package/templates/blank/screens/learn.js +1 -1
- package/templates/blank/template.json +1 -1
- package/templates/document/README.md +92 -0
- package/templates/document/commentary.txt +2 -0
- package/templates/document/core/dom.d.ts +13 -0
- package/templates/document/core/dom.js +83 -0
- package/templates/document/core/file-type.d.ts +21 -0
- package/templates/document/core/file-type.js +85 -0
- package/templates/document/core/group-3d.d.ts +20 -0
- package/templates/document/core/group-3d.js +256 -0
- package/templates/document/core/inline-edit.d.ts +15 -0
- package/templates/document/core/inline-edit.js +377 -0
- package/templates/document/core/load.d.ts +13 -0
- package/templates/document/core/load.js +40 -0
- package/templates/document/core/pdf-options.d.ts +9 -0
- package/templates/document/core/pdf-options.js +36 -0
- package/templates/document/core/pdf-worker.d.ts +24 -0
- package/templates/document/core/pdf-worker.js +122 -0
- package/templates/document/core/pdf.d.ts +12 -0
- package/templates/document/core/pdf.js +190 -0
- package/templates/document/core/pptx-edit.d.ts +14 -0
- package/templates/document/core/pptx-edit.js +137 -0
- package/templates/document/core/pptx-fonts.d.ts +5 -0
- package/templates/document/core/pptx-fonts.js +115 -0
- package/templates/document/core/pptx-media.d.ts +18 -0
- package/templates/document/core/pptx-media.js +83 -0
- package/templates/document/core/pptx-view.d.ts +5 -0
- package/templates/document/core/pptx-view.js +185 -0
- package/templates/document/core/settings.d.ts +25 -0
- package/templates/document/core/settings.js +86 -0
- package/templates/document/core/slide-edges.d.ts +3 -0
- package/templates/document/core/slide-edges.js +82 -0
- package/templates/document/core/viewer.d.ts +28 -0
- package/templates/document/core/viewer.js +159 -0
- package/templates/document/edit.html +17 -0
- package/templates/document/gitignore +4 -0
- package/templates/document/index.html +18 -0
- package/templates/document/metadata.json +9 -0
- package/templates/document/package.json +17 -0
- package/templates/document/public/fonts/OFL-Caladea.txt +93 -0
- package/templates/document/public/fonts/OFL-Carlito.txt +93 -0
- package/templates/document/public/fonts/caladea-latin-400-normal.woff2 +0 -0
- package/templates/document/public/fonts/caladea-latin-700-normal.woff2 +0 -0
- package/templates/document/public/fonts/carlito-latin-400-normal.woff2 +0 -0
- package/templates/document/public/fonts/carlito-latin-700-normal.woff2 +0 -0
- package/templates/document/screens/edit.js +574 -0
- package/templates/document/screens/learn.js +61 -0
- package/templates/document/styles.css +644 -0
- package/templates/document/template.json +6 -0
- package/templates/document/ui/templates/edit.js +82 -0
- package/templates/document/ui/templates/page.js +11 -0
- package/templates/document/ui/templates/viewer.js +41 -0
- package/templates/document/ui/texts.d.ts +3 -0
- package/templates/document/ui/texts.js +62 -0
- package/templates/document/ui/theme.css +69 -0
- package/templates/quiz/README.md +32 -14
- package/templates/quiz/core/behaviors.d.ts +17 -7
- package/templates/quiz/core/behaviors.js +40 -53
- package/templates/quiz/core/editor.d.ts +27 -2
- package/templates/quiz/core/editor.js +412 -11
- package/templates/quiz/core/markdown.d.ts +19 -0
- package/templates/quiz/core/markdown.js +225 -11
- package/templates/quiz/core/model.d.ts +40 -3
- package/templates/quiz/core/model.js +112 -5
- package/templates/quiz/core/rich-text.d.ts +18 -0
- package/templates/quiz/core/rich-text.js +469 -0
- package/templates/quiz/edit.html +12 -3
- package/templates/quiz/index.html +12 -3
- package/templates/quiz/public/img/mascot-half.webp +0 -0
- package/templates/quiz/screens/edit.js +331 -49
- package/templates/quiz/screens/learn.js +147 -15
- package/templates/quiz/styles.css +1244 -622
- package/templates/quiz/template.json +9 -2
- package/templates/quiz/ui/templates/edit.d.ts +19 -5
- package/templates/quiz/ui/templates/edit.js +371 -77
- 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 +33 -8
- package/templates/quiz/ui/templates/question.js +6 -4
- package/templates/quiz/ui/texts.js +91 -26
- 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,10 @@
|
|
|
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
|
+
* 자료 파일 (편집 화면에서 PDF · PPTX 올리기, 학생 화면에서 열기): app.assets.uploadFile(file, { onProgress, signal }) · await app.assets.url(asset_key)
|
|
10
|
+
* 이미지 (편집 화면에서 줄여 올리기): app.assets.uploadImage(file, { onProgress, signal }) · 보기는 같은 app.assets.url(asset_key)
|
|
11
|
+
* 화면 틀: data-ec-layout="single | split | stage | media" + data-ec-region (CSS만, lib/elice-content.css "레이아웃" 절)
|
|
9
12
|
* 읽기 전용 잠금, 답 복원, 결과·오류 안내, 저장 문구, 로컬 mock 표시는 키트가 합니다.
|
|
10
13
|
*
|
|
11
14
|
* 화면(screens/*.js)은 이 키트만 부릅니다. 키트가 SDK로 인증 · 화면 확인 · 내용 불러오기 ·
|
|
@@ -28,10 +31,11 @@
|
|
|
28
31
|
* await app.submit(answer)
|
|
29
32
|
*
|
|
30
33
|
* 정답은 콘텐츠(zip)에 넣지 않습니다. 채점은 서버가 채점 설정(settings.grading)으로 합니다 (ADR 0009).
|
|
31
|
-
* 채점 설정 { type: pattern | rubric, answer_key | rubric }은 편집 화면이 edit 토큰으로 저장하고, 서버는 학생에게
|
|
34
|
+
* 채점 설정 { type: pattern | partial_pattern | rubric, answer_key (+ scores) | rubric }은 편집 화면이 edit 토큰으로 저장하고, 서버는 학생에게
|
|
32
35
|
* settings.grading을 내려주지 않습니다. 완료 정책(on_access · on_submit · on_graded)은 콘텐츠가 다루지 않습니다:
|
|
33
36
|
* LXP에 올린 뒤 자료 편집 화면의 '설정'에서 교육자가 고릅니다 (ADR 0012).
|
|
34
37
|
*/
|
|
38
|
+
import { emptyContentArt } from './icons/empty-content.js';
|
|
35
39
|
|
|
36
40
|
/**
|
|
37
41
|
* 이 HTML(metadata.json의 learn · instructor · edit)을 SDK가 알려 준 화면 · 보는 사람으로 열어도 되는지.
|
|
@@ -51,9 +55,12 @@ const MESSAGES = {
|
|
|
51
55
|
read_only_mode: '보기 전용 화면이라 제출할 수 없습니다.',
|
|
52
56
|
rate_limited: '제출이 너무 잦습니다. 잠시 뒤 다시 시도해 주세요.',
|
|
53
57
|
invalid_input: '답이 너무 크거나 형식이 올바르지 않습니다.',
|
|
58
|
+
// 키트만의 문구: 저장(settings)이 서버 크기 한도를 넘음 (invalid_input · reason too_large)
|
|
59
|
+
save_too_large: '저장할 내용이 너무 커요. 그림이나 글을 줄여 주세요.',
|
|
54
60
|
content_not_ready: '아직 저장된 자료가 없습니다.',
|
|
55
|
-
// 키트만의 문구: 편집 화면이 아직 내용을 저장하지 않음 (기본 내용 파일은 없음)
|
|
56
|
-
content_empty: '
|
|
61
|
+
// 키트만의 문구: 편집 화면이 아직 내용을 저장하지 않음 (기본 내용 파일은 없음). app.emptyState()의 제목 · 설명
|
|
62
|
+
content_empty: '학습 자료를 준비하고 있어요',
|
|
63
|
+
content_empty_description: '준비가 완료되면 이곳에서 볼 수 있어요',
|
|
57
64
|
external_service_error: '채점하지 못했어요. 제출이 저장되지 않았으니 다시 제출해 주세요.',
|
|
58
65
|
screen_not_supported: '이 화면에서는 할 수 없는 일입니다.',
|
|
59
66
|
navigation_timeout: '수업 페이지 정보를 받지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
|
|
@@ -65,11 +72,30 @@ const MESSAGES = {
|
|
|
65
72
|
// 서버 코드 (SDK content_not_ready의 cause): 업로드한 draft를 아직 처리 중이거나 처리에 실패함 (409)
|
|
66
73
|
material_draft_not_ready:
|
|
67
74
|
'업로드한 자료를 아직 처리하고 있거나 처리하지 못했어요. 잠시 뒤 다시 저장하고, 계속되면 자료를 다시 올려 주세요.',
|
|
75
|
+
// 서버 422 VALIDATION_ERROR (SDK는 이 코드를 몰라 request_failed로 넘김): 학생 제출 · 편집 화면 저장
|
|
76
|
+
submit_invalid: '이 자료의 채점 설정과 답 모양이 맞지 않아 제출하지 못했어요. 교육자에게 알려 주세요.',
|
|
77
|
+
save_scores_too_low: '배점 합계는 100점 이상이어야 합니다.',
|
|
78
|
+
save_length_mismatch: '문항별 정답과 점수의 개수가 맞지 않아요.',
|
|
79
|
+
save_regex_invalid: '정답 형식이 올바르지 않아요.',
|
|
80
|
+
save_invalid: '저장할 내용의 형식이 올바르지 않아요.',
|
|
68
81
|
not_initialized: '아직 준비되지 않았습니다.',
|
|
82
|
+
// 키트만의 코드: 자료 파일 올리기 (app.assets.uploadFile)
|
|
83
|
+
upload_not_supported:
|
|
84
|
+
'아직 파일을 올릴 수 없어요. 이 SDK에는 파일 올리기가 없습니다 (@eliceio/cdk를 올려 주세요).',
|
|
85
|
+
upload_failed: '파일을 올리지 못했어요. 잠시 뒤 다시 시도해 주세요.',
|
|
86
|
+
upload_bad_file: '파일이 비어 있거나 95MB를 넘어 올릴 수 없어요.',
|
|
87
|
+
upload_bad_type: 'PDF나 PPTX 파일만 올릴 수 있어요.',
|
|
88
|
+
// 키트만의 코드: 이미지 올리기 (app.assets.uploadImage). 코드는 파일과 같고 문구만 이미지용
|
|
89
|
+
image_bad_type: 'PNG · JPEG · WebP · GIF 이미지만 올릴 수 있어요.',
|
|
90
|
+
image_bad_file: '이미지가 비어 있거나 10MB를 넘어 올릴 수 없어요.',
|
|
91
|
+
image_unreadable: '이미지를 읽지 못했어요. 다른 파일로 다시 시도해 주세요.',
|
|
69
92
|
request_failed: '서버와 연결하지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
|
|
70
93
|
// 키트만의 코드: 자료 주소인데 접속 토큰이 없음 (새로고침 · 다른 HTML로 이동하면 SDK가 지운 토큰이 남지 않는다)
|
|
71
94
|
reopen_required:
|
|
72
95
|
'자료를 다시 열어 주세요. 새로고침하거나 다른 페이지로 옮기면 다시 열어야 합니다.',
|
|
96
|
+
// 키트만의 코드: ecdk build 결과물(dist/content)을 LXP 밖에서 열었다. 운영 zip에는 흉내 SDK가 없다
|
|
97
|
+
mock_unavailable:
|
|
98
|
+
'빌드한 화면에는 로컬 흉내 SDK가 없습니다. 로컬에서는 ecdk dev로 열고, 실제 화면은 LXP에 올려 확인해 주세요.',
|
|
73
99
|
};
|
|
74
100
|
|
|
75
101
|
export class ContentError extends Error {
|
|
@@ -85,32 +111,86 @@ export class ContentError extends Error {
|
|
|
85
111
|
}
|
|
86
112
|
}
|
|
87
113
|
|
|
88
|
-
/** SDK
|
|
89
|
-
|
|
114
|
+
/** 서버 오류 detail의 ctx.reason들 (SDK 오류의 cause.cause.detail, 예: [{ ctx: { reason: 'too_large' } }]) */
|
|
115
|
+
const reasonsOf = err => {
|
|
116
|
+
const detail = err?.cause?.cause?.detail;
|
|
117
|
+
return Array.isArray(detail) ? detail.map(item => item?.ctx?.reason).filter(Boolean) : [];
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/** 서버 오류 detail의 type들 (pydantic 오류 type, 예: [{ type: 'partial_pattern_scores_too_low' }]) */
|
|
121
|
+
const typesOf = err => {
|
|
122
|
+
const detail = err?.cause?.cause?.detail;
|
|
123
|
+
return Array.isArray(detail) ? detail.map(item => item?.type).filter(t => typeof t === 'string') : [];
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** 저장 422 VALIDATION_ERROR: 서버 detail type → 문구 (type이 없거나 모르면 save_invalid) */
|
|
127
|
+
const SAVE_VALIDATION_MESSAGES = {
|
|
128
|
+
partial_pattern_scores_too_low: 'save_scores_too_low',
|
|
129
|
+
partial_pattern_length_mismatch: 'save_length_mismatch',
|
|
130
|
+
regex_answer_key_invalid: 'save_regex_invalid',
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* SDK 오류를 화면이 그대로 보여 줄 수 있는 한국어 메시지로
|
|
135
|
+
* @param {unknown} err
|
|
136
|
+
* @param {'save' | 'submit'} [action] 무엇을 하다 났는지 (저장이면 크기 초과 문구가 다르고, 422 VALIDATION_ERROR는 저장 · 제출마다 문구가 다르다)
|
|
137
|
+
*/
|
|
138
|
+
function toContentError(err, action) {
|
|
90
139
|
if (err instanceof ContentError) return err;
|
|
140
|
+
if (action === 'save' && err?.code === 'invalid_input' && reasonsOf(err).includes('too_large'))
|
|
141
|
+
return new ContentError('invalid_input', MESSAGES.save_too_large, err);
|
|
91
142
|
// 서버 오류 코드는 SDK 오류의 cause.cause.code에 있다 (예: 409 MATERIAL_DRAFT_NOT_READY → SDK content_not_ready)
|
|
92
143
|
const serverCode = err?.cause?.cause?.code;
|
|
93
144
|
if (serverCode === 'MATERIAL_DRAFT_NOT_READY')
|
|
94
145
|
return new ContentError('material_draft_not_ready', MESSAGES.material_draft_not_ready, err);
|
|
95
146
|
if (serverCode === 'MATERIAL_GRADING_REQUIRED')
|
|
96
147
|
return new ContentError('material_grading_required', MESSAGES.material_grading_required, err);
|
|
148
|
+
// 422 VALIDATION_ERROR: 제출은 채점 설정과 답 모양이 맞지 않음(예: partial_pattern인데 문자열 답), 저장은 detail type별
|
|
149
|
+
if (serverCode === 'VALIDATION_ERROR' && action === 'submit')
|
|
150
|
+
return new ContentError('validation_error', MESSAGES.submit_invalid, err);
|
|
151
|
+
if (serverCode === 'VALIDATION_ERROR' && action === 'save') {
|
|
152
|
+
const key = typesOf(err).map(t => SAVE_VALIDATION_MESSAGES[t]).find(Boolean) ?? 'save_invalid';
|
|
153
|
+
return new ContentError('validation_error', MESSAGES[key], err);
|
|
154
|
+
}
|
|
97
155
|
const code = typeof err?.code === 'string' ? err.code : 'request_failed';
|
|
98
156
|
return new ContentError(code, MESSAGES[code] ?? MESSAGES.request_failed, err);
|
|
99
157
|
}
|
|
100
158
|
|
|
159
|
+
/**
|
|
160
|
+
* 점수를 숫자로: 서버가 "70" · "70.00"처럼 글자로 줄 때가 있다 (SDK는 그대로 넘김). null · undefined는 그대로,
|
|
161
|
+
* 숫자로 읽지 못하는 값도 그대로 둔다
|
|
162
|
+
*/
|
|
163
|
+
function toScore(value) {
|
|
164
|
+
if (typeof value !== 'string' || value.trim() === '') return value;
|
|
165
|
+
const n = Number(value);
|
|
166
|
+
return Number.isFinite(n) ? n : value;
|
|
167
|
+
}
|
|
168
|
+
/** score가 글자인 결과 객체는 score만 숫자로 바꾼 사본을, 아니면 그대로 */
|
|
169
|
+
function withNumberScore(r) {
|
|
170
|
+
if (!r || typeof r !== 'object' || typeof r.score !== 'string') return r;
|
|
171
|
+
return { ...r, score: toScore(r.score) };
|
|
172
|
+
}
|
|
173
|
+
|
|
101
174
|
const MATERIAL_PATH = /\/materials\/[0-9a-f-]{36}\//i;
|
|
102
175
|
|
|
103
176
|
/**
|
|
104
|
-
* 저장된 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` ·
|
|
105
|
-
*
|
|
177
|
+
* 저장된 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` ·
|
|
178
|
+
* `{ type: 'partial_pattern', answer_key: string[], scores: number[] }` · `{ type: 'rubric', rubric }`.
|
|
179
|
+
* 옛 SDK(G129 해결 전)는 settings 안 키까지 camelCase로 바꿔 answer_key가 answerKey로 왔다. 그 SDK로 빌드한 자료를 위해 둘 다 받는다.
|
|
180
|
+
* partial_pattern 배열은 복사해 둔다 (값은 그대로, 검사는 validatePartialGrading).
|
|
106
181
|
* 채점 방식이 아닌 값(옛 on_access · on_submit 등)이면 null
|
|
107
182
|
*/
|
|
108
183
|
export function normalizeGrading(grading) {
|
|
109
184
|
if (!grading || typeof grading !== 'object') return null;
|
|
110
|
-
|
|
111
|
-
|
|
185
|
+
const answerKey = grading.answer_key ?? grading.answerKey;
|
|
186
|
+
if (grading.type === 'pattern')
|
|
112
187
|
return { type: 'pattern', ...(typeof answerKey === 'string' ? { answer_key: answerKey } : {}) };
|
|
113
|
-
|
|
188
|
+
if (grading.type === 'partial_pattern')
|
|
189
|
+
return {
|
|
190
|
+
type: 'partial_pattern',
|
|
191
|
+
answer_key: Array.isArray(answerKey) ? [...answerKey] : [],
|
|
192
|
+
scores: Array.isArray(grading.scores) ? [...grading.scores] : [],
|
|
193
|
+
};
|
|
114
194
|
if (grading.type === 'rubric')
|
|
115
195
|
return { type: 'rubric', ...(typeof grading.rubric === 'string' ? { rubric: grading.rubric } : {}) };
|
|
116
196
|
return null;
|
|
@@ -247,8 +327,13 @@ export async function start(options) {
|
|
|
247
327
|
try {
|
|
248
328
|
if (kind === 'custom') sdk = options.sdk;
|
|
249
329
|
else if (kind === 'mock') {
|
|
250
|
-
|
|
251
|
-
|
|
330
|
+
// ecdk build는 __ECDK_MOCK_SDK__를 false로 바꿔 이 분기를 지운다: 흉내 SDK는 운영 zip에 들어가지 않는다.
|
|
331
|
+
// ecdk dev · 테스트(바꾸지 않음)에서는 그대로 흉내 SDK를 쓴다
|
|
332
|
+
// eslint-disable-next-line no-undef
|
|
333
|
+
if (typeof __ECDK_MOCK_SDK__ === 'undefined' || __ECDK_MOCK_SDK__) {
|
|
334
|
+
const { MockEliceCDK } = await import('./cdk-mock.js');
|
|
335
|
+
sdk = new MockEliceCDK({ onSessionExpired, loadJson: options.loadJson, ...options.mock });
|
|
336
|
+
} else throw new ContentError('mock_unavailable', MESSAGES.mock_unavailable);
|
|
252
337
|
} else sdk = new (await loadRealSdk())({ onSessionExpired, ...devApi() });
|
|
253
338
|
if (kind === 'mock' && typeof console !== 'undefined')
|
|
254
339
|
console.info(
|
|
@@ -289,6 +374,36 @@ export async function start(options) {
|
|
|
289
374
|
/** 다음 저장의 바탕: 서버에 저장된 settings 그대로 */
|
|
290
375
|
let savedSettings = sdk.material?.settings ?? {};
|
|
291
376
|
|
|
377
|
+
/** 파일 · 이미지 올리기 전 확인: 편집 화면, assets.post가 있는 SDK */
|
|
378
|
+
function assertUploadable() {
|
|
379
|
+
if (screen !== 'edit')
|
|
380
|
+
throw new ContentError('screen_not_supported', '파일은 편집 화면에서만 올립니다.');
|
|
381
|
+
if (typeof sdk.assets?.post !== 'function')
|
|
382
|
+
throw new ContentError('upload_not_supported', MESSAGES.upload_not_supported);
|
|
383
|
+
}
|
|
384
|
+
/** SDK assets.post로 올리고 서버 파일 키를. 형식 · 크기 오류는 messages의 문구로 (코드는 upload_bad_type · upload_bad_file) */
|
|
385
|
+
async function postAsset(file, options, messages) {
|
|
386
|
+
assertUploadable();
|
|
387
|
+
try {
|
|
388
|
+
const asset = await sdk.assets.post(file, {
|
|
389
|
+
onProgress: options.onProgress,
|
|
390
|
+
signal: options.signal,
|
|
391
|
+
});
|
|
392
|
+
if (typeof asset?.id !== 'string' || !asset.id)
|
|
393
|
+
throw new ContentError('upload_failed', MESSAGES.upload_failed);
|
|
394
|
+
return asset.id;
|
|
395
|
+
} catch (err) {
|
|
396
|
+
// 취소는 오류 안내 없이 그대로 (SDK는 signal.reason, 보통 AbortError)
|
|
397
|
+
if (err?.name === 'AbortError' || (options.signal?.aborted && err === options.signal.reason))
|
|
398
|
+
throw err;
|
|
399
|
+
if (err?.code === 'file_invalid_size')
|
|
400
|
+
throw new ContentError('upload_bad_file', messages.bad_file, err);
|
|
401
|
+
if (err?.code === 'file_invalid_type')
|
|
402
|
+
throw new ContentError('upload_bad_type', messages.bad_type, err);
|
|
403
|
+
throw toContentError(err);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
292
407
|
const readOnly = viewer === 'tutor';
|
|
293
408
|
const app = {
|
|
294
409
|
/** 이 HTML이 어떤 화면인지 (start에 넘긴 값) */
|
|
@@ -309,8 +424,8 @@ export async function start(options) {
|
|
|
309
424
|
sdkKind: kind,
|
|
310
425
|
/** 보는 사람 { anonymousId, fullname } */
|
|
311
426
|
account: sdk.account,
|
|
312
|
-
/** 내 결과 { score(가장 최근
|
|
313
|
-
result: sdk.result,
|
|
427
|
+
/** 내 결과 { score(가장 최근 채점, 숫자 · null), submitCount, completedAt } 또는 null */
|
|
428
|
+
result: withNumberScore(sdk.result),
|
|
314
429
|
/** 제출이 기록되는지 (학생만, draft · mock 제외) */
|
|
315
430
|
get records() {
|
|
316
431
|
return viewer === 'student' && !app.isDraft && kind !== 'mock';
|
|
@@ -323,13 +438,17 @@ export async function start(options) {
|
|
|
323
438
|
get hasContent() {
|
|
324
439
|
return Object.keys(content).length > 0;
|
|
325
440
|
},
|
|
326
|
-
/**
|
|
327
|
-
|
|
328
|
-
|
|
441
|
+
/**
|
|
442
|
+
* 내용이 없을 때 보여 줄 안내: 가운데 그림 + 제목 "학습 자료를 준비하고 있어요" + 설명. 학생 · 교육자 화면에서
|
|
443
|
+
* app.hasContent가 false일 때. title · description으로 문구를 바꾸고(description: ''이면 설명 줄 없음),
|
|
444
|
+
* theme: 'dark'는 밝은 테마 화면 안의 어두운 바탕(예: 문서 학생 화면)에서 어두운 색으로
|
|
445
|
+
*/
|
|
446
|
+
emptyState(options) {
|
|
447
|
+
return emptyState(options);
|
|
329
448
|
},
|
|
330
449
|
/**
|
|
331
450
|
* 저장된 채점 설정 `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }` 또는 null.
|
|
332
|
-
* edit 범위(편집
|
|
451
|
+
* edit 범위(편집 화면)에서만 오고, 학생 · 튜터 · 교육자 화면에는 서버가 내려주지 않는다
|
|
333
452
|
*/
|
|
334
453
|
get grading() {
|
|
335
454
|
return grading;
|
|
@@ -339,11 +458,11 @@ export async function start(options) {
|
|
|
339
458
|
async submit(answer) {
|
|
340
459
|
if (readOnly) throw new ContentError('read_only_mode', MESSAGES.read_only_mode);
|
|
341
460
|
try {
|
|
342
|
-
const res = await sdk.submit(answer);
|
|
343
|
-
app.result = sdk.result ?? app.result;
|
|
461
|
+
const res = withNumberScore(await sdk.submit(answer));
|
|
462
|
+
app.result = withNumberScore(sdk.result) ?? app.result;
|
|
344
463
|
return res;
|
|
345
464
|
} catch (err) {
|
|
346
|
-
throw toContentError(err);
|
|
465
|
+
throw toContentError(err, 'submit');
|
|
347
466
|
}
|
|
348
467
|
},
|
|
349
468
|
|
|
@@ -356,7 +475,7 @@ export async function start(options) {
|
|
|
356
475
|
async lastSubmission() {
|
|
357
476
|
try {
|
|
358
477
|
const [last] = await sdk.history({ limit: 1 });
|
|
359
|
-
return last ?? null;
|
|
478
|
+
return withNumberScore(last) ?? null;
|
|
360
479
|
} catch (err) {
|
|
361
480
|
throw toContentError(err);
|
|
362
481
|
}
|
|
@@ -365,10 +484,11 @@ export async function start(options) {
|
|
|
365
484
|
/**
|
|
366
485
|
* 내용 저장 (편집 화면): SDK saveSettings가 edit 토큰으로 자료의 draft에 저장한다. 학생에게는 LXP 편집 페이지에서
|
|
367
486
|
* 저장(새 버전)한 뒤 보인다. 보통은 useSave를 쓴다.
|
|
368
|
-
* nextGrading(채점 설정 `{ type, answer_key | rubric }
|
|
487
|
+
* nextGrading(채점 설정 `{ type, answer_key | rubric }`, partial_pattern은 배열 answer_key · scores)을 주면
|
|
488
|
+
* settings.grading으로 그대로(배열도 바꾸지 않고) 같이 저장하고,
|
|
369
489
|
* 주지 않으면 저장된 채점 설정을 그대로 둔다
|
|
370
490
|
* @param {Record<string, unknown>} next
|
|
371
|
-
* @param {{ type: 'pattern' | 'rubric', answer_key?: string, rubric?: string }} [nextGrading]
|
|
491
|
+
* @param {{ type: 'pattern' | 'partial_pattern' | 'rubric', answer_key?: string | string[], scores?: number[], rubric?: string }} [nextGrading]
|
|
372
492
|
*/
|
|
373
493
|
async saveContent(next, nextGrading) {
|
|
374
494
|
if (screen !== 'edit')
|
|
@@ -381,7 +501,7 @@ export async function start(options) {
|
|
|
381
501
|
grading = g;
|
|
382
502
|
savedSettings = settings;
|
|
383
503
|
} catch (err) {
|
|
384
|
-
throw toContentError(err);
|
|
504
|
+
throw toContentError(err, 'save');
|
|
385
505
|
}
|
|
386
506
|
},
|
|
387
507
|
|
|
@@ -396,6 +516,55 @@ export async function start(options) {
|
|
|
396
516
|
return mountSubmit(app, opts);
|
|
397
517
|
},
|
|
398
518
|
|
|
519
|
+
/**
|
|
520
|
+
* 자료 파일 (서버 스펙: POST /storage/upload-url → PUT, settings에는 asset_key, 보기는 asset_base_url + asset_key).
|
|
521
|
+
* SDK `assets.post` · `assets.get`(!99)을 부른다.
|
|
522
|
+
* - uploadFile(file, { onProgress, signal }): 편집 화면에서 올리고 `{ asset_key }`
|
|
523
|
+
* (SDK가 준 id = 서버 파일 키 `assets/{자료 id}/{이름}` 그대로, settings에 그대로 넣음).
|
|
524
|
+
* 종류는 SDK가 파일 형식(MIME), 없으면 확장자로 정한다. signal로 취소하면 AbortError를 그대로 던진다
|
|
525
|
+
* - url(asset_key): Promise로 그 파일 주소 (화면 버전의 서명 주소). 이 자료의 파일이 아니거나 모르면 null
|
|
526
|
+
* - uploadImage(file, { onProgress, signal }): 이미지(PNG · JPEG · WebP · GIF, SVG는 안 받음)를 optimizeImage로 줄인 뒤 올리고
|
|
527
|
+
* `{ asset_key, size, original_size, width, height, type }`. 오류 코드는 uploadFile과 같고 문구만 이미지용,
|
|
528
|
+
* 읽지 못한 그림은 image_unreadable
|
|
529
|
+
* SDK에 assets.post가 없으면(파일 올리기 전 SDK) uploadFile · uploadImage는 upload_not_supported, url은 null.
|
|
530
|
+
* ecdk dev는 실제 SDK가 흉내 서버(.ecdk/assets/)로 올리고 연다
|
|
531
|
+
*/
|
|
532
|
+
assets: {
|
|
533
|
+
async uploadFile(file, options = {}) {
|
|
534
|
+
const asset_key = await postAsset(file, options, {
|
|
535
|
+
bad_type: MESSAGES.upload_bad_type,
|
|
536
|
+
bad_file: MESSAGES.upload_bad_file,
|
|
537
|
+
});
|
|
538
|
+
return { asset_key };
|
|
539
|
+
},
|
|
540
|
+
async uploadImage(file, options = {}) {
|
|
541
|
+
assertUploadable();
|
|
542
|
+
const image = await optimizeImage(file);
|
|
543
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
544
|
+
const asset_key = await postAsset(image.file, options, {
|
|
545
|
+
bad_type: MESSAGES.image_bad_type,
|
|
546
|
+
bad_file: MESSAGES.image_bad_file,
|
|
547
|
+
});
|
|
548
|
+
return {
|
|
549
|
+
asset_key,
|
|
550
|
+
size: image.file.size,
|
|
551
|
+
original_size: file.size,
|
|
552
|
+
width: image.width,
|
|
553
|
+
height: image.height,
|
|
554
|
+
type: image.file.type,
|
|
555
|
+
};
|
|
556
|
+
},
|
|
557
|
+
async url(assetKey) {
|
|
558
|
+
if (typeof assetKey !== 'string' || !assetKey || typeof sdk.assets?.get !== 'function')
|
|
559
|
+
return null;
|
|
560
|
+
try {
|
|
561
|
+
return (await sdk.assets.get(assetKey))?.url || null;
|
|
562
|
+
} catch {
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
},
|
|
566
|
+
},
|
|
567
|
+
|
|
399
568
|
/**
|
|
400
569
|
* 편집 화면의 저장 영역. 저장하지 않은 변경 표시, 검증, 저장 문구, 나가기 경고를 키트가 한다.
|
|
401
570
|
* @param {SaveOptions} opts
|
|
@@ -415,13 +584,21 @@ export async function start(options) {
|
|
|
415
584
|
},
|
|
416
585
|
|
|
417
586
|
/**
|
|
418
|
-
* 자료 안 여러 단계
|
|
587
|
+
* 자료 안 여러 단계 이동 (스테퍼). 단계는 내용 영역 안 `<section data-ec-step>`들, 또는 `{ count, onChange }`로 코드가 그린다.
|
|
588
|
+
* 이전 · 다음 버튼은 양옆 거터의 화면 세로 가운데, 단계 표시 n / N은 왼쪽 아래 (모바일은 화면 아래 가운데 둥근 묶음).
|
|
589
|
+
* 버튼은 `<ec-stepper-nav>`(Shadow DOM, top layer) 안이라 작성자 CSS · z-index가 덮거나 바꾸지 못한다.
|
|
419
590
|
* 첫 단계의 왼쪽 · 마지막 단계의 오른쪽은 LXP 이전 · 다음 수업 자료로 가는 버튼(모양이 다름)이 되고,
|
|
420
591
|
* 그쪽 수업 자료가 없거나 LXP 밖이면 숨긴다. LXP 아래 이전 · 다음 막대와 헷갈리지 않게 아래 막대는 만들지 않는다.
|
|
421
|
-
*
|
|
592
|
+
* ← → 키(입력 칸 · 슬라이더 밖), 단계를 넘기면 제목에 초점 · 화면 맨 위로. 옵션: canNext(다음 막기) · remember(마지막 단계 기억)
|
|
593
|
+
* @param {StepperOptions} [opts]
|
|
422
594
|
*/
|
|
595
|
+
useStepper(opts) {
|
|
596
|
+
return mountStepper(app, opts ?? {});
|
|
597
|
+
},
|
|
598
|
+
|
|
599
|
+
/** useStepper의 옛 이름 (같은 동작) */
|
|
423
600
|
usePaging(opts) {
|
|
424
|
-
return
|
|
601
|
+
return mountStepper(app, opts ?? {});
|
|
425
602
|
},
|
|
426
603
|
};
|
|
427
604
|
if (options.status !== false) showStatus(app);
|
|
@@ -433,22 +610,31 @@ export async function start(options) {
|
|
|
433
610
|
* @property {() => unknown} getAnswer 화면에서 답 모으기
|
|
434
611
|
* @property {(answer: unknown) => void} [setAnswer] 저장된 답을 화면에 채우기 (복원 · 튜터링)
|
|
435
612
|
* @property {(answer: unknown) => true | string} [validate] 통과면 true, 아니면 보여 줄 문장
|
|
436
|
-
* @property {(result: object, info: { restored: boolean }) => void} [onResult] 채점 결과 { isCorrect, score } (제출 직후 · 다시 열었을
|
|
613
|
+
* @property {(result: object, info: { restored: boolean }) => void} [onResult] 채점 결과 { isCorrect, score, answerCorrectness } (제출 직후 · 다시 열었을 때는 마지막 제출 기록). 정답 표시 등에
|
|
614
|
+
* @property {(result: object) => string | undefined} [resultText] 결과 줄 문장을 화면이 정할 때 (undefined면 키트 기본 문장)
|
|
615
|
+
* @property {boolean} [allowUnchanged] true면 같은 답도 다시 제출할 수 있다 (기본: 제출한 답 그대로면 버튼을 끄고 고치면 켬)
|
|
616
|
+
* @property {'result' | 'bottom'} [scrollOnResult] 제출 뒤 스크롤 (기본 'result': 결과 줄을 화면 안으로, 성공일 때만).
|
|
617
|
+
* 'bottom': 서버 응답(성공 · 실패) 뒤 화면 맨 아래로 (결과가 그려진 다음 프레임, 늦게 들어온 그림이 있으면 한 번 더)
|
|
437
618
|
* @property {Element} [root] 잠글 화면 영역 (기본 #app)
|
|
438
619
|
* @property {string} [label] 버튼 글자 (기본 '제출')
|
|
439
620
|
*/
|
|
440
621
|
|
|
441
622
|
/**
|
|
442
|
-
* @typedef {object}
|
|
443
|
-
* @property {number} count 단계 수 (1 이상)
|
|
444
|
-
* @property {(step: number) => void} onChange 단계가 바뀔 때 (0부터). 시작할 때도 한 번
|
|
445
|
-
* @property {number} [start] 처음 단계 (기본 0)
|
|
446
|
-
* @property {Element} [root]
|
|
623
|
+
* @typedef {object} StepperOptions
|
|
624
|
+
* @property {number} [count] 단계 수 (1 이상). 없으면 내용 영역 안 `[data-ec-step]` 요소 수
|
|
625
|
+
* @property {(step: number, ctx: { content: Element, section: Element | null }) => void} [onChange] 단계가 바뀔 때 (0부터). 시작할 때도 한 번
|
|
626
|
+
* @property {number} [start] 처음 단계 (기본 0, remember면 기억한 단계)
|
|
627
|
+
* @property {Element} [root] 내용 영역 (기본 #app)
|
|
628
|
+
* @property {(step: number) => true | string | false} [canNext] 다음으로 가도 되는지. 문장이면 다음 버튼을 막고 그 이유를 보인다 (기본: 늘 됨)
|
|
629
|
+
* @property {boolean | string} [remember] 마지막 단계를 이 브라우저(localStorage)에만 기억, 서버에는 저장하지 않음 (기본 끔, 문자열이면 저장 이름)
|
|
447
630
|
*/
|
|
448
631
|
|
|
632
|
+
/** @typedef {StepperOptions} PagingOptions */
|
|
633
|
+
|
|
449
634
|
/**
|
|
450
635
|
* @typedef {object} SaveOptions
|
|
451
|
-
* @property {() => Record<string, unknown>} getContent 저장할 내용 (학생에게 공개, 정답 넣지 않음)
|
|
636
|
+
* @property {() => Record<string, unknown> | Promise<Record<string, unknown>>} getContent 저장할 내용 (학생에게 공개, 정답 넣지 않음).
|
|
637
|
+
* 저장 직전에 파일을 올려야 하면(예: 고친 문서) Promise를 돌려준다: 끝날 때까지 버튼을 막고, 던진 오류는 저장 문구로 보인다
|
|
452
638
|
* @property {() => object | string | undefined} [getGrading] 같이 저장할 채점 방식 · 답 (settings.grading에 합침, 학생에게 안 감).
|
|
453
639
|
* 문장이면 저장을 막고 보여 줌, undefined면 채점 설정은 그대로 (ADR 0009)
|
|
454
640
|
* @property {(content: Record<string, unknown>) => true | string} [validate]
|
|
@@ -494,26 +680,100 @@ function resultText(r) {
|
|
|
494
680
|
: `${r.score}점이에요. 다시 풀어 볼 수 있어요.`;
|
|
495
681
|
}
|
|
496
682
|
|
|
497
|
-
|
|
683
|
+
const UNCHANGED_HINT = '답을 고치면 다시 제출할 수 있어요.';
|
|
684
|
+
|
|
685
|
+
function mountSubmit(
|
|
686
|
+
app,
|
|
687
|
+
{
|
|
688
|
+
getAnswer,
|
|
689
|
+
setAnswer,
|
|
690
|
+
validate,
|
|
691
|
+
onResult,
|
|
692
|
+
resultText: customText,
|
|
693
|
+
allowUnchanged = false,
|
|
694
|
+
scrollOnResult = 'result',
|
|
695
|
+
root,
|
|
696
|
+
label = '제출',
|
|
697
|
+
}
|
|
698
|
+
) {
|
|
498
699
|
const area = appRoot(root);
|
|
499
700
|
const result = h('p', { className: 'ec-result', role: 'status', hidden: true });
|
|
500
701
|
const error = h('p', { className: 'ec-error', role: 'alert' });
|
|
702
|
+
const hint = h('p', { className: 'ec-submit-hint', hidden: true, textContent: UNCHANGED_HINT });
|
|
501
703
|
const button = h('button', { className: 'ec-primary', type: 'button', textContent: label });
|
|
502
704
|
const bar = h('div', { className: 'ec-submitbar' });
|
|
503
|
-
bar.append(error, button);
|
|
705
|
+
bar.append(error, hint, button);
|
|
504
706
|
area.after(result, bar);
|
|
505
707
|
|
|
708
|
+
const text = r => customText?.(r) ?? resultText(r);
|
|
506
709
|
const show = (r, past = false) => {
|
|
507
710
|
const ungraded = r.isCorrect === null || r.score === null || r.score === undefined;
|
|
508
711
|
result.textContent = past
|
|
509
712
|
? ungraded
|
|
510
713
|
? '이미 제출했어요.'
|
|
511
|
-
: `지난 점수: ${
|
|
512
|
-
:
|
|
714
|
+
: `지난 점수: ${text(r)}`
|
|
715
|
+
: text(r);
|
|
513
716
|
result.className = `ec-result ${r.isCorrect ? 'ok' : r.isCorrect === false ? 'no' : ''}`;
|
|
514
717
|
result.hidden = false;
|
|
515
718
|
};
|
|
516
719
|
|
|
720
|
+
// 같은 답 다시 제출 막기: 이 화면에서 제출한 답과 지금 답이 같으면 버튼을 끄고 안내, 고치면 다시 켠다 (다시 열어 복원한 답은 막지 않음).
|
|
721
|
+
// 답이 바뀌는 길(입력 · 고르기 · 끌어 놓기 · 키보드)이 화면마다 달라 문서의 이벤트 뒤에 지금 답을 다시 비교한다
|
|
722
|
+
let lastAnswer = null;
|
|
723
|
+
let busy = false;
|
|
724
|
+
const answerKey = () => {
|
|
725
|
+
try {
|
|
726
|
+
return JSON.stringify(getAnswer() ?? null);
|
|
727
|
+
} catch {
|
|
728
|
+
return null;
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
const sync = () => {
|
|
732
|
+
if (allowUnchanged || app.readOnly || busy || lastAnswer === null) return;
|
|
733
|
+
const same = answerKey() === lastAnswer;
|
|
734
|
+
button.disabled = same;
|
|
735
|
+
hint.hidden = !same;
|
|
736
|
+
};
|
|
737
|
+
if (!allowUnchanged && typeof document !== 'undefined')
|
|
738
|
+
for (const type of ['input', 'change', 'click', 'pointerup', 'keyup', 'drop'])
|
|
739
|
+
document.addEventListener(type, () => setTimeout(sync, 0), true);
|
|
740
|
+
/** 방금 나온 결과를 화면 안으로. 아래 고정 제출 바(안내 줄이 붙으면 더 높음)에 가리지 않게 그 높이만큼 띄운다. 움직임 줄이기 설정이면 바로 */
|
|
741
|
+
const reveal = () => {
|
|
742
|
+
const reduce =
|
|
743
|
+
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
744
|
+
if (bar.offsetHeight) result.style.scrollMarginBottom = `${bar.offsetHeight + 16}px`;
|
|
745
|
+
result.scrollIntoView?.({ block: 'nearest', behavior: reduce ? 'auto' : 'smooth' });
|
|
746
|
+
};
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* 화면 맨 아래로 (scrollOnResult 'bottom'). 콘텐츠는 LXP iframe 안이라 부모 페이지는 못 움직이고, 키트 학생 화면은 문서가 스크롤된다
|
|
750
|
+
* (제출 바는 sticky). 결과가 그려진 다음 프레임에 한 번, 그때 아직 안 들어온 그림(해설 그림 · 마스코트)이 있으면 다 들어오거나
|
|
751
|
+
* 3초가 지나면 한 번 더 맞춘다 (계속 따라가지 않음). 움직임 줄이기 설정이면 바로
|
|
752
|
+
*/
|
|
753
|
+
const scrollToEnd = () => {
|
|
754
|
+
if (typeof document === 'undefined') return;
|
|
755
|
+
const reduce =
|
|
756
|
+
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
757
|
+
const go = () => {
|
|
758
|
+
const page = document.scrollingElement ?? document.documentElement;
|
|
759
|
+
page.scrollTo?.({ top: page.scrollHeight, behavior: reduce ? 'auto' : 'smooth' });
|
|
760
|
+
};
|
|
761
|
+
const nextFrame = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : f => setTimeout(f, 0);
|
|
762
|
+
nextFrame(() => {
|
|
763
|
+
go();
|
|
764
|
+
const late = [...document.querySelectorAll('img')].filter(img => !img.complete);
|
|
765
|
+
if (!late.length) return;
|
|
766
|
+
const loaded = late.map(
|
|
767
|
+
img =>
|
|
768
|
+
new Promise(done => {
|
|
769
|
+
img.addEventListener('load', done, { once: true });
|
|
770
|
+
img.addEventListener('error', done, { once: true });
|
|
771
|
+
})
|
|
772
|
+
);
|
|
773
|
+
Promise.race([Promise.all(loaded), new Promise(done => setTimeout(done, 3000))]).then(go);
|
|
774
|
+
});
|
|
775
|
+
};
|
|
776
|
+
|
|
517
777
|
if (app.readOnly) {
|
|
518
778
|
area.inert = true;
|
|
519
779
|
area.setAttribute('aria-readonly', 'true');
|
|
@@ -556,18 +816,31 @@ function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, labe
|
|
|
556
816
|
}
|
|
557
817
|
error.textContent = '';
|
|
558
818
|
submitted = true;
|
|
819
|
+
busy = true;
|
|
559
820
|
button.disabled = true;
|
|
560
821
|
button.setAttribute('aria-busy', 'true');
|
|
822
|
+
let succeeded = false;
|
|
823
|
+
let answered = false;
|
|
561
824
|
try {
|
|
562
825
|
const res = await app.submit(answer);
|
|
826
|
+
lastAnswer = JSON.stringify(answer ?? null);
|
|
563
827
|
show(res);
|
|
564
828
|
onResult?.(res, { restored: false });
|
|
565
829
|
button.textContent = `다시 ${label}`;
|
|
830
|
+
succeeded = true;
|
|
831
|
+
answered = true;
|
|
566
832
|
} catch (e) {
|
|
567
833
|
error.textContent = e.message;
|
|
834
|
+
answered = true;
|
|
568
835
|
} finally {
|
|
836
|
+
busy = false;
|
|
569
837
|
button.disabled = false;
|
|
570
838
|
button.removeAttribute('aria-busy');
|
|
839
|
+
sync();
|
|
840
|
+
// 안내 줄까지 붙은 뒤의 제출 바 높이로 옮긴다. 'bottom'이면 성공 · 실패(오류 줄은 제출 바 안) 모두 맨 아래로
|
|
841
|
+
if (scrollOnResult === 'bottom') {
|
|
842
|
+
if (answered) scrollToEnd();
|
|
843
|
+
} else if (succeeded) reveal();
|
|
571
844
|
}
|
|
572
845
|
});
|
|
573
846
|
return { element: bar, result, restored };
|
|
@@ -584,88 +857,495 @@ async function hasLecturePage(app, side) {
|
|
|
584
857
|
}
|
|
585
858
|
}
|
|
586
859
|
|
|
587
|
-
|
|
860
|
+
/** 스테퍼 버튼 묶음(<ec-stepper-nav>) 안 스타일. Shadow DOM이라 작성자 CSS(button { … } · * { … })가 들어오지 않고,
|
|
861
|
+
* 색 · 간격은 상속되는 토큰(--ec-* · --eds-*)으로 받는다. :host의 !important는 바깥 CSS의 !important보다 이긴다 */
|
|
862
|
+
const STEPPER_NAV_CSS = `
|
|
863
|
+
:host {
|
|
864
|
+
display: block !important;
|
|
865
|
+
pointer-events: none !important;
|
|
866
|
+
margin: 0 !important;
|
|
867
|
+
padding: 0 !important;
|
|
868
|
+
border: 0 !important;
|
|
869
|
+
background: transparent !important;
|
|
870
|
+
overflow: visible !important;
|
|
871
|
+
opacity: 1 !important;
|
|
872
|
+
visibility: visible !important;
|
|
873
|
+
transform: none !important;
|
|
874
|
+
filter: none !important;
|
|
875
|
+
clip-path: none !important;
|
|
876
|
+
color: var(--ec-fg);
|
|
877
|
+
font-family: var(--eds-font-family);
|
|
878
|
+
}
|
|
879
|
+
/* top layer(popover): 화면 전체를 덮는 투명 막. 버튼만 누를 수 있다 */
|
|
880
|
+
:host([data-mode='top']) {
|
|
881
|
+
position: fixed !important;
|
|
882
|
+
inset: 0 !important;
|
|
883
|
+
width: auto !important;
|
|
884
|
+
height: auto !important;
|
|
885
|
+
}
|
|
886
|
+
/* popover를 못 쓰는 브라우저: 틀(.ec-stepper) 안에 겹친다 (z-index 1) */
|
|
887
|
+
:host([data-mode='inline']) {
|
|
888
|
+
position: absolute !important;
|
|
889
|
+
inset: 0 !important;
|
|
890
|
+
z-index: 1 !important;
|
|
891
|
+
}
|
|
892
|
+
[hidden] {
|
|
893
|
+
display: none !important;
|
|
894
|
+
}
|
|
895
|
+
.nav {
|
|
896
|
+
display: contents;
|
|
897
|
+
}
|
|
898
|
+
button {
|
|
899
|
+
all: unset;
|
|
900
|
+
box-sizing: border-box;
|
|
901
|
+
pointer-events: auto;
|
|
902
|
+
position: absolute;
|
|
903
|
+
top: 50%;
|
|
904
|
+
translate: 0 -50%;
|
|
905
|
+
/* 둥근 버튼: 문서 자료 학생 화면의 쪽 넘김 버튼과 같은 모양. 테두리 1px 원, 채움 · 그림자 없음(면은 바탕색),
|
|
906
|
+
꺾쇠는 16px 선 그림(svg, 글자가 아님) secondary 색 */
|
|
907
|
+
display: inline-grid;
|
|
908
|
+
place-items: center;
|
|
909
|
+
min-width: var(--ec-nav-size);
|
|
910
|
+
height: var(--ec-nav-size);
|
|
911
|
+
padding: 0;
|
|
912
|
+
border: 1px solid var(--ec-nav-border);
|
|
913
|
+
border-radius: 999px;
|
|
914
|
+
background: var(--ec-nav-bg);
|
|
915
|
+
color: var(--ec-nav-fg);
|
|
916
|
+
line-height: 1;
|
|
917
|
+
cursor: pointer;
|
|
918
|
+
}
|
|
919
|
+
svg {
|
|
920
|
+
display: block;
|
|
921
|
+
width: var(--ec-nav-icon);
|
|
922
|
+
height: var(--ec-nav-icon);
|
|
923
|
+
}
|
|
924
|
+
:host([data-mode='top']) button {
|
|
925
|
+
position: fixed;
|
|
926
|
+
}
|
|
927
|
+
@media (hover: hover) {
|
|
928
|
+
button:not([aria-disabled='true']):hover {
|
|
929
|
+
background: linear-gradient(var(--ec-nav-hover-bg), var(--ec-nav-hover-bg)), var(--ec-nav-bg);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
button:focus-visible {
|
|
933
|
+
outline: 2px solid var(--ec-accent);
|
|
934
|
+
outline-offset: 1px;
|
|
935
|
+
}
|
|
936
|
+
/* 막힌 버튼(canNext): 꺾쇠 색만 흐리게 (테두리 · 면은 그대로) */
|
|
937
|
+
button[aria-disabled='true'] {
|
|
938
|
+
color: var(--ec-nav-disabled-fg);
|
|
939
|
+
cursor: default;
|
|
940
|
+
}
|
|
941
|
+
.prev {
|
|
942
|
+
left: var(--ec-nav-inset);
|
|
943
|
+
}
|
|
944
|
+
.next {
|
|
945
|
+
right: var(--ec-nav-inset);
|
|
946
|
+
}
|
|
947
|
+
/* 끝에서 나가는 버튼: 같은 테두리 알약에 글자 (LXP 이전 · 다음 수업 자료). 강조색(보라)은 쓰지 않는다 */
|
|
948
|
+
.leave {
|
|
949
|
+
display: inline-flex;
|
|
950
|
+
align-items: center;
|
|
951
|
+
gap: 4px;
|
|
952
|
+
padding: 0 14px;
|
|
953
|
+
font-size: var(--ec-nav-count-size);
|
|
954
|
+
font-weight: var(--eds-fw-semibold);
|
|
955
|
+
white-space: nowrap;
|
|
956
|
+
}
|
|
957
|
+
.leave.prev {
|
|
958
|
+
padding-left: 10px;
|
|
959
|
+
}
|
|
960
|
+
.leave.next {
|
|
961
|
+
padding-right: 10px;
|
|
962
|
+
}
|
|
963
|
+
/* 단계 표시 "1 / 6": 테두리 알약(버튼과 같은 높이), 14px / 600 secondary. 데스크톱은 왼쪽 아래 거터
|
|
964
|
+
(오른쪽 아래 --ec-fab-safe는 비움), 모바일은 두 버튼 사이 */
|
|
965
|
+
.count {
|
|
966
|
+
pointer-events: auto;
|
|
967
|
+
position: absolute;
|
|
968
|
+
left: var(--ec-nav-inset);
|
|
969
|
+
bottom: 0;
|
|
970
|
+
box-sizing: border-box;
|
|
971
|
+
display: inline-flex;
|
|
972
|
+
align-items: center;
|
|
973
|
+
justify-content: center;
|
|
974
|
+
height: var(--ec-nav-size);
|
|
975
|
+
margin: 0;
|
|
976
|
+
padding: 0 14px;
|
|
977
|
+
border: 1px solid var(--ec-nav-border);
|
|
978
|
+
border-radius: 999px;
|
|
979
|
+
background: var(--ec-nav-bg);
|
|
980
|
+
color: var(--ec-nav-fg);
|
|
981
|
+
font-size: var(--ec-nav-count-size);
|
|
982
|
+
font-weight: var(--eds-fw-semibold);
|
|
983
|
+
line-height: 20px;
|
|
984
|
+
font-variant-numeric: tabular-nums;
|
|
985
|
+
white-space: nowrap;
|
|
986
|
+
}
|
|
987
|
+
:host([data-mode='top']) .count {
|
|
988
|
+
position: fixed;
|
|
989
|
+
bottom: 16px;
|
|
990
|
+
}
|
|
991
|
+
/* 낮은 창: LXP는 콘텐츠 iframe 높이를 (창 높이 − 112px: 위 머리 56 + 아래 막대 56)로 두되 512px 아래로는 줄이지 않는다.
|
|
992
|
+
창이 약 568px보다 낮으면 iframe(512px)이 창 밖으로 나가, 창 아래 기준인 LXP 플로팅 버튼(⊞ 위 끝 = 창 높이 − 236,
|
|
993
|
+
오른쪽 20–60px)이 세로 가운데 다음 버튼에 닿고(1440×560 실측: iframe 안 ⊞ 위 끝 약 268, 32px 버튼이면 240–272), 아래 막대가
|
|
994
|
+
iframe 아래 약 64px를 덮어 n / N이 가려진다. 그래서 iframe이 이 최소 높이일 때만 버튼을 위로 올리고(--ec-nav-short-shift,
|
|
995
|
+
512px이면 190–222), n / N은 왼쪽 버튼 바로 아래로 옮긴다 (230–262) */
|
|
996
|
+
@media (min-width: 512px) and (max-height: 520px) {
|
|
997
|
+
:host([data-mode='top']) button {
|
|
998
|
+
top: calc(50% - var(--ec-nav-short-shift, 50px));
|
|
999
|
+
}
|
|
1000
|
+
:host([data-mode='top']) .count {
|
|
1001
|
+
top: calc(50% - var(--ec-nav-short-shift, 50px) + var(--ec-nav-size) / 2 + 8px);
|
|
1002
|
+
bottom: auto;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
.sr {
|
|
1006
|
+
position: absolute;
|
|
1007
|
+
width: 1px;
|
|
1008
|
+
height: 1px;
|
|
1009
|
+
overflow: hidden;
|
|
1010
|
+
clip-path: inset(50%);
|
|
1011
|
+
white-space: nowrap;
|
|
1012
|
+
}
|
|
1013
|
+
/* 모바일: 화면 아래 가운데에 ‹ n / N › 한 줄 (문서 자료 쪽 넘김처럼 단계 표시 알약이 두 버튼 사이, 바탕 띠 없음).
|
|
1014
|
+
LXP의 화면 폭 이전 · 다음 막대와 모양이 다르다. 버튼 · 알약은 같은 테두리 모양, 크기만 --ec-nav-size-mobile(40px) */
|
|
1015
|
+
@media (max-width: 511.98px) {
|
|
1016
|
+
:host {
|
|
1017
|
+
--ec-nav-size: var(--ec-nav-size-mobile);
|
|
1018
|
+
--ec-nav-count-size: var(--eds-fs-body1);
|
|
1019
|
+
}
|
|
1020
|
+
/* 칸 셋(1fr · n / N · 1fr): 끝 단계 알약으로 버튼 폭이 바뀌어도 n / N과 반대쪽 버튼이 단계마다 움직이지 않는다 */
|
|
1021
|
+
.nav {
|
|
1022
|
+
pointer-events: none;
|
|
1023
|
+
position: absolute;
|
|
1024
|
+
left: 16px;
|
|
1025
|
+
right: 16px;
|
|
1026
|
+
bottom: 0;
|
|
1027
|
+
display: grid;
|
|
1028
|
+
grid-template-columns: 1fr auto 1fr;
|
|
1029
|
+
align-items: center;
|
|
1030
|
+
gap: 8px;
|
|
1031
|
+
}
|
|
1032
|
+
.nav .prev {
|
|
1033
|
+
justify-self: end;
|
|
1034
|
+
}
|
|
1035
|
+
.nav .next {
|
|
1036
|
+
justify-self: start;
|
|
1037
|
+
}
|
|
1038
|
+
:host([data-mode='top']) .nav {
|
|
1039
|
+
position: fixed;
|
|
1040
|
+
bottom: 12px;
|
|
1041
|
+
}
|
|
1042
|
+
.nav button,
|
|
1043
|
+
:host([data-mode='top']) .nav button,
|
|
1044
|
+
.nav .count,
|
|
1045
|
+
:host([data-mode='top']) .nav .count {
|
|
1046
|
+
position: static;
|
|
1047
|
+
translate: none;
|
|
1048
|
+
}
|
|
1049
|
+
.count {
|
|
1050
|
+
padding: 0 16px;
|
|
1051
|
+
}
|
|
1052
|
+
.leave {
|
|
1053
|
+
padding: 0 12px;
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
`;
|
|
1057
|
+
|
|
1058
|
+
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
1059
|
+
/** 꺾쇠 그림 (24 칸 선 그림). 문서 자료 학생 화면의 쪽 넘김 꺾쇠와 같은 경로 · 굵기 */
|
|
1060
|
+
const CHEVRON_PATHS = {
|
|
1061
|
+
prev: "m15 18-6-6 6-6",
|
|
1062
|
+
next: "m9 18 6-6-6-6",
|
|
1063
|
+
};
|
|
1064
|
+
function chevronIcon(side) {
|
|
1065
|
+
const svg = document.createElementNS(SVG_NS, "svg");
|
|
1066
|
+
svg.setAttribute("viewBox", "0 0 24 24");
|
|
1067
|
+
svg.setAttribute("aria-hidden", "true");
|
|
1068
|
+
svg.setAttribute("focusable", "false");
|
|
1069
|
+
const path = document.createElementNS(SVG_NS, "path");
|
|
1070
|
+
path.setAttribute("d", CHEVRON_PATHS[side]);
|
|
1071
|
+
for (const [k, v] of [
|
|
1072
|
+
["fill", "none"],
|
|
1073
|
+
["stroke", "currentColor"],
|
|
1074
|
+
["stroke-width", "2.6"],
|
|
1075
|
+
["stroke-linecap", "round"],
|
|
1076
|
+
["stroke-linejoin", "round"],
|
|
1077
|
+
])
|
|
1078
|
+
path.setAttribute(k, v);
|
|
1079
|
+
svg.append(path);
|
|
1080
|
+
return svg;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/** 스테퍼 버튼 묶음 요소. 화면 코드가 직접 만들지 않는다 (app.useStepper가 만든다) */
|
|
1084
|
+
function stepperNavElement() {
|
|
1085
|
+
if (
|
|
1086
|
+
typeof customElements !== "undefined" &&
|
|
1087
|
+
!customElements.get("ec-stepper-nav")
|
|
1088
|
+
)
|
|
1089
|
+
customElements.define("ec-stepper-nav", class extends HTMLElement {});
|
|
1090
|
+
const host = document.createElement("ec-stepper-nav");
|
|
1091
|
+
const shadow = host.attachShadow({ mode: "open" });
|
|
1092
|
+
const style = h("style", { textContent: STEPPER_NAV_CSS });
|
|
1093
|
+
const nav = h("div", { className: "nav" });
|
|
1094
|
+
nav.setAttribute("role", "group");
|
|
1095
|
+
nav.setAttribute("aria-label", "단계 이동");
|
|
1096
|
+
const prev = h("button", { type: "button", className: "ec-step-nav prev" });
|
|
1097
|
+
const next = h("button", { type: "button", className: "ec-step-nav next" });
|
|
1098
|
+
const count = h("p", { className: "ec-step-count count" });
|
|
1099
|
+
// 보이는 글은 "2 / 5", 화면 읽기 프로그램에는 "5단계 중 2단계: 제목"
|
|
1100
|
+
const shown = h("span");
|
|
1101
|
+
shown.setAttribute("aria-hidden", "true");
|
|
1102
|
+
const spoken = h("span", { className: "sr" });
|
|
1103
|
+
count.setAttribute("aria-live", "polite");
|
|
1104
|
+
count.append(shown, spoken);
|
|
1105
|
+
nav.append(prev, count, next);
|
|
1106
|
+
shadow.append(style, nav);
|
|
1107
|
+
return { host, prev, next, count, shown, spoken };
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
/** top layer(popover)에 올릴 수 있는지. 못 쓰면 틀 안에 겹쳐 둔다 */
|
|
1111
|
+
const canPopover = (el) => typeof el.showPopover === "function";
|
|
1112
|
+
|
|
1113
|
+
/** ← → 키를 무시할 곳: 글 · 숫자 · 슬라이더 · 고르기 칸, 직접 고치는 글 */
|
|
1114
|
+
function typingTarget(el) {
|
|
1115
|
+
if (!el || el.nodeType !== 1) return false;
|
|
1116
|
+
return Boolean(
|
|
1117
|
+
el.closest(
|
|
1118
|
+
'input, textarea, select, [contenteditable=""], [contenteditable="true"], [role="slider"], [role="textbox"]',
|
|
1119
|
+
),
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/** 마지막 단계 기억 (브라우저 저장소, 막히면 아무것도 안 함). 학습 기록이 아니라 이 브라우저의 편의 */
|
|
1124
|
+
function stepMemory(key) {
|
|
1125
|
+
const name = `ec-step:${key}`;
|
|
1126
|
+
let store = null;
|
|
1127
|
+
try {
|
|
1128
|
+
// ecdk-ignore-next-line api.storage (이 브라우저에만 남음. 저장소 오류는 catch: 기억하지 않음)
|
|
1129
|
+
store = globalThis.localStorage ?? null;
|
|
1130
|
+
} catch {
|
|
1131
|
+
store = null;
|
|
1132
|
+
}
|
|
1133
|
+
return {
|
|
1134
|
+
read() {
|
|
1135
|
+
try {
|
|
1136
|
+
const v = Number(store?.getItem(name));
|
|
1137
|
+
return Number.isInteger(v) ? v : null;
|
|
1138
|
+
} catch {
|
|
1139
|
+
return null;
|
|
1140
|
+
}
|
|
1141
|
+
},
|
|
1142
|
+
write(step) {
|
|
1143
|
+
try {
|
|
1144
|
+
store?.setItem(name, String(step));
|
|
1145
|
+
} catch {
|
|
1146
|
+
// 저장소가 막혔거나 가득 참: 기억하지 않는다
|
|
1147
|
+
}
|
|
1148
|
+
},
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/** 단계의 제목: data-ec-step-title · 첫 제목(h1–h3) */
|
|
1153
|
+
function stepTitleEl(scope) {
|
|
1154
|
+
return scope?.querySelector("[data-ec-step-title], h1, h2, h3") ?? null;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
function mountStepper(
|
|
1158
|
+
app,
|
|
1159
|
+
{ count, onChange, start, root, canNext, remember = false } = {},
|
|
1160
|
+
) {
|
|
588
1161
|
const area = appRoot(root);
|
|
589
|
-
|
|
590
|
-
|
|
1162
|
+
// 단계: count가 없으면 내용 영역 안 <section data-ec-step>을 차례대로. 키트가 hidden으로 하나만 보인다
|
|
1163
|
+
const sections =
|
|
1164
|
+
count === undefined ? [...area.querySelectorAll("[data-ec-step]")] : [];
|
|
1165
|
+
const total = Math.max(1, Math.floor(count ?? sections.length));
|
|
1166
|
+
const memory = remember
|
|
1167
|
+
? stepMemory(
|
|
1168
|
+
`${typeof location === "undefined" ? "" : location.pathname}#${typeof remember === "string" ? remember : area.id || "app"}`,
|
|
1169
|
+
)
|
|
1170
|
+
: null;
|
|
1171
|
+
const first = start ?? memory?.read() ?? 0;
|
|
1172
|
+
let step = Math.min(Math.max(0, Math.floor(first) || 0), total - 1);
|
|
591
1173
|
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)에만 그린다.
|
|
1174
|
+
const ui = stepperNavElement();
|
|
1175
|
+
const { prev, next } = ui;
|
|
1176
|
+
|
|
1177
|
+
// 키트 틀(.ec-stepper)이 내용 영역을 감싼다: 버튼 · n / N은 틀에, 화면 코드는 내용 영역(기본 #app)에만 그린다.
|
|
599
1178
|
// 그래서 화면 코드가 #app을 replaceChildren · innerHTML로 다시 그려도 버튼이 지워지지 않는다
|
|
600
1179
|
let frame;
|
|
601
1180
|
if (area === document.body || !area.parentNode) {
|
|
602
1181
|
// 감쌀 수 없는 영역(body)이면 그 안에 붙인다 (다시 그리면 지워짐)
|
|
603
1182
|
frame = area;
|
|
604
|
-
area.append(
|
|
1183
|
+
area.append(ui.host);
|
|
605
1184
|
} else {
|
|
606
|
-
frame = h(
|
|
1185
|
+
frame = h("div", { className: "ec-stepper-frame" });
|
|
607
1186
|
area.before(frame);
|
|
608
|
-
frame.append(
|
|
1187
|
+
frame.append(area, ui.host);
|
|
609
1188
|
}
|
|
610
|
-
frame.classList.add(
|
|
611
|
-
area.classList.add(
|
|
1189
|
+
frame.classList.add("ec-stepper");
|
|
1190
|
+
area.classList.add("ec-step-content");
|
|
1191
|
+
// top layer: 작성자 요소의 z-index · position: fixed · 조상 overflow · transform이 버튼을 덮거나 자르지 못한다.
|
|
1192
|
+
// 나중에 연 <dialog> · 전체 화면은 그 위 (의도대로). 못 쓰는 브라우저는 틀 안에 겹친다
|
|
1193
|
+
let mode = "inline";
|
|
1194
|
+
if (canPopover(ui.host)) {
|
|
1195
|
+
try {
|
|
1196
|
+
ui.host.popover = "manual";
|
|
1197
|
+
ui.host.showPopover();
|
|
1198
|
+
mode = "top";
|
|
1199
|
+
} catch {
|
|
1200
|
+
ui.host.removeAttribute("popover");
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
ui.host.dataset.mode = mode;
|
|
1204
|
+
frame.dataset.ecStepperMode = mode;
|
|
1205
|
+
|
|
1206
|
+
const current = () => sections[step] ?? area;
|
|
1207
|
+
/** 다음으로 가도 되는지: true면 통과, 문장이면 막고 그 이유를 보인다 */
|
|
1208
|
+
const gate = () => {
|
|
1209
|
+
if (!canNext) return true;
|
|
1210
|
+
try {
|
|
1211
|
+
const r = canNext(step);
|
|
1212
|
+
return r === true || r === undefined
|
|
1213
|
+
? true
|
|
1214
|
+
: typeof r === "string" && r
|
|
1215
|
+
? r
|
|
1216
|
+
: "아직 다음으로 갈 수 없습니다.";
|
|
1217
|
+
} catch {
|
|
1218
|
+
return true;
|
|
1219
|
+
}
|
|
1220
|
+
};
|
|
612
1221
|
|
|
613
1222
|
// 단계 안: 동그란 화살표만. 끝에서 나가는 버튼: 글자 있는 알약 모양(이전 자료 · 다음 자료)
|
|
614
|
-
const paint = (el, side, leaving, available) => {
|
|
615
|
-
const arrow = side
|
|
616
|
-
el.classList.toggle(
|
|
1223
|
+
const paint = (el, side, leaving, available, blocked) => {
|
|
1224
|
+
const arrow = chevronIcon(side);
|
|
1225
|
+
el.classList.toggle("leave", leaving);
|
|
617
1226
|
el.hidden = leaving && !available;
|
|
1227
|
+
let label;
|
|
618
1228
|
if (leaving) {
|
|
619
|
-
const text = side ===
|
|
620
|
-
el.
|
|
621
|
-
|
|
622
|
-
|
|
1229
|
+
const text = side === "prev" ? "이전 자료" : "다음 자료";
|
|
1230
|
+
el.replaceChildren(
|
|
1231
|
+
...(side === "prev"
|
|
1232
|
+
? [arrow, h("span", { textContent: text })]
|
|
1233
|
+
: [h("span", { textContent: text }), arrow]),
|
|
1234
|
+
);
|
|
1235
|
+
label = `${text}로 이동 (이 자료를 나갑니다)`;
|
|
1236
|
+
el.title = `LXP ${side === "prev" ? "이전" : "다음"} 수업 자료로 이동`;
|
|
623
1237
|
} else {
|
|
624
|
-
el.
|
|
625
|
-
|
|
626
|
-
el.removeAttribute(
|
|
1238
|
+
el.replaceChildren(arrow);
|
|
1239
|
+
label = side === "prev" ? "이전 단계" : "다음 단계";
|
|
1240
|
+
el.removeAttribute("title");
|
|
627
1241
|
}
|
|
1242
|
+
// 막힌 다음 버튼: 초점은 받고(이유를 읽게) 누르면 아무것도 안 함. 이유는 툴팁 · 이름에
|
|
1243
|
+
if (blocked) {
|
|
1244
|
+
el.setAttribute("aria-disabled", "true");
|
|
1245
|
+
el.title = blocked;
|
|
1246
|
+
label = `${label}: ${blocked}`;
|
|
1247
|
+
} else el.removeAttribute("aria-disabled");
|
|
1248
|
+
el.setAttribute("aria-label", label);
|
|
628
1249
|
};
|
|
629
1250
|
const render = () => {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
1251
|
+
sections.forEach((s, i) => (s.hidden = i !== step));
|
|
1252
|
+
const g = gate();
|
|
1253
|
+
paint(prev, "prev", step === 0, edge.prev, null);
|
|
1254
|
+
paint(next, "next", step === total - 1, edge.next, g === true ? null : g);
|
|
1255
|
+
const title = stepTitleEl(current())?.textContent?.trim() ?? "";
|
|
1256
|
+
ui.shown.replaceChildren(
|
|
1257
|
+
h("span", { className: "now", textContent: String(step + 1) }),
|
|
1258
|
+
` / ${total}`,
|
|
1259
|
+
);
|
|
1260
|
+
ui.spoken.textContent = `${total}단계 중 ${step + 1}단계${title ? `: ${title}` : ""}`;
|
|
1261
|
+
};
|
|
1262
|
+
/** 새 단계로: 화면 맨 위로, 초점은 단계 제목 (없으면 내용 영역) */
|
|
1263
|
+
const arrive = () => {
|
|
1264
|
+
if (typeof window !== "undefined") window.scrollTo?.({ top: 0 });
|
|
1265
|
+
const target = stepTitleEl(current()) ?? current();
|
|
1266
|
+
if (!target.hasAttribute("tabindex")) target.setAttribute("tabindex", "-1");
|
|
1267
|
+
target.focus?.({ preventScroll: true });
|
|
633
1268
|
};
|
|
1269
|
+
const changed = () =>
|
|
1270
|
+
onChange?.(step, { content: area, section: sections[step] ?? null });
|
|
634
1271
|
const go = (i) => {
|
|
635
|
-
const to = Math.min(Math.max(0, i), total - 1);
|
|
1272
|
+
const to = Math.min(Math.max(0, Math.floor(i)), total - 1);
|
|
636
1273
|
if (to === step) return;
|
|
637
1274
|
step = to;
|
|
638
1275
|
render();
|
|
639
|
-
|
|
1276
|
+
memory?.write(step);
|
|
1277
|
+
changed();
|
|
1278
|
+
// 화면 코드가 onChange에서 그린 제목에 초점
|
|
1279
|
+
arrive();
|
|
640
1280
|
};
|
|
641
1281
|
const leave = (side) => {
|
|
642
1282
|
try {
|
|
643
|
-
if (side ===
|
|
1283
|
+
if (side === "prev") app.navigation?.previous();
|
|
644
1284
|
else app.navigation?.next();
|
|
645
1285
|
} catch {
|
|
646
1286
|
// 화면이 이동을 지원하지 않으면(편집 화면 등) 아무것도 하지 않는다
|
|
647
1287
|
}
|
|
648
1288
|
};
|
|
649
|
-
|
|
650
|
-
|
|
1289
|
+
const forward = () => {
|
|
1290
|
+
if (gate() !== true) return render();
|
|
1291
|
+
if (step === total - 1) leave("next");
|
|
1292
|
+
else go(step + 1);
|
|
1293
|
+
};
|
|
1294
|
+
prev.addEventListener("click", () =>
|
|
1295
|
+
step === 0 ? leave("prev") : go(step - 1),
|
|
1296
|
+
);
|
|
1297
|
+
next.addEventListener("click", forward);
|
|
1298
|
+
// ← → 키: 자료 안 단계만 (끝에서 자료를 나가지는 않음). 입력 칸 · 슬라이더에 초점이 있으면 그 칸의 키
|
|
1299
|
+
const onKey = (e) => {
|
|
1300
|
+
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey)
|
|
1301
|
+
return;
|
|
1302
|
+
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
|
|
1303
|
+
if (
|
|
1304
|
+
typingTarget(e.composedPath?.()[0] ?? e.target) ||
|
|
1305
|
+
typingTarget(document.activeElement)
|
|
1306
|
+
)
|
|
1307
|
+
return;
|
|
1308
|
+
if (e.key === "ArrowLeft" && step > 0) go(step - 1);
|
|
1309
|
+
else if (e.key === "ArrowRight" && step < total - 1 && gate() === true)
|
|
1310
|
+
go(step + 1);
|
|
1311
|
+
else return;
|
|
1312
|
+
e.preventDefault();
|
|
1313
|
+
};
|
|
1314
|
+
document.addEventListener("keydown", onKey);
|
|
651
1315
|
|
|
652
1316
|
render();
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
1317
|
+
changed();
|
|
1318
|
+
// 화면 코드가 처음 그린 제목으로 다시 (n / N 옆 읽기 글)
|
|
1319
|
+
render();
|
|
1320
|
+
memory?.write(step);
|
|
1321
|
+
// 도구용 손잡이: ecdk dev --check --step이 단계를 바꿔 찍는다 (canNext와 상관없이 go)
|
|
1322
|
+
ui.host.ecStepper = {
|
|
1323
|
+
go,
|
|
1324
|
+
count: total,
|
|
1325
|
+
get step() {
|
|
1326
|
+
return step;
|
|
659
1327
|
},
|
|
660
|
-
|
|
1328
|
+
};
|
|
1329
|
+
const ready = Promise.all([
|
|
1330
|
+
hasLecturePage(app, "prev"),
|
|
1331
|
+
hasLecturePage(app, "next"),
|
|
1332
|
+
]).then(([p, n]) => {
|
|
1333
|
+
edge.prev = p;
|
|
1334
|
+
edge.next = n;
|
|
1335
|
+
render();
|
|
1336
|
+
});
|
|
661
1337
|
return {
|
|
662
1338
|
element: frame,
|
|
663
1339
|
content: area,
|
|
1340
|
+
nav: ui.host,
|
|
664
1341
|
ready,
|
|
665
1342
|
go,
|
|
1343
|
+
/** canNext를 다시 묻는다 (단계 안 상태가 바뀌었을 때) */
|
|
1344
|
+
refresh: render,
|
|
666
1345
|
get step() {
|
|
667
1346
|
return step;
|
|
668
1347
|
},
|
|
1348
|
+
count: total,
|
|
669
1349
|
};
|
|
670
1350
|
}
|
|
671
1351
|
|
|
@@ -682,8 +1362,13 @@ function mountSave(app, { getContent, getGrading, validate, root, label = '저
|
|
|
682
1362
|
anchor.after(bar);
|
|
683
1363
|
|
|
684
1364
|
let dirty = false;
|
|
1365
|
+
// 저장하는 동안(getContent가 파일을 올리는 중 · 서버 저장 중) 바뀐 것은 이번 저장에 들어가지 않을 수 있다:
|
|
1366
|
+
// 저장이 끝나도 "저장하지 않은 변경"으로 남긴다
|
|
1367
|
+
let saving = false;
|
|
1368
|
+
let changedWhileSaving = false;
|
|
685
1369
|
const markDirty = () => {
|
|
686
1370
|
dirty = true;
|
|
1371
|
+
if (saving) changedWhileSaving = true;
|
|
687
1372
|
// settings는 이 버튼만 저장한다 (LXP 하단 저장은 draft를 새 버전으로 낼 뿐, 화면 안 내용을 가져가지 않음).
|
|
688
1373
|
// 그래서 저장 전 상태는 이 문구가 유일한 안내
|
|
689
1374
|
status.textContent = '저장하지 않은 변경이 있어요.';
|
|
@@ -721,7 +1406,29 @@ function mountSave(app, { getContent, getGrading, validate, root, label = '저
|
|
|
721
1406
|
: "저장했어요. 학생에게는 편집 페이지 위쪽 '수업 자료에 반영'을 누르면 보입니다.";
|
|
722
1407
|
|
|
723
1408
|
button.addEventListener('click', async () => {
|
|
724
|
-
|
|
1409
|
+
saving = true;
|
|
1410
|
+
changedWhileSaving = false;
|
|
1411
|
+
try {
|
|
1412
|
+
await saveOnce();
|
|
1413
|
+
} finally {
|
|
1414
|
+
saving = false;
|
|
1415
|
+
}
|
|
1416
|
+
});
|
|
1417
|
+
async function saveOnce() {
|
|
1418
|
+
let next;
|
|
1419
|
+
try {
|
|
1420
|
+
next = getContent();
|
|
1421
|
+
// getContent가 저장 전에 파일을 올릴 수 있다 (Promise): 그동안 버튼을 막는다
|
|
1422
|
+
if (next && typeof next.then === 'function') {
|
|
1423
|
+
button.disabled = true;
|
|
1424
|
+
next = await next;
|
|
1425
|
+
}
|
|
1426
|
+
} catch (e) {
|
|
1427
|
+
status.textContent = `저장하지 못했어요: ${e?.message ?? e}`;
|
|
1428
|
+
button.disabled = false;
|
|
1429
|
+
return;
|
|
1430
|
+
}
|
|
1431
|
+
button.disabled = false;
|
|
725
1432
|
const ok = validate ? validate(next) : true;
|
|
726
1433
|
if (ok !== true) {
|
|
727
1434
|
status.textContent = typeof ok === 'string' ? ok : '내용을 확인해 주세요.';
|
|
@@ -735,8 +1442,8 @@ function mountSave(app, { getContent, getGrading, validate, root, label = '저
|
|
|
735
1442
|
button.disabled = true;
|
|
736
1443
|
try {
|
|
737
1444
|
await app.saveContent(next, gradingPart ?? undefined);
|
|
738
|
-
dirty =
|
|
739
|
-
status.textContent = savedText();
|
|
1445
|
+
dirty = changedWhileSaving;
|
|
1446
|
+
status.textContent = dirty ? '저장하지 않은 변경이 있어요.' : savedText();
|
|
740
1447
|
} catch (e) {
|
|
741
1448
|
// 로컬에서 실제 SDK로 연 draft(#edit=1)는 저장할 곳이 없다
|
|
742
1449
|
status.textContent =
|
|
@@ -746,7 +1453,7 @@ function mountSave(app, { getContent, getGrading, validate, root, label = '저
|
|
|
746
1453
|
} finally {
|
|
747
1454
|
button.disabled = false;
|
|
748
1455
|
}
|
|
749
|
-
}
|
|
1456
|
+
}
|
|
750
1457
|
return {
|
|
751
1458
|
element: bar,
|
|
752
1459
|
markDirty,
|
|
@@ -799,6 +1506,39 @@ const GRADING_TEXT = {
|
|
|
799
1506
|
|
|
800
1507
|
/** 정답 정규식 길이 상한. 서버(elice-material grading.py _REGEX_MAX_LENGTH)와 같게: 넘으면 서버가 저장을 거절한다 */
|
|
801
1508
|
export const ANSWER_KEY_MAX = 500;
|
|
1509
|
+
/** partial_pattern 문항 수 상한 (서버와 같게) */
|
|
1510
|
+
export const PARTIAL_ITEMS_MAX = 50;
|
|
1511
|
+
|
|
1512
|
+
/** 맨 앞 Python 전체 플래그 `(?i)` · `(?s)` · `(?m)` (조합 가능). JS RegExp는 이 문법을 받지 않아 플래그로 바꾼다 */
|
|
1513
|
+
const LEADING_FLAGS = /^\(\?([ims]+)\)/;
|
|
1514
|
+
|
|
1515
|
+
/**
|
|
1516
|
+
* 정답 정규식(서버는 Python re) → JS에서 같은 뜻으로 쓸 { source, flags }.
|
|
1517
|
+
* 맨 앞 `(?i)`(대소문자 무시) · `(?s)` · `(?m)`은 떼고 JS 플래그로 (Python에서도 맨 앞에서만 전체에 걸림)
|
|
1518
|
+
* @param {string} regex
|
|
1519
|
+
* @returns {{ source: string, flags: string }}
|
|
1520
|
+
*/
|
|
1521
|
+
export function toJsRegex(regex) {
|
|
1522
|
+
const m = LEADING_FLAGS.exec(regex);
|
|
1523
|
+
if (!m) return { source: regex, flags: '' };
|
|
1524
|
+
return { source: regex.slice(m[0].length), flags: [...new Set(m[1])].join('') };
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/**
|
|
1528
|
+
* 정답 정규식이 답 문자열(앞뒤 공백을 자름) 전체와 맞는지. 서버 채점(Python re.fullmatch)과 같은 판정.
|
|
1529
|
+
* 정규식이 틀리면 false
|
|
1530
|
+
* @param {string} regex
|
|
1531
|
+
* @param {string} answer
|
|
1532
|
+
*/
|
|
1533
|
+
export function matchesAnswer(regex, answer) {
|
|
1534
|
+
if (typeof regex !== 'string' || typeof answer !== 'string') return false;
|
|
1535
|
+
try {
|
|
1536
|
+
const { source, flags } = toJsRegex(regex);
|
|
1537
|
+
return new RegExp(`^(?:${source})$`, flags).test(answer.trim());
|
|
1538
|
+
} catch {
|
|
1539
|
+
return false;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
802
1542
|
/** 정답 정규식 한 번 맞춰 보는 시간 상한(ms). 넘으면 ReDoS 위험으로 막는다 */
|
|
803
1543
|
const REGEX_TIME_LIMIT_MS = 50;
|
|
804
1544
|
|
|
@@ -814,13 +1554,15 @@ export function validateAnswerRegex(regex, samples = []) {
|
|
|
814
1554
|
if (!key) return '기준 답안(정규표현식)을 입력해 주세요.';
|
|
815
1555
|
if (key.length > ANSWER_KEY_MAX)
|
|
816
1556
|
return `기준 답안이 너무 깁니다 (${key.length}자, 최대 ${ANSWER_KEY_MAX}자).`;
|
|
1557
|
+
// 맨 앞 (?i) 같은 Python 플래그는 JS 플래그로 바꿔 검사한다 (서버는 Python re)
|
|
1558
|
+
const { source, flags } = toJsRegex(key);
|
|
817
1559
|
let re;
|
|
818
1560
|
try {
|
|
819
|
-
re = new RegExp(
|
|
1561
|
+
re = new RegExp(source, flags);
|
|
820
1562
|
} catch (e) {
|
|
821
1563
|
return `기준 답안이 올바른 정규표현식이 아닙니다: ${e.message}`;
|
|
822
1564
|
}
|
|
823
|
-
if (!
|
|
1565
|
+
if (!source.startsWith('^') || !source.endsWith('$') || /(^|[^\\])(\\\\)*\\\$$/.test(source))
|
|
824
1566
|
return '기준 답안은 ^로 시작해 $로 끝나야 합니다 (답 전체와 맞춰야 부분만 맞아도 정답이 되지 않음).';
|
|
825
1567
|
const now = () => (typeof performance === 'undefined' ? Date.now() : performance.now());
|
|
826
1568
|
const slow = text => {
|
|
@@ -833,12 +1575,51 @@ export function validateAnswerRegex(regex, samples = []) {
|
|
|
833
1575
|
if (samples.some(slow)) return tooSlow;
|
|
834
1576
|
// 겹친 반복(예: (a+)+)은 길이가 늘수록 시간이 두 배씩 는다: 짧은 길이부터 늘려 가며 재고, 느려지면 바로 멈춘다
|
|
835
1577
|
// (긴 문자열을 한 번에 넣으면 멈추지 않을 수 있다)
|
|
836
|
-
const chars = [...new Set(
|
|
1578
|
+
const chars = [...new Set(source.replace(/\\./g, '').match(/[A-Za-z0-9가-힣%=;,]/g) ?? ['a'])].slice(0, 4);
|
|
837
1579
|
for (const c of chars)
|
|
838
1580
|
for (let n = 8; n <= 28; n += 2) if (slow(`${c.repeat(n)}\u0000`)) return tooSlow;
|
|
839
1581
|
return null;
|
|
840
1582
|
}
|
|
841
1583
|
|
|
1584
|
+
/**
|
|
1585
|
+
* partial_pattern 채점 설정 검사 (서버 저장 규칙과 같게): 문항 수 1~50 · 정답과 점수 개수가 같음 ·
|
|
1586
|
+
* 점수는 0~100 정수 · 합계 100 이상(작으면 다 맞혀도 완료되지 않음) · 문항마다 validateAnswerRegex.
|
|
1587
|
+
* 문제가 없으면 null, 있으면 보여 줄 문장
|
|
1588
|
+
* @param {{ answer_key: string[], scores: number[] }} grading
|
|
1589
|
+
* @returns {string | null}
|
|
1590
|
+
*/
|
|
1591
|
+
export function validatePartialGrading({ answer_key: answerKey, scores } = {}) {
|
|
1592
|
+
if (!Array.isArray(answerKey) || !Array.isArray(scores))
|
|
1593
|
+
return '문항별 기준 답안과 점수를 입력해 주세요.';
|
|
1594
|
+
if (answerKey.length < 1 || answerKey.length > PARTIAL_ITEMS_MAX)
|
|
1595
|
+
return `문항은 1개부터 ${PARTIAL_ITEMS_MAX}개까지 채점할 수 있습니다 (지금 ${answerKey.length}개).`;
|
|
1596
|
+
if (scores.length !== answerKey.length)
|
|
1597
|
+
return `기준 답안(${answerKey.length}개)과 점수(${scores.length}개)의 개수가 같아야 합니다.`;
|
|
1598
|
+
const badScore = scores.findIndex(n => !Number.isInteger(n) || n < 0 || n > 100);
|
|
1599
|
+
if (badScore >= 0) return `${badScore + 1}번 문항 점수는 0부터 100 사이의 정수로 입력해 주세요.`;
|
|
1600
|
+
const total = scores.reduce((sum, n) => sum + n, 0);
|
|
1601
|
+
if (total < 100)
|
|
1602
|
+
return `점수 합계가 100점 이상이어야 합니다 (지금 ${total}점). 100점보다 작으면 다 맞혀도 완료되지 않습니다.`;
|
|
1603
|
+
for (const [i, regex] of answerKey.entries()) {
|
|
1604
|
+
const problem = validateAnswerRegex(regex);
|
|
1605
|
+
if (problem) return `${i + 1}번 문항: ${problem}`;
|
|
1606
|
+
}
|
|
1607
|
+
return null;
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
/**
|
|
1611
|
+
* 문항 n개에 100점을 정수로 똑같이 나눈다. 합은 꼭 100, 나머지는 뒤 문항에 1점씩 (3 → [33, 33, 34])
|
|
1612
|
+
* @param {number} n 문항 수 (1 이상)
|
|
1613
|
+
* @returns {number[]}
|
|
1614
|
+
*/
|
|
1615
|
+
export function splitScores(n) {
|
|
1616
|
+
const count = Math.floor(n);
|
|
1617
|
+
if (!(count >= 1)) return [];
|
|
1618
|
+
const base = Math.floor(100 / count);
|
|
1619
|
+
const rest = 100 - base * count;
|
|
1620
|
+
return Array.from({ length: count }, (_, i) => base + (i >= count - rest ? 1 : 0));
|
|
1621
|
+
}
|
|
1622
|
+
|
|
842
1623
|
/** 라디오 카드 하나 (LXP 설정 모양) */
|
|
843
1624
|
function radioCard(name, value, info, checked) {
|
|
844
1625
|
const card = h('label', { className: 'ec-grading-type' });
|
|
@@ -881,7 +1662,7 @@ function mountGradingBlock(app, { graders = ['pattern', 'rubric'], examples = GR
|
|
|
881
1662
|
spellcheck: false,
|
|
882
1663
|
});
|
|
883
1664
|
keyInput.className = 'ec-grading-key';
|
|
884
|
-
keyInput.value = saved?.answer_key
|
|
1665
|
+
keyInput.value = typeof saved?.answer_key === 'string' ? saved.answer_key : '';
|
|
885
1666
|
const toggle = h('button', { type: 'button', className: 'ec-text-button', textContent: t.examples });
|
|
886
1667
|
const exampleList = h('dl', { className: 'ec-grading-examples', hidden: true });
|
|
887
1668
|
for (const [regex, meaning] of examples)
|
|
@@ -952,3 +1733,310 @@ function showBanner(error) {
|
|
|
952
1733
|
}
|
|
953
1734
|
el.textContent = error.message;
|
|
954
1735
|
}
|
|
1736
|
+
|
|
1737
|
+
/**
|
|
1738
|
+
* 빈 안내 (app.emptyState): 그림(lib/icons/empty-content.js) + 제목 + 설명, 가운데 · role=status.
|
|
1739
|
+
* 색은 lib/elice-content.css .ec-empty: 밝은 테마 = EDS 토큰, 어두운 테마(data-eds-theme="dark") · theme: 'dark' = 어두운 그림
|
|
1740
|
+
*/
|
|
1741
|
+
function emptyState({
|
|
1742
|
+
title = MESSAGES.content_empty,
|
|
1743
|
+
description = MESSAGES.content_empty_description,
|
|
1744
|
+
theme,
|
|
1745
|
+
} = {}) {
|
|
1746
|
+
const box = h('div', { className: 'ec-empty', role: 'status' });
|
|
1747
|
+
if (theme === 'dark') box.dataset.theme = 'dark';
|
|
1748
|
+
box.append(emptyContentArt(), h('p', { className: 'ec-empty-title', textContent: title }));
|
|
1749
|
+
if (description) box.append(h('p', { className: 'ec-empty-desc', textContent: description }));
|
|
1750
|
+
return box;
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
/**
|
|
1754
|
+
* 불러오는 동안 보일 자리 (회색 면 + 빛, "불러오는 중…"은 화면 읽기 프로그램에만). start()를 기다리기 전에
|
|
1755
|
+
* #app에 넣는다: `root.replaceChildren(skeleton('edit'))`. 자료마다 다른 모양은 parts로 고른다.
|
|
1756
|
+
* layout 'learn': 화면을 채우는 면 하나 (parts 무시). 'edit': parts를 위에서부터 쌓는다
|
|
1757
|
+
* parts: 'bar'(파일 줄 48px) · 'media'(16:9 미리보기) — 기본은 파일 줄 + 미리보기 (동영상 · PDF/PPT)
|
|
1758
|
+
* @param {'learn' | 'edit'} [layout]
|
|
1759
|
+
* @param {{ label?: string, parts?: Array<'bar' | 'media'> }} [opts]
|
|
1760
|
+
* @returns {HTMLElement} `.ec-sk` (role="status")
|
|
1761
|
+
*/
|
|
1762
|
+
export function skeleton(layout = 'learn', { label = '불러오는 중…', parts = ['bar', 'media'] } = {}) {
|
|
1763
|
+
const learn = layout === 'learn';
|
|
1764
|
+
const el = h('div', { className: learn ? 'ec-sk ec-sk-learn ec-sk-shimmer' : 'ec-sk ec-sk-edit' });
|
|
1765
|
+
el.setAttribute('role', 'status');
|
|
1766
|
+
el.append(h('span', { className: 'ec-visually-hidden', textContent: label }));
|
|
1767
|
+
if (!learn) for (const part of parts) el.append(h('div', { className: `ec-sk-${part} ec-sk-shimmer` }));
|
|
1768
|
+
return el;
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
/**
|
|
1772
|
+
* canvas 그림 버퍼를 화면에 보이는 크기 × devicePixelRatio로 맞춘다 (흐리거나 넘치지 않게). 크기가 바뀔 때마다 다시 맞추고
|
|
1773
|
+
* onResize({ ctx, width, height, dpr })를 부른다: 그 안에서 받은 ctx로 다시 그린다 (처음 한 번은 fitCanvas 안에서 바로 부르므로
|
|
1774
|
+
* 돌려받은 값이 아니라 인자의 ctx를 쓴다). ctx는 dpr만큼 늘려 두어 CSS px 단위로 그리면 된다.
|
|
1775
|
+
* stage 칸 바로 아래 canvas는 키트 CSS가 칸 크기에 맞춘다 (elice-content.css "레이아웃")
|
|
1776
|
+
* @param {HTMLCanvasElement} canvas
|
|
1777
|
+
* @param {(size: { ctx: CanvasRenderingContext2D | null, width: number, height: number, dpr: number }) => void} [onResize]
|
|
1778
|
+
* @returns {{ ctx: CanvasRenderingContext2D | null, size: { width: number, height: number, dpr: number }, stop: () => void }}
|
|
1779
|
+
*/
|
|
1780
|
+
export function fitCanvas(canvas, onResize) {
|
|
1781
|
+
const ctx = canvas.getContext("2d");
|
|
1782
|
+
const size = { width: 0, height: 0, dpr: 1 };
|
|
1783
|
+
const apply = () => {
|
|
1784
|
+
const box = canvas.getBoundingClientRect();
|
|
1785
|
+
const dpr = Math.min(globalThis.devicePixelRatio || 1, 3);
|
|
1786
|
+
const w = Math.max(1, Math.round(box.width * dpr));
|
|
1787
|
+
const hgt = Math.max(1, Math.round(box.height * dpr));
|
|
1788
|
+
if (canvas.width !== w) canvas.width = w;
|
|
1789
|
+
if (canvas.height !== hgt) canvas.height = hgt;
|
|
1790
|
+
ctx?.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
1791
|
+
Object.assign(size, { width: box.width, height: box.height, dpr });
|
|
1792
|
+
onResize?.({ ctx, ...size });
|
|
1793
|
+
};
|
|
1794
|
+
const observer = typeof ResizeObserver === "function" ? new ResizeObserver(apply) : null;
|
|
1795
|
+
observer?.observe(canvas);
|
|
1796
|
+
apply();
|
|
1797
|
+
return { ctx, size, stop: () => observer?.disconnect() };
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
// ---------- 편집 화면 도우미 (모양은 elice-content.css의 편집 화면 절) ----------
|
|
1801
|
+
|
|
1802
|
+
/** 스낵바가 떠 있는 시간 (되돌리기를 누를 수 있는 시간) */
|
|
1803
|
+
export const SNACKBAR_MS = 6000;
|
|
1804
|
+
let snackbar = null;
|
|
1805
|
+
|
|
1806
|
+
/**
|
|
1807
|
+
* 스낵바 (EDS Snackbar · info): 지우기 · 바꾸기처럼 되돌릴 수 있는 변경 뒤에 화면 아래 가운데에 잠깐 띄운다.
|
|
1808
|
+
* 한 번에 하나만(새 것이 앞의 것을 대신), body에 붙여 화면 영역을 다시 그려도 남고 저장 전 표시(useSave)를 켜지 않는다.
|
|
1809
|
+
* 초점은 옮기지 않는다 (focus: true면 되돌리기 버튼으로: 키보드로 지웠을 때 초점이 갈 곳).
|
|
1810
|
+
* onClose(까닭)는 한 번만: 'action'(눌렀음) · 'timeout'(시간이 지남) · 'replaced'(새 스낵바) · 'close'(close())
|
|
1811
|
+
* @param {{ text: string, action?: string, onAction?: () => void, onClose?: (reason: string) => void,
|
|
1812
|
+
* ms?: number, focus?: boolean }} opts
|
|
1813
|
+
* @returns {{ element: HTMLElement, close: () => void }}
|
|
1814
|
+
*/
|
|
1815
|
+
export function showSnackbar({
|
|
1816
|
+
text,
|
|
1817
|
+
action = '되돌리기',
|
|
1818
|
+
onAction,
|
|
1819
|
+
onClose,
|
|
1820
|
+
ms = SNACKBAR_MS,
|
|
1821
|
+
focus = false,
|
|
1822
|
+
}) {
|
|
1823
|
+
snackbar?.close('replaced');
|
|
1824
|
+
const element = h('div', { className: 'ec-snackbar' });
|
|
1825
|
+
element.setAttribute('role', 'status');
|
|
1826
|
+
element.dataset.ecQuiet = '';
|
|
1827
|
+
const icon = h('span', { className: 'ec-snackbar-icon' });
|
|
1828
|
+
icon.innerHTML =
|
|
1829
|
+
'<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>';
|
|
1830
|
+
element.append(icon, h('span', { className: 'ec-snackbar-text', textContent: text }));
|
|
1831
|
+
let timer;
|
|
1832
|
+
let open = true;
|
|
1833
|
+
const close = (reason = 'close') => {
|
|
1834
|
+
if (!open) return;
|
|
1835
|
+
open = false;
|
|
1836
|
+
clearTimeout(timer);
|
|
1837
|
+
// 초점이 스낵바에 있었는지는 onClose가 볼 수 있게 지우기 전에 알린다
|
|
1838
|
+
onClose?.(reason);
|
|
1839
|
+
element.remove();
|
|
1840
|
+
if (snackbar?.element === element) snackbar = null;
|
|
1841
|
+
};
|
|
1842
|
+
if (onAction) {
|
|
1843
|
+
const button = h('button', { type: 'button', className: 'ec-snackbar-action', textContent: action });
|
|
1844
|
+
button.addEventListener('click', () => {
|
|
1845
|
+
close('action');
|
|
1846
|
+
onAction();
|
|
1847
|
+
});
|
|
1848
|
+
element.append(button);
|
|
1849
|
+
}
|
|
1850
|
+
document.body.append(element);
|
|
1851
|
+
timer = setTimeout(() => close('timeout'), ms);
|
|
1852
|
+
snackbar = { element, close };
|
|
1853
|
+
if (focus) element.querySelector('button')?.focus();
|
|
1854
|
+
return snackbar;
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
/**
|
|
1858
|
+
* 이미지 올리기 규칙 (서버 한도와 같게): PNG · JPEG · WebP · GIF, 10MB까지, SVG는 받지 않는다.
|
|
1859
|
+
* 긴 변 2048px까지 줄이고 WebP(품질 0.85)로, 못 만들면 JPEG(투명한 그림은 PNG)로 다시 저장한다
|
|
1860
|
+
*/
|
|
1861
|
+
export const IMAGE_RULES = Object.freeze({
|
|
1862
|
+
maxBytes: 10 * 1024 * 1024,
|
|
1863
|
+
maxSide: 2048,
|
|
1864
|
+
quality: 0.85,
|
|
1865
|
+
types: Object.freeze(['image/png', 'image/jpeg', 'image/webp', 'image/gif']),
|
|
1866
|
+
});
|
|
1867
|
+
const IMAGE_TYPE_BY_EXT = Object.freeze({
|
|
1868
|
+
png: 'image/png',
|
|
1869
|
+
jpg: 'image/jpeg',
|
|
1870
|
+
jpeg: 'image/jpeg',
|
|
1871
|
+
webp: 'image/webp',
|
|
1872
|
+
gif: 'image/gif',
|
|
1873
|
+
});
|
|
1874
|
+
const IMAGE_EXT_BY_TYPE = Object.freeze({
|
|
1875
|
+
'image/png': 'png',
|
|
1876
|
+
'image/jpeg': 'jpg',
|
|
1877
|
+
'image/webp': 'webp',
|
|
1878
|
+
'image/gif': 'gif',
|
|
1879
|
+
});
|
|
1880
|
+
/** 파일 형식(MIME), 없으면 확장자로 이미지 종류. 받지 않는 종류(SVG 등)면 null */
|
|
1881
|
+
function imageTypeOf(file) {
|
|
1882
|
+
if (IMAGE_RULES.types.includes(file?.type)) return file.type;
|
|
1883
|
+
if (file?.type) return null;
|
|
1884
|
+
const ext = String(file?.name ?? '').split('.').pop()?.toLowerCase() ?? '';
|
|
1885
|
+
return IMAGE_TYPE_BY_EXT[ext] ?? null;
|
|
1886
|
+
}
|
|
1887
|
+
/** 파일 앞부분에 EXIF · XMP(촬영 위치 · 기기 정보)가 있는지 (JPEG APP1, PNG eXIf, WebP EXIF · XMP 덩어리) */
|
|
1888
|
+
async function hasImageMetadata(file) {
|
|
1889
|
+
try {
|
|
1890
|
+
const head = new Uint8Array(await file.slice(0, 256 * 1024).arrayBuffer());
|
|
1891
|
+
let text = '';
|
|
1892
|
+
for (let i = 0; i < head.length; i += 8192)
|
|
1893
|
+
text += String.fromCharCode(...head.subarray(i, i + 8192));
|
|
1894
|
+
return /Exif\0\0|eXIf|EXIF|XMP |http:\/\/ns\.adobe\.com\/xap/.test(text);
|
|
1895
|
+
} catch {
|
|
1896
|
+
return true;
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
const canvasBlob = (canvas, type, quality) =>
|
|
1900
|
+
new Promise((resolve) => {
|
|
1901
|
+
try {
|
|
1902
|
+
canvas.toBlob((blob) => resolve(blob), type, quality);
|
|
1903
|
+
} catch {
|
|
1904
|
+
resolve(null);
|
|
1905
|
+
}
|
|
1906
|
+
});
|
|
1907
|
+
const renamed = (name, type) =>
|
|
1908
|
+
`${String(name || 'image').replace(/\.[^./]*$/, '') || 'image'}.${IMAGE_EXT_BY_TYPE[type]}`;
|
|
1909
|
+
|
|
1910
|
+
/**
|
|
1911
|
+
* 올리기 전에 이미지를 줄인다 (app.assets.uploadImage가 부름, 브라우저에서 한 번).
|
|
1912
|
+
* - PNG · JPEG · WebP: 사진 방향(EXIF)대로 바로 세워 긴 변 2048px까지 줄이고 WebP 품질 0.85로 다시 저장
|
|
1913
|
+
* (WebP를 못 만드는 브라우저는 JPEG, 투명할 수 있는 PNG · WebP는 PNG). 다시 저장하면 EXIF · GPS가 빠진다
|
|
1914
|
+
* - 다시 저장한 쪽이 더 크면 원본을 쓴다. 단 줄여야 하거나 원본에 EXIF · XMP가 있으면 다시 저장한 쪽
|
|
1915
|
+
* - GIF: 움직임이 있을 수 있어 그대로 (크기만 확인)
|
|
1916
|
+
* 오류: upload_bad_type(받지 않는 종류) · upload_bad_file(비었거나 결과가 10MB 초과) · image_unreadable
|
|
1917
|
+
* @param {File} file
|
|
1918
|
+
* @returns {Promise<{ file: File, width: number | null, height: number | null, optimized: boolean }>}
|
|
1919
|
+
*/
|
|
1920
|
+
export async function optimizeImage(file, { maxSide = IMAGE_RULES.maxSide, quality = IMAGE_RULES.quality } = {}) {
|
|
1921
|
+
const type = imageTypeOf(file);
|
|
1922
|
+
if (!type) throw new ContentError('upload_bad_type', MESSAGES.image_bad_type);
|
|
1923
|
+
if (!(file.size >= 1)) throw new ContentError('upload_bad_file', MESSAGES.image_bad_file);
|
|
1924
|
+
const checked = (result) => {
|
|
1925
|
+
if (result.file.size > IMAGE_RULES.maxBytes)
|
|
1926
|
+
throw new ContentError('upload_bad_file', MESSAGES.image_bad_file);
|
|
1927
|
+
return result;
|
|
1928
|
+
};
|
|
1929
|
+
if (type === 'image/gif') return checked({ file, width: null, height: null, optimized: false });
|
|
1930
|
+
|
|
1931
|
+
let bitmap;
|
|
1932
|
+
try {
|
|
1933
|
+
bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
|
1934
|
+
} catch (err) {
|
|
1935
|
+
throw new ContentError('image_unreadable', MESSAGES.image_unreadable, err);
|
|
1936
|
+
}
|
|
1937
|
+
const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height));
|
|
1938
|
+
const width = Math.max(1, Math.round(bitmap.width * scale));
|
|
1939
|
+
const height = Math.max(1, Math.round(bitmap.height * scale));
|
|
1940
|
+
const canvas = document.createElement('canvas');
|
|
1941
|
+
canvas.width = width;
|
|
1942
|
+
canvas.height = height;
|
|
1943
|
+
const ctx = canvas.getContext('2d');
|
|
1944
|
+
const mayBeTransparent = type !== 'image/jpeg';
|
|
1945
|
+
const draw = (background) => {
|
|
1946
|
+
ctx.clearRect(0, 0, width, height);
|
|
1947
|
+
if (background) {
|
|
1948
|
+
ctx.fillStyle = background;
|
|
1949
|
+
ctx.fillRect(0, 0, width, height);
|
|
1950
|
+
}
|
|
1951
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
1952
|
+
};
|
|
1953
|
+
draw();
|
|
1954
|
+
let blob = await canvasBlob(canvas, 'image/webp', quality);
|
|
1955
|
+
if (blob?.type !== 'image/webp') {
|
|
1956
|
+
if (mayBeTransparent) blob = await canvasBlob(canvas, 'image/png');
|
|
1957
|
+
else {
|
|
1958
|
+
// JPEG는 투명한 곳이 검게 되지 않게 흰 바탕
|
|
1959
|
+
draw('#fff');
|
|
1960
|
+
blob = await canvasBlob(canvas, 'image/jpeg', quality);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
bitmap.close?.();
|
|
1964
|
+
if (!blob) throw new ContentError('image_unreadable', MESSAGES.image_unreadable);
|
|
1965
|
+
|
|
1966
|
+
const keepOriginal =
|
|
1967
|
+
scale === 1 && blob.size >= file.size && type === file.type && !(await hasImageMetadata(file));
|
|
1968
|
+
if (keepOriginal) return checked({ file, width, height, optimized: false });
|
|
1969
|
+
const out = new File([blob], renamed(file.name, blob.type), { type: blob.type });
|
|
1970
|
+
return checked({ file: out, width, height, optimized: true });
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
/** 파일 크기 · 길이 · 쪽 수를 "1.4MB, 8쪽" · "120MB, 08:30"처럼 (모르는 값은 뺀다) */
|
|
1974
|
+
export function formatFileMeta({ size, duration, pages } = {}) {
|
|
1975
|
+
const parts = [];
|
|
1976
|
+
if (typeof size === 'number' && size >= 0) {
|
|
1977
|
+
const units = ['B', 'KB', 'MB', 'GB'];
|
|
1978
|
+
let value = size;
|
|
1979
|
+
let unit = 0;
|
|
1980
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
1981
|
+
value /= 1024;
|
|
1982
|
+
unit += 1;
|
|
1983
|
+
}
|
|
1984
|
+
parts.push(`${unit > 0 && value < 10 ? value.toFixed(1) : Math.round(value)}${units[unit]}`);
|
|
1985
|
+
}
|
|
1986
|
+
if (typeof duration === 'number' && duration > 0) {
|
|
1987
|
+
const total = Math.round(duration);
|
|
1988
|
+
const hours = Math.floor(total / 3600);
|
|
1989
|
+
const mm = String(Math.floor((total % 3600) / 60)).padStart(2, '0');
|
|
1990
|
+
const ss = String(total % 60).padStart(2, '0');
|
|
1991
|
+
parts.push(hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`);
|
|
1992
|
+
}
|
|
1993
|
+
if (typeof pages === 'number' && pages > 0) parts.push(`${pages}쪽`);
|
|
1994
|
+
return parts.join(', ');
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
/**
|
|
1998
|
+
* 올린 파일 한 줄 (V3 시안: 동영상 · PDF/PPT 공통). 흰 줄에 파일 아이콘 · 이름(굵게) · 크기 등 · 오른쪽 "다른 파일로 변경".
|
|
1999
|
+
* 무엇을 고르고 올릴지는 템플릿이 정한다 (onChange에서 동영상은 부모 창 업로드, 문서는 파일 고르기).
|
|
2000
|
+
* icon: lib/icons/의 아이콘 — 동영상 fileVideoIcon()(icons/file-video.js) · 그 밖 fileIcon()(icons/file.js).
|
|
2001
|
+
* 쓰는 아이콘만 import하므로 zip에는 그 그림과 Font Awesome 출처 주석만 들어간다
|
|
2002
|
+
* @param {{ icon?: Element, name: string, meta?: string, changeLabel?: string, onChange?: () => void,
|
|
2003
|
+
* disabled?: boolean }} opts
|
|
2004
|
+
* @returns {HTMLElement} `.ec-file-bar` (버튼은 data-role="change")
|
|
2005
|
+
*/
|
|
2006
|
+
export function fileBar({ icon, name, meta = '', changeLabel = '다른 파일로 변경', onChange, disabled = false }) {
|
|
2007
|
+
const bar = h('div', { className: 'ec-file-bar' });
|
|
2008
|
+
if (icon) {
|
|
2009
|
+
const box = h('span', { className: 'ec-file-icon' });
|
|
2010
|
+
box.append(icon);
|
|
2011
|
+
bar.append(box);
|
|
2012
|
+
}
|
|
2013
|
+
bar.append(
|
|
2014
|
+
h('span', { className: 'ec-file-name', textContent: name, title: name }),
|
|
2015
|
+
h('span', { className: 'ec-file-meta', textContent: meta })
|
|
2016
|
+
);
|
|
2017
|
+
if (onChange) {
|
|
2018
|
+
const button = h('button', {
|
|
2019
|
+
type: 'button',
|
|
2020
|
+
className: 'ec-button-small',
|
|
2021
|
+
textContent: changeLabel,
|
|
2022
|
+
disabled,
|
|
2023
|
+
});
|
|
2024
|
+
button.dataset.role = 'change';
|
|
2025
|
+
button.addEventListener('click', () => onChange());
|
|
2026
|
+
bar.append(button);
|
|
2027
|
+
}
|
|
2028
|
+
return bar;
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
/** ⓘ 안내 목록 (지원 형식 · 최대 크기처럼 칸 아래 조건들). 한 줄이면 `.ec-info-line`처럼 쓴다 */
|
|
2032
|
+
export function infoList(lines) {
|
|
2033
|
+
const list = h('ul', { className: 'ec-info-list' });
|
|
2034
|
+
for (const line of lines) {
|
|
2035
|
+
const item = h('li');
|
|
2036
|
+
item.innerHTML =
|
|
2037
|
+
'<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>';
|
|
2038
|
+
item.append(document.createTextNode(line));
|
|
2039
|
+
list.append(item);
|
|
2040
|
+
}
|
|
2041
|
+
return list;
|
|
2042
|
+
}
|