-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathindex.js
95 lines (84 loc) · 2.73 KB
/
index.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import avif from "../avif.js";
if ("serviceWorker" in navigator) {
avif.register(navigator.serviceWorker.register("../avif-sw.js"), {
wasmURL: require("dav1d.js/dav1d.wasm"),
// forcePolyfill: true,
});
}
function showExternalURL() {
document.body.innerHTML = "";
navigator.serviceWorker.addEventListener("message", e => {
const msg = e.data;
if (msg && msg.type === "avif-task") {
const blob = new Blob([msg.data], {type: "image/bmp"});
const img = document.createElement("img");
img.src = URL.createObjectURL(blob);
document.body.appendChild(img);
}
});
fetch(extURL).then(res => res.arrayBuffer()).then(avifArr => {
navigator.serviceWorker.controller.postMessage({
id: "demo",
type: "avif-task",
data: avifArr,
}, [avifArr]);
});
}
function setupInteractiveDemo() {
const loadButton = document.getElementById("load-button");
const customItem = document.getElementById("custom-item");
const fileInput = document.getElementById("file-input");
function clearItems() {
const items = document.querySelectorAll(".item:not(.user)");
for (const item of items) {
item.remove();
}
}
function emptyCustomItem() {
customItem.classList.add("hidden");
while (customItem.firstChild) {
customItem.firstChild.remove();
}
}
// TODO(Kagami): Add this to library API.
function sendDecodeRequest(file) {
const reader = new FileReader();
reader.onload = e => {
const avifArr = e.target.result;
navigator.serviceWorker.controller.postMessage({
id: "demo", // We have only single concurrent task so doesn't matter
type: "avif-task",
data: avifArr,
}, [avifArr]);
};
reader.readAsArrayBuffer(file);
}
function showCustomImage(bmpArr) {
const img = document.createElement("img");
const blob = new Blob([bmpArr], {type: "image/bmp"});
img.className = "user-img";
img.src = URL.createObjectURL(blob);
customItem.appendChild(img);
customItem.classList.remove("hidden");
loadButton.disabled = false;
}
loadButton.addEventListener("click", () => {
fileInput.click();
});
fileInput.addEventListener("change", () => {
loadButton.disabled = true;
clearItems();
emptyCustomItem();
sendDecodeRequest(fileInput.files[0]);
fileInput.value = null; // Allow to select same value second time
});
navigator.serviceWorker.addEventListener("message", e => {
const msg = e.data;
if (msg && msg.type === "avif-task") {
showCustomImage(msg.data);
}
});
}
const urlParams = new URLSearchParams(location.search);
const extURL = urlParams.get("src");
document.addEventListener("DOMContentLoaded", extURL ? showExternalURL : setupInteractiveDemo);