-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathtypst.ts
More file actions
70 lines (57 loc) · 2.12 KB
/
Copy pathtypst.ts
File metadata and controls
70 lines (57 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import CommonFormats from "src/CommonFormats.ts";
import type { FileData, FileFormat, FormatHandler } from "../FormatHandler.ts";
import type { TypstSnippet } from "@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs";
import { BadMagicError, EOFError, InitializationError } from "src/errors.ts";
class TypstHandler implements FormatHandler {
public name: string = "typst";
public ready: boolean = false;
public supportedFormats: FileFormat[] = [
CommonFormats.TYPST.supported("typst", true, false, true),
CommonFormats.PDF.supported("pdf", false, true),
CommonFormats.SVG.supported("svg", false, true),
];
private $typst?: TypstSnippet;
async init() {
const { $typst } = await import(
"@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs"
);
$typst.setCompilerInitOptions({
getModule: () =>
`${import.meta.env.BASE_URL}wasm/typst_ts_web_compiler_bg.wasm`,
});
$typst.setRendererInitOptions({
getModule: () =>
`${import.meta.env.BASE_URL}wasm/typst_ts_renderer_bg.wasm`,
});
this.$typst = $typst;
this.ready = true;
}
async doConvert(
inputFiles: FileData[],
_inputFormat: FileFormat,
outputFormat: FileFormat,
): Promise<FileData[]> {
if (!this.ready || !this.$typst) throw new InitializationError("Handler not initialized.");
const outputFiles: FileData[] = [];
for (const file of inputFiles) {
const mainContent = new TextDecoder().decode(file.bytes);
const baseName = file.name.replace(/\.[^.]+$/u, "");
if (outputFormat.internal === "pdf") {
const pdfData = await this.$typst.pdf({ mainContent });
if (!pdfData) throw new Error("Typst compilation to PDF failed.");
outputFiles.push({
name: `${baseName}.pdf`,
bytes: new Uint8Array(pdfData),
});
} else if (outputFormat.internal === "svg") {
const svgString = await this.$typst.svg({ mainContent });
outputFiles.push({
name: `${baseName}.svg`,
bytes: new TextEncoder().encode(svgString),
});
}
}
return outputFiles;
}
}
export default TypstHandler;