forked from p2r3/convert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtmlEmbed.ts
More file actions
81 lines (66 loc) · 2.57 KB
/
Copy pathhtmlEmbed.ts
File metadata and controls
81 lines (66 loc) · 2.57 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
70
71
72
73
74
75
76
77
78
79
80
81
import CommonFormats from "src/CommonFormats.ts";
import type { FileData, FileFormat, FormatHandler } from "../FormatHandler.ts";
class htmlEmbedHandler implements FormatHandler {
public name: string = "htmlEmbed";
public supportedFormats: FileFormat[] = [
CommonFormats.HTML.supported("html", false, true, true),
CommonFormats.PNG.supported("png", true, false),
CommonFormats.JPEG.supported("jpeg", true, false),
CommonFormats.WEBP.supported("webp", true, false),
CommonFormats.GIF.supported("gif", true, false),
CommonFormats.SVG.supported("svg", true, false),
CommonFormats.TEXT.supported("text", true, false),
CommonFormats.MP4.builder("mp4").allowFrom(),
CommonFormats.MP3.supported("mp3", true, false)
];
public ready: boolean = false;
async init () {
this.ready = true;
}
static bytesToBase64 (bytes: Uint8Array): string {
const chunks = [];
for (let i = 0; i < bytes.length; i += 32768) {
const byteChunk = bytes.subarray(i, i + 32768);
chunks.push(String.fromCharCode(...byteChunk));
}
return btoa(chunks.join(""));
}
async doConvert (
inputFiles: FileData[],
inputFormat: FileFormat,
outputFormat: FileFormat
): Promise<FileData[]> {
if (outputFormat.internal !== "html") throw "Invalid output format.";
const encoder = new TextEncoder();
let html = "";
if (inputFormat.internal === "text") {
const decoder = new TextDecoder();
for (const inputFile of inputFiles) {
const text = decoder.decode(inputFile.bytes)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">");
html += `<pre>${text}</pre>`;
}
} else {
for (const inputFile of inputFiles) {
const base64 = htmlEmbedHandler.bytesToBase64(inputFile.bytes);
if (inputFormat.mime.startsWith("image/")) {
html += `<img src="data:${inputFormat.mime};base64,${base64}"><br>`;
} else if (inputFormat.mime.startsWith("audio/")) {
html += `<audio controls>
<source src="data:${inputFormat.mime};base64,${base64}" type="${inputFormat.mime}"></source>
</audio><br>`;
} else {
html += `<video controls>
<source src="data:${inputFormat.mime};base64,${base64}" type="${inputFormat.mime}"></source>
</video><br>`;
}
}
}
const bytes = encoder.encode(html);
const name = inputFiles[0].name.split(".").slice(0, -1).join(".") + "." + outputFormat.extension;
return [{ bytes, name }];
}
}
export default htmlEmbedHandler;