diff --git a/.gitignore b/.gitignore index 95fa5a0..74f9b21 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ /albums/ /dist/ *.tmp-* +/web/node_modules/ diff --git a/README.md b/README.md index 2323bc6..71b3dce 100644 --- a/README.md +++ b/README.md @@ -41,3 +41,14 @@ state/ site.key pyramids/.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. diff --git a/internal/build/build.go b/internal/build/build.go index 2b71395..cfedd41 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -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() diff --git a/internal/site/assets.go b/internal/site/assets.go new file mode 100644 index 0000000..ef5e552 --- /dev/null +++ b/internal/site/assets.go @@ -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 +} diff --git a/internal/site/site.go b/internal/site/site.go index c5c88a7..b5b3fc9 100644 --- a/internal/site/site.go +++ b/internal/site/site.go @@ -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, diff --git a/internal/site/static/app.css b/internal/site/static/app.css new file mode 100644 index 0000000..bbf7efa --- /dev/null +++ b/internal/site/static/app.css @@ -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}} diff --git a/internal/site/static/app.js b/internal/site/static/app.js new file mode 100644 index 0000000..c525543 --- /dev/null +++ b/internal/site/static/app.js @@ -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;nthis.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{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.running0;){let t=0;for(let i=1;i0){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.iso)}return n.join(" \xB7 ")}function rt(r,t){r.textContent="",t.split(/\r?\n/).forEach((e,i)=>{i>0&&r.appendChild(document.createElement("br"));let n=e.split("*"),s=(n.length-1)%2===0;n.forEach((o,h)=>{let c=h%2===1;if(c&&(s||h!==n.length-1)){let a=document.createElement("em");a.textContent=o,r.appendChild(a)}else r.appendChild(document.createTextNode((c?"*":"")+o))})})}var S=class{constructor(t){this.visible=!1;this.placement="";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),t.appendChild(this.element)}set(t,e,i,n){this.meta.textContent=st(e,i,t,n),this.title.textContent=t.title??"",this.title.hidden=!t.title,rt(this.text,t.caption??""),this.text.hidden=!t.caption,this.alt.textContent=t.alt??""}show(t){t!==this.visible&&(this.visible=t,this.element.classList.toggle("is-visible",t))}place(t,e,i){let n=Math.round(t)+","+Math.round(e)+","+Math.round(i);if(n===this.placement)return;this.placement=n;let s=this.element.style;s.width=Math.round(e)+"px",s.transform="translate3d("+Math.round(t)+"px,"+-Math.round(i)+"px,0)"}};function I(r,t,e){let i=t*e;for(let n=0;n=i)return n;return r.levels.length-1}function A(r,t,e){let i=Math.max(0,t.u0*r.width),n=Math.min(r.width,t.u1*r.width),s=Math.max(0,t.v0*r.height),o=Math.min(r.height,t.v1*r.height);return n<=i||o<=s?null:{x0:Math.min(r.cols-1,Math.floor(i/e)),x1:Math.min(r.cols-1,Math.ceil(n/e)-1),y0:Math.min(r.rows-1,Math.floor(s/e)),y1:Math.min(r.rows-1,Math.ceil(o/e)-1)}}function V(r,t,e,i){let n=r.levels[t],s=A(n,e,i);if(!s)return[];let o=(e.u0+e.u1)/2*n.width,h=(e.v0+e.v1)/2*n.height,c=[];for(let a=s.y0;a<=s.y1;a++)for(let u=s.x0;u<=s.x1;u++){let m=(u*i+Math.min((u+1)*i,n.width))/2,d=(a*i+Math.min((a+1)*i,n.height))/2;c.push({level:t,x:u,y:a,index:a*n.cols+u,distance:(m-o)**2+(d-h)**2})}return c.sort((a,u)=>a.distance-u.distance),c.map(({level:a,x:u,y:m,index:d})=>({level:a,x:u,y:m,index:d}))}function O(r,t,e,i,n,s,o,h,c,a){let u=i*s,m=Math.min((i+1)*s,e.width),d=n*s,l=Math.min((n+1)*s,e.height),p=i>0?u-o:0,g=n>0?d-o:0,y=Math.round(h+u*a),f=Math.round(h+m*a),b=Math.round(c+d*a),M=Math.round(c+l*a);if(f<=y||M<=b)return;let C=Math.max(p,(y-h)/a),w=Math.min(p+t.width,(f-h)/a),v=Math.max(g,(b-c)/a),x=Math.min(g+t.height,(M-c)/a);w<=C||x<=v||r.drawImage(t,C-p,v-g,w-C,x-v,y,b,f-y,M-b)}var F="luphoto.throughput";function z(){try{let r=Number(sessionStorage.getItem(F));return Number.isFinite(r)&&r>0?r:null}catch{return null}}function J(){return z()??1e3}function Z(r){let t=z(),e=t===null?r:t*(1-.5)+r*.5;try{sessionStorage.setItem(F,String(e))}catch{return e}return e}var U=180,G=3,q=4,D=class{constructor(t,e){this.pyramid=t;this.env=e;this.seedImage=null;this.seedPromise=null;this.session=null;this.prefetchController=null;this.finalLevel=-1}tileUrl(t){let e=this.env.tiles;return e.path+this.pyramid.hash+"/"+t+"."+e.format}ensureSeed(){return this.seedPromise||(this.seedPromise=this.decodeSeed().then(()=>this.env.requestDraw(),()=>{})),this.seedPromise}async decodeSeed(){if(!this.pyramid.seed)return;let t=atob(this.pyramid.seed),e=new Uint8Array(t.length);for(let h=0;h(this.env.cache.put(n,s.bitmap),this.env.requestDraw(),s))}uncached(t,e){let i=this.pyramid.levels[t].tiles;return V(this.pyramid,t,e,this.env.tiles.tile_size).filter(n=>!this.env.cache.has(i[n.index]))}uncachedBytes(t,e){let i=this.pyramid.levels[t].bytes,n=0;for(let s of this.uncached(t,e))n+=i[s.index];return n}fetchAll(t,e,i){return Promise.allSettled(t.map(n=>this.fetchTile(n,e,i)))}probeLevel(t,e){return Math.max(0,I(this.pyramid,t.displayWidth,e)-G)}start(t,e,i){this.stopSession();let n=new AbortController;this.session=n,this.run(t,e,n).then(()=>{this.session===n&&(this.session=null),(!n.signal.aborted||n.signal.reason==="deadline")&&i()})}async run(t,e,i){let n=i.signal,s=performance.now(),o=this.env.settings.budgetMs,h=setTimeout(()=>i.abort("deadline"),o);try{if(await this.ensureSeed(),n.aborted)return;let c=I(this.pyramid,t.displayWidth,e),a=Math.max(0,c-G),u=this.uncached(a,t).slice(0,2);if(u.length>0){let g=await this.fetchAll(u,0,n),y=0,f=0;for(let b of g)b.status==="fulfilled"&&(y+=b.value.bytes,f=Math.max(f,b.value.ms));y>0&&f>0&&Z(y/f)}if(n.aborted)return;this.finalLevel=Math.max(this.finalLevel,a);let m=J(),d=o-(performance.now()-s),l=a;for(let g=c;g>a;g--)if(this.uncachedBytes(g,t)/m<=d*.8){l=g;break}let p=[];l-a>=2&&p.push(Math.floor((a+l)/2)),l>a&&p.push(l),this.finalLevel=l;for(let g of p)if(await this.fetchAll(this.uncached(g,t),0,n),n.aborted)return}finally{clearTimeout(h)}}prefetchProbe(t,e){let i=this.resetPrefetch();this.ensureSeed().then(()=>{i.signal.aborted||this.fetchAll(this.uncached(this.probeLevel(t,e),t),1,i.signal)})}prefetchLevel(t,e){if(e<0)return;let i=this.resetPrefetch();this.fetchAll(this.uncached(e,t),1,i.signal)}resetPrefetch(){return this.prefetchController?.abort(),this.prefetchController=new AbortController,this.prefetchController}stopPrefetch(){this.prefetchController?.abort(),this.prefetchController=null}stopSession(){this.session?.abort("superseded"),this.session=null}stop(){this.stopSession(),this.stopPrefetch()}draw(t){let{g:e,originX:i,originY:n,width:s,height:o,canvasWidth:h,canvasHeight:c}=t,a=Math.max(0,i),u=Math.max(0,n),m=Math.min(h,i+s),d=Math.min(c,n+o);if(m<=a||d<=u)return!1;this.seedPromise||this.ensureSeed();let l={displayWidth:t.displayWidth,u0:(a-i)/s,u1:(m-i)/s,v0:(u-n)/o,v1:(d-n)/o},p=this.env.tiles.tile_size,g=this.env.tiles.overlap,y=this.env.cache,f=this.pyramid.levels,b=I(this.pyramid,t.displayWidth,t.dpr),M=-1;for(let w=b;w>=0&&M<0;w--){let v=A(f[w],l,p);if(!v)continue;let x=!0;for(let k=v.y0;k<=v.y1&&x;k++)for(let T=v.x0;T<=v.x1;T++){let E=y.get(f[w].tiles[k*f[w].cols+T]);if(!E||t.now-E.at((o*l+s)*l+n)*l,m=l=>((a*l+c)*l+h)*l,d=l=>(3*o*l+2*s)*l+n;return l=>{if(l<=0)return 0;if(l>=1)return 1;let p=l;for(let f=0;f<8;f++){let b=u(p)-l,M=d(p);if(Math.abs(b)<1e-5)return m(p);if(Math.abs(M)<1e-6)break;p-=b/M}let g=0,y=1;p=l;for(let f=0;f<24;f++){let b=u(p);if(Math.abs(b-l)<1e-5)break;bthis.requestDraw()}),this.loaders[t]=e),e}measure(){let t=this.stage.getBoundingClientRect();this.vw=Math.max(1,t.width),this.vh=Math.max(1,t.height),this.dpr=Math.min(window.devicePixelRatio||1,this.settings.maxDpr);let e=Math.max(1,Math.round(this.vw*this.dpr)),i=Math.max(1,Math.round(this.vh*this.dpr));(this.canvas.width!==e||this.canvas.height!==i)&&(this.canvas.width=e,this.canvas.height=i),this.layouts=[],this.stops=[];let n=0;this.manifest.photos.forEach((s,o)=>{let h=Math.max(1,s.slides||1),c=Math.min(this.vw/(s.width/h),this.vh/s.height),a=s.width*c,u=s.height*c,m=a/h,d=n+N/2+(this.vw-m)/2;this.layouts.push({scale:c,width:a,height:u,section:m,slides:h,start:n,left:d,top:(this.vh-u)/2});for(let l=0;ln.photo===e);return i<0?0:i}bind(){let t=this.stage;t.addEventListener("pointerdown",e=>this.onPointerDown(e)),t.addEventListener("pointermove",e=>this.onPointerMove(e)),t.addEventListener("pointerup",e=>this.onPointerUp(e,!1)),t.addEventListener("pointercancel",e=>this.onPointerUp(e,!0)),t.addEventListener("pointerleave",e=>{e.pointerType==="mouse"&&this.pointerId===null&&(this.hover=!1,this.updateCaption())}),t.addEventListener("dragstart",e=>e.preventDefault()),t.addEventListener("selectstart",e=>e.preventDefault()),this.settings.blockContextMenu&&t.addEventListener("contextmenu",e=>e.preventDefault()),window.addEventListener("keydown",e=>this.onKey(e)),window.addEventListener("hashchange",()=>{let e=this.stopForHash();this.stops[e].photo!==this.stops[this.current].photo&&this.jump(e)}),new ResizeObserver(()=>this.onResize()).observe(t),this.fade.addEventListener("transitionend",()=>{this.fade.style.opacity==="0"&&(this.fade.width=1,this.fade.height=1)})}onResize(){let t=this.vw+"x"+this.vh+"@"+this.dpr;this.measure(),t!==this.vw+"x"+this.vh+"@"+this.dpr&&(this.tween=null,this.camera=this.stops[this.current].camera,this.requestDraw(),clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>this.startSession(),200))}onKey(t){if(t.altKey||t.ctrlKey||t.metaKey)return;let e=t.target;if(!(e&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName)))){switch(t.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}t.preventDefault()}}onPointerDown(t){this.pointerId!==null||t.pointerType==="mouse"&&t.button!==0||t.target.closest("a, button")||(this.pointerId=t.pointerId,this.pointerType=t.pointerType,this.dragging=!1,this.downX=t.clientX,this.downY=t.clientY,this.downT=t.timeStamp,this.tween=null,this.downCamera=this.camera,this.samples=[{t:t.timeStamp,x:t.clientX}],this.stage.setPointerCapture(t.pointerId))}onPointerMove(t){if(this.pointerId===null){t.pointerType==="mouse"&&(this.hover=this.inCaptionZone(t.clientX,t.clientY),this.updateCaption());return}if(t.pointerId!==this.pointerId)return;let e=t.clientX-this.downX,i=t.clientY-this.downY;if(!this.dragging&&Math.hypot(e,i)>=j&&(this.dragging=!0,this.stage.classList.add("is-dragging"),this.updateCaption()),!!this.dragging){for(this.samples.push({t:t.timeStamp,x:t.clientX});this.samples.length>2&&t.timeStamp-this.samples[0].t>100;)this.samples.shift();this.camera=this.rubber(this.downCamera-e),this.requestDraw()}}onPointerUp(t,e){if(t.pointerId!==this.pointerId)return;this.stage.hasPointerCapture(t.pointerId)&&this.stage.releasePointerCapture(t.pointerId),this.pointerId=null;let i=this.dragging;this.dragging=!1,this.stage.classList.remove("is-dragging");let n=Math.hypot(t.clientX-this.downX,t.clientY-this.downY);if(!e&&!i&&no.t&&t.timeStamp-h.t<100&&(s=(h.x-o.x)/(h.t-o.t));let c=this.nearestStop(this.camera);if(!e&&Math.abs(s)>at)if(s<0){let a=this.stops.findIndex(u=>u.camera>this.camera+1);c=a<0?this.stops.length-1:a}else{let a=0;this.stops.forEach((u,m)=>{u.camera=i.left&&t.clientX<=i.right&&t.clientY>=i.top&&t.clientY<=i.bottom&&(this.pinned=!this.pinned,this.updateCaption())}rubber(t){let e=this.stops[0].camera,i=this.stops[this.stops.length-1].camera;return ti?i+(t-i)*tt:t}nearestStop(t){let e=0;return this.stops.forEach((i,n)=>{Math.abs(i.camera-t){this.current=e,this.camera=n});else{let s=Math.abs(n-this.camera);s>.5?this.tween={from:this.camera,to:n,start:performance.now(),duration:240+200*Math.min(1,s/this.vw)}:this.camera=n,this.current=e}e!==i?this.activate(i):this.updateCaption(),this.requestDraw()}jump(t){let e=this.current;this.tween=null,this.crossfade(()=>{this.current=t,this.camera=this.stops[t].camera}),this.activate(e),this.requestDraw()}crossfade(t){let e=this.fade;(e.width!==this.canvas.width||e.height!==this.canvas.height)&&(e.width=this.canvas.width,e.height=this.canvas.height);let i=e.getContext("2d");i&&i.drawImage(this.canvas,0,0),e.style.transition="none",e.style.opacity="1",t(),this.render(performance.now()),requestAnimationFrame(()=>{requestAnimationFrame(()=>{e.style.transition="",e.style.opacity="0"})})}activate(t){let e=this.stops[this.current],i=t>=0?this.stops[t]:null;if(i&&i.photo>=0&&i.photo!==e.photo&&this.loaders[i.photo]?.stop(),this.loaders.forEach((n,s)=>{n&&s!==e.photo&&s!==e.photo+1&&n.stopPrefetch()}),e.photo>=0){let n=this.manifest.photos[e.photo];this.caption.set(n,e.photo,this.manifest.photos.length,this.manifest.show_exif),(t>=0||location.hash!=="")&&location.hash!=="#"+(e.photo+1)&&history.replaceState(history.state,"","#"+(e.photo+1)),this.startSession()}(e.photo<0||e.photo===this.manifest.photos.length-1)&&this.loadNextAlbum(),this.updateCaption()}startSession(){let t=this.stops[this.current];if(t.photo<0)return;let e=this.current;this.loader(t.photo).start(this.viewAt(t),this.dpr,()=>{this.current===e&&this.prefetchAround(e)})}prefetchAround(t){let e=this.stops[t],i=this.stops[t+1];if(!(!i||i.photo<0)){if(i.photo===e.photo){let n=this.loader(e.photo);n.prefetchLevel(this.viewAt(i),n.finalLevel);let s=this.stops.find(o=>o.photo===e.photo+1);s&&this.loader(s.photo).prefetchProbe(this.viewAt(s),this.dpr);return}this.loader(i.photo).prefetchProbe(this.viewAt(i),this.dpr)}}viewAt(t){let e=this.layouts[t.photo],i=t.camera-this.vw/2,n=Math.max(i,e.left),s=Math.min(i+this.vw,e.left+e.width),o=Math.max(0,e.top),h=Math.min(this.vh,e.top+e.height);return{displayWidth:e.width,u0:(n-e.left)/e.width,u1:(s-e.left)/e.width,v0:(o-e.top)/e.height,v1:(h-e.top)/e.height}}photoRect(t){let e=this.layouts[t],i=e.left-(this.camera-this.vw/2);return{left:Math.max(0,i),right:Math.min(this.vw,i+e.width),top:Math.max(0,e.top),bottom:Math.min(this.vh,e.top+e.height)}}inCaptionZone(t,e){let i=this.stops[this.current];if(i.photo<0)return!1;let n=this.stage.getBoundingClientRect(),s=t-n.left,o=e-n.top,h=this.layouts[i.photo],c=this.photoRect(i.photo),a=h.top+h.height*(1-ht);return s>=c.left&&s<=c.right&&o>=a&&o<=c.bottom}updateCaption(){let t=this.stops[this.current],e=t.photo>=0&&!this.dragging&&(this.pinned||this.hover);if(e){let i=this.photoRect(t.photo);this.caption.place(i.left,i.right-i.left,this.vh-i.bottom)}this.caption.show(e)}loadNextAlbum(){this.indexRequested||!this.settings.indexUrl||(this.indexRequested=!0,fetch(this.settings.indexUrl,{credentials:"same-origin"}).then(t=>t.ok?t.json():Promise.reject(new Error("index"))).then(t=>{let e=t.albums;if(e.length===0)return;let i=e.findIndex(h=>h.slug===this.manifest.slug),n=e[(i+1)%e.length];if(!n||n.slug===this.manifest.slug)return;this.nextLink.href="/a/"+encodeURIComponent(n.slug)+"/";let s=this.nextLink.querySelector(".next-eyebrow"),o=this.nextLink.querySelector(".next-title");s&&(s.textContent="Next album"+(n.date?" \xB7 "+n.date:"")),o&&(o.textContent=n.title)}).catch(()=>{this.indexRequested=!1}))}requestDraw(){this.frame===0&&(this.frame=requestAnimationFrame(t=>{this.frame=0,this.render(t)}))}render(t){let e=!1;if(this.tween){let d=Math.min(1,(t-this.tween.start)/this.tween.duration);this.camera=this.tween.from+(this.tween.to-this.tween.from)*ct(d),d>=1?(this.tween=null,this.updateCaption()):e=!0}let i=this.g,n=this.canvas.width,s=this.canvas.height;i.setTransform(1,0,0,1,0,0),i.globalAlpha=1,i.fillStyle="#111114",i.fillRect(0,0,n,s);let o=this.camera-this.vw/2,h=o+this.vw,c=this.dpr,a=this.stops[this.current].photo,u=Math.max(0,(a<0?this.layouts.length-1:a)-2),m=Math.min(this.layouts.length-1,(a<0?this.layouts.length-1:a)+2);for(let d=u;d<=m;d++){let l=this.layouts[d];l.left+l.widthh||this.loader(d).draw({g:i,originX:(l.left-o)*c,originY:l.top*c,width:l.width*c,height:l.height*c,canvasWidth:n,canvasHeight:s,displayWidth:l.width,dpr:c,now:t})&&(e=!0)}this.endCard.style.transform="translate3d("+Math.round(this.endLeft-o)+"px,0,0)",this.caption.element.classList.contains("is-visible")&&this.tween&&this.updateCaption(),e&&this.requestDraw()}};async function ut(r){let t=X(document.body),e=await fetch(t.manifestUrl,{credentials:"same-origin"});if(!e.ok)throw new Error("manifest "+e.status);let i=await e.json();if(i.photos.length===0)return;let n=new R(t.concurrency,t.workerUrl),s=new L(_());document.documentElement.classList.add("has-viewer"),new W(r,i,t,{scheduler:n,cache:s,settings:t,tiles:i.tiles})}function et(){let r=document.getElementById("stage");document.body.dataset.page==="album"&&r&&ut(r).catch(t=>{r.dataset.error=String(t),document.documentElement.classList.remove("has-viewer")})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",et,{once:!0}):et();})(); diff --git a/internal/site/static/worker.js b/internal/site/static/worker.js new file mode 100644 index 0000000..0f13b66 --- /dev/null +++ b/internal/site/static/worker.js @@ -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)}}})(); diff --git a/internal/site/templates/album.html b/internal/site/templates/album.html index 6c2d370..1e87ee3 100644 --- a/internal/site/templates/album.html +++ b/internal/site/templates/album.html @@ -2,19 +2,22 @@ - + + {{.Title}} · Lucio + + - -
-

{{.Title}}

-{{- if .Subtitle}} -

{{.Subtitle}}

-{{- end}} -

{{.Photos}} photos{{if .Date}} · {{end}}

-

All albums

+ +
+

{{.Title}}{{if .Subtitle}} · {{.Subtitle}}{{end}}

+
+

{{.Photos}} photos{{if .Date}} · {{end}}

+ +

All albums

+
diff --git a/internal/site/templates/index.html b/internal/site/templates/index.html index 31123ed..47fba2e 100644 --- a/internal/site/templates/index.html +++ b/internal/site/templates/index.html @@ -2,13 +2,15 @@ - + + Photos · Lucio + - -
+ +

Photos · Lucio

    {{- range .Albums}} diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..996b7c9 --- /dev/null +++ b/web/package-lock.json @@ -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" + } + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..9b12bcb --- /dev/null +++ b/web/package.json @@ -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" + } +} diff --git a/web/src/app.css b/web/src/app.css new file mode 100644 index 0000000..9f49ef8 --- /dev/null +++ b/web/src/app.css @@ -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; + } +} diff --git a/web/src/app.ts b/web/src/app.ts new file mode 100644 index 0000000..84d1d37 --- /dev/null +++ b/web/src/app.ts @@ -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 { + 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(); +} diff --git a/web/src/cache.ts b/web/src/cache.ts new file mode 100644 index 0000000..d8d9ab3 --- /dev/null +++ b/web/src/cache.ts @@ -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(); + 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(); + } + } + } +} diff --git a/web/src/caption.ts b/web/src/caption.ts new file mode 100644 index 0000000..5dfc04c --- /dev/null +++ b/web/src/caption.ts @@ -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)"; + } +} diff --git a/web/src/geometry.ts b/web/src/geometry.ts new file mode 100644 index 0000000..1d39c7a --- /dev/null +++ b/web/src/geometry.ts @@ -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 = []; + 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); +} diff --git a/web/src/loader.ts b/web/src/loader.ts new file mode 100644 index 0000000..3fc3d78 --- /dev/null +++ b/web/src/loader.ts @@ -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 | 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 { + if (!this.seedPromise) { + this.seedPromise = this.decodeSeed().then( + () => this.env.requestDraw(), + () => undefined, + ); + } + return this.seedPromise; + } + + private async decodeSeed(): Promise { + 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 { + 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[]> { + 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 { + 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; + } +} diff --git a/web/src/scheduler.ts b/web/src/scheduler.ts new file mode 100644 index 0000000..8d95711 --- /dev/null +++ b/web/src/scheduler.ts @@ -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; + 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(); + private readonly byKey = new Map(); + 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) => 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 { + if (signal.aborted) { + return Promise.reject(new AbortError()); + } + return new Promise((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 { + 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(); + } +} diff --git a/web/src/throughput.ts b/web/src/throughput.ts new file mode 100644 index 0000000..a327df8 --- /dev/null +++ b/web/src/throughput.ts @@ -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; +} diff --git a/web/src/types.ts b/web/src/types.ts new file mode 100644 index 0000000..0798fc6 --- /dev/null +++ b/web/src/types.ts @@ -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", + }; +} diff --git a/web/src/viewer.ts b/web/src/viewer.ts new file mode 100644 index 0000000..152d3e7 --- /dev/null +++ b/web/src/viewer.ts @@ -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; + 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, + ) { + 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) : 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(); + } + } +} diff --git a/web/src/worker.ts b/web/src/worker.ts new file mode 100644 index 0000000..93bbd16 --- /dev/null +++ b/web/src/worker.ts @@ -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) => void) | null; + postMessage(message: Outgoing, transfer?: Transferable[]): void; +} + +const scope = self as unknown as WorkerScope; +const controllers = new Map(); + +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 { + 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); + } +} diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..0ad425e --- /dev/null +++ b/web/tsconfig.json @@ -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"] +}