Anti-scraping: 3x3 grids, decoy pools, robot check
Every pyramid level is cut into at least min_grid x min_grid tiles. Each photo's tile pool mixes real tiles with hard-linked decoys from other photos; the grid-to-pool map, byte sizes, seed and scramble seed are sealed per build and unlocked by a press-and-hold check backed by a static proof of work. Cell scrambling is on by default, and robots.txt disallows tiles and pool files. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
aaf7cafdf9
commit
f5152fb709
30 files changed
+2136
-203
No files matched your search
+149
@@ -481,6 +481,155 @@ html:not(.has-strips) .strip-subtitle {
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.has-gate,
|
||||
.has-gate body {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.gate {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
padding: var(--gutter);
|
||||
background: var(--veil);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
backdrop-filter: blur(12px);
|
||||
transition: opacity var(--lucio-motion-base) var(--lucio-ease-base);
|
||||
}
|
||||
|
||||
.gate.is-leaving {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.gate-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--lucio-space-4);
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
padding: var(--lucio-space-6) var(--lucio-space-5);
|
||||
background: var(--lucio-graphite-2);
|
||||
border: 1px solid var(--lucio-graphite-3);
|
||||
border-radius: var(--lucio-radius-lg);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.gate-eyebrow {
|
||||
margin: 0;
|
||||
font-family: var(--lucio-font-mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--lucio-ash-light);
|
||||
}
|
||||
|
||||
.gate-line {
|
||||
margin: 0 0 var(--lucio-space-2);
|
||||
font-family: var(--lucio-font-display);
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--lucio-paper);
|
||||
}
|
||||
|
||||
.gate-hold {
|
||||
display: block;
|
||||
width: 88px;
|
||||
height: 88px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
background: var(--lucio-graphite-3);
|
||||
cursor: pointer;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
-webkit-touch-callout: none;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
transition: transform var(--lucio-motion-fast) var(--lucio-ease-fast), box-shadow var(--lucio-motion-fast) var(--lucio-ease-fast);
|
||||
}
|
||||
|
||||
.gate-hold:hover,
|
||||
.gate-hold.is-pressed {
|
||||
box-shadow: var(--lucio-shadow-glow);
|
||||
}
|
||||
|
||||
.gate-hold.is-pressed {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
|
||||
.gate-hold:focus-visible {
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
.gate-hold:disabled {
|
||||
cursor: default;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.gate-hold svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.gate-track,
|
||||
.gate-ring {
|
||||
fill: none;
|
||||
stroke-width: 3;
|
||||
}
|
||||
|
||||
.gate-track {
|
||||
stroke: var(--lucio-ash-dark);
|
||||
}
|
||||
|
||||
.gate-ring {
|
||||
stroke: var(--lucio-beam);
|
||||
stroke-linecap: round;
|
||||
stroke-dasharray: 100;
|
||||
stroke-dashoffset: 100;
|
||||
transition: stroke-dashoffset var(--lucio-motion-base) var(--lucio-ease-base);
|
||||
}
|
||||
|
||||
.gate-hold.is-pressed .gate-ring {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.gate-dot {
|
||||
fill: var(--lucio-paper);
|
||||
transform-origin: 32px 32px;
|
||||
transition: transform var(--lucio-motion-fast) var(--lucio-ease-fast);
|
||||
}
|
||||
|
||||
.gate-hold.is-pressed .gate-dot {
|
||||
transform: scale(1.5);
|
||||
}
|
||||
|
||||
.gate.is-waiting .gate-hold svg {
|
||||
animation: gate-spin 900ms linear infinite;
|
||||
}
|
||||
|
||||
@keyframes gate-spin {
|
||||
from {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(270deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
|
||||
+20
-6
@@ -1,5 +1,6 @@
|
||||
import { mountWordmark } from "./brand";
|
||||
import { TileCache, cacheBudget } from "./cache";
|
||||
import { Gate } from "./gate";
|
||||
import { IndexPage } from "./index";
|
||||
import { Scheduler } from "./scheduler";
|
||||
import { readSettings, type Manifest, type Settings, type SiteIndex } from "./types";
|
||||
@@ -17,20 +18,27 @@ function shared(settings: Settings): { scheduler: Scheduler; cache: TileCache }
|
||||
return { scheduler: new Scheduler(settings.concurrency, settings.workerUrl), cache: new TileCache(cacheBudget()) };
|
||||
}
|
||||
|
||||
async function startAlbum(stage: HTMLElement, settings: Settings): Promise<void> {
|
||||
async function startAlbum(stage: HTMLElement, settings: Settings, gate: Gate): Promise<void> {
|
||||
const manifest = await fetchJSON<Manifest>(settings.manifestUrl);
|
||||
if (manifest.photos.length === 0) {
|
||||
gate.abandon();
|
||||
return;
|
||||
}
|
||||
gate.configure(manifest.gate);
|
||||
const { scheduler, cache } = shared(settings);
|
||||
document.documentElement.classList.add("has-viewer");
|
||||
lifecycle(new Viewer(stage, manifest, settings, { scheduler, cache, settings, tiles: manifest.tiles }));
|
||||
lifecycle(new Viewer(stage, manifest, settings, { scheduler, cache, settings, gate, tiles: manifest.tiles }));
|
||||
}
|
||||
|
||||
async function startIndex(root: HTMLElement, settings: Settings): Promise<void> {
|
||||
async function startIndex(root: HTMLElement, settings: Settings, gate: Gate): Promise<void> {
|
||||
const index = await fetchJSON<SiteIndex>(settings.indexUrl);
|
||||
if (index.albums.length === 0) {
|
||||
gate.abandon();
|
||||
return;
|
||||
}
|
||||
gate.configure(index.gate);
|
||||
const { scheduler, cache } = shared(settings);
|
||||
lifecycle(new IndexPage(root, index, settings, { scheduler, cache, settings, tiles: index.tiles }));
|
||||
lifecycle(new IndexPage(root, index, settings, { scheduler, cache, settings, gate, tiles: index.tiles }));
|
||||
}
|
||||
|
||||
interface Suspendable {
|
||||
@@ -64,7 +72,11 @@ function boot(): void {
|
||||
if (settings.page === "album") {
|
||||
const stage = document.getElementById("stage");
|
||||
if (stage) {
|
||||
startAlbum(stage, settings).catch(() => showLoadError());
|
||||
const gate = new Gate(settings.build, settings.gate, settings.workerUrl);
|
||||
startAlbum(stage, settings, gate).catch(() => {
|
||||
gate.abandon();
|
||||
showLoadError();
|
||||
});
|
||||
}
|
||||
} else if (settings.page === "notfound") {
|
||||
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
|
||||
@@ -74,7 +86,9 @@ function boot(): void {
|
||||
} else if (settings.page === "index") {
|
||||
const root = document.getElementById("strips");
|
||||
if (root) {
|
||||
startIndex(root, settings).catch(() => {
|
||||
const gate = new Gate(settings.build, settings.gate, settings.workerUrl);
|
||||
startIndex(root, settings, gate).catch(() => {
|
||||
gate.abandon();
|
||||
document.documentElement.classList.remove("has-strips");
|
||||
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
|
||||
if (header && !header.classList.contains("has-svg")) {
|
||||
|
||||
+400
@@ -0,0 +1,400 @@
|
||||
import { PowSearch, deriveKey, fromHex, toHex } from "./sha256";
|
||||
import type { GateInfo } from "./types";
|
||||
|
||||
const storageKey = "luphoto.pass";
|
||||
const holdMs = 900;
|
||||
const sliceSize = 1 << 14;
|
||||
const svgNS = "http://www.w3.org/2000/svg";
|
||||
const line = "Press and hold to see the photos";
|
||||
|
||||
let memoryPass: string | null = null;
|
||||
|
||||
interface Pass {
|
||||
build: string;
|
||||
s: string;
|
||||
}
|
||||
|
||||
function readPass(): Pass | null {
|
||||
let raw = memoryPass;
|
||||
try {
|
||||
raw = localStorage.getItem(storageKey) ?? raw;
|
||||
} catch {
|
||||
raw = memoryPass;
|
||||
}
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const pass = JSON.parse(raw) as Partial<Pass>;
|
||||
if (typeof pass.build === "string" && typeof pass.s === "string" && /^[0-9a-f]{64}$/.test(pass.s)) {
|
||||
return { build: pass.build, s: pass.s };
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function writePass(pass: Pass | null): void {
|
||||
memoryPass = pass ? JSON.stringify(pass) : null;
|
||||
try {
|
||||
if (memoryPass) {
|
||||
localStorage.setItem(storageKey, memoryPass);
|
||||
} else {
|
||||
localStorage.removeItem(storageKey);
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export class Gate {
|
||||
key: Uint8Array | null = null;
|
||||
private stored = false;
|
||||
private found: Uint8Array | null = null;
|
||||
private held = false;
|
||||
private info: GateInfo | null = null;
|
||||
private card: GateCard | null = null;
|
||||
private worker: Worker | null = null;
|
||||
private readonly listeners: Array<() => void> = [];
|
||||
|
||||
constructor(
|
||||
private readonly build: string,
|
||||
private readonly enabled: boolean,
|
||||
private readonly workerUrl: string,
|
||||
) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const pass = readPass();
|
||||
if (pass && pass.build === build) {
|
||||
this.key = fromHex(pass.s);
|
||||
this.stored = true;
|
||||
return;
|
||||
}
|
||||
this.card = new GateCard(() => this.onHeld());
|
||||
}
|
||||
|
||||
onUnlock(listener: () => void): void {
|
||||
this.listeners.push(listener);
|
||||
}
|
||||
|
||||
configure(info: GateInfo): void {
|
||||
if (this.info) {
|
||||
return;
|
||||
}
|
||||
this.info = info;
|
||||
if (info.key) {
|
||||
this.found = fromHex(info.key);
|
||||
this.unlock(false);
|
||||
return;
|
||||
}
|
||||
if (this.key && info.build !== this.build) {
|
||||
this.reset();
|
||||
return;
|
||||
}
|
||||
if (!this.key) {
|
||||
this.search();
|
||||
}
|
||||
}
|
||||
|
||||
reject(key: Uint8Array): void {
|
||||
if (key !== this.key || !this.stored || !this.info || this.info.key) {
|
||||
return;
|
||||
}
|
||||
this.reset();
|
||||
}
|
||||
|
||||
abandon(): void {
|
||||
this.card?.dismiss();
|
||||
this.card = null;
|
||||
this.worker?.terminate();
|
||||
this.worker = null;
|
||||
}
|
||||
|
||||
private reset(): void {
|
||||
writePass(null);
|
||||
this.key = null;
|
||||
this.stored = false;
|
||||
this.held = false;
|
||||
this.found = null;
|
||||
if (!this.card) {
|
||||
this.card = new GateCard(() => this.onHeld());
|
||||
}
|
||||
this.search();
|
||||
}
|
||||
|
||||
private search(): void {
|
||||
const info = this.info;
|
||||
if (!info || !info.salt || !info.check || !info.bits || this.worker) {
|
||||
return;
|
||||
}
|
||||
const salt = fromHex(info.salt);
|
||||
const done = (n: number) => {
|
||||
this.worker?.terminate();
|
||||
this.worker = null;
|
||||
if (n < 0) {
|
||||
this.card?.fail();
|
||||
return;
|
||||
}
|
||||
this.found = deriveKey(salt, n);
|
||||
if (this.held) {
|
||||
this.unlock(true);
|
||||
}
|
||||
};
|
||||
const fallback = () => this.searchHere(salt, fromHex(info.check ?? ""), info.bits ?? 0, done);
|
||||
if (typeof Worker === "undefined" || !this.workerUrl) {
|
||||
fallback();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const worker = new Worker(this.workerUrl);
|
||||
this.worker = worker;
|
||||
worker.onmessage = (event: MessageEvent<{ pow?: number }>) => {
|
||||
if (typeof event.data.pow === "number" && this.worker === worker) {
|
||||
done(event.data.pow);
|
||||
}
|
||||
};
|
||||
worker.onerror = () => {
|
||||
if (this.worker === worker) {
|
||||
worker.terminate();
|
||||
this.worker = null;
|
||||
fallback();
|
||||
}
|
||||
};
|
||||
worker.postMessage({ type: "pow", salt: info.salt, check: info.check, bits: info.bits });
|
||||
} catch {
|
||||
this.worker = null;
|
||||
fallback();
|
||||
}
|
||||
}
|
||||
|
||||
private searchHere(salt: Uint8Array, check: Uint8Array, bits: number, done: (n: number) => void): void {
|
||||
const search = new PowSearch(salt, check);
|
||||
const end = 2 ** bits;
|
||||
let from = 0;
|
||||
const step = () => {
|
||||
const to = Math.min(end, from + sliceSize);
|
||||
const n = search.run(from, to);
|
||||
from = to;
|
||||
if (n >= 0 || from >= end) {
|
||||
done(n);
|
||||
return;
|
||||
}
|
||||
setTimeout(step, 0);
|
||||
};
|
||||
setTimeout(step, 0);
|
||||
}
|
||||
|
||||
private onHeld(): void {
|
||||
this.held = true;
|
||||
if (this.found) {
|
||||
this.unlock(true);
|
||||
} else {
|
||||
this.card?.wait();
|
||||
}
|
||||
}
|
||||
|
||||
private unlock(remember: boolean): void {
|
||||
if (!this.found) {
|
||||
return;
|
||||
}
|
||||
this.key = this.found;
|
||||
this.stored = false;
|
||||
if (remember && this.enabled) {
|
||||
writePass({ build: this.info?.build ?? this.build, s: toHex(this.key) });
|
||||
}
|
||||
this.card?.dismiss();
|
||||
this.card = null;
|
||||
for (const listener of this.listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class GateCard {
|
||||
private readonly root: HTMLElement;
|
||||
private readonly button: HTMLButtonElement;
|
||||
private readonly ring: SVGCircleElement;
|
||||
private readonly status: HTMLElement;
|
||||
private readonly text: HTMLElement;
|
||||
private readonly inert: Element[] = [];
|
||||
private readonly restore: Element | null;
|
||||
private start = 0;
|
||||
private frame = 0;
|
||||
private holding = false;
|
||||
private finished = false;
|
||||
|
||||
constructor(private readonly onHeld: () => void) {
|
||||
this.restore = document.activeElement;
|
||||
const root = document.createElement("div");
|
||||
root.className = "gate";
|
||||
root.setAttribute("role", "dialog");
|
||||
root.setAttribute("aria-modal", "true");
|
||||
root.setAttribute("aria-labelledby", "gate-line");
|
||||
const card = document.createElement("div");
|
||||
card.className = "gate-card";
|
||||
const eyebrow = document.createElement("p");
|
||||
eyebrow.className = "gate-eyebrow";
|
||||
eyebrow.textContent = "Photos · Lucio";
|
||||
const text = document.createElement("p");
|
||||
text.className = "gate-line";
|
||||
text.id = "gate-line";
|
||||
text.textContent = line;
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "gate-hold";
|
||||
button.setAttribute("aria-label", "Hold to see the photos");
|
||||
button.setAttribute("aria-describedby", "gate-status");
|
||||
const svg = document.createElementNS(svgNS, "svg");
|
||||
svg.setAttribute("viewBox", "0 0 64 64");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
svg.setAttribute("focusable", "false");
|
||||
const circle = (cls: string, r: string): SVGCircleElement => {
|
||||
const c = document.createElementNS(svgNS, "circle");
|
||||
c.setAttribute("class", cls);
|
||||
c.setAttribute("cx", "32");
|
||||
c.setAttribute("cy", "32");
|
||||
c.setAttribute("r", r);
|
||||
return c;
|
||||
};
|
||||
const ring = circle("gate-ring", "28");
|
||||
ring.setAttribute("pathLength", "100");
|
||||
svg.append(circle("gate-track", "28"), ring, circle("gate-dot", "6"));
|
||||
button.appendChild(svg);
|
||||
const status = document.createElement("p");
|
||||
status.className = "visually-hidden";
|
||||
status.id = "gate-status";
|
||||
status.setAttribute("aria-live", "polite");
|
||||
card.append(eyebrow, text, button, status);
|
||||
root.appendChild(card);
|
||||
this.root = root;
|
||||
this.button = button;
|
||||
this.ring = ring;
|
||||
this.status = status;
|
||||
this.text = text;
|
||||
for (const child of Array.from(document.body.children)) {
|
||||
if (!child.hasAttribute("inert")) {
|
||||
child.setAttribute("inert", "");
|
||||
this.inert.push(child);
|
||||
}
|
||||
}
|
||||
document.body.appendChild(root);
|
||||
document.documentElement.classList.add("has-gate");
|
||||
this.bind();
|
||||
button.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
private bind(): void {
|
||||
const button = this.button;
|
||||
button.addEventListener("pointerdown", (e) => {
|
||||
if (e.pointerType === "mouse" && e.button !== 0) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
button.setPointerCapture(e.pointerId);
|
||||
this.press();
|
||||
});
|
||||
for (const type of ["pointerup", "pointercancel", "lostpointercapture"]) {
|
||||
button.addEventListener(type, () => this.release());
|
||||
}
|
||||
button.addEventListener("keydown", (e) => {
|
||||
if (e.key === " " || e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) {
|
||||
this.press();
|
||||
}
|
||||
}
|
||||
});
|
||||
button.addEventListener("keyup", (e) => {
|
||||
if (e.key === " " || e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
this.release();
|
||||
}
|
||||
});
|
||||
button.addEventListener("blur", () => this.release());
|
||||
button.addEventListener("click", (e) => e.preventDefault());
|
||||
button.addEventListener("contextmenu", (e) => e.preventDefault());
|
||||
this.root.addEventListener("transitionend", (e) => {
|
||||
if (e.target === this.root && this.root.classList.contains("is-leaving")) {
|
||||
this.root.remove();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private setProgress(fraction: number): void {
|
||||
this.ring.style.setProperty("stroke-dashoffset", String(100 - Math.max(0, Math.min(1, fraction)) * 100));
|
||||
}
|
||||
|
||||
private press(): void {
|
||||
if (this.holding || this.finished) {
|
||||
return;
|
||||
}
|
||||
this.holding = true;
|
||||
this.start = performance.now();
|
||||
this.button.classList.add("is-pressed");
|
||||
this.status.textContent = "Keep holding";
|
||||
const tick = (now: number) => {
|
||||
if (!this.holding) {
|
||||
return;
|
||||
}
|
||||
const fraction = (now - this.start) / holdMs;
|
||||
this.setProgress(fraction);
|
||||
if (fraction >= 1) {
|
||||
this.holding = false;
|
||||
this.finished = true;
|
||||
this.frame = 0;
|
||||
this.button.classList.remove("is-pressed");
|
||||
this.onHeld();
|
||||
return;
|
||||
}
|
||||
this.frame = requestAnimationFrame(tick);
|
||||
};
|
||||
this.frame = requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
private release(): void {
|
||||
if (!this.holding) {
|
||||
return;
|
||||
}
|
||||
this.holding = false;
|
||||
cancelAnimationFrame(this.frame);
|
||||
this.frame = 0;
|
||||
this.button.classList.remove("is-pressed");
|
||||
this.setProgress(0);
|
||||
this.status.textContent = "";
|
||||
}
|
||||
|
||||
wait(): void {
|
||||
this.root.classList.add("is-waiting");
|
||||
this.setProgress(0.28);
|
||||
this.status.textContent = "One moment";
|
||||
}
|
||||
|
||||
fail(): void {
|
||||
this.root.classList.remove("is-waiting");
|
||||
this.finished = true;
|
||||
this.setProgress(0);
|
||||
this.button.disabled = true;
|
||||
this.text.textContent = "Something went wrong. Reload the page to try again.";
|
||||
this.status.textContent = this.text.textContent;
|
||||
}
|
||||
|
||||
dismiss(): void {
|
||||
cancelAnimationFrame(this.frame);
|
||||
const hadFocus = this.root.contains(document.activeElement);
|
||||
for (const element of this.inert) {
|
||||
element.removeAttribute("inert");
|
||||
}
|
||||
document.documentElement.classList.remove("has-gate");
|
||||
this.root.classList.add("is-leaving");
|
||||
window.setTimeout(() => this.root.remove(), 400);
|
||||
if (hadFocus) {
|
||||
const target =
|
||||
this.restore instanceof HTMLElement && this.restore !== document.body && this.restore.isConnected
|
||||
? this.restore
|
||||
: document.querySelector<HTMLElement>("main");
|
||||
target?.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-5
@@ -32,7 +32,8 @@ export function neededLevel(pyramid: Pyramid, displayWidth: number, dpr: number)
|
||||
return pyramid.levels.length - 1;
|
||||
}
|
||||
|
||||
export function tileRange(level: Level, view: View, tileSize: number): TileRange | null {
|
||||
export function tileRange(level: Level, view: View): TileRange | null {
|
||||
const tileSize = level.tile_size;
|
||||
const a = Math.max(0, view.u0 * level.width);
|
||||
const b = Math.min(level.width, view.u1 * level.width);
|
||||
const c = Math.max(0, view.v0 * level.height);
|
||||
@@ -48,9 +49,10 @@ export function tileRange(level: Level, view: View, tileSize: number): TileRange
|
||||
};
|
||||
}
|
||||
|
||||
export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View, tileSize: number): TileRef[] {
|
||||
export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View): TileRef[] {
|
||||
const level = pyramid.levels[levelIndex];
|
||||
const range = tileRange(level, view, tileSize);
|
||||
const tileSize = level.tile_size;
|
||||
const range = tileRange(level, view);
|
||||
if (!range) {
|
||||
return [];
|
||||
}
|
||||
@@ -68,18 +70,37 @@ export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View, t
|
||||
return tiles.map(({ level: l, x, y, index }) => ({ level: l, x, y, index }));
|
||||
}
|
||||
|
||||
export interface CellRect {
|
||||
dx: number;
|
||||
dy: number;
|
||||
dw: number;
|
||||
dh: number;
|
||||
}
|
||||
|
||||
export function cellRect(level: Level, x: number, y: number, originX: number, originY: number, scale: number): CellRect | null {
|
||||
const tileSize = level.tile_size;
|
||||
const dx0 = Math.round(originX + x * tileSize * scale);
|
||||
const dx1 = Math.round(originX + Math.min((x + 1) * tileSize, level.width) * scale);
|
||||
const dy0 = Math.round(originY + y * tileSize * scale);
|
||||
const dy1 = Math.round(originY + Math.min((y + 1) * tileSize, level.height) * scale);
|
||||
if (dx1 <= dx0 || dy1 <= dy0) {
|
||||
return null;
|
||||
}
|
||||
return { dx: dx0, dy: dy0, dw: dx1 - dx0, dh: dy1 - dy0 };
|
||||
}
|
||||
|
||||
export function drawTile(
|
||||
g: CanvasRenderingContext2D,
|
||||
bitmap: { width: number; height: number } & CanvasImageSource,
|
||||
level: Level,
|
||||
x: number,
|
||||
y: number,
|
||||
tileSize: number,
|
||||
overlap: number,
|
||||
originX: number,
|
||||
originY: number,
|
||||
scale: number,
|
||||
): void {
|
||||
const tileSize = level.tile_size;
|
||||
const overlap = level.overlap ?? 0;
|
||||
const lx0 = x * tileSize;
|
||||
const lx1 = Math.min((x + 1) * tileSize, level.width);
|
||||
const ly0 = y * tileSize;
|
||||
|
||||
+17
-2
@@ -1,7 +1,7 @@
|
||||
import { mountWordmark, type MorphHandle } from "./brand";
|
||||
import { BusyIndicator } from "./indicator";
|
||||
import { Strip, type StripEnv } from "./strip";
|
||||
import type { SiteIndex, Settings } from "./types";
|
||||
import { poolUrl, type SiteIndex, type Settings } from "./types";
|
||||
|
||||
const hysteresis = 24;
|
||||
|
||||
@@ -30,7 +30,11 @@ export class IndexPage {
|
||||
if (!album || !album.cover) {
|
||||
continue;
|
||||
}
|
||||
this.strips.push(new Strip(anchor, album.cover, album.collapsed_focus_y ?? 0.5, env, (strip) => this.onStripStatus(strip)));
|
||||
this.strips.push(
|
||||
new Strip(anchor, album.cover, album.collapsed_focus_y ?? 0.5, poolUrl(index.build, album.slug, album.cover.hash), env, (strip) =>
|
||||
this.onStripStatus(strip),
|
||||
),
|
||||
);
|
||||
}
|
||||
this.hoverMode = matchMedia("(hover: hover) and (pointer: fine)");
|
||||
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
|
||||
@@ -52,6 +56,17 @@ export class IndexPage {
|
||||
this.measure();
|
||||
this.observe();
|
||||
this.bind();
|
||||
env.gate.onUnlock(() => {
|
||||
if (this.suspended) {
|
||||
return;
|
||||
}
|
||||
for (const strip of this.strips) {
|
||||
if (strip.isNear) {
|
||||
strip.startSession();
|
||||
}
|
||||
strip.requestDraw();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
suspend(hidden: boolean): void {
|
||||
|
||||
+294
-57
@@ -1,15 +1,18 @@
|
||||
import type { TileCache } from "./cache";
|
||||
import { drawTile, neededLevel, tileRange, visibleTiles, type TileRef, type View } from "./geometry";
|
||||
import type { Gate } from "./gate";
|
||||
import { cellRect, drawTile, neededLevel, tileRange, visibleTiles, type TileRef, type View } from "./geometry";
|
||||
import { AbortError, PRIORITY_CURRENT, PRIORITY_PREFETCH, decodeBlob, releaseImage, type Scheduler, type TileResult } from "./scheduler";
|
||||
import type { ScrambleSpec } from "./scramble";
|
||||
import { fromBase64, unseal } from "./sha256";
|
||||
import { currentThroughput, recordThroughput } from "./throughput";
|
||||
import type { Pyramid, Settings, Tiles } from "./types";
|
||||
import type { PoolFile, Pyramid, Sealed, Settings, Tiles } from "./types";
|
||||
|
||||
export interface LoaderEnv {
|
||||
scheduler: Scheduler;
|
||||
cache: TileCache;
|
||||
settings: Settings;
|
||||
tiles: Tiles;
|
||||
gate: Gate;
|
||||
requestDraw: () => void;
|
||||
onStatus?: (loader: PhotoLoader) => void;
|
||||
}
|
||||
@@ -24,6 +27,9 @@ export interface LoadStatus {
|
||||
|
||||
const fadeMs = 180;
|
||||
const retryMs = 400;
|
||||
const poolRetryMs = 2000;
|
||||
const idWidth = 16;
|
||||
const jumbleKey = "j:";
|
||||
|
||||
function wait(ms: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -42,6 +48,21 @@ function wait(ms: number, signal: AbortSignal): Promise<void> {
|
||||
signal.addEventListener("abort", stop, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function until<T>(promise: Promise<T>, signal: AbortSignal, fallback: T): Promise<T> {
|
||||
if (signal.aborted) {
|
||||
return Promise.resolve(fallback);
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const stop = () => resolve(fallback);
|
||||
signal.addEventListener("abort", stop, { once: true });
|
||||
void promise.then((value) => {
|
||||
signal.removeEventListener("abort", stop);
|
||||
resolve(value);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const probeStep = 3;
|
||||
const seedUpscale = 4;
|
||||
|
||||
@@ -61,23 +82,134 @@ export interface DrawTarget {
|
||||
export class PhotoLoader {
|
||||
private seedImage: CanvasImageSource | null = null;
|
||||
private seedPromise: Promise<void> | null = null;
|
||||
private seedAt = 0;
|
||||
private pool: string[] | null = null;
|
||||
private sealed = "";
|
||||
private poolPromise: Promise<boolean> | null = null;
|
||||
private poolRetryAt = 0;
|
||||
private opened: Sealed | null = null;
|
||||
private ids: string[][] | null = null;
|
||||
private triedKey: Uint8Array | null = null;
|
||||
private jumbleLevel = -1;
|
||||
private jumble: string[] = [];
|
||||
private session: AbortController | null = null;
|
||||
private prefetchController: AbortController | null = null;
|
||||
finalLevel = -1;
|
||||
private targetLevel = -1;
|
||||
readonly status: LoadStatus = { active: false, started: 0, planned: 0, done: 0, sharp: false };
|
||||
|
||||
constructor(readonly pyramid: Pyramid, private readonly env: LoaderEnv) {}
|
||||
constructor(
|
||||
readonly pyramid: Pyramid,
|
||||
private readonly poolUrl: string,
|
||||
private readonly env: LoaderEnv,
|
||||
) {}
|
||||
|
||||
private tileUrl(id: string): string {
|
||||
const tiles = this.env.tiles;
|
||||
return tiles.path + this.pyramid.hash + "/" + id + "." + tiles.format;
|
||||
}
|
||||
|
||||
private ensurePool(): Promise<boolean> {
|
||||
if (this.pool) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
if (!this.poolPromise) {
|
||||
this.poolPromise = fetch(this.poolUrl, { credentials: "same-origin" })
|
||||
.then((response) => (response.ok ? (response.json() as Promise<PoolFile>) : Promise.reject(new Error("pool"))))
|
||||
.then((file) => {
|
||||
const levels = this.pyramid.levels;
|
||||
if (!Array.isArray(file.levels) || file.levels.length !== levels.length || typeof file.sealed !== "string") {
|
||||
throw new Error("pool");
|
||||
}
|
||||
for (let i = 0; i < levels.length; i++) {
|
||||
if (typeof file.levels[i] !== "string" || file.levels[i].length < levels[i].cols * levels[i].rows * idWidth) {
|
||||
throw new Error("pool");
|
||||
}
|
||||
}
|
||||
this.pool = file.levels;
|
||||
this.sealed = file.sealed;
|
||||
this.env.requestDraw();
|
||||
return true;
|
||||
})
|
||||
.catch(() => {
|
||||
this.poolPromise = null;
|
||||
this.poolRetryAt = performance.now() + poolRetryMs;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
return this.poolPromise;
|
||||
}
|
||||
|
||||
private open(): boolean {
|
||||
if (this.opened) {
|
||||
return true;
|
||||
}
|
||||
const key = this.env.gate.key;
|
||||
const pool = this.pool;
|
||||
if (!key || !pool || key === this.triedKey) {
|
||||
return false;
|
||||
}
|
||||
this.triedKey = key;
|
||||
const plain = unseal(key, this.sealed);
|
||||
let sealed: Sealed | null = null;
|
||||
if (plain) {
|
||||
try {
|
||||
sealed = JSON.parse(new TextDecoder().decode(plain)) as Sealed;
|
||||
} catch {
|
||||
sealed = null;
|
||||
}
|
||||
}
|
||||
const levels = this.pyramid.levels;
|
||||
if (!sealed || !Array.isArray(sealed.levels) || sealed.levels.length !== levels.length) {
|
||||
this.env.gate.reject(key);
|
||||
return false;
|
||||
}
|
||||
const ids: string[][] = [];
|
||||
for (let l = 0; l < levels.length; l++) {
|
||||
const map = sealed.levels[l].map;
|
||||
const entries = pool[l].length / idWidth;
|
||||
if (!Array.isArray(map) || map.length !== levels[l].cols * levels[l].rows) {
|
||||
return false;
|
||||
}
|
||||
const row = new Array<string>(map.length);
|
||||
for (let i = 0; i < map.length; i++) {
|
||||
const at = map[i];
|
||||
if (!(at >= 0 && at < entries)) {
|
||||
return false;
|
||||
}
|
||||
row[i] = pool[l].substr(at * idWidth, idWidth);
|
||||
}
|
||||
ids.push(row);
|
||||
}
|
||||
this.opened = sealed;
|
||||
this.ids = ids;
|
||||
this.sealed = "";
|
||||
void this.ensureSeed();
|
||||
return true;
|
||||
}
|
||||
|
||||
private prepare(): void {
|
||||
if (!this.pool) {
|
||||
if (!this.poolPromise && performance.now() >= this.poolRetryAt) {
|
||||
void this.ensurePool();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!this.opened) {
|
||||
this.open();
|
||||
}
|
||||
}
|
||||
|
||||
ensureSeed(): Promise<void> {
|
||||
if (!this.opened) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (!this.seedPromise) {
|
||||
this.seedPromise = this.decodeSeed().then(
|
||||
() => this.env.requestDraw(),
|
||||
() => {
|
||||
this.seedAt = performance.now();
|
||||
this.env.requestDraw();
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
@@ -85,15 +217,11 @@ export class PhotoLoader {
|
||||
}
|
||||
|
||||
private async decodeSeed(): Promise<void> {
|
||||
if (!this.pyramid.seed) {
|
||||
const seed = this.opened?.seed;
|
||||
if (!seed) {
|
||||
return;
|
||||
}
|
||||
const raw = atob(this.pyramid.seed);
|
||||
const bytes = new Uint8Array(raw.length);
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
bytes[i] = raw.charCodeAt(i);
|
||||
}
|
||||
const bitmap = await decodeBlob(new Blob([bytes], { type: "image/" + this.env.tiles.format }));
|
||||
const bitmap = await decodeBlob(new Blob([fromBase64(seed)], { type: "image/" + this.env.tiles.format }));
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = bitmap.width * seedUpscale;
|
||||
canvas.height = bitmap.height * seedUpscale;
|
||||
@@ -113,45 +241,78 @@ export class PhotoLoader {
|
||||
this.seedImage = canvas;
|
||||
}
|
||||
|
||||
private async fetchTile(tile: TileRef, priority: number, signal: AbortSignal): Promise<TileResult> {
|
||||
const level = this.pyramid.levels[tile.level];
|
||||
const id = level.tiles[tile.index];
|
||||
const tiles = this.env.tiles;
|
||||
const scramble: ScrambleSpec | undefined =
|
||||
tiles.scrambled && this.pyramid.scramble
|
||||
? { seed: this.pyramid.scramble, level: tile.level, x: tile.x, y: tile.y, cell: tiles.cell ?? 64 }
|
||||
: undefined;
|
||||
private async request(key: string, id: string, priority: number, signal: AbortSignal, scramble?: ScrambleSpec): Promise<TileResult> {
|
||||
const url = this.tileUrl(id);
|
||||
let result: TileResult;
|
||||
try {
|
||||
result = await this.env.scheduler.request(id, this.tileUrl(id), priority, signal, scramble);
|
||||
result = await this.env.scheduler.request(key, url, priority, signal, scramble);
|
||||
} catch (error) {
|
||||
if (signal.aborted || error instanceof AbortError) {
|
||||
throw error;
|
||||
}
|
||||
await wait(retryMs + Math.random() * retryMs, signal);
|
||||
result = await this.env.scheduler.request(id, this.tileUrl(id), priority, signal, scramble);
|
||||
result = await this.env.scheduler.request(key, url, priority, signal, scramble);
|
||||
}
|
||||
this.env.cache.put(id, result.bitmap);
|
||||
this.env.cache.put(key, result.bitmap);
|
||||
this.env.requestDraw();
|
||||
return result;
|
||||
}
|
||||
|
||||
private fetchTile(tile: TileRef, priority: number, signal: AbortSignal): Promise<TileResult> {
|
||||
const ids = this.ids;
|
||||
const opened = this.opened;
|
||||
if (!ids || !opened) {
|
||||
return Promise.reject(new AbortError());
|
||||
}
|
||||
const id = ids[tile.level][tile.index];
|
||||
const tiles = this.env.tiles;
|
||||
const cell = tiles.cell ?? 64;
|
||||
const scramble: ScrambleSpec | undefined =
|
||||
tiles.scrambled && opened.scramble && this.pyramid.levels[tile.level].tile_size >= 2 * cell
|
||||
? { seed: opened.scramble, level: tile.level, x: tile.x, y: tile.y, cell }
|
||||
: undefined;
|
||||
return this.request(id, id, priority, signal, scramble);
|
||||
}
|
||||
|
||||
private fetchJumble(id: string, priority: number, signal: AbortSignal): Promise<TileResult> {
|
||||
return this.request(jumbleKey + id, id, priority, signal);
|
||||
}
|
||||
|
||||
private uncached(level: number, view: View): TileRef[] {
|
||||
const ids = this.pyramid.levels[level].tiles;
|
||||
return visibleTiles(this.pyramid, level, view, this.env.tiles.tile_size).filter((t) => !this.env.cache.has(ids[t.index]));
|
||||
const ids = this.ids;
|
||||
if (!ids) {
|
||||
return [];
|
||||
}
|
||||
return visibleTiles(this.pyramid, level, view).filter((t) => !this.env.cache.has(ids[level][t.index]));
|
||||
}
|
||||
|
||||
private uncachedBytes(level: number, view: View): number {
|
||||
const bytes = this.pyramid.levels[level].bytes;
|
||||
const bytes = this.opened?.levels[level].bytes ?? [];
|
||||
let total = 0;
|
||||
for (const tile of this.uncached(level, view)) {
|
||||
total += bytes[tile.index];
|
||||
total += bytes[tile.index] ?? 0;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private fetchAll(tiles: TileRef[], priority: number, signal: AbortSignal): Promise<PromiseSettledResult<TileResult>[]> {
|
||||
return Promise.allSettled(tiles.map((tile) => this.fetchTile(tile, priority, signal)));
|
||||
private chooseJumble(view: View, dpr: number): string[] {
|
||||
const pool = this.pool;
|
||||
if (!pool) {
|
||||
return [];
|
||||
}
|
||||
if (this.jumbleLevel < 0) {
|
||||
const level = this.probeLevel(view, dpr);
|
||||
const grid = this.pyramid.levels[level].cols * this.pyramid.levels[level].rows;
|
||||
const entries = pool[level].length / idWidth;
|
||||
const picks = new Array<string>(grid);
|
||||
for (let i = 0; i < grid; i++) {
|
||||
const at = Math.floor(Math.random() * entries);
|
||||
picks[i] = pool[level].substr(at * idWidth, idWidth);
|
||||
}
|
||||
this.jumbleLevel = level;
|
||||
this.jumble = picks;
|
||||
}
|
||||
return Array.from(new Set(this.jumble)).filter((id) => !this.env.cache.has(jumbleKey + id));
|
||||
}
|
||||
|
||||
probeLevel(view: View, dpr: number): number {
|
||||
@@ -162,12 +323,12 @@ export class PhotoLoader {
|
||||
this.env.onStatus?.(this);
|
||||
}
|
||||
|
||||
private track(tiles: TileRef[], controller: AbortController, signal: AbortSignal): Promise<PromiseSettledResult<TileResult>[]> {
|
||||
this.status.planned += tiles.length;
|
||||
private track(jobs: Array<() => Promise<TileResult>>, controller: AbortController): Promise<PromiseSettledResult<TileResult>[]> {
|
||||
this.status.planned += jobs.length;
|
||||
this.notify();
|
||||
return Promise.allSettled(
|
||||
tiles.map((tile) =>
|
||||
this.fetchTile(tile, PRIORITY_CURRENT, signal).finally(() => {
|
||||
jobs.map((job) =>
|
||||
job().finally(() => {
|
||||
if (this.session === controller) {
|
||||
this.status.done++;
|
||||
this.notify();
|
||||
@@ -206,6 +367,18 @@ export class PhotoLoader {
|
||||
const budget = this.env.settings.budgetMs;
|
||||
const timer = setTimeout(() => controller.abort("deadline"), budget);
|
||||
try {
|
||||
const ready = await until(this.ensurePool(), signal, false);
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
if (!ready || !this.open()) {
|
||||
const ids = this.chooseJumble(view, dpr);
|
||||
await this.track(
|
||||
ids.map((id) => () => this.fetchJumble(id, PRIORITY_CURRENT, signal)),
|
||||
controller,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await this.ensureSeed();
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
@@ -214,7 +387,10 @@ export class PhotoLoader {
|
||||
const probe = Math.max(0, needed - probeStep);
|
||||
const probeTiles = this.uncached(probe, view).slice(0, 2);
|
||||
if (probeTiles.length > 0) {
|
||||
const results = await this.track(probeTiles, controller, signal);
|
||||
const results = await this.track(
|
||||
probeTiles.map((tile) => () => this.fetchTile(tile, PRIORITY_CURRENT, signal)),
|
||||
controller,
|
||||
);
|
||||
let bytes = 0;
|
||||
let ms = 0;
|
||||
for (const result of results) {
|
||||
@@ -251,7 +427,10 @@ export class PhotoLoader {
|
||||
this.targetLevel = final;
|
||||
this.env.requestDraw();
|
||||
for (const level of plan) {
|
||||
await this.track(this.uncached(level, view), controller, signal);
|
||||
await this.track(
|
||||
this.uncached(level, view).map((tile) => () => this.fetchTile(tile, PRIORITY_CURRENT, signal)),
|
||||
controller,
|
||||
);
|
||||
if (signal.aborted) {
|
||||
return;
|
||||
}
|
||||
@@ -263,19 +442,34 @@ export class PhotoLoader {
|
||||
|
||||
prefetchProbe(view: View, dpr: number): void {
|
||||
const controller = this.resetPrefetch();
|
||||
void this.ensureSeed().then(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
void this.fetchAll(this.uncached(this.probeLevel(view, dpr), view), PRIORITY_PREFETCH, controller.signal);
|
||||
const signal = controller.signal;
|
||||
void this.ensurePool().then(async (ready) => {
|
||||
if (signal.aborted || !ready) {
|
||||
return;
|
||||
}
|
||||
if (!this.open()) {
|
||||
for (const id of this.chooseJumble(view, dpr)) {
|
||||
void this.fetchJumble(id, PRIORITY_PREFETCH, signal).catch(() => undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await this.ensureSeed();
|
||||
if (!signal.aborted) {
|
||||
for (const tile of this.uncached(this.probeLevel(view, dpr), view)) {
|
||||
void this.fetchTile(tile, PRIORITY_PREFETCH, signal).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
prefetchLevel(view: View, level: number): void {
|
||||
if (level < 0) {
|
||||
if (level < 0 || !this.opened) {
|
||||
return;
|
||||
}
|
||||
const controller = this.resetPrefetch();
|
||||
void this.fetchAll(this.uncached(level, view), PRIORITY_PREFETCH, controller.signal);
|
||||
const signal = this.resetPrefetch().signal;
|
||||
for (const tile of this.uncached(level, view)) {
|
||||
void this.fetchTile(tile, PRIORITY_PREFETCH, signal).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
private resetPrefetch(): AbortController {
|
||||
@@ -303,6 +497,40 @@ export class PhotoLoader {
|
||||
this.stopPrefetch();
|
||||
}
|
||||
|
||||
private drawJumble(target: DrawTarget, view: View): boolean {
|
||||
if (this.jumbleLevel < 0) {
|
||||
return false;
|
||||
}
|
||||
const { g, originX, originY, width, now } = target;
|
||||
const level = this.pyramid.levels[this.jumbleLevel];
|
||||
const range = tileRange(level, view);
|
||||
if (!range) {
|
||||
return false;
|
||||
}
|
||||
const scale = width / level.width;
|
||||
const cache = this.env.cache;
|
||||
let animating = false;
|
||||
g.imageSmoothingEnabled = true;
|
||||
g.imageSmoothingQuality = "medium";
|
||||
for (let y = range.y0; y <= range.y1; y++) {
|
||||
for (let x = range.x0; x <= range.x1; x++) {
|
||||
const entry = cache.get(jumbleKey + this.jumble[y * level.cols + x]);
|
||||
const rect = entry ? cellRect(level, x, y, originX, originY, scale) : null;
|
||||
if (!entry || !rect) {
|
||||
continue;
|
||||
}
|
||||
const age = now - entry.at;
|
||||
if (age < fadeMs) {
|
||||
g.globalAlpha = Math.max(0, age / fadeMs);
|
||||
animating = true;
|
||||
}
|
||||
g.drawImage(entry.bitmap, 0, 0, entry.bitmap.width, entry.bitmap.height, rect.dx, rect.dy, rect.dw, rect.dh);
|
||||
g.globalAlpha = 1;
|
||||
}
|
||||
}
|
||||
return animating;
|
||||
}
|
||||
|
||||
draw(target: DrawTarget): boolean {
|
||||
const { g, originX, originY, width, height, canvasWidth, canvasHeight } = target;
|
||||
const left = Math.max(0, originX);
|
||||
@@ -312,9 +540,7 @@ export class PhotoLoader {
|
||||
if (right <= left || bottom <= top) {
|
||||
return false;
|
||||
}
|
||||
if (!this.seedPromise) {
|
||||
void this.ensureSeed();
|
||||
}
|
||||
this.prepare();
|
||||
const view: View = {
|
||||
displayWidth: target.displayWidth,
|
||||
u0: (left - originX) / width,
|
||||
@@ -322,22 +548,21 @@ export class PhotoLoader {
|
||||
v0: (top - originY) / height,
|
||||
v1: (bottom - originY) / height,
|
||||
};
|
||||
const tileSize = this.env.tiles.tile_size;
|
||||
const overlap = this.env.tiles.overlap;
|
||||
const cache = this.env.cache;
|
||||
const levels = this.pyramid.levels;
|
||||
const ids = this.ids;
|
||||
const needed = neededLevel(this.pyramid, target.displayWidth, target.dpr);
|
||||
|
||||
let base = -1;
|
||||
for (let l = needed; l >= 0 && base < 0; l--) {
|
||||
const range = tileRange(levels[l], view, tileSize);
|
||||
for (let l = needed; ids && l >= 0 && base < 0; l--) {
|
||||
const range = tileRange(levels[l], view);
|
||||
if (!range) {
|
||||
continue;
|
||||
}
|
||||
let complete = true;
|
||||
for (let y = range.y0; y <= range.y1 && complete; y++) {
|
||||
for (let x = range.x0; x <= range.x1; x++) {
|
||||
const entry = cache.get(levels[l].tiles[y * levels[l].cols + x]);
|
||||
const entry = cache.get(ids[l][y * levels[l].cols + x]);
|
||||
if (!entry || target.now - entry.at < fadeMs) {
|
||||
complete = false;
|
||||
break;
|
||||
@@ -349,28 +574,40 @@ export class PhotoLoader {
|
||||
}
|
||||
}
|
||||
|
||||
if (base < 0 && this.seedImage) {
|
||||
let animating = false;
|
||||
if (base < 0) {
|
||||
g.save();
|
||||
g.beginPath();
|
||||
g.rect(left, top, right - left, bottom - top);
|
||||
g.clip();
|
||||
g.imageSmoothingEnabled = true;
|
||||
g.imageSmoothingQuality = "low";
|
||||
g.drawImage(this.seedImage, originX, originY, width, height);
|
||||
animating = this.drawJumble(target, view);
|
||||
if (this.seedImage) {
|
||||
const age = target.now - this.seedAt;
|
||||
if (this.jumbleLevel >= 0 && age < fadeMs) {
|
||||
g.globalAlpha = Math.max(0, age / fadeMs);
|
||||
animating = true;
|
||||
}
|
||||
g.imageSmoothingEnabled = true;
|
||||
g.imageSmoothingQuality = "low";
|
||||
g.drawImage(this.seedImage, originX, originY, width, height);
|
||||
g.globalAlpha = 1;
|
||||
}
|
||||
g.restore();
|
||||
}
|
||||
|
||||
const sharpLevel = this.targetLevel >= 0 ? Math.min(this.targetLevel, needed) : needed;
|
||||
const sharp = base >= sharpLevel;
|
||||
const sharp = ids !== null && base >= sharpLevel;
|
||||
if (sharp !== this.status.sharp) {
|
||||
this.status.sharp = sharp;
|
||||
queueMicrotask(() => this.notify());
|
||||
}
|
||||
if (!ids) {
|
||||
return animating;
|
||||
}
|
||||
|
||||
let animating = false;
|
||||
for (let l = Math.max(0, base); l <= needed; l++) {
|
||||
const level = levels[l];
|
||||
const range = tileRange(level, view, tileSize);
|
||||
const range = tileRange(level, view);
|
||||
if (!range) {
|
||||
continue;
|
||||
}
|
||||
@@ -379,7 +616,7 @@ export class PhotoLoader {
|
||||
g.imageSmoothingQuality = scale < 1 ? "high" : "medium";
|
||||
for (let y = range.y0; y <= range.y1; y++) {
|
||||
for (let x = range.x0; x <= range.x1; x++) {
|
||||
const entry = cache.get(level.tiles[y * level.cols + x]);
|
||||
const entry = cache.get(ids[l][y * level.cols + x]);
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
@@ -388,7 +625,7 @@ export class PhotoLoader {
|
||||
g.globalAlpha = Math.max(0, age / fadeMs);
|
||||
animating = true;
|
||||
}
|
||||
drawTile(g, entry.bitmap, level, x, y, tileSize, overlap, originX, originY, scale);
|
||||
drawTile(g, entry.bitmap, level, x, y, originX, originY, scale);
|
||||
g.globalAlpha = 1;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -46,10 +46,10 @@ export function unscramble(g: CellCanvas, image: CanvasImageSource, width: numbe
|
||||
const cell = spec.cell;
|
||||
const cols = Math.floor(width / cell);
|
||||
const rows = Math.floor(height / cell);
|
||||
const n = cols * rows;
|
||||
if (n < 2) {
|
||||
if (cols < 2 || rows < 2) {
|
||||
return;
|
||||
}
|
||||
const n = cols * rows;
|
||||
const perm = cellPermutation(n, tileSeed(spec));
|
||||
for (let i = 0; i < n; i++) {
|
||||
const source = perm[i];
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
const K = new Int32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
|
||||
0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
|
||||
0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
|
||||
0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
|
||||
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
|
||||
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
|
||||
const IV = new Int32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
|
||||
|
||||
function expand(w: Int32Array, from: number): void {
|
||||
for (let i = from; i < 64; i++) {
|
||||
const x = w[i - 15];
|
||||
const y = w[i - 2];
|
||||
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
|
||||
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
|
||||
}
|
||||
}
|
||||
|
||||
function rounds(s: Int32Array, w: Int32Array, from: number, to: number): void {
|
||||
let a = s[0];
|
||||
let b = s[1];
|
||||
let c = s[2];
|
||||
let d = s[3];
|
||||
let e = s[4];
|
||||
let f = s[5];
|
||||
let g = s[6];
|
||||
let h = s[7];
|
||||
for (let i = from; i < to; i++) {
|
||||
const t1 =
|
||||
(h + (((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
|
||||
const t2 = ((((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = (d + t1) | 0;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = (t1 + t2) | 0;
|
||||
}
|
||||
s[0] = a;
|
||||
s[1] = b;
|
||||
s[2] = c;
|
||||
s[3] = d;
|
||||
s[4] = e;
|
||||
s[5] = f;
|
||||
s[6] = g;
|
||||
s[7] = h;
|
||||
}
|
||||
|
||||
const W = new Int32Array(64);
|
||||
const S = new Int32Array(8);
|
||||
const H = new Int32Array(8);
|
||||
|
||||
export function sha256(message: Uint8Array, out: Uint8Array = new Uint8Array(32)): Uint8Array {
|
||||
H.set(IV);
|
||||
const length = message.length;
|
||||
const blocks = Math.ceil((length + 9) / 64);
|
||||
for (let block = 0; block < blocks; block++) {
|
||||
const base = block * 64;
|
||||
for (let i = 0; i < 16; i++) {
|
||||
let word = 0;
|
||||
for (let j = 0; j < 4; j++) {
|
||||
const at = base + i * 4 + j;
|
||||
let byte = 0;
|
||||
if (at < length) {
|
||||
byte = message[at];
|
||||
} else if (at === length) {
|
||||
byte = 0x80;
|
||||
} else if (block === blocks - 1 && at >= base + 56) {
|
||||
const bits = at - base - 56;
|
||||
byte = bits < 3 ? 0 : bits === 3 ? (length >>> 29) & 255 : ((length * 8) >>> ((7 - bits) * 8)) & 255;
|
||||
}
|
||||
word = (word << 8) | byte;
|
||||
}
|
||||
W[i] = word;
|
||||
}
|
||||
expand(W, 16);
|
||||
S.set(H);
|
||||
rounds(S, W, 0, 64);
|
||||
for (let i = 0; i < 8; i++) {
|
||||
H[i] = (H[i] + S[i]) | 0;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[i * 4] = H[i] >>> 24;
|
||||
out[i * 4 + 1] = (H[i] >>> 16) & 255;
|
||||
out[i * 4 + 2] = (H[i] >>> 8) & 255;
|
||||
out[i * 4 + 3] = H[i] & 255;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function labelled(label: string, salt: Uint8Array, n: number): Uint8Array {
|
||||
const prefix = encoder.encode(label);
|
||||
const message = new Uint8Array(prefix.length + salt.length + 4);
|
||||
message.set(prefix);
|
||||
message.set(salt, prefix.length);
|
||||
const at = prefix.length + salt.length;
|
||||
message[at] = n >>> 24;
|
||||
message[at + 1] = (n >>> 16) & 255;
|
||||
message[at + 2] = (n >>> 8) & 255;
|
||||
message[at + 3] = n & 255;
|
||||
return message;
|
||||
}
|
||||
|
||||
export function deriveKey(salt: Uint8Array, n: number): Uint8Array {
|
||||
return sha256(labelled("luphoto-key", salt, n));
|
||||
}
|
||||
|
||||
export function checkFor(salt: Uint8Array, n: number): Uint8Array {
|
||||
return sha256(labelled("luphoto-check", salt, n)).subarray(0, 16);
|
||||
}
|
||||
|
||||
export class PowSearch {
|
||||
private readonly w = new Int32Array(64);
|
||||
private readonly mid = new Int32Array(8);
|
||||
private readonly s = new Int32Array(8);
|
||||
private readonly target = new Int32Array(4);
|
||||
private readonly saltTail: number;
|
||||
|
||||
constructor(salt: Uint8Array, check: Uint8Array) {
|
||||
const block = new Uint8Array(64);
|
||||
block.set(labelled("luphoto-check", salt, 0));
|
||||
block[33] = 0x80;
|
||||
block[62] = (33 * 8) >>> 8;
|
||||
block[63] = (33 * 8) & 255;
|
||||
const w = this.w;
|
||||
for (let i = 0; i < 16; i++) {
|
||||
w[i] = (block[i * 4] << 24) | (block[i * 4 + 1] << 16) | (block[i * 4 + 2] << 8) | block[i * 4 + 3];
|
||||
}
|
||||
this.saltTail = block[28] << 24;
|
||||
for (let i = 16; i < 22; i++) {
|
||||
const x = w[i - 15];
|
||||
const y = w[i - 2];
|
||||
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
|
||||
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
|
||||
}
|
||||
this.mid.set(IV);
|
||||
rounds(this.mid, w, 0, 7);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
this.target[i] = (check[i * 4] << 24) | (check[i * 4 + 1] << 16) | (check[i * 4 + 2] << 8) | check[i * 4 + 3];
|
||||
}
|
||||
}
|
||||
|
||||
run(from: number, to: number): number {
|
||||
const w = this.w;
|
||||
const s = this.s;
|
||||
const mid = this.mid;
|
||||
const t0 = this.target[0];
|
||||
const tail = this.saltTail;
|
||||
for (let n = from; n < to; n++) {
|
||||
w[7] = tail | (n >>> 8);
|
||||
w[8] = ((n & 255) << 24) | 0x800000;
|
||||
expand(w, 22);
|
||||
s.set(mid);
|
||||
rounds(s, w, 7, 64);
|
||||
if (((IV[0] + s[0]) | 0) !== t0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
((IV[1] + s[1]) | 0) === this.target[1] &&
|
||||
((IV[2] + s[2]) | 0) === this.target[2] &&
|
||||
((IV[3] + s[3]) | 0) === this.target[3]
|
||||
) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
export const sealMagic = "luphoto-sealed-1";
|
||||
const nonceSize = 12;
|
||||
|
||||
export function fromHex(text: string): Uint8Array {
|
||||
const out = new Uint8Array(text.length >>> 1);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(text.substr(i * 2, 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function toHex(bytes: Uint8Array): string {
|
||||
let text = "";
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
text += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export function fromBase64(text: string): Uint8Array {
|
||||
const raw = atob(text);
|
||||
const out = new Uint8Array(raw.length);
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
out[i] = raw.charCodeAt(i);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function unseal(key: Uint8Array, sealed: string): Uint8Array | null {
|
||||
const data = fromBase64(sealed);
|
||||
if (data.length < nonceSize + sealMagic.length) {
|
||||
return null;
|
||||
}
|
||||
const block = new Uint8Array(32 + nonceSize + 4);
|
||||
block.set(key.subarray(0, 32));
|
||||
block.set(data.subarray(0, nonceSize), 32);
|
||||
const stream = new Uint8Array(32);
|
||||
const body = data.subarray(nonceSize);
|
||||
for (let i = 0, at = 0; at < body.length; i++, at += 32) {
|
||||
block[44] = i >>> 24;
|
||||
block[45] = (i >>> 16) & 255;
|
||||
block[46] = (i >>> 8) & 255;
|
||||
block[47] = i & 255;
|
||||
sha256(block, stream);
|
||||
const end = Math.min(32, body.length - at);
|
||||
for (let j = 0; j < end; j++) {
|
||||
body[at + j] ^= stream[j];
|
||||
}
|
||||
if (i === 0) {
|
||||
for (let j = 0; j < sealMagic.length; j++) {
|
||||
if (body[j] !== sealMagic.charCodeAt(j)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return body.subarray(sealMagic.length);
|
||||
}
|
||||
+2
-1
@@ -40,10 +40,11 @@ export class Strip {
|
||||
readonly element: HTMLElement,
|
||||
readonly cover: Pyramid,
|
||||
private readonly focusY: number,
|
||||
poolUrl: string,
|
||||
env: StripEnv,
|
||||
private readonly onStatus: (strip: Strip) => void,
|
||||
) {
|
||||
this.loader = new PhotoLoader(cover, {
|
||||
this.loader = new PhotoLoader(cover, poolUrl, {
|
||||
...env,
|
||||
requestDraw: () => this.requestDraw(),
|
||||
onStatus: () => this.onStatus(this),
|
||||
|
||||
+32
-5
@@ -1,11 +1,10 @@
|
||||
export interface Level {
|
||||
width: number;
|
||||
height: number;
|
||||
tile_size: number;
|
||||
overlap?: number;
|
||||
cols: number;
|
||||
rows: number;
|
||||
quality: number;
|
||||
tiles: string[];
|
||||
bytes: number[];
|
||||
}
|
||||
|
||||
export interface Pyramid {
|
||||
@@ -13,8 +12,30 @@ export interface Pyramid {
|
||||
width: number;
|
||||
height: number;
|
||||
levels: Level[];
|
||||
}
|
||||
|
||||
export interface GateInfo {
|
||||
build: string;
|
||||
salt?: string;
|
||||
bits?: number;
|
||||
check?: string;
|
||||
key?: string;
|
||||
}
|
||||
|
||||
export interface PoolFile {
|
||||
levels: string[];
|
||||
sealed: string;
|
||||
}
|
||||
|
||||
export interface SealedLevel {
|
||||
map: number[];
|
||||
bytes: number[];
|
||||
}
|
||||
|
||||
export interface Sealed {
|
||||
seed: string;
|
||||
scramble?: string;
|
||||
levels: SealedLevel[];
|
||||
}
|
||||
|
||||
export interface Exif {
|
||||
@@ -38,8 +59,6 @@ export interface Photo extends Pyramid {
|
||||
|
||||
export interface Tiles {
|
||||
format: string;
|
||||
tile_size: number;
|
||||
overlap: number;
|
||||
path: string;
|
||||
scrambled?: boolean;
|
||||
cell?: number;
|
||||
@@ -54,6 +73,7 @@ export interface Manifest {
|
||||
collapsed_focus_y: number;
|
||||
show_exif: boolean;
|
||||
tiles: Tiles;
|
||||
gate: GateInfo;
|
||||
cover: Pyramid;
|
||||
og?: string;
|
||||
photos: Photo[];
|
||||
@@ -74,6 +94,7 @@ export interface IndexAlbum {
|
||||
export interface SiteIndex {
|
||||
build: string;
|
||||
tiles: Tiles;
|
||||
gate: GateInfo;
|
||||
albums: IndexAlbum[];
|
||||
}
|
||||
|
||||
@@ -88,6 +109,7 @@ export interface Settings {
|
||||
maxDpr: number;
|
||||
concurrency: number;
|
||||
blockContextMenu: boolean;
|
||||
gate: boolean;
|
||||
}
|
||||
|
||||
export function readSettings(body: HTMLElement): Settings {
|
||||
@@ -107,5 +129,10 @@ export function readSettings(body: HTMLElement): Settings {
|
||||
maxDpr: num(data.maxDpr, 2),
|
||||
concurrency: Math.max(1, Math.round(num(data.concurrency, 6))),
|
||||
blockContextMenu: data.blockContextMenu !== "false",
|
||||
gate: data.gate !== "false",
|
||||
};
|
||||
}
|
||||
|
||||
export function poolUrl(build: string, slug: string, hash: string): string {
|
||||
return "/a/" + encodeURIComponent(slug) + "/p/" + hash + "." + build + ".json";
|
||||
}
|
||||
+23
-2
@@ -4,7 +4,7 @@ import type { View } from "./geometry";
|
||||
import { BusyIndicator, ProgressLine } from "./indicator";
|
||||
import { PhotoLoader, type LoaderEnv } from "./loader";
|
||||
import { Strip } from "./strip";
|
||||
import type { Manifest, Settings, SiteIndex } from "./types";
|
||||
import { poolUrl, type Manifest, type Settings, type SiteIndex } from "./types";
|
||||
|
||||
interface PhotoLayout {
|
||||
scale: number;
|
||||
@@ -202,6 +202,7 @@ export class Viewer {
|
||||
this.requestDraw();
|
||||
this.wake();
|
||||
this.loadNextAlbum();
|
||||
env.gate.onUnlock(() => this.onUnlock());
|
||||
}
|
||||
|
||||
private buildEndCard(): HTMLElement {
|
||||
@@ -240,7 +241,8 @@ export class Viewer {
|
||||
private loader(index: number): PhotoLoader {
|
||||
let loader = this.loaders[index];
|
||||
if (!loader) {
|
||||
loader = new PhotoLoader(this.manifest.photos[index], {
|
||||
const photo = this.manifest.photos[index];
|
||||
loader = new PhotoLoader(photo, poolUrl(this.manifest.build, this.manifest.slug, photo.hash), {
|
||||
...this.env,
|
||||
requestDraw: () => this.requestDraw(),
|
||||
onStatus: (changed) => {
|
||||
@@ -928,6 +930,24 @@ export class Viewer {
|
||||
this.requestDraw();
|
||||
}
|
||||
|
||||
private onUnlock(): void {
|
||||
if (this.suspended) {
|
||||
return;
|
||||
}
|
||||
if (this.zoomPhoto >= 0) {
|
||||
this.startZoomSession();
|
||||
} else {
|
||||
this.startSession();
|
||||
}
|
||||
if (this.nextStrip) {
|
||||
if (this.nextStrip.isNear) {
|
||||
this.nextStrip.startSession();
|
||||
}
|
||||
this.nextStrip.requestDraw();
|
||||
}
|
||||
this.requestDraw();
|
||||
}
|
||||
|
||||
private startSession(): void {
|
||||
const stop = this.stops[this.current];
|
||||
if (stop.photo < 0) {
|
||||
@@ -1052,6 +1072,7 @@ export class Viewer {
|
||||
this.nextFrame,
|
||||
next.cover,
|
||||
next.collapsed_focus_y ?? 0.5,
|
||||
poolUrl(index.build, next.slug, next.cover.hash),
|
||||
{ ...this.env, tiles: index.tiles },
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
+19
-3
@@ -1,4 +1,5 @@
|
||||
import { unscramble, type ScrambleSpec } from "./scramble";
|
||||
import { PowSearch, fromHex } from "./sha256";
|
||||
|
||||
interface FetchMessage {
|
||||
type: "fetch";
|
||||
@@ -12,7 +13,14 @@ interface AbortMessage {
|
||||
key: number;
|
||||
}
|
||||
|
||||
type Incoming = FetchMessage | AbortMessage;
|
||||
interface PowMessage {
|
||||
type: "pow";
|
||||
salt: string;
|
||||
check: string;
|
||||
bits: number;
|
||||
}
|
||||
|
||||
type Incoming = FetchMessage | AbortMessage | PowMessage;
|
||||
|
||||
interface Outgoing {
|
||||
key: number;
|
||||
@@ -23,9 +31,13 @@ interface Outgoing {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface PowReply {
|
||||
pow: number;
|
||||
}
|
||||
|
||||
interface WorkerScope {
|
||||
onmessage: ((event: MessageEvent<Incoming>) => void) | null;
|
||||
postMessage(message: Outgoing, transfer?: Transferable[]): void;
|
||||
postMessage(message: Outgoing | PowReply, transfer?: Transferable[]): void;
|
||||
}
|
||||
|
||||
interface OffscreenLike {
|
||||
@@ -42,6 +54,11 @@ const Offscreen = (self as unknown as { OffscreenCanvas?: OffscreenConstructor }
|
||||
|
||||
scope.onmessage = (event) => {
|
||||
const message = event.data;
|
||||
if (message.type === "pow") {
|
||||
const search = new PowSearch(fromHex(message.salt), fromHex(message.check));
|
||||
scope.postMessage({ pow: search.run(0, 2 ** message.bits) });
|
||||
return;
|
||||
}
|
||||
if (message.type === "abort") {
|
||||
controllers.get(message.key)?.abort();
|
||||
controllers.delete(message.key);
|
||||
@@ -49,7 +66,6 @@ scope.onmessage = (event) => {
|
||||
}
|
||||
void load(message);
|
||||
};
|
||||
|
||||
function restore(bitmap: ImageBitmap, spec: ScrambleSpec): ImageBitmap {
|
||||
if (!Offscreen) {
|
||||
throw new Error("unsupported-offscreen");
|
||||
|
||||
Reference in new issue
Block a user