M2-M3: tile loader and album viewer

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
lucioandClaude Opus 5.5 committed 2026-11-04 04:22:20 -08:00
1 parent 18a397653a
commit 6d39dc1713
24 files changed
+2687 -16

No files matched your search

+1
View File
@@ -5,3 +5,4 @@
/albums/
/dist/
*.tmp-*
/web/node_modules/
+11
View File
@@ -41,3 +41,14 @@ state/
site.key
pyramids/<photo-hash>.json
```
## Front-end
TypeScript and CSS live in `web/src`; the minified bundles in `internal/site/static` are committed, so `go build` never needs Node. After changing the front-end, rebuild on the host with Node 22:
```sh
npm --prefix web ci
npm --prefix web run build
```
`build` type-checks with `tsc --noEmit` (strict) and bundles `app.js`, `app.css` and `worker.js` with esbuild. Each site build copies them to `/assets/` under content-hashed names.
+13 -2
View File
@@ -413,6 +413,17 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
if err := os.Symlink(filepath.Join("..", "..", "t"), filepath.Join(stage, "t")); err != nil {
return fmt.Errorf("link tiles: %w", err)
}
assets := site.StaticAssets()
if err := assets.Write(stage); err != nil {
return err
}
page := site.Page{
Assets: assets,
BudgetMS: b.cfg.Loading.BudgetMS,
MaxDPR: b.cfg.Loading.MaxDPR,
Concurrency: b.cfg.Loading.Concurrency,
BlockContextMenu: b.cfg.Protection.BlockContextMenu,
}
index := &site.Index{Build: id, Tiles: b.tiles(), Albums: []site.IndexAlbum{}}
for _, m := range manifests {
@@ -450,7 +461,7 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
return
}
errs[i] = fsutil.WriteAtomic(filepath.Join(dir, "index.html"), 0o644, func(w io.Writer) error {
return site.RenderAlbum(w, m)
return site.RenderAlbum(w, m, page)
})
}(i, m)
}
@@ -462,7 +473,7 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
return
}
errs[len(manifests)] = fsutil.WriteAtomic(filepath.Join(stage, "index.html"), 0o644, func(w io.Writer) error {
return site.RenderIndex(w, index)
return site.RenderIndex(w, index, page)
})
}()
wg.Wait()
+66
View File
@@ -0,0 +1,66 @@
package site
import (
"crypto/sha256"
"embed"
"encoding/hex"
"os"
"path"
"path/filepath"
"strings"
"sync"
"github.com/luciochen233/luphoto/internal/fsutil"
)
//go:embed static/app.js static/app.css static/worker.js
var staticFiles embed.FS
type Asset struct {
Name string
URL string
data []byte
}
type Assets struct {
JS Asset
CSS Asset
Worker Asset
}
var loadAssets = sync.OnceValue(func() Assets {
return Assets{
JS: hashedAsset("static/app.js"),
CSS: hashedAsset("static/app.css"),
Worker: hashedAsset("static/worker.js"),
}
})
func hashedAsset(source string) Asset {
data, err := staticFiles.ReadFile(source)
if err != nil {
panic(err)
}
sum := sha256.Sum256(data)
base := path.Base(source)
ext := path.Ext(base)
name := strings.TrimSuffix(base, ext) + "." + hex.EncodeToString(sum[:])[:8] + ext
return Asset{Name: name, URL: "/assets/" + name, data: data}
}
func StaticAssets() Assets {
return loadAssets()
}
func (a Assets) Write(buildDir string) error {
dir := filepath.Join(buildDir, "assets")
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
for _, asset := range []Asset{a.JS, a.CSS, a.Worker} {
if err := fsutil.WriteFileAtomic(filepath.Join(dir, asset.Name), asset.data, 0o644); err != nil {
return err
}
}
return nil
}
+14 -2
View File
@@ -77,13 +77,23 @@ func IndexName(build string) string {
return "index." + build + ".json"
}
type Page struct {
Assets Assets
BudgetMS int
MaxDPR float64
Concurrency int
BlockContextMenu bool
}
type indexPage struct {
Page
Build string
IndexURL string
Albums []IndexAlbum
}
type albumPage struct {
Page
Build string
Slug string
Title string
@@ -94,16 +104,18 @@ type albumPage struct {
IndexURL string
}
func RenderIndex(w io.Writer, index *Index) error {
func RenderIndex(w io.Writer, index *Index, page Page) error {
return templates.ExecuteTemplate(w, "index.html", indexPage{
Page: page,
Build: index.Build,
IndexURL: IndexURL(index.Build),
Albums: index.Albums,
})
}
func RenderAlbum(w io.Writer, m *Manifest) error {
func RenderAlbum(w io.Writer, m *Manifest, page Page) error {
return templates.ExecuteTemplate(w, "album.html", albumPage{
Page: page,
Build: m.Build,
Slug: m.Slug,
Title: m.Title,
+1
View File
@@ -0,0 +1 @@
:root{--graphite: #111114;--paper: #f3f1ec;--beam: #fff3cf;--steel: #8a94a6;--steel-deep: #3f4b60;--cinnabar: #c3361f;--font-display: "Bricolage Grotesque", "Noto Sans SC", system-ui, sans-serif;--font-body: "IBM Plex Sans", "Noto Sans SC", system-ui, -apple-system, "Segoe UI", sans-serif;--font-mono: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;--font-chop: "Noto Serif SC", "Songti SC", serif;--ease-light: cubic-bezier(.16, 1, .3, 1);--t-hover: .12s;--t-reveal: .24s;color-scheme:dark}html,body{margin:0;min-height:100%;background:var(--graphite);color:var(--paper);font-family:var(--font-body);-webkit-font-smoothing:antialiased}a{color:var(--paper)}:focus-visible{outline:2px solid var(--beam);outline-offset:3px}.visually-hidden{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}.index-list{max-width:48rem;margin:0 auto;padding:48px 16px}.index-list h1{font-family:var(--font-display);font-weight:600}.index-list li{margin:8px 0}.index-list time,.index-list span{font-family:var(--font-mono);color:var(--steel);font-size:.85em}.has-viewer body.viewer{position:fixed;inset:0;overflow:hidden;overscroll-behavior:none}.album-fallback{padding:48px 16px}.has-viewer .album-fallback{display:none}.stage{overflow:hidden;background:var(--graphite);touch-action:none;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;cursor:grab}.has-viewer .stage{position:fixed;inset:0}.stage.is-dragging{cursor:grabbing}.stage-canvas,.stage-fade{position:absolute;inset:0;width:100%;height:100%;display:block}.stage-fade{pointer-events:none;opacity:0;transition:opacity var(--t-reveal) var(--ease-light)}.caption{position:absolute;left:0;bottom:0;box-sizing:border-box;max-height:60%;overflow:hidden;padding:72px 24px 20px;background:linear-gradient(to top,#111114e6,#1111149e 55%,#11111400);opacity:0;pointer-events:none;transition:opacity var(--t-reveal) var(--ease-light)}.caption.is-visible{opacity:1}.caption-meta{margin:0;font-family:var(--font-mono);font-size:12px;letter-spacing:.04em;color:var(--steel);font-variant-numeric:tabular-nums}.caption-title{margin:10px 0 0;font-family:var(--font-display);font-size:22px;font-weight:600;line-height:1.2}.caption-text{margin:8px 0 0;max-width:62ch;font-size:15px;line-height:1.55}.caption-text em{font-style:italic}.end-card{position:absolute;top:0;left:0;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;will-change:transform}.chop{width:56px;height:56px;display:grid;place-items:center;border-radius:8px;background:var(--cinnabar);color:var(--paper);font-family:var(--font-chop);font-size:34px;line-height:1}.signature{margin:0;font-family:var(--font-display);font-size:28px}.next-album{display:flex;flex-direction:column;align-items:center;gap:6px;margin-top:24px;text-decoration:none;transition:color var(--t-hover) var(--ease-light)}.next-album:hover .next-title{color:var(--beam)}.next-eyebrow{font-family:var(--font-mono);font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--steel)}.next-title{font-family:var(--font-display);font-size:24px;font-weight:600}@media (prefers-reduced-motion: reduce){.next-album{transition:none}}
+1
View File
@@ -0,0 +1 @@
"use strict";(()=>{function _(){let t=navigator.deviceMemory,e=typeof matchMedia=="function"&&matchMedia("(pointer: coarse)").matches,i=Math.min(screen.width,screen.height)<=820;return t!==void 0&&t<=4||e&&i?120*1048576:250*1048576}var L=class{constructor(t){this.budget=t;this.entries=new Map;this.used=0}get(t){let e=this.entries.get(t);return e&&(this.entries.delete(t),this.entries.set(t,e)),e}has(t){return this.entries.has(t)}put(t,e){let i=this.entries.get(t);if(i){i.bitmap!==e&&e.close();return}let n=e.width*e.height*4;this.entries.set(t,{bitmap:e,bytes:n,at:performance.now()}),this.used+=n,this.evict()}evict(){for(;this.used>this.budget&&this.entries.size>1;){let t=this.entries.keys().next();if(t.done)return;let e=this.entries.get(t.value);this.entries.delete(t.value),e&&(this.used-=e.bytes,e.bitmap.close())}}};var P=class extends Error{constructor(){super("aborted"),this.name="AbortError"}},R=class{constructor(t,e){this.concurrency=t;this.byId=new Map;this.byKey=new Map;this.queue=[];this.workers=[];this.running=0;this.nextKey=1;this.nextSeq=1;this.nextWorker=0;if(typeof Worker>"u"||e==="")return;let i=(navigator.hardwareConcurrency??2)>=4?2:1;for(let n=0;n<i;n++)try{let s=new Worker(e),o=this.workers.length;s.onmessage=h=>this.onReply(h.data),s.onerror=()=>this.dropWorker(o),this.workers.push(s)}catch{break}}request(t,e,i,n){return n.aborted?Promise.reject(new P):new Promise((s,o)=>{let h=this.byId.get(t);h?i<h.priority&&(h.priority=i):(h={key:this.nextKey++,id:t,url:e,priority:i,seq:this.nextSeq++,waiters:new Set,running:!1,worker:-1,controller:null},this.byId.set(t,h),this.byKey.set(h.key,h),this.queue.push(h));let c={resolve:s,reject:o};h.waiters.add(c);let a=h;n.addEventListener("abort",()=>{a.waiters.delete(c)&&(o(new P),a.waiters.size===0&&setTimeout(()=>{a.waiters.size===0&&this.byKey.get(a.key)===a&&this.cancel(a)},0))},{once:!0}),this.pump()})}cancel(t){if(this.forget(t),!t.running){let e=this.queue.indexOf(t);e>=0&&this.queue.splice(e,1);return}t.running=!1,this.running--,t.controller?t.controller.abort():t.worker>=0&&this.workers[t.worker]&&this.workers[t.worker].postMessage({type:"abort",key:t.key}),this.pump()}forget(t){this.byId.get(t.id)===t&&this.byId.delete(t.id),this.byKey.delete(t.key)}pump(){for(;this.running<this.concurrency&&this.queue.length>0;){let t=0;for(let i=1;i<this.queue.length;i++){let n=this.queue[i],s=this.queue[t];(n.priority<s.priority||n.priority===s.priority&&n.seq<s.seq)&&(t=i)}let e=this.queue.splice(t,1)[0];e.running=!0,this.running++,this.start(e)}}start(t){let e=this.liveWorkers();if(e.length>0){let i=e[this.nextWorker++%e.length];t.worker=i,this.workers[i].postMessage({type:"fetch",key:t.key,url:t.url});return}t.worker=-1,t.controller=new AbortController,this.fetchOnMainThread(t,t.controller.signal)}liveWorkers(){let t=[];return this.workers.forEach((e,i)=>{e&&t.push(i)}),t}dropWorker(t){let e=this.workers[t];if(e){e.terminate(),delete this.workers[t];for(let i of this.byKey.values())i.running&&i.worker===t&&(i.worker=-1,i.controller=new AbortController,this.fetchOnMainThread(i,i.controller.signal))}}async fetchOnMainThread(t,e){let i=performance.now();try{let n=await fetch(t.url,{signal:e,credentials:"same-origin"});if(!n.ok)throw new Error("HTTP "+n.status);let s=await n.blob(),o=performance.now()-i,h=await createImageBitmap(s);this.onReply({key:t.key,ok:!0,bitmap:h,bytes:s.size,ms:o})}catch(n){this.onReply({key:t.key,ok:!1,bytes:0,ms:0,error:String(n)})}}onReply(t){let e=this.byKey.get(t.key);if(!e||!e.running){t.bitmap?.close();return}e.running=!1,this.running--,this.forget(e);let i=[...e.waiters];if(e.waiters.clear(),t.ok&&t.bitmap){let n={bitmap:t.bitmap,bytes:t.bytes,ms:t.ms};for(let s of i)s.resolve(n);i.length===0&&t.bitmap.close()}else{let n=new Error(t.error??"tile failed");for(let s of i)s.reject(n)}this.pump()}};function X(r){let t=r.dataset,e=(i,n)=>{let s=Number(i);return Number.isFinite(s)&&s>0?s:n};return{page:t.page??"",build:t.build??"",slug:t.album??"",manifestUrl:t.manifest??"",indexUrl:t.index??"",workerUrl:t.worker??"",budgetMs:e(t.budgetMs,3e3),maxDpr:e(t.maxDpr,2),concurrency:Math.max(1,Math.round(e(t.concurrency,6))),blockContextMenu:t.blockContextMenu!=="false"}}function Y(r){return r<10?"0"+r:String(r)}function it(r){let t=(r.model??"").trim(),e=(r.make??"").trim(),i=e.split(/\s+/)[0]??"";i&&t.toLowerCase().startsWith(i.toLowerCase()+" ")&&(t=t.slice(i.length+1).trim());let n=/^([A-Za-z]{1,3}) (\d+[A-Za-z0-9]*)$/.exec(t);return n&&(t=n[1]+n[2]),t||e}function nt(r){let t=/(\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)?)\s*mm\s*(?:F|f\/?)\s*([\d.]+(?:-[\d.]+)?)/.exec(r);return t?t[1]+" f/"+t[2]:r.trim()}function K(r){return String(Math.round(r*10)/10)}function st(r,t,e,i){let n=[Y(r+1)+" / "+Y(t)],s=e.exif;if(i&&s){let o=it(s);o&&n.push(o),s.lens&&n.push(nt(s.lens)),s.focal_length&&n.push(K(s.focal_length)+"mm"),s.f_number&&n.push("f/"+K(s.f_number)),s.exposure&&n.push(s.exposure.includes("/")?s.exposure:s.exposure+"s"),s.iso&&n.push("ISO "+s.isLine truncated
+1
View File
@@ -0,0 +1 @@
"use strict";(()=>{var s=self,o=new Map;s.onmessage=t=>{let e=t.data;if(e.type==="abort"){o.get(e.key)?.abort(),o.delete(e.key);return}l(e)};async function l(t){let e=new AbortController;o.set(t.key,e);let i=performance.now();try{let r=await fetch(t.url,{signal:e.signal,credentials:"same-origin"});if(!r.ok)throw new Error("HTTP "+r.status);let a=await r.blob(),c=performance.now()-i,n=await createImageBitmap(a);if(e.signal.aborted)throw n.close(),new Error("aborted");s.postMessage({key:t.key,ok:!0,bitmap:n,bytes:a.size,ms:c},[n])}catch(r){s.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:String(r)})}finally{o.delete(t.key)}}})();
+12 -9
View File
@@ -2,19 +2,22 @@
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="robots" content="noimageindex">
<meta name="theme-color" content="#111114">
<title>{{.Title}} · Lucio</title>
<link rel="stylesheet" href="{{.Assets.CSS.URL}}">
<link rel="preload" href="{{.ManifestURL}}" as="fetch" crossorigin>
<script src="{{.Assets.JS.URL}}" defer></script>
</head>
<body data-build="{{.Build}}" data-album="{{.Slug}}" data-manifest="{{.ManifestURL}}" data-index="{{.IndexURL}}">
<main>
<h1>{{.Title}}</h1>
{{- if .Subtitle}}
<p>{{.Subtitle}}</p>
{{- end}}
<p>{{.Photos}} photos{{if .Date}} · <time>{{.Date}}</time>{{end}}</p>
<p><a href="/">All albums</a></p>
<body class="viewer" data-page="album" data-build="{{.Build}}" data-album="{{.Slug}}" data-manifest="{{.ManifestURL}}" data-index="{{.IndexURL}}" data-worker="{{.Assets.Worker.URL}}" data-budget-ms="{{.BudgetMS}}" data-max-dpr="{{.MaxDPR}}" data-concurrency="{{.Concurrency}}" data-block-context-menu="{{.BlockContextMenu}}">
<main id="stage" class="stage" aria-label="{{.Title}}">
<h1 class="visually-hidden">{{.Title}}{{if .Subtitle}} · {{.Subtitle}}{{end}}</h1>
</main>
<div class="album-fallback">
<p>{{.Photos}} photos{{if .Date}} · <time>{{.Date}}</time>{{end}}</p>
<noscript><p>This album needs JavaScript to draw its photos.</p></noscript>
<p><a href="/">All albums</a></p>
</div>
</body>
</html>
+5 -3
View File
@@ -2,13 +2,15 @@
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="robots" content="noimageindex">
<meta name="theme-color" content="#111114">
<title>Photos · Lucio</title>
<link rel="stylesheet" href="{{.Assets.CSS.URL}}">
<link rel="preload" href="{{.IndexURL}}" as="fetch" crossorigin>
</head>
<body data-build="{{.Build}}" data-index="{{.IndexURL}}">
<main>
<body class="index" data-page="index" data-build="{{.Build}}" data-index="{{.IndexURL}}">
<main class="index-list">
<h1>Photos · Lucio</h1>
<ul>
{{- range .Albums}}
+496
View File
@@ -0,0 +1,496 @@
{
"name": "luphoto-web",
"version": "0.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "luphoto-web",
"version": "0.0.0",
"devDependencies": {
"esbuild": "0.24.2",
"typescript": "5.7.3"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz",
"integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz",
"integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz",
"integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz",
"integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz",
"integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz",
"integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz",
"integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz",
"integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz",
"integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz",
"integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz",
"integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz",
"integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz",
"integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz",
"integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz",
"integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz",
"integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz",
"integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz",
"integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz",
"integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz",
"integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz",
"integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz",
"integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz",
"integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz",
"integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz",
"integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/esbuild": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz",
"integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.24.2",
"@esbuild/android-arm": "0.24.2",
"@esbuild/android-arm64": "0.24.2",
"@esbuild/android-x64": "0.24.2",
"@esbuild/darwin-arm64": "0.24.2",
"@esbuild/darwin-x64": "0.24.2",
"@esbuild/freebsd-arm64": "0.24.2",
"@esbuild/freebsd-x64": "0.24.2",
"@esbuild/linux-arm": "0.24.2",
"@esbuild/linux-arm64": "0.24.2",
"@esbuild/linux-ia32": "0.24.2",
"@esbuild/linux-loong64": "0.24.2",
"@esbuild/linux-mips64el": "0.24.2",
"@esbuild/linux-ppc64": "0.24.2",
"@esbuild/linux-riscv64": "0.24.2",
"@esbuild/linux-s390x": "0.24.2",
"@esbuild/linux-x64": "0.24.2",
"@esbuild/netbsd-arm64": "0.24.2",
"@esbuild/netbsd-x64": "0.24.2",
"@esbuild/openbsd-arm64": "0.24.2",
"@esbuild/openbsd-x64": "0.24.2",
"@esbuild/sunos-x64": "0.24.2",
"@esbuild/win32-arm64": "0.24.2",
"@esbuild/win32-ia32": "0.24.2",
"@esbuild/win32-x64": "0.24.2"
}
},
"node_modules/typescript": {
"version": "5.7.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz",
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "luphoto-web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit",
"bundle": "esbuild src/app.ts src/worker.ts src/app.css --bundle --minify --target=es2020,safari15 --legal-comments=none --outdir=../internal/site/static",
"build": "npm run typecheck && npm run bundle"
},
"devDependencies": {
"esbuild": "0.24.2",
"typescript": "5.7.3"
}
}
+231
View File
@@ -0,0 +1,231 @@
:root {
--graphite: #111114;
--paper: #f3f1ec;
--beam: #fff3cf;
--steel: #8a94a6;
--steel-deep: #3f4b60;
--cinnabar: #c3361f;
--font-display: "Bricolage Grotesque", "Noto Sans SC", system-ui, sans-serif;
--font-body: "IBM Plex Sans", "Noto Sans SC", system-ui, -apple-system, "Segoe UI", sans-serif;
--font-mono: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
--font-chop: "Noto Serif SC", "Songti SC", serif;
--ease-light: cubic-bezier(0.16, 1, 0.3, 1);
--t-hover: 120ms;
--t-reveal: 240ms;
color-scheme: dark;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--graphite);
color: var(--paper);
font-family: var(--font-body);
-webkit-font-smoothing: antialiased;
}
a {
color: var(--paper);
}
:focus-visible {
outline: 2px solid var(--beam);
outline-offset: 3px;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
border: 0;
}
.index-list {
max-width: 48rem;
margin: 0 auto;
padding: 48px 16px;
}
.index-list h1 {
font-family: var(--font-display);
font-weight: 600;
}
.index-list li {
margin: 8px 0;
}
.index-list time,
.index-list span {
font-family: var(--font-mono);
color: var(--steel);
font-size: 0.85em;
}
.has-viewer body.viewer {
position: fixed;
inset: 0;
overflow: hidden;
overscroll-behavior: none;
}
.album-fallback {
padding: 48px 16px;
}
.has-viewer .album-fallback {
display: none;
}
.stage {
overflow: hidden;
background: var(--graphite);
touch-action: none;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
-webkit-tap-highlight-color: transparent;
cursor: grab;
}
.has-viewer .stage {
position: fixed;
inset: 0;
}
.stage.is-dragging {
cursor: grabbing;
}
.stage-canvas,
.stage-fade {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
.stage-fade {
pointer-events: none;
opacity: 0;
transition: opacity var(--t-reveal) var(--ease-light);
}
.caption {
position: absolute;
left: 0;
bottom: 0;
box-sizing: border-box;
max-height: 60%;
overflow: hidden;
padding: 72px 24px 20px;
background: linear-gradient(to top, rgba(17, 17, 20, 0.9) 0%, rgba(17, 17, 20, 0.62) 55%, rgba(17, 17, 20, 0) 100%);
opacity: 0;
pointer-events: none;
transition: opacity var(--t-reveal) var(--ease-light);
}
.caption.is-visible {
opacity: 1;
}
.caption-meta {
margin: 0;
font-family: var(--font-mono);
font-size: 12px;
letter-spacing: 0.04em;
color: var(--steel);
font-variant-numeric: tabular-nums;
}
.caption-title {
margin: 10px 0 0;
font-family: var(--font-display);
font-size: 22px;
font-weight: 600;
line-height: 1.2;
}
.caption-text {
margin: 8px 0 0;
max-width: 62ch;
font-size: 15px;
line-height: 1.55;
}
.caption-text em {
font-style: italic;
}
.end-card {
position: absolute;
top: 0;
left: 0;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 20px;
will-change: transform;
}
.chop {
width: 56px;
height: 56px;
display: grid;
place-items: center;
border-radius: 8px;
background: var(--cinnabar);
color: var(--paper);
font-family: var(--font-chop);
font-size: 34px;
line-height: 1;
}
.signature {
margin: 0;
font-family: var(--font-display);
font-size: 28px;
}
.next-album {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
margin-top: 24px;
text-decoration: none;
transition: color var(--t-hover) var(--ease-light);
}
.next-album:hover .next-title {
color: var(--beam);
}
.next-eyebrow {
font-family: var(--font-mono);
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--steel);
}
.next-title {
font-family: var(--font-display);
font-size: 24px;
font-weight: 600;
}
@media (prefers-reduced-motion: reduce) {
.next-album {
transition: none;
}
}
+36
View File
@@ -0,0 +1,36 @@
import { TileCache, cacheBudget } from "./cache";
import { Scheduler } from "./scheduler";
import { readSettings, type Manifest } from "./types";
import { Viewer } from "./viewer";
async function startAlbum(stage: HTMLElement): Promise<void> {
const settings = readSettings(document.body);
const response = await fetch(settings.manifestUrl, { credentials: "same-origin" });
if (!response.ok) {
throw new Error("manifest " + response.status);
}
const manifest = (await response.json()) as Manifest;
if (manifest.photos.length === 0) {
return;
}
const scheduler = new Scheduler(settings.concurrency, settings.workerUrl);
const cache = new TileCache(cacheBudget());
document.documentElement.classList.add("has-viewer");
new Viewer(stage, manifest, settings, { scheduler, cache, settings, tiles: manifest.tiles });
}
function boot(): void {
const stage = document.getElementById("stage");
if (document.body.dataset.page === "album" && stage) {
startAlbum(stage).catch((error: unknown) => {
stage.dataset.error = String(error);
document.documentElement.classList.remove("has-viewer");
});
}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", boot, { once: true });
} else {
boot();
}
+69
View File
@@ -0,0 +1,69 @@
export interface CachedTile {
bitmap: ImageBitmap;
bytes: number;
at: number;
}
interface NavigatorWithMemory extends Navigator {
deviceMemory?: number;
}
export function cacheBudget(): number {
const mb = 1024 * 1024;
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;
}
return 250 * mb;
}
export class TileCache {
private readonly entries = new Map<string, CachedTile>();
private used = 0;
constructor(private readonly budget: number) {}
get(id: string): CachedTile | undefined {
const entry = this.entries.get(id);
if (entry) {
this.entries.delete(id);
this.entries.set(id, entry);
}
return entry;
}
has(id: string): boolean {
return this.entries.has(id);
}
put(id: string, bitmap: ImageBitmap): void {
const existing = this.entries.get(id);
if (existing) {
if (existing.bitmap !== bitmap) {
bitmap.close();
}
return;
}
const bytes = bitmap.width * bitmap.height * 4;
this.entries.set(id, { bitmap, bytes, at: performance.now() });
this.used += bytes;
this.evict();
}
private evict(): void {
while (this.used > this.budget && this.entries.size > 1) {
const oldest = this.entries.keys().next();
if (oldest.done) {
return;
}
const entry = this.entries.get(oldest.value);
this.entries.delete(oldest.value);
if (entry) {
this.used -= entry.bytes;
entry.bitmap.close();
}
}
}
}
+132
View File
@@ -0,0 +1,132 @@
import type { Exif, Photo } from "./types";
function pad(n: number): string {
return n < 10 ? "0" + n : String(n);
}
function shortCamera(exif: Exif): string {
let model = (exif.model ?? "").trim();
const make = (exif.make ?? "").trim();
const brand = make.split(/\s+/)[0] ?? "";
if (brand && model.toLowerCase().startsWith(brand.toLowerCase() + " ")) {
model = model.slice(brand.length + 1).trim();
}
const joined = /^([A-Za-z]{1,3}) (\d+[A-Za-z0-9]*)$/.exec(model);
if (joined) {
model = joined[1] + joined[2];
}
return model || make;
}
function shortLens(lens: string): string {
const match = /(\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)?)\s*mm\s*(?:F|f\/?)\s*([\d.]+(?:-[\d.]+)?)/.exec(lens);
if (match) {
return match[1] + " f/" + match[2];
}
return lens.trim();
}
function trimNumber(n: number): string {
return String(Math.round(n * 10) / 10);
}
export function metaLine(index: number, total: number, photo: Photo, showExif: boolean): string {
const parts = [pad(index + 1) + " / " + pad(total)];
const exif = photo.exif;
if (showExif && exif) {
const camera = shortCamera(exif);
if (camera) {
parts.push(camera);
}
if (exif.lens) {
parts.push(shortLens(exif.lens));
}
if (exif.focal_length) {
parts.push(trimNumber(exif.focal_length) + "mm");
}
if (exif.f_number) {
parts.push("f/" + trimNumber(exif.f_number));
}
if (exif.exposure) {
parts.push(exif.exposure.includes("/") ? exif.exposure : exif.exposure + "s");
}
if (exif.iso) {
parts.push("ISO " + exif.iso);
}
}
return parts.join(" · ");
}
export function renderRichText(target: HTMLElement, text: string): void {
target.textContent = "";
text.split(/\r?\n/).forEach((line, lineIndex) => {
if (lineIndex > 0) {
target.appendChild(document.createElement("br"));
}
const parts = line.split("*");
const balanced = (parts.length - 1) % 2 === 0;
parts.forEach((part, i) => {
const odd = i % 2 === 1;
if (odd && (balanced || i !== parts.length - 1)) {
const em = document.createElement("em");
em.textContent = part;
target.appendChild(em);
} else {
target.appendChild(document.createTextNode((odd ? "*" : "") + part));
}
});
});
}
export class CaptionPanel {
readonly element: HTMLElement;
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.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);
parent.appendChild(this.element);
}
set(photo: Photo, index: number, total: number, showExif: boolean): void {
this.meta.textContent = metaLine(index, total, photo, showExif);
this.title.textContent = photo.title ?? "";
this.title.hidden = !photo.title;
renderRichText(this.text, photo.caption ?? "");
this.text.hidden = !photo.caption;
this.alt.textContent = photo.alt ?? "";
}
show(visible: boolean): void {
if (visible !== this.visible) {
this.visible = visible;
this.element.classList.toggle("is-visible", visible);
}
}
place(left: number, width: number, bottom: number): void {
const key = Math.round(left) + "," + Math.round(width) + "," + Math.round(bottom);
if (key === this.placement) {
return;
}
this.placement = key;
const style = this.element.style;
style.width = Math.round(width) + "px";
style.transform = "translate3d(" + Math.round(left) + "px," + -Math.round(bottom) + "px,0)";
}
}
+104
View File
@@ -0,0 +1,104 @@
import type { Level, Pyramid } from "./types";
export interface View {
displayWidth: number;
u0: number;
v0: number;
u1: number;
v1: number;
}
export interface TileRange {
x0: number;
x1: number;
y0: number;
y1: number;
}
export interface TileRef {
level: number;
x: number;
y: number;
index: number;
}
export function neededLevel(pyramid: Pyramid, displayWidth: number, dpr: number): number {
const wanted = displayWidth * dpr;
for (let i = 0; i < pyramid.levels.length; i++) {
if (pyramid.levels[i].width >= wanted) {
return i;
}
}
return pyramid.levels.length - 1;
}
export function tileRange(level: Level, view: View, tileSize: number): TileRange | null {
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);
const d = Math.min(level.height, view.v1 * level.height);
if (b <= a || d <= c) {
return null;
}
return {
x0: Math.min(level.cols - 1, Math.floor(a / tileSize)),
x1: Math.min(level.cols - 1, Math.ceil(b / tileSize) - 1),
y0: Math.min(level.rows - 1, Math.floor(c / tileSize)),
y1: Math.min(level.rows - 1, Math.ceil(d / tileSize) - 1),
};
}
export function visibleTiles(pyramid: Pyramid, levelIndex: number, view: View, tileSize: number): TileRef[] {
const level = pyramid.levels[levelIndex];
const range = tileRange(level, view, tileSize);
if (!range) {
return [];
}
const cx = ((view.u0 + view.u1) / 2) * level.width;
const cy = ((view.v0 + view.v1) / 2) * level.height;
const tiles: Array<TileRef & { distance: number }> = [];
for (let y = range.y0; y <= range.y1; y++) {
for (let x = range.x0; x <= range.x1; x++) {
const mx = (x * tileSize + Math.min((x + 1) * tileSize, level.width)) / 2;
const my = (y * tileSize + Math.min((y + 1) * tileSize, level.height)) / 2;
tiles.push({ level: levelIndex, x, y, index: y * level.cols + x, distance: (mx - cx) ** 2 + (my - cy) ** 2 });
}
}
tiles.sort((p, q) => p.distance - q.distance);
return tiles.map(({ level: l, x, y, index }) => ({ level: l, x, y, index }));
}
export function drawTile(
g: CanvasRenderingContext2D,
bitmap: ImageBitmap,
level: Level,
x: number,
y: number,
tileSize: number,
overlap: number,
originX: number,
originY: number,
scale: number,
): void {
const lx0 = x * tileSize;
const lx1 = Math.min((x + 1) * tileSize, level.width);
const ly0 = y * tileSize;
const ly1 = Math.min((y + 1) * tileSize, level.height);
const fileX = x > 0 ? lx0 - overlap : 0;
const fileY = y > 0 ? ly0 - overlap : 0;
const dx0 = Math.round(originX + lx0 * scale);
const dx1 = Math.round(originX + lx1 * scale);
const dy0 = Math.round(originY + ly0 * scale);
const dy1 = Math.round(originY + ly1 * scale);
if (dx1 <= dx0 || dy1 <= dy0) {
return;
}
const sx0 = Math.max(fileX, (dx0 - originX) / scale);
const sx1 = Math.min(fileX + bitmap.width, (dx1 - originX) / scale);
const sy0 = Math.max(fileY, (dy0 - originY) / scale);
const sy1 = Math.min(fileY + bitmap.height, (dy1 - originY) / scale);
if (sx1 <= sx0 || sy1 <= sy0) {
return;
}
g.drawImage(bitmap, sx0 - fileX, sy0 - fileY, sx1 - sx0, sy1 - sy0, dx0, dy0, dx1 - dx0, dy1 - dy0);
}
+312
View File
@@ -0,0 +1,312 @@
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 { currentThroughput, recordThroughput } from "./throughput";
import type { Pyramid, Settings, Tiles } from "./types";
export interface LoaderEnv {
scheduler: Scheduler;
cache: TileCache;
settings: Settings;
tiles: Tiles;
requestDraw: () => void;
}
const fadeMs = 180;
const probeStep = 3;
const seedUpscale = 4;
export interface DrawTarget {
g: CanvasRenderingContext2D;
originX: number;
originY: number;
width: number;
height: number;
canvasWidth: number;
canvasHeight: number;
displayWidth: number;
dpr: number;
now: number;
}
export class PhotoLoader {
private seedImage: CanvasImageSource | null = null;
private seedPromise: Promise<void> | null = null;
private session: AbortController | null = null;
private prefetchController: AbortController | null = null;
finalLevel = -1;
constructor(readonly pyramid: Pyramid, private readonly env: LoaderEnv) {}
private tileUrl(id: string): string {
const tiles = this.env.tiles;
return tiles.path + this.pyramid.hash + "/" + id + "." + tiles.format;
}
ensureSeed(): Promise<void> {
if (!this.seedPromise) {
this.seedPromise = this.decodeSeed().then(
() => this.env.requestDraw(),
() => undefined,
);
}
return this.seedPromise;
}
private async decodeSeed(): Promise<void> {
if (!this.pyramid.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 createImageBitmap(new Blob([bytes], { type: "image/" + this.env.tiles.format }));
const canvas = document.createElement("canvas");
canvas.width = bitmap.width * seedUpscale;
canvas.height = bitmap.height * seedUpscale;
const g = canvas.getContext("2d");
if (!g) {
this.seedImage = bitmap;
return;
}
g.imageSmoothingEnabled = true;
g.imageSmoothingQuality = "high";
if ("filter" in g) {
g.filter = "blur(" + seedUpscale * 0.75 + "px)";
}
const pad = seedUpscale * 2;
g.drawImage(bitmap, -pad, -pad, canvas.width + pad * 2, canvas.height + pad * 2);
bitmap.close();
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 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]));
}
private uncachedBytes(level: number, view: View): number {
const bytes = this.pyramid.levels[level].bytes;
let total = 0;
for (const tile of this.uncached(level, view)) {
total += bytes[tile.index];
}
return total;
}
private fetchAll(tiles: TileRef[], priority: number, signal: AbortSignal): Promise<PromiseSettledResult<TileResult>[]> {
return Promise.allSettled(tiles.map((tile) => this.fetchTile(tile, priority, signal)));
}
probeLevel(view: View, dpr: number): number {
return Math.max(0, neededLevel(this.pyramid, view.displayWidth, dpr) - probeStep);
}
start(view: View, dpr: number, onSettled: () => void): void {
this.stopSession();
const controller = new AbortController();
this.session = controller;
void this.run(view, dpr, controller).then(() => {
if (this.session === controller) {
this.session = null;
}
if (!controller.signal.aborted || controller.signal.reason === "deadline") {
onSettled();
}
});
}
private async run(view: View, dpr: number, controller: AbortController): Promise<void> {
const signal = controller.signal;
const started = performance.now();
const budget = this.env.settings.budgetMs;
const timer = setTimeout(() => controller.abort("deadline"), budget);
try {
await this.ensureSeed();
if (signal.aborted) {
return;
}
const needed = neededLevel(this.pyramid, view.displayWidth, dpr);
const probe = Math.max(0, needed - probeStep);
const probeTiles = this.uncached(probe, view).slice(0, 2);
if (probeTiles.length > 0) {
const results = await this.fetchAll(probeTiles, PRIORITY_CURRENT, signal);
let bytes = 0;
let ms = 0;
for (const result of results) {
if (result.status === "fulfilled") {
bytes += result.value.bytes;
ms = Math.max(ms, result.value.ms);
}
}
if (bytes > 0 && ms > 0) {
recordThroughput(bytes / ms);
}
}
if (signal.aborted) {
return;
}
this.finalLevel = Math.max(this.finalLevel, probe);
const throughput = currentThroughput();
const remaining = budget - (performance.now() - started);
let final = probe;
for (let level = needed; level > probe; level--) {
if (this.uncachedBytes(level, view) / throughput <= remaining * 0.8) {
final = level;
break;
}
}
const plan: number[] = [];
if (final - probe >= 2) {
plan.push(Math.floor((probe + final) / 2));
}
if (final > probe) {
plan.push(final);
}
this.finalLevel = final;
for (const level of plan) {
await this.fetchAll(this.uncached(level, view), PRIORITY_CURRENT, signal);
if (signal.aborted) {
return;
}
}
} finally {
clearTimeout(timer);
}
}
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);
}
});
}
prefetchLevel(view: View, level: number): void {
if (level < 0) {
return;
}
const controller = this.resetPrefetch();
void this.fetchAll(this.uncached(level, view), PRIORITY_PREFETCH, controller.signal);
}
private resetPrefetch(): AbortController {
this.prefetchController?.abort();
this.prefetchController = new AbortController();
return this.prefetchController;
}
stopPrefetch(): void {
this.prefetchController?.abort();
this.prefetchController = null;
}
stopSession(): void {
this.session?.abort("superseded");
this.session = null;
}
stop(): void {
this.stopSession();
this.stopPrefetch();
}
draw(target: DrawTarget): boolean {
const { g, originX, originY, width, height, canvasWidth, canvasHeight } = target;
const left = Math.max(0, originX);
const top = Math.max(0, originY);
const right = Math.min(canvasWidth, originX + width);
const bottom = Math.min(canvasHeight, originY + height);
if (right <= left || bottom <= top) {
return false;
}
if (!this.seedPromise) {
void this.ensureSeed();
}
const view: View = {
displayWidth: target.displayWidth,
u0: (left - originX) / width,
u1: (right - originX) / width,
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 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);
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]);
if (!entry || target.now - entry.at < fadeMs) {
complete = false;
break;
}
}
}
if (complete) {
base = l;
}
}
if (base < 0 && this.seedImage) {
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);
g.restore();
}
let animating = false;
for (let l = Math.max(0, base); l <= needed; l++) {
const level = levels[l];
const range = tileRange(level, view, tileSize);
if (!range) {
continue;
}
const scale = width / level.width;
g.imageSmoothingEnabled = true;
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]);
if (!entry) {
continue;
}
const age = target.now - entry.at;
if (age < fadeMs) {
g.globalAlpha = Math.max(0, age / fadeMs);
animating = true;
}
drawTile(g, entry.bitmap, level, x, y, tileSize, overlap, originX, originY, scale);
g.globalAlpha = 1;
}
}
}
return animating;
}
}
+246
View File
@@ -0,0 +1,246 @@
export const PRIORITY_CURRENT = 0;
export const PRIORITY_PREFETCH = 1;
export interface TileResult {
bitmap: ImageBitmap;
bytes: number;
ms: number;
}
interface Waiter {
resolve: (result: TileResult) => void;
reject: (error: Error) => void;
}
interface Job {
key: number;
id: string;
url: string;
priority: number;
seq: number;
waiters: Set<Waiter>;
running: boolean;
worker: number;
controller: AbortController | null;
}
interface WorkerReply {
key: number;
ok: boolean;
bitmap?: ImageBitmap;
bytes: number;
ms: number;
error?: string;
}
export class AbortError extends Error {
constructor() {
super("aborted");
this.name = "AbortError";
}
}
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 running = 0;
private nextKey = 1;
private nextSeq = 1;
private nextWorker = 0;
constructor(private readonly concurrency: number, workerUrl: string) {
if (typeof Worker === "undefined" || workerUrl === "") {
return;
}
const count = (navigator.hardwareConcurrency ?? 2) >= 4 ? 2 : 1;
for (let i = 0; i < count; i++) {
try {
const worker = new Worker(workerUrl);
const index = this.workers.length;
worker.onmessage = (event: MessageEvent<WorkerReply>) => this.onReply(event.data);
worker.onerror = () => this.dropWorker(index);
this.workers.push(worker);
} catch {
break;
}
}
}
request(id: string, url: string, priority: number, signal: AbortSignal): Promise<TileResult> {
if (signal.aborted) {
return Promise.reject(new AbortError());
}
return new Promise<TileResult>((resolve, reject) => {
let job = this.byId.get(id);
if (job) {
if (priority < job.priority) {
job.priority = priority;
}
} else {
job = {
key: this.nextKey++,
id,
url,
priority,
seq: this.nextSeq++,
waiters: new Set(),
running: false,
worker: -1,
controller: null,
};
this.byId.set(id, job);
this.byKey.set(job.key, job);
this.queue.push(job);
}
const waiter: Waiter = { resolve, reject };
job.waiters.add(waiter);
const owner = job;
signal.addEventListener(
"abort",
() => {
if (!owner.waiters.delete(waiter)) {
return;
}
reject(new AbortError());
if (owner.waiters.size === 0) {
setTimeout(() => {
if (owner.waiters.size === 0 && this.byKey.get(owner.key) === owner) {
this.cancel(owner);
}
}, 0);
}
},
{ once: true },
);
this.pump();
});
}
private cancel(job: Job): void {
this.forget(job);
if (!job.running) {
const at = this.queue.indexOf(job);
if (at >= 0) {
this.queue.splice(at, 1);
}
return;
}
job.running = false;
this.running--;
if (job.controller) {
job.controller.abort();
} else if (job.worker >= 0 && this.workers[job.worker]) {
this.workers[job.worker].postMessage({ type: "abort", key: job.key });
}
this.pump();
}
private forget(job: Job): void {
if (this.byId.get(job.id) === job) {
this.byId.delete(job.id);
}
this.byKey.delete(job.key);
}
private pump(): void {
while (this.running < this.concurrency && this.queue.length > 0) {
let best = 0;
for (let i = 1; i < this.queue.length; i++) {
const a = this.queue[i];
const b = this.queue[best];
if (a.priority < b.priority || (a.priority === b.priority && a.seq < b.seq)) {
best = i;
}
}
const job = this.queue.splice(best, 1)[0];
job.running = true;
this.running++;
this.start(job);
}
}
private start(job: Job): void {
const live = this.liveWorkers();
if (live.length > 0) {
const index = live[this.nextWorker++ % live.length];
job.worker = index;
this.workers[index].postMessage({ type: "fetch", key: job.key, url: job.url });
return;
}
job.worker = -1;
job.controller = new AbortController();
void this.fetchOnMainThread(job, job.controller.signal);
}
private liveWorkers(): number[] {
const live: number[] = [];
this.workers.forEach((worker, index) => {
if (worker) {
live.push(index);
}
});
return live;
}
private dropWorker(index: number): void {
const worker = this.workers[index];
if (!worker) {
return;
}
worker.terminate();
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);
}
}
}
private async fetchOnMainThread(job: Job, signal: AbortSignal): Promise<void> {
const started = performance.now();
try {
const response = await fetch(job.url, { signal, credentials: "same-origin" });
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
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 });
} catch (error) {
this.onReply({ key: job.key, ok: false, bytes: 0, ms: 0, error: String(error) });
}
}
private onReply(reply: WorkerReply): void {
const job = this.byKey.get(reply.key);
if (!job || !job.running) {
reply.bitmap?.close();
return;
}
job.running = false;
this.running--;
this.forget(job);
const waiters = [...job.waiters];
job.waiters.clear();
if (reply.ok && reply.bitmap) {
const result: TileResult = { bitmap: reply.bitmap, bytes: reply.bytes, ms: reply.ms };
for (const waiter of waiters) {
waiter.resolve(result);
}
if (waiters.length === 0) {
reply.bitmap.close();
}
} else {
const error = new Error(reply.error ?? "tile failed");
for (const waiter of waiters) {
waiter.reject(error);
}
}
this.pump();
}
}
+27
View File
@@ -0,0 +1,27 @@
const storageKey = "luphoto.throughput";
const defaultBytesPerMs = 1000;
const weight = 0.5;
export function readThroughput(): number | null {
try {
const value = Number(sessionStorage.getItem(storageKey));
return Number.isFinite(value) && value > 0 ? value : null;
} catch {
return null;
}
}
export function currentThroughput(): number {
return readThroughput() ?? defaultBytesPerMs;
}
export function recordThroughput(sample: number): number {
const previous = readThroughput();
const blended = previous === null ? sample : previous * (1 - weight) + sample * weight;
try {
sessionStorage.setItem(storageKey, String(blended));
} catch {
return blended;
}
return blended;
}
+106
View File
@@ -0,0 +1,106 @@
export interface Level {
width: number;
height: number;
cols: number;
rows: number;
quality: number;
tiles: string[];
bytes: number[];
}
export interface Pyramid {
hash: string;
width: number;
height: number;
levels: Level[];
seed: string;
}
export interface Exif {
make?: string;
model?: string;
lens?: string;
focal_length?: number;
f_number?: number;
exposure?: string;
iso?: number;
date?: string;
}
export interface Photo extends Pyramid {
title?: string;
caption?: string;
alt?: string;
slides: number;
exif?: Exif;
}
export interface Tiles {
format: string;
tile_size: number;
overlap: number;
path: string;
}
export interface Manifest {
build: string;
slug: string;
title: string;
subtitle?: string;
date?: string;
collapsed_focus_y: number;
show_exif: boolean;
tiles: Tiles;
cover: Pyramid;
photos: Photo[];
}
export interface IndexAlbum {
slug: string;
title: string;
subtitle?: string;
date?: string;
collapsed_focus_y: number;
photos: number;
manifest: string;
cover: Pyramid;
}
export interface SiteIndex {
build: string;
tiles: Tiles;
albums: IndexAlbum[];
}
export interface Settings {
page: string;
build: string;
slug: string;
manifestUrl: string;
indexUrl: string;
workerUrl: string;
budgetMs: number;
maxDpr: number;
concurrency: number;
blockContextMenu: boolean;
}
export function readSettings(body: HTMLElement): Settings {
const data = body.dataset;
const num = (value: string | undefined, fallback: number): number => {
const parsed = Number(value);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
};
return {
page: data.page ?? "",
build: data.build ?? "",
slug: data.album ?? "",
manifestUrl: data.manifest ?? "",
indexUrl: data.index ?? "",
workerUrl: data.worker ?? "",
budgetMs: num(data.budgetMs, 3000),
maxDpr: num(data.maxDpr, 2),
concurrency: Math.max(1, Math.round(num(data.concurrency, 6))),
blockContextMenu: data.blockContextMenu !== "false",
};
}
+707
View File
@@ -0,0 +1,707 @@
import { CaptionPanel } from "./caption";
import type { View } from "./geometry";
import { PhotoLoader, type LoaderEnv } from "./loader";
import type { Manifest, Settings, SiteIndex } from "./types";
interface PhotoLayout {
scale: number;
width: number;
height: number;
section: number;
slides: number;
start: number;
left: number;
top: number;
}
interface Stop {
photo: number;
slide: number;
camera: number;
}
interface Sample {
t: number;
x: number;
}
interface Tween {
from: number;
to: number;
start: number;
duration: number;
}
const gutter = 24;
const tapDistance = 10;
const tapMs = 300;
const flickSpeed = 0.35;
const rubberBand = 0.35;
const captionZone = 0.2;
function cubicBezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {
const cx = 3 * x1;
const bx = 3 * (x2 - x1) - cx;
const ax = 1 - cx - bx;
const cy = 3 * y1;
const by = 3 * (y2 - y1) - cy;
const ay = 1 - cy - by;
const sampleX = (s: number) => ((ax * s + bx) * s + cx) * s;
const sampleY = (s: number) => ((ay * s + by) * s + cy) * s;
const slopeX = (s: number) => (3 * ax * s + 2 * bx) * s + cx;
return (t: number) => {
if (t <= 0) {
return 0;
}
if (t >= 1) {
return 1;
}
let s = t;
for (let i = 0; i < 8; i++) {
const err = sampleX(s) - t;
const d = slopeX(s);
if (Math.abs(err) < 1e-5) {
return sampleY(s);
}
if (Math.abs(d) < 1e-6) {
break;
}
s -= err / d;
}
let lo = 0;
let hi = 1;
s = t;
for (let i = 0; i < 24; i++) {
const x = sampleX(s);
if (Math.abs(x - t) < 1e-5) {
break;
}
if (x < t) {
lo = s;
} else {
hi = s;
}
s = (lo + hi) / 2;
}
return sampleY(s);
};
}
const ease = cubicBezier(0.16, 1, 0.3, 1);
export class Viewer {
private readonly canvas: HTMLCanvasElement;
private readonly fade: HTMLCanvasElement;
private readonly g: CanvasRenderingContext2D;
private readonly caption: CaptionPanel;
private readonly endCard: HTMLElement;
private readonly nextLink: HTMLAnchorElement;
private readonly reducedMotion: MediaQueryList;
private readonly loaders: Array<PhotoLoader | undefined>;
private layouts: PhotoLayout[] = [];
private stops: Stop[] = [];
private endLeft = 0;
private vw = 0;
private vh = 0;
private dpr = 1;
private camera = 0;
private current = 0;
private tween: Tween | null = null;
private frame = 0;
private pointerId: number | null = null;
private pointerType = "";
private dragging = false;
private downX = 0;
private downY = 0;
private downT = 0;
private downCamera = 0;
private samples: Sample[] = [];
private hover = false;
private pinned = false;
private resizeTimer = 0;
private indexRequested = false;
constructor(
private readonly stage: HTMLElement,
private readonly manifest: Manifest,
private readonly settings: Settings,
private readonly env: Omit<LoaderEnv, "requestDraw">,
) {
this.canvas = document.createElement("canvas");
this.canvas.className = "stage-canvas";
this.canvas.setAttribute("aria-hidden", "true");
this.fade = document.createElement("canvas");
this.fade.className = "stage-fade";
this.fade.setAttribute("aria-hidden", "true");
this.fade.width = 1;
this.fade.height = 1;
const g = this.canvas.getContext("2d", { alpha: false });
if (!g) {
throw new Error("canvas 2d unavailable");
}
this.g = g;
this.endCard = this.buildEndCard();
this.nextLink = this.endCard.querySelector("a.next-album") as HTMLAnchorElement;
stage.prepend(this.canvas, this.fade);
stage.appendChild(this.endCard);
this.caption = new CaptionPanel(stage);
this.loaders = new Array(manifest.photos.length);
this.reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
this.measure();
this.current = this.stopForHash();
this.camera = this.stops[this.current].camera;
this.bind();
this.activate(-1);
this.requestDraw();
}
private buildEndCard(): HTMLElement {
const card = document.createElement("section");
card.className = "end-card";
card.setAttribute("aria-label", "End of album");
const chop = document.createElement("div");
chop.className = "chop";
chop.setAttribute("aria-hidden", "true");
chop.textContent = "陈";
const signature = document.createElement("p");
signature.className = "signature";
signature.textContent = "— Lucio";
const next = document.createElement("a");
next.className = "next-album";
next.href = "/";
const eyebrow = document.createElement("span");
eyebrow.className = "next-eyebrow";
eyebrow.textContent = "All albums";
const title = document.createElement("span");
title.className = "next-title";
next.append(eyebrow, title);
card.append(chop, signature, next);
return card;
}
private loader(index: number): PhotoLoader {
let loader = this.loaders[index];
if (!loader) {
loader = new PhotoLoader(this.manifest.photos[index], { ...this.env, requestDraw: () => this.requestDraw() });
this.loaders[index] = loader;
}
return loader;
}
private measure(): void {
const rect = this.stage.getBoundingClientRect();
this.vw = Math.max(1, rect.width);
this.vh = Math.max(1, rect.height);
this.dpr = Math.min(window.devicePixelRatio || 1, this.settings.maxDpr);
const cw = Math.max(1, Math.round(this.vw * this.dpr));
const ch = Math.max(1, Math.round(this.vh * this.dpr));
if (this.canvas.width !== cw || this.canvas.height !== ch) {
this.canvas.width = cw;
this.canvas.height = ch;
}
this.layouts = [];
this.stops = [];
let start = 0;
this.manifest.photos.forEach((photo, index) => {
const slides = Math.max(1, photo.slides || 1);
const scale = Math.min(this.vw / (photo.width / slides), this.vh / photo.height);
const width = photo.width * scale;
const height = photo.height * scale;
const section = width / slides;
const left = start + gutter / 2 + (this.vw - section) / 2;
this.layouts.push({ scale, width, height, section, slides, start, left, top: (this.vh - height) / 2 });
for (let slide = 0; slide < slides; slide++) {
this.stops.push({ photo: index, slide, camera: start + gutter / 2 + this.vw / 2 + slide * section });
}
start += this.vw + (slides - 1) * section + gutter;
});
this.endLeft = start + gutter / 2;
this.stops.push({ photo: -1, slide: 0, camera: this.endLeft + this.vw / 2 });
this.endCard.style.width = this.vw + "px";
}
private stopForHash(): number {
const match = /^#(\d+)$/.exec(location.hash);
if (!match) {
return 0;
}
const photo = Math.min(this.manifest.photos.length, Math.max(1, Number(match[1]))) - 1;
const index = this.stops.findIndex((stop) => stop.photo === photo);
return index < 0 ? 0 : index;
}
private bind(): void {
const stage = this.stage;
stage.addEventListener("pointerdown", (e) => this.onPointerDown(e));
stage.addEventListener("pointermove", (e) => this.onPointerMove(e));
stage.addEventListener("pointerup", (e) => this.onPointerUp(e, false));
stage.addEventListener("pointercancel", (e) => this.onPointerUp(e, true));
stage.addEventListener("pointerleave", (e) => {
if (e.pointerType === "mouse" && this.pointerId === null) {
this.hover = false;
this.updateCaption();
}
});
stage.addEventListener("dragstart", (e) => e.preventDefault());
stage.addEventListener("selectstart", (e) => e.preventDefault());
if (this.settings.blockContextMenu) {
stage.addEventListener("contextmenu", (e) => e.preventDefault());
}
window.addEventListener("keydown", (e) => this.onKey(e));
window.addEventListener("hashchange", () => {
const target = this.stopForHash();
if (this.stops[target].photo !== this.stops[this.current].photo) {
this.jump(target);
}
});
new ResizeObserver(() => this.onResize()).observe(stage);
this.fade.addEventListener("transitionend", () => {
if (this.fade.style.opacity === "0") {
this.fade.width = 1;
this.fade.height = 1;
}
});
}
private onResize(): void {
const before = this.vw + "x" + this.vh + "@" + this.dpr;
this.measure();
if (before === this.vw + "x" + this.vh + "@" + this.dpr) {
return;
}
this.tween = null;
this.camera = this.stops[this.current].camera;
this.requestDraw();
clearTimeout(this.resizeTimer);
this.resizeTimer = window.setTimeout(() => this.startSession(), 200);
}
private onKey(e: KeyboardEvent): void {
if (e.altKey || e.ctrlKey || e.metaKey) {
return;
}
const target = e.target as HTMLElement | null;
if (target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))) {
return;
}
switch (e.key) {
case "ArrowRight":
this.go(this.current + 1);
break;
case "ArrowLeft":
this.go(this.current - 1);
break;
case "Home":
this.go(0);
break;
case "End":
this.go(this.stops.length - 2);
break;
case "Escape":
location.assign("/");
break;
case "i":
case "I":
this.pinned = !this.pinned;
this.updateCaption();
break;
default:
return;
}
e.preventDefault();
}
private onPointerDown(e: PointerEvent): void {
if (this.pointerId !== null || (e.pointerType === "mouse" && e.button !== 0)) {
return;
}
if ((e.target as Element).closest("a, button")) {
return;
}
this.pointerId = e.pointerId;
this.pointerType = e.pointerType;
this.dragging = false;
this.downX = e.clientX;
this.downY = e.clientY;
this.downT = e.timeStamp;
this.tween = null;
this.downCamera = this.camera;
this.samples = [{ t: e.timeStamp, x: e.clientX }];
this.stage.setPointerCapture(e.pointerId);
}
private onPointerMove(e: PointerEvent): void {
if (this.pointerId === null) {
if (e.pointerType === "mouse") {
this.hover = this.inCaptionZone(e.clientX, e.clientY);
this.updateCaption();
}
return;
}
if (e.pointerId !== this.pointerId) {
return;
}
const dx = e.clientX - this.downX;
const dy = e.clientY - this.downY;
if (!this.dragging && Math.hypot(dx, dy) >= tapDistance) {
this.dragging = true;
this.stage.classList.add("is-dragging");
this.updateCaption();
}
if (!this.dragging) {
return;
}
this.samples.push({ t: e.timeStamp, x: e.clientX });
while (this.samples.length > 2 && e.timeStamp - this.samples[0].t > 100) {
this.samples.shift();
}
this.camera = this.rubber(this.downCamera - dx);
this.requestDraw();
}
private onPointerUp(e: PointerEvent, cancelled: boolean): void {
if (e.pointerId !== this.pointerId) {
return;
}
if (this.stage.hasPointerCapture(e.pointerId)) {
this.stage.releasePointerCapture(e.pointerId);
}
this.pointerId = null;
const wasDragging = this.dragging;
this.dragging = false;
this.stage.classList.remove("is-dragging");
const moved = Math.hypot(e.clientX - this.downX, e.clientY - this.downY);
if (!cancelled && !wasDragging && moved < tapDistance && e.timeStamp - this.downT < tapMs) {
this.onTap(e);
return;
}
if (!wasDragging) {
return;
}
let velocity = 0;
const first = this.samples[0];
const last = this.samples[this.samples.length - 1];
if (first && last && last.t > first.t && e.timeStamp - last.t < 100) {
velocity = (last.x - first.x) / (last.t - first.t);
}
let target = this.nearestStop(this.camera);
if (!cancelled && Math.abs(velocity) > flickSpeed) {
if (velocity < 0) {
const next = this.stops.findIndex((stop) => stop.camera > this.camera + 1);
target = next < 0 ? this.stops.length - 1 : next;
} else {
let previous = 0;
this.stops.forEach((stop, index) => {
if (stop.camera < this.camera - 1) {
previous = index;
}
});
target = previous;
}
}
if (this.pointerType === "mouse") {
this.hover = this.inCaptionZone(e.clientX, e.clientY);
}
this.go(target);
}
private onTap(e: PointerEvent): void {
const stop = this.stops[this.current];
if (stop.photo < 0) {
return;
}
const rect = this.photoRect(stop.photo);
if (e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom) {
this.pinned = !this.pinned;
this.updateCaption();
}
}
private rubber(camera: number): number {
const min = this.stops[0].camera;
const max = this.stops[this.stops.length - 1].camera;
if (camera < min) {
return min - (min - camera) * rubberBand;
}
if (camera > max) {
return max + (camera - max) * rubberBand;
}
return camera;
}
private nearestStop(camera: number): number {
let best = 0;
this.stops.forEach((stop, index) => {
if (Math.abs(stop.camera - camera) < Math.abs(this.stops[best].camera - camera)) {
best = index;
}
});
return best;
}
private go(index: number): void {
const target = Math.max(0, Math.min(this.stops.length - 1, index));
const previous = this.current;
const to = this.stops[target].camera;
if (this.reducedMotion.matches) {
this.crossfade(() => {
this.current = target;
this.camera = to;
});
} else {
const distance = Math.abs(to - this.camera);
if (distance > 0.5) {
this.tween = {
from: this.camera,
to,
start: performance.now(),
duration: 240 + 200 * Math.min(1, distance / this.vw),
};
} else {
this.camera = to;
}
this.current = target;
}
if (target !== previous) {
this.activate(previous);
} else {
this.updateCaption();
}
this.requestDraw();
}
private jump(index: number): void {
const previous = this.current;
this.tween = null;
this.crossfade(() => {
this.current = index;
this.camera = this.stops[index].camera;
});
this.activate(previous);
this.requestDraw();
}
private crossfade(change: () => void): void {
const fade = this.fade;
if (fade.width !== this.canvas.width || fade.height !== this.canvas.height) {
fade.width = this.canvas.width;
fade.height = this.canvas.height;
}
const fg = fade.getContext("2d");
if (fg) {
fg.drawImage(this.canvas, 0, 0);
}
fade.style.transition = "none";
fade.style.opacity = "1";
change();
this.render(performance.now());
requestAnimationFrame(() => {
requestAnimationFrame(() => {
fade.style.transition = "";
fade.style.opacity = "0";
});
});
}
private activate(previousStop: number): void {
const stop = this.stops[this.current];
const before = previousStop >= 0 ? this.stops[previousStop] : null;
if (before && before.photo >= 0 && before.photo !== stop.photo) {
this.loaders[before.photo]?.stop();
}
this.loaders.forEach((loader, index) => {
if (loader && index !== stop.photo && index !== stop.photo + 1) {
loader.stopPrefetch();
}
});
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);
if ((previousStop >= 0 || location.hash !== "") && location.hash !== "#" + (stop.photo + 1)) {
history.replaceState(history.state, "", "#" + (stop.photo + 1));
}
this.startSession();
}
if (stop.photo < 0 || stop.photo === this.manifest.photos.length - 1) {
this.loadNextAlbum();
}
this.updateCaption();
}
private startSession(): void {
const stop = this.stops[this.current];
if (stop.photo < 0) {
return;
}
const index = this.current;
this.loader(stop.photo).start(this.viewAt(stop), this.dpr, () => {
if (this.current === index) {
this.prefetchAround(index);
}
});
}
private prefetchAround(index: number): void {
const stop = this.stops[index];
const next = this.stops[index + 1];
if (!next || next.photo < 0) {
return;
}
if (next.photo === stop.photo) {
const loader = this.loader(stop.photo);
loader.prefetchLevel(this.viewAt(next), loader.finalLevel);
const following = this.stops.find((s) => s.photo === stop.photo + 1);
if (following) {
this.loader(following.photo).prefetchProbe(this.viewAt(following), this.dpr);
}
return;
}
this.loader(next.photo).prefetchProbe(this.viewAt(next), this.dpr);
}
private viewAt(stop: Stop): View {
const layout = this.layouts[stop.photo];
const left = stop.camera - this.vw / 2;
const a = Math.max(left, layout.left);
const b = Math.min(left + this.vw, layout.left + layout.width);
const c = Math.max(0, layout.top);
const d = Math.min(this.vh, layout.top + layout.height);
return {
displayWidth: layout.width,
u0: (a - layout.left) / layout.width,
u1: (b - layout.left) / layout.width,
v0: (c - layout.top) / layout.height,
v1: (d - layout.top) / layout.height,
};
}
private photoRect(index: number): { left: number; right: number; top: number; bottom: number } {
const layout = this.layouts[index];
const x = layout.left - (this.camera - this.vw / 2);
return {
left: Math.max(0, x),
right: Math.min(this.vw, x + layout.width),
top: Math.max(0, layout.top),
bottom: Math.min(this.vh, layout.top + layout.height),
};
}
private inCaptionZone(clientX: number, clientY: number): boolean {
const stop = this.stops[this.current];
if (stop.photo < 0) {
return false;
}
const bounds = this.stage.getBoundingClientRect();
const x = clientX - bounds.left;
const y = clientY - bounds.top;
const layout = this.layouts[stop.photo];
const rect = this.photoRect(stop.photo);
const zoneTop = layout.top + layout.height * (1 - captionZone);
return x >= rect.left && x <= rect.right && y >= zoneTop && y <= rect.bottom;
}
private updateCaption(): void {
const stop = this.stops[this.current];
const visible = stop.photo >= 0 && !this.dragging && (this.pinned || this.hover);
if (visible) {
const rect = this.photoRect(stop.photo);
this.caption.place(rect.left, rect.right - rect.left, this.vh - rect.bottom);
}
this.caption.show(visible);
}
private loadNextAlbum(): void {
if (this.indexRequested || !this.settings.indexUrl) {
return;
}
this.indexRequested = true;
fetch(this.settings.indexUrl, { credentials: "same-origin" })
.then((response) => (response.ok ? (response.json() as Promise<SiteIndex>) : Promise.reject(new Error("index"))))
.then((index) => {
const albums = index.albums;
if (albums.length === 0) {
return;
}
const at = albums.findIndex((album) => album.slug === this.manifest.slug);
const next = albums[(at + 1) % albums.length];
if (!next || next.slug === this.manifest.slug) {
return;
}
this.nextLink.href = "/a/" + encodeURIComponent(next.slug) + "/";
const eyebrow = this.nextLink.querySelector(".next-eyebrow");
const title = this.nextLink.querySelector(".next-title");
if (eyebrow) {
eyebrow.textContent = "Next album" + (next.date ? " · " + next.date : "");
}
if (title) {
title.textContent = next.title;
}
})
.catch(() => {
this.indexRequested = false;
});
}
private requestDraw(): void {
if (this.frame === 0) {
this.frame = requestAnimationFrame((now) => {
this.frame = 0;
this.render(now);
});
}
}
private render(now: number): void {
let again = false;
if (this.tween) {
const t = Math.min(1, (now - this.tween.start) / this.tween.duration);
this.camera = this.tween.from + (this.tween.to - this.tween.from) * ease(t);
if (t >= 1) {
this.tween = null;
this.updateCaption();
} else {
again = true;
}
}
const g = this.g;
const cw = this.canvas.width;
const ch = this.canvas.height;
g.setTransform(1, 0, 0, 1, 0, 0);
g.globalAlpha = 1;
g.fillStyle = "#111114";
g.fillRect(0, 0, cw, ch);
const left = this.camera - this.vw / 2;
const right = left + this.vw;
const dpr = this.dpr;
const near = this.stops[this.current].photo;
const from = Math.max(0, (near < 0 ? this.layouts.length - 1 : near) - 2);
const to = Math.min(this.layouts.length - 1, (near < 0 ? this.layouts.length - 1 : near) + 2);
for (let i = from; i <= to; i++) {
const layout = this.layouts[i];
if (layout.left + layout.width < left || layout.left > right) {
continue;
}
if (this.loader(i).draw({
g,
originX: (layout.left - left) * dpr,
originY: layout.top * dpr,
width: layout.width * dpr,
height: layout.height * dpr,
canvasWidth: cw,
canvasHeight: ch,
displayWidth: layout.width,
dpr,
now,
})) {
again = true;
}
}
this.endCard.style.transform = "translate3d(" + Math.round(this.endLeft - left) + "px,0,0)";
if (this.caption.element.classList.contains("is-visible") && this.tween) {
this.updateCaption();
}
if (again) {
this.requestDraw();
}
}
}
+63
View File
@@ -0,0 +1,63 @@
interface FetchMessage {
type: "fetch";
key: number;
url: string;
}
interface AbortMessage {
type: "abort";
key: number;
}
type Incoming = FetchMessage | AbortMessage;
interface Outgoing {
key: number;
ok: boolean;
bitmap?: ImageBitmap;
bytes: number;
ms: number;
error?: string;
}
interface WorkerScope {
onmessage: ((event: MessageEvent<Incoming>) => void) | null;
postMessage(message: Outgoing, transfer?: Transferable[]): void;
}
const scope = self as unknown as WorkerScope;
const controllers = new Map<number, AbortController>();
scope.onmessage = (event) => {
const message = event.data;
if (message.type === "abort") {
controllers.get(message.key)?.abort();
controllers.delete(message.key);
return;
}
void load(message);
};
async function load(message: FetchMessage): Promise<void> {
const controller = new AbortController();
controllers.set(message.key, controller);
const started = performance.now();
try {
const response = await fetch(message.url, { signal: controller.signal, credentials: "same-origin" });
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
const blob = await response.blob();
const ms = performance.now() - started;
const bitmap = await createImageBitmap(blob);
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) });
} finally {
controllers.delete(message.key);
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"exactOptionalPropertyTypes": false,
"isolatedModules": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["src/**/*.ts"]
}