@eliceio/cdk-cli 1.3.0-contenttypes.0 → 1.3.0-contenttypes.2
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 +24 -23
- package/es/cli.js +1 -1
- package/es/commands/create/index.js +1 -0
- package/es/commands/create/scaffold.d.ts +1 -1
- package/es/commands/create/scaffold.js +1 -1
- package/es/commands/doctor/index.js +6 -2
- package/es/core/config.d.ts +22 -0
- package/es/core/config.js +165 -1
- package/es/dev/assets.d.ts +80 -0
- package/es/dev/assets.js +240 -0
- package/es/dev/grading.d.ts +42 -26
- package/es/dev/grading.js +88 -39
- package/es/dev/host-page.js +26 -2
- package/es/dev/inject.d.ts +2 -1
- package/es/dev/inject.js +10 -2
- package/es/dev/mock-api.d.ts +23 -2
- package/es/dev/mock-api.js +210 -40
- package/es/dev/server.d.ts +12 -1
- package/es/dev/server.js +115 -9
- package/es/rules.json.js +1 -1
- package/package.json +2 -2
- package/rules.json +3 -3
- package/skills/_shared/references/02-design-the-material.md +1 -1
- package/skills/_shared/references/03-create-the-project.md +9 -8
- package/skills/_shared/references/04-rules.md +1 -1
- package/skills/_shared/references/05-screen-code.md +22 -20
- package/skills/_shared/references/06-using-the-quiz-template.md +6 -4
- package/skills/_shared/references/08-fix-check-errors.md +1 -1
- package/skills/_shared/references/09-check.md +1 -0
- package/skills/_shared/references/12-upload-with-the-material-mcp.md +1 -1
- package/skills/elice-content-publish/SKILL.md +1 -1
- package/templates/_shared/lib/cdk-mock.d.ts +17 -0
- package/templates/_shared/lib/cdk-mock.js +212 -7
- package/templates/_shared/lib/elice-content.d.ts +61 -1
- package/templates/_shared/lib/elice-content.js +317 -10
- package/templates/blank/README.md +1 -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 +13 -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 +16 -12
- package/templates/quiz/core/behaviors.d.ts +4 -0
- package/templates/quiz/core/behaviors.js +4 -2
- package/templates/quiz/core/editor.d.ts +17 -2
- package/templates/quiz/core/editor.js +85 -10
- package/templates/quiz/core/markdown.d.ts +15 -0
- package/templates/quiz/core/markdown.js +164 -4
- package/templates/quiz/core/model.d.ts +53 -9
- package/templates/quiz/core/model.js +384 -41
- package/templates/quiz/core/rich-text.d.ts +1 -2
- package/templates/quiz/core/rich-text.js +7 -59
- package/templates/quiz/public/img/mascot-half.webp +0 -0
- package/templates/quiz/screens/edit.js +403 -126
- package/templates/quiz/screens/learn.js +106 -40
- package/templates/quiz/styles.css +584 -4
- package/templates/quiz/template.json +1 -1
- package/templates/quiz/ui/templates/edit.d.ts +3 -0
- package/templates/quiz/ui/templates/edit.js +113 -11
- package/templates/quiz/ui/templates/page.js +14 -0
- package/templates/quiz/ui/templates/question.js +5 -3
- package/templates/quiz/ui/texts.js +89 -26
|
@@ -5,8 +5,11 @@
|
|
|
5
5
|
// shuffle?, placeholder?, explanation: { enabled, text } }] }
|
|
6
6
|
// 퀴즈 제목 · 안내(title · description)는 지금 화면이 쓰지 않는다. 예전에 저장한 값은 지우지 않고 그대로 둔다
|
|
7
7
|
// 문항 description은 편집 화면에서 적을 때만 생긴다 (새 문항에는 키가 없음)
|
|
8
|
-
// 제출하는 답: 문자열 하나 (ADR 0008). 문항 순서대로 `문항id=답`을 `;`로
|
|
9
|
-
// "q1=b;q2=a,d;
|
|
8
|
+
// 제출하는 답: 문자열 하나 (ADR 0008 · 0013). 문항 순서대로 `문항id=답`을 `;`로 잇는다. 주관식 답은 답 형식(공개 값 answerFormat)에 따라
|
|
9
|
+
// - 2 (1.10.0부터 편집 화면이 저장): 원문, `%` → `%25` · `;` → `%3B`만 바꿈 "q1=b;q2=a,d;q4=가중치"
|
|
10
|
+
// - 없음 (1.9.x 이하가 저장한 자료): encodeURIComponent "q4=%EA%B0%80%EC%A4%91%EC%B9%98"
|
|
11
|
+
// 어느 쪽이든 decodeURIComponent 하나로 원래 답이 된다. 정답 정규식(grading)도 같은 형식으로 만들어 둘이 늘 짝이 맞는다
|
|
12
|
+
// 주관식 문항의 공개 값 answerMode: 'list'(허용 답 목록, 기본) · 'regex'(작성자 정규식). 다시 열 때 정답 입력 방식을 되살린다
|
|
10
13
|
// 채점 방식은 둘 중 하나 (작성자가 고름, 완료 정책은 LXP 설정, ADR 0012). 정답(settings.grading)은 편집 화면이 문항마다 고른 답으로 만든다.
|
|
11
14
|
// - pattern (기본, 모두 맞혀야 100점): 정규식 하나 { type: 'pattern', answer_key: '^q1=b;…$' }, 답은 위 문자열 하나
|
|
12
15
|
// - partial_pattern (문항별 부분 점수): 문항마다 정규식 { type: 'partial_pattern', answer_key: ['^q1=b$', …], scores: [50, …] },
|
|
@@ -25,9 +28,9 @@ export const LIMITS = {
|
|
|
25
28
|
groupsMax: 6,
|
|
26
29
|
// 여러 문항 퀴즈: 문항 20개까지. pattern은 모든 문항을 맞혀야 100점, partial_pattern은 맞은 문항 점수의 합
|
|
27
30
|
questionsMax: 20,
|
|
28
|
-
// 편집 화면에서 올린 그림 (지문 · 해설):
|
|
29
|
-
|
|
30
|
-
|
|
31
|
+
// 편집 화면에서 올린 그림 (지문 · 해설): 퀴즈 전체에 50개까지. 그림은 서버 파일로 올리고 글에는 파일 키(약 90자)만 두어
|
|
32
|
+
// settings(서버 한도 약 64KB)에는 50개를 넣어도 약 5KB
|
|
33
|
+
imagesMax: 50,
|
|
31
34
|
};
|
|
32
35
|
|
|
33
36
|
/** 편집 화면에서 문항을 더 넣을 수 있는지. 이미 여러 문항으로 저장된 퀴즈도 그대로 보이고 저장되며, 더 넣는 것만 막는다 */
|
|
@@ -90,8 +93,14 @@ export function convertType(q, type, names) {
|
|
|
90
93
|
{ id: 'g2', name: names.group('B') },
|
|
91
94
|
];
|
|
92
95
|
else delete next.groups;
|
|
93
|
-
if (type === 'text')
|
|
94
|
-
|
|
96
|
+
if (type === 'text') {
|
|
97
|
+
next.placeholder = q.placeholder ?? '';
|
|
98
|
+
// 정답 입력 방식 (공개 값, ADR 0013): 직접 입력이 기본
|
|
99
|
+
next.answerMode = q.answerMode === 'regex' ? 'regex' : 'list';
|
|
100
|
+
} else {
|
|
101
|
+
delete next.placeholder;
|
|
102
|
+
delete next.answerMode;
|
|
103
|
+
}
|
|
95
104
|
return next;
|
|
96
105
|
}
|
|
97
106
|
|
|
@@ -120,9 +129,35 @@ export function validateQuiz(content, v) {
|
|
|
120
129
|
return at(v.placeholderMax(LIMITS.placeholderMax));
|
|
121
130
|
if (q.explanation?.enabled && !q.explanation.text?.trim()) return at(v.explanation);
|
|
122
131
|
}
|
|
132
|
+
// 부분 채점(문제 2개 이상): 문제별 배점은 0~100 정수, 합은 100 이상 (100보다 작으면 다 맞혀도 완료되지 않음)
|
|
133
|
+
if (content.gradingType === PARTIAL && content.questions.length > 1) {
|
|
134
|
+
const bad = content.questions.findIndex(
|
|
135
|
+
(q) => !Number.isInteger(q.points) || q.points < 0 || q.points > 100,
|
|
136
|
+
);
|
|
137
|
+
if (bad >= 0) return { questionIndex: bad, message: v.at(bad + 1, v.pointsInt), field: 'points' };
|
|
138
|
+
if (totalPoints(content.questions) < 100)
|
|
139
|
+
return { questionIndex: -1, message: v.pointsTotal, field: 'points' };
|
|
140
|
+
}
|
|
123
141
|
return null;
|
|
124
142
|
}
|
|
125
143
|
|
|
144
|
+
/**
|
|
145
|
+
* 자동 배점: 문제마다 같은 점수 ceil(100 / 문제 수) (연주님 부분 채점 UI, 2026-11-18 결정). 3문제면 34 · 34 · 34(합 102)이고
|
|
146
|
+
* 서버가 학생 점수를 100에서 자르므로 다 맞히면 100점. 100으로 나눠떨어지면 합 100 (4문제 25 · 25 · 25 · 25)
|
|
147
|
+
* @param {number} n 문제 수
|
|
148
|
+
* @returns {number[]}
|
|
149
|
+
*/
|
|
150
|
+
export function equalPoints(n) {
|
|
151
|
+
const count = Math.floor(n);
|
|
152
|
+
if (!(count >= 1)) return [];
|
|
153
|
+
return Array.from({ length: count }, () => Math.ceil(100 / count));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 문제별 배점 합 (정수가 아닌 배점은 0으로) */
|
|
157
|
+
export function totalPoints(questions) {
|
|
158
|
+
return questions.reduce((sum, q) => sum + (Number.isInteger(q.points) ? q.points : 0), 0);
|
|
159
|
+
}
|
|
160
|
+
|
|
126
161
|
// ---------- 답 문자열 (편집 화면이 같은 모양으로 정답 정규식을 만든다) ----------
|
|
127
162
|
|
|
128
163
|
/**
|
|
@@ -174,21 +209,44 @@ export function decodeAnswer(q, text) {
|
|
|
174
209
|
}
|
|
175
210
|
}
|
|
176
211
|
|
|
212
|
+
// ---------- 답 형식 (ADR 0013) ----------
|
|
213
|
+
|
|
214
|
+
/** 1.10.0 편집 화면이 저장하는 답 형식. 공개 settings answerFormat에 둔다 (학생 화면이 주관식 답을 어떻게 보낼지 안다) */
|
|
215
|
+
export const ANSWER_FORMAT = 2;
|
|
216
|
+
/**
|
|
217
|
+
* 이 settings를 읽으려면 필요한 템플릿 버전 (공개 settings requires). 앞으로 형식을 바꾸는 판이 올리고, 옛 판 화면에 안내할 때 쓴다.
|
|
218
|
+
* 템플릿 이름을 키로 두어 한 settings를 여러 템플릿이 읽게 돼도 섞이지 않게 한다
|
|
219
|
+
*/
|
|
220
|
+
export const REQUIRES = { quiz: '1.10.0' };
|
|
221
|
+
|
|
222
|
+
/** settings → 학생 화면이 쓸 답 형식 (1 = encodeURIComponent, 2 = 원문). 모르는 미래 형식(3 이상)은 2로 보낸다 */
|
|
223
|
+
export const answerFormatOf = (content) => (Number(content?.answerFormat) >= 2 ? 2 : 1);
|
|
224
|
+
|
|
225
|
+
/** 원문 형식 주관식 답: `%` · `;`만 바꾼다 (`;`는 문항 경계, `%`는 decodeURIComponent로 되돌릴 수 있게) */
|
|
226
|
+
export const encodeRaw = (text) => String(text).replace(/%/g, '%25').replace(/;/g, '%3B');
|
|
227
|
+
|
|
228
|
+
/** 주관식 답(앞뒤 공백을 자른 것) → 제출 문자열 조각 */
|
|
229
|
+
export const encodeText = (text, format = 1) =>
|
|
230
|
+
format >= 2 ? encodeRaw(text) : encodeURIComponent(text);
|
|
231
|
+
|
|
177
232
|
// ---------- 제출 답 하나로 잇기 · 풀기 (ADR 0008) ----------
|
|
178
233
|
|
|
179
|
-
/**
|
|
180
|
-
|
|
234
|
+
/**
|
|
235
|
+
* 문항별 답 문자열 → 제출할 답 문자열 하나. 주관식 답은 encodeText (`;`가 들어가도 경계가 그대로).
|
|
236
|
+
* format: answerFormatOf(settings) (없으면 1 = 옛 형식)
|
|
237
|
+
*/
|
|
238
|
+
export function joinAnswers(questions, values, format = 1) {
|
|
181
239
|
return questions
|
|
182
240
|
.map((q, i) => {
|
|
183
241
|
const a = encodeAnswer(q, values[i]);
|
|
184
|
-
return `${q.id}=${q.type === 'text' ?
|
|
242
|
+
return `${q.id}=${q.type === 'text' ? encodeText(a, format) : a}`;
|
|
185
243
|
})
|
|
186
244
|
.join(';');
|
|
187
245
|
}
|
|
188
246
|
|
|
189
247
|
/**
|
|
190
248
|
* 제출한 답 → 문항 id별 답 문자열 (다시 열기 · 튜터링). 옛 답 `{ answers: { q1: "b" } }`도 받는다.
|
|
191
|
-
* `;`로 나누고 첫 `=`에서 문항 id와 답을 나눈 뒤, 주관식은 decodeURIComponent
|
|
249
|
+
* `;`로 나누고 첫 `=`에서 문항 id와 답을 나눈 뒤, 주관식은 decodeURIComponent (답 형식 1 · 2 모두 이것 하나로 풀림)
|
|
192
250
|
*/
|
|
193
251
|
export function splitAnswers(questions, answer) {
|
|
194
252
|
// partial_pattern 답: 문항별 문자열 배열 → 한 문자열로 이어 같은 방식으로 푼다
|
|
@@ -215,60 +273,322 @@ export function splitAnswers(questions, answer) {
|
|
|
215
273
|
return out;
|
|
216
274
|
}
|
|
217
275
|
|
|
218
|
-
// ---------- 정답 정규식 (편집 화면, ADR 0009) ----------
|
|
276
|
+
// ---------- 정답 정규식 (편집 화면, ADR 0009 · 0013) ----------
|
|
219
277
|
|
|
220
278
|
const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
221
279
|
const unescapeRegex = (text) => text.replace(/\\(.)/g, '$1');
|
|
222
280
|
|
|
223
|
-
/** 정답
|
|
224
|
-
|
|
281
|
+
/** 주관식 정답 입력 방식: 'list'(허용 답 목록, 기본) · 'regex'(작성자 정규식) */
|
|
282
|
+
export const isRegexMode = (q) => q?.type === 'text' && q.answerMode === 'regex';
|
|
283
|
+
|
|
284
|
+
/** 정답 하나(화면 값) → 문항 정규식 조각. 주관식 목록은 허용 답 여러 개를 (?:…|…)로, 정규식은 바꾼 식을 (?:…)로 */
|
|
285
|
+
function keyPart(q, value, format) {
|
|
225
286
|
if (q.type === 'text') {
|
|
226
|
-
|
|
227
|
-
|
|
287
|
+
if (isRegexMode(q)) {
|
|
288
|
+
const result = compileTextRegex(typeof value === 'string' ? value : '');
|
|
289
|
+
return `(?:${result.body ?? ''})`;
|
|
290
|
+
}
|
|
291
|
+
const alts = (Array.isArray(value) ? value : []).map((t) => String(t).trim()).filter(Boolean);
|
|
292
|
+
return `(?:${alts.map((t) => escapeRegex(encodeText(t, format))).join('|')})`;
|
|
228
293
|
}
|
|
229
294
|
return escapeRegex(encodeAnswer(q, value));
|
|
230
295
|
}
|
|
231
296
|
|
|
232
297
|
/**
|
|
233
|
-
* 문항별 정답(화면 값:
|
|
234
|
-
* 인코딩 → 정규식 이스케이프 → `|`로 묶기 → 전체를 `^…$` (ADR 0008 §4)
|
|
298
|
+
* 문항별 정답(화면 값: 주관식 목록은 허용 답 배열, 정규식은 작성자가 쓴 식) → regex 정답 정규식 하나.
|
|
299
|
+
* 인코딩 → 정규식 이스케이프 → `|`로 묶기 → 전체를 `^…$` (ADR 0008 §4). format: 답 형식 (편집 화면은 ANSWER_FORMAT)
|
|
300
|
+
*/
|
|
301
|
+
export function buildAnswerKey(questions, key, format = 1) {
|
|
302
|
+
return `^${questions.map((q) => `${escapeRegex(q.id)}=${keyPart(q, key[q.id], format)}`).join(';')}$`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* 정답 정규식 `^…$` → 문항 조각 목록 (`문항id=…`). 경계는 `;문항id=` (정답 조각 안의 `;`는 주관식 인코딩 %3B이고,
|
|
307
|
+
* 작성자 정규식에는 `;`를 쓰지 못한다). 모양이 다르면 null
|
|
235
308
|
*/
|
|
236
|
-
|
|
237
|
-
|
|
309
|
+
function keyParts(questions, regex) {
|
|
310
|
+
if (typeof regex !== 'string' || !regex.startsWith('^') || !regex.endsWith('$')) return null;
|
|
311
|
+
const body = regex.slice(1, -1);
|
|
312
|
+
const ids = questions.map((q) => escapeRegex(escapeRegex(q.id)));
|
|
313
|
+
return ids.length ? body.split(new RegExp(`;(?=(?:${ids.join('|')})=)`)) : body.split(';');
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** 정답 정규식 → 문항 id별 조각(`문항id=…`) Map. 모양이 다르면 null */
|
|
317
|
+
function splitKeyParts(questions, regex) {
|
|
318
|
+
const parts = keyParts(questions, regex);
|
|
319
|
+
if (!parts) return null;
|
|
320
|
+
const out = new Map();
|
|
321
|
+
for (const part of parts) {
|
|
322
|
+
const at = part.indexOf('=');
|
|
323
|
+
if (at < 0) return null;
|
|
324
|
+
out.set(unescapeRegex(part.slice(0, at)), part);
|
|
325
|
+
}
|
|
326
|
+
return out;
|
|
238
327
|
}
|
|
239
328
|
|
|
240
329
|
/**
|
|
241
330
|
* buildAnswerKey가 만든 정규식 → 문항별 정답(화면 값). 다른 모양(손으로 쓴 정규식)이면 null.
|
|
242
|
-
*
|
|
331
|
+
* 주관식 정규식 문항(answerMode 'regex')은 저장한 식을 작성자가 쓴 모양으로 되돌린다 (`%25` → `%`).
|
|
332
|
+
* 목록은 답 형식 1 · 2 모두 decodeURIComponent로 푼다. 문항이 바뀌었으면 있는 문항만 돌려준다 (없는 문항은 validateAnswerKey가 알려 줌)
|
|
243
333
|
*/
|
|
244
334
|
export function parseAnswerKey(questions, regex) {
|
|
245
|
-
|
|
335
|
+
const parts = keyParts(questions, regex);
|
|
336
|
+
if (!parts) return null;
|
|
246
337
|
const byId = Object.fromEntries(questions.map((q) => [q.id, q]));
|
|
247
338
|
const out = {};
|
|
248
|
-
|
|
249
|
-
for (const part of regex.slice(1, -1).split(';')) {
|
|
339
|
+
for (const part of parts) {
|
|
250
340
|
const at = part.indexOf('=');
|
|
251
341
|
if (at < 0) return null;
|
|
252
342
|
const id = unescapeRegex(part.slice(0, at));
|
|
253
|
-
const
|
|
343
|
+
const piece = part.slice(at + 1);
|
|
254
344
|
const q = byId[id];
|
|
255
345
|
if (!q) continue;
|
|
256
346
|
if (q.type === 'text') {
|
|
257
|
-
if (!
|
|
347
|
+
if (!piece.startsWith('(?:') || !piece.endsWith(')')) return null;
|
|
348
|
+
const inner = piece.slice(3, -1);
|
|
349
|
+
if (isRegexMode(q)) {
|
|
350
|
+
out[id] = inner.replace(/%25/g, '%');
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
258
353
|
try {
|
|
259
|
-
out[id] =
|
|
260
|
-
.slice(3, -1)
|
|
354
|
+
out[id] = inner
|
|
261
355
|
.split(/(?<!\\)\|/)
|
|
262
356
|
.map((t) => decodeURIComponent(unescapeRegex(t)))
|
|
263
357
|
.filter(Boolean);
|
|
264
358
|
} catch {
|
|
265
359
|
return null;
|
|
266
360
|
}
|
|
267
|
-
} else out[id] = decodeAnswer(q, unescapeRegex(
|
|
361
|
+
} else out[id] = decodeAnswer(q, unescapeRegex(piece));
|
|
362
|
+
}
|
|
363
|
+
return out;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* 정규식 조각이 이스케이프한 글자만으로 된 `a|b|…`이면 허용 답 목록, 아니면 null (정규식 → 직접 입력으로 바꿀 때)
|
|
368
|
+
* @param {string} source 작성자가 쓴 정규식
|
|
369
|
+
*/
|
|
370
|
+
export function regexToList(source) {
|
|
371
|
+
const out = [];
|
|
372
|
+
for (const alt of String(source ?? '').trim().split(/(?<!\\)\|/)) {
|
|
373
|
+
if (!alt) continue;
|
|
374
|
+
if (/[.*+?^${}()|[\]\\]/.test(alt.replace(/\\[\\.*+?^${}()|[\]]/g, ''))) return null;
|
|
375
|
+
out.push(unescapeRegex(alt));
|
|
268
376
|
}
|
|
269
377
|
return out;
|
|
270
378
|
}
|
|
271
379
|
|
|
380
|
+
/** 허용 답 목록 → 같은 뜻의 정규식 (직접 입력 → 정규식으로 바꿀 때) */
|
|
381
|
+
export const listToRegex = (list) =>
|
|
382
|
+
(list ?? [])
|
|
383
|
+
.map((t) => String(t).trim())
|
|
384
|
+
.filter(Boolean)
|
|
385
|
+
.map(escapeRegex)
|
|
386
|
+
.join('|');
|
|
387
|
+
|
|
388
|
+
// Python regex(서버)와 브라우저 RegExp가 같은 뜻으로 읽는 글자만 받는다
|
|
389
|
+
const ALLOWED_LETTER_ESCAPES = new Set(['d', 'D', 'w', 'W', 's', 'S', 'n', 'r', 't', 'f', 'v']);
|
|
390
|
+
// 서버 \w (Python regex, 유니코드): 글자 · 결합 문자 · 숫자 · 연결 문장 부호
|
|
391
|
+
const UNICODE_WORD = '\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}\\u200C\\u200D';
|
|
392
|
+
// u 플래그에서 \로 써도 되는 글자 (그 밖의 기호는 \ 없이 글자 그대로)
|
|
393
|
+
const U_SYNTAX = new Set([...'^$\\.*+?()[]{}|/']);
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* 작성자 주관식 정규식 → 서버 정답 조각(body, `(?:…)` 안에 들어감)과 채점 테스트용 JS 정규식(test, u 플래그).
|
|
397
|
+
* - 맨 앞 `^` · 맨 뒤 `$`는 뗀다 (답 전체와 맞춰 봄, notes에 'anchors')
|
|
398
|
+
* - 맨 앞 `(?i)`(대소문자 무시)는 `(?i:…)`로 감싼다 (가운데 전역 플래그는 서버 오류, notes에 'flag')
|
|
399
|
+
* - 답 형식 2에서 학생 답의 `%`는 `%25`로 가므로 식의 `%`(`\%`)도 `%25`로
|
|
400
|
+
* - 서버(Python regex)와 브라우저가 다르게 읽거나 한쪽만 아는 문법은 막는다 (error 코드)
|
|
401
|
+
* 채점 테스트(test)는 서버처럼: `\d` → `\p{Nd}`, `\w` → 유니코드 글자, `.`은 줄바꿈만 빼고
|
|
402
|
+
* @param {string} source
|
|
403
|
+
* @returns {{ body?: string, test?: string, notes: string[], error?: string, detail?: string }}
|
|
404
|
+
*/
|
|
405
|
+
export function compileTextRegex(source) {
|
|
406
|
+
const notes = [];
|
|
407
|
+
let s = String(source ?? '').trim();
|
|
408
|
+
const fail = (error, detail) => ({ error, detail, notes });
|
|
409
|
+
if (!s) return fail('empty');
|
|
410
|
+
let ignoreCase = false;
|
|
411
|
+
// 맨 앞 `^` · `(?i)`는 어느 순서로 와도 뗀다
|
|
412
|
+
for (;;) {
|
|
413
|
+
const lead = /^\(\?([a-zA-Z]+)\)/.exec(s);
|
|
414
|
+
if (lead) {
|
|
415
|
+
if (lead[1] !== 'i') return fail('flag');
|
|
416
|
+
ignoreCase = true;
|
|
417
|
+
s = s.slice(lead[0].length);
|
|
418
|
+
if (!notes.includes('flag')) notes.push('flag');
|
|
419
|
+
} else if (s.startsWith('^')) {
|
|
420
|
+
s = s.slice(1);
|
|
421
|
+
if (!notes.includes('anchors')) notes.push('anchors');
|
|
422
|
+
} else break;
|
|
423
|
+
}
|
|
424
|
+
if (/(^|[^\\])(\\\\)*\$$/.test(s)) {
|
|
425
|
+
s = s.slice(0, -1);
|
|
426
|
+
if (!notes.includes('anchors')) notes.push('anchors');
|
|
427
|
+
}
|
|
428
|
+
if (!s) return fail('empty');
|
|
429
|
+
let body = '';
|
|
430
|
+
let test = '';
|
|
431
|
+
let inClass = false;
|
|
432
|
+
for (let i = 0; i < s.length; i++) {
|
|
433
|
+
const c = s[i];
|
|
434
|
+
if (c === ';') return fail('semicolon');
|
|
435
|
+
if (c === '\\') {
|
|
436
|
+
const n = s[i + 1];
|
|
437
|
+
if (n === undefined) return fail('invalid');
|
|
438
|
+
i++;
|
|
439
|
+
if (n === ';') return fail('semicolon');
|
|
440
|
+
if (n === '%') {
|
|
441
|
+
if (inClass) return fail('percentInClass');
|
|
442
|
+
body += '%25';
|
|
443
|
+
test += '%25';
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
if (/[1-9]/.test(n) || n === 'k' || n === 'g') return fail('backref');
|
|
447
|
+
if (n === 'p' || n === 'P') return fail('unicodeProperty');
|
|
448
|
+
if (n === 'b' || n === 'B') {
|
|
449
|
+
if (inClass && n === 'b') {
|
|
450
|
+
body += '\\b';
|
|
451
|
+
test += '\\x08';
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
return fail('wordBoundary');
|
|
455
|
+
}
|
|
456
|
+
if (n === '0') {
|
|
457
|
+
if (/[0-9]/.test(s[i + 1] ?? '')) return fail('escape', `\\0${s[i + 1]}`);
|
|
458
|
+
body += '\\0';
|
|
459
|
+
test += '\\0';
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
if (n === 'x') {
|
|
463
|
+
const hex = s.slice(i + 1, i + 3);
|
|
464
|
+
if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return fail('escape', '\\x');
|
|
465
|
+
body += `\\x${hex}`;
|
|
466
|
+
test += `\\x${hex}`;
|
|
467
|
+
i += 2;
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (n === 'u') {
|
|
471
|
+
const hex = s.slice(i + 1, i + 5);
|
|
472
|
+
if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return fail('escape', '\\u');
|
|
473
|
+
body += `\\u${hex}`;
|
|
474
|
+
test += `\\u${hex}`;
|
|
475
|
+
i += 4;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (/[A-Za-z0-9]/.test(n)) {
|
|
479
|
+
if (!ALLOWED_LETTER_ESCAPES.has(n)) return fail('escape', `\\${n}`);
|
|
480
|
+
body += `\\${n}`;
|
|
481
|
+
if (n === 'd') test += '\\p{Nd}';
|
|
482
|
+
else if (n === 'w') test += inClass ? UNICODE_WORD : `[${UNICODE_WORD}]`;
|
|
483
|
+
else if (n === 'D' || n === 'W') {
|
|
484
|
+
if (inClass) return fail('negatedInClass', `\\${n}`);
|
|
485
|
+
test += n === 'D' ? '\\P{Nd}' : `[^${UNICODE_WORD}]`;
|
|
486
|
+
} else test += `\\${n}`;
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
// 기호: 서버는 글자 그대로. u 플래그는 문법 기호(와 [ ] 안의 -)만 \를 받는다
|
|
490
|
+
body += `\\${n}`;
|
|
491
|
+
test += U_SYNTAX.has(n) || (inClass && n === '-') ? `\\${n}` : n;
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
if (inClass) {
|
|
495
|
+
if (c === ']') inClass = false;
|
|
496
|
+
else if (c === '[') return fail('nestedClass');
|
|
497
|
+
else if (c === '%') return fail('percentInClass');
|
|
498
|
+
body += c;
|
|
499
|
+
test += c;
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
if (c === '[') {
|
|
503
|
+
const neg = s[i + 1] === '^';
|
|
504
|
+
const first = s[i + (neg ? 2 : 1)];
|
|
505
|
+
// [] · [^] · []a]: 브라우저와 서버가 다르게 읽는다
|
|
506
|
+
if (first === ']' || first === undefined) return fail('emptyClass');
|
|
507
|
+
inClass = true;
|
|
508
|
+
body += neg ? '[^' : '[';
|
|
509
|
+
test += neg ? '[^' : '[';
|
|
510
|
+
if (neg) i++;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (c === '%') {
|
|
514
|
+
body += '%25';
|
|
515
|
+
test += '%25';
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (c === '^' || c === '$') return fail('anchorMiddle');
|
|
519
|
+
if (c === '.') {
|
|
520
|
+
body += '.';
|
|
521
|
+
// 서버 `.`은 줄바꿈(\n)만 빼고 모두 (브라우저는 \r · \u2028 · \u2029도 뺌)
|
|
522
|
+
test += '[^\\n]';
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (c === '(') {
|
|
526
|
+
if (s[i + 1] === '?') {
|
|
527
|
+
const rest = s.slice(i + 2);
|
|
528
|
+
const ok = ['<=', '<!', ':', '=', '!', 'i:'].find((p) => rest.startsWith(p));
|
|
529
|
+
if (!ok) {
|
|
530
|
+
if (/^(P?<[A-Za-z_]|P=|P>)/.test(rest)) return fail('namedGroup');
|
|
531
|
+
if (/^[a-zA-Z-]+\)/.test(rest)) return fail('flag');
|
|
532
|
+
return fail('group', `(?${rest.slice(0, 2)}`);
|
|
533
|
+
}
|
|
534
|
+
body += `(?${ok}`;
|
|
535
|
+
test += `(?${ok}`;
|
|
536
|
+
i += 1 + ok.length;
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
body += c;
|
|
540
|
+
test += c;
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
if (c === '{') {
|
|
544
|
+
const m = /^\{(\d*)(,?)(\d*)\}/.exec(s.slice(i));
|
|
545
|
+
if (m && m[1] === '' && m[2] === ',') return fail('quantifier', m[0]);
|
|
546
|
+
if (m && (m[1] !== '' || m[3] === '')) {
|
|
547
|
+
body += m[0];
|
|
548
|
+
test += m[0];
|
|
549
|
+
i += m[0].length - 1;
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
// 반복이 아닌 `{`는 서버에서 글자 그대로 (u 플래그는 \{여야 함)
|
|
553
|
+
body += '{';
|
|
554
|
+
test += '\\{';
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
if (c === '}' || c === ']') {
|
|
558
|
+
body += c;
|
|
559
|
+
test += `\\${c}`;
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
body += c;
|
|
563
|
+
test += c;
|
|
564
|
+
}
|
|
565
|
+
if (inClass) return fail('invalid');
|
|
566
|
+
if (ignoreCase) {
|
|
567
|
+
body = `(?i:${body})`;
|
|
568
|
+
test = `(?i:${test})`;
|
|
569
|
+
}
|
|
570
|
+
try {
|
|
571
|
+
new RegExp(`^(?:${test})$`, 'u');
|
|
572
|
+
} catch (e) {
|
|
573
|
+
return fail('invalid', e instanceof Error ? e.message : String(e));
|
|
574
|
+
}
|
|
575
|
+
return { body, test, notes };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* 채점 테스트: 학생이 이 답을 내면 정답인지 (서버처럼 앞뒤 공백을 자르고 답 형식 2로 바꾼 뒤 전체 일치).
|
|
580
|
+
* 정규식이 틀리면 null
|
|
581
|
+
*/
|
|
582
|
+
export function testTextRegex(source, answer) {
|
|
583
|
+
const { test } = compileTextRegex(source);
|
|
584
|
+
if (test === undefined) return null;
|
|
585
|
+
try {
|
|
586
|
+
return new RegExp(`^(?:${test})$`, 'u').test(encodeRaw(String(answer ?? '').trim()));
|
|
587
|
+
} catch {
|
|
588
|
+
return null;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
272
592
|
// ---------- 문항별 부분 점수 (partial_pattern) ----------
|
|
273
593
|
|
|
274
594
|
export const PARTIAL = 'partial_pattern';
|
|
@@ -280,13 +600,13 @@ export function gradingTypeOf(content, grading) {
|
|
|
280
600
|
}
|
|
281
601
|
|
|
282
602
|
/** 문항별 답 → 제출할 문자열 배열 (문항 순서). 한 항목은 pattern 답의 한 조각과 같은 `문항id=답` */
|
|
283
|
-
export function joinAnswerList(questions, values) {
|
|
284
|
-
return questions.map((q, i) => joinAnswers([q], [values[i]]));
|
|
603
|
+
export function joinAnswerList(questions, values, format = 1) {
|
|
604
|
+
return questions.map((q, i) => joinAnswers([q], [values[i]], format));
|
|
285
605
|
}
|
|
286
606
|
|
|
287
607
|
/** 문항별 정답 → 문항마다 정답 정규식 `^문항id=…$` (buildAnswerKey를 문항 하나씩) */
|
|
288
|
-
export function buildAnswerKeys(questions, key) {
|
|
289
|
-
return questions.map((q) => buildAnswerKey([q], key));
|
|
608
|
+
export function buildAnswerKeys(questions, key, format = 1) {
|
|
609
|
+
return questions.map((q) => buildAnswerKey([q], key, format));
|
|
290
610
|
}
|
|
291
611
|
|
|
292
612
|
/** buildAnswerKeys가 만든 정규식 배열 → 문항별 정답(화면 값). 다른 모양이면 null */
|
|
@@ -300,10 +620,11 @@ export function parseAnswerKeys(questions, keys) {
|
|
|
300
620
|
* 정답 검증 2 (문항별): 문항마다 checkAnswerKey (정답으로 낸 답은 맞고, 하나 바꾼 답은 맞지 않음).
|
|
301
621
|
* 문제가 없으면 null, 있으면 { questionIndex, message }
|
|
302
622
|
*/
|
|
303
|
-
export function checkAnswerKeys(questions, key, keys, v) {
|
|
623
|
+
export function checkAnswerKeys(questions, key, keys, v, format = 1) {
|
|
304
624
|
for (const [i, q] of questions.entries()) {
|
|
625
|
+
if (isRegexMode(q)) continue;
|
|
305
626
|
const at = (_no, message) => v.at(i + 1, message);
|
|
306
|
-
const problem = checkAnswerKey([q], key, keys[i], { ...v, at });
|
|
627
|
+
const problem = checkAnswerKey([q], key, keys[i], { ...v, at }, format);
|
|
307
628
|
if (!problem) continue;
|
|
308
629
|
if (problem.message === v.badRegex) return { questionIndex: i, message: at(0, v.badRegex) };
|
|
309
630
|
return {
|
|
@@ -316,7 +637,7 @@ export function checkAnswerKeys(questions, key, keys, v) {
|
|
|
316
637
|
|
|
317
638
|
/**
|
|
318
639
|
* 저장할 문항별 점수. 저장된 점수는 같은 자리 정규식(answer_key[i] = "^문제id=…")의 문제 것이라, 문제 id로 맞춰 지금 문제 순서로 다시 놓는다
|
|
319
|
-
* (순서를 바꿔도 점수가 제 문제를 따라감). 저장된 문제 id와 지금 문제 id가 하나라도 다르면(더함 · 지움) 똑같이 나눈 점수 (split
|
|
640
|
+
* (순서를 바꿔도 점수가 제 문제를 따라감). 저장된 문제 id와 지금 문제 id가 하나라도 다르면(더함 · 지움) 똑같이 나눈 점수 (split: 퀴즈 편집 화면은 equalPoints).
|
|
320
641
|
* resplit: 저장된 점수가 있었는데 맞추지 못해 다시 나눴는지 (화면이 짧게 알림)
|
|
321
642
|
* @param {{ answer_key?: unknown, scores?: unknown } | undefined} saved 저장된 partial_pattern 채점 설정
|
|
322
643
|
* @returns {{ scores: number[], resplit: boolean }}
|
|
@@ -351,7 +672,13 @@ export function validateAnswerKey(questions, key, v) {
|
|
|
351
672
|
const at = (message) => ({ questionIndex: i, message: v.at(i + 1, message) });
|
|
352
673
|
const value = key[q.id];
|
|
353
674
|
if (q.type === 'text') {
|
|
354
|
-
if (
|
|
675
|
+
if (isRegexMode(q)) {
|
|
676
|
+
const { error, detail } = compileTextRegex(typeof value === 'string' ? value : '');
|
|
677
|
+
if (error === 'empty') return at(v.noAnswer);
|
|
678
|
+
if (error) return at(v.regex[error]?.(detail) ?? v.regex.invalid(detail));
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
if (!(Array.isArray(value) ? value : []).some((t) => String(t).trim())) return at(v.noAnswer);
|
|
355
682
|
continue;
|
|
356
683
|
}
|
|
357
684
|
if (!isAnswered(q, value)) return at(v.noAnswer);
|
|
@@ -482,7 +809,23 @@ export function wrongValue(q, value) {
|
|
|
482
809
|
* 문제가 없으면 null, 있으면 { questionIndex, message }
|
|
483
810
|
* @param {object} v 검증 문구 (ui/texts.js의 answers.validation)
|
|
484
811
|
*/
|
|
485
|
-
export function checkAnswerKey(questions, key, regex, v) {
|
|
812
|
+
export function checkAnswerKey(questions, key, regex, v, format = 1) {
|
|
813
|
+
// 주관식 정규식 문항은 작성자가 일부러 넓게 쓸 수 있어 왕복 · 오답 검사에서 뺀다 (채점 테스트 · 빈 답 경고로 대신, ADR 0013).
|
|
814
|
+
// 나머지 문항만으로 만든 정규식으로 검사하고 문항 번호는 원래 자리로
|
|
815
|
+
if (questions.some(isRegexMode)) {
|
|
816
|
+
const kept = questions.map((q, i) => (isRegexMode(q) ? -1 : i)).filter((i) => i >= 0);
|
|
817
|
+
if (kept.length === 0) return null;
|
|
818
|
+
const sub = kept.map((i) => questions[i]);
|
|
819
|
+
// 받은 정규식에서 남길 문항 조각만 골라 잇는다 (모양이 다르면 다시 만들지 않고 그대로 검사해 왕복에서 걸리게)
|
|
820
|
+
const parts = splitKeyParts(questions, regex);
|
|
821
|
+
const subKey = parts
|
|
822
|
+
? `^${sub.map((q) => parts.get(q.id) ?? '').join(';')}$`
|
|
823
|
+
: regex;
|
|
824
|
+
const problem = checkAnswerKey(sub, key, subKey, v, format);
|
|
825
|
+
return problem && problem.questionIndex >= 0
|
|
826
|
+
? { ...problem, questionIndex: kept[problem.questionIndex] }
|
|
827
|
+
: problem;
|
|
828
|
+
}
|
|
486
829
|
let re;
|
|
487
830
|
try {
|
|
488
831
|
re = new RegExp(regex);
|
|
@@ -491,20 +834,20 @@ export function checkAnswerKey(questions, key, regex, v) {
|
|
|
491
834
|
}
|
|
492
835
|
// 화면 값으로: 주관식은 허용 답 중 하나
|
|
493
836
|
const base = questions.map((q) => (q.type === 'text' ? (key[q.id] ?? [])[0] : key[q.id]));
|
|
494
|
-
if (!re.test(joinAnswers(questions, base))) return { questionIndex: -1, message: v.roundTrip };
|
|
837
|
+
if (!re.test(joinAnswers(questions, base, format))) return { questionIndex: -1, message: v.roundTrip };
|
|
495
838
|
for (const [i, q] of questions.entries()) {
|
|
496
839
|
const at = (message) => ({ questionIndex: i, message: v.at(i + 1, message) });
|
|
497
840
|
if (q.type === 'text')
|
|
498
841
|
for (const alt of key[q.id] ?? []) {
|
|
499
842
|
const values = [...base];
|
|
500
843
|
values[i] = alt;
|
|
501
|
-
if (!re.test(joinAnswers(questions, values))) return at(v.roundTrip);
|
|
844
|
+
if (!re.test(joinAnswers(questions, values, format))) return at(v.roundTrip);
|
|
502
845
|
}
|
|
503
846
|
const wrong = wrongValue(q, key[q.id]);
|
|
504
847
|
if (wrong === undefined) continue;
|
|
505
848
|
const values = [...base];
|
|
506
849
|
values[i] = q.type === 'text' ? wrong[0] : wrong;
|
|
507
|
-
if (re.test(joinAnswers(questions, values))) return at(v.tooWide);
|
|
850
|
+
if (re.test(joinAnswers(questions, values, format))) return at(v.tooWide);
|
|
508
851
|
}
|
|
509
852
|
return null;
|
|
510
853
|
}
|
|
@@ -11,9 +11,8 @@ export interface RichText {
|
|
|
11
11
|
list(tag?: 'ul' | 'ol'): void;
|
|
12
12
|
code(sample: string): void;
|
|
13
13
|
}
|
|
14
|
-
export type Block = { type: 'text'; text: string } | { type: 'image'; alt: string;
|
|
14
|
+
export type Block = { type: 'text'; text: string } | { type: 'image'; alt: string; ref: string };
|
|
15
15
|
export declare function toMarkdown(root: Node): string;
|
|
16
16
|
export declare function richText(el: HTMLElement, opts: { onChange: (markdown: string) => void }): RichText;
|
|
17
17
|
export declare function splitBlocks(source: string): Block[];
|
|
18
18
|
export declare function joinBlocks(items: Block[]): string;
|
|
19
|
-
export declare function compressImage(file: File, maxChars: number): Promise<string>;
|
|
@@ -436,10 +436,12 @@ export function richText(el, { onChange }) {
|
|
|
436
436
|
return editor;
|
|
437
437
|
}
|
|
438
438
|
|
|
439
|
-
|
|
439
|
+
/** 한 줄을 차지하는 그림: 올린 그림 asset:파일키 · 옛 그림 image:아이디 */
|
|
440
|
+
const IMAGE_LINE =
|
|
441
|
+
/^!\[([^\]]*)\]\((image:[\w-]+|asset:assets\/[\w-]+\/[\w-]+\.(?:png|jpe?g|webp|gif))\)$/i;
|
|
440
442
|
/**
|
|
441
|
-
* 마크다운을 글 칸 · 그림 칸 차례로 나눈다 (한 줄을 차지하는 올린 그림 만 그림 칸)
|
|
442
|
-
* @returns {({ type: 'text', text: string } | { type: 'image', alt: string,
|
|
443
|
+
* 마크다운을 글 칸 · 그림 칸 차례로 나눈다 (한 줄을 차지하는 올린 그림  · 옛 만 그림 칸)
|
|
444
|
+
* @returns {({ type: 'text', text: string } | { type: 'image', alt: string, ref: string })[]}
|
|
443
445
|
*/
|
|
444
446
|
export function splitBlocks(source) {
|
|
445
447
|
const out = [];
|
|
@@ -452,7 +454,7 @@ export function splitBlocks(source) {
|
|
|
452
454
|
const image = IMAGE_LINE.exec(line.trim());
|
|
453
455
|
if (image) {
|
|
454
456
|
flush();
|
|
455
|
-
out.push({ type: 'image', alt: image[1],
|
|
457
|
+
out.push({ type: 'image', alt: image[1], ref: image[2] });
|
|
456
458
|
} else lines.push(line);
|
|
457
459
|
}
|
|
458
460
|
flush();
|
|
@@ -462,60 +464,6 @@ export function splitBlocks(source) {
|
|
|
462
464
|
/** splitBlocks의 반대 (빈 글 칸은 뺀다) */
|
|
463
465
|
export const joinBlocks = (items) =>
|
|
464
466
|
items
|
|
465
|
-
.map((b) =>
|
|
466
|
-
b.type === 'image' ? `` : b.text.replace(/^\n+|\n+$/g, ''),
|
|
467
|
-
)
|
|
467
|
+
.map((b) => (b.type === 'image' ? `` : b.text.replace(/^\n+|\n+$/g, '')))
|
|
468
468
|
.filter((s) => s !== '')
|
|
469
469
|
.join('\n\n');
|
|
470
|
-
|
|
471
|
-
const SIZES = [
|
|
472
|
-
[1280, 0.85],
|
|
473
|
-
[1280, 0.7],
|
|
474
|
-
[960, 0.7],
|
|
475
|
-
[800, 0.6],
|
|
476
|
-
[640, 0.55],
|
|
477
|
-
];
|
|
478
|
-
const fail = (code) => Object.assign(new Error(code), { code });
|
|
479
|
-
/**
|
|
480
|
-
* 올린 그림 파일을 maxChars 글자 이하의 data: 주소로 (webp, 못 만들면 jpeg). 크기 · 품질을 차례로 줄여 맞춘다
|
|
481
|
-
* 실패하면 code가 'not-image' | 'unreadable' | 'too-big'인 오류
|
|
482
|
-
*/
|
|
483
|
-
export async function compressImage(file, maxChars) {
|
|
484
|
-
if (!file.type.startsWith('image/')) throw fail('not-image');
|
|
485
|
-
let bitmap;
|
|
486
|
-
try {
|
|
487
|
-
bitmap = await createImageBitmap(file);
|
|
488
|
-
} catch {
|
|
489
|
-
throw fail('unreadable');
|
|
490
|
-
}
|
|
491
|
-
const canvas = document.createElement('canvas');
|
|
492
|
-
const ctx = canvas.getContext('2d');
|
|
493
|
-
let type = 'image/webp';
|
|
494
|
-
const draw = () => {
|
|
495
|
-
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
496
|
-
// jpeg는 투명한 곳이 검게 되지 않게 흰 바탕
|
|
497
|
-
if (type === 'image/jpeg') {
|
|
498
|
-
ctx.fillStyle = '#fff';
|
|
499
|
-
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
500
|
-
}
|
|
501
|
-
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
|
502
|
-
};
|
|
503
|
-
for (const [side, quality] of SIZES) {
|
|
504
|
-
const scale = Math.min(1, side / Math.max(bitmap.width, bitmap.height));
|
|
505
|
-
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
|
506
|
-
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
|
507
|
-
draw();
|
|
508
|
-
let url = canvas.toDataURL(type, quality);
|
|
509
|
-
if (type === 'image/webp' && !url.startsWith('data:image/webp')) {
|
|
510
|
-
type = 'image/jpeg';
|
|
511
|
-
draw();
|
|
512
|
-
url = canvas.toDataURL(type, quality);
|
|
513
|
-
}
|
|
514
|
-
if (url.length <= maxChars) {
|
|
515
|
-
bitmap.close?.();
|
|
516
|
-
return url;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
bitmap.close?.();
|
|
520
|
-
throw fail('too-big');
|
|
521
|
-
}
|
|
Binary file
|