@celljs/ta-office 0.0.0-stage → 4.39.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.
- package/README.en.md +12 -0
- package/README.md +11 -2
- package/extension/index.mjs +2256 -0
- package/package.json +59 -4
- package/web/index.js +6108 -0
|
@@ -0,0 +1,2256 @@
|
|
|
1
|
+
// web-src/extension.ts
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
// ../ta-protocol/esm/common/ta-extension-host.js
|
|
6
|
+
var TA_CLOUD_OUTPUT_BYTES = 1024 * 1024;
|
|
7
|
+
var TA_HOST_EVENT = "ta:host";
|
|
8
|
+
var TaHostUtil;
|
|
9
|
+
(function(TaHostUtil2) {
|
|
10
|
+
TaHostUtil2.WAIT_MS = 1000;
|
|
11
|
+
function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
let heard = false;
|
|
14
|
+
let answered = false;
|
|
15
|
+
const timer = setTimeout(() => resolve(undefined), waitMs);
|
|
16
|
+
const request = {
|
|
17
|
+
name,
|
|
18
|
+
heard: () => {
|
|
19
|
+
heard = true;
|
|
20
|
+
},
|
|
21
|
+
resolve: (answer) => {
|
|
22
|
+
answered = true;
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
resolve(answer);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
events.emit(TA_HOST_EVENT, request);
|
|
28
|
+
if (!heard && !answered) {
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
resolve(undefined);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
TaHostUtil2.reach = reach;
|
|
35
|
+
function marked(systemPrompt, mark) {
|
|
36
|
+
return role(systemPrompt).includes(mark);
|
|
37
|
+
}
|
|
38
|
+
TaHostUtil2.marked = marked;
|
|
39
|
+
function role(systemPrompt) {
|
|
40
|
+
if (!systemPrompt) {
|
|
41
|
+
return "";
|
|
42
|
+
}
|
|
43
|
+
const open = `<addendum>
|
|
44
|
+
`;
|
|
45
|
+
const start = systemPrompt.indexOf(open);
|
|
46
|
+
const context = systemPrompt.indexOf(`<project_context>
|
|
47
|
+
`);
|
|
48
|
+
if (start < 0 || context >= 0 && context < start) {
|
|
49
|
+
return "";
|
|
50
|
+
}
|
|
51
|
+
const end = systemPrompt.indexOf(`
|
|
52
|
+
</addendum>`, start);
|
|
53
|
+
return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
|
|
54
|
+
}
|
|
55
|
+
TaHostUtil2.role = role;
|
|
56
|
+
})(TaHostUtil || (TaHostUtil = {}));
|
|
57
|
+
var TA_DOUBLE_LOOK = {
|
|
58
|
+
name: "@celljs/ta-web",
|
|
59
|
+
key: "assistant.species",
|
|
60
|
+
given: ["trex", "triceratops", "stegosaurus", "brachiosaurus", "velociraptor", "ankylosaurus", "pteranodon", "parasaurolophus"]
|
|
61
|
+
};
|
|
62
|
+
var TaDoubleLookUtil;
|
|
63
|
+
(function(TaDoubleLookUtil2) {
|
|
64
|
+
function given(id) {
|
|
65
|
+
let hash = 2166136261;
|
|
66
|
+
for (let i = 0;i < id.length; i++) {
|
|
67
|
+
hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
|
|
68
|
+
}
|
|
69
|
+
return TA_DOUBLE_LOOK.given[(hash >>> 0) % TA_DOUBLE_LOOK.given.length];
|
|
70
|
+
}
|
|
71
|
+
TaDoubleLookUtil2.given = given;
|
|
72
|
+
})(TaDoubleLookUtil || (TaDoubleLookUtil = {}));
|
|
73
|
+
|
|
74
|
+
// web-src/office-protocol.ts
|
|
75
|
+
var NAME = "@celljs/ta-office";
|
|
76
|
+
var DOC = "ta-doc";
|
|
77
|
+
var SLIDES = "ta-slides";
|
|
78
|
+
var SHEET = "ta-sheet";
|
|
79
|
+
var LANGUAGES = [DOC, SLIDES, SHEET];
|
|
80
|
+
var FILES = { [DOC]: "docx", [SLIDES]: "pptx", [SHEET]: "xlsx" };
|
|
81
|
+
var OfficeMarks;
|
|
82
|
+
((OfficeMarks) => {
|
|
83
|
+
OfficeMarks.PAGE_BREAK = "<!-- pagebreak -->";
|
|
84
|
+
OfficeMarks.COLUMN = "<!-- column -->";
|
|
85
|
+
OfficeMarks.LAYOUT = /^<!--\s*layout:\s*([a-z-]+)\s*-->$/;
|
|
86
|
+
OfficeMarks.COMMENT = /^<!--[\s\S]*-->$/;
|
|
87
|
+
})(OfficeMarks ||= {});
|
|
88
|
+
var OfficeLimits;
|
|
89
|
+
((OfficeLimits) => {
|
|
90
|
+
OfficeLimits.FILE = 50 * 1024 * 1024;
|
|
91
|
+
OfficeLimits.INFLATED = 200 * 1024 * 1024;
|
|
92
|
+
OfficeLimits.CODE = 900 * 1024;
|
|
93
|
+
OfficeLimits.ROWS = 5000;
|
|
94
|
+
OfficeLimits.COLUMNS = 200;
|
|
95
|
+
OfficeLimits.SHOWN = 200;
|
|
96
|
+
OfficeLimits.PREVIEW = 12;
|
|
97
|
+
})(OfficeLimits ||= {});
|
|
98
|
+
var OfficeFiles;
|
|
99
|
+
((OfficeFiles) => {
|
|
100
|
+
function languageOf(name2) {
|
|
101
|
+
const extension = /\.(docx|pptx|xlsx)$/i.exec(name2)?.[1]?.toLowerCase();
|
|
102
|
+
return extension ? LANGUAGES.find((language) => FILES[language] === extension) : undefined;
|
|
103
|
+
}
|
|
104
|
+
OfficeFiles.languageOf = languageOf;
|
|
105
|
+
OfficeFiles.TYPES = {
|
|
106
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
107
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
108
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
|
109
|
+
};
|
|
110
|
+
function name(title, language) {
|
|
111
|
+
const base = title.replace(/[\\/:*?"<>|\s]+/g, " ").trim().slice(0, 80) || "Ta";
|
|
112
|
+
return `${base}.${FILES[language]}`;
|
|
113
|
+
}
|
|
114
|
+
OfficeFiles.name = name;
|
|
115
|
+
})(OfficeFiles ||= {});
|
|
116
|
+
|
|
117
|
+
// web-src/office-prompt.ts
|
|
118
|
+
var OFFICE_PROMPT = `When the user wants a document, a deck of slides or a sheet (a report, a plan, a letter, a talk, a budget, a bill to split, a table to fill in), write it as a fenced block Ta draws as one, not as Markdown of the reply; they view it, point at a part for you to change, change words and values themselves, and export it as Word, PowerPoint or Excel:
|
|
119
|
+
- ${DOC}: Markdown (headings, paragraphs, lists, tables, quotes, code); \`<!-- pagebreak -->\` on a line of its own starts a page.
|
|
120
|
+
- ${SLIDES}: Markdown, a slide at each line \`---\`; each starts with its \`# title\`, then a few short points. A slide may begin with \`<!-- layout: title|content|two|image|number -->\` (a title alone, a title over its points, two columns split at a line \`<!-- column -->\`, a picture beside the points, one big number as its title with a line under it); without, it is read from what the slide holds. Aim at one idea a slide and at most six points.
|
|
121
|
+
- ${SHEET}: JSON {"title"?: string, "sheets": [{"name": string, "cells": [["Item", "Price"], ["Tea", "12.5"], ["Total", "=SUM(B2:B3)"]], "formats"?: {"B2:B9": "#,##0.00"}}]}: cells by row, as text; a cell starting with = is a formula (+ - * / ^ & %, comparisons, A1 references and ranges, Sheet!A1 of another sheet, SUM AVERAGE COUNT MIN MAX IF ROUND are worked out in Ta; any other is shown as written and worked out once exported); formats are number formats by range (0, 0.00, #,##0, 0%, 0.0%). The first row is the head.
|
|
122
|
+
Words in the user's language. To read a .docx, .pptx or .xlsx file of the workspace, use the tool office_read, which gives it as such a block; to make one, write the block and save it with office_write.`;
|
|
123
|
+
|
|
124
|
+
// ../ta-protocol/esm/common/zip.js
|
|
125
|
+
var CRC_TABLE = (() => {
|
|
126
|
+
const table = new Uint32Array(256);
|
|
127
|
+
for (let n = 0;n < 256; n++) {
|
|
128
|
+
let c = n;
|
|
129
|
+
for (let k = 0;k < 8; k++) {
|
|
130
|
+
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
131
|
+
}
|
|
132
|
+
table[n] = c >>> 0;
|
|
133
|
+
}
|
|
134
|
+
return table;
|
|
135
|
+
})();
|
|
136
|
+
var ZIP_MAX_BYTES = 4294967295;
|
|
137
|
+
var ZIP_MAX_ENTRIES = 65535;
|
|
138
|
+
var ZipUtil;
|
|
139
|
+
(function(ZipUtil2) {
|
|
140
|
+
ZipUtil2.READ_MAX = 256 * 1024 * 1024;
|
|
141
|
+
function crc32(data) {
|
|
142
|
+
let crc = 4294967295;
|
|
143
|
+
for (let i = 0;i < data.length; i++) {
|
|
144
|
+
crc = CRC_TABLE[(crc ^ data[i]) & 255] ^ crc >>> 8;
|
|
145
|
+
}
|
|
146
|
+
return (crc ^ 4294967295) >>> 0;
|
|
147
|
+
}
|
|
148
|
+
ZipUtil2.crc32 = crc32;
|
|
149
|
+
function dosTime(date) {
|
|
150
|
+
const year = Math.max(1980, date.getFullYear());
|
|
151
|
+
return [
|
|
152
|
+
date.getHours() << 11 | date.getMinutes() << 5 | Math.floor(date.getSeconds() / 2),
|
|
153
|
+
year - 1980 << 9 | date.getMonth() + 1 << 5 | date.getDate()
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
async function create(entries, deflate) {
|
|
157
|
+
var _a;
|
|
158
|
+
if (entries.length > ZIP_MAX_ENTRIES) {
|
|
159
|
+
throw new Error(`An archive holds at most ${ZIP_MAX_ENTRIES} files.`);
|
|
160
|
+
}
|
|
161
|
+
const encoder = new TextEncoder;
|
|
162
|
+
const locals = [];
|
|
163
|
+
const centrals = [];
|
|
164
|
+
let offset = 0;
|
|
165
|
+
for (const entry of entries) {
|
|
166
|
+
const name = encoder.encode(entry.path.replace(/^\/+/, ""));
|
|
167
|
+
const crc = crc32(entry.data);
|
|
168
|
+
const deflated = deflate && entry.data.length > 0 ? await deflate(entry.data) : undefined;
|
|
169
|
+
const compressed = deflated && deflated.length < entry.data.length ? deflated : entry.data;
|
|
170
|
+
const method = compressed === entry.data ? 0 : 8;
|
|
171
|
+
const [time, date] = dosTime((_a = entry.modified) !== null && _a !== undefined ? _a : new Date);
|
|
172
|
+
if (offset + 30 + name.length + compressed.length > ZIP_MAX_BYTES) {
|
|
173
|
+
throw new Error("An archive holds at most 4 GB.");
|
|
174
|
+
}
|
|
175
|
+
const header = (signature, central) => {
|
|
176
|
+
const view = new DataView(new ArrayBuffer(central ? 46 : 30));
|
|
177
|
+
let at2 = 0;
|
|
178
|
+
const u16 = (value) => {
|
|
179
|
+
view.setUint16(at2, value, true);
|
|
180
|
+
at2 += 2;
|
|
181
|
+
};
|
|
182
|
+
const u32 = (value) => {
|
|
183
|
+
view.setUint32(at2, value >>> 0, true);
|
|
184
|
+
at2 += 4;
|
|
185
|
+
};
|
|
186
|
+
u32(signature);
|
|
187
|
+
if (central) {
|
|
188
|
+
u16(20);
|
|
189
|
+
}
|
|
190
|
+
u16(20);
|
|
191
|
+
u16(2048);
|
|
192
|
+
u16(method);
|
|
193
|
+
u16(time);
|
|
194
|
+
u16(date);
|
|
195
|
+
u32(crc);
|
|
196
|
+
u32(compressed.length);
|
|
197
|
+
u32(entry.data.length);
|
|
198
|
+
u16(name.length);
|
|
199
|
+
u16(0);
|
|
200
|
+
if (central) {
|
|
201
|
+
u16(0);
|
|
202
|
+
u16(0);
|
|
203
|
+
u16(0);
|
|
204
|
+
u32(0);
|
|
205
|
+
u32(offset);
|
|
206
|
+
}
|
|
207
|
+
return new Uint8Array(view.buffer);
|
|
208
|
+
};
|
|
209
|
+
const local = header(67324752, false);
|
|
210
|
+
locals.push(local, name, compressed);
|
|
211
|
+
centrals.push(header(33639248, true), name);
|
|
212
|
+
offset += local.length + name.length + compressed.length;
|
|
213
|
+
}
|
|
214
|
+
const centralSize = centrals.reduce((sum, part) => sum + part.length, 0);
|
|
215
|
+
const end = new DataView(new ArrayBuffer(22));
|
|
216
|
+
end.setUint32(0, 101010256, true);
|
|
217
|
+
end.setUint16(8, entries.length, true);
|
|
218
|
+
end.setUint16(10, entries.length, true);
|
|
219
|
+
end.setUint32(12, centralSize, true);
|
|
220
|
+
end.setUint32(16, offset, true);
|
|
221
|
+
const parts = [...locals, ...centrals, new Uint8Array(end.buffer)];
|
|
222
|
+
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
223
|
+
let at = 0;
|
|
224
|
+
for (const part of parts) {
|
|
225
|
+
out.set(part, at);
|
|
226
|
+
at += part.length;
|
|
227
|
+
}
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
ZipUtil2.create = create;
|
|
231
|
+
function browserDeflate() {
|
|
232
|
+
const Stream = stream("CompressionStream");
|
|
233
|
+
return Stream && ((data) => pipe(new Stream("deflate-raw"), data));
|
|
234
|
+
}
|
|
235
|
+
ZipUtil2.browserDeflate = browserDeflate;
|
|
236
|
+
function browserInflate() {
|
|
237
|
+
const Stream = stream("DecompressionStream");
|
|
238
|
+
return Stream && ((data, max) => pipe(new Stream("deflate-raw"), data, max));
|
|
239
|
+
}
|
|
240
|
+
ZipUtil2.browserInflate = browserInflate;
|
|
241
|
+
async function read(zip, options = {}) {
|
|
242
|
+
var _a, _b;
|
|
243
|
+
const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
|
|
244
|
+
let end = -1;
|
|
245
|
+
for (let at2 = zip.length - 22;at2 >= Math.max(0, zip.length - 22 - 65535); at2--) {
|
|
246
|
+
if (view.getUint32(at2, true) === 101010256) {
|
|
247
|
+
end = at2;
|
|
248
|
+
break;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (end < 0) {
|
|
252
|
+
throw new Error("This is not a zip archive.");
|
|
253
|
+
}
|
|
254
|
+
const count = view.getUint16(end + 10, true);
|
|
255
|
+
let at = view.getUint32(end + 16, true);
|
|
256
|
+
const decoder = new TextDecoder;
|
|
257
|
+
const files = new Map;
|
|
258
|
+
const max = (_a = options.maxBytes) !== null && _a !== undefined ? _a : ZipUtil2.READ_MAX;
|
|
259
|
+
let total = 0;
|
|
260
|
+
for (let i = 0;i < count; i++) {
|
|
261
|
+
if (at + 46 > zip.length || view.getUint32(at, true) !== 33639248) {
|
|
262
|
+
throw new Error("The archive is broken.");
|
|
263
|
+
}
|
|
264
|
+
const method = view.getUint16(at + 10, true);
|
|
265
|
+
const compressed = view.getUint32(at + 20, true);
|
|
266
|
+
const size = view.getUint32(at + 24, true);
|
|
267
|
+
const nameLength = view.getUint16(at + 28, true);
|
|
268
|
+
const skip = nameLength + view.getUint16(at + 30, true) + view.getUint16(at + 32, true);
|
|
269
|
+
const local = view.getUint32(at + 42, true);
|
|
270
|
+
const path = decoder.decode(zip.subarray(at + 46, at + 46 + nameLength));
|
|
271
|
+
at += 46 + skip;
|
|
272
|
+
if (path.endsWith("/") || options.only && !options.only(path)) {
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
total += size;
|
|
276
|
+
if (total > max) {
|
|
277
|
+
throw new Error("The archive holds too much.");
|
|
278
|
+
}
|
|
279
|
+
if (local + 30 > zip.length || view.getUint32(local, true) !== 67324752) {
|
|
280
|
+
throw new Error("The archive is broken.");
|
|
281
|
+
}
|
|
282
|
+
const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);
|
|
283
|
+
const stored = zip.subarray(start, start + compressed);
|
|
284
|
+
if (method === 0) {
|
|
285
|
+
files.set(path, stored);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const inflate = (_b = options.inflate) !== null && _b !== undefined ? _b : browserInflate();
|
|
289
|
+
if (method !== 8 || !inflate) {
|
|
290
|
+
throw new Error(`${path} is compressed in a way that cannot be read here.`);
|
|
291
|
+
}
|
|
292
|
+
const data = await inflate(stored, size);
|
|
293
|
+
if (data.length !== size) {
|
|
294
|
+
throw new Error("The archive is broken.");
|
|
295
|
+
}
|
|
296
|
+
files.set(path, data);
|
|
297
|
+
}
|
|
298
|
+
return files;
|
|
299
|
+
}
|
|
300
|
+
ZipUtil2.read = read;
|
|
301
|
+
function stream(name) {
|
|
302
|
+
return globalThis[name];
|
|
303
|
+
}
|
|
304
|
+
async function pipe(stream2, data, max) {
|
|
305
|
+
const writer = stream2.writable.getWriter();
|
|
306
|
+
writer.write(data).then(() => writer.close()).catch(() => {
|
|
307
|
+
return;
|
|
308
|
+
});
|
|
309
|
+
if (max === undefined) {
|
|
310
|
+
return new Uint8Array(await new Response(stream2.readable).arrayBuffer());
|
|
311
|
+
}
|
|
312
|
+
const reader = stream2.readable.getReader();
|
|
313
|
+
const chunks = [];
|
|
314
|
+
let length = 0;
|
|
315
|
+
for (let read2 = await reader.read();!read2.done; read2 = await reader.read()) {
|
|
316
|
+
length += read2.value.length;
|
|
317
|
+
if (length > max) {
|
|
318
|
+
await reader.cancel().catch(() => {
|
|
319
|
+
return;
|
|
320
|
+
});
|
|
321
|
+
throw new Error("The archive is broken: a file inflates past the size it says.");
|
|
322
|
+
}
|
|
323
|
+
chunks.push(read2.value);
|
|
324
|
+
}
|
|
325
|
+
const out = new Uint8Array(length);
|
|
326
|
+
let at = 0;
|
|
327
|
+
for (const chunk of chunks) {
|
|
328
|
+
out.set(chunk, at);
|
|
329
|
+
at += chunk.length;
|
|
330
|
+
}
|
|
331
|
+
return out;
|
|
332
|
+
}
|
|
333
|
+
})(ZipUtil || (ZipUtil = {}));
|
|
334
|
+
|
|
335
|
+
// web-src/md-blocks.ts
|
|
336
|
+
var FENCE = /^ {0,3}(`{3,}|~{3,})/;
|
|
337
|
+
var HEADING = /^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/;
|
|
338
|
+
var RULE = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/;
|
|
339
|
+
var ITEM = /^(\s*)([-*+]|\d{1,9}[.)])(\s+|$)/;
|
|
340
|
+
var QUOTE = /^ {0,3}>/;
|
|
341
|
+
var TABLE_RULE = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
|
|
342
|
+
var MdBlocks;
|
|
343
|
+
((MdBlocks) => {
|
|
344
|
+
function split(text, from = 0, to) {
|
|
345
|
+
const lines = text.split(`
|
|
346
|
+
`);
|
|
347
|
+
const end = to ?? lines.length;
|
|
348
|
+
const blocks = [];
|
|
349
|
+
const add = (kind, start, stop, extra = {}) => blocks.push({ kind, start, end: stop, source: lines.slice(start, stop).join(`
|
|
350
|
+
`), ...extra });
|
|
351
|
+
let at = from;
|
|
352
|
+
while (at < end) {
|
|
353
|
+
const line = lines[at];
|
|
354
|
+
if (!line.trim()) {
|
|
355
|
+
at++;
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const fence = FENCE.exec(line);
|
|
359
|
+
if (fence) {
|
|
360
|
+
const close = new RegExp(`^ {0,3}${fence[1][0] === "`" ? "`" : "~"}{${fence[1].length},}\\s*$`);
|
|
361
|
+
let stop2 = at + 1;
|
|
362
|
+
while (stop2 < end && !close.test(lines[stop2])) {
|
|
363
|
+
stop2++;
|
|
364
|
+
}
|
|
365
|
+
add("code", at, Math.min(end, stop2 + 1));
|
|
366
|
+
at = stop2 + 1;
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
const heading = HEADING.exec(line);
|
|
370
|
+
if (heading) {
|
|
371
|
+
add("heading", at, at + 1, { level: heading[1].length, text: heading[2] ?? "" });
|
|
372
|
+
at++;
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
if (OfficeMarks.COMMENT.test(line.trim())) {
|
|
376
|
+
add("comment", at, at + 1);
|
|
377
|
+
at++;
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
if (RULE.test(line)) {
|
|
381
|
+
add("rule", at, at + 1);
|
|
382
|
+
at++;
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
if (line.includes("|") && at + 1 < end && TABLE_RULE.test(lines[at + 1]) && lines[at + 1].includes("-")) {
|
|
386
|
+
let stop2 = at + 2;
|
|
387
|
+
while (stop2 < end && lines[stop2].includes("|") && lines[stop2].trim()) {
|
|
388
|
+
stop2++;
|
|
389
|
+
}
|
|
390
|
+
add("table", at, stop2);
|
|
391
|
+
at = stop2;
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
if (QUOTE.test(line)) {
|
|
395
|
+
let stop2 = at + 1;
|
|
396
|
+
while (stop2 < end && lines[stop2].trim() && (QUOTE.test(lines[stop2]) || !starts(lines[stop2]))) {
|
|
397
|
+
stop2++;
|
|
398
|
+
}
|
|
399
|
+
add("quote", at, stop2);
|
|
400
|
+
at = stop2;
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
if (ITEM.test(line)) {
|
|
404
|
+
let stop2 = at + 1;
|
|
405
|
+
for (;; ) {
|
|
406
|
+
while (stop2 < end && lines[stop2].trim() && (ITEM.test(lines[stop2]) || !starts(lines[stop2]))) {
|
|
407
|
+
stop2++;
|
|
408
|
+
}
|
|
409
|
+
let next = stop2;
|
|
410
|
+
while (next < end && !lines[next].trim()) {
|
|
411
|
+
next++;
|
|
412
|
+
}
|
|
413
|
+
if (next > stop2 && next < end && (ITEM.test(lines[next]) || /^\s{2,}\S/.test(lines[next]))) {
|
|
414
|
+
stop2 = next;
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
add("list", at, stop2);
|
|
420
|
+
at = stop2;
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
let stop = at + 1;
|
|
424
|
+
while (stop < end && lines[stop].trim() && !starts(lines[stop])) {
|
|
425
|
+
stop++;
|
|
426
|
+
}
|
|
427
|
+
add("paragraph", at, stop);
|
|
428
|
+
at = stop;
|
|
429
|
+
}
|
|
430
|
+
return blocks;
|
|
431
|
+
}
|
|
432
|
+
MdBlocks.split = split;
|
|
433
|
+
function replace(text, block, source) {
|
|
434
|
+
const lines = text.split(`
|
|
435
|
+
`);
|
|
436
|
+
lines.splice(block.start, block.end - block.start, ...source.split(`
|
|
437
|
+
`));
|
|
438
|
+
return lines.join(`
|
|
439
|
+
`);
|
|
440
|
+
}
|
|
441
|
+
MdBlocks.replace = replace;
|
|
442
|
+
function editable(block) {
|
|
443
|
+
if (block.kind === "heading") {
|
|
444
|
+
return block.text ?? "";
|
|
445
|
+
}
|
|
446
|
+
return block.kind === "paragraph" || block.kind === "list" || block.kind === "quote" ? block.source : undefined;
|
|
447
|
+
}
|
|
448
|
+
MdBlocks.editable = editable;
|
|
449
|
+
function edited(block, text) {
|
|
450
|
+
if (block.kind === "heading") {
|
|
451
|
+
return `${"#".repeat(block.level ?? 1)} ${text.replace(/\s*\n\s*/g, " ").trim()}`;
|
|
452
|
+
}
|
|
453
|
+
return text.replace(/\n{2,}/g, `
|
|
454
|
+
`).trimEnd();
|
|
455
|
+
}
|
|
456
|
+
MdBlocks.edited = edited;
|
|
457
|
+
function plain(source) {
|
|
458
|
+
return source.replace(/^\s*(#{1,6}|>|[-*+]|\d+[.)])\s+/gm, "").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[*_`~]+/g, "").replace(/\s+/g, " ").trim();
|
|
459
|
+
}
|
|
460
|
+
MdBlocks.plain = plain;
|
|
461
|
+
function starts(line) {
|
|
462
|
+
return FENCE.test(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || ITEM.test(line) || OfficeMarks.COMMENT.test(line.trim());
|
|
463
|
+
}
|
|
464
|
+
})(MdBlocks ||= {});
|
|
465
|
+
|
|
466
|
+
// web-src/doc-model.ts
|
|
467
|
+
var DocModel;
|
|
468
|
+
((DocModel) => {
|
|
469
|
+
function pages(code) {
|
|
470
|
+
const pages2 = [{ parts: [] }];
|
|
471
|
+
const counts = [];
|
|
472
|
+
let path = "";
|
|
473
|
+
let under = 0;
|
|
474
|
+
for (const block of MdBlocks.split(code)) {
|
|
475
|
+
if (block.kind === "comment") {
|
|
476
|
+
if (block.source.trim() === OfficeMarks.PAGE_BREAK && pages2[pages2.length - 1].parts.length) {
|
|
477
|
+
pages2.push({ parts: [] });
|
|
478
|
+
}
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (block.kind === "heading") {
|
|
482
|
+
const level = block.level ?? 1;
|
|
483
|
+
counts.length = level;
|
|
484
|
+
counts[level - 1] = (counts[level - 1] ?? 0) + 1;
|
|
485
|
+
path = Array.from(counts, (count) => count ?? 0).join(".");
|
|
486
|
+
under = 0;
|
|
487
|
+
pages2[pages2.length - 1].parts.push({ ...block, anchor: `h:${path}` });
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
under++;
|
|
491
|
+
pages2[pages2.length - 1].parts.push({ ...block, anchor: path ? `h:${path}/p:${under}` : `p:${under}` });
|
|
492
|
+
}
|
|
493
|
+
return pages2.filter((page, index) => page.parts.length || index === 0);
|
|
494
|
+
}
|
|
495
|
+
DocModel.pages = pages;
|
|
496
|
+
function title(code) {
|
|
497
|
+
const heading = MdBlocks.split(code).find((block) => block.kind === "heading");
|
|
498
|
+
return heading?.text ? MdBlocks.plain(heading.text) : undefined;
|
|
499
|
+
}
|
|
500
|
+
DocModel.title = title;
|
|
501
|
+
})(DocModel ||= {});
|
|
502
|
+
|
|
503
|
+
// web-src/md-text.ts
|
|
504
|
+
var MdText;
|
|
505
|
+
((MdText) => {
|
|
506
|
+
function join(spans2) {
|
|
507
|
+
const merged = [];
|
|
508
|
+
for (const span of spans2) {
|
|
509
|
+
const last = merged[merged.length - 1];
|
|
510
|
+
if (last && !!last.bold === !!span.bold && !!last.italic === !!span.italic && !!last.code === !!span.code && last.link === span.link) {
|
|
511
|
+
last.text += span.text;
|
|
512
|
+
} else if (span.text) {
|
|
513
|
+
merged.push({ ...span });
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return merged.map((span) => {
|
|
517
|
+
const [, before, words, after] = /^(\s*)([\s\S]*?)(\s*)$/.exec(span.text);
|
|
518
|
+
if (!words) {
|
|
519
|
+
return span.text;
|
|
520
|
+
}
|
|
521
|
+
let text = span.code ? `\`${words}\`` : literal(words);
|
|
522
|
+
const mark = span.code ? "" : `${span.bold ? "**" : ""}${span.italic ? "*" : ""}`;
|
|
523
|
+
text = mark && !words.includes(`
|
|
524
|
+
`) ? `${mark}${text}${[...mark].reverse().join("")}` : text;
|
|
525
|
+
return `${before}${span.link ? `[${text}](${span.link.replace(/[()\s]/g, encodeURIComponent)})` : text}${after}`;
|
|
526
|
+
}).join("");
|
|
527
|
+
}
|
|
528
|
+
MdText.join = join;
|
|
529
|
+
function literal(text) {
|
|
530
|
+
return text.replace(/([\\*`]|\[(?=[^\]]*\]\())/g, "\\$1");
|
|
531
|
+
}
|
|
532
|
+
MdText.literal = literal;
|
|
533
|
+
function escapeLine(text) {
|
|
534
|
+
return text.replace(/^(\s*)(#{1,6}\s|>|[-+*]\s|\d{1,9}[.)]\s|\|)/gm, (_, space, mark) => `${space}\\${mark}`);
|
|
535
|
+
}
|
|
536
|
+
MdText.escapeLine = escapeLine;
|
|
537
|
+
function table(rows) {
|
|
538
|
+
const width = Math.max(1, ...rows.map((row) => row.length));
|
|
539
|
+
const line = (row) => `| ${Array.from({ length: width }, (_, index) => (row[index] ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ")).join(" | ")} |`;
|
|
540
|
+
const [head = [], ...body] = rows;
|
|
541
|
+
return [line(head), `|${" --- |".repeat(width)}`, ...body.map(line)].join(`
|
|
542
|
+
`);
|
|
543
|
+
}
|
|
544
|
+
MdText.table = table;
|
|
545
|
+
function cells(line) {
|
|
546
|
+
const inner = line.trim().replace(/^\|/, "").replace(/(?<!\\)\|$/, "");
|
|
547
|
+
return inner.split(/(?<!\\)\|/).map((cell) => cell.trim().replace(/\\\|/g, "|"));
|
|
548
|
+
}
|
|
549
|
+
MdText.cells = cells;
|
|
550
|
+
function spans(text, style = {}) {
|
|
551
|
+
const out = [];
|
|
552
|
+
let plain = "";
|
|
553
|
+
const flush = () => {
|
|
554
|
+
if (plain) {
|
|
555
|
+
out.push({ ...style, text: plain });
|
|
556
|
+
plain = "";
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
for (let i = 0;i < text.length; ) {
|
|
560
|
+
const rest = text.slice(i);
|
|
561
|
+
if (rest[0] === "\\" && /[!-/:-@[-`{-~]/.test(rest[1] ?? "")) {
|
|
562
|
+
plain += rest[1];
|
|
563
|
+
i += 2;
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
const code = /^(`+)([\s\S]*?[^`])\1(?!`)/.exec(rest);
|
|
567
|
+
const strong = /^(\*\*|__)(?=\S)([\s\S]*?\S)\1/.exec(rest);
|
|
568
|
+
const em = /^([*_])(?=\S)([\s\S]*?\S)\1(?![*_\w])/.exec(rest);
|
|
569
|
+
const link = /^!?\[([^\]]*)\]\(\s*<?([^)\s>]*)>?(?:\s+"[^"]*")?\s*\)/.exec(rest);
|
|
570
|
+
const br = /^<br\s*\/?>/i.exec(rest);
|
|
571
|
+
if (code) {
|
|
572
|
+
flush();
|
|
573
|
+
out.push({ ...style, text: code[2], code: true });
|
|
574
|
+
i += code[0].length;
|
|
575
|
+
} else if (strong) {
|
|
576
|
+
flush();
|
|
577
|
+
out.push(...spans(strong[2], { ...style, bold: true }));
|
|
578
|
+
i += strong[0].length;
|
|
579
|
+
} else if (em && (em[1] === "*" || !/\w/.test(text[i - 1] ?? ""))) {
|
|
580
|
+
flush();
|
|
581
|
+
out.push(...spans(em[2], { ...style, italic: true }));
|
|
582
|
+
i += em[0].length;
|
|
583
|
+
} else if (link) {
|
|
584
|
+
flush();
|
|
585
|
+
const picture = rest[0] === "!";
|
|
586
|
+
out.push(...spans(link[1], picture ? { ...style, italic: true } : { ...style, .../^(https?:|mailto:)/i.test(link[2]) ? { link: link[2] } : {} }));
|
|
587
|
+
i += link[0].length;
|
|
588
|
+
} else if (br) {
|
|
589
|
+
plain += `
|
|
590
|
+
`;
|
|
591
|
+
i += br[0].length;
|
|
592
|
+
} else {
|
|
593
|
+
plain += rest[0];
|
|
594
|
+
i++;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
flush();
|
|
598
|
+
return out;
|
|
599
|
+
}
|
|
600
|
+
MdText.spans = spans;
|
|
601
|
+
})(MdText ||= {});
|
|
602
|
+
|
|
603
|
+
// web-src/xml.ts
|
|
604
|
+
var ENTITIES = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" };
|
|
605
|
+
var TaXml;
|
|
606
|
+
((TaXml) => {
|
|
607
|
+
function parse(text2) {
|
|
608
|
+
const root = { name: "", attrs: {}, children: [] };
|
|
609
|
+
const stack = [root];
|
|
610
|
+
const tokens = /<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<[?!][^>]*>|<(\/?)([^\s/>]+)([^>]*?)(\/?)>|([^<]+)/g;
|
|
611
|
+
for (let match = tokens.exec(text2);match; match = tokens.exec(text2)) {
|
|
612
|
+
const top = stack[stack.length - 1];
|
|
613
|
+
if (match[1] !== undefined) {
|
|
614
|
+
top.children.push(match[1]);
|
|
615
|
+
} else if (match[6] !== undefined) {
|
|
616
|
+
top.children.push(decode(match[6]));
|
|
617
|
+
} else if (match[3] === undefined) {} else if (match[2]) {
|
|
618
|
+
const at = stack.map((node) => node.name).lastIndexOf(match[3]);
|
|
619
|
+
if (at > 0) {
|
|
620
|
+
stack.length = at;
|
|
621
|
+
}
|
|
622
|
+
} else {
|
|
623
|
+
const node = { name: match[3], attrs: attributes(match[4]), children: [] };
|
|
624
|
+
top.children.push(node);
|
|
625
|
+
if (!match[5]) {
|
|
626
|
+
stack.push(node);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return root.children.find((child) => typeof child !== "string") ?? root;
|
|
631
|
+
}
|
|
632
|
+
TaXml.parse = parse;
|
|
633
|
+
function kids(node, name) {
|
|
634
|
+
return (node?.children ?? []).filter((child) => typeof child !== "string" && (!name || child.name === name));
|
|
635
|
+
}
|
|
636
|
+
TaXml.kids = kids;
|
|
637
|
+
function find(node, name) {
|
|
638
|
+
for (const child of kids(node)) {
|
|
639
|
+
if (child.name === name) {
|
|
640
|
+
return child;
|
|
641
|
+
}
|
|
642
|
+
const found = find(child, name);
|
|
643
|
+
if (found) {
|
|
644
|
+
return found;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
TaXml.find = find;
|
|
650
|
+
function all(node, name, into = []) {
|
|
651
|
+
for (const child of kids(node)) {
|
|
652
|
+
if (child.name === name) {
|
|
653
|
+
into.push(child);
|
|
654
|
+
} else {
|
|
655
|
+
all(child, name, into);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return into;
|
|
659
|
+
}
|
|
660
|
+
TaXml.all = all;
|
|
661
|
+
function text(node) {
|
|
662
|
+
return (node?.children ?? []).map((child) => typeof child === "string" ? child : text(child)).join("");
|
|
663
|
+
}
|
|
664
|
+
TaXml.text = text;
|
|
665
|
+
function local(name) {
|
|
666
|
+
return name.slice(name.indexOf(":") + 1);
|
|
667
|
+
}
|
|
668
|
+
TaXml.local = local;
|
|
669
|
+
function encode(text2) {
|
|
670
|
+
return text2.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/[^\t\n\r\u0020-\ufffd\u{10000}-\u{10ffff}]/gu, "");
|
|
671
|
+
}
|
|
672
|
+
TaXml.encode = encode;
|
|
673
|
+
function attributes(text2) {
|
|
674
|
+
const attrs = {};
|
|
675
|
+
const pattern = /([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
|
|
676
|
+
for (let match = pattern.exec(text2);match; match = pattern.exec(text2)) {
|
|
677
|
+
attrs[match[1]] = decode(match[2] ?? match[3] ?? "");
|
|
678
|
+
}
|
|
679
|
+
return attrs;
|
|
680
|
+
}
|
|
681
|
+
function decode(text2) {
|
|
682
|
+
return text2.indexOf("&") < 0 ? text2 : text2.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (entity, name) => {
|
|
683
|
+
if (name[0] === "#") {
|
|
684
|
+
const code = name[1] === "x" || name[1] === "X" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1));
|
|
685
|
+
return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
|
|
686
|
+
}
|
|
687
|
+
return ENTITIES[name] ?? entity;
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
})(TaXml ||= {});
|
|
691
|
+
|
|
692
|
+
// web-src/read-docx.ts
|
|
693
|
+
var ReadDocx;
|
|
694
|
+
((ReadDocx) => {
|
|
695
|
+
function read(files) {
|
|
696
|
+
const document = files.get("word/document.xml");
|
|
697
|
+
if (!document) {
|
|
698
|
+
throw new Error("This is not a Word document.");
|
|
699
|
+
}
|
|
700
|
+
const context = {
|
|
701
|
+
headings: headings(files.get("word/styles.xml")),
|
|
702
|
+
...numbering(files.get("word/numbering.xml")),
|
|
703
|
+
links: links(files.get("word/_rels/document.xml.rels"))
|
|
704
|
+
};
|
|
705
|
+
const body = TaXml.find(TaXml.parse(document), "w:body");
|
|
706
|
+
const out = [];
|
|
707
|
+
let list;
|
|
708
|
+
for (const node of TaXml.kids(body)) {
|
|
709
|
+
if (node.name === "w:p") {
|
|
710
|
+
const { line, item, breaks } = paragraph(node, context);
|
|
711
|
+
if (line !== undefined) {
|
|
712
|
+
if (!item || item.list !== list?.list || item.again && item.num !== list.num) {
|
|
713
|
+
out.push("");
|
|
714
|
+
}
|
|
715
|
+
out.push(line);
|
|
716
|
+
list = item;
|
|
717
|
+
}
|
|
718
|
+
if (breaks) {
|
|
719
|
+
out.push("", OfficeMarks.PAGE_BREAK);
|
|
720
|
+
list = undefined;
|
|
721
|
+
}
|
|
722
|
+
} else if (node.name === "w:tbl") {
|
|
723
|
+
out.push("", table(node, context));
|
|
724
|
+
list = undefined;
|
|
725
|
+
} else if (node.name === "w:sdt") {
|
|
726
|
+
for (const p of TaXml.all(node, "w:p")) {
|
|
727
|
+
const { line } = paragraph(p, context);
|
|
728
|
+
if (line !== undefined) {
|
|
729
|
+
out.push("", line);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
const core = files.get("docProps/core.xml");
|
|
735
|
+
const title = core ? TaXml.text(TaXml.find(TaXml.parse(core), "dc:title")).trim() : "";
|
|
736
|
+
return {
|
|
737
|
+
code: out.join(`
|
|
738
|
+
`).replace(/^\n+/, "").replace(/\n{3,}/g, `
|
|
739
|
+
|
|
740
|
+
`),
|
|
741
|
+
...title ? { title } : {}
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
ReadDocx.read = read;
|
|
745
|
+
function paragraph(node, context) {
|
|
746
|
+
const props = TaXml.kids(node, "w:pPr")[0];
|
|
747
|
+
const style = TaXml.kids(props, "w:pStyle")[0]?.attrs["w:val"] ?? "";
|
|
748
|
+
const outline = TaXml.kids(props, "w:outlineLvl")[0]?.attrs["w:val"];
|
|
749
|
+
const level = context.headings.get(style) ?? (outline !== undefined && Number(outline) < 6 ? Number(outline) + 1 : undefined);
|
|
750
|
+
const breaks = TaXml.all(node, "w:br").some((br) => br.attrs["w:type"] === "page") || !!TaXml.kids(props, "w:pageBreakBefore").length;
|
|
751
|
+
const text = runs(node, context).trim();
|
|
752
|
+
if (!text) {
|
|
753
|
+
return { breaks };
|
|
754
|
+
}
|
|
755
|
+
if (level) {
|
|
756
|
+
return { line: `${"#".repeat(Math.min(6, level))} ${text.replace(/\s*\n\s*/g, " ")}`, breaks };
|
|
757
|
+
}
|
|
758
|
+
const number = TaXml.kids(props, "w:numPr")[0];
|
|
759
|
+
const id = TaXml.kids(number, "w:numId")[0]?.attrs["w:val"];
|
|
760
|
+
if (id && id !== "0") {
|
|
761
|
+
const depth = Number(TaXml.kids(number, "w:ilvl")[0]?.attrs["w:val"] ?? 0);
|
|
762
|
+
const mark = context.ordered.get(`${id}:${depth}`) ? "1." : "-";
|
|
763
|
+
return {
|
|
764
|
+
line: `${" ".repeat(depth)}${mark} ${text.replace(/\n/g, " ")}`,
|
|
765
|
+
item: { num: id, ...context.lists.get(id) ?? { list: id, again: false } },
|
|
766
|
+
breaks
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
const quote = /quote/i.test(style);
|
|
770
|
+
const escaped = MdText.escapeLine(text);
|
|
771
|
+
return { line: quote ? escaped.replace(/^/gm, "> ") : escaped, breaks };
|
|
772
|
+
}
|
|
773
|
+
function runs(node, context) {
|
|
774
|
+
const spans = [];
|
|
775
|
+
const walk = (parent, link) => {
|
|
776
|
+
for (const child of TaXml.kids(parent)) {
|
|
777
|
+
if (child.name === "w:r") {
|
|
778
|
+
const props = TaXml.kids(child, "w:rPr")[0];
|
|
779
|
+
const on = (name) => {
|
|
780
|
+
const flag = TaXml.kids(props, name)[0];
|
|
781
|
+
return !!flag && !["0", "false", "none"].includes(flag.attrs["w:val"] ?? "");
|
|
782
|
+
};
|
|
783
|
+
let text = "";
|
|
784
|
+
for (const part of TaXml.kids(child)) {
|
|
785
|
+
if (part.name === "w:t") {
|
|
786
|
+
text += TaXml.text(part);
|
|
787
|
+
} else if (part.name === "w:tab") {
|
|
788
|
+
text += " ";
|
|
789
|
+
} else if (part.name === "w:br" && part.attrs["w:type"] !== "page" || part.name === "w:cr") {
|
|
790
|
+
text += `
|
|
791
|
+
`;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const font = TaXml.kids(props, "w:rFonts")[0]?.attrs["w:ascii"] ?? "";
|
|
795
|
+
const code = /consolas|courier|mono|menlo/i.test(font) || TaXml.kids(props, "w:rStyle")[0]?.attrs["w:val"] === "Code";
|
|
796
|
+
spans.push({ text, bold: on("w:b"), italic: on("w:i"), ...code ? { code } : {}, ...link ? { link } : {} });
|
|
797
|
+
} else if (child.name === "w:hyperlink") {
|
|
798
|
+
const id = child.attrs["r:id"];
|
|
799
|
+
walk(child, id && context.links.get(id) || undefined);
|
|
800
|
+
} else if (child.name === "w:ins" || child.name === "w:smartTag" || child.name === "w:fldSimple" || child.name === "w:sdt" || child.name === "w:sdtContent") {
|
|
801
|
+
walk(child, link);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
walk(node);
|
|
806
|
+
return MdText.join(spans);
|
|
807
|
+
}
|
|
808
|
+
function table(node, context) {
|
|
809
|
+
const rows = TaXml.kids(node, "w:tr").map((row, index) => TaXml.kids(row, "w:tc").map((cell) => {
|
|
810
|
+
const text = TaXml.kids(cell, "w:p").map((p) => runs(p, context).trim()).filter(Boolean).join(" ");
|
|
811
|
+
return index === 0 ? text.replace(/^\*\*([^*]*)\*\*$/, "$1") : text;
|
|
812
|
+
}));
|
|
813
|
+
return MdText.table(rows);
|
|
814
|
+
}
|
|
815
|
+
function headings(styles) {
|
|
816
|
+
const map = new Map;
|
|
817
|
+
for (const style of TaXml.all(styles ? TaXml.parse(styles) : undefined, "w:style")) {
|
|
818
|
+
const id = style.attrs["w:styleId"];
|
|
819
|
+
const name = (TaXml.kids(style, "w:name")[0]?.attrs["w:val"] ?? "").toLowerCase();
|
|
820
|
+
const outline = TaXml.find(style, "w:outlineLvl")?.attrs["w:val"];
|
|
821
|
+
const level = name === "title" ? 1 : /^heading (\d)$/.exec(name)?.[1] ?? (outline !== undefined ? Number(outline) + 1 : undefined);
|
|
822
|
+
if (id && level !== undefined && Number(level) <= 6) {
|
|
823
|
+
map.set(id, Number(level));
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
for (let level = 1;level <= 6; level++) {
|
|
827
|
+
if (!map.has(`Heading${level}`)) {
|
|
828
|
+
map.set(`Heading${level}`, level);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
return map;
|
|
832
|
+
}
|
|
833
|
+
function numbering(xml) {
|
|
834
|
+
const root = xml ? TaXml.parse(xml) : undefined;
|
|
835
|
+
const abstract = new Map;
|
|
836
|
+
for (const node of TaXml.kids(root, "w:abstractNum")) {
|
|
837
|
+
const levels = new Map;
|
|
838
|
+
for (const level of TaXml.kids(node, "w:lvl")) {
|
|
839
|
+
const format = TaXml.kids(level, "w:numFmt")[0]?.attrs["w:val"] ?? "bullet";
|
|
840
|
+
levels.set(Number(level.attrs["w:ilvl"] ?? 0), format !== "bullet" && format !== "none");
|
|
841
|
+
}
|
|
842
|
+
abstract.set(node.attrs["w:abstractNumId"] ?? "", levels);
|
|
843
|
+
}
|
|
844
|
+
const ordered = new Map;
|
|
845
|
+
const lists = new Map;
|
|
846
|
+
for (const node of TaXml.kids(root, "w:num")) {
|
|
847
|
+
const id = TaXml.kids(node, "w:abstractNumId")[0]?.attrs["w:val"] ?? "";
|
|
848
|
+
lists.set(node.attrs["w:numId"], { list: id, again: TaXml.all(node, "w:startOverride").length > 0 });
|
|
849
|
+
for (const [level, isOrdered] of abstract.get(id) ?? []) {
|
|
850
|
+
ordered.set(`${node.attrs["w:numId"]}:${level}`, isOrdered);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
return { ordered, lists };
|
|
854
|
+
}
|
|
855
|
+
function links(xml) {
|
|
856
|
+
const map = new Map;
|
|
857
|
+
for (const rel of TaXml.kids(xml ? TaXml.parse(xml) : undefined, "Relationship")) {
|
|
858
|
+
if (rel.attrs.TargetMode === "External" && /^(https?:|mailto:)/i.test(rel.attrs.Target ?? "")) {
|
|
859
|
+
map.set(rel.attrs.Id, rel.attrs.Target);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
return map;
|
|
863
|
+
}
|
|
864
|
+
})(ReadDocx ||= {});
|
|
865
|
+
|
|
866
|
+
// web-src/read-pptx.ts
|
|
867
|
+
var ReadPptx;
|
|
868
|
+
((ReadPptx) => {
|
|
869
|
+
function read(files) {
|
|
870
|
+
const presentation = files.get("ppt/presentation.xml");
|
|
871
|
+
if (!presentation) {
|
|
872
|
+
throw new Error("This is not a PowerPoint deck.");
|
|
873
|
+
}
|
|
874
|
+
const rels = relations(files.get("ppt/_rels/presentation.xml.rels"));
|
|
875
|
+
const ids = TaXml.all(TaXml.parse(presentation), "p:sldId").map((node) => node.attrs["r:id"]);
|
|
876
|
+
const slides = [];
|
|
877
|
+
for (const id of ids) {
|
|
878
|
+
const target = rels.get(id);
|
|
879
|
+
const xml = target && files.get(`ppt/${target.replace(/^\.?\//, "").replace(/^\/?ppt\//, "")}`);
|
|
880
|
+
if (xml) {
|
|
881
|
+
const text = slide(xml);
|
|
882
|
+
if (text) {
|
|
883
|
+
slides.push(text);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
const core = files.get("docProps/core.xml");
|
|
888
|
+
const title = core ? TaXml.text(TaXml.find(TaXml.parse(core), "dc:title")).trim() : "";
|
|
889
|
+
return { code: slides.join(`
|
|
890
|
+
|
|
891
|
+
---
|
|
892
|
+
|
|
893
|
+
`), ...title ? { title } : {} };
|
|
894
|
+
}
|
|
895
|
+
ReadPptx.read = read;
|
|
896
|
+
function slide(xml) {
|
|
897
|
+
const tree = TaXml.find(TaXml.parse(xml), "p:spTree");
|
|
898
|
+
const boxes = [];
|
|
899
|
+
collect(tree, boxes);
|
|
900
|
+
const title = boxes.find((box) => box.kind === "title");
|
|
901
|
+
const rest = boxes.filter((box) => box !== title).sort((a, b) => a.y - b.y || a.x - b.x);
|
|
902
|
+
const bodies = rest.filter((box) => box.kind === "body" || box.kind === "text");
|
|
903
|
+
const side = bodies.length === 2 && Math.abs(bodies[0].y - bodies[1].y) < 400000 && Math.abs(bodies[0].x - bodies[1].x) > 1e6;
|
|
904
|
+
let layout;
|
|
905
|
+
if (side) {
|
|
906
|
+
layout = "two";
|
|
907
|
+
bodies.sort((a, b) => a.x - b.x);
|
|
908
|
+
} else if (title && rest.every((box) => box.kind === "subtitle")) {
|
|
909
|
+
layout = "title";
|
|
910
|
+
}
|
|
911
|
+
const out = [];
|
|
912
|
+
if (layout === "two") {
|
|
913
|
+
out.push(`<!-- layout: two -->`);
|
|
914
|
+
}
|
|
915
|
+
if (title) {
|
|
916
|
+
out.push(`# ${title.lines.join(" ").replace(/^\s*(#+|[-*]|\d+\.)\s+/, "").replace(/^\*\*([^*]*)\*\*$/, "$1")}`);
|
|
917
|
+
}
|
|
918
|
+
const ordered = side ? [...rest.filter((box) => !bodies.includes(box)), bodies[0], bodies[1]] : rest;
|
|
919
|
+
for (const box of ordered) {
|
|
920
|
+
if (side && box === bodies[1]) {
|
|
921
|
+
out.push(OfficeMarks.COLUMN);
|
|
922
|
+
}
|
|
923
|
+
if (box.lines.length) {
|
|
924
|
+
out.push(box.lines.join(`
|
|
925
|
+
`));
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
return out.join(`
|
|
929
|
+
|
|
930
|
+
`).trim();
|
|
931
|
+
}
|
|
932
|
+
function collect(parent, boxes) {
|
|
933
|
+
for (const node of TaXml.kids(parent)) {
|
|
934
|
+
if (node.name === "p:grpSp") {
|
|
935
|
+
collect(node, boxes);
|
|
936
|
+
} else if (node.name === "p:sp") {
|
|
937
|
+
const type = TaXml.find(TaXml.find(node, "p:nvSpPr"), "p:ph");
|
|
938
|
+
const named = /^(title|subtitle|body)\b/i.exec(TaXml.find(node, "p:cNvPr")?.attrs.name ?? "")?.[1].toLowerCase();
|
|
939
|
+
const kind = type?.attrs.type === "title" || type?.attrs.type === "ctrTitle" || !type && named === "title" ? "title" : type?.attrs.type === "subTitle" || !type && named === "subtitle" ? "subtitle" : type && (type.attrs.type === "body" || type.attrs.type === undefined || type.attrs.type === "obj") || !type && named === "body" ? "body" : "text";
|
|
940
|
+
if (type && ["dt", "ftr", "sldNum", "hdr"].includes(type.attrs.type ?? "")) {
|
|
941
|
+
continue;
|
|
942
|
+
}
|
|
943
|
+
const lines = paragraphs(TaXml.find(node, "p:txBody"), kind === "body");
|
|
944
|
+
if (lines.length) {
|
|
945
|
+
boxes.push({ kind, ...where(node), lines });
|
|
946
|
+
}
|
|
947
|
+
} else if (node.name === "p:graphicFrame") {
|
|
948
|
+
const table = TaXml.find(node, "a:tbl");
|
|
949
|
+
if (table) {
|
|
950
|
+
const rows = TaXml.kids(table, "a:tr").map((row) => TaXml.kids(row, "a:tc").map((cell) => paragraphs(TaXml.find(cell, "a:txBody"), false).join(" ")));
|
|
951
|
+
boxes.push({ kind: "table", ...where(node), lines: [MdText.table(rows)] });
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
function paragraphs(body, points) {
|
|
957
|
+
const lines = [];
|
|
958
|
+
for (const p of TaXml.kids(body, "a:p")) {
|
|
959
|
+
const props = TaXml.kids(p, "a:pPr")[0];
|
|
960
|
+
const spans = [];
|
|
961
|
+
for (const run of TaXml.kids(p)) {
|
|
962
|
+
if (run.name === "a:r" || run.name === "a:fld") {
|
|
963
|
+
const style = TaXml.kids(run, "a:rPr")[0];
|
|
964
|
+
spans.push({ text: TaXml.text(TaXml.kids(run, "a:t")[0]), bold: style?.attrs.b === "1", italic: style?.attrs.i === "1" });
|
|
965
|
+
} else if (run.name === "a:br") {
|
|
966
|
+
spans.push({ text: `
|
|
967
|
+
` });
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
const text = MdText.join(spans).trim();
|
|
971
|
+
if (!text) {
|
|
972
|
+
continue;
|
|
973
|
+
}
|
|
974
|
+
const plain = !!TaXml.kids(props, "a:buNone").length;
|
|
975
|
+
const numbered = !!TaXml.kids(props, "a:buAutoNum").length;
|
|
976
|
+
const level = Number(props?.attrs.lvl ?? 0);
|
|
977
|
+
if (points && !plain) {
|
|
978
|
+
lines.push(`${" ".repeat(level)}${numbered ? "1." : "-"} ${text.replace(/\n/g, " ")}`);
|
|
979
|
+
} else {
|
|
980
|
+
lines.push(MdText.escapeLine(text));
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
return points ? lines : lines.length > 1 ? [lines.join(`
|
|
984
|
+
|
|
985
|
+
`)] : lines;
|
|
986
|
+
}
|
|
987
|
+
function where(node) {
|
|
988
|
+
const off = TaXml.find(node, "a:off");
|
|
989
|
+
const ext = TaXml.find(node, "a:ext");
|
|
990
|
+
return { x: Number(off?.attrs.x ?? 0), y: Number(off?.attrs.y ?? 0), width: Number(ext?.attrs.cx ?? 0) };
|
|
991
|
+
}
|
|
992
|
+
function relations(xml) {
|
|
993
|
+
const map = new Map;
|
|
994
|
+
for (const rel of TaXml.kids(xml ? TaXml.parse(xml) : undefined, "Relationship")) {
|
|
995
|
+
map.set(rel.attrs.Id, rel.attrs.Target);
|
|
996
|
+
}
|
|
997
|
+
return map;
|
|
998
|
+
}
|
|
999
|
+
ReadPptx.relations = relations;
|
|
1000
|
+
})(ReadPptx ||= {});
|
|
1001
|
+
|
|
1002
|
+
// web-src/sheet-model.ts
|
|
1003
|
+
var SheetModel;
|
|
1004
|
+
((SheetModel) => {
|
|
1005
|
+
function parse(code) {
|
|
1006
|
+
const value = JSON.parse(code);
|
|
1007
|
+
if (!value || typeof value !== "object") {
|
|
1008
|
+
throw new Error("A sheet is a JSON object.");
|
|
1009
|
+
}
|
|
1010
|
+
const given = Array.isArray(value.sheets) ? value.sheets : Array.isArray(value.cells) ? [{ name: "Sheet1", cells: value.cells }] : [];
|
|
1011
|
+
const sheets = given.filter((sheet) => !!sheet && typeof sheet === "object" && Array.isArray(sheet.cells)).map((sheet, index) => ({
|
|
1012
|
+
name: typeof sheet.name === "string" && sheet.name.trim() ? sheet.name.trim() : `Sheet${index + 1}`,
|
|
1013
|
+
cells: sheet.cells.slice(0, OfficeLimits.ROWS).map((row) => Array.isArray(row) ? row.slice(0, OfficeLimits.COLUMNS).map(text) : []),
|
|
1014
|
+
...sheet.formats && typeof sheet.formats === "object" ? { formats: formats(sheet.formats) } : {}
|
|
1015
|
+
}));
|
|
1016
|
+
if (!sheets.length) {
|
|
1017
|
+
throw new Error('A sheet has "sheets": [{"name", "cells"}].');
|
|
1018
|
+
}
|
|
1019
|
+
return {
|
|
1020
|
+
...typeof value.work === "string" ? { work: value.work } : {},
|
|
1021
|
+
...typeof value.title === "string" ? { title: value.title } : {},
|
|
1022
|
+
sheets
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
SheetModel.parse = parse;
|
|
1026
|
+
function stringify(book) {
|
|
1027
|
+
const json = (value) => JSON.stringify(value);
|
|
1028
|
+
const sheets = book.sheets.map((sheet) => {
|
|
1029
|
+
const lines = [` {`, ` "name": ${json(sheet.name)},`];
|
|
1030
|
+
if (sheet.formats && Object.keys(sheet.formats).length) {
|
|
1031
|
+
lines.push(` "formats": ${json(sheet.formats)},`);
|
|
1032
|
+
}
|
|
1033
|
+
lines.push(` "cells": [`, sheet.cells.map((row) => ` ${json(row)}`).join(`,
|
|
1034
|
+
`), " ]", " }");
|
|
1035
|
+
return lines.filter((line) => line !== "").join(`
|
|
1036
|
+
`);
|
|
1037
|
+
});
|
|
1038
|
+
return [
|
|
1039
|
+
"{",
|
|
1040
|
+
...book.work !== undefined ? [` "work": ${json(book.work)},`] : [],
|
|
1041
|
+
...book.title !== undefined ? [` "title": ${json(book.title)},`] : [],
|
|
1042
|
+
' "sheets": [',
|
|
1043
|
+
sheets.join(`,
|
|
1044
|
+
`),
|
|
1045
|
+
" ]",
|
|
1046
|
+
"}"
|
|
1047
|
+
].join(`
|
|
1048
|
+
`);
|
|
1049
|
+
}
|
|
1050
|
+
SheetModel.stringify = stringify;
|
|
1051
|
+
function column(index) {
|
|
1052
|
+
let name2 = "";
|
|
1053
|
+
for (let n = index + 1;n > 0; n = Math.floor((n - 1) / 26)) {
|
|
1054
|
+
name2 = String.fromCharCode(65 + (n - 1) % 26) + name2;
|
|
1055
|
+
}
|
|
1056
|
+
return name2;
|
|
1057
|
+
}
|
|
1058
|
+
SheetModel.column = column;
|
|
1059
|
+
function at(ref) {
|
|
1060
|
+
const match = /^\$?([A-Za-z]{1,3})\$?(\d{1,7})$/.exec(ref.trim());
|
|
1061
|
+
if (!match) {
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const col = [...match[1].toUpperCase()].reduce((sum, letter) => sum * 26 + letter.charCodeAt(0) - 64, 0) - 1;
|
|
1065
|
+
const row = Number(match[2]) - 1;
|
|
1066
|
+
return row >= 0 ? { col, row } : undefined;
|
|
1067
|
+
}
|
|
1068
|
+
SheetModel.at = at;
|
|
1069
|
+
function name(at2) {
|
|
1070
|
+
return `${column(at2.col)}${at2.row + 1}`;
|
|
1071
|
+
}
|
|
1072
|
+
SheetModel.name = name;
|
|
1073
|
+
function range(text2) {
|
|
1074
|
+
const [a, b = a] = text2.split(":");
|
|
1075
|
+
const from = at(a);
|
|
1076
|
+
const to = at(b);
|
|
1077
|
+
if (!from || !to) {
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
return {
|
|
1081
|
+
from: { col: Math.min(from.col, to.col), row: Math.min(from.row, to.row) },
|
|
1082
|
+
to: { col: Math.max(from.col, to.col), row: Math.max(from.row, to.row) }
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
SheetModel.range = range;
|
|
1086
|
+
function formatOf(sheet, cell) {
|
|
1087
|
+
let found;
|
|
1088
|
+
for (const [key, format] of Object.entries(sheet.formats ?? {})) {
|
|
1089
|
+
const area = range(key) ?? (/^[A-Za-z]{1,3}$/.test(key) ? range(`${key}1:${key}${OfficeLimits.ROWS}`) : undefined);
|
|
1090
|
+
if (area && cell.col >= area.from.col && cell.col <= area.to.col && cell.row >= area.from.row && cell.row <= area.to.row) {
|
|
1091
|
+
found = format;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return found;
|
|
1095
|
+
}
|
|
1096
|
+
SheetModel.formatOf = formatOf;
|
|
1097
|
+
function width(sheet) {
|
|
1098
|
+
return sheet.cells.reduce((max, row) => Math.max(max, row.length), 0);
|
|
1099
|
+
}
|
|
1100
|
+
SheetModel.width = width;
|
|
1101
|
+
function withCell(book, sheet, cell, value) {
|
|
1102
|
+
return {
|
|
1103
|
+
...book,
|
|
1104
|
+
sheets: book.sheets.map((each, index) => {
|
|
1105
|
+
if (index !== sheet) {
|
|
1106
|
+
return each;
|
|
1107
|
+
}
|
|
1108
|
+
const cells = each.cells.map((row2) => [...row2]);
|
|
1109
|
+
while (cells.length <= cell.row) {
|
|
1110
|
+
cells.push([]);
|
|
1111
|
+
}
|
|
1112
|
+
const row = cells[cell.row];
|
|
1113
|
+
while (row.length < cell.col) {
|
|
1114
|
+
row.push("");
|
|
1115
|
+
}
|
|
1116
|
+
row[cell.col] = value;
|
|
1117
|
+
return { ...each, cells };
|
|
1118
|
+
})
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
SheetModel.withCell = withCell;
|
|
1122
|
+
function text(value) {
|
|
1123
|
+
return typeof value === "string" ? value : typeof value === "number" || typeof value === "boolean" ? String(value).toUpperCase() : "";
|
|
1124
|
+
}
|
|
1125
|
+
function formats(value) {
|
|
1126
|
+
return Object.fromEntries(Object.entries(value).filter(([, format]) => typeof format === "string"));
|
|
1127
|
+
}
|
|
1128
|
+
})(SheetModel ||= {});
|
|
1129
|
+
|
|
1130
|
+
// web-src/read-xlsx.ts
|
|
1131
|
+
var DATE_IDS = new Set([14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47]);
|
|
1132
|
+
var ReadXlsx;
|
|
1133
|
+
((ReadXlsx) => {
|
|
1134
|
+
function read(files) {
|
|
1135
|
+
const workbook = files.get("xl/workbook.xml");
|
|
1136
|
+
if (!workbook) {
|
|
1137
|
+
throw new Error("This is not an Excel workbook.");
|
|
1138
|
+
}
|
|
1139
|
+
const rels = ReadPptx.relations(files.get("xl/_rels/workbook.xml.rels"));
|
|
1140
|
+
const strings = shared(files.get("xl/sharedStrings.xml"));
|
|
1141
|
+
const styles = formats(files.get("xl/styles.xml"));
|
|
1142
|
+
const sheets = [];
|
|
1143
|
+
for (const node of TaXml.all(TaXml.parse(workbook), "sheet")) {
|
|
1144
|
+
const target = rels.get(node.attrs["r:id"]);
|
|
1145
|
+
const xml = target && files.get(target.startsWith("/") ? target.slice(1) : `xl/${target}`);
|
|
1146
|
+
if (xml && node.attrs.state !== "hidden" && node.attrs.state !== "veryHidden") {
|
|
1147
|
+
sheets.push(sheet(node.attrs.name ?? `Sheet${sheets.length + 1}`, xml, strings, styles));
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
if (!sheets.length) {
|
|
1151
|
+
sheets.push({ name: "Sheet1", cells: [] });
|
|
1152
|
+
}
|
|
1153
|
+
const core = files.get("docProps/core.xml");
|
|
1154
|
+
const title = core ? TaXml.text(TaXml.find(TaXml.parse(core), "dc:title")).trim() : "";
|
|
1155
|
+
return { code: SheetModel.stringify({ ...title ? { title } : {}, sheets }), ...title ? { title } : {} };
|
|
1156
|
+
}
|
|
1157
|
+
ReadXlsx.read = read;
|
|
1158
|
+
function sheet(name, xml, strings, styles) {
|
|
1159
|
+
const data = TaXml.find(TaXml.parse(xml), "sheetData");
|
|
1160
|
+
const cells = [];
|
|
1161
|
+
const formats2 = {};
|
|
1162
|
+
let next = 0;
|
|
1163
|
+
for (const row of TaXml.kids(data, "row")) {
|
|
1164
|
+
const r = row.attrs.r ? Number(row.attrs.r) - 1 : next;
|
|
1165
|
+
next = r + 1;
|
|
1166
|
+
if (r >= OfficeLimits.ROWS) {
|
|
1167
|
+
break;
|
|
1168
|
+
}
|
|
1169
|
+
let col = 0;
|
|
1170
|
+
for (const c of TaXml.kids(row, "c")) {
|
|
1171
|
+
const at = c.attrs.r && SheetModel.at(c.attrs.r) || { col, row: r };
|
|
1172
|
+
col = at.col + 1;
|
|
1173
|
+
if (at.col >= OfficeLimits.COLUMNS) {
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
const style = styles[Number(c.attrs.s ?? 0)];
|
|
1177
|
+
const text = value(c, strings, style?.date ?? false);
|
|
1178
|
+
if (text === "") {
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
while (cells.length <= r) {
|
|
1182
|
+
cells.push([]);
|
|
1183
|
+
}
|
|
1184
|
+
const line = cells[r];
|
|
1185
|
+
while (line.length < at.col) {
|
|
1186
|
+
line.push("");
|
|
1187
|
+
}
|
|
1188
|
+
line[at.col] = text;
|
|
1189
|
+
if (style?.format && !style.date && (text.startsWith("=") || /^-?[\d.]/.test(text))) {
|
|
1190
|
+
formats2[SheetModel.name(at)] = style.format;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
return { name, cells, ...Object.keys(formats2).length ? { formats: merge(formats2) } : {} };
|
|
1195
|
+
}
|
|
1196
|
+
function value(c, strings, date) {
|
|
1197
|
+
const formula = TaXml.kids(c, "f")[0];
|
|
1198
|
+
const v = TaXml.text(TaXml.kids(c, "v")[0]);
|
|
1199
|
+
if (formula && TaXml.text(formula).trim()) {
|
|
1200
|
+
return `=${TaXml.text(formula).trim()}`;
|
|
1201
|
+
}
|
|
1202
|
+
switch (c.attrs.t) {
|
|
1203
|
+
case "s":
|
|
1204
|
+
return strings[Number(v)] ?? "";
|
|
1205
|
+
case "inlineStr":
|
|
1206
|
+
return TaXml.text(TaXml.find(c, "is"));
|
|
1207
|
+
case "b":
|
|
1208
|
+
return v === "1" ? "TRUE" : "FALSE";
|
|
1209
|
+
case "str":
|
|
1210
|
+
case "e":
|
|
1211
|
+
return v;
|
|
1212
|
+
default:
|
|
1213
|
+
return date && v ? day(Number(v)) : v;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
function day(serial) {
|
|
1217
|
+
const time = new Date(Math.round((serial - 25569) * 86400000));
|
|
1218
|
+
const iso = time.toISOString();
|
|
1219
|
+
return serial % 1 ? iso.slice(0, 16).replace("T", " ") : iso.slice(0, 10);
|
|
1220
|
+
}
|
|
1221
|
+
function shared(xml) {
|
|
1222
|
+
return TaXml.kids(xml ? TaXml.parse(xml) : undefined, "si").map((si) => TaXml.all(si, "t").filter((t) => !isPhonetic(si, t)).map((t) => TaXml.text(t)).join(""));
|
|
1223
|
+
}
|
|
1224
|
+
function isPhonetic(si, t) {
|
|
1225
|
+
return TaXml.kids(si, "rPh").some((rph) => TaXml.kids(rph, "t").includes(t));
|
|
1226
|
+
}
|
|
1227
|
+
function formats(xml) {
|
|
1228
|
+
const root = xml ? TaXml.parse(xml) : undefined;
|
|
1229
|
+
const custom = new Map;
|
|
1230
|
+
for (const node of TaXml.all(root, "numFmt")) {
|
|
1231
|
+
custom.set(Number(node.attrs.numFmtId), node.attrs.formatCode ?? "");
|
|
1232
|
+
}
|
|
1233
|
+
const BUILT = { 1: "0", 2: "0.00", 3: "#,##0", 4: "#,##0.00", 9: "0%", 10: "0.00%" };
|
|
1234
|
+
return TaXml.kids(TaXml.find(root, "cellXfs"), "xf").map((xf) => {
|
|
1235
|
+
const id = Number(xf.attrs.numFmtId ?? 0);
|
|
1236
|
+
const code = custom.get(id) ?? BUILT[id];
|
|
1237
|
+
const date = DATE_IDS.has(id) || !!code && /(^|[^"\\])[ymd]/i.test(code.replace(/"[^"]*"/g, "").replace(/\[[^\]]*\]/g, ""));
|
|
1238
|
+
const format = code?.split(";")[0];
|
|
1239
|
+
return { date, ...format && !date && format !== "General" && format !== "@" ? { format } : {} };
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
function merge(formats2) {
|
|
1243
|
+
const byColumn = new Map;
|
|
1244
|
+
for (const [ref, format] of Object.entries(formats2)) {
|
|
1245
|
+
const at = SheetModel.at(ref);
|
|
1246
|
+
if (at) {
|
|
1247
|
+
const column = SheetModel.column(at.col);
|
|
1248
|
+
byColumn.set(column, [...byColumn.get(column) ?? [], { row: at.row, format }]);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
const out = {};
|
|
1252
|
+
for (const [column, cells] of byColumn) {
|
|
1253
|
+
cells.sort((a, b) => a.row - b.row);
|
|
1254
|
+
let start = cells[0];
|
|
1255
|
+
let last = cells[0];
|
|
1256
|
+
const flush = () => {
|
|
1257
|
+
out[start.row === last.row ? `${column}${start.row + 1}` : `${column}${start.row + 1}:${column}${last.row + 1}`] = start.format;
|
|
1258
|
+
};
|
|
1259
|
+
for (const cell of cells.slice(1)) {
|
|
1260
|
+
if (cell.format === start.format && cell.row === last.row + 1) {
|
|
1261
|
+
last = cell;
|
|
1262
|
+
} else {
|
|
1263
|
+
flush();
|
|
1264
|
+
start = cell;
|
|
1265
|
+
last = cell;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
flush();
|
|
1269
|
+
}
|
|
1270
|
+
return out;
|
|
1271
|
+
}
|
|
1272
|
+
})(ReadXlsx ||= {});
|
|
1273
|
+
|
|
1274
|
+
// web-src/slides-model.ts
|
|
1275
|
+
var LAYOUTS = ["title", "content", "two", "image", "number"];
|
|
1276
|
+
var IMAGE = /^\s*!\[[^\]]*\]\([^)]*\)\s*$/;
|
|
1277
|
+
var SlidesModel;
|
|
1278
|
+
((SlidesModel) => {
|
|
1279
|
+
function slides(code) {
|
|
1280
|
+
const groups = [{ blocks: [], start: 0, end: 0 }];
|
|
1281
|
+
for (const block of MdBlocks.split(code)) {
|
|
1282
|
+
const last = groups[groups.length - 1];
|
|
1283
|
+
if (block.kind === "rule" && block.source.trim() === "---") {
|
|
1284
|
+
last.end = block.start;
|
|
1285
|
+
groups.push({ blocks: [], start: block.end, end: block.end });
|
|
1286
|
+
} else {
|
|
1287
|
+
last.blocks.push(block);
|
|
1288
|
+
last.end = block.end;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
const slides2 = [];
|
|
1292
|
+
for (const group of groups) {
|
|
1293
|
+
const content = group.blocks.filter((block) => block.kind !== "comment");
|
|
1294
|
+
if (!content.length) {
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
const n = slides2.length + 1;
|
|
1298
|
+
const said = group.blocks.map((block) => OfficeMarks.LAYOUT.exec(block.source.trim())?.[1]).find(Boolean);
|
|
1299
|
+
const heading = content[0].kind === "heading" ? content[0] : undefined;
|
|
1300
|
+
const rest = group.blocks.filter((block) => block !== heading && !OfficeMarks.LAYOUT.test(block.source.trim()));
|
|
1301
|
+
const split = rest.findIndex((block) => block.source.trim() === OfficeMarks.COLUMN);
|
|
1302
|
+
const body = rest.filter((block) => block.kind !== "comment");
|
|
1303
|
+
const layout = said && LAYOUTS.includes(said) ? said : split >= 0 ? "two" : body.length <= 1 && heading && (n === 1 || !body.length) ? "title" : body.some((block) => IMAGE.test(block.source)) && body.length > 1 ? "image" : "content";
|
|
1304
|
+
let box = 0;
|
|
1305
|
+
const boxed = (block) => ({ ...block, anchor: `slide:${n}/box:${++box}` });
|
|
1306
|
+
let columns;
|
|
1307
|
+
if (layout === "two" && split >= 0) {
|
|
1308
|
+
columns = [rest.slice(0, split), rest.slice(split + 1)].map((part) => part.filter((block) => block.kind !== "comment").map(boxed));
|
|
1309
|
+
} else if (layout === "image") {
|
|
1310
|
+
const picture = body.find((block) => IMAGE.test(block.source));
|
|
1311
|
+
columns = [picture ? [boxed(picture)] : [], body.filter((block) => block !== picture).map(boxed)];
|
|
1312
|
+
} else {
|
|
1313
|
+
columns = [body.map(boxed)];
|
|
1314
|
+
}
|
|
1315
|
+
slides2.push({
|
|
1316
|
+
n,
|
|
1317
|
+
layout,
|
|
1318
|
+
...heading ? { title: { ...heading, anchor: `slide:${n}/box:title` } } : {},
|
|
1319
|
+
columns,
|
|
1320
|
+
start: group.start,
|
|
1321
|
+
end: group.end
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
return slides2;
|
|
1325
|
+
}
|
|
1326
|
+
SlidesModel.slides = slides;
|
|
1327
|
+
function source(code, slide) {
|
|
1328
|
+
return code.split(`
|
|
1329
|
+
`).slice(slide.start, slide.end).join(`
|
|
1330
|
+
`).trim();
|
|
1331
|
+
}
|
|
1332
|
+
SlidesModel.source = source;
|
|
1333
|
+
function title(code) {
|
|
1334
|
+
const first = slides(code).find((slide) => slide.title);
|
|
1335
|
+
return first?.title?.text ? MdBlocks.plain(first.title.text) : undefined;
|
|
1336
|
+
}
|
|
1337
|
+
SlidesModel.title = title;
|
|
1338
|
+
})(SlidesModel ||= {});
|
|
1339
|
+
|
|
1340
|
+
// web-src/office-read.ts
|
|
1341
|
+
var OfficeRead;
|
|
1342
|
+
((OfficeRead) => {
|
|
1343
|
+
async function read(name, bytes) {
|
|
1344
|
+
const language = OfficeFiles.languageOf(name);
|
|
1345
|
+
if (!language) {
|
|
1346
|
+
throw new Error(`${name} is not a docx, pptx or xlsx file.`);
|
|
1347
|
+
}
|
|
1348
|
+
if (bytes.length > OfficeLimits.FILE) {
|
|
1349
|
+
throw new Error(`${name} is too big to open here.`);
|
|
1350
|
+
}
|
|
1351
|
+
const zip = await ZipUtil.read(bytes, { only: (path) => path.endsWith(".xml") || path.endsWith(".rels"), maxBytes: OfficeLimits.INFLATED });
|
|
1352
|
+
const decoder = new TextDecoder;
|
|
1353
|
+
const files = new Map([...zip].map(([path, data]) => [path, decoder.decode(data)]));
|
|
1354
|
+
const kind = FILES[language];
|
|
1355
|
+
const read2 = kind === "docx" ? ReadDocx.read(files) : kind === "pptx" ? ReadPptx.read(files) : ReadXlsx.read(files);
|
|
1356
|
+
if (read2.code.length > OfficeLimits.CODE) {
|
|
1357
|
+
throw new Error(`${name} holds too much to open here.`);
|
|
1358
|
+
}
|
|
1359
|
+
const base = name.replace(/^.*[\\/]/, "").replace(/\.[^.]+$/, "");
|
|
1360
|
+
const title = (read2.title || (kind === "docx" ? DocModel.title(read2.code) : kind === "pptx" ? SlidesModel.title(read2.code) : undefined) || base).slice(0, 60);
|
|
1361
|
+
const code = kind === "xlsx" && !read2.title ? SheetModel.stringify({ ...SheetModel.parse(read2.code), title }) : read2.code;
|
|
1362
|
+
return { language, code, title };
|
|
1363
|
+
}
|
|
1364
|
+
OfficeRead.read = read;
|
|
1365
|
+
})(OfficeRead ||= {});
|
|
1366
|
+
|
|
1367
|
+
// web-src/ooxml.ts
|
|
1368
|
+
var HEAD = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
1369
|
+
`;
|
|
1370
|
+
var Ooxml;
|
|
1371
|
+
((Ooxml) => {
|
|
1372
|
+
Ooxml.encode = TaXml.encode;
|
|
1373
|
+
function types(overrides) {
|
|
1374
|
+
return `${HEAD}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>${Object.entries(overrides).map(([part, type]) => `<Override PartName="/${part}" ContentType="${type}"/>`).join("")}</Types>`;
|
|
1375
|
+
}
|
|
1376
|
+
Ooxml.types = types;
|
|
1377
|
+
function rels(relations) {
|
|
1378
|
+
return `${HEAD}<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relations.map((rel) => `<Relationship Id="${rel.id}" Type="${rel.type.startsWith("http") ? rel.type : `http://schemas.openxmlformats.org/officeDocument/2006/relationships/${rel.type}`}" Target="${Ooxml.encode(rel.target)}"${rel.external ? ' TargetMode="External"' : ""}/>`).join("")}</Relationships>`;
|
|
1379
|
+
}
|
|
1380
|
+
Ooxml.rels = rels;
|
|
1381
|
+
function common(main, title, types2) {
|
|
1382
|
+
const now = new Date().toISOString().replace(/\.\d+Z$/, "Z");
|
|
1383
|
+
return {
|
|
1384
|
+
"[Content_Types].xml": Ooxml.types({
|
|
1385
|
+
...types2,
|
|
1386
|
+
"docProps/core.xml": "application/vnd.openxmlformats-package.core-properties+xml",
|
|
1387
|
+
"docProps/app.xml": "application/vnd.openxmlformats-officedocument.extended-properties+xml"
|
|
1388
|
+
}),
|
|
1389
|
+
"_rels/.rels": rels([
|
|
1390
|
+
{ id: "rId1", type: "officeDocument", target: main },
|
|
1391
|
+
{ id: "rId2", type: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", target: "docProps/core.xml" },
|
|
1392
|
+
{ id: "rId3", type: "extended-properties", target: "docProps/app.xml" }
|
|
1393
|
+
]),
|
|
1394
|
+
"docProps/core.xml": `${HEAD}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>${Ooxml.encode(title)}</dc:title><dc:creator>Ta</dc:creator><dcterms:created xsi:type="dcterms:W3CDTF">${now}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${now}</dcterms:modified></cp:coreProperties>`,
|
|
1395
|
+
"docProps/app.xml": `${HEAD}<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"><Application>Ta</Application></Properties>`
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
Ooxml.common = common;
|
|
1399
|
+
function xml(body) {
|
|
1400
|
+
return HEAD + body;
|
|
1401
|
+
}
|
|
1402
|
+
Ooxml.xml = xml;
|
|
1403
|
+
function pack(parts, deflate = ZipUtil.browserDeflate()) {
|
|
1404
|
+
const encoder = new TextEncoder;
|
|
1405
|
+
const paths = Object.keys(parts).sort((a, b) => a === "[Content_Types].xml" ? -1 : b === "[Content_Types].xml" ? 1 : 0);
|
|
1406
|
+
return ZipUtil.create(paths.map((path) => ({ path, data: encoder.encode(parts[path]) })), deflate);
|
|
1407
|
+
}
|
|
1408
|
+
Ooxml.pack = pack;
|
|
1409
|
+
})(Ooxml ||= {});
|
|
1410
|
+
|
|
1411
|
+
// web-src/write-docx.ts
|
|
1412
|
+
var W_NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
|
|
1413
|
+
var ITEM2 = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
|
|
1414
|
+
var e = Ooxml.encode;
|
|
1415
|
+
var WriteDocx;
|
|
1416
|
+
((WriteDocx) => {
|
|
1417
|
+
function parts(code, title) {
|
|
1418
|
+
const writing = { links: [], lists: 0 };
|
|
1419
|
+
const body = [];
|
|
1420
|
+
for (const block of MdBlocks.split(code)) {
|
|
1421
|
+
switch (block.kind) {
|
|
1422
|
+
case "heading":
|
|
1423
|
+
body.push(paragraph(MdText.spans(block.text ?? ""), writing, `<w:pStyle w:val="Heading${block.level}"/>`));
|
|
1424
|
+
break;
|
|
1425
|
+
case "paragraph":
|
|
1426
|
+
body.push(paragraph(MdText.spans(block.source), writing));
|
|
1427
|
+
break;
|
|
1428
|
+
case "quote":
|
|
1429
|
+
body.push(paragraph(MdText.spans(block.source.replace(/^\s*>\s?/gm, "")), writing, '<w:pStyle w:val="Quote"/>'));
|
|
1430
|
+
break;
|
|
1431
|
+
case "list":
|
|
1432
|
+
body.push(list(block.source, writing));
|
|
1433
|
+
break;
|
|
1434
|
+
case "code":
|
|
1435
|
+
for (const line of block.source.split(`
|
|
1436
|
+
`).slice(1, /^\s*(`{3,}|~{3,})\s*$/.test(block.source.split(`
|
|
1437
|
+
`).at(-1) ?? "") ? -1 : undefined)) {
|
|
1438
|
+
body.push(`<w:p><w:pPr><w:pStyle w:val="Code"/></w:pPr>${run({ text: line })}</w:p>`);
|
|
1439
|
+
}
|
|
1440
|
+
break;
|
|
1441
|
+
case "table":
|
|
1442
|
+
body.push(table(block.source, writing));
|
|
1443
|
+
break;
|
|
1444
|
+
case "rule":
|
|
1445
|
+
body.push('<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="BFBFBF"/></w:pBdr></w:pPr></w:p>');
|
|
1446
|
+
break;
|
|
1447
|
+
case "comment":
|
|
1448
|
+
if (block.source.trim() === OfficeMarks.PAGE_BREAK) {
|
|
1449
|
+
body.push('<w:p><w:r><w:br w:type="page"/></w:r></w:p>');
|
|
1450
|
+
}
|
|
1451
|
+
break;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
const document = Ooxml.xml(`<w:document ${W_NS}><w:body>${body.join("")}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr></w:body></w:document>`);
|
|
1455
|
+
return {
|
|
1456
|
+
...Ooxml.common("word/document.xml", title, {
|
|
1457
|
+
"word/document.xml": "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
|
|
1458
|
+
"word/styles.xml": "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
|
|
1459
|
+
"word/numbering.xml": "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"
|
|
1460
|
+
}),
|
|
1461
|
+
"word/document.xml": document,
|
|
1462
|
+
"word/styles.xml": STYLES,
|
|
1463
|
+
"word/numbering.xml": numbering(writing.lists),
|
|
1464
|
+
"word/_rels/document.xml.rels": Ooxml.rels([
|
|
1465
|
+
{ id: "rId1", type: "styles", target: "styles.xml" },
|
|
1466
|
+
{ id: "rId2", type: "numbering", target: "numbering.xml" },
|
|
1467
|
+
...writing.links.map((target, index) => ({ id: `rIdL${index + 1}`, type: "hyperlink", target, external: true }))
|
|
1468
|
+
])
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
WriteDocx.parts = parts;
|
|
1472
|
+
function paragraph(spans, writing, props = "") {
|
|
1473
|
+
return `<w:p>${props ? `<w:pPr>${props}</w:pPr>` : ""}${runs(spans, writing)}</w:p>`;
|
|
1474
|
+
}
|
|
1475
|
+
function runs(spans, writing) {
|
|
1476
|
+
return spans.map((span) => {
|
|
1477
|
+
if (!span.link) {
|
|
1478
|
+
return run(span);
|
|
1479
|
+
}
|
|
1480
|
+
writing.links.push(span.link);
|
|
1481
|
+
return `<w:hyperlink r:id="rIdL${writing.links.length}">${run(span)}</w:hyperlink>`;
|
|
1482
|
+
}).join("");
|
|
1483
|
+
}
|
|
1484
|
+
function run(span) {
|
|
1485
|
+
const props = [
|
|
1486
|
+
span.link ? '<w:rStyle w:val="Hyperlink"/>' : "",
|
|
1487
|
+
span.code ? '<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>' : "",
|
|
1488
|
+
span.bold ? "<w:b/>" : "",
|
|
1489
|
+
span.italic ? "<w:i/>" : ""
|
|
1490
|
+
].join("");
|
|
1491
|
+
const text = span.text.split(`
|
|
1492
|
+
`).map((line) => `<w:t xml:space="preserve">${e(line)}</w:t>`).join("<w:br/>");
|
|
1493
|
+
return `<w:r>${props ? `<w:rPr>${props}</w:rPr>` : ""}${text}</w:r>`;
|
|
1494
|
+
}
|
|
1495
|
+
function list(source, writing) {
|
|
1496
|
+
const items = [];
|
|
1497
|
+
for (const line of source.split(`
|
|
1498
|
+
`)) {
|
|
1499
|
+
const item = ITEM2.exec(line);
|
|
1500
|
+
if (item) {
|
|
1501
|
+
items.push({ depth: Math.min(8, Math.floor(item[1].replace(/\t/g, " ").length / 2)), ordered: /\d/.test(item[2]), text: item[3] });
|
|
1502
|
+
} else if (items.length && line.trim()) {
|
|
1503
|
+
items[items.length - 1].text += `
|
|
1504
|
+
${line.trim()}`;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
const number = items.some((item) => item.ordered) ? 2 + writing.lists++ : 1;
|
|
1508
|
+
return items.map((item) => paragraph(MdText.spans(item.text.replace(/^\[( |x)\]\s+/i, (_, done) => done === " " ? "☐ " : "☑ ")), writing, `<w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="${item.depth}"/><w:numId w:val="${item.ordered ? number : 1}"/></w:numPr>`)).join("");
|
|
1509
|
+
}
|
|
1510
|
+
function table(source, writing) {
|
|
1511
|
+
const rows = source.split(`
|
|
1512
|
+
`).filter((line, index) => index !== 1 && line.trim()).map(MdText.cells);
|
|
1513
|
+
const width = Math.max(1, ...rows.map((row) => row.length));
|
|
1514
|
+
const cell = (text, head) => `<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${paragraph(MdText.spans(text).map((span) => head ? { ...span, bold: true } : span), writing)}</w:tc>`;
|
|
1515
|
+
const grid = Array.from({ length: width }, () => `<w:gridCol w:w="${Math.floor(9026 / width)}"/>`).join("");
|
|
1516
|
+
return `<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="5000" w:type="pct"/></w:tblPr><w:tblGrid>${grid}</w:tblGrid>${rows.map((row, index) => `<w:tr>${index === 0 ? "<w:trPr><w:tblHeader/></w:trPr>" : ""}${Array.from({ length: width }, (_, column) => cell(row[column] ?? "", index === 0)).join("")}</w:tr>`).join("")}</w:tbl><w:p/>`;
|
|
1517
|
+
}
|
|
1518
|
+
function numbering(lists) {
|
|
1519
|
+
const levels = (ordered2) => Array.from({ length: 9 }, (_, level) => {
|
|
1520
|
+
const format = ordered2 ? ["decimal", "lowerLetter", "lowerRoman"][level % 3] : "bullet";
|
|
1521
|
+
const text = ordered2 ? `%${level + 1}.` : ["•", "◦", "▪"][level % 3];
|
|
1522
|
+
return `<w:lvl w:ilvl="${level}"><w:start w:val="1"/><w:numFmt w:val="${format}"/><w:lvlText w:val="${text}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (level + 1)}" w:hanging="360"/></w:pPr></w:lvl>`;
|
|
1523
|
+
}).join("");
|
|
1524
|
+
const ordered = Array.from({ length: lists }, (_, index) => `<w:num w:numId="${index + 2}"><w:abstractNumId w:val="1"/><w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride></w:num>`).join("");
|
|
1525
|
+
return Ooxml.xml(`<w:numbering ${W_NS}><w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/>${levels(false)}</w:abstractNum><w:abstractNum w:abstractNumId="1"><w:multiLevelType w:val="hybridMultilevel"/>${levels(true)}</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>${ordered}</w:numbering>`);
|
|
1526
|
+
}
|
|
1527
|
+
})(WriteDocx ||= {});
|
|
1528
|
+
var heading = (level, size) => `<w:style w:type="paragraph" w:styleId="Heading${level}"><w:name w:val="heading ${level}"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="9"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="${level === 1 ? 360 : 240}" w:after="120"/><w:outlineLvl w:val="${level - 1}"/></w:pPr><w:rPr><w:b/><w:sz w:val="${size}"/><w:szCs w:val="${size}"/></w:rPr></w:style>`;
|
|
1529
|
+
var STYLES = Ooxml.xml(`<w:styles ${W_NS}><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Microsoft YaHei" w:cs="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US" w:eastAsia="zh-CN"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="300" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>${[
|
|
1530
|
+
44,
|
|
1531
|
+
32,
|
|
1532
|
+
28,
|
|
1533
|
+
26,
|
|
1534
|
+
24,
|
|
1535
|
+
22
|
|
1536
|
+
].map((size, index) => heading(index + 1, size)).join("")}<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:pBdr><w:left w:val="single" w:sz="18" w:space="8" w:color="BFBFBF"/></w:pBdr><w:ind w:left="360"/></w:pPr><w:rPr><w:i/><w:color w:val="595959"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="F2F2F2"/><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/><w:sz w:val="19"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:qFormat/><w:pPr><w:spacing w:after="60"/><w:contextualSpacing/></w:pPr></w:style><w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style><w:style w:type="table" w:default="1" w:styleId="TableNormal"><w:name w:val="Normal Table"/><w:tblPr><w:tblCellMar><w:top w:w="0" w:type="dxa"/><w:left w:w="108" w:type="dxa"/><w:bottom w:w="0" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style><w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:basedOn w:val="TableNormal"/><w:pPr><w:spacing w:after="0"/></w:pPr><w:tblPr><w:tblBorders><w:top w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:left w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:bottom w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:right w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:insideH w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:insideV w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/></w:tblBorders></w:tblPr></w:style></w:styles>`);
|
|
1537
|
+
|
|
1538
|
+
// web-src/pptx-parts.ts
|
|
1539
|
+
var P_NS = 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"';
|
|
1540
|
+
var SLIDE_WIDTH = 12192000;
|
|
1541
|
+
var SLIDE_HEIGHT = 6858000;
|
|
1542
|
+
var GROUP = '<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>';
|
|
1543
|
+
function shapeTree(shapes) {
|
|
1544
|
+
return `<p:spTree>${GROUP}${shapes}</p:spTree>`;
|
|
1545
|
+
}
|
|
1546
|
+
var level = (n, size) => `<a:lvl${n}pPr marL="${n === 1 ? 0 : (n - 1) * 457200}" indent="0" algn="l" defTabSz="914400"><a:defRPr sz="${size}" kern="1200"><a:solidFill><a:schemeClr val="tx1"/></a:solidFill><a:latin typeface="+mn-lt"/><a:ea typeface="+mn-ea"/><a:cs typeface="+mn-cs"/></a:defRPr></a:lvl${n}pPr>`;
|
|
1547
|
+
var PptxParts;
|
|
1548
|
+
((PptxParts) => {
|
|
1549
|
+
function fixed() {
|
|
1550
|
+
return {
|
|
1551
|
+
"ppt/slideMasters/slideMaster1.xml": Ooxml.xml(`<p:sldMaster ${P_NS}><p:cSld><p:bg><p:bgRef idx="1001"><a:schemeClr val="bg1"/></p:bgRef></p:bg>${shapeTree("")}</p:cSld><p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst><p:txStyles><p:titleStyle>${level(1, 4000)}</p:titleStyle><p:bodyStyle>${[1, 2, 3].map((n) => level(n, 2000)).join("")}</p:bodyStyle><p:otherStyle>${level(1, 1800)}</p:otherStyle></p:txStyles></p:sldMaster>`),
|
|
1552
|
+
"ppt/slideMasters/_rels/slideMaster1.xml.rels": Ooxml.rels([
|
|
1553
|
+
{ id: "rId1", type: "slideLayout", target: "../slideLayouts/slideLayout1.xml" },
|
|
1554
|
+
{ id: "rId2", type: "theme", target: "../theme/theme1.xml" }
|
|
1555
|
+
]),
|
|
1556
|
+
"ppt/slideLayouts/slideLayout1.xml": Ooxml.xml(`<p:sldLayout ${P_NS} type="blank" preserve="1"><p:cSld name="Blank">${shapeTree("")}</p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>`),
|
|
1557
|
+
"ppt/slideLayouts/_rels/slideLayout1.xml.rels": Ooxml.rels([{ id: "rId1", type: "slideMaster", target: "../slideMasters/slideMaster1.xml" }]),
|
|
1558
|
+
"ppt/theme/theme1.xml": THEME,
|
|
1559
|
+
"ppt/presProps.xml": Ooxml.xml(`<p:presentationPr ${P_NS}/>`),
|
|
1560
|
+
"ppt/viewProps.xml": Ooxml.xml(`<p:viewPr ${P_NS}><p:normalViewPr><p:restoredLeft sz="15620"/><p:restoredTop sz="94660"/></p:normalViewPr><p:gridSpacing cx="76200" cy="76200"/></p:viewPr>`),
|
|
1561
|
+
"ppt/tableStyles.xml": Ooxml.xml('<a:tblStyleLst xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" def="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"/>')
|
|
1562
|
+
};
|
|
1563
|
+
}
|
|
1564
|
+
PptxParts.fixed = fixed;
|
|
1565
|
+
PptxParts.TYPES = {
|
|
1566
|
+
"ppt/presentation.xml": "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml",
|
|
1567
|
+
"ppt/slideMasters/slideMaster1.xml": "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml",
|
|
1568
|
+
"ppt/slideLayouts/slideLayout1.xml": "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml",
|
|
1569
|
+
"ppt/theme/theme1.xml": "application/vnd.openxmlformats-officedocument.theme+xml",
|
|
1570
|
+
"ppt/presProps.xml": "application/vnd.openxmlformats-officedocument.presentationml.presProps+xml",
|
|
1571
|
+
"ppt/viewProps.xml": "application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml",
|
|
1572
|
+
"ppt/tableStyles.xml": "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml"
|
|
1573
|
+
};
|
|
1574
|
+
PptxParts.SLIDE_TYPE = "application/vnd.openxmlformats-officedocument.presentationml.slide+xml";
|
|
1575
|
+
})(PptxParts ||= {});
|
|
1576
|
+
var color = (name, rgb) => `<a:${name}><a:srgbClr val="${rgb}"/></a:${name}>`;
|
|
1577
|
+
var fill = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
|
|
1578
|
+
var line = (w) => `<a:ln w="${w}" cap="flat" cmpd="sng" algn="ctr">${fill}<a:prstDash val="solid"/><a:miter lim="800000"/></a:ln>`;
|
|
1579
|
+
var fonts = (latin) => `<a:latin typeface="${latin}"/><a:ea typeface=""/><a:cs typeface=""/>`;
|
|
1580
|
+
var THEME = Ooxml.xml(`<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Ta"><a:themeElements><a:clrScheme name="Ta">${color("dk1", "1F2328")}${color("lt1", "FFFFFF")}${color("dk2", "44546A")}${color("lt2", "F3F4F6")}${color("accent1", "2563EB")}${color("accent2", "16A34A")}${color("accent3", "F59E0B")}${color("accent4", "DC2626")}${color("accent5", "7C3AED")}${color("accent6", "0891B2")}${color("hlink", "2563EB")}${color("folHlink", "7C3AED")}</a:clrScheme><a:fontScheme name="Ta"><a:majorFont>${fonts("Calibri Light")}</a:majorFont><a:minorFont>${fonts("Calibri")}</a:minorFont></a:fontScheme><a:fmtScheme name="Ta"><a:fillStyleLst>${fill}${fill}${fill}</a:fillStyleLst><a:lnStyleLst>${line(6350)}${line(12700)}${line(19050)}</a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst>${fill}${fill}${fill}</a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>`);
|
|
1581
|
+
|
|
1582
|
+
// web-src/write-pptx.ts
|
|
1583
|
+
var e2 = Ooxml.encode;
|
|
1584
|
+
var INCH = 914400;
|
|
1585
|
+
var MARGIN = Math.round(0.6 * INCH);
|
|
1586
|
+
var GAP = Math.round(0.4 * INCH);
|
|
1587
|
+
var INNER = SLIDE_WIDTH - 2 * MARGIN;
|
|
1588
|
+
var ITEM3 = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
|
|
1589
|
+
|
|
1590
|
+
class SlideWriter {
|
|
1591
|
+
shapes = [];
|
|
1592
|
+
links = [];
|
|
1593
|
+
id = 1;
|
|
1594
|
+
text(rect, paras, anchor = "t", name = "Text") {
|
|
1595
|
+
if (!paras.length) {
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
const body = paras.map((para) => this.para(para)).join("");
|
|
1599
|
+
this.shapes.push(`<p:sp><p:nvSpPr><p:cNvPr id="${++this.id}" name="${name} ${this.id}"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr><p:spPr>${xfrm(rect)}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr><p:txBody><a:bodyPr wrap="square" lIns="91440" tIns="45720" rIns="91440" bIns="45720" anchor="${anchor}"><a:normAutofit/></a:bodyPr><a:lstStyle/>${body}</p:txBody></p:sp>`);
|
|
1600
|
+
}
|
|
1601
|
+
table(rect, rows) {
|
|
1602
|
+
const width = Math.max(1, ...rows.map((row) => row.length));
|
|
1603
|
+
const column = Math.floor(rect.w / width);
|
|
1604
|
+
const height = Math.min(Math.floor(rect.h / Math.max(1, rows.length)), Math.round(0.5 * INCH));
|
|
1605
|
+
const border = (side) => `<a:${side} w="12700"><a:solidFill><a:srgbClr val="BFBFBF"/></a:solidFill></a:${side}>`;
|
|
1606
|
+
const cell = (text, head) => `<a:tc><a:txBody><a:bodyPr/><a:lstStyle/>${this.para({ spans: MdText.spans(text), size: rows.length > 8 ? 1200 : 1400, bold: head })}</a:txBody><a:tcPr>${[
|
|
1607
|
+
"lnL",
|
|
1608
|
+
"lnR",
|
|
1609
|
+
"lnT",
|
|
1610
|
+
"lnB"
|
|
1611
|
+
].map(border).join("")}${head ? '<a:solidFill><a:srgbClr val="EEF2FF"/></a:solidFill>' : ""}</a:tcPr></a:tc>`;
|
|
1612
|
+
const grid = `<a:gridCol w="${column}"/>`.repeat(width);
|
|
1613
|
+
const body = rows.map((row, index) => `<a:tr h="${height}">${Array.from({ length: width }, (_, at) => cell(row[at] ?? "", index === 0)).join("")}</a:tr>`).join("");
|
|
1614
|
+
this.shapes.push(`<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="${++this.id}" name="Table ${this.id}"/><p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr><p:xfrm><a:off x="${rect.x}" y="${rect.y}"/><a:ext cx="${column * width}" cy="${height * rows.length}"/></p:xfrm><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/table"><a:tbl><a:tblPr firstRow="1"/><a:tblGrid>${grid}</a:tblGrid>${body}</a:tbl></a:graphicData></a:graphic></p:graphicFrame>`);
|
|
1615
|
+
}
|
|
1616
|
+
para(para) {
|
|
1617
|
+
const bullet = para.bullet ? `<a:pPr marL="${(para.bullet.level + 1) * 342900}" indent="-285750"${para.align ? ` algn="${para.align}"` : ""}>${para.bullet.ordered ? '<a:buFont typeface="+mj-lt"/><a:buAutoNum type="arabicPeriod"/>' : '<a:buFont typeface="Arial"/><a:buChar char="•"/>'}</a:pPr>` : `<a:pPr${para.align ? ` algn="${para.align}"` : ""}><a:buNone/></a:pPr>`;
|
|
1618
|
+
const runs = para.spans.map((span) => {
|
|
1619
|
+
let link = "";
|
|
1620
|
+
if (span.link) {
|
|
1621
|
+
this.links.push(span.link);
|
|
1622
|
+
link = `<a:hlinkClick r:id="rIdL${this.links.length}"/>`;
|
|
1623
|
+
}
|
|
1624
|
+
const color2 = para.color ? `<a:solidFill><a:srgbClr val="${para.color}"/></a:solidFill>` : "";
|
|
1625
|
+
const font = span.code || para.mono ? '<a:latin typeface="Consolas"/>' : "";
|
|
1626
|
+
const props = `<a:rPr lang="zh-CN" sz="${para.size}"${para.bold || span.bold ? ' b="1"' : ""}${span.italic ? ' i="1"' : ""} dirty="0">${color2}${font}${link}</a:rPr>`;
|
|
1627
|
+
return span.text.split(`
|
|
1628
|
+
`).map((text) => `<a:r>${props}<a:t>${e2(text)}</a:t></a:r>`).join("<a:br/>");
|
|
1629
|
+
}).join("");
|
|
1630
|
+
return `<a:p>${bullet}${runs || `<a:endParaRPr lang="zh-CN" sz="${para.size}"/>`}</a:p>`;
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
function xfrm(rect) {
|
|
1634
|
+
return `<a:xfrm><a:off x="${Math.round(rect.x)}" y="${Math.round(rect.y)}"/><a:ext cx="${Math.round(rect.w)}" cy="${Math.round(rect.h)}"/></a:xfrm>`;
|
|
1635
|
+
}
|
|
1636
|
+
function paragraphs(blocks, size, align) {
|
|
1637
|
+
const paras = [];
|
|
1638
|
+
for (const block of blocks) {
|
|
1639
|
+
if (block.kind === "heading") {
|
|
1640
|
+
paras.push({ spans: MdText.spans(block.text ?? ""), size: size + 400, bold: true, ...align ? { align } : {} });
|
|
1641
|
+
} else if (block.kind === "list") {
|
|
1642
|
+
for (const line2 of block.source.split(`
|
|
1643
|
+
`)) {
|
|
1644
|
+
const item = ITEM3.exec(line2);
|
|
1645
|
+
if (item) {
|
|
1646
|
+
const level2 = Math.min(4, Math.floor(item[1].length / 2));
|
|
1647
|
+
paras.push({ spans: MdText.spans(item[3]), size: level2 ? size - 200 : size, bullet: { level: level2, ordered: /\d/.test(item[2]) } });
|
|
1648
|
+
} else if (line2.trim() && paras.length) {
|
|
1649
|
+
paras[paras.length - 1].spans.push({ text: ` ${line2.trim()}` });
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
} else if (block.kind === "code") {
|
|
1653
|
+
for (const line2 of block.source.split(`
|
|
1654
|
+
`).slice(1, -1)) {
|
|
1655
|
+
paras.push({ spans: [{ text: line2 }], size: size - 400, mono: true });
|
|
1656
|
+
}
|
|
1657
|
+
} else if (block.kind === "quote") {
|
|
1658
|
+
paras.push({ spans: MdText.spans(block.source.replace(/^\s*>\s?/gm, "")).map((span) => ({ ...span, italic: true })), size, color: "595959" });
|
|
1659
|
+
} else if (block.kind === "paragraph") {
|
|
1660
|
+
paras.push({ spans: MdText.spans(block.source), size, ...align ? { align } : {} });
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
return paras;
|
|
1664
|
+
}
|
|
1665
|
+
function fit(blocks, base) {
|
|
1666
|
+
const lines = blocks.reduce((sum, block) => sum + block.source.split(`
|
|
1667
|
+
`).length, 0);
|
|
1668
|
+
return lines > 14 ? Math.max(1200, base - 800) : lines > 9 ? base - 400 : base;
|
|
1669
|
+
}
|
|
1670
|
+
function column(slide, rect, blocks, size) {
|
|
1671
|
+
const tables = blocks.filter((block) => block.kind === "table");
|
|
1672
|
+
const rest = blocks.filter((block) => block.kind !== "table");
|
|
1673
|
+
if (!tables.length) {
|
|
1674
|
+
slide.text(rect, paragraphs(rest, fit(rest, size)), "t", "Body");
|
|
1675
|
+
return;
|
|
1676
|
+
}
|
|
1677
|
+
const top = rest.length ? Math.round(rect.h * 0.3) : 0;
|
|
1678
|
+
slide.text({ ...rect, h: top }, paragraphs(rest, fit(rest, size)), "t", "Body");
|
|
1679
|
+
const each = (rect.h - top) / tables.length;
|
|
1680
|
+
tables.forEach((table, index) => {
|
|
1681
|
+
const rows = table.source.split(`
|
|
1682
|
+
`).filter((line2, at) => at !== 1 && line2.trim()).map(MdText.cells);
|
|
1683
|
+
slide.table({ x: rect.x, y: rect.y + top + index * each, w: rect.w, h: each - GAP / 2 }, rows);
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
var WritePptx;
|
|
1687
|
+
((WritePptx) => {
|
|
1688
|
+
function parts(code, title) {
|
|
1689
|
+
const slides = SlidesModel.slides(code);
|
|
1690
|
+
const parts2 = { ...PptxParts.fixed() };
|
|
1691
|
+
const types = { ...PptxParts.TYPES };
|
|
1692
|
+
slides.forEach((slide, index) => {
|
|
1693
|
+
const writer = new SlideWriter;
|
|
1694
|
+
layout(writer, slide);
|
|
1695
|
+
const path = `ppt/slides/slide${index + 1}.xml`;
|
|
1696
|
+
parts2[path] = Ooxml.xml(`<p:sld ${P_NS}><p:cSld>${shapeTree(writer.shapes.join(""))}</p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>`);
|
|
1697
|
+
parts2[`ppt/slides/_rels/slide${index + 1}.xml.rels`] = Ooxml.rels([
|
|
1698
|
+
{ id: "rId1", type: "slideLayout", target: "../slideLayouts/slideLayout1.xml" },
|
|
1699
|
+
...writer.links.map((target, at) => ({ id: `rIdL${at + 1}`, type: "hyperlink", target, external: true }))
|
|
1700
|
+
]);
|
|
1701
|
+
types[path] = PptxParts.SLIDE_TYPE;
|
|
1702
|
+
});
|
|
1703
|
+
parts2["ppt/presentation.xml"] = Ooxml.xml(`<p:presentation ${P_NS} saveSubsetFonts="1"><p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst><p:sldIdLst>${slides.map((_, index) => `<p:sldId id="${256 + index}" r:id="rId${10 + index}"/>`).join("")}</p:sldIdLst><p:sldSz cx="${SLIDE_WIDTH}" cy="${SLIDE_HEIGHT}"/><p:notesSz cx="6858000" cy="9144000"/><p:defaultTextStyle><a:lvl1pPr><a:defRPr sz="1800"/></a:lvl1pPr></p:defaultTextStyle></p:presentation>`);
|
|
1704
|
+
parts2["ppt/_rels/presentation.xml.rels"] = Ooxml.rels([
|
|
1705
|
+
{ id: "rId1", type: "slideMaster", target: "slideMasters/slideMaster1.xml" },
|
|
1706
|
+
{ id: "rId2", type: "theme", target: "theme/theme1.xml" },
|
|
1707
|
+
{ id: "rId3", type: "presProps", target: "presProps.xml" },
|
|
1708
|
+
{ id: "rId4", type: "viewProps", target: "viewProps.xml" },
|
|
1709
|
+
{ id: "rId5", type: "tableStyles", target: "tableStyles.xml" },
|
|
1710
|
+
...slides.map((_, index) => ({ id: `rId${10 + index}`, type: "slide", target: `slides/slide${index + 1}.xml` }))
|
|
1711
|
+
]);
|
|
1712
|
+
return { ...Ooxml.common("ppt/presentation.xml", title, types), ...parts2 };
|
|
1713
|
+
}
|
|
1714
|
+
WritePptx.parts = parts;
|
|
1715
|
+
function layout(writer, slide) {
|
|
1716
|
+
const heading2 = slide.title ? [{ spans: MdText.spans(slide.title.text ?? ""), size: 3600, bold: true }] : [];
|
|
1717
|
+
const body = slide.columns.flat();
|
|
1718
|
+
switch (slide.layout) {
|
|
1719
|
+
case "title":
|
|
1720
|
+
writer.text({ x: MARGIN, y: SLIDE_HEIGHT * 0.3, w: INNER, h: SLIDE_HEIGHT * 0.22 }, heading2.map((para) => ({ ...para, size: 4800, align: "ctr" })), "ctr", "Title");
|
|
1721
|
+
writer.text({ x: MARGIN, y: SLIDE_HEIGHT * 0.54, w: INNER, h: SLIDE_HEIGHT * 0.3 }, paragraphs(body, 2400, "ctr").map((para) => ({ ...para, color: "595959" })), "t", "Subtitle");
|
|
1722
|
+
return;
|
|
1723
|
+
case "number":
|
|
1724
|
+
writer.text({ x: MARGIN, y: SLIDE_HEIGHT * 0.16, w: INNER, h: SLIDE_HEIGHT * 0.4 }, heading2.map((para) => ({ ...para, size: 9600, align: "ctr", color: "2563EB" })), "ctr", "Title");
|
|
1725
|
+
writer.text({ x: MARGIN, y: SLIDE_HEIGHT * 0.58, w: INNER, h: SLIDE_HEIGHT * 0.3 }, paragraphs(body, 2400, "ctr"), "t", "Body");
|
|
1726
|
+
return;
|
|
1727
|
+
}
|
|
1728
|
+
const top = slide.title ? MARGIN + Math.round(1.25 * INCH) : MARGIN;
|
|
1729
|
+
writer.text({ x: MARGIN, y: MARGIN * 0.7, w: INNER, h: Math.round(1.2 * INCH) }, heading2, "ctr", "Title");
|
|
1730
|
+
const height = SLIDE_HEIGHT - top - MARGIN;
|
|
1731
|
+
const columns = slide.layout === "two" || slide.layout === "image" ? slide.columns : [body];
|
|
1732
|
+
const width = (INNER - GAP * (columns.length - 1)) / columns.length;
|
|
1733
|
+
columns.forEach((blocks, index) => {
|
|
1734
|
+
column(writer, { x: MARGIN + index * (width + GAP), y: top, w: width, h: height }, blocks, 2000);
|
|
1735
|
+
});
|
|
1736
|
+
}
|
|
1737
|
+
})(WritePptx ||= {});
|
|
1738
|
+
|
|
1739
|
+
// web-src/sheet-formula.ts
|
|
1740
|
+
class CellError {
|
|
1741
|
+
code;
|
|
1742
|
+
constructor(code) {
|
|
1743
|
+
this.code = code;
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
class Unsupported extends Error {
|
|
1748
|
+
}
|
|
1749
|
+
var FUNCTIONS = ["SUM", "AVERAGE", "COUNT", "MIN", "MAX", "IF", "ROUND"];
|
|
1750
|
+
var LEVELS = [["=", "<>", "<=", ">=", "<", ">"], ["&"], ["+", "-"], ["*", "/"], ["^"]];
|
|
1751
|
+
|
|
1752
|
+
class SheetCalc {
|
|
1753
|
+
book;
|
|
1754
|
+
done = new Map;
|
|
1755
|
+
going = new Set;
|
|
1756
|
+
constructor(book) {
|
|
1757
|
+
this.book = book;
|
|
1758
|
+
}
|
|
1759
|
+
value(sheet, at) {
|
|
1760
|
+
const key = `${sheet}!${at.col},${at.row}`;
|
|
1761
|
+
const known = this.done.get(key);
|
|
1762
|
+
if (known !== undefined) {
|
|
1763
|
+
return known;
|
|
1764
|
+
}
|
|
1765
|
+
const raw = this.book.sheets[sheet]?.cells[at.row]?.[at.col] ?? "";
|
|
1766
|
+
if (!raw.startsWith("=") || raw.length < 2) {
|
|
1767
|
+
return SheetCalc.literal(raw);
|
|
1768
|
+
}
|
|
1769
|
+
if (this.going.has(key)) {
|
|
1770
|
+
return new CellError("#CYCLE!");
|
|
1771
|
+
}
|
|
1772
|
+
this.going.add(key);
|
|
1773
|
+
let value;
|
|
1774
|
+
try {
|
|
1775
|
+
value = this.scalar(new FormulaParser(raw.slice(1), sheet, this.book).parse());
|
|
1776
|
+
} catch (error) {
|
|
1777
|
+
value = error instanceof Unsupported ? error : new CellError("#VALUE!");
|
|
1778
|
+
} finally {
|
|
1779
|
+
this.going.delete(key);
|
|
1780
|
+
}
|
|
1781
|
+
this.done.set(key, value);
|
|
1782
|
+
return value;
|
|
1783
|
+
}
|
|
1784
|
+
static literal(raw) {
|
|
1785
|
+
const text = raw.trim();
|
|
1786
|
+
if (/^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(text)) {
|
|
1787
|
+
return Number(text);
|
|
1788
|
+
}
|
|
1789
|
+
if (/^[-+]?(\d+\.?\d*|\.\d+)%$/.test(text)) {
|
|
1790
|
+
return Number(text.slice(0, -1)) / 100;
|
|
1791
|
+
}
|
|
1792
|
+
return text === "TRUE" ? true : text === "FALSE" ? false : raw;
|
|
1793
|
+
}
|
|
1794
|
+
scalar(node) {
|
|
1795
|
+
const value = this.evaluate(node);
|
|
1796
|
+
if (Array.isArray(value)) {
|
|
1797
|
+
return value.length === 1 ? value[0] : new CellError("#VALUE!");
|
|
1798
|
+
}
|
|
1799
|
+
return value;
|
|
1800
|
+
}
|
|
1801
|
+
evaluate(node) {
|
|
1802
|
+
switch (node.type) {
|
|
1803
|
+
case "value":
|
|
1804
|
+
return node.value;
|
|
1805
|
+
case "ref":
|
|
1806
|
+
return this.cell(node.sheet, node.at);
|
|
1807
|
+
case "range": {
|
|
1808
|
+
const values = [];
|
|
1809
|
+
for (let row = node.from.row;row <= node.to.row; row++) {
|
|
1810
|
+
for (let col = node.from.col;col <= node.to.col; col++) {
|
|
1811
|
+
values.push(this.cell(node.sheet, { col, row }));
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
return values;
|
|
1815
|
+
}
|
|
1816
|
+
case "unary": {
|
|
1817
|
+
const value = SheetCalc.number(this.scalar(node.arg));
|
|
1818
|
+
return value instanceof CellError ? value : node.op === "%" ? value / 100 : node.op === "-" ? -value : value;
|
|
1819
|
+
}
|
|
1820
|
+
case "binary":
|
|
1821
|
+
return this.binary(node.op, this.scalar(node.left), this.scalar(node.right));
|
|
1822
|
+
case "call":
|
|
1823
|
+
return this.call(node.name, node.args);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
cell(sheet, at) {
|
|
1827
|
+
const value = this.value(sheet, at);
|
|
1828
|
+
if (value instanceof Unsupported) {
|
|
1829
|
+
throw value;
|
|
1830
|
+
}
|
|
1831
|
+
return value;
|
|
1832
|
+
}
|
|
1833
|
+
binary(op, left, right) {
|
|
1834
|
+
if (left instanceof CellError) {
|
|
1835
|
+
return left;
|
|
1836
|
+
}
|
|
1837
|
+
if (right instanceof CellError) {
|
|
1838
|
+
return right;
|
|
1839
|
+
}
|
|
1840
|
+
if (op === "&") {
|
|
1841
|
+
return SheetCalc.text(left) + SheetCalc.text(right);
|
|
1842
|
+
}
|
|
1843
|
+
if (LEVELS[0].includes(op)) {
|
|
1844
|
+
const order = SheetCalc.compare(left, right);
|
|
1845
|
+
return op === "=" ? order === 0 : op === "<>" ? order !== 0 : op === "<" ? order < 0 : op === ">" ? order > 0 : op === "<=" ? order <= 0 : order >= 0;
|
|
1846
|
+
}
|
|
1847
|
+
const a = SheetCalc.number(left);
|
|
1848
|
+
const b = SheetCalc.number(right);
|
|
1849
|
+
if (a instanceof CellError) {
|
|
1850
|
+
return a;
|
|
1851
|
+
}
|
|
1852
|
+
if (b instanceof CellError) {
|
|
1853
|
+
return b;
|
|
1854
|
+
}
|
|
1855
|
+
if (op === "/" && b === 0) {
|
|
1856
|
+
return new CellError("#DIV/0!");
|
|
1857
|
+
}
|
|
1858
|
+
const result = op === "+" ? a + b : op === "-" ? a - b : op === "*" ? a * b : op === "/" ? a / b : a ** b;
|
|
1859
|
+
return Number.isFinite(result) ? result : new CellError("#NUM!");
|
|
1860
|
+
}
|
|
1861
|
+
call(name, args) {
|
|
1862
|
+
if (name === "IF") {
|
|
1863
|
+
if (args.length < 2 || args.length > 3) {
|
|
1864
|
+
return new CellError("#VALUE!");
|
|
1865
|
+
}
|
|
1866
|
+
const test = this.scalar(args[0]);
|
|
1867
|
+
if (test instanceof CellError) {
|
|
1868
|
+
return test;
|
|
1869
|
+
}
|
|
1870
|
+
const yes = typeof test === "string" ? test !== "" : !!SheetCalc.number(test);
|
|
1871
|
+
return yes ? this.scalar(args[1]) : args[2] ? this.scalar(args[2]) : false;
|
|
1872
|
+
}
|
|
1873
|
+
if (name === "ROUND") {
|
|
1874
|
+
const value = SheetCalc.number(args[0] ? this.scalar(args[0]) : new CellError("#VALUE!"));
|
|
1875
|
+
const digits = SheetCalc.number(args[1] ? this.scalar(args[1]) : 0);
|
|
1876
|
+
if (value instanceof CellError || digits instanceof CellError) {
|
|
1877
|
+
return value instanceof CellError ? value : digits;
|
|
1878
|
+
}
|
|
1879
|
+
const scale = 10 ** Math.trunc(digits);
|
|
1880
|
+
return Math.sign(value) * Math.round(Math.abs(value) * scale * (1 + Number.EPSILON)) / scale;
|
|
1881
|
+
}
|
|
1882
|
+
const numbers = [];
|
|
1883
|
+
for (const arg of args) {
|
|
1884
|
+
const value = this.evaluate(arg);
|
|
1885
|
+
if (arg.type === "ref" || arg.type === "range") {
|
|
1886
|
+
for (const each of Array.isArray(value) ? value : [value]) {
|
|
1887
|
+
if (each instanceof CellError) {
|
|
1888
|
+
return each;
|
|
1889
|
+
}
|
|
1890
|
+
if (typeof each === "number") {
|
|
1891
|
+
numbers.push(each);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
continue;
|
|
1895
|
+
}
|
|
1896
|
+
const number = SheetCalc.number(Array.isArray(value) ? new CellError("#VALUE!") : value);
|
|
1897
|
+
if (number instanceof CellError) {
|
|
1898
|
+
if (name !== "COUNT") {
|
|
1899
|
+
return number;
|
|
1900
|
+
}
|
|
1901
|
+
} else {
|
|
1902
|
+
numbers.push(number);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
switch (name) {
|
|
1906
|
+
case "SUM":
|
|
1907
|
+
return numbers.reduce((sum, n) => sum + n, 0);
|
|
1908
|
+
case "COUNT":
|
|
1909
|
+
return numbers.length;
|
|
1910
|
+
case "AVERAGE":
|
|
1911
|
+
return numbers.length ? numbers.reduce((sum, n) => sum + n, 0) / numbers.length : new CellError("#DIV/0!");
|
|
1912
|
+
case "MIN":
|
|
1913
|
+
return numbers.length ? Math.min(...numbers) : 0;
|
|
1914
|
+
default:
|
|
1915
|
+
return numbers.length ? Math.max(...numbers) : 0;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
static number(value) {
|
|
1919
|
+
if (typeof value === "number" || value instanceof CellError) {
|
|
1920
|
+
return value;
|
|
1921
|
+
}
|
|
1922
|
+
if (typeof value === "boolean") {
|
|
1923
|
+
return value ? 1 : 0;
|
|
1924
|
+
}
|
|
1925
|
+
if (value.trim() === "") {
|
|
1926
|
+
return 0;
|
|
1927
|
+
}
|
|
1928
|
+
const literal = SheetCalc.literal(value);
|
|
1929
|
+
return typeof literal === "number" ? literal : new CellError("#VALUE!");
|
|
1930
|
+
}
|
|
1931
|
+
static text(value) {
|
|
1932
|
+
if (value instanceof CellError) {
|
|
1933
|
+
return value.code;
|
|
1934
|
+
}
|
|
1935
|
+
if (typeof value === "boolean") {
|
|
1936
|
+
return value ? "TRUE" : "FALSE";
|
|
1937
|
+
}
|
|
1938
|
+
return typeof value === "number" ? String(Number(value.toPrecision(12))) : value;
|
|
1939
|
+
}
|
|
1940
|
+
static compare(a, b) {
|
|
1941
|
+
const rank = (value) => typeof value === "number" ? 0 : typeof value === "string" ? 1 : 2;
|
|
1942
|
+
if (a === "" && typeof b === "number") {
|
|
1943
|
+
a = 0;
|
|
1944
|
+
}
|
|
1945
|
+
if (b === "" && typeof a === "number") {
|
|
1946
|
+
b = 0;
|
|
1947
|
+
}
|
|
1948
|
+
if (rank(a) !== rank(b)) {
|
|
1949
|
+
return rank(a) - rank(b);
|
|
1950
|
+
}
|
|
1951
|
+
if (typeof a === "string" && typeof b === "string") {
|
|
1952
|
+
return a.toLowerCase().localeCompare(b.toLowerCase());
|
|
1953
|
+
}
|
|
1954
|
+
return Number(a) - Number(b);
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
class FormulaParser {
|
|
1959
|
+
text;
|
|
1960
|
+
sheet;
|
|
1961
|
+
book;
|
|
1962
|
+
at = 0;
|
|
1963
|
+
constructor(text, sheet, book) {
|
|
1964
|
+
this.text = text;
|
|
1965
|
+
this.sheet = sheet;
|
|
1966
|
+
this.book = book;
|
|
1967
|
+
}
|
|
1968
|
+
parse() {
|
|
1969
|
+
const node = this.level(0);
|
|
1970
|
+
this.space();
|
|
1971
|
+
if (this.at < this.text.length) {
|
|
1972
|
+
throw new Unsupported(`Cannot read ${this.text.slice(this.at)}`);
|
|
1973
|
+
}
|
|
1974
|
+
return node;
|
|
1975
|
+
}
|
|
1976
|
+
level(n) {
|
|
1977
|
+
if (n >= LEVELS.length) {
|
|
1978
|
+
return this.unary();
|
|
1979
|
+
}
|
|
1980
|
+
let left = this.level(n + 1);
|
|
1981
|
+
for (;; ) {
|
|
1982
|
+
this.space();
|
|
1983
|
+
const op = LEVELS[n].find((candidate) => this.text.startsWith(candidate, this.at));
|
|
1984
|
+
if (!op) {
|
|
1985
|
+
return left;
|
|
1986
|
+
}
|
|
1987
|
+
this.at += op.length;
|
|
1988
|
+
const right = op === "^" ? this.level(n) : this.level(n + 1);
|
|
1989
|
+
left = { type: "binary", op, left, right };
|
|
1990
|
+
if (op === "^") {
|
|
1991
|
+
return left;
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
unary() {
|
|
1996
|
+
this.space();
|
|
1997
|
+
const sign = this.text[this.at];
|
|
1998
|
+
if (sign === "-" || sign === "+") {
|
|
1999
|
+
this.at++;
|
|
2000
|
+
return { type: "unary", op: sign, arg: this.unary() };
|
|
2001
|
+
}
|
|
2002
|
+
let node = this.primary();
|
|
2003
|
+
this.space();
|
|
2004
|
+
while (this.text[this.at] === "%") {
|
|
2005
|
+
this.at++;
|
|
2006
|
+
node = { type: "unary", op: "%", arg: node };
|
|
2007
|
+
}
|
|
2008
|
+
return node;
|
|
2009
|
+
}
|
|
2010
|
+
primary() {
|
|
2011
|
+
this.space();
|
|
2012
|
+
const rest = this.text.slice(this.at);
|
|
2013
|
+
if (rest[0] === "(") {
|
|
2014
|
+
this.at++;
|
|
2015
|
+
const node = this.level(0);
|
|
2016
|
+
this.expect(")");
|
|
2017
|
+
return node;
|
|
2018
|
+
}
|
|
2019
|
+
if (rest[0] === '"') {
|
|
2020
|
+
const match = /^"((?:[^"]|"")*)"/.exec(rest);
|
|
2021
|
+
if (!match) {
|
|
2022
|
+
throw new Unsupported("An open string");
|
|
2023
|
+
}
|
|
2024
|
+
this.at += match[0].length;
|
|
2025
|
+
return { type: "value", value: match[1].replace(/""/g, '"') };
|
|
2026
|
+
}
|
|
2027
|
+
const number = /^(\d+\.?\d*|\.\d+)(e[-+]?\d+)?/i.exec(rest);
|
|
2028
|
+
if (number) {
|
|
2029
|
+
this.at += number[0].length;
|
|
2030
|
+
return { type: "value", value: Number(number[0]) };
|
|
2031
|
+
}
|
|
2032
|
+
const bool = /^(TRUE|FALSE)(\s*\(\s*\))?(?![\w(])/i.exec(rest);
|
|
2033
|
+
if (bool) {
|
|
2034
|
+
this.at += bool[0].length;
|
|
2035
|
+
return { type: "value", value: bool[1].toUpperCase() === "TRUE" };
|
|
2036
|
+
}
|
|
2037
|
+
const call = /^([A-Za-z][A-Za-z0-9.]*)\s*\(/.exec(rest);
|
|
2038
|
+
if (call) {
|
|
2039
|
+
const name = call[1].toUpperCase();
|
|
2040
|
+
if (!FUNCTIONS.includes(name)) {
|
|
2041
|
+
throw new Unsupported(name);
|
|
2042
|
+
}
|
|
2043
|
+
this.at += call[0].length;
|
|
2044
|
+
const args = [];
|
|
2045
|
+
this.space();
|
|
2046
|
+
if (this.text[this.at] !== ")") {
|
|
2047
|
+
do {
|
|
2048
|
+
args.push(this.level(0));
|
|
2049
|
+
this.space();
|
|
2050
|
+
} while ((this.text[this.at] === "," || this.text[this.at] === ";") && ++this.at);
|
|
2051
|
+
}
|
|
2052
|
+
this.expect(")");
|
|
2053
|
+
return { type: "call", name, args };
|
|
2054
|
+
}
|
|
2055
|
+
const ref = /^(?:'((?:[^']|'')+)'!|([A-Za-z_\u00c0-\uffff][\w.\u00c0-\uffff]*)!)?(\$?[A-Za-z]{1,3}\$?\d+)(?::(\$?[A-Za-z]{1,3}\$?\d+))?/.exec(rest);
|
|
2056
|
+
if (ref) {
|
|
2057
|
+
this.at += ref[0].length;
|
|
2058
|
+
const name = ref[1]?.replace(/''/g, "'") ?? ref[2];
|
|
2059
|
+
const sheet = name === undefined ? this.sheet : this.book.sheets.findIndex((each) => each.name === name);
|
|
2060
|
+
if (sheet < 0) {
|
|
2061
|
+
return { type: "value", value: new CellError("#REF!") };
|
|
2062
|
+
}
|
|
2063
|
+
const area = SheetModel.range(ref[4] ? `${ref[3]}:${ref[4]}` : ref[3]);
|
|
2064
|
+
if (!area) {
|
|
2065
|
+
return { type: "value", value: new CellError("#REF!") };
|
|
2066
|
+
}
|
|
2067
|
+
return ref[4] ? { type: "range", sheet, from: area.from, to: area.to } : { type: "ref", sheet, at: area.from };
|
|
2068
|
+
}
|
|
2069
|
+
throw new Unsupported(rest);
|
|
2070
|
+
}
|
|
2071
|
+
expect(char) {
|
|
2072
|
+
this.space();
|
|
2073
|
+
if (this.text[this.at] !== char) {
|
|
2074
|
+
throw new Unsupported(`Expected ${char}`);
|
|
2075
|
+
}
|
|
2076
|
+
this.at++;
|
|
2077
|
+
}
|
|
2078
|
+
space() {
|
|
2079
|
+
while (this.text[this.at] === " ") {
|
|
2080
|
+
this.at++;
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
|
|
2085
|
+
// web-src/write-xlsx.ts
|
|
2086
|
+
var S_NS = 'xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
|
|
2087
|
+
var e3 = Ooxml.encode;
|
|
2088
|
+
var WriteXlsx;
|
|
2089
|
+
((WriteXlsx) => {
|
|
2090
|
+
function parts(code, title) {
|
|
2091
|
+
const book = SheetModel.parse(code);
|
|
2092
|
+
const calc = new SheetCalc(book);
|
|
2093
|
+
const formats = [...new Set(book.sheets.flatMap((sheet) => Object.values(sheet.formats ?? {})))];
|
|
2094
|
+
const names = sheetNames(book);
|
|
2095
|
+
const parts2 = {};
|
|
2096
|
+
const types = {
|
|
2097
|
+
"xl/workbook.xml": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
|
|
2098
|
+
"xl/styles.xml": "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"
|
|
2099
|
+
};
|
|
2100
|
+
book.sheets.forEach((sheet, index) => {
|
|
2101
|
+
const rows = [];
|
|
2102
|
+
const widths = [];
|
|
2103
|
+
sheet.cells.forEach((row, r) => {
|
|
2104
|
+
const cells = [];
|
|
2105
|
+
row.forEach((raw, c) => {
|
|
2106
|
+
if (raw === "") {
|
|
2107
|
+
return;
|
|
2108
|
+
}
|
|
2109
|
+
const at = { col: c, row: r };
|
|
2110
|
+
const format = SheetModel.formatOf(sheet, at);
|
|
2111
|
+
const style = r === 0 ? 1 : format ? 2 + formats.indexOf(format) : 0;
|
|
2112
|
+
const ref = SheetModel.name(at);
|
|
2113
|
+
const s = style ? ` s="${style}"` : "";
|
|
2114
|
+
widths[c] = Math.max(widths[c] ?? 0, width(raw.startsWith("=") ? SheetCalc.text(value(calc.value(index, at))) : raw));
|
|
2115
|
+
if (raw.startsWith("=") && raw.length > 1) {
|
|
2116
|
+
const reckoned = calc.value(index, at);
|
|
2117
|
+
const v = value(reckoned);
|
|
2118
|
+
const type = typeof v === "string" ? ' t="str"' : typeof v === "boolean" ? ' t="b"' : v instanceof CellError ? ' t="e"' : "";
|
|
2119
|
+
const cached = reckoned instanceof Unsupported ? "" : `<v>${e3(v instanceof CellError ? v.code : typeof v === "boolean" ? v ? "1" : "0" : String(v))}</v>`;
|
|
2120
|
+
cells.push(`<c r="${ref}"${s}${cached ? type : ""}><f>${e3(raw.slice(1))}</f>${cached}</c>`);
|
|
2121
|
+
return;
|
|
2122
|
+
}
|
|
2123
|
+
const literal = SheetCalc.literal(raw);
|
|
2124
|
+
if (typeof literal === "number" && /^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(raw.trim())) {
|
|
2125
|
+
cells.push(`<c r="${ref}"${s}><v>${literal}</v></c>`);
|
|
2126
|
+
} else if (typeof literal === "boolean") {
|
|
2127
|
+
cells.push(`<c r="${ref}"${s} t="b"><v>${literal ? 1 : 0}</v></c>`);
|
|
2128
|
+
} else {
|
|
2129
|
+
cells.push(`<c r="${ref}"${s} t="inlineStr"><is><t xml:space="preserve">${e3(raw)}</t></is></c>`);
|
|
2130
|
+
}
|
|
2131
|
+
});
|
|
2132
|
+
if (cells.length) {
|
|
2133
|
+
rows.push(`<row r="${r + 1}">${cells.join("")}</row>`);
|
|
2134
|
+
}
|
|
2135
|
+
});
|
|
2136
|
+
const cols = widths.length ? `<cols>${Array.from(widths, (w, c) => `<col min="${c + 1}" max="${c + 1}" width="${Math.min(60, Math.max(8, (w ?? 0) + 2))}" customWidth="1"/>`).join("")}</cols>` : "";
|
|
2137
|
+
const frozen = sheet.cells.length > 1 ? '<pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/>' : "";
|
|
2138
|
+
const path = `xl/worksheets/sheet${index + 1}.xml`;
|
|
2139
|
+
parts2[path] = Ooxml.xml(`<worksheet ${S_NS}><sheetViews><sheetView workbookViewId="0"${index === 0 ? ' tabSelected="1"' : ""}>${frozen}</sheetView></sheetViews><sheetFormatPr defaultRowHeight="15"/>${cols}<sheetData>${rows.join("")}</sheetData></worksheet>`);
|
|
2140
|
+
types[path] = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
|
|
2141
|
+
});
|
|
2142
|
+
parts2["xl/workbook.xml"] = Ooxml.xml(`<workbook ${S_NS}><bookViews><workbookView/></bookViews><sheets>${names.map((name, index) => `<sheet name="${e3(name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`).join("")}</sheets><calcPr calcId="191029" fullCalcOnLoad="1"/></workbook>`);
|
|
2143
|
+
parts2["xl/_rels/workbook.xml.rels"] = Ooxml.rels([
|
|
2144
|
+
...names.map((_, index) => ({ id: `rId${index + 1}`, type: "worksheet", target: `worksheets/sheet${index + 1}.xml` })),
|
|
2145
|
+
{ id: `rId${names.length + 1}`, type: "styles", target: "styles.xml" }
|
|
2146
|
+
]);
|
|
2147
|
+
parts2["xl/styles.xml"] = styles(formats);
|
|
2148
|
+
return { ...Ooxml.common("xl/workbook.xml", title, types), ...parts2 };
|
|
2149
|
+
}
|
|
2150
|
+
WriteXlsx.parts = parts;
|
|
2151
|
+
function value(value2) {
|
|
2152
|
+
return value2 instanceof Unsupported ? "" : value2;
|
|
2153
|
+
}
|
|
2154
|
+
function width(text) {
|
|
2155
|
+
let width2 = 0;
|
|
2156
|
+
for (const char of text.slice(0, 80)) {
|
|
2157
|
+
width2 += /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/.test(char) ? 2 : 1;
|
|
2158
|
+
}
|
|
2159
|
+
return width2;
|
|
2160
|
+
}
|
|
2161
|
+
function sheetNames(book) {
|
|
2162
|
+
const seen = new Set;
|
|
2163
|
+
return book.sheets.map((sheet, index) => {
|
|
2164
|
+
let name = sheet.name.replace(/[[\]:*?/\\]/g, " ").trim().slice(0, 31) || `Sheet${index + 1}`;
|
|
2165
|
+
for (let n = 2;seen.has(name.toLowerCase()); n++) {
|
|
2166
|
+
name = `${name.slice(0, 28)} ${n}`;
|
|
2167
|
+
}
|
|
2168
|
+
seen.add(name.toLowerCase());
|
|
2169
|
+
return name;
|
|
2170
|
+
});
|
|
2171
|
+
}
|
|
2172
|
+
function styles(formats) {
|
|
2173
|
+
const numFmts = formats.length ? `<numFmts count="${formats.length}">${formats.map((format, index) => `<numFmt numFmtId="${164 + index}" formatCode="${e3(format)}"/>`).join("")}</numFmts>` : "";
|
|
2174
|
+
const xfs = [
|
|
2175
|
+
'<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>',
|
|
2176
|
+
'<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>',
|
|
2177
|
+
...formats.map((_, index) => `<xf numFmtId="${164 + index}" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>`)
|
|
2178
|
+
];
|
|
2179
|
+
return Ooxml.xml(`<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">${numFmts}<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="${xfs.length}">${xfs.join("")}</cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`);
|
|
2180
|
+
}
|
|
2181
|
+
})(WriteXlsx ||= {});
|
|
2182
|
+
|
|
2183
|
+
// web-src/office-write.ts
|
|
2184
|
+
var OfficeWrite;
|
|
2185
|
+
((OfficeWrite) => {
|
|
2186
|
+
async function write(language, code, title) {
|
|
2187
|
+
const parts = language === DOC ? WriteDocx.parts(code, title) : language === SLIDES ? WritePptx.parts(code, title) : WriteXlsx.parts(code, title);
|
|
2188
|
+
return { data: await Ooxml.pack(parts), extension: FILES[language] };
|
|
2189
|
+
}
|
|
2190
|
+
OfficeWrite.write = write;
|
|
2191
|
+
})(OfficeWrite ||= {});
|
|
2192
|
+
|
|
2193
|
+
// web-src/extension.ts
|
|
2194
|
+
var text = (value) => ({ content: [{ type: "text", text: value }], details: {} });
|
|
2195
|
+
function activate(pi) {
|
|
2196
|
+
let served;
|
|
2197
|
+
const underServe = () => served ??= TaHostUtil.reach(pi.events, NAME).then((answer) => answer !== undefined);
|
|
2198
|
+
pi.on("session_start", () => {
|
|
2199
|
+
underServe();
|
|
2200
|
+
});
|
|
2201
|
+
pi.on("before_agent_start", async (event) => {
|
|
2202
|
+
if (await underServe()) {
|
|
2203
|
+
event.systemPromptOptions.sections = { ...event.systemPromptOptions.sections, "ta-office": OFFICE_PROMPT };
|
|
2204
|
+
}
|
|
2205
|
+
});
|
|
2206
|
+
pi.registerTool({
|
|
2207
|
+
name: "office_read",
|
|
2208
|
+
label: "Read Office file",
|
|
2209
|
+
description: "Reads a Word (.docx), PowerPoint (.pptx) or Excel (.xlsx) file as text: a ta-doc block (Markdown), a ta-slides block (Markdown, a slide at each ---) or a ta-sheet block (JSON of the cells, formulas as =…). Pictures, styles and charts are left out.",
|
|
2210
|
+
promptSnippet: "Read a .docx, .pptx or .xlsx file as a ta-doc, ta-slides or ta-sheet block",
|
|
2211
|
+
parameters: {
|
|
2212
|
+
type: "object",
|
|
2213
|
+
properties: { path: { type: "string", description: "The file, relative to the working directory or absolute" } },
|
|
2214
|
+
required: ["path"]
|
|
2215
|
+
},
|
|
2216
|
+
async execute(_id, params, _signal, _update, ctx) {
|
|
2217
|
+
const file = isAbsolute(params.path) ? params.path : resolve(ctx.cwd, params.path);
|
|
2218
|
+
const block = await OfficeRead.read(file, new Uint8Array(readFileSync(file)));
|
|
2219
|
+
const ticks = "`".repeat(Math.max(3, ...(block.code.match(/`+/g) ?? []).map((run) => run.length + 1)));
|
|
2220
|
+
return text(`"${block.title}", read from ${params.path}:
|
|
2221
|
+
${ticks}${block.language}
|
|
2222
|
+
${block.code}
|
|
2223
|
+
${ticks}`);
|
|
2224
|
+
}
|
|
2225
|
+
});
|
|
2226
|
+
pi.registerTool({
|
|
2227
|
+
name: "office_write",
|
|
2228
|
+
label: "Write Office file",
|
|
2229
|
+
description: "Writes a ta-doc, ta-slides or ta-sheet block as a Word (.docx), PowerPoint (.pptx) or Excel (.xlsx) file: headings, paragraphs, lists, tables, slides by their layout, cells with their formulas and number formats. The file is written whole, over one there is.",
|
|
2230
|
+
promptSnippet: "Save a ta-doc, ta-slides or ta-sheet block as a .docx, .pptx or .xlsx file",
|
|
2231
|
+
parameters: {
|
|
2232
|
+
type: "object",
|
|
2233
|
+
properties: {
|
|
2234
|
+
path: { type: "string", description: "The file to write, ending in .docx, .pptx or .xlsx as its language" },
|
|
2235
|
+
language: { type: "string", enum: [...LANGUAGES] },
|
|
2236
|
+
code: { type: "string", description: "The block, as it is written in the fence" },
|
|
2237
|
+
title: { type: "string", description: "The title of the file; its first heading when left out" }
|
|
2238
|
+
},
|
|
2239
|
+
required: ["path", "language", "code"]
|
|
2240
|
+
},
|
|
2241
|
+
async execute(_id, params, _signal, _update, ctx) {
|
|
2242
|
+
if (!LANGUAGES.includes(params.language) || OfficeFiles.languageOf(params.path) !== params.language) {
|
|
2243
|
+
throw new Error(`A ${params.language} block is written to a .${FILES[params.language] ?? "docx, .pptx or .xlsx"} file.`);
|
|
2244
|
+
}
|
|
2245
|
+
const file = isAbsolute(params.path) ? params.path : resolve(ctx.cwd, params.path);
|
|
2246
|
+
const title = params.title ?? params.path.replace(/^.*[\\/]/, "").replace(/\.[^.]+$/, "");
|
|
2247
|
+
const { data } = await OfficeWrite.write(params.language, params.code, title);
|
|
2248
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
2249
|
+
writeFileSync(file, data);
|
|
2250
|
+
return text(`Wrote ${params.path} (${data.length} bytes).`);
|
|
2251
|
+
}
|
|
2252
|
+
});
|
|
2253
|
+
}
|
|
2254
|
+
export {
|
|
2255
|
+
activate as default
|
|
2256
|
+
};
|