@eliceio/cdk-cli 1.2.1 → 1.3.0-contenttypes.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +59 -50
  2. package/es/cli.js +11 -2
  3. package/es/commands/build/index.js +12 -0
  4. package/es/commands/create/index.js +1 -0
  5. package/es/commands/create/scaffold.d.ts +2 -2
  6. package/es/commands/create/scaffold.js +3 -3
  7. package/es/commands/dev/index.d.ts +10 -1
  8. package/es/commands/dev/index.js +47 -7
  9. package/es/core/config.d.ts +20 -9
  10. package/es/core/config.js +53 -12
  11. package/es/core/project-check.d.ts +3 -2
  12. package/es/core/project-check.js +14 -3
  13. package/es/core/regex.d.ts +11 -0
  14. package/es/core/regex.js +41 -0
  15. package/es/core/sandbox.d.ts +26 -0
  16. package/es/core/sandbox.js +240 -30
  17. package/es/dev/check.d.ts +30 -0
  18. package/es/dev/check.js +224 -34
  19. package/es/dev/grading.d.ts +20 -1
  20. package/es/dev/grading.js +38 -7
  21. package/es/dev/host-page.js +1 -1
  22. package/es/dev/mock-api.d.ts +3 -1
  23. package/es/dev/mock-api.js +20 -11
  24. package/es/engines/vite/index.js +1 -1
  25. package/es/engines/vite/plugin.d.ts +2 -0
  26. package/es/engines/vite/plugin.js +33 -5
  27. package/es/rules/answers.d.ts +13 -0
  28. package/es/rules/answers.js +94 -0
  29. package/es/rules/check.js +70 -1
  30. package/es/rules/index.d.ts +1 -0
  31. package/es/rules/index.js +1 -0
  32. package/es/rules/size.d.ts +31 -0
  33. package/es/rules/size.js +58 -0
  34. package/es/rules/types.d.ts +12 -0
  35. package/es/rules.json.js +2 -2
  36. package/package.json +2 -2
  37. package/rules.json +32 -3
  38. package/skills/_shared/always.md +3 -3
  39. package/skills/_shared/references/00-what-the-person-decides.md +1 -1
  40. package/skills/_shared/references/02-design-the-material.md +10 -7
  41. package/skills/_shared/references/03-create-the-project.md +2 -1
  42. package/skills/_shared/references/05-screen-code.md +49 -22
  43. package/skills/_shared/references/06-using-the-quiz-template.md +7 -6
  44. package/skills/_shared/references/08-fix-check-errors.md +23 -22
  45. package/skills/_shared/references/09-check.md +7 -6
  46. package/skills/_shared/references/12-upload-with-the-material-mcp.md +13 -13
  47. package/skills/_shared/references/13-edit-screen-design.md +122 -0
  48. package/skills/_shared/references/14-layouts.md +96 -0
  49. package/skills/elice-content-check/SKILL.md +2 -2
  50. package/skills/elice-content-create/SKILL.md +1 -1
  51. package/skills/elice-content-migrate/SKILL.md +1 -1
  52. package/templates/_shared/lib/cdk-mock.d.ts +30 -3
  53. package/templates/_shared/lib/cdk-mock.js +88 -15
  54. package/templates/_shared/lib/elice-content-editor.js +89 -58
  55. package/templates/_shared/lib/elice-content.css +1313 -126
  56. package/templates/_shared/lib/elice-content.d.ts +162 -23
  57. package/templates/_shared/lib/elice-content.js +863 -82
  58. package/templates/_shared/lib/icons/empty-content.d.ts +2 -0
  59. package/templates/_shared/lib/icons/empty-content.js +11 -0
  60. package/templates/_shared/lib/icons/file-video.d.ts +2 -0
  61. package/templates/_shared/lib/icons/file-video.js +11 -0
  62. package/templates/_shared/lib/icons/file.d.ts +2 -0
  63. package/templates/_shared/lib/icons/file.js +11 -0
  64. package/templates/blank/README.md +5 -3
  65. package/templates/blank/edit.html +8 -2
  66. package/templates/blank/index.html +6 -1
  67. package/templates/blank/instructor.html +6 -1
  68. package/templates/blank/template.json +1 -1
  69. package/templates/quiz/README.md +28 -12
  70. package/templates/quiz/core/behaviors.d.ts +13 -7
  71. package/templates/quiz/core/behaviors.js +36 -51
  72. package/templates/quiz/core/editor.d.ts +10 -0
  73. package/templates/quiz/core/editor.js +334 -8
  74. package/templates/quiz/core/markdown.d.ts +4 -0
  75. package/templates/quiz/core/markdown.js +65 -11
  76. package/templates/quiz/core/model.d.ts +34 -1
  77. package/templates/quiz/core/model.js +86 -5
  78. package/templates/quiz/core/rich-text.d.ts +19 -0
  79. package/templates/quiz/core/rich-text.js +521 -0
  80. package/templates/quiz/edit.html +12 -3
  81. package/templates/quiz/index.html +12 -3
  82. package/templates/quiz/screens/edit.js +217 -48
  83. package/templates/quiz/screens/learn.js +90 -14
  84. package/templates/quiz/styles.css +840 -678
  85. package/templates/quiz/template.json +9 -2
  86. package/templates/quiz/ui/templates/edit.d.ts +18 -5
  87. package/templates/quiz/ui/templates/edit.js +309 -71
  88. package/templates/quiz/ui/templates/group.js +19 -8
  89. package/templates/quiz/ui/templates/order.js +25 -24
  90. package/templates/quiz/ui/templates/page.js +19 -8
  91. package/templates/quiz/ui/templates/question.js +2 -2
  92. package/templates/quiz/ui/texts.js +72 -25
  93. package/templates/quiz/ui/theme.css +8 -9
  94. package/templates/steps/README.md +77 -0
  95. package/templates/steps/commentary.txt +7 -0
  96. package/templates/steps/edit.html +21 -0
  97. package/templates/steps/gitignore +4 -0
  98. package/templates/steps/index.html +69 -0
  99. package/templates/steps/metadata.json +9 -0
  100. package/templates/steps/package.json +13 -0
  101. package/templates/steps/screens/edit.js +32 -0
  102. package/templates/steps/screens/learn.js +108 -0
  103. package/templates/steps/styles.css +54 -0
  104. package/templates/steps/template.json +6 -0
@@ -1,13 +1,17 @@
1
1
  // 퀴즈 데이터 모델. 학생 · 교육자 · 편집 화면이 같이 씁니다. (기존 퀴즈 material 명세: docs/quiz-spec.md)
2
2
  //
3
3
  // 편집 화면이 저장하는 settings (학생에게 공개, 정답 없음)
4
- // { title, description, questions: [{ id, type, title, description?, options?, groups?, slots?,
4
+ // { questions: [{ id, type, title, description?, options?, groups?, slots?,
5
5
  // shuffle?, placeholder?, explanation: { enabled, text } }] }
6
+ // 퀴즈 제목 · 안내(title · description)는 지금 화면이 쓰지 않는다. 예전에 저장한 값은 지우지 않고 그대로 둔다
6
7
  // 문항 description은 편집 화면에서 적을 때만 생긴다 (새 문항에는 키가 없음)
7
8
  // 제출하는 답: 문자열 하나 (ADR 0008). 문항 순서대로 `문항id=답`을 `;`로 잇고, 주관식 답은 encodeURIComponent
8
9
  // "q1=b;q2=a,d;q3=c,a,b;q4=%EA%B0%80%EC%A4%91%EC%B9%98;q5=g1:a|g2:b,c"
9
- // 퀴즈는 채점 방식 pattern 고정 (ADR 0009, 완료 정책은 LXP 설정, ADR 0012). 정답(settings.grading)은 편집 화면이 문항마다 고른 답으로
10
- // 만든 정규식 하나: { type: 'pattern', answer_key: '^q1=b;…$' }
10
+ // 채점 방식은 둘 중 하나 (작성자가 고름, 완료 정책은 LXP 설정, ADR 0012). 정답(settings.grading)은 편집 화면이 문항마다 고른 답으로 만든다.
11
+ // - pattern (기본, 모두 맞혀야 100점): 정규식 하나 { type: 'pattern', answer_key: '^q1=b;…$' }, 답은 위 문자열 하나
12
+ // - partial_pattern (문항별 부분 점수): 문항마다 정규식 { type: 'partial_pattern', answer_key: ['^q1=b$', …], scores: [50, …] },
13
+ // 답은 문항 순서대로 문자열 배열 ["q1=b", "q2=a,d", …] (한 항목의 모양은 pattern 답 · 정답의 한 조각과 같음).
14
+ // 학생 화면은 grading을 받지 못하므로 settings에 공개 값 gradingType: 'partial_pattern'을 같이 둔다 (없으면 pattern)
11
15
 
12
16
  // 화면에 보이는 문구는 여기 두지 않습니다 (ui/texts.js). 문구가 필요한 함수는 화면(screens/)이 문구를 넘겨 줍니다.
13
17
 
@@ -19,8 +23,11 @@ export const LIMITS = {
19
23
  optionsMax: 20,
20
24
  groupsMin: 2,
21
25
  groupsMax: 6,
22
- // 여러 문항 퀴즈: 문항 20개까지. 모든 문항을 맞혀야 100점 (부분 점수 없음)
26
+ // 여러 문항 퀴즈: 문항 20개까지. pattern은 모든 문항을 맞혀야 100점, partial_pattern은 맞은 문항 점수의 합
23
27
  questionsMax: 20,
28
+ // 편집 화면에서 올린 그림 (지문 · 해설): 하나는 data: 주소 40만 자까지 줄이고, 모두 합쳐 270만 자(약 2MB)까지 내용 images에
29
+ imageChars: 400_000,
30
+ imagesTotalChars: 2_700_000,
24
31
  };
25
32
 
26
33
  /** 편집 화면에서 문항을 더 넣을 수 있는지. 이미 여러 문항으로 저장된 퀴즈도 그대로 보이고 저장되며, 더 넣는 것만 막는다 */
@@ -93,7 +100,6 @@ export function convertType(q, type, names) {
93
100
  * @param {object} v 검증 문구 (ui/texts.js의 validation)
94
101
  */
95
102
  export function validateQuiz(content, v) {
96
- if (!content.title?.trim()) return { questionIndex: -1, message: v.quizTitle };
97
103
  if (!content.questions?.length) return { questionIndex: -1, message: v.noQuestions };
98
104
  for (const [i, q] of content.questions.entries()) {
99
105
  const at = (message) => ({ questionIndex: i, message: v.at(i + 1, message) });
@@ -185,6 +191,9 @@ export function joinAnswers(questions, values) {
185
191
  * `;`로 나누고 첫 `=`에서 문항 id와 답을 나눈 뒤, 주관식은 decodeURIComponent
186
192
  */
187
193
  export function splitAnswers(questions, answer) {
194
+ // partial_pattern 답: 문항별 문자열 배열 → 한 문자열로 이어 같은 방식으로 푼다
195
+ if (Array.isArray(answer))
196
+ return splitAnswers(questions, answer.filter((a) => typeof a === 'string').join(';'));
188
197
  if (answer && typeof answer === 'object') return { ...(answer.answers ?? {}) };
189
198
  if (typeof answer !== 'string') return {};
190
199
  const byId = Object.fromEntries(questions.map((q) => [q.id, q]));
@@ -260,6 +269,78 @@ export function parseAnswerKey(questions, regex) {
260
269
  return out;
261
270
  }
262
271
 
272
+ // ---------- 문항별 부분 점수 (partial_pattern) ----------
273
+
274
+ export const PARTIAL = 'partial_pattern';
275
+
276
+ /** 채점 방식: 저장된 settings.grading.type, 없으면 학생 화면에도 보이는 settings.gradingType, 둘 다 없으면 pattern */
277
+ export function gradingTypeOf(content, grading) {
278
+ if (grading?.type === PARTIAL || grading?.type === 'pattern') return grading.type;
279
+ return content?.gradingType === PARTIAL ? PARTIAL : 'pattern';
280
+ }
281
+
282
+ /** 문항별 답 → 제출할 문자열 배열 (문항 순서). 한 항목은 pattern 답의 한 조각과 같은 `문항id=답` */
283
+ export function joinAnswerList(questions, values) {
284
+ return questions.map((q, i) => joinAnswers([q], [values[i]]));
285
+ }
286
+
287
+ /** 문항별 정답 → 문항마다 정답 정규식 `^문항id=…$` (buildAnswerKey를 문항 하나씩) */
288
+ export function buildAnswerKeys(questions, key) {
289
+ return questions.map((q) => buildAnswerKey([q], key));
290
+ }
291
+
292
+ /** buildAnswerKeys가 만든 정규식 배열 → 문항별 정답(화면 값). 다른 모양이면 null */
293
+ export function parseAnswerKeys(questions, keys) {
294
+ if (!Array.isArray(keys) || keys.length === 0) return null;
295
+ if (keys.some((k) => typeof k !== 'string' || !k.startsWith('^') || !k.endsWith('$'))) return null;
296
+ return parseAnswerKey(questions, `^${keys.map((k) => k.slice(1, -1)).join(';')}$`);
297
+ }
298
+
299
+ /**
300
+ * 정답 검증 2 (문항별): 문항마다 checkAnswerKey (정답으로 낸 답은 맞고, 하나 바꾼 답은 맞지 않음).
301
+ * 문제가 없으면 null, 있으면 { questionIndex, message }
302
+ */
303
+ export function checkAnswerKeys(questions, key, keys, v) {
304
+ for (const [i, q] of questions.entries()) {
305
+ const at = (_no, message) => v.at(i + 1, message);
306
+ const problem = checkAnswerKey([q], key, keys[i], { ...v, at });
307
+ if (!problem) continue;
308
+ if (problem.message === v.badRegex) return { questionIndex: i, message: at(0, v.badRegex) };
309
+ return {
310
+ questionIndex: i,
311
+ message: problem.questionIndex === -1 ? at(0, problem.message) : problem.message,
312
+ };
313
+ }
314
+ return null;
315
+ }
316
+
317
+ /**
318
+ * 저장할 문항별 점수. 저장된 점수는 같은 자리 정규식(answer_key[i] = "^문제id=…")의 문제 것이라, 문제 id로 맞춰 지금 문제 순서로 다시 놓는다
319
+ * (순서를 바꿔도 점수가 제 문제를 따라감). 저장된 문제 id와 지금 문제 id가 하나라도 다르면(더함 · 지움) 똑같이 나눈 점수 (split = 키트 splitScores).
320
+ * resplit: 저장된 점수가 있었는데 맞추지 못해 다시 나눴는지 (화면이 짧게 알림)
321
+ * @param {{ answer_key?: unknown, scores?: unknown } | undefined} saved 저장된 partial_pattern 채점 설정
322
+ * @returns {{ scores: number[], resplit: boolean }}
323
+ */
324
+ export function scoresFor(questions, saved, split) {
325
+ const keys = saved?.answer_key;
326
+ const scores = saved?.scores;
327
+ const had = Array.isArray(scores) && scores.length > 0;
328
+ if (Array.isArray(keys) && Array.isArray(scores) && keys.length === scores.length) {
329
+ const byId = new Map();
330
+ keys.forEach((key, i) => {
331
+ const id = typeof key === 'string' ? /^\^([A-Za-z0-9_-]+)=/.exec(key)?.[1] : undefined;
332
+ if (id) byId.set(id, scores[i]);
333
+ });
334
+ if (
335
+ byId.size === keys.length &&
336
+ byId.size === questions.length &&
337
+ questions.every((q) => byId.has(q.id))
338
+ )
339
+ return { scores: questions.map((q) => byId.get(q.id)), resplit: false };
340
+ }
341
+ return { scores: split(questions.length), resplit: had };
342
+ }
343
+
263
344
  /**
264
345
  * 정답 검증 1: 모든 문항에 정답이 있고, 정답이 지금 있는 보기 · 그룹을 가리키는지.
265
346
  * 문제가 없으면 null, 있으면 { questionIndex, message }
@@ -0,0 +1,19 @@
1
+ export interface RichText {
2
+ el: HTMLElement;
3
+ set(markdown: string): void;
4
+ get(): string;
5
+ focus(atEnd?: boolean): void;
6
+ split(): { before: string; after: string };
7
+ state(): { bold: boolean; italic: boolean; strike: boolean; ul: boolean; ol: boolean; code: boolean };
8
+ bold(): void;
9
+ italic(): void;
10
+ strike(): void;
11
+ list(tag?: 'ul' | 'ol'): void;
12
+ code(sample: string): void;
13
+ }
14
+ export type Block = { type: 'text'; text: string } | { type: 'image'; alt: string; id: string };
15
+ export declare function toMarkdown(root: Node): string;
16
+ export declare function richText(el: HTMLElement, opts: { onChange: (markdown: string) => void }): RichText;
17
+ export declare function splitBlocks(source: string): Block[];
18
+ export declare function joinBlocks(items: Block[]): string;
19
+ export declare function compressImage(file: File, maxChars: number): Promise<string>;
@@ -0,0 +1,521 @@
1
+ // 지문 · 해설 편집 칸: 보이는 그대로 고치는 글 칸(contenteditable)과 마크다운 사이를 오간다 (연주님 최종 수정본).
2
+ // 저장하는 값은 늘 마크다운이라 학생 화면(core/markdown.js)이 그대로 읽는다. 붙여 넣기는 글자만 받는다.
3
+ // 서식: 굵게 · 기울임 · 취소선 · 글머리 · 번호 목록 · 코드(한 문단 안은 `코드`, 여러 문단을 고르면 코드 블록)
4
+ import { lineNumbers, markdown } from './markdown.js';
5
+
6
+ // 서식은 브라우저 편집 명령으로 (없는 환경에서는 아무 일도 하지 않음)
7
+ const command = (...args) => document.execCommand?.(...args);
8
+ const commandState = (name) => Boolean(document.queryCommandState?.(name));
9
+
10
+ const BLOCK_TAGS = new Set([
11
+ 'P',
12
+ 'DIV',
13
+ 'UL',
14
+ 'OL',
15
+ 'LI',
16
+ 'PRE',
17
+ 'BLOCKQUOTE',
18
+ 'H1',
19
+ 'H2',
20
+ 'H3',
21
+ 'H4',
22
+ 'H5',
23
+ 'H6',
24
+ ]);
25
+ const isBlock = (node) => node.nodeType === 1 && BLOCK_TAGS.has(node.tagName);
26
+ // 글 속 서식 기호는 \로 막아 마크다운으로 읽히지 않게 (코드 안은 \ · `만)
27
+ const escapeText = (s) => s.replace(/ /g, ' ').replace(/[\\*`[\]~]/g, '\\$&');
28
+ const escapeCode = (s) => s.replace(/ /g, ' ').replace(/[\\`]/g, '\\$&');
29
+ const wrap = (s, mark) => (s.trim() === '' ? s : `${mark}${s}${mark}`);
30
+
31
+ /** 한 문단 안의 글과 서식을 마크다운으로 */
32
+ function inlineMarkdown(node, inCode = false) {
33
+ let out = '';
34
+ for (const child of node.childNodes) {
35
+ if (child.nodeType === 3) {
36
+ out += inCode ? escapeCode(child.data) : escapeText(child.data);
37
+ continue;
38
+ }
39
+ if (child.nodeType !== 1) continue;
40
+ const tag = child.tagName;
41
+ if (tag === 'BR') {
42
+ out += '\n';
43
+ continue;
44
+ }
45
+ if (tag === 'IMG') {
46
+ // zip 안 그림(img/…)만 글 속에 남는다. 올린 그림은 칸 사이 그림 칸(블록)으로 따로 둔다
47
+ const src = child.getAttribute('src') ?? '';
48
+ if (/^img\//.test(src))
49
+ out += `![${(child.getAttribute('alt') ?? '').replace(/[[\]]/g, '')}](${src})`;
50
+ continue;
51
+ }
52
+ const inner = inlineMarkdown(child, inCode || tag === 'CODE');
53
+ if (!inner) continue;
54
+ if (inCode) out += inner;
55
+ else if (tag === 'STRONG' || tag === 'B') out += wrap(inner, '**');
56
+ else if (tag === 'EM' || tag === 'I') out += wrap(inner, '*');
57
+ else if (tag === 'DEL' || tag === 'S' || tag === 'STRIKE') out += wrap(inner, '~~');
58
+ else if (tag === 'CODE') out += inner.trim() === '' ? inner : `\`${inner}\``;
59
+ else if (tag === 'A') {
60
+ const href = child.getAttribute('href') ?? '';
61
+ out += /^https?:\/\//.test(href) ? `[${inner}](${href})` : inner;
62
+ } else out += inner;
63
+ }
64
+ return out;
65
+ }
66
+
67
+ /** 문단 첫머리의 # · - · 1. 은 제목 · 목록으로 읽히지 않게 막는다 */
68
+ const paragraph = (s) =>
69
+ s
70
+ .split('\n')
71
+ .map((line) =>
72
+ line
73
+ .replace(/^(\s*)(#{1,3})(\s)/, '$1\\$2$3')
74
+ .replace(/^(\s*)-(\s)/, '$1\\-$2')
75
+ .replace(/^(\s*)(\d+)\.(\s)/, '$1$2\\.$3'),
76
+ )
77
+ .join('\n')
78
+ .replace(/^\n+|\n+$/g, '')
79
+ .trim();
80
+
81
+ /** 서식 없이 글만 (코드 블록) */
82
+ function plainText(node) {
83
+ let out = '';
84
+ const walk = (n) => {
85
+ for (const child of n.childNodes) {
86
+ if (child.nodeType === 3) out += child.data.replace(/ /g, ' ');
87
+ else if (child.tagName === 'BR') out += '\n';
88
+ else walk(child);
89
+ }
90
+ };
91
+ walk(node);
92
+ return out.replace(/\n+$/, '');
93
+ }
94
+
95
+ /** 칸 안의 문단들을 마크다운 덩어리로 */
96
+ function blocks(root) {
97
+ const out = [];
98
+ let loose = [];
99
+ const flush = () => {
100
+ if (!loose.length) return;
101
+ const box = document.createElement('div');
102
+ for (const n of loose) box.append(n.cloneNode(true));
103
+ const text = paragraph(inlineMarkdown(box));
104
+ if (text) out.push(text);
105
+ loose = [];
106
+ };
107
+ for (const node of root.childNodes) {
108
+ if (node.nodeType === 3 || (node.nodeType === 1 && !isBlock(node))) {
109
+ loose.push(node);
110
+ continue;
111
+ }
112
+ flush();
113
+ if (node.nodeType !== 1) continue;
114
+ const tag = node.tagName;
115
+ if (tag === 'UL' || tag === 'OL') {
116
+ const items = [...node.children]
117
+ .filter((li) => li.tagName === 'LI')
118
+ .map((li, i) => [
119
+ tag === 'UL' ? '- ' : `${i + 1}. `,
120
+ inlineMarkdown(li).replace(/\n+/g, ' ').trim(),
121
+ ])
122
+ .filter(([, text]) => text)
123
+ .map(([mark, text]) => mark + text);
124
+ if (items.length) out.push(items.join('\n'));
125
+ } else if (tag === 'PRE') {
126
+ const code = plainText(node);
127
+ if (code.trim()) out.push(`\`\`\`\n${code}\n\`\`\``);
128
+ } else if (/^H[1-6]$/.test(tag)) {
129
+ const text = inlineMarkdown(node).replace(/\n+/g, ' ').trim();
130
+ if (text) out.push(`${'#'.repeat(Math.min(3, Math.max(1, Number(tag[1]) - 2)))} ${text}`);
131
+ } else if (node.querySelector('p, div, ul, ol, pre, h1, h2, h3, h4, h5, h6')) {
132
+ out.push(...blocks(node));
133
+ } else {
134
+ const text = paragraph(inlineMarkdown(node));
135
+ if (text) out.push(text);
136
+ }
137
+ }
138
+ flush();
139
+ return out;
140
+ }
141
+
142
+ /** 글 칸(또는 그 일부)을 마크다운으로 */
143
+ export const toMarkdown = (root) => blocks(root).join('\n\n');
144
+
145
+ const LAST_BLOCK = /^(PRE|UL|OL|H[1-6])$/;
146
+ const emptyParagraph = () => {
147
+ const p = document.createElement('p');
148
+ p.append(document.createElement('br'));
149
+ return p;
150
+ };
151
+ /** 마지막이 목록 · 코드 블록이면 뒤에 빈 문단을 두어 그 밖으로 이어 쓸 수 있게 */
152
+ function keepTrailingParagraph(root) {
153
+ const last = root.lastElementChild;
154
+ if (!last || LAST_BLOCK.test(last.tagName)) root.append(emptyParagraph());
155
+ }
156
+ /** 커서를 요소 처음(false) · 끝(true)으로 */
157
+ function caretAt(node, atEnd) {
158
+ const range = document.createRange();
159
+ range.selectNodeContents(node);
160
+ range.collapse(!atEnd);
161
+ const selection = getSelection();
162
+ selection.removeAllRanges();
163
+ selection.addRange(range);
164
+ }
165
+
166
+ /**
167
+ * 글 칸 하나를 보이는 그대로 고치는 칸으로. 고칠 때마다 onChange(마크다운)
168
+ * @param {HTMLElement} el contenteditable 요소
169
+ * @param {{ onChange: (markdown: string) => void }} opts
170
+ */
171
+ export function richText(el, { onChange }) {
172
+ let saved = null;
173
+ const remember = () => {
174
+ const selection = getSelection();
175
+ if (selection.rangeCount && el.contains(selection.anchorNode))
176
+ saved = selection.getRangeAt(0).cloneRange();
177
+ };
178
+ /** 서식 버튼을 누를 때 칸의 선택 범위 (초점이 버튼에 가 있었으면 마지막 선택을 되살림) */
179
+ const range = () => {
180
+ el.focus();
181
+ const selection = getSelection();
182
+ if (selection.rangeCount && el.contains(selection.anchorNode)) return selection.getRangeAt(0);
183
+ if (saved && el.contains(saved.startContainer)) {
184
+ selection.removeAllRanges();
185
+ selection.addRange(saved);
186
+ return saved;
187
+ }
188
+ caretAt(el, true);
189
+ return selection.getRangeAt(0);
190
+ };
191
+ /** 칸 바로 아래 문단 */
192
+ const topBlock = (node) => {
193
+ let n = node;
194
+ while (n && n.parentNode !== el) n = n.parentNode;
195
+ return n && n !== el ? n : null;
196
+ };
197
+ const closest = (node, tag) => {
198
+ for (let n = node; n && n !== el; n = n.parentNode) if (n.tagName === tag) return n;
199
+ return null;
200
+ };
201
+ const markLines = () => {
202
+ for (const pre of el.querySelectorAll('pre')) {
203
+ const count = plainText(pre).split('\n').length;
204
+ if (count >= 3) {
205
+ pre.classList.add('qz-lines');
206
+ pre.dataset.lines = lineNumbers(count);
207
+ } else {
208
+ pre.classList.remove('qz-lines');
209
+ delete pre.dataset.lines;
210
+ }
211
+ }
212
+ };
213
+ const markEmpty = () => el.toggleAttribute('data-empty', toMarkdown(el) === '');
214
+ const changed = () => {
215
+ markLines();
216
+ markEmpty();
217
+ onChange(toMarkdown(el));
218
+ };
219
+ const tidy = () => {
220
+ if (!el.childNodes.length || (el.childNodes.length === 1 && el.firstChild.nodeName === 'BR')) {
221
+ el.replaceChildren(emptyParagraph());
222
+ caretAt(el, false);
223
+ }
224
+ keepTrailingParagraph(el);
225
+ };
226
+
227
+ el.addEventListener('input', () => {
228
+ tidy();
229
+ changed();
230
+ remember();
231
+ });
232
+ for (const type of ['keyup', 'mouseup', 'touchend', 'focusout'])
233
+ el.addEventListener(type, remember);
234
+ el.addEventListener('paste', (e) => {
235
+ e.preventDefault();
236
+ command('insertText', false, e.clipboardData?.getData('text/plain') ?? '');
237
+ });
238
+ // 코드 블록 안에서 Enter는 블록을 끝내지 않고 줄만 바꾼다
239
+ el.addEventListener('keydown', (e) => {
240
+ if (e.key !== 'Enter' || e.shiftKey || e.isComposing) return;
241
+ const selection = getSelection();
242
+ if (selection.rangeCount && closest(selection.anchorNode, 'PRE')) {
243
+ e.preventDefault();
244
+ command('insertLineBreak');
245
+ }
246
+ });
247
+
248
+ const textOf = (node) => {
249
+ let out = '';
250
+ for (const child of node.childNodes)
251
+ out += child.nodeType === 3 ? child.data : child.tagName === 'BR' ? '\n' : textOf(child);
252
+ return out.replace(/ /g, ' ');
253
+ };
254
+ /** 코드 블록을 줄마다 문단으로 */
255
+ const unwrapPre = (pre) => {
256
+ const fragment = document.createDocumentFragment();
257
+ for (const line of plainText(pre).split('\n')) {
258
+ const p = document.createElement('p');
259
+ if (line) p.textContent = line;
260
+ else p.append(document.createElement('br'));
261
+ fragment.append(p);
262
+ }
263
+ pre.replaceWith(fragment);
264
+ };
265
+ /** first부터 last까지 문단을 코드 블록 하나로 */
266
+ const wrapPre = (first, last) => {
267
+ const nodes = [];
268
+ for (let n = first; n; n = n.nextSibling) {
269
+ nodes.push(n);
270
+ if (n === last) break;
271
+ }
272
+ const lines = nodes.flatMap((n) =>
273
+ n.tagName === 'UL' || n.tagName === 'OL'
274
+ ? [...n.children].map((li) => li.textContent)
275
+ : n.tagName === 'PRE'
276
+ ? plainText(n).split('\n')
277
+ : textOf(n).split('\n'),
278
+ );
279
+ const pre = document.createElement('pre');
280
+ const code = document.createElement('code');
281
+ code.textContent = lines.join('\n');
282
+ pre.append(code);
283
+ first.before(pre);
284
+ for (const n of nodes) n.remove();
285
+ caretAt(code, true);
286
+ };
287
+
288
+ const editor = {
289
+ el,
290
+ set(value) {
291
+ el.replaceChildren(...markdown(value ?? '').childNodes);
292
+ keepTrailingParagraph(el);
293
+ markLines();
294
+ markEmpty();
295
+ },
296
+ get: () => toMarkdown(el),
297
+ focus(atEnd = false) {
298
+ el.focus();
299
+ caretAt(el, atEnd);
300
+ },
301
+ /** 커서 앞 · 뒤 글 (그 자리에 그림을 넣을 때) */
302
+ split() {
303
+ const at = range();
304
+ const before = document.createRange();
305
+ before.selectNodeContents(el);
306
+ before.setEnd(at.startContainer, at.startOffset);
307
+ const after = document.createRange();
308
+ after.selectNodeContents(el);
309
+ after.setStart(at.endContainer, at.endOffset);
310
+ return {
311
+ before: toMarkdown(before.cloneContents()),
312
+ after: toMarkdown(after.cloneContents()),
313
+ };
314
+ },
315
+ /** 서식 버튼 눌림 표시 */
316
+ state() {
317
+ const selection = getSelection();
318
+ const inside = selection.rangeCount && el.contains(selection.anchorNode);
319
+ return {
320
+ bold: inside && commandState('bold'),
321
+ italic: inside && commandState('italic'),
322
+ strike: inside && commandState('strikeThrough'),
323
+ ul: inside && Boolean(closest(selection.anchorNode, 'UL')),
324
+ ol: inside && Boolean(closest(selection.anchorNode, 'OL')),
325
+ code:
326
+ inside &&
327
+ Boolean(closest(selection.anchorNode, 'CODE') || closest(selection.anchorNode, 'PRE')),
328
+ };
329
+ },
330
+ bold() {
331
+ range();
332
+ if (!editor.state().code) command('bold');
333
+ },
334
+ italic() {
335
+ range();
336
+ if (!editor.state().code) command('italic');
337
+ },
338
+ strike() {
339
+ range();
340
+ if (!editor.state().code) command('strikeThrough');
341
+ },
342
+ /** 고른 문단을 목록으로 · 같은 목록이면 문단으로 · 다른 목록이면 종류만 바꿈 */
343
+ list(tag = 'ul') {
344
+ const at = range();
345
+ if (editor.state().code) return;
346
+ const first = topBlock(at.startContainer);
347
+ const last = topBlock(at.endContainer);
348
+ if (!first || !last) return;
349
+ const selection = getSelection();
350
+ const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;
351
+ const isList = (n) => n.tagName === 'UL' || n.tagName === 'OL';
352
+ let caret;
353
+ if (isList(first) && first === last && first.tagName !== tag.toUpperCase()) {
354
+ const next = document.createElement(tag);
355
+ next.append(...first.childNodes);
356
+ first.replaceWith(next);
357
+ caret = next.lastElementChild;
358
+ } else if (isList(first) && first === last) {
359
+ const fragment = document.createDocumentFragment();
360
+ for (const li of first.children) {
361
+ const p = document.createElement('p');
362
+ p.append(...li.childNodes);
363
+ if (!p.childNodes.length) p.append(document.createElement('br'));
364
+ fragment.append(p);
365
+ caret = p;
366
+ }
367
+ first.replaceWith(fragment);
368
+ } else {
369
+ const nodes = [];
370
+ for (let n = first; n; n = n.nextSibling) {
371
+ nodes.push(n);
372
+ if (n === last) break;
373
+ }
374
+ const list = document.createElement(tag);
375
+ for (const n of nodes) {
376
+ if (isList(n)) list.append(...n.children);
377
+ else if (n.tagName === 'PRE') {
378
+ const li = document.createElement('li');
379
+ li.textContent = plainText(n);
380
+ list.append(li);
381
+ } else {
382
+ const li = document.createElement('li');
383
+ li.append(...n.childNodes);
384
+ if (!li.childNodes.length) li.append(document.createElement('br'));
385
+ list.append(li);
386
+ }
387
+ }
388
+ first.before(list);
389
+ for (const n of nodes) n.remove();
390
+ caret = list.lastElementChild;
391
+ }
392
+ if (anchorNode && focusNode && el.contains(anchorNode) && el.contains(focusNode))
393
+ selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
394
+ else if (caret) caretAt(caret, true);
395
+ tidy();
396
+ changed();
397
+ remember();
398
+ },
399
+ /** 코드: 코드 블록 안이면 풀고, 여러 문단을 골랐으면 코드 블록, 아니면 `코드` 켜고 끄기 (빈 커서면 sample을 넣음) */
400
+ code(sample) {
401
+ const at = range();
402
+ const pre = closest(at.startContainer, 'PRE');
403
+ if (pre) unwrapPre(pre);
404
+ else {
405
+ const first = topBlock(at.startContainer);
406
+ const last = topBlock(at.endContainer);
407
+ if (first && last && first !== last) wrapPre(first, last);
408
+ else {
409
+ const start = closest(at.startContainer, 'CODE');
410
+ const end = closest(at.endContainer, 'CODE');
411
+ if (start && (at.collapsed || start === end)) start.replaceWith(...start.childNodes);
412
+ else {
413
+ if (start) at.setStartBefore(start);
414
+ if (end) at.setEndAfter(end);
415
+ const code = document.createElement('code');
416
+ if (at.collapsed) code.textContent = sample;
417
+ else code.append(at.extractContents());
418
+ for (const inner of code.querySelectorAll('code, b, strong, i, em, s, del, strike'))
419
+ inner.replaceWith(...inner.childNodes);
420
+ at.insertNode(code);
421
+ const selection = getSelection();
422
+ selection.removeAllRanges();
423
+ const picked = document.createRange();
424
+ picked.selectNodeContents(code);
425
+ selection.addRange(picked);
426
+ }
427
+ }
428
+ }
429
+ tidy();
430
+ changed();
431
+ remember();
432
+ },
433
+ };
434
+ // Enter로 새 문단을 <p>로 (브라우저 기본 <div> 대신)
435
+ command('defaultParagraphSeparator', false, 'p');
436
+ return editor;
437
+ }
438
+
439
+ const IMAGE_LINE = /^!\[([^\]]*)\]\(image:([\w-]+)\)$/;
440
+ /**
441
+ * 마크다운을 글 칸 · 그림 칸 차례로 나눈다 (한 줄을 차지하는 올린 그림 ![설명](image:아이디)만 그림 칸)
442
+ * @returns {({ type: 'text', text: string } | { type: 'image', alt: string, id: string })[]}
443
+ */
444
+ export function splitBlocks(source) {
445
+ const out = [];
446
+ let lines = [];
447
+ const flush = () => {
448
+ out.push({ type: 'text', text: lines.join('\n').replace(/^\n+|\n+$/g, '') });
449
+ lines = [];
450
+ };
451
+ for (const line of String(source ?? '').split('\n')) {
452
+ const image = IMAGE_LINE.exec(line.trim());
453
+ if (image) {
454
+ flush();
455
+ out.push({ type: 'image', alt: image[1], id: image[2] });
456
+ } else lines.push(line);
457
+ }
458
+ flush();
459
+ return out;
460
+ }
461
+
462
+ /** splitBlocks의 반대 (빈 글 칸은 뺀다) */
463
+ export const joinBlocks = (items) =>
464
+ items
465
+ .map((b) =>
466
+ b.type === 'image' ? `![${b.alt}](image:${b.id})` : b.text.replace(/^\n+|\n+$/g, ''),
467
+ )
468
+ .filter((s) => s !== '')
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
+ }