M7: hardening and final pass
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
00ee2a6d12
commit
ae898a2787
30 files changed
+878
-107
No files matched your search
@@ -490,3 +490,74 @@ html:not(.has-strips) .strip-subtitle {
|
||||
animation-duration: 0ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
html {
|
||||
touch-action: manipulation;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
.skip-link {
|
||||
position: absolute;
|
||||
top: var(--lucio-space-2);
|
||||
left: var(--lucio-space-4);
|
||||
z-index: 10;
|
||||
padding: var(--lucio-space-2) var(--lucio-space-3);
|
||||
background: var(--lucio-graphite-2);
|
||||
color: var(--lucio-paper);
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
text-decoration: none;
|
||||
transform: translateY(-200%);
|
||||
}
|
||||
|
||||
.skip-link:focus-visible {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.stage:focus-visible {
|
||||
outline: 2px solid var(--lucio-beam);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.strip {
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
.load-error {
|
||||
color: var(--lucio-ash-light);
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: var(--lucio-space-9) var(--gutter) var(--lucio-space-8);
|
||||
max-width: 68ch;
|
||||
}
|
||||
|
||||
.message-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);
|
||||
}
|
||||
|
||||
.message-title {
|
||||
margin: var(--lucio-space-2) 0 var(--lucio-space-4);
|
||||
font-family: var(--lucio-font-display);
|
||||
font-size: 36px;
|
||||
font-weight: 700;
|
||||
line-height: 1.15;
|
||||
letter-spacing: -0.015em;
|
||||
}
|
||||
|
||||
.message-text {
|
||||
margin: 0;
|
||||
color: var(--lucio-paper);
|
||||
}
|
||||
|
||||
.message-text a {
|
||||
text-decoration: underline;
|
||||
}
|
||||
+41
-8
@@ -1,3 +1,4 @@
|
||||
import { mountWordmark } from "./brand";
|
||||
import { TileCache, cacheBudget } from "./cache";
|
||||
import { IndexPage } from "./index";
|
||||
import { Scheduler } from "./scheduler";
|
||||
@@ -23,13 +24,39 @@ async function startAlbum(stage: HTMLElement, settings: Settings): Promise<void>
|
||||
}
|
||||
const { scheduler, cache } = shared(settings);
|
||||
document.documentElement.classList.add("has-viewer");
|
||||
new Viewer(stage, manifest, settings, { scheduler, cache, settings, tiles: manifest.tiles });
|
||||
lifecycle(new Viewer(stage, manifest, settings, { scheduler, cache, settings, tiles: manifest.tiles }));
|
||||
}
|
||||
|
||||
async function startIndex(root: HTMLElement, settings: Settings): Promise<void> {
|
||||
const index = await fetchJSON<SiteIndex>(settings.indexUrl);
|
||||
const { scheduler, cache } = shared(settings);
|
||||
new IndexPage(root, index, settings, { scheduler, cache, settings, tiles: index.tiles });
|
||||
lifecycle(new IndexPage(root, index, settings, { scheduler, cache, settings, tiles: index.tiles }));
|
||||
}
|
||||
|
||||
interface Suspendable {
|
||||
suspend(hidden: boolean): void;
|
||||
resume(): void;
|
||||
}
|
||||
|
||||
function lifecycle(target: Suspendable): void {
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "hidden") {
|
||||
target.suspend(false);
|
||||
} else {
|
||||
target.resume();
|
||||
}
|
||||
});
|
||||
window.addEventListener("pagehide", () => target.suspend(true));
|
||||
window.addEventListener("pageshow", (event) => {
|
||||
if (event.persisted) {
|
||||
target.resume();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function showLoadError(): void {
|
||||
document.documentElement.classList.remove("has-viewer");
|
||||
document.querySelector<HTMLElement>(".load-error")?.removeAttribute("hidden");
|
||||
}
|
||||
|
||||
function boot(): void {
|
||||
@@ -37,16 +64,22 @@ function boot(): void {
|
||||
if (settings.page === "album") {
|
||||
const stage = document.getElementById("stage");
|
||||
if (stage) {
|
||||
startAlbum(stage, settings).catch((error: unknown) => {
|
||||
stage.dataset.error = String(error);
|
||||
document.documentElement.classList.remove("has-viewer");
|
||||
});
|
||||
startAlbum(stage, settings).catch(() => showLoadError());
|
||||
}
|
||||
} else if (settings.page === "notfound") {
|
||||
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
|
||||
if (header) {
|
||||
mountWordmark(header, false);
|
||||
}
|
||||
} else if (settings.page === "index") {
|
||||
const root = document.getElementById("strips");
|
||||
if (root) {
|
||||
startIndex(root, settings).catch((error: unknown) => {
|
||||
root.dataset.error = String(error);
|
||||
startIndex(root, settings).catch(() => {
|
||||
document.documentElement.classList.remove("has-strips");
|
||||
const header = document.querySelector<HTMLElement>(".site-header .wordmark");
|
||||
if (header && !header.classList.contains("has-svg")) {
|
||||
mountWordmark(header, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+22
-15
@@ -1,5 +1,7 @@
|
||||
import { releaseImage, type TileImage } from "./scheduler";
|
||||
|
||||
export interface CachedTile {
|
||||
bitmap: ImageBitmap;
|
||||
bitmap: TileImage;
|
||||
bytes: number;
|
||||
at: number;
|
||||
}
|
||||
@@ -8,22 +10,27 @@ interface NavigatorWithMemory extends Navigator {
|
||||
deviceMemory?: number;
|
||||
}
|
||||
|
||||
export function cacheBudget(): number {
|
||||
const mb = 1024 * 1024;
|
||||
const mb = 1024 * 1024;
|
||||
|
||||
export function isConstrainedDevice(): boolean {
|
||||
const memory = (navigator as NavigatorWithMemory).deviceMemory;
|
||||
const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
|
||||
const smallScreen = Math.min(screen.width, screen.height) <= 820;
|
||||
if ((memory !== undefined && memory <= 4) || (coarse && smallScreen)) {
|
||||
return 120 * mb;
|
||||
if (typeof memory === "number" && memory <= 4) {
|
||||
return true;
|
||||
}
|
||||
return 250 * mb;
|
||||
const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
|
||||
const shortSide = Math.min(screen.width, screen.height);
|
||||
return coarse && shortSide <= 820;
|
||||
}
|
||||
|
||||
export function cacheBudget(): number {
|
||||
return isConstrainedDevice() ? 120 * mb : 250 * mb;
|
||||
}
|
||||
|
||||
export class TileCache {
|
||||
private readonly entries = new Map<string, CachedTile>();
|
||||
private used = 0;
|
||||
|
||||
constructor(private readonly budget: number) {}
|
||||
constructor(readonly budget: number) {}
|
||||
|
||||
get(id: string): CachedTile | undefined {
|
||||
const entry = this.entries.get(id);
|
||||
@@ -38,22 +45,22 @@ export class TileCache {
|
||||
return this.entries.has(id);
|
||||
}
|
||||
|
||||
put(id: string, bitmap: ImageBitmap): void {
|
||||
put(id: string, bitmap: TileImage): void {
|
||||
const existing = this.entries.get(id);
|
||||
if (existing) {
|
||||
if (existing.bitmap !== bitmap) {
|
||||
bitmap.close();
|
||||
releaseImage(bitmap);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const bytes = bitmap.width * bitmap.height * 4;
|
||||
this.entries.set(id, { bitmap, bytes, at: performance.now() });
|
||||
this.used += bytes;
|
||||
this.evict();
|
||||
this.trim(this.budget);
|
||||
}
|
||||
|
||||
private evict(): void {
|
||||
while (this.used > this.budget && this.entries.size > 1) {
|
||||
trim(limit: number): void {
|
||||
while (this.used > limit && this.entries.size > 0) {
|
||||
const oldest = this.entries.keys().next();
|
||||
if (oldest.done) {
|
||||
return;
|
||||
@@ -62,7 +69,7 @@ export class TileCache {
|
||||
this.entries.delete(oldest.value);
|
||||
if (entry) {
|
||||
this.used -= entry.bytes;
|
||||
entry.bitmap.close();
|
||||
releaseImage(entry.bitmap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+14
-6
@@ -1,5 +1,15 @@
|
||||
import type { Exif, Photo } from "./types";
|
||||
|
||||
const han = /[㐀-鿿豈-]/;
|
||||
|
||||
export function setLang(element: HTMLElement, text: string): void {
|
||||
if (han.test(text)) {
|
||||
element.lang = "zh";
|
||||
} else {
|
||||
element.removeAttribute("lang");
|
||||
}
|
||||
}
|
||||
|
||||
function pad(n: number): string {
|
||||
return n < 10 ? "0" + n : String(n);
|
||||
}
|
||||
@@ -102,23 +112,20 @@ export class CaptionPanel {
|
||||
private readonly meta: HTMLElement;
|
||||
private readonly title: HTMLElement;
|
||||
private readonly text: HTMLElement;
|
||||
private readonly alt: HTMLElement;
|
||||
private visible = false;
|
||||
private placement = "";
|
||||
|
||||
constructor(parent: HTMLElement) {
|
||||
this.element = document.createElement("section");
|
||||
this.element.className = "caption";
|
||||
this.element.setAttribute("aria-live", "polite");
|
||||
this.element.setAttribute("aria-label", "Caption");
|
||||
this.meta = document.createElement("p");
|
||||
this.meta.className = "caption-meta";
|
||||
this.title = document.createElement("h2");
|
||||
this.title.className = "caption-title";
|
||||
this.text = document.createElement("p");
|
||||
this.text.className = "caption-text";
|
||||
this.alt = document.createElement("p");
|
||||
this.alt.className = "visually-hidden";
|
||||
this.element.append(this.meta, this.title, this.text, this.alt);
|
||||
this.element.append(this.meta, this.title, this.text);
|
||||
parent.appendChild(this.element);
|
||||
}
|
||||
|
||||
@@ -126,9 +133,10 @@ export class CaptionPanel {
|
||||
this.meta.textContent = metaLine(index, total, photo, showExif);
|
||||
this.title.textContent = photo.title ?? "";
|
||||
this.title.hidden = !photo.title;
|
||||
setLang(this.title, photo.title ?? "");
|
||||
renderRichText(this.text, photo.caption ?? "");
|
||||
this.text.hidden = !photo.caption;
|
||||
this.alt.textContent = photo.alt ?? "";
|
||||
setLang(this.text, photo.caption ?? "");
|
||||
}
|
||||
|
||||
show(visible: boolean): void {
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View, t
|
||||
|
||||
export function drawTile(
|
||||
g: CanvasRenderingContext2D,
|
||||
bitmap: ImageBitmap,
|
||||
bitmap: { width: number; height: number } & CanvasImageSource,
|
||||
level: Level,
|
||||
x: number,
|
||||
y: number,
|
||||
|
||||
+38
-2
@@ -8,6 +8,8 @@ const hysteresis = 24;
|
||||
export class IndexPage {
|
||||
private readonly strips: Strip[] = [];
|
||||
private readonly onScreen = new Set<Strip>();
|
||||
private readonly inView = new Set<Strip>();
|
||||
private suspended = false;
|
||||
private readonly indicator: BusyIndicator;
|
||||
private readonly hoverMode: MediaQueryList;
|
||||
private wordmark: MorphHandle | null = null;
|
||||
@@ -19,7 +21,7 @@ export class IndexPage {
|
||||
private readonly root: HTMLElement,
|
||||
index: SiteIndex,
|
||||
private readonly settings: Settings,
|
||||
env: StripEnv,
|
||||
private readonly env: StripEnv,
|
||||
) {
|
||||
const anchors = Array.from(root.querySelectorAll<HTMLElement>("a.strip"));
|
||||
const bySlug = new Map(index.albums.map((album) => [album.slug, album]));
|
||||
@@ -52,6 +54,36 @@ export class IndexPage {
|
||||
this.bind();
|
||||
}
|
||||
|
||||
suspend(hidden: boolean): void {
|
||||
if (this.suspended) {
|
||||
return;
|
||||
}
|
||||
this.suspended = true;
|
||||
for (const strip of this.strips) {
|
||||
strip.loader.stop();
|
||||
if (hidden) {
|
||||
strip.detach();
|
||||
}
|
||||
}
|
||||
this.env.scheduler.cancelAll();
|
||||
this.env.cache.trim(hidden ? 0 : this.env.cache.budget / 4);
|
||||
}
|
||||
|
||||
resume(): void {
|
||||
if (!this.suspended) {
|
||||
return;
|
||||
}
|
||||
this.suspended = false;
|
||||
for (const strip of this.strips) {
|
||||
if (this.inView.has(strip)) {
|
||||
strip.attach();
|
||||
}
|
||||
if (strip.isNear) {
|
||||
strip.startSession();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private wordmarkMoving(): boolean {
|
||||
const t = this.wordmark?.t ?? 0;
|
||||
return t > 0 && t < 1;
|
||||
@@ -93,8 +125,12 @@ export class IndexPage {
|
||||
continue;
|
||||
}
|
||||
if (entry.isIntersecting) {
|
||||
strip.attach();
|
||||
this.inView.add(strip);
|
||||
if (!this.suspended) {
|
||||
strip.attach();
|
||||
}
|
||||
} else {
|
||||
this.inView.delete(strip);
|
||||
strip.detach();
|
||||
}
|
||||
}
|
||||
|
||||
+44
-10
@@ -1,6 +1,7 @@
|
||||
import type { TileCache } from "./cache";
|
||||
import { drawTile, neededLevel, tileRange, visibleTiles, type TileRef, type View } from "./geometry";
|
||||
import { PRIORITY_CURRENT, PRIORITY_PREFETCH, type Scheduler, type TileResult } from "./scheduler";
|
||||
import { AbortError, PRIORITY_CURRENT, PRIORITY_PREFETCH, decodeBlob, releaseImage, type Scheduler, type TileResult } from "./scheduler";
|
||||
import type { ScrambleSpec } from "./scramble";
|
||||
import { currentThroughput, recordThroughput } from "./throughput";
|
||||
import type { Pyramid, Settings, Tiles } from "./types";
|
||||
|
||||
@@ -22,6 +23,25 @@ export interface LoadStatus {
|
||||
}
|
||||
|
||||
const fadeMs = 180;
|
||||
const retryMs = 400;
|
||||
|
||||
function wait(ms: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal.aborted) {
|
||||
reject(new AbortError());
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener("abort", stop);
|
||||
resolve();
|
||||
}, ms);
|
||||
const stop = () => {
|
||||
clearTimeout(timer);
|
||||
reject(new AbortError());
|
||||
};
|
||||
signal.addEventListener("abort", stop, { once: true });
|
||||
});
|
||||
}
|
||||
const probeStep = 3;
|
||||
const seedUpscale = 4;
|
||||
|
||||
@@ -73,7 +93,7 @@ export class PhotoLoader {
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
bytes[i] = raw.charCodeAt(i);
|
||||
}
|
||||
const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/" + this.env.tiles.format }));
|
||||
const bitmap = await decodeBlob(new Blob([bytes], { type: "image/" + this.env.tiles.format }));
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = bitmap.width * seedUpscale;
|
||||
canvas.height = bitmap.height * seedUpscale;
|
||||
@@ -89,17 +109,31 @@ export class PhotoLoader {
|
||||
}
|
||||
const pad = seedUpscale * 2;
|
||||
g.drawImage(bitmap, -pad, -pad, canvas.width + pad * 2, canvas.height + pad * 2);
|
||||
bitmap.close();
|
||||
releaseImage(bitmap);
|
||||
this.seedImage = canvas;
|
||||
}
|
||||
|
||||
private fetchTile(tile: TileRef, priority: number, signal: AbortSignal): Promise<TileResult> {
|
||||
const id = this.pyramid.levels[tile.level].tiles[tile.index];
|
||||
return this.env.scheduler.request(id, this.tileUrl(id), priority, signal).then((result) => {
|
||||
this.env.cache.put(id, result.bitmap);
|
||||
this.env.requestDraw();
|
||||
return result;
|
||||
});
|
||||
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;
|
||||
let result: TileResult;
|
||||
try {
|
||||
result = await this.env.scheduler.request(id, this.tileUrl(id), 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);
|
||||
}
|
||||
this.env.cache.put(id, result.bitmap);
|
||||
this.env.requestDraw();
|
||||
return result;
|
||||
}
|
||||
|
||||
private uncached(level: number, view: View): TileRef[] {
|
||||
|
||||
+94
-16
@@ -1,8 +1,12 @@
|
||||
import { unscramble, type ScrambleSpec } from "./scramble";
|
||||
|
||||
export const PRIORITY_CURRENT = 0;
|
||||
export const PRIORITY_PREFETCH = 1;
|
||||
|
||||
export type TileImage = ImageBitmap | HTMLImageElement | HTMLCanvasElement;
|
||||
|
||||
export interface TileResult {
|
||||
bitmap: ImageBitmap;
|
||||
bitmap: TileImage;
|
||||
bytes: number;
|
||||
ms: number;
|
||||
}
|
||||
@@ -16,6 +20,7 @@ interface Job {
|
||||
key: number;
|
||||
id: string;
|
||||
url: string;
|
||||
scramble?: ScrambleSpec;
|
||||
priority: number;
|
||||
seq: number;
|
||||
waiters: Set<Waiter>;
|
||||
@@ -27,7 +32,7 @@ interface Job {
|
||||
interface WorkerReply {
|
||||
key: number;
|
||||
ok: boolean;
|
||||
bitmap?: ImageBitmap;
|
||||
bitmap?: TileImage;
|
||||
bytes: number;
|
||||
ms: number;
|
||||
error?: string;
|
||||
@@ -40,11 +45,56 @@ export class AbortError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function releaseImage(image: TileImage): void {
|
||||
if ("close" in image) {
|
||||
image.close();
|
||||
} else if (image instanceof HTMLCanvasElement) {
|
||||
image.width = 0;
|
||||
image.height = 0;
|
||||
}
|
||||
}
|
||||
|
||||
export async function decodeBlob(blob: Blob): Promise<TileImage> {
|
||||
if (typeof createImageBitmap === "function") {
|
||||
return createImageBitmap(blob);
|
||||
}
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const image = new Image();
|
||||
image.decoding = "async";
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
return image;
|
||||
} finally {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
async function restore(image: TileImage, spec: ScrambleSpec): Promise<TileImage> {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = image.width;
|
||||
canvas.height = image.height;
|
||||
const g = canvas.getContext("2d");
|
||||
if (!g) {
|
||||
return image;
|
||||
}
|
||||
unscramble(g, image, image.width, image.height, spec);
|
||||
releaseImage(image);
|
||||
if (typeof createImageBitmap === "function") {
|
||||
const bitmap = await createImageBitmap(canvas);
|
||||
canvas.width = 0;
|
||||
canvas.height = 0;
|
||||
return bitmap;
|
||||
}
|
||||
return canvas;
|
||||
}
|
||||
|
||||
export class Scheduler {
|
||||
private readonly byId = new Map<string, Job>();
|
||||
private readonly byKey = new Map<number, Job>();
|
||||
private readonly queue: Job[] = [];
|
||||
private readonly workers: Worker[] = [];
|
||||
private workersUnscramble = true;
|
||||
private running = 0;
|
||||
private nextKey = 1;
|
||||
private nextSeq = 1;
|
||||
@@ -59,7 +109,7 @@ export class Scheduler {
|
||||
try {
|
||||
const worker = new Worker(workerUrl);
|
||||
const index = this.workers.length;
|
||||
worker.onmessage = (event: MessageEvent<WorkerReply>) => this.onReply(event.data);
|
||||
worker.onmessage = (event: MessageEvent<WorkerReply>) => this.onReply(event.data, index);
|
||||
worker.onerror = () => this.dropWorker(index);
|
||||
this.workers.push(worker);
|
||||
} catch {
|
||||
@@ -68,7 +118,7 @@ export class Scheduler {
|
||||
}
|
||||
}
|
||||
|
||||
request(id: string, url: string, priority: number, signal: AbortSignal): Promise<TileResult> {
|
||||
request(id: string, url: string, priority: number, signal: AbortSignal, scramble?: ScrambleSpec): Promise<TileResult> {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(new AbortError());
|
||||
}
|
||||
@@ -83,6 +133,7 @@ export class Scheduler {
|
||||
key: this.nextKey++,
|
||||
id,
|
||||
url,
|
||||
scramble,
|
||||
priority,
|
||||
seq: this.nextSeq++,
|
||||
waiters: new Set(),
|
||||
@@ -118,6 +169,17 @@ export class Scheduler {
|
||||
});
|
||||
}
|
||||
|
||||
cancelAll(): void {
|
||||
for (const job of [...this.byKey.values()]) {
|
||||
const waiters = [...job.waiters];
|
||||
job.waiters.clear();
|
||||
for (const waiter of waiters) {
|
||||
waiter.reject(new AbortError());
|
||||
}
|
||||
this.cancel(job);
|
||||
}
|
||||
}
|
||||
|
||||
private cancel(job: Job): void {
|
||||
this.forget(job);
|
||||
if (!job.running) {
|
||||
@@ -163,12 +225,16 @@ export class Scheduler {
|
||||
|
||||
private start(job: Job): void {
|
||||
const live = this.liveWorkers();
|
||||
if (live.length > 0) {
|
||||
if (live.length > 0 && (!job.scramble || this.workersUnscramble)) {
|
||||
const index = live[this.nextWorker++ % live.length];
|
||||
job.worker = index;
|
||||
this.workers[index].postMessage({ type: "fetch", key: job.key, url: job.url });
|
||||
this.workers[index].postMessage({ type: "fetch", key: job.key, url: job.url, scramble: job.scramble });
|
||||
return;
|
||||
}
|
||||
this.runOnMainThread(job);
|
||||
}
|
||||
|
||||
private runOnMainThread(job: Job): void {
|
||||
job.worker = -1;
|
||||
job.controller = new AbortController();
|
||||
void this.fetchOnMainThread(job, job.controller.signal);
|
||||
@@ -193,9 +259,7 @@ export class Scheduler {
|
||||
delete this.workers[index];
|
||||
for (const job of this.byKey.values()) {
|
||||
if (job.running && job.worker === index) {
|
||||
job.worker = -1;
|
||||
job.controller = new AbortController();
|
||||
void this.fetchOnMainThread(job, job.controller.signal);
|
||||
this.runOnMainThread(job);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,17 +273,31 @@ export class Scheduler {
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const ms = performance.now() - started;
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
this.onReply({ key: job.key, ok: true, bitmap, bytes: blob.size, ms });
|
||||
let image = await decodeBlob(blob);
|
||||
if (job.scramble) {
|
||||
image = await restore(image, job.scramble);
|
||||
}
|
||||
this.onReply({ key: job.key, ok: true, bitmap: image, bytes: blob.size, ms }, -1);
|
||||
} catch (error) {
|
||||
this.onReply({ key: job.key, ok: false, bytes: 0, ms: 0, error: String(error) });
|
||||
this.onReply({ key: job.key, ok: false, bytes: 0, ms: 0, error: String(error) }, -1);
|
||||
}
|
||||
}
|
||||
|
||||
private onReply(reply: WorkerReply): void {
|
||||
private onReply(reply: WorkerReply, from: number): void {
|
||||
const job = this.byKey.get(reply.key);
|
||||
if (!job || !job.running) {
|
||||
reply.bitmap?.close();
|
||||
if (!job || !job.running || job.worker !== from) {
|
||||
if (reply.bitmap) {
|
||||
releaseImage(reply.bitmap);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!reply.ok && from >= 0 && (reply.error === "unsupported-bitmap" || reply.error === "unsupported-offscreen")) {
|
||||
if (reply.error === "unsupported-bitmap") {
|
||||
this.dropWorker(from);
|
||||
} else {
|
||||
this.workersUnscramble = false;
|
||||
this.runOnMainThread(job);
|
||||
}
|
||||
return;
|
||||
}
|
||||
job.running = false;
|
||||
@@ -233,7 +311,7 @@ export class Scheduler {
|
||||
waiter.resolve(result);
|
||||
}
|
||||
if (waiters.length === 0) {
|
||||
reply.bitmap.close();
|
||||
releaseImage(reply.bitmap);
|
||||
}
|
||||
} else {
|
||||
const error = new Error(reply.error ?? "tile failed");
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
export interface ScrambleSpec {
|
||||
seed: string;
|
||||
level: number;
|
||||
x: number;
|
||||
y: number;
|
||||
cell: number;
|
||||
}
|
||||
|
||||
export function tileSeed(spec: ScrambleSpec): number {
|
||||
const text = spec.seed + "|" + spec.level + "|" + spec.x + "|" + spec.y;
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
h = Math.imul(h ^ text.charCodeAt(i), 16777619) >>> 0;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
export function cellPermutation(n: number, seed: number): number[] {
|
||||
const perm = new Array<number>(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
perm[i] = i;
|
||||
}
|
||||
let state = seed | 0;
|
||||
const next = (): number => {
|
||||
state = (state + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
for (let i = n - 1; i > 0; i--) {
|
||||
const j = Math.floor(next() * (i + 1));
|
||||
const swap = perm[i];
|
||||
perm[i] = perm[j];
|
||||
perm[j] = swap;
|
||||
}
|
||||
return perm;
|
||||
}
|
||||
|
||||
export interface CellCanvas {
|
||||
drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
|
||||
drawImage(image: CanvasImageSource, dx: number, dy: number): void;
|
||||
}
|
||||
|
||||
export function unscramble(g: CellCanvas, image: CanvasImageSource, width: number, height: number, spec: ScrambleSpec): void {
|
||||
g.drawImage(image, 0, 0);
|
||||
const cell = spec.cell;
|
||||
const cols = Math.floor(width / cell);
|
||||
const rows = Math.floor(height / cell);
|
||||
const n = cols * rows;
|
||||
if (n < 2) {
|
||||
return;
|
||||
}
|
||||
const perm = cellPermutation(n, tileSeed(spec));
|
||||
for (let i = 0; i < n; i++) {
|
||||
const source = perm[i];
|
||||
if (source === i) {
|
||||
continue;
|
||||
}
|
||||
const sx = (i % cols) * cell;
|
||||
const sy = Math.floor(i / cols) * cell;
|
||||
const dx = (source % cols) * cell;
|
||||
const dy = Math.floor(source / cols) * cell;
|
||||
g.drawImage(image, sx, sy, cell, cell, dx, dy, cell, cell);
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,10 @@ export class Strip {
|
||||
return this.expanded;
|
||||
}
|
||||
|
||||
get isNear(): boolean {
|
||||
return this.near;
|
||||
}
|
||||
|
||||
layout(size: StripSize): void {
|
||||
const cover = this.cover;
|
||||
const scale = Math.max(size.width / cover.width, size.open / cover.height);
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface Pyramid {
|
||||
height: number;
|
||||
levels: Level[];
|
||||
seed: string;
|
||||
scramble?: string;
|
||||
}
|
||||
|
||||
export interface Exif {
|
||||
@@ -40,6 +41,8 @@ export interface Tiles {
|
||||
tile_size: number;
|
||||
overlap: number;
|
||||
path: string;
|
||||
scrambled?: boolean;
|
||||
cell?: number;
|
||||
}
|
||||
|
||||
export interface Manifest {
|
||||
|
||||
+66
-2
@@ -1,5 +1,5 @@
|
||||
import { cloneChop, mountWordmark } from "./brand";
|
||||
import { CaptionPanel } from "./caption";
|
||||
import { CaptionPanel, setLang } from "./caption";
|
||||
import type { View } from "./geometry";
|
||||
import { BusyIndicator, ProgressLine } from "./indicator";
|
||||
import { PhotoLoader, type LoaderEnv } from "./loader";
|
||||
@@ -106,6 +106,9 @@ export class Viewer {
|
||||
private readonly homeMark: HTMLElement | null;
|
||||
private nextStrip: Strip | null = null;
|
||||
private idleTimer = 0;
|
||||
private announceTimer = 0;
|
||||
private suspended = false;
|
||||
private readonly announcer: HTMLElement;
|
||||
private readonly reducedMotion: MediaQueryList;
|
||||
private readonly loaders: Array<PhotoLoader | undefined>;
|
||||
private layouts: PhotoLayout[] = [];
|
||||
@@ -139,7 +142,11 @@ export class Viewer {
|
||||
) {
|
||||
this.canvas = document.createElement("canvas");
|
||||
this.canvas.className = "stage-canvas";
|
||||
this.canvas.setAttribute("aria-hidden", "true");
|
||||
this.canvas.setAttribute("role", "img");
|
||||
this.announcer = document.createElement("p");
|
||||
this.announcer.className = "visually-hidden";
|
||||
this.announcer.setAttribute("aria-live", "polite");
|
||||
this.announcer.setAttribute("aria-atomic", "true");
|
||||
this.fade = document.createElement("canvas");
|
||||
this.fade.className = "stage-fade";
|
||||
this.fade.setAttribute("aria-hidden", "true");
|
||||
@@ -155,6 +162,7 @@ export class Viewer {
|
||||
this.nextFrame = this.endCard.querySelector(".next-strip") as HTMLElement;
|
||||
stage.prepend(this.canvas, this.fade);
|
||||
stage.appendChild(this.endCard);
|
||||
stage.appendChild(this.announcer);
|
||||
this.caption = new CaptionPanel(stage);
|
||||
this.progress = new ProgressLine(document.body);
|
||||
this.indicator = new BusyIndicator(document.body);
|
||||
@@ -594,6 +602,7 @@ export class Viewer {
|
||||
this.indicator.watch(null);
|
||||
this.progress.watch(null);
|
||||
}
|
||||
this.describe(stop.photo, previousStop >= 0);
|
||||
if (stop.photo >= 0) {
|
||||
const photo = this.manifest.photos[stop.photo];
|
||||
this.caption.set(photo, stop.photo, this.manifest.photos.length, this.manifest.show_exif);
|
||||
@@ -606,6 +615,60 @@ export class Viewer {
|
||||
this.updateCaption();
|
||||
}
|
||||
|
||||
private describe(photoIndex: number, announce: boolean): void {
|
||||
const total = this.manifest.photos.length;
|
||||
let label: string;
|
||||
if (photoIndex < 0) {
|
||||
const next = this.nextLink.querySelector(".next-title")?.textContent ?? "";
|
||||
label = "End of album." + (next ? " Next album: " + next + "." : "");
|
||||
} else {
|
||||
const photo = this.manifest.photos[photoIndex];
|
||||
const name = photo.alt || photo.title || "";
|
||||
label = "Photo " + (photoIndex + 1) + " of " + total + (name ? ": " + name : "");
|
||||
}
|
||||
this.canvas.setAttribute("aria-label", label);
|
||||
clearTimeout(this.announceTimer);
|
||||
if (announce) {
|
||||
this.announceTimer = window.setTimeout(() => {
|
||||
this.announcer.textContent = label;
|
||||
}, 500);
|
||||
}
|
||||
}
|
||||
|
||||
suspend(hidden: boolean): void {
|
||||
if (this.suspended) {
|
||||
return;
|
||||
}
|
||||
this.suspended = true;
|
||||
this.tween = null;
|
||||
for (const loader of this.loaders) {
|
||||
loader?.stop();
|
||||
}
|
||||
this.nextStrip?.loader.stop();
|
||||
this.env.scheduler.cancelAll();
|
||||
this.env.cache.trim(hidden ? 0 : this.env.cache.budget / 4);
|
||||
if (hidden) {
|
||||
this.nextStrip?.detach();
|
||||
this.canvas.width = 1;
|
||||
this.canvas.height = 1;
|
||||
this.fade.width = 1;
|
||||
this.fade.height = 1;
|
||||
}
|
||||
}
|
||||
|
||||
resume(): void {
|
||||
if (!this.suspended) {
|
||||
return;
|
||||
}
|
||||
this.suspended = false;
|
||||
this.canvas.width = 0;
|
||||
this.measure();
|
||||
this.camera = this.stops[this.current].camera;
|
||||
this.syncNextStrip();
|
||||
this.startSession();
|
||||
this.requestDraw();
|
||||
}
|
||||
|
||||
private startSession(): void {
|
||||
const stop = this.stops[this.current];
|
||||
if (stop.photo < 0) {
|
||||
@@ -723,6 +786,7 @@ export class Viewer {
|
||||
}
|
||||
if (title) {
|
||||
title.textContent = next.title;
|
||||
setLang(title as HTMLElement, next.title);
|
||||
}
|
||||
if (next.cover) {
|
||||
this.nextStrip = new Strip(
|
||||
|
||||
+40
-2
@@ -1,7 +1,10 @@
|
||||
import { unscramble, type ScrambleSpec } from "./scramble";
|
||||
|
||||
interface FetchMessage {
|
||||
type: "fetch";
|
||||
key: number;
|
||||
url: string;
|
||||
scramble?: ScrambleSpec;
|
||||
}
|
||||
|
||||
interface AbortMessage {
|
||||
@@ -25,8 +28,17 @@ interface WorkerScope {
|
||||
postMessage(message: Outgoing, transfer?: Transferable[]): void;
|
||||
}
|
||||
|
||||
interface OffscreenLike {
|
||||
getContext(kind: "2d"): CanvasRenderingContext2D | null;
|
||||
transferToImageBitmap(): ImageBitmap;
|
||||
}
|
||||
|
||||
type OffscreenConstructor = new (width: number, height: number) => OffscreenLike;
|
||||
|
||||
const scope = self as unknown as WorkerScope;
|
||||
const controllers = new Map<number, AbortController>();
|
||||
const canDecode = typeof createImageBitmap === "function";
|
||||
const Offscreen = (self as unknown as { OffscreenCanvas?: OffscreenConstructor }).OffscreenCanvas;
|
||||
|
||||
scope.onmessage = (event) => {
|
||||
const message = event.data;
|
||||
@@ -38,7 +50,29 @@ scope.onmessage = (event) => {
|
||||
void load(message);
|
||||
};
|
||||
|
||||
function restore(bitmap: ImageBitmap, spec: ScrambleSpec): ImageBitmap {
|
||||
if (!Offscreen) {
|
||||
throw new Error("unsupported-offscreen");
|
||||
}
|
||||
const canvas = new Offscreen(bitmap.width, bitmap.height);
|
||||
const g = canvas.getContext("2d");
|
||||
if (!g) {
|
||||
throw new Error("unsupported-offscreen");
|
||||
}
|
||||
unscramble(g, bitmap, bitmap.width, bitmap.height, spec);
|
||||
bitmap.close();
|
||||
return canvas.transferToImageBitmap();
|
||||
}
|
||||
|
||||
async function load(message: FetchMessage): Promise<void> {
|
||||
if (!canDecode) {
|
||||
scope.postMessage({ key: message.key, ok: false, bytes: 0, ms: 0, error: "unsupported-bitmap" });
|
||||
return;
|
||||
}
|
||||
if (message.scramble && !Offscreen) {
|
||||
scope.postMessage({ key: message.key, ok: false, bytes: 0, ms: 0, error: "unsupported-offscreen" });
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
controllers.set(message.key, controller);
|
||||
const started = performance.now();
|
||||
@@ -49,14 +83,18 @@ async function load(message: FetchMessage): Promise<void> {
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const ms = performance.now() - started;
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
let bitmap = await createImageBitmap(blob);
|
||||
if (message.scramble) {
|
||||
bitmap = restore(bitmap, message.scramble);
|
||||
}
|
||||
if (controller.signal.aborted) {
|
||||
bitmap.close();
|
||||
throw new Error("aborted");
|
||||
}
|
||||
scope.postMessage({ key: message.key, ok: true, bitmap, bytes: blob.size, ms }, [bitmap]);
|
||||
} catch (error) {
|
||||
scope.postMessage({ key: message.key, ok: false, bytes: 0, ms: 0, error: String(error) });
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
scope.postMessage({ key: message.key, ok: false, bytes: 0, ms: 0, error: text });
|
||||
} finally {
|
||||
controllers.delete(message.key);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user