@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.
Files changed (113) hide show
  1. package/README.md +24 -23
  2. package/es/cli.js +1 -1
  3. package/es/commands/create/index.js +1 -0
  4. package/es/commands/create/scaffold.d.ts +1 -1
  5. package/es/commands/create/scaffold.js +1 -1
  6. package/es/commands/doctor/index.js +6 -2
  7. package/es/core/config.d.ts +22 -0
  8. package/es/core/config.js +165 -1
  9. package/es/dev/assets.d.ts +80 -0
  10. package/es/dev/assets.js +240 -0
  11. package/es/dev/grading.d.ts +42 -26
  12. package/es/dev/grading.js +88 -39
  13. package/es/dev/host-page.js +26 -2
  14. package/es/dev/inject.d.ts +2 -1
  15. package/es/dev/inject.js +10 -2
  16. package/es/dev/mock-api.d.ts +23 -2
  17. package/es/dev/mock-api.js +210 -40
  18. package/es/dev/server.d.ts +12 -1
  19. package/es/dev/server.js +115 -9
  20. package/es/rules.json.js +1 -1
  21. package/package.json +2 -2
  22. package/rules.json +3 -3
  23. package/skills/_shared/references/02-design-the-material.md +1 -1
  24. package/skills/_shared/references/03-create-the-project.md +9 -8
  25. package/skills/_shared/references/04-rules.md +1 -1
  26. package/skills/_shared/references/05-screen-code.md +22 -20
  27. package/skills/_shared/references/06-using-the-quiz-template.md +6 -4
  28. package/skills/_shared/references/08-fix-check-errors.md +1 -1
  29. package/skills/_shared/references/09-check.md +1 -0
  30. package/skills/_shared/references/12-upload-with-the-material-mcp.md +1 -1
  31. package/skills/elice-content-publish/SKILL.md +1 -1
  32. package/templates/_shared/lib/cdk-mock.d.ts +17 -0
  33. package/templates/_shared/lib/cdk-mock.js +212 -7
  34. package/templates/_shared/lib/elice-content.d.ts +61 -1
  35. package/templates/_shared/lib/elice-content.js +317 -10
  36. package/templates/blank/README.md +1 -1
  37. package/templates/blank/screens/instructor.js +8 -2
  38. package/templates/blank/screens/learn.js +1 -1
  39. package/templates/blank/template.json +1 -1
  40. package/templates/document/README.md +92 -0
  41. package/templates/document/commentary.txt +2 -0
  42. package/templates/document/core/dom.d.ts +13 -0
  43. package/templates/document/core/dom.js +83 -0
  44. package/templates/document/core/file-type.d.ts +21 -0
  45. package/templates/document/core/file-type.js +85 -0
  46. package/templates/document/core/group-3d.d.ts +20 -0
  47. package/templates/document/core/group-3d.js +256 -0
  48. package/templates/document/core/inline-edit.d.ts +15 -0
  49. package/templates/document/core/inline-edit.js +377 -0
  50. package/templates/document/core/load.d.ts +13 -0
  51. package/templates/document/core/load.js +40 -0
  52. package/templates/document/core/pdf-options.d.ts +9 -0
  53. package/templates/document/core/pdf-options.js +36 -0
  54. package/templates/document/core/pdf-worker.d.ts +24 -0
  55. package/templates/document/core/pdf-worker.js +122 -0
  56. package/templates/document/core/pdf.d.ts +12 -0
  57. package/templates/document/core/pdf.js +190 -0
  58. package/templates/document/core/pptx-edit.d.ts +14 -0
  59. package/templates/document/core/pptx-edit.js +137 -0
  60. package/templates/document/core/pptx-fonts.d.ts +5 -0
  61. package/templates/document/core/pptx-fonts.js +115 -0
  62. package/templates/document/core/pptx-media.d.ts +18 -0
  63. package/templates/document/core/pptx-media.js +83 -0
  64. package/templates/document/core/pptx-view.d.ts +5 -0
  65. package/templates/document/core/pptx-view.js +185 -0
  66. package/templates/document/core/settings.d.ts +25 -0
  67. package/templates/document/core/settings.js +86 -0
  68. package/templates/document/core/slide-edges.d.ts +3 -0
  69. package/templates/document/core/slide-edges.js +82 -0
  70. package/templates/document/core/viewer.d.ts +28 -0
  71. package/templates/document/core/viewer.js +159 -0
  72. package/templates/document/edit.html +17 -0
  73. package/templates/document/gitignore +4 -0
  74. package/templates/document/index.html +18 -0
  75. package/templates/document/metadata.json +9 -0
  76. package/templates/document/package.json +17 -0
  77. package/templates/document/public/fonts/OFL-Caladea.txt +93 -0
  78. package/templates/document/public/fonts/OFL-Carlito.txt +93 -0
  79. package/templates/document/public/fonts/caladea-latin-400-normal.woff2 +0 -0
  80. package/templates/document/public/fonts/caladea-latin-700-normal.woff2 +0 -0
  81. package/templates/document/public/fonts/carlito-latin-400-normal.woff2 +0 -0
  82. package/templates/document/public/fonts/carlito-latin-700-normal.woff2 +0 -0
  83. package/templates/document/screens/edit.js +574 -0
  84. package/templates/document/screens/learn.js +61 -0
  85. package/templates/document/styles.css +644 -0
  86. package/templates/document/template.json +13 -0
  87. package/templates/document/ui/templates/edit.js +82 -0
  88. package/templates/document/ui/templates/page.js +11 -0
  89. package/templates/document/ui/templates/viewer.js +41 -0
  90. package/templates/document/ui/texts.d.ts +3 -0
  91. package/templates/document/ui/texts.js +62 -0
  92. package/templates/document/ui/theme.css +69 -0
  93. package/templates/quiz/README.md +16 -12
  94. package/templates/quiz/core/behaviors.d.ts +4 -0
  95. package/templates/quiz/core/behaviors.js +4 -2
  96. package/templates/quiz/core/editor.d.ts +17 -2
  97. package/templates/quiz/core/editor.js +85 -10
  98. package/templates/quiz/core/markdown.d.ts +15 -0
  99. package/templates/quiz/core/markdown.js +164 -4
  100. package/templates/quiz/core/model.d.ts +53 -9
  101. package/templates/quiz/core/model.js +384 -41
  102. package/templates/quiz/core/rich-text.d.ts +1 -2
  103. package/templates/quiz/core/rich-text.js +7 -59
  104. package/templates/quiz/public/img/mascot-half.webp +0 -0
  105. package/templates/quiz/screens/edit.js +403 -126
  106. package/templates/quiz/screens/learn.js +106 -40
  107. package/templates/quiz/styles.css +584 -4
  108. package/templates/quiz/template.json +1 -1
  109. package/templates/quiz/ui/templates/edit.d.ts +3 -0
  110. package/templates/quiz/ui/templates/edit.js +113 -11
  111. package/templates/quiz/ui/templates/page.js +14 -0
  112. package/templates/quiz/ui/templates/question.js +5 -3
  113. package/templates/quiz/ui/texts.js +89 -26
@@ -0,0 +1,377 @@
1
+ // 슬라이드 글자 제자리 고치기 (편집 화면, 고치지 않습니다).
2
+ // @aiden0z/pptx-renderer가 그린 글자 상자를 그대로 contenteditable로 바꿔, 글꼴 · 크기 · 색 · 굵기 · 정렬 · 줄 간격 ·
3
+ // 위치 · 줄바꿈이 슬라이드와 같은 채로 고친다. 고친 글자는 화면 코드가 @office-kit headless로 파일에 넣는다.
4
+ // 쓰는 것은 DOM뿐이라 happy-dom 테스트로 확인한다. 렌더러 마크업에는 class가 없어 모양으로 찾는다:
5
+ // 슬라이드(core/pptx-view.js가 data-dc-slide를 붙임) 안 도형은 left · top · width · height(px, 파일 좌표)를 가진 div,
6
+ // 그 안 글자 상자는 display: flex; flex-direction: column인 div, 문단마다 div > span, 글머리 기호는 문단 첫 span(position: absolute).
7
+ // 그룹은 자식 도형을 담은 div (자식 위치는 그룹 기준). 표는 도형 div > table > tbody > tr > td이고, 병합으로 가려진 칸은 td가 없다.
8
+
9
+ /** 그린 도형 위치(px)와 @office-kit 도형 위치가 이만큼 안이면 같은 도형으로 본다 */
10
+ const MATCH_PX = 2;
11
+
12
+ const px = (el, prop) => Number.parseFloat(el.style[prop]) || 0;
13
+
14
+ /** 렌더러의 글자 상자 (도형 div 바로 안, 문단 div를 세로로 쌓는 flex) */
15
+ const isTextBox = el =>
16
+ el.tagName === 'DIV' && el.style.display === 'flex' && el.style.flexDirection === 'column';
17
+
18
+ /** 도형 div의 슬라이드 기준 위치: 그룹 안 도형은 그룹 기준으로 그려지므로 슬라이드까지 조상들의 위치를 더한다 */
19
+ function slidePosition(el, slide) {
20
+ let left = px(el, 'left');
21
+ let top = px(el, 'top');
22
+ for (let g = el.parentElement; g && g !== slide; g = g.parentElement) {
23
+ left += px(g, 'left');
24
+ top += px(g, 'top');
25
+ }
26
+ return { left, top, width: px(el, 'width') };
27
+ }
28
+
29
+ const squash = t => t.replace(/\s+/g, ' ').trim();
30
+
31
+ /**
32
+ * 그려진 슬라이드에서 글자 도형마다 글자 상자를 찾는다 (위치 · 크기로 짝지음, 좌표는 파일 크기 px).
33
+ * 같은 자리에 도형(바탕 · 동그라미)과 그 위 글자 상자가 겹칠 수 있다 (렌더러는 글자가 없는 도형에는 글자 상자를 그리지 않지만,
34
+ * 빈 문단만 있는 도형 등 빈 상자가 생길 수 있음): 같은 자리 후보 중 글자가 같은 것 → 글자가 있는 것 순으로 고르고,
35
+ * 도형에 글자가 있는데 빈 상자뿐이면 짝짓지 않는다.
36
+ * 그룹 안 도형 위치는 core/pptx-edit.js가 슬라이드 좌표로 옮겨 준다. 그래도 위치로 못 찾으면(그룹 회전 등)
37
+ * 글자 · 폭이 같은 상자가 하나뿐일 때만 그것으로.
38
+ * 표 칸(shape.cell)은 위치가 같은 표에서 cell.row번째 줄의 cell.index번째 td를 글자 상자로 쓴다 (빈 칸도)
39
+ * @param {Element} root 슬라이드를 그린 곳 ([data-dc-slide]가 안에 있음)
40
+ * @param {Array<{ text?: string, box: { x: number, y: number, w: number, h: number }, cell?: { row: number, index: number } }>} shapes 슬라이드 크기에 대한 비율
41
+ * @param {(shape: object) => string} [textOf] 지금 보이는 글자 (고친 뒤 다시 그렸으면 고친 글자, 기본 shape.text)
42
+ * @returns {Array<{ shape: object, element: HTMLElement }>}
43
+ */
44
+ export function findTextBoxes(root, shapes, textOf = shape => shape.text ?? '') {
45
+ const slide = root.querySelector('[data-dc-slide]');
46
+ if (!slide) return [];
47
+ const width = px(slide, 'width');
48
+ const height = px(slide, 'height');
49
+ const boxes = [...slide.querySelectorAll('div')]
50
+ .filter(el => isTextBox(el) && el.parentElement && el.parentElement !== slide)
51
+ .map(el => ({ el, pos: slidePosition(el.parentElement, slide), text: squash(readBoxText(el)) }));
52
+ const tables = [...slide.querySelectorAll('table')]
53
+ .filter(el => el.parentElement && el.parentElement !== slide)
54
+ .map(el => ({ el, pos: slidePosition(el.parentElement, slide) }));
55
+ const near = (pos, { x, y, w }) =>
56
+ Math.abs(pos.left - x * width) <= MATCH_PX &&
57
+ Math.abs(pos.top - y * height) <= MATCH_PX &&
58
+ Math.abs(pos.width - w * width) <= MATCH_PX;
59
+ const used = new Set();
60
+ const found = [];
61
+ for (const shape of shapes) {
62
+ if (shape.cell) {
63
+ const table = tables.find(t => near(t.pos, shape.box));
64
+ // 줄 · 칸은 요소로 센다 (tBodies · rows · cells가 없는 DOM도 있음)
65
+ const rows = table ? [...table.el.querySelectorAll('tr')] : [];
66
+ const tr = rows.filter(r => r.closest('table') === table.el)[shape.cell.row];
67
+ const td = tr && [...tr.children].filter(c => c.tagName === 'TD')[shape.cell.index];
68
+ if (td && !used.has(td)) {
69
+ used.add(td);
70
+ found.push({ shape, element: td });
71
+ }
72
+ continue;
73
+ }
74
+ const { w } = shape.box;
75
+ const want = squash(textOf(shape));
76
+ let best = null;
77
+ let bestScore = -1;
78
+ for (const c of boxes) {
79
+ if (used.has(c.el) || !near(c.pos, shape.box)) continue;
80
+ // 글자가 같음 2, 글자가 있음 1, 빈 상자 0 (같은 점수면 앞에 그린 것)
81
+ const score = c.text === want ? 2 : c.text ? 1 : 0;
82
+ if (score > bestScore) {
83
+ best = c;
84
+ bestScore = score;
85
+ }
86
+ }
87
+ if (!best || (want && bestScore === 0)) {
88
+ const same = want
89
+ ? boxes.filter(
90
+ c => !used.has(c.el) && c.text === want && Math.abs(c.pos.width - w * width) <= MATCH_PX
91
+ )
92
+ : [];
93
+ if (same.length !== 1) continue;
94
+ best = same[0];
95
+ }
96
+ used.add(best.el);
97
+ found.push({ shape, element: best.el });
98
+ }
99
+ return found;
100
+ }
101
+
102
+ /**
103
+ * 누른 곳의 글자가 다른 글자 상자에 가려 있으면 그 글자의 상자로 보낸다. 도형 글자 상자는 도형 크기만큼 투명하게 깔려,
104
+ * 뒤에 그린 넓은 상자(같은 그룹의 긴 줄, 바탕 도형 등)가 앞 상자의 글자를 덮는다 (PowerPoint는 채우기 없는 도형을 글자로 고름).
105
+ * 누른 곳 맨 위가 글자가 아니고(빈 자리) 그 아래 고칠 수 있는 상자의 글자가 있을 때만 바꾸고, 커서는 누른 글자 자리에 둔다
106
+ * @param {HTMLElement} page 슬라이드를 그리는 곳 (쪽을 넘겨도 같은 요소, 한 번만 붙임)
107
+ */
108
+ export function routeTextClicks(page) {
109
+ if (page.dataset.dcRoute !== undefined) return;
110
+ page.dataset.dcRoute = '';
111
+ const doc = page.ownerDocument;
112
+ page.addEventListener(
113
+ 'mousedown',
114
+ e => {
115
+ if (e.button !== 0 || typeof doc.elementsFromPoint !== 'function') return;
116
+ const stack = doc.elementsFromPoint(e.clientX, e.clientY);
117
+ const top = stack[0];
118
+ const owner = top?.closest('.dc-editable');
119
+ // 맨 위가 고칠 수 있는 상자의 글자이거나 고치는 중인 상자면 그대로
120
+ if (!top || (owner && (top.tagName === 'SPAN' || owner === doc.activeElement))) return;
121
+ const span = stack.find(
122
+ el =>
123
+ el.tagName === 'SPAN' && el.dataset.dcBullet === undefined && el.closest('.dc-editable')
124
+ );
125
+ const box = span?.closest('.dc-editable');
126
+ if (!box || box === owner || !page.contains(box)) return;
127
+ e.preventDefault();
128
+ box.focus();
129
+ placeCaret(span, e.clientX);
130
+ },
131
+ true
132
+ );
133
+ }
134
+
135
+ /** span 글자 중 x(화면 좌표)에 가장 가까운 자리에 커서 */
136
+ function placeCaret(span, x) {
137
+ const doc = span.ownerDocument;
138
+ const sel = doc.getSelection();
139
+ const text = [...span.childNodes].find(n => n.nodeType === 3);
140
+ if (!sel || !text) return;
141
+ const range = doc.createRange();
142
+ let offset = text.data.length;
143
+ for (let i = 0; i < text.data.length; i += 1) {
144
+ range.setStart(text, i);
145
+ range.setEnd(text, i + 1);
146
+ const r = range.getBoundingClientRect();
147
+ if (x < r.left + r.width / 2) {
148
+ offset = i;
149
+ break;
150
+ }
151
+ }
152
+ range.setStart(text, offset);
153
+ range.collapse(true);
154
+ sel.removeAllRanges();
155
+ sel.addRange(range);
156
+ }
157
+
158
+ /** 글자 상자 안 문단 (렌더러는 div, 붙여넣기 · 브라우저가 p를 만들 수 있음) */
159
+ const isParagraph = el => el.tagName === 'DIV' || el.tagName === 'P';
160
+
161
+ /** 문단 첫 span이 글머리 기호(따로 띄워 둠, 뒤에 글자가 이어짐)인지 */
162
+ const isBullet = span =>
163
+ span.tagName === 'SPAN' &&
164
+ !span.previousElementSibling &&
165
+ Boolean(span.nextElementSibling) &&
166
+ span.style.position === 'absolute';
167
+
168
+ /** 글머리 기호는 고칠 수 없게 (글자로 읽지 않음) */
169
+ function lockBullets(box) {
170
+ for (const p of box.children) {
171
+ const first = p.firstElementChild;
172
+ if (first && isBullet(first)) {
173
+ first.contentEditable = 'false';
174
+ first.dataset.dcBullet = '';
175
+ }
176
+ }
177
+ }
178
+
179
+ /**
180
+ * 글자 상자의 글자: 문단(p · div)마다 한 줄, 줄바꿈(<br>)도 줄. 글머리 기호는 뺀다. @office-kit setShapeText와 같은 모양(\n)
181
+ * @param {Element} box 글자 상자
182
+ */
183
+ export function readBoxText(box) {
184
+ const lines = [];
185
+ let line = null;
186
+ const walk = node => {
187
+ for (const c of node.childNodes) {
188
+ if (c.nodeType === 3) {
189
+ line = (line ?? '') + c.data;
190
+ } else if (c.nodeType === 1) {
191
+ if (c.dataset?.dcBullet !== undefined || isBullet(c)) continue;
192
+ if (c.tagName === 'BR') {
193
+ lines.push(line ?? '');
194
+ line = null;
195
+ continue;
196
+ }
197
+ const block = c.tagName === 'P' || c.tagName === 'DIV';
198
+ if (block && line !== null) {
199
+ lines.push(line);
200
+ line = null;
201
+ }
202
+ walk(c);
203
+ if (block && line !== null) {
204
+ lines.push(line);
205
+ line = null;
206
+ }
207
+ }
208
+ }
209
+ };
210
+ walk(box);
211
+ if (line !== null) lines.push(line);
212
+ // 문단을 감싼 div · p가 겹쳐 생긴 빈 줄은 빼지 않는다 (사용자가 만든 빈 문단일 수 있음). 끝의 빈 줄만 정리
213
+ while (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
214
+ return lines.join('\n');
215
+ }
216
+
217
+ /**
218
+ * 편집 테두리 범위를 잰다 (styles.css div.dc-editable::before가 그림). 도형 글자 상자는 도형 크기라 글자보다 넓어
219
+ * 문단을 글자 폭으로 줄여 두었다: 테두리는 상자마다 하나로, 상자 안 문단(직속 자식) 전체를 감싼다.
220
+ * 좌표는 상자 안 좌표(offsetLeft · offsetTop · offsetWidth · offsetHeight, 상자는 position: absolute라 문단의 offsetParent)라
221
+ * 쪽 맞춤(transform: scale) · 회전 · 그룹과 상관없이 같고, 테두리도 상자와 같이 기운다. 화면 좌표(getBoundingClientRect)는 쓰지 않는다.
222
+ * 문단이 아닌 직속 자식(span · br, flex 항목이라 블록)도 같이 잰다. 상자에 바로 들어간 글자(텍스트 노드)는 자리를 잴 수 없어
223
+ * 상자 전체로 둔다. 표 칸(td)은 칸 전체 테두리 그대로라 재지 않는다.
224
+ * 상자 style에 CSS 변수만 쓰므로 자식 노드(저장 글자 · Esc 되돌리기 · 변경 감지 childList)는 바뀌지 않는다
225
+ * @param {HTMLElement} box 글자 상자
226
+ */
227
+ export function outlineBox(box) {
228
+ if (box.tagName !== 'DIV') return;
229
+ let left = Infinity;
230
+ let top = Infinity;
231
+ let right = -Infinity;
232
+ let bottom = -Infinity;
233
+ let loose = false;
234
+ for (const node of box.childNodes) {
235
+ if (node.nodeType === 3) {
236
+ if (node.data.trim()) loose = true;
237
+ continue;
238
+ }
239
+ if (node.nodeType !== 1 || node.offsetParent !== box) continue;
240
+ const { offsetLeft: x, offsetTop: y, offsetWidth: w, offsetHeight: h } = node;
241
+ if (!w && !h) continue;
242
+ left = Math.min(left, x);
243
+ top = Math.min(top, y);
244
+ right = Math.max(right, x + w);
245
+ bottom = Math.max(bottom, y + h);
246
+ }
247
+ const style = box.style;
248
+ if (loose || left === Infinity) {
249
+ for (const k of ['left', 'top', 'width', 'height']) style.removeProperty(`--dc-edit-${k}`);
250
+ return;
251
+ }
252
+ style.setProperty('--dc-edit-left', `${left}px`);
253
+ style.setProperty('--dc-edit-top', `${top}px`);
254
+ style.setProperty('--dc-edit-width', `${right - left}px`);
255
+ style.setProperty('--dc-edit-height', `${bottom - top}px`);
256
+ }
257
+
258
+ /**
259
+ * 글자 상자를 제자리에서 고칠 수 있게 한다. Enter는 새 문단, Esc는 취소, 바깥을 누르면(blur) 적용,
260
+ * Ctrl/⌘+Enter도 적용. 붙여넣기는 글자만, 굵게 · 기울임 같은 서식 단축키는 막는다 (글자만 고침). 한글 조합 중 키는 건드리지 않는다
261
+ * @param {HTMLElement} box 글자 상자 (findTextBoxes)
262
+ * @param {{ label: string, onCommit: (text: string) => void }} opts
263
+ */
264
+ export function makeEditable(box, { label, onCommit }) {
265
+ // 쪽을 다시 맞출 때(크기 바뀜) 같은 상자에 또 붙이지 않는다 (고치는 중 글자를 원래 글자로 잘못 기억함)
266
+ if (box.dataset.dcEditable !== undefined) {
267
+ outlineBox(box);
268
+ return { before: readBoxText(box) };
269
+ }
270
+ box.dataset.dcEditable = '';
271
+ lockBullets(box);
272
+ // 고친 뒤에도 같은 상자를 계속 쓴다 (화면 코드가 다시 그리지 않음): 적용할 때마다 기준(before · Esc로 되돌릴 모양)을 바꾼다
273
+ let original = [...box.childNodes].map(n => n.cloneNode(true));
274
+ let before = readBoxText(box);
275
+ box.contentEditable = 'true';
276
+ box.spellcheck = false;
277
+ box.tabIndex = 0;
278
+ box.classList.add('dc-editable');
279
+ box.setAttribute('role', 'textbox');
280
+ box.setAttribute('aria-multiline', 'true');
281
+ box.setAttribute('aria-label', label);
282
+ let cancelled = false;
283
+ // 문단 정렬 · 줄 간격 · 글자 크기는 문단 div에 있다. 글자를 다 지운 뒤 Backspace를 더 누르면 브라우저가 마지막 문단 div까지
284
+ // 지워, 새로 쓴 글자가 상자에 바로 들어가 왼쪽 정렬 · 기본 크기가 된다 (filled-template 24쪽 '일반 처리'). 문단을 지키고,
285
+ // 그래도 문단이 없어지면(전체 잘라내기 등) 처음 문단 모양으로 다시 감싼다
286
+ const paragraph = [...box.children].find(isParagraph)?.cloneNode(false) ?? null;
287
+ const keepParagraph = () => {
288
+ if (!paragraph || [...box.children].some(isParagraph)) return;
289
+ const p = paragraph.cloneNode(false);
290
+ p.append(...box.childNodes);
291
+ if (!p.firstChild) p.append(box.ownerDocument.createElement('br'));
292
+ box.append(p);
293
+ const sel = box.ownerDocument.getSelection();
294
+ if (sel && box.ownerDocument.activeElement === box) {
295
+ const range = box.ownerDocument.createRange();
296
+ range.selectNodeContents(p);
297
+ range.collapse(false);
298
+ sel.removeAllRanges();
299
+ sel.addRange(range);
300
+ }
301
+ };
302
+ // 입력하는 동안은 저장 전 변경으로 보지 않는다 (적용하면 화면 코드가 markDirty). 한글 조합 중에는 DOM을 건드리지 않는다.
303
+ // 테두리 범위는 글자가 바뀔 때(입력 · 붙여넣기 · 조합 끝)와 보일 때(가리킴 · focus) 다시 잰다. 조합 중 글자 폭도 따라가게
304
+ // 조합 중 input에서도 잰다 (DOM은 건드리지 않고 읽기만)
305
+ box.addEventListener('input', e => {
306
+ e.stopPropagation();
307
+ if (!e.isComposing) keepParagraph();
308
+ outlineBox(box);
309
+ });
310
+ box.addEventListener('compositionend', () => {
311
+ keepParagraph();
312
+ outlineBox(box);
313
+ });
314
+ // 상자는 누를 수 없어(pointer-events: none) 문단에서 올라온 것. 쪽 맞춤 · 글꼴이 늦게 들어와 바뀐 크기도 여기서 맞춘다
315
+ box.addEventListener('pointerover', () => outlineBox(box));
316
+ box.addEventListener('keydown', e => {
317
+ if (e.isComposing) return;
318
+ if (
319
+ (e.key === 'Backspace' || e.key === 'Delete') &&
320
+ readBoxText(box) === '' &&
321
+ [...box.children].filter(isParagraph).length <= 1
322
+ ) {
323
+ // 지울 글자가 없다: 남은 빈 문단(정렬 · 크기)을 지우지 않게
324
+ e.preventDefault();
325
+ } else if (e.key === 'Escape') {
326
+ e.preventDefault();
327
+ cancelled = true;
328
+ box.blur();
329
+ // 되돌리기는 다음 차례에: 고치는 동안 생긴 변화 알림(MutationObserver, 키트 useSave)이 먼저 처리되게.
330
+ // 바로 바꾸면 알림이 늦게 와 떼어 낸 노드를 보고 "저장하지 않은 변경"으로 잘못 센다
331
+ setTimeout(
332
+ () => {
333
+ box.replaceChildren(...original.map(n => n.cloneNode(true)));
334
+ lockBullets(box);
335
+ outlineBox(box);
336
+ },
337
+ 0
338
+ );
339
+ } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
340
+ e.preventDefault();
341
+ box.blur();
342
+ } else if ((e.ctrlKey || e.metaKey) && ['b', 'i', 'u'].includes(e.key.toLowerCase())) {
343
+ e.preventDefault();
344
+ }
345
+ });
346
+ box.addEventListener('paste', e => {
347
+ e.preventDefault();
348
+ const text = e.clipboardData?.getData('text/plain') ?? '';
349
+ const sel = box.ownerDocument.getSelection();
350
+ if (!sel || sel.rangeCount === 0) return;
351
+ const range = sel.getRangeAt(0);
352
+ range.deleteContents();
353
+ const node = box.ownerDocument.createTextNode(text);
354
+ range.insertNode(node);
355
+ range.setStartAfter(node);
356
+ range.collapse(true);
357
+ sel.removeAllRanges();
358
+ sel.addRange(range);
359
+ // 막은 붙여넣기는 input이 오지 않는다: 전체를 골라 붙이면 문단이 지워져 글자가 상자에 바로 들어가므로 여기서도 감싼다
360
+ keepParagraph();
361
+ outlineBox(box);
362
+ });
363
+ box.addEventListener('focus', () => {
364
+ cancelled = false;
365
+ outlineBox(box);
366
+ });
367
+ box.addEventListener('blur', () => {
368
+ if (cancelled) return;
369
+ const after = readBoxText(box);
370
+ if (after === before) return;
371
+ before = after;
372
+ original = [...box.childNodes].map(n => n.cloneNode(true));
373
+ onCommit(after);
374
+ });
375
+ outlineBox(box);
376
+ return { before };
377
+ }
@@ -0,0 +1,13 @@
1
+ // core/load.js 타입 (편집기 자동완성 · 테스트용)
2
+ import type { OpenedDocument } from './pdf.js';
3
+
4
+ export declare class FetchError extends Error {
5
+ status: number;
6
+ constructor(message: string, status: number);
7
+ }
8
+ export declare function fetchBytes(url: string, fetchImpl?: typeof fetch): Promise<Uint8Array>;
9
+ export declare function openDocument(
10
+ kind: 'pdf' | 'pptx',
11
+ source: Uint8Array | string,
12
+ opts?: { prefetch?: boolean }
13
+ ): Promise<OpenedDocument>;
@@ -0,0 +1,40 @@
1
+ // 문서 불러오기 (고치지 않습니다): 저장된 주소에서 파일 바이트를 받고, 종류에 맞는 그리기 모듈로 엽니다.
2
+ // PDF · PPTX 모듈은 필요할 때만 불러온다 (import()): 둘 다 묶여 들어가지만 쓰지 않는 쪽은 실행하지 않는다.
3
+
4
+ /** 파일을 받지 못함 (주소 · 권한 · 콘텐츠 CSP connect-src) */
5
+ export class FetchError extends Error {
6
+ constructor(message, status) {
7
+ super(message);
8
+ this.name = 'FetchError';
9
+ this.status = status;
10
+ }
11
+ }
12
+
13
+ /**
14
+ * 올린 파일 바이트 (주소는 await app.assets.url(asset_key) = asset_base_url + assets/{자료 id}/{asset_key}, 자료 API 출처의 서명 경로).
15
+ * 운영 콘텐츠 CSP의 connect-src는 지금 material API뿐이라 콘텐츠 출처 fetch가 막힌다 (서버에 connect-src 추가 요청).
16
+ * ecdk dev는 그 경로만 dev CSP에 더해 둔다
17
+ * @param {string} url
18
+ * @param {typeof fetch} [fetchImpl] 테스트용
19
+ */
20
+ export async function fetchBytes(url, fetchImpl = globalThis.fetch) {
21
+ let res;
22
+ try {
23
+ res = await fetchImpl(url);
24
+ } catch (e) {
25
+ throw new FetchError(String(e?.message ?? e), 0);
26
+ }
27
+ if (!res.ok) throw new FetchError(`HTTP ${res.status}`, res.status);
28
+ return new Uint8Array(await res.arrayBuffer());
29
+ }
30
+
31
+ /**
32
+ * @param {'pdf' | 'pptx'} kind
33
+ * @param {Uint8Array | string} source 바이트, 또는 주소 (PDF는 pdf.js가 Range로 필요한 부분만 받음, PPTX는 전체를 받음)
34
+ * @param {{ prefetch?: boolean }} [opts] PDF 주소: 첫 쪽 뒤 나머지를 미리 받기 (편집 화면, core/pdf-options.js)
35
+ */
36
+ export async function openDocument(kind, source, opts) {
37
+ if (kind === 'pdf') return (await import('./pdf.js')).openPdf(source, opts);
38
+ const bytes = typeof source === 'string' ? await fetchBytes(source) : source;
39
+ return (await import('./pptx-view.js')).openPptx(bytes);
40
+ }
@@ -0,0 +1,9 @@
1
+ // core/pdf-options.js 타입 (편집기 자동완성 · 테스트용)
2
+ export declare const RANGE_CHUNK_BYTES: number;
3
+ export declare function pdfSourceOptions(
4
+ source: Uint8Array | string,
5
+ opts?: { prefetch?: boolean }
6
+ ):
7
+ | { data: Uint8Array }
8
+ | { url: string; rangeChunkSize: number; disableStream: true; disableAutoFetch: boolean };
9
+ export declare function isExpiredSource(e: unknown): boolean;
@@ -0,0 +1,36 @@
1
+ // pdf.js 여는 옵션 (고치지 않습니다). core/pdf.js가 씁니다 (테스트가 pdf.js 없이 확인하려고 따로 둠).
2
+ //
3
+ // 주소로 열 때 (서버가 Range 응답 헤더를 내보내면 pdf.js가 Range로 받는다):
4
+ // - disableStream: 첫 요청(Range 없음)은 크기 · Range 지원만 보고 끊는다. 켜 두면 그 응답으로 파일 전체를 받으면서
5
+ // Range 요청도 해서 같은 바이트를 두 번 받는다
6
+ // - 학생 화면(기본): 보는 쪽만 그때그때 받는다 (disableAutoFetch). 서명 주소는 6시간 유효(발행 버전)라 그 뒤 넘긴
7
+ // 쪽은 받지 못할 수 있다 → 화면이 "문서 주소가 만료됐어요"를 보인다 (screens/learn.js)
8
+ // - 편집 화면(prefetch): 첫 쪽을 보인 뒤 나머지를 뒤에서 모두 받는다. 초안 서명 주소는 1시간 유효라 그 안에 다 받아 둔다
9
+
10
+ /** 주소로 열 때 한 번에 받는 크기 (Range). 큰 PDF도 첫 쪽부터 빨리 보이게 */
11
+ export const RANGE_CHUNK_BYTES = 256 * 1024;
12
+
13
+ /**
14
+ * @param {Uint8Array | string} source 바이트, 또는 주소
15
+ * @param {{ prefetch?: boolean }} [opts] prefetch: 첫 쪽 뒤 나머지를 미리 받기 (편집 화면)
16
+ */
17
+ export function pdfSourceOptions(source, opts = {}) {
18
+ if (typeof source !== 'string')
19
+ // pdf.js가 바이트를 작업자로 넘기며 비우므로 사본을 준다 (편집 화면이 같은 바이트를 다시 쓸 수 있게)
20
+ return { data: source.slice() };
21
+ return {
22
+ url: source,
23
+ rangeChunkSize: RANGE_CHUNK_BYTES,
24
+ disableStream: true,
25
+ disableAutoFetch: !opts.prefetch,
26
+ };
27
+ }
28
+
29
+ /**
30
+ * 서명 주소가 만료되어 받지 못한 것인지 (pdf.js UnexpectedResponseException · 받기 오류의 HTTP 상태 401 · 403 · 410)
31
+ * @param {unknown} e
32
+ */
33
+ export function isExpiredSource(e) {
34
+ const status = e?.status ?? Number(/\((\d{3})\)/.exec(String(e?.message ?? ''))?.[1]);
35
+ return status === 401 || status === 403 || status === 410;
36
+ }
@@ -0,0 +1,24 @@
1
+ // core/pdf-worker.js 타입 (편집기 자동완성 · 테스트용)
2
+ export declare const WORKER_READY_MS: number;
3
+ export declare function toClassicWorker(code: string): string;
4
+ export declare function withTimeout<T>(
5
+ promise: Promise<T>,
6
+ ms: number,
7
+ message: string,
8
+ onTimeout?: () => void
9
+ ): Promise<T>;
10
+ export declare function workerUrl(classicCode: string): string;
11
+ export declare function startClassicWorker(
12
+ classicCode: string,
13
+ env?: { Worker?: typeof Worker; timeoutMs?: number; url?: string }
14
+ ): Promise<Worker | null>;
15
+ export declare function loadMainThreadWorker(classicCode: string): boolean;
16
+ export declare function preparePdfWorker(
17
+ code: string,
18
+ env?: {
19
+ Worker?: typeof Worker;
20
+ timeoutMs?: number;
21
+ url?: string;
22
+ loadMainThread?: (code: string) => boolean;
23
+ }
24
+ ): Promise<{ port: Worker | null }>;
@@ -0,0 +1,122 @@
1
+ // pdf.js 작업자(worker) 띄우기 (고치지 않습니다). core/pdf.js가 씁니다.
2
+ //
3
+ // LXP 콘텐츠는 출처가 null인 sandbox iframe에서 돕니다(서버 CSP `sandbox allow-scripts`). 그 안에서는
4
+ // new Worker(blob:, { type: 'module' })가 실패하고(error) 일반(classic) blob 작업자는 됩니다. 그래서:
5
+ // 1. pdf.js 작업자 코드(ES 모듈)를 일반 스크립트로 바꿔 blob 작업자로 띄운다 (toClassicWorker)
6
+ // 2. 작업자가 첫 메시지(ready)를 보내지 않고 실패하거나 시간 안에 답이 없으면, 작업자 없이 화면 스레드에서
7
+ // 돌린다 (pdf.js "fake worker": 같은 코드를 <script>로 실행하면 globalThis.pdfjsWorker가 생김)
8
+ // 3. 그래도 안 되면 오류를 던져 화면이 "열지 못했어요"를 보인다 (멈춰 있지 않게)
9
+
10
+ /** 작업자가 첫 메시지를 보낼 때까지 기다리는 시간 */
11
+ export const WORKER_READY_MS = 5000;
12
+
13
+ /**
14
+ * pdf.js 작업자 ES 모듈 코드 → 일반 스크립트 코드: 끝의 `export { … }`를 빼고, 모듈 주소(import 메타의 url)는
15
+ * 스크립트 주소(self.location.href)로 (wasm 디코더가 기준 주소로만 쓰고 실패해도 넘어감)
16
+ * @param {string} code
17
+ */
18
+ export function toClassicWorker(code) {
19
+ return code
20
+ .replace(/export\s*\{[^}]*\}\s*;?\s*$/, '')
21
+ // 정규식으로 적는다: 글자 그대로 쓰면 빌드(Vite)가 그 글자를 파일 주소로 바꿔 버린다
22
+ .replace(/\bimport\.meta\.url\b/g, 'self.location.href');
23
+ }
24
+
25
+ /**
26
+ * promise가 ms 안에 끝나지 않으면 onTimeout()을 부르고 오류로 끝낸다
27
+ * @template T
28
+ * @param {Promise<T>} promise
29
+ * @param {number} ms
30
+ * @param {string} message
31
+ * @param {() => void} [onTimeout]
32
+ * @returns {Promise<T>}
33
+ */
34
+ export function withTimeout(promise, ms, message, onTimeout) {
35
+ let timer = 0;
36
+ const timeout = new Promise((_, reject) => {
37
+ timer = setTimeout(
38
+ () => {
39
+ onTimeout?.();
40
+ reject(new Error(message));
41
+ },
42
+ ms
43
+ );
44
+ });
45
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
46
+ }
47
+
48
+ /**
49
+ * 일반 스크립트 작업자 코드의 blob: 주소. 페이지에서 한 번만 만든다 (core/pdf.js가 모듈을 읽을 때)
50
+ * @param {string} classicCode
51
+ */
52
+ export const workerUrl = classicCode =>
53
+ URL.createObjectURL(new Blob([classicCode], { type: 'text/javascript' }));
54
+
55
+ /**
56
+ * 일반 blob 작업자를 띄우고 첫 메시지를 기다린다. 되면 작업자, 아니면 null (만든 작업자는 닫음)
57
+ * @param {string} classicCode
58
+ * @param {{ Worker?: typeof Worker, timeoutMs?: number, url?: string }} [env] url: 미리 만든 blob: 주소 (없으면 만듦)
59
+ * @returns {Promise<Worker | null>}
60
+ */
61
+ export async function startClassicWorker(classicCode, env = {}) {
62
+ const WorkerClass = env.Worker ?? globalThis.Worker;
63
+ if (typeof WorkerClass !== 'function') return null;
64
+ const url = env.url ?? workerUrl(classicCode);
65
+ let worker;
66
+ try {
67
+ worker = new WorkerClass(url);
68
+ } catch (e) {
69
+ console.warn('[document] PDF 작업자를 띄우지 못해 작업자 없이 엽니다', e);
70
+ return null;
71
+ }
72
+ const ready = await new Promise(resolve => {
73
+ const done = ok => {
74
+ clearTimeout(timer);
75
+ worker.removeEventListener('message', onMessage);
76
+ worker.removeEventListener('error', onError);
77
+ resolve(ok);
78
+ };
79
+ const onMessage = () => done(true);
80
+ const onError = e => {
81
+ e.preventDefault?.();
82
+ done(false);
83
+ };
84
+ const timer = setTimeout(
85
+ () => done(false),
86
+ env.timeoutMs ?? WORKER_READY_MS
87
+ );
88
+ worker.addEventListener('message', onMessage);
89
+ worker.addEventListener('error', onError);
90
+ });
91
+ if (ready) return worker;
92
+ console.warn('[document] PDF 작업자가 답하지 않아 작업자 없이 엽니다');
93
+ worker.terminate();
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * 작업자 없이(화면 스레드) 돌릴 준비: 작업자 코드를 <script>로 실행해 globalThis.pdfjsWorker를 만든다.
99
+ * 되면 true
100
+ * @param {string} classicCode
101
+ */
102
+ export function loadMainThreadWorker(classicCode) {
103
+ if (globalThis.pdfjsWorker?.WorkerMessageHandler) return true;
104
+ const script = document.createElement('script');
105
+ script.textContent = classicCode;
106
+ document.head.append(script);
107
+ script.remove();
108
+ return Boolean(globalThis.pdfjsWorker?.WorkerMessageHandler);
109
+ }
110
+
111
+ /**
112
+ * pdf.js 작업자를 준비한다: 일반 blob 작업자 → 안 되면 작업자 없이. 둘 다 안 되면 오류
113
+ * @param {string} code 일반 스크립트로 바꾼 작업자 코드 (toClassicWorker)
114
+ * @param {{ Worker?: typeof Worker, timeoutMs?: number, url?: string, loadMainThread?: (code: string) => boolean }} [env]
115
+ * @returns {Promise<{ port: Worker | null }>} port가 null이면 pdf.js가 화면 스레드에서 돈다
116
+ */
117
+ export async function preparePdfWorker(code, env = {}) {
118
+ const port = await startClassicWorker(code, env);
119
+ if (port) return { port };
120
+ if ((env.loadMainThread ?? loadMainThreadWorker)(code)) return { port: null };
121
+ throw new Error('PDF 작업자를 띄우지 못했습니다');
122
+ }
@@ -0,0 +1,12 @@
1
+ // core/pdf.js · core/pptx-view.js 타입 (편집기 자동완성 · 테스트용)
2
+ import type { ViewerDoc } from './viewer.js';
3
+
4
+ export interface OpenedDocument extends ViewerDoc {
5
+ kind: 'pdf' | 'pptx';
6
+ thumbnails(width: number): Promise<HTMLElement[]>;
7
+ destroy(): void;
8
+ }
9
+ export declare function openPdf(
10
+ source: Uint8Array | string,
11
+ opts?: { prefetch?: boolean }
12
+ ): Promise<OpenedDocument>;