-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathgallery.js
More file actions
184 lines (161 loc) · 5.76 KB
/
Copy pathgallery.js
File metadata and controls
184 lines (161 loc) · 5.76 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/* The gallery wall. Sketches are other people's code, so none of it runs on
this page: each one renders in its own sandboxed frame (gallery-frame.js)
and only the finished PNG comes back. Everything from the API is set with
textContent or as a checked URL, never as HTML. */
// Some sketches shade every pixel with layered noise and take a while.
const RENDER_TIMEOUT = 60000;
const PARALLEL = 2;
const wall = document.querySelector("[data-wall]");
const status = document.querySelector("[data-status]");
load();
async function load() {
let items;
try {
const res = await fetch("/api/gallery");
if (!res.ok) throw new Error(res.status);
({ items } = await res.json());
} catch {
status.textContent = "Couldn't fetch the gallery. Try again in a minute.";
return;
}
if (!items.length) {
status.textContent = "Nothing on the wall yet. Be the first!";
return;
}
status.hidden = true;
const cards = items.map((item, index) => {
const card = buildCard(item, index);
wall.append(card.root);
return { item, ...card };
});
// The cards are built after load, so the browser's own jump to the hash (and
// :target) never finds them. Do it here instead.
history.scrollRestoration = "manual";
showLinked();
addEventListener("hashchange", showLinked);
// Print only what's about to be seen, nearest first, a couple at a time.
const queue = [];
let running = 0;
const pump = () => {
while (running < PARALLEL && queue.length) {
const card = queue.shift();
running += 1;
renderSketch(card.item.source)
.then(card.show, (error) => card.fail(error.message))
.finally(() => {
running -= 1;
pump();
});
}
};
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
observer.unobserve(entry.target);
queue.push(cards.find((card) => card.root === entry.target));
}
pump();
},
{ rootMargin: "600px 0px" },
);
for (const card of cards) observer.observe(card.root);
}
function showLinked() {
const slug = decodeURIComponent(location.hash.slice(1)).toLowerCase();
for (const item of wall.children) item.classList.toggle("is-linked", item.id === slug);
if (slug) document.getElementById(slug)?.scrollIntoView({ block: "center" });
}
function buildCard(item, index) {
const root = el("li", "wall-item");
root.id = item.slug;
root.style.setProperty("--tilt", `${[-2.2, 1.4, -0.8, 2.4, -1.6, 0.9][index % 6]}deg`);
const art = el("a", "wall-art");
art.href = `#${item.slug}`;
art.setAttribute("aria-label", `Receipt by @${item.author}`);
art.append(el("span", "tape"));
const paper = el("div", "wall-paper");
paper.textContent = "printing…";
if (item.height) paper.style.aspectRatio = `384 / ${item.height}`;
art.append(paper);
const caption = el("p", "wall-caption");
caption.append("By ");
const author = item.slackId ? el("a") : el("span");
author.textContent = `@${item.author}`;
if (item.slackId) {
author.href = `https://hackclub.slack.com/team/${encodeURIComponent(item.slackId)}`;
author.target = "_blank";
author.rel = "noopener";
}
caption.append(author);
const code = el("a", "wall-code");
code.textContent = "sketch.js ↗";
code.href = githubUrl(item.sketchUrl);
code.target = "_blank";
code.rel = "noopener";
root.append(art, caption, code);
return {
root,
show(blob) {
const img = new Image(384);
img.alt = `Receipt artwork by @${item.author}`;
img.src = URL.createObjectURL(blob);
paper.replaceWith(img);
},
fail(message) {
paper.classList.add("wall-paper-error");
paper.textContent = `this one jammed the printer: ${message}`;
},
};
}
/* One throwaway frame per sketch; see gallery-frame.js for why. */
function renderSketch(source) {
return new Promise((resolve, reject) => {
const frame = document.createElement("iframe");
frame.className = "render-frame";
frame.setAttribute("sandbox", "allow-scripts");
frame.setAttribute("aria-hidden", "true");
frame.tabIndex = -1;
frame.src = "/gallery-frame.html";
const done = (fn, value) => {
clearTimeout(timer);
removeEventListener("message", onMessage);
frame.remove();
fn(value);
};
const timer = setTimeout(() => done(reject, new Error("took too long")), RENDER_TIMEOUT);
function onMessage(event) {
if (event.source !== frame.contentWindow) return;
const data = event.data || {};
if (data.ready) frame.contentWindow.postMessage({ source }, "*");
else if (data.png instanceof Blob) isPng(data.png).then((ok) => (ok ? done(resolve, asPng(data.png)) : done(reject, new Error("not a PNG"))));
else done(reject, new Error(String(data.error || "unknown error").slice(0, 200)));
}
addEventListener("message", onMessage);
document.body.append(frame);
});
}
/* The Blob comes from a sketch, and its type is whatever the sketch says. Its
object URL is on this site's origin, so a Blob typed text/html, opened with
"open image in new tab", would be a page on this site. Only a real PNG, typed
as one, gets a URL. */
async function isPng(blob) {
const head = new Uint8Array(await blob.slice(0, 8).arrayBuffer());
return [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((byte, i) => head[i] === byte);
}
function asPng(blob) {
return new Blob([blob], { type: "image/png" });
}
function githubUrl(value) {
try {
const url = new URL(value);
return url.protocol === "https:" && url.hostname === "github.com" ? url.href : "#";
} catch {
return "#";
}
}
function el(tag, className) {
const node = document.createElement(tag);
if (className) node.className = className;
return node;
}