@eliceio/cdk-cli 1.3.0-contenttypes.0 → 1.3.0-contenttypes.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -20
- 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 +2 -2
- 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 +6 -0
- package/templates/document/ui/templates/edit.js +82 -0
- package/templates/document/ui/templates/page.js +11 -0
- package/templates/document/ui/templates/viewer.js +41 -0
- package/templates/document/ui/texts.d.ts +3 -0
- package/templates/document/ui/texts.js +62 -0
- package/templates/document/ui/theme.css +69 -0
- package/templates/quiz/README.md +11 -9
- 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 +6 -2
- package/templates/quiz/core/model.js +30 -4
- 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 +165 -52
- package/templates/quiz/screens/learn.js +94 -38
- package/templates/quiz/styles.css +464 -4
- package/templates/quiz/template.json +1 -1
- package/templates/quiz/ui/templates/edit.d.ts +1 -0
- package/templates/quiz/ui/templates/edit.js +65 -9
- package/templates/quiz/ui/templates/page.js +14 -0
- package/templates/quiz/ui/templates/question.js +5 -3
- package/templates/quiz/ui/texts.js +38 -20
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// PDF 그리기 (고치지 않습니다). pdf.js(pdfjs-dist) legacy 빌드로 쪽을 canvas에 그리고, 글자 층(text layer)을 얹어
|
|
2
|
+
// 글자를 고르고 복사할 수 있게 합니다.
|
|
3
|
+
//
|
|
4
|
+
// 콘텐츠 CSP 안에서 돌리려고 pdf.js가 스스로 파일을 받지 않게 했습니다:
|
|
5
|
+
// - legacy 빌드: 최신 빌드는 Firefox 142에서 아직 없는 API(getOrInsertComputed)를 써서 멈춘다
|
|
6
|
+
// - 작업자(worker): 콘텐츠 출처의 파일 작업자는 CSP(worker-src blob:)에 막히므로, 작업자 코드를 번들에 글로 넣고
|
|
7
|
+
// Blob 주소로 띄운다. LXP(출처 null)에서는 모듈 작업자가 실패해 일반(classic) 작업자로 띄우고, 그것도 안 되면
|
|
8
|
+
// 작업자 없이 화면 스레드에서 돌린다 (core/pdf-worker.js). 열기가 오래 멈추면 오류로 끝낸다 (OPEN_TIMEOUT_MS)
|
|
9
|
+
// - 글꼴 · CMap · wasm: connect-src가 material API뿐이라 fetch로 받지 못한다. 번들에 넣은 데이터(data: 주소)를
|
|
10
|
+
// BinaryDataFactory로 넘긴다. CMap은 한국어(Adobe-Korea1 · KSC · UniKS)만 넣어 크기를 줄였다 (Identity-H는 pdf.js 안에 있음).
|
|
11
|
+
// 글꼴을 넣지 않은 중국어 · 일본어 PDF는 글자가 빠질 수 있다
|
|
12
|
+
// - PDF 안 스크립트는 돌리지 않는다 (enableScripting: false, quickjs wasm을 넣지 않음)
|
|
13
|
+
import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.min.mjs';
|
|
14
|
+
import workerCode from 'pdfjs-dist/legacy/build/pdf.worker.min.mjs?raw';
|
|
15
|
+
import { pdfSourceOptions } from './pdf-options.js';
|
|
16
|
+
import { preparePdfWorker, toClassicWorker, withTimeout, workerUrl } from './pdf-worker.js';
|
|
17
|
+
|
|
18
|
+
// 키: pdf.js가 요청하는 데이터 종류. 값: [폴더, 파일 경로 → data: 주소를 주는 함수]
|
|
19
|
+
const BUNDLED = {
|
|
20
|
+
cMapUrl: [
|
|
21
|
+
'cmaps',
|
|
22
|
+
import.meta.glob('/node_modules/pdfjs-dist/cmaps/{Adobe-Korea1-*,KSC*,UniKS-*}.bcmap', {
|
|
23
|
+
query: '?url&inline',
|
|
24
|
+
import: 'default',
|
|
25
|
+
}),
|
|
26
|
+
],
|
|
27
|
+
standardFontDataUrl: [
|
|
28
|
+
'standard_fonts',
|
|
29
|
+
import.meta.glob('/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}', {
|
|
30
|
+
query: '?url&inline',
|
|
31
|
+
import: 'default',
|
|
32
|
+
}),
|
|
33
|
+
],
|
|
34
|
+
wasmUrl: [
|
|
35
|
+
'wasm',
|
|
36
|
+
import.meta.glob('/node_modules/pdfjs-dist/wasm/{openjpeg,jbig2,qcms_bg}.wasm', {
|
|
37
|
+
query: '?url&inline',
|
|
38
|
+
import: 'default',
|
|
39
|
+
}),
|
|
40
|
+
],
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const fromDataUrl = (url) => Uint8Array.from(atob(url.slice(url.indexOf(',') + 1)), (c) => c.charCodeAt(0));
|
|
44
|
+
|
|
45
|
+
/** pdf.js가 글꼴 · CMap · wasm을 달라고 하면 번들에 넣은 것을 준다 (네트워크 없음) */
|
|
46
|
+
class BundledDataFactory {
|
|
47
|
+
async fetch({ kind, filename }) {
|
|
48
|
+
const [dir, files] = BUNDLED[kind] ?? [];
|
|
49
|
+
const load = files?.[`/node_modules/pdfjs-dist/${dir}/${filename}`];
|
|
50
|
+
if (!load) throw new Error(`번들에 없는 pdf.js 데이터: ${kind} ${filename}`);
|
|
51
|
+
return fromDataUrl(await load());
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 작업자 코드 · blob: 주소는 이 모듈을 읽을 때 한 번만 만든다
|
|
56
|
+
const WORKER_CODE = toClassicWorker(workerCode);
|
|
57
|
+
const WORKER_URL = workerUrl(WORKER_CODE);
|
|
58
|
+
|
|
59
|
+
let worker = null;
|
|
60
|
+
/** 작업자는 페이지에 하나만 띄워 여러 문서가 같이 쓴다 (준비가 실패하면 다음에 다시 시도) */
|
|
61
|
+
function ensureWorker() {
|
|
62
|
+
worker ??= preparePdfWorker(WORKER_CODE, { url: WORKER_URL }).then(
|
|
63
|
+
({ port }) => {
|
|
64
|
+
pdfjs.GlobalWorkerOptions.workerPort = port;
|
|
65
|
+
},
|
|
66
|
+
(e) => {
|
|
67
|
+
worker = null;
|
|
68
|
+
throw e;
|
|
69
|
+
}
|
|
70
|
+
);
|
|
71
|
+
return worker;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** PDF를 여는(첫 응답 · 쪽 크기) 데 이 시간보다 오래 걸리면 멈춘 것으로 보고 오류 */
|
|
75
|
+
const OPEN_TIMEOUT_MS = 30000;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* PDF를 연다. 문서 뷰어(core/viewer.js)가 쓰는 모양으로 돌려준다
|
|
79
|
+
* @param {Uint8Array | string} source 바이트, 또는 주소(pdf.js가 Range로 필요한 부분만 받음, core/pdf-options.js)
|
|
80
|
+
* @param {{ prefetch?: boolean }} [opts] prefetch: 첫 쪽 뒤 나머지를 미리 받기 (편집 화면)
|
|
81
|
+
*/
|
|
82
|
+
export async function openPdf(source, opts = {}) {
|
|
83
|
+
await ensureWorker();
|
|
84
|
+
const task = pdfjs.getDocument({
|
|
85
|
+
...pdfSourceOptions(source, opts),
|
|
86
|
+
BinaryDataFactory: BundledDataFactory,
|
|
87
|
+
enableScripting: false,
|
|
88
|
+
isEvalSupported: false,
|
|
89
|
+
});
|
|
90
|
+
const { doc, sizes } = await withTimeout(
|
|
91
|
+
(async () => {
|
|
92
|
+
const doc = await task.promise;
|
|
93
|
+
const sizes = [];
|
|
94
|
+
for (let i = 1; i <= doc.numPages; i += 1) {
|
|
95
|
+
const vp = (await doc.getPage(i)).getViewport({ scale: 1 });
|
|
96
|
+
sizes.push({ width: vp.width, height: vp.height });
|
|
97
|
+
}
|
|
98
|
+
return { doc, sizes };
|
|
99
|
+
})(),
|
|
100
|
+
OPEN_TIMEOUT_MS,
|
|
101
|
+
'PDF를 여는 데 너무 오래 걸립니다',
|
|
102
|
+
() => void task.destroy()
|
|
103
|
+
);
|
|
104
|
+
return {
|
|
105
|
+
kind: 'pdf',
|
|
106
|
+
count: doc.numPages,
|
|
107
|
+
/** 0부터. 배율 1의 크기 (CSS px) */
|
|
108
|
+
pageSize: (i) => sizes[i],
|
|
109
|
+
/**
|
|
110
|
+
* i쪽을 target에 그린다 (배율 scale, 화면 픽셀 밀도만큼 선명하게). 그리는 중에 다시 부르면 앞의 것은 취소
|
|
111
|
+
* @param {number} i
|
|
112
|
+
* @param {HTMLElement} target
|
|
113
|
+
* @param {number} scale
|
|
114
|
+
* @param {{ textLayer?: boolean }} [opts]
|
|
115
|
+
*/
|
|
116
|
+
async render(i, target, scale, opts = {}) {
|
|
117
|
+
const page = await doc.getPage(i + 1);
|
|
118
|
+
const viewport = page.getViewport({ scale });
|
|
119
|
+
const ratio = Math.min(globalThis.devicePixelRatio || 1, 3);
|
|
120
|
+
const canvas = document.createElement('canvas');
|
|
121
|
+
canvas.width = Math.floor(viewport.width * ratio);
|
|
122
|
+
canvas.height = Math.floor(viewport.height * ratio);
|
|
123
|
+
canvas.style.width = `${viewport.width}px`;
|
|
124
|
+
canvas.style.height = `${viewport.height}px`;
|
|
125
|
+
const box = document.createElement('div');
|
|
126
|
+
box.className = 'dc-pdf-page';
|
|
127
|
+
box.style.width = `${viewport.width}px`;
|
|
128
|
+
box.style.height = `${viewport.height}px`;
|
|
129
|
+
// pdf.js 글자 층이 읽는 CSS 변수
|
|
130
|
+
box.style.setProperty('--total-scale-factor', String(scale));
|
|
131
|
+
box.style.setProperty('--scale-round-x', '1px');
|
|
132
|
+
box.style.setProperty('--scale-round-y', '1px');
|
|
133
|
+
box.append(canvas);
|
|
134
|
+
target.__dcTask?.cancel();
|
|
135
|
+
const task = page.render({
|
|
136
|
+
canvas,
|
|
137
|
+
viewport,
|
|
138
|
+
transform: ratio === 1 ? undefined : [ratio, 0, 0, ratio, 0, 0],
|
|
139
|
+
});
|
|
140
|
+
target.__dcTask = task;
|
|
141
|
+
try {
|
|
142
|
+
await task.promise;
|
|
143
|
+
} catch (e) {
|
|
144
|
+
if (e?.name === 'RenderingCancelledException') return false;
|
|
145
|
+
throw e;
|
|
146
|
+
} finally {
|
|
147
|
+
if (target.__dcTask === task) target.__dcTask = null;
|
|
148
|
+
}
|
|
149
|
+
if (opts.textLayer !== false) {
|
|
150
|
+
const layer = document.createElement('div');
|
|
151
|
+
layer.className = 'textLayer';
|
|
152
|
+
box.append(layer);
|
|
153
|
+
await new pdfjs.TextLayer({
|
|
154
|
+
textContentSource: page.streamTextContent(),
|
|
155
|
+
container: layer,
|
|
156
|
+
viewport,
|
|
157
|
+
}).render();
|
|
158
|
+
}
|
|
159
|
+
target.replaceChildren(box);
|
|
160
|
+
return true;
|
|
161
|
+
},
|
|
162
|
+
/**
|
|
163
|
+
* 모든 쪽을 작게 그린 것 (편집 화면 왼쪽 목록). 폭 width(px). 쪽마다 빈 틀을 바로 주고 그림은 차례로 채운다
|
|
164
|
+
* @param {number} width
|
|
165
|
+
* @returns {Promise<HTMLElement[]>}
|
|
166
|
+
*/
|
|
167
|
+
async thumbnails(width) {
|
|
168
|
+
const boxes = sizes.map((s) => {
|
|
169
|
+
const box = document.createElement('div');
|
|
170
|
+
box.className = 'dc-pdf-thumb';
|
|
171
|
+
box.style.width = `${width}px`;
|
|
172
|
+
box.style.height = `${Math.round((width * s.height) / s.width)}px`;
|
|
173
|
+
return box;
|
|
174
|
+
});
|
|
175
|
+
void (async () => {
|
|
176
|
+
for (let i = 0; i < boxes.length; i += 1) {
|
|
177
|
+
const page = await doc.getPage(i + 1);
|
|
178
|
+
const viewport = page.getViewport({ scale: (width * 2) / sizes[i].width });
|
|
179
|
+
const canvas = document.createElement('canvas');
|
|
180
|
+
canvas.width = Math.floor(viewport.width);
|
|
181
|
+
canvas.height = Math.floor(viewport.height);
|
|
182
|
+
await page.render({ canvas, viewport }).promise.catch(() => undefined);
|
|
183
|
+
boxes[i].replaceChildren(canvas);
|
|
184
|
+
}
|
|
185
|
+
})();
|
|
186
|
+
return boxes;
|
|
187
|
+
},
|
|
188
|
+
destroy: () => void task.destroy(),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// core/pptx-edit.js 타입 (편집기 자동완성 · 테스트용)
|
|
2
|
+
export interface TextShape {
|
|
3
|
+
/** 도형 ref, 표 칸이면 표 ref + row · col */
|
|
4
|
+
ref: { shapeId: number; row?: number; col?: number };
|
|
5
|
+
text: string;
|
|
6
|
+
box: { x: number; y: number; w: number; h: number };
|
|
7
|
+
/** 표 칸: 줄 · 칸, index는 그 줄에서 그려지는 칸(병합으로 가려진 칸 뺌) 중 몇 번째 */
|
|
8
|
+
cell?: { row: number; col: number; index: number };
|
|
9
|
+
}
|
|
10
|
+
export declare function readTextShapes(bytes: Uint8Array): Promise<TextShape[][]>;
|
|
11
|
+
export declare function applyTextEdits(
|
|
12
|
+
bytes: Uint8Array,
|
|
13
|
+
edits: Array<{ ref: object; text: string }>
|
|
14
|
+
): Promise<Uint8Array>;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// PPTX 글자 고치기 (편집 화면만, 고치지 않습니다). @office-kit/pptx로 파일을 읽고 쓰고,
|
|
2
|
+
// @office-kit/pptx-editor의 headless 편집(setShapeText · setTableCellText)으로 글자를 바꿉니다. 바꾸지 않은 글자의 서식은 그대로 두고,
|
|
3
|
+
// 글자 말고 다른 요소(그림 · 도형 · 표 틀 · 차트)는 원래 파일 그대로입니다.
|
|
4
|
+
//
|
|
5
|
+
// 에디터 화면 전체(mountEditor, 리본 · 메뉴가 있는 발표 자료 편집기)는 쓰지 않습니다: 시안은 "슬라이드의 글자를 눌러
|
|
6
|
+
// 바로 고침"만 보이고, 화면 전체 편집기는 번들이 수 MB 더 큽니다. 학생 화면은 이 파일을 부르지 않습니다.
|
|
7
|
+
import {
|
|
8
|
+
getGroupChildren,
|
|
9
|
+
getGroupTransform,
|
|
10
|
+
getShapeId,
|
|
11
|
+
getShapeKind,
|
|
12
|
+
getShapeXmlString,
|
|
13
|
+
getSlides,
|
|
14
|
+
getSlideShapes,
|
|
15
|
+
getSlideSize,
|
|
16
|
+
getTableCell,
|
|
17
|
+
getTableCellSpan,
|
|
18
|
+
loadPresentation,
|
|
19
|
+
savePresentation,
|
|
20
|
+
} from '@office-kit/pptx';
|
|
21
|
+
import { applyAgentEdits, decodeAgentEdits, readForAgent } from '@office-kit/pptx-editor/headless';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 그룹 안 도형의 위치를 슬라이드 좌표로 옮기는 함수 (도형 id마다).
|
|
25
|
+
* @office-kit 도형 위치는 그룹 안 좌표(chOff · chExt 기준)라, 그룹을 옮기거나 늘리면(off ≠ chOff, ext ≠ chExt) 그려진 위치와 다르다.
|
|
26
|
+
* 렌더러처럼 slide = outer + (child − inner) × outer / inner를 그룹마다 바깥으로 거듭 적용한다
|
|
27
|
+
* @param {object} slide
|
|
28
|
+
* @returns {Map<number, (b: { x: number, y: number, w: number, h: number }) => { x: number, y: number, w: number, h: number }>}
|
|
29
|
+
*/
|
|
30
|
+
function groupProjections(slide) {
|
|
31
|
+
const out = new Map();
|
|
32
|
+
const visit = (group, outer) => {
|
|
33
|
+
const t = getGroupTransform(group);
|
|
34
|
+
const sx = t && t.inner.w ? t.outer.w / t.inner.w : 1;
|
|
35
|
+
const sy = t && t.inner.h ? t.outer.h / t.inner.h : 1;
|
|
36
|
+
const project = b =>
|
|
37
|
+
outer(
|
|
38
|
+
t
|
|
39
|
+
? {
|
|
40
|
+
x: t.outer.x + (b.x - t.inner.x) * sx,
|
|
41
|
+
y: t.outer.y + (b.y - t.inner.y) * sy,
|
|
42
|
+
w: b.w * sx,
|
|
43
|
+
h: b.h * sy,
|
|
44
|
+
}
|
|
45
|
+
: b
|
|
46
|
+
);
|
|
47
|
+
for (const child of getGroupChildren(group)) {
|
|
48
|
+
out.set(getShapeId(child), project);
|
|
49
|
+
if (getShapeKind(child) === 'group') visit(child, project);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
// 슬라이드 도형 목록에는 그룹 안 도형도 들어 있다: 맨 바깥 그룹에서만 시작
|
|
53
|
+
for (const shape of getSlideShapes(slide)) {
|
|
54
|
+
if (getShapeKind(shape) === 'group' && !out.has(getShapeId(shape))) visit(shape, b => b);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 글자가 필드(<a:fld>: 날짜 · 슬라이드 번호 등)뿐인 도형. PowerPoint가 열 때 채우는 글자라 고칠 것이 아니고,
|
|
61
|
+
* 고치면 필드가 평문이 되어 더는 바뀌지 않는다 (@office-kit setShapeText는 고친 곳이 필드에 걸치면 평문으로 씀).
|
|
62
|
+
* 글자와 필드가 섞인 도형은 고칠 수 있다 (필드를 건드리지 않으면 필드는 그대로)
|
|
63
|
+
* @param {object} shape
|
|
64
|
+
*/
|
|
65
|
+
function isFieldOnly(shape) {
|
|
66
|
+
const xml = getShapeXmlString(shape);
|
|
67
|
+
return /<a:fld\b/.test(xml) && !/<a:r>(?:(?!<\/a:r>)[\s\S])*?<a:t>[^<]*\S/.test(xml);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 슬라이드마다 고칠 수 있는 글자 (위치는 슬라이드 크기에 대한 비율 0~1): 글자가 있는 도형과 표 칸.
|
|
72
|
+
* 표 칸은 ref가 칸(표 ref + row · col)이고 box는 표 전체, cell.index는 그 줄에서 그려지는 칸 중 몇 번째인지
|
|
73
|
+
* (병합으로 가려진 칸 hMerge · vMerge는 렌더러가 그리지 않으므로 빼고 셈). 빈 칸도 넣는다 (글자를 새로 쓸 수 있게).
|
|
74
|
+
* 필드뿐인 도형(날짜 · 슬라이드 번호)은 뺀다
|
|
75
|
+
* @param {Uint8Array} bytes
|
|
76
|
+
* @returns {Promise<Array<Array<{ ref: object, text: string, box: { x: number, y: number, w: number, h: number }, cell?: { row: number, col: number, index: number } }>>>}
|
|
77
|
+
*/
|
|
78
|
+
export async function readTextShapes(bytes) {
|
|
79
|
+
const pres = await loadPresentation(bytes);
|
|
80
|
+
const { width, height } = getSlideSize(pres);
|
|
81
|
+
const { slides } = readForAgent(pres, null);
|
|
82
|
+
const models = getSlides(pres);
|
|
83
|
+
return slides.map((slide, i) => {
|
|
84
|
+
const model = models[slide.index ?? i];
|
|
85
|
+
const projections = groupProjections(model);
|
|
86
|
+
const byId = new Map(getSlideShapes(model).map(s => [getShapeId(s), s]));
|
|
87
|
+
const items = [];
|
|
88
|
+
for (const s of slide.shapes) {
|
|
89
|
+
if (!s.bounds || !s.shape) continue;
|
|
90
|
+
const b = projections.get(s.shape.shapeId)?.(s.bounds) ?? s.bounds;
|
|
91
|
+
const box = { x: b.x / width, y: b.y / height, w: b.w / width, h: b.h / height };
|
|
92
|
+
const shape = byId.get(s.shape.shapeId);
|
|
93
|
+
if (s.kind === 'table') {
|
|
94
|
+
if (!shape || !Array.isArray(s.cells)) continue;
|
|
95
|
+
s.cells.forEach((row, r) => {
|
|
96
|
+
let index = 0;
|
|
97
|
+
row.forEach((text, c) => {
|
|
98
|
+
const span = getTableCellSpan(getTableCell(shape, r, c));
|
|
99
|
+
if (span.hMerge || span.vMerge) return;
|
|
100
|
+
items.push({
|
|
101
|
+
ref: { ...s.shape, row: r, col: c },
|
|
102
|
+
text,
|
|
103
|
+
box,
|
|
104
|
+
cell: { row: r, col: c, index },
|
|
105
|
+
});
|
|
106
|
+
index += 1;
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
} else if (typeof s.text === 'string' && !(shape && isFieldOnly(shape))) {
|
|
110
|
+
items.push({ ref: s.shape, text: s.text, box });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return items;
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 원래 파일에 글자 바꾸기를 모두 적용한 새 파일
|
|
119
|
+
* @param {Uint8Array} bytes 원래 파일
|
|
120
|
+
* @param {Array<{ ref: object, text: string }>} edits 도형 · 표 칸마다 바꾼 전체 글자 (줄은 \n). 표 칸은 ref에 row · col이 있다
|
|
121
|
+
* @returns {Promise<Uint8Array>}
|
|
122
|
+
*/
|
|
123
|
+
export async function applyTextEdits(bytes, edits) {
|
|
124
|
+
const pres = await loadPresentation(bytes);
|
|
125
|
+
// 한 번에 50개까지 받는다 (headless 편집 묶음 한도)
|
|
126
|
+
for (let i = 0; i < edits.length; i += 50) {
|
|
127
|
+
const batch = edits
|
|
128
|
+
.slice(i, i + 50)
|
|
129
|
+
.map(e =>
|
|
130
|
+
typeof e.ref.row === 'number'
|
|
131
|
+
? { tool: 'setTableCellText', input: { cell: e.ref, text: e.text } }
|
|
132
|
+
: { tool: 'setShapeText', input: { shape: e.ref, value: e.text } }
|
|
133
|
+
);
|
|
134
|
+
await applyAgentEdits(pres, decodeAgentEdits(batch).edits);
|
|
135
|
+
}
|
|
136
|
+
return savePresentation(pres);
|
|
137
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// core/pptx-fonts.js 타입 (편집기 자동완성 · 테스트용)
|
|
2
|
+
export declare function slideFontFamily(value: string): string;
|
|
3
|
+
export declare function applySlideFonts(root: Element): void;
|
|
4
|
+
export declare function fontFaceCss(base?: string): string;
|
|
5
|
+
export declare function installSlideFonts(doc?: Document): void;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/*! 슬라이드 글꼴 (zip의 fonts/, SIL Open Font License 1.1, 원본 파일 그대로):
|
|
2
|
+
Carlito 5.3.0 (npm @fontsource/carlito, fonts/OFL-Carlito.txt), Caladea 5.3.0 (npm @fontsource/caladea, fonts/OFL-Caladea.txt) */
|
|
3
|
+
// PPTX 슬라이드 글꼴 (고치지 않습니다). 슬라이드가 쓰는 글꼴이 이 PC에 없을 때 비슷한 글꼴로 그린다:
|
|
4
|
+
// - Calibri → Carlito, Cambria → Caladea (글자 폭이 같은 대체 글꼴: 줄바꿈 · 위치가 PowerPoint와 같게).
|
|
5
|
+
// 넣은 것은 보통 · 굵게의 latin 범위뿐 (기울임은 브라우저가 기울여 그리고, 그 밖 글자는 이 PC 글꼴로)
|
|
6
|
+
// - 한글은 넣지 않고 이 PC 글꼴로: 고딕은 맑은 고딕 · Apple SD Gothic Neo · Noto Sans KR, 명조 글꼴(Cambria 등) 안 한글은
|
|
7
|
+
// 바탕 · AppleMyungjo · Noto Serif KR (한글 글꼴은 용량이 커서 넣지 않음)
|
|
8
|
+
// 렌더러는 run마다 글꼴 목록을 적는데(예: "Calibri, Aptos, …, system-ui, 等线, …"), 한글이 목록 중간의 system-ui나
|
|
9
|
+
// 중국어 글꼴로 먼저 가므로 첫 글꼴 바로 뒤에 대체 글꼴과 한글 글꼴 이름을 넣는다 (slideFontFamily).
|
|
10
|
+
// 이 PC에 진짜 Calibri가 있으면 목록 앞이라 그것을 쓴다. @font-face는 쓰일 때만 받는다 (렌더러 fontFaces 옵션은 바로 받음).
|
|
11
|
+
|
|
12
|
+
/** Carlito · Caladea latin 범위 (fontsource unicode.json) */
|
|
13
|
+
const LATIN_RANGE =
|
|
14
|
+
'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD';
|
|
15
|
+
/** [family, 파일, weight] */
|
|
16
|
+
const LATIN_FACES = [
|
|
17
|
+
['Carlito', 'carlito-latin-400-normal.woff2', 400],
|
|
18
|
+
['Carlito', 'carlito-latin-700-normal.woff2', 700],
|
|
19
|
+
['Caladea', 'caladea-latin-400-normal.woff2', 400],
|
|
20
|
+
['Caladea', 'caladea-latin-700-normal.woff2', 700],
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
/** 글자 폭이 같은 대체 글꼴 */
|
|
24
|
+
const SUBSTITUTES = { calibri: 'Carlito', cambria: 'Caladea' };
|
|
25
|
+
/** 명조 계열 글꼴 (그 run 안 한글을 명조로) */
|
|
26
|
+
const SERIF = new Set([
|
|
27
|
+
'cambria',
|
|
28
|
+
'georgia',
|
|
29
|
+
'times new roman',
|
|
30
|
+
'times',
|
|
31
|
+
'garamond',
|
|
32
|
+
'book antiqua',
|
|
33
|
+
'palatino linotype',
|
|
34
|
+
'palatino',
|
|
35
|
+
'constantia',
|
|
36
|
+
'century',
|
|
37
|
+
'century schoolbook',
|
|
38
|
+
'baskerville old face',
|
|
39
|
+
'bodoni mt',
|
|
40
|
+
'batang',
|
|
41
|
+
'바탕',
|
|
42
|
+
'바탕체',
|
|
43
|
+
'batangche',
|
|
44
|
+
'gungsuh',
|
|
45
|
+
'궁서',
|
|
46
|
+
'serif',
|
|
47
|
+
]);
|
|
48
|
+
/** 이 PC의 한글 글꼴 (이름만, 넣지 않음) */
|
|
49
|
+
const SANS_KO = ['맑은 고딕', 'Malgun Gothic', 'Apple SD Gothic Neo', 'Noto Sans KR'];
|
|
50
|
+
const SERIF_KO = ['바탕', 'Batang', 'AppleMyungjo', 'Noto Serif KR'];
|
|
51
|
+
|
|
52
|
+
/** font-family 값을 글꼴 이름 목록으로 (따옴표 · 쉼표) */
|
|
53
|
+
function splitFamilies(value) {
|
|
54
|
+
const out = [];
|
|
55
|
+
for (const m of value.matchAll(
|
|
56
|
+
/\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^,]+))\s*(?:,|$)/g
|
|
57
|
+
)) {
|
|
58
|
+
const name = (m[1] ?? m[2] ?? m[3] ?? '').trim();
|
|
59
|
+
if (name) out.push(name);
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
const quote = name => (/^[a-z-]+$/i.test(name) ? name : `"${name.replace(/"/g, '\\"')}"`);
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 렌더러가 적은 글꼴 목록에 대체 · 한글 글꼴을 넣은 목록. 첫 글꼴(파일의 글꼴) 바로 뒤에 넣는다 (두 번 해도 같음)
|
|
67
|
+
* @param {string} value CSS font-family
|
|
68
|
+
*/
|
|
69
|
+
export function slideFontFamily(value) {
|
|
70
|
+
const names = splitFamilies(value);
|
|
71
|
+
if (names.length === 0) return value;
|
|
72
|
+
const first = names[0];
|
|
73
|
+
const key = first.toLowerCase();
|
|
74
|
+
const sub = SUBSTITUTES[key];
|
|
75
|
+
const added = [...(sub ? [sub] : []), ...(SERIF.has(key) ? SERIF_KO : SANS_KO)].filter(
|
|
76
|
+
n => n.toLowerCase() !== key
|
|
77
|
+
);
|
|
78
|
+
const lower = new Set(added.map(n => n.toLowerCase()));
|
|
79
|
+
const rest = names.slice(1).filter(n => !lower.has(n.toLowerCase()));
|
|
80
|
+
return [first, ...added, ...rest].map(quote).join(', ');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 그린 슬라이드의 글자 요소마다 글꼴 목록을 바꾼다 (렌더러가 쓰는 style · SVG font-family 속성)
|
|
85
|
+
* @param {Element} root
|
|
86
|
+
*/
|
|
87
|
+
export function applySlideFonts(root) {
|
|
88
|
+
const els = [root, ...root.querySelectorAll('[style*="font-family"], [font-family]')];
|
|
89
|
+
for (const el of els) {
|
|
90
|
+
const style = /** @type {HTMLElement} */ (el).style;
|
|
91
|
+
if (style?.fontFamily) style.fontFamily = slideFontFamily(style.fontFamily);
|
|
92
|
+
const attr = el.getAttribute('font-family');
|
|
93
|
+
if (attr) el.setAttribute('font-family', slideFontFamily(attr));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** @font-face 규칙 (글꼴 파일은 문서 기준 fonts/: zip 최상위, 원본 public/fonts/) */
|
|
98
|
+
export function fontFaceCss(base = 'fonts/') {
|
|
99
|
+
return LATIN_FACES.map(
|
|
100
|
+
([family, file, weight]) =>
|
|
101
|
+
`@font-face{font-family:${family};font-style:normal;font-weight:${weight};font-display:swap;` +
|
|
102
|
+
`src:url(${base}${file}) format("woff2");unicode-range:${LATIN_RANGE}}`
|
|
103
|
+
).join('\n');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
let installed = false;
|
|
107
|
+
/** 글꼴 규칙을 문서에 한 번 넣는다 (PPTX를 열 때만: PDF · 다른 화면은 받지 않음) */
|
|
108
|
+
export function installSlideFonts(doc = document) {
|
|
109
|
+
if (installed || !doc?.head) return;
|
|
110
|
+
installed = true;
|
|
111
|
+
const style = doc.createElement('style');
|
|
112
|
+
style.dataset.dcPptxFonts = '';
|
|
113
|
+
style.textContent = fontFaceCss();
|
|
114
|
+
doc.head.append(style);
|
|
115
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// core/pptx-media.js 타입 (편집기 자동완성 · 테스트용)
|
|
2
|
+
export declare function shapeFillRelIds(xml: string): string[];
|
|
3
|
+
export declare function shapeFillTargets(
|
|
4
|
+
files: { slides: Map<string, string>; slideLayouts: Map<string, string>; slideMasters: Map<string, string> },
|
|
5
|
+
pres: {
|
|
6
|
+
slides: Array<{
|
|
7
|
+
slidePath: string;
|
|
8
|
+
layoutIndex: string;
|
|
9
|
+
rels: Map<string, { target: string; targetMode?: string }>;
|
|
10
|
+
showMasterSp?: boolean;
|
|
11
|
+
}>;
|
|
12
|
+
layouts: Map<string, { rels: Map<string, { target: string; targetMode?: string }>; showMasterSp?: boolean }>;
|
|
13
|
+
masters: Map<string, { rels: Map<string, { target: string; targetMode?: string }> }>;
|
|
14
|
+
layoutToMaster: Map<string, string>;
|
|
15
|
+
},
|
|
16
|
+
i: number,
|
|
17
|
+
cache: Map<string, string[]>
|
|
18
|
+
): string[];
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// 슬라이드를 그리기 전에 미리 읽어 둘 그림 (고치지 않습니다). core/pptx-view.js가 부릅니다.
|
|
2
|
+
//
|
|
3
|
+
// 그림은 그 슬라이드를 그릴 때 읽는다(parseZipLazyMedia). 그런데 @aiden0z/pptx-renderer 1.4.0은 도형 그림 채우기
|
|
4
|
+
// (p:spPr의 a:blipFill)를 그릴 때 그림을 이미 읽었는지만 보고(동기), 아직이면 그림을 나중에 기본 채우기(p:style fillRef) 밑에
|
|
5
|
+
// 넣어 그림이 가려진다. 그래서 그 슬라이드 · 레이아웃 · 마스터의 도형 그림 채우기가 가리키는 그림만 그리기 전에 읽어 둔다.
|
|
6
|
+
// 배경 · 글자 그림 채우기 · 그림(p:pic)은 렌더러가 읽은 뒤 제자리에 넣으므로 미리 읽지 않는다 (첫 쪽이 늦지 않게).
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 슬라이드 XML에서 도형 그림 채우기(spPr > blipFill > blip)의 관계 id (r:embed · r:link)
|
|
10
|
+
* @param {string} xml slide · slideLayout · slideMaster XML
|
|
11
|
+
* @returns {string[]}
|
|
12
|
+
*/
|
|
13
|
+
export function shapeFillRelIds(xml) {
|
|
14
|
+
// 빠른 확인: blipFill이 없으면 XML을 읽지 않는다
|
|
15
|
+
if (!xml || !xml.includes('blipFill')) return [];
|
|
16
|
+
const doc = new DOMParser().parseFromString(xml, 'application/xml');
|
|
17
|
+
const ids = new Set();
|
|
18
|
+
// 접두어(a: · r:)는 파일마다 다를 수 있어 이름 끝(localName)으로 찾는다
|
|
19
|
+
for (const fill of doc.getElementsByTagName('*')) {
|
|
20
|
+
if (fill.localName !== 'blipFill' || fill.parentElement?.localName !== 'spPr') continue;
|
|
21
|
+
const blip = [...fill.children].find(c => c.localName === 'blip');
|
|
22
|
+
const attrs = blip ? [...blip.attributes] : [];
|
|
23
|
+
const ref = name => attrs.find(a => a.name.split(':').pop() === name)?.value;
|
|
24
|
+
const id = ref('embed') || ref('link');
|
|
25
|
+
if (id) ids.add(id);
|
|
26
|
+
}
|
|
27
|
+
return [...ids];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* i번째 슬라이드를 그리기 전에 읽어 둘 그림 주소 (관계 target, 파일 안의 것만). 슬라이드 · 레이아웃 · 마스터 순.
|
|
32
|
+
* 레이아웃 · 마스터 결과는 cache에 둔다 (여러 슬라이드가 같이 씀)
|
|
33
|
+
* @param {{ slides: Map<string, string>, slideLayouts: Map<string, string>, slideMasters: Map<string, string> }} files parseZipLazyMedia 결과
|
|
34
|
+
* @param {{ slides: Array<{ slidePath: string, layoutIndex: string, rels: Map<string, { target: string, targetMode?: string }>, showMasterSp?: boolean }>, layouts: Map<string, { rels: Map<string, { target: string, targetMode?: string }>, showMasterSp?: boolean }>, masters: Map<string, { rels: Map<string, { target: string, targetMode?: string }> }>, layoutToMaster: Map<string, string> }} pres
|
|
35
|
+
* @param {number} i
|
|
36
|
+
* @param {Map<string, string[]>} cache
|
|
37
|
+
* @returns {string[]}
|
|
38
|
+
*/
|
|
39
|
+
export function shapeFillTargets(files, pres, i, cache) {
|
|
40
|
+
const slide = pres.slides[i];
|
|
41
|
+
if (!slide) return [];
|
|
42
|
+
const parts = [
|
|
43
|
+
{
|
|
44
|
+
path: slide.slidePath,
|
|
45
|
+
xml: files.slides.get(slide.slidePath),
|
|
46
|
+
rels: slide.rels,
|
|
47
|
+
shared: false,
|
|
48
|
+
},
|
|
49
|
+
];
|
|
50
|
+
const layout = pres.layouts.get(slide.layoutIndex);
|
|
51
|
+
if (layout) {
|
|
52
|
+
parts.push({
|
|
53
|
+
path: slide.layoutIndex,
|
|
54
|
+
xml: files.slideLayouts.get(slide.layoutIndex),
|
|
55
|
+
rels: layout.rels,
|
|
56
|
+
shared: true,
|
|
57
|
+
});
|
|
58
|
+
const masterPath = pres.layoutToMaster.get(slide.layoutIndex);
|
|
59
|
+
const master = masterPath ? pres.masters.get(masterPath) : undefined;
|
|
60
|
+
// 마스터 도형을 감춘 슬라이드 · 레이아웃이면 마스터 그림은 읽지 않는다
|
|
61
|
+
if (master && slide.showMasterSp !== false && layout.showMasterSp !== false)
|
|
62
|
+
parts.push({
|
|
63
|
+
path: masterPath,
|
|
64
|
+
xml: files.slideMasters.get(masterPath),
|
|
65
|
+
rels: master.rels,
|
|
66
|
+
shared: true,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const targets = new Set();
|
|
70
|
+
for (const part of parts) {
|
|
71
|
+
let list = part.shared ? cache.get(part.path) : undefined;
|
|
72
|
+
if (!list) {
|
|
73
|
+
list = [];
|
|
74
|
+
for (const id of shapeFillRelIds(part.xml ?? '')) {
|
|
75
|
+
const rel = part.rels?.get(id);
|
|
76
|
+
if (rel?.target && rel.targetMode?.trim().toLowerCase() !== 'external') list.push(rel.target);
|
|
77
|
+
}
|
|
78
|
+
if (part.shared) cache.set(part.path, list);
|
|
79
|
+
}
|
|
80
|
+
for (const t of list) targets.add(t);
|
|
81
|
+
}
|
|
82
|
+
return [...targets];
|
|
83
|
+
}
|