Refactor to TypeScript ES modules and add metadata sidebar

This commit is contained in:
Alan Grainger
2026-06-04 07:40:52 +12:00
parent d86c8721cc
commit e43b57d644
49 changed files with 5909 additions and 2409 deletions
+53
View File
@@ -0,0 +1,53 @@
// Gallery client entry point. Reads the JSON init block from the page,
// populates shared state, sets up the toolbar + lightbox, attaches the
// resize / scroll observers, and handles deep-link opening.
//
// Layout is pre-computed for all items based on container width. Only tiles
// within viewport ± 1 viewport-height buffer exist in the DOM at any moment.
// PhotoSwipe runs with a full dataSource array so the lightbox navigates
// across all items regardless of which tiles are currently rendered.
import type { InitParams } from '../shared/types.js'
import { state } from './state.js'
import { setupToolbar } from './selection.js'
import { initLightbox, openLightbox } from './lightbox.js'
import { computeLayoutAndRender, onScroll } from './virtualization.js'
function readInitParams (): InitParams {
const el = document.getElementById('ipp-init')
if (!el) return {}
try { return JSON.parse(el.textContent || '{}') } catch (e) { return {} }
}
function init () {
const params = readInitParams()
state.items = params.items || []
state.lightboxConfig = params.lightboxConfig || {}
if (params.metadataConfig) state.metadataConfig = params.metadataConfig
state.groupByDate = !!params.groupByDate
state.container = document.getElementById('gallery')
if (!state.container) return
setupToolbar()
initLightbox()
let resizeFrame: number | undefined
const resizeObserver = new ResizeObserver(() => {
if (resizeFrame) cancelAnimationFrame(resizeFrame)
resizeFrame = requestAnimationFrame(computeLayoutAndRender)
})
resizeObserver.observe(state.container)
window.addEventListener('scroll', onScroll, { passive: true })
// Deep-link: prefer #asset-id in the URL hash, fall back to ?openItem
const hash = window.location.hash.slice(1)
if (hash) {
const idx = state.items.findIndex(it => it.id === hash)
if (idx >= 0) openLightbox(idx)
} else if (params.openItem && params.openItem > 0 && params.openItem <= state.items.length) {
openLightbox(params.openItem - 1)
}
}
init()
+172
View File
@@ -0,0 +1,172 @@
// Justified-rows + square-grid layout, with optional month grouping. Pure
// geometry: takes a container width, returns positions for every tile and
// every header. Called by virtualization on first render and on resize.
import {
state,
TARGET_ROW_HEIGHT,
GAP,
MOBILE_BREAKPOINT,
MOBILE_COLS,
HEADER_HEIGHT,
GROUP_GAP,
type LayoutEntry,
type HeaderEntry,
type GroupSpec
} from './state.js'
export interface LayoutResult {
layout: LayoutEntry[]
headers: HeaderEntry[]
totalHeight: number
}
/**
* Compute tile positions, group-header positions, and total scroll height
* for the gallery at the given container width.
*
* Reads `state.items` and `state.groupByDate`. Output is pure data - the
* caller (virtualization) is responsible for actually placing DOM nodes
* according to the returned positions.
*
* Switches between a mobile square grid (under MOBILE_BREAKPOINT) and the
* justified-rows algorithm. When grouping by date is enabled, items are
* bucketed by YYYY-MM and a header is reserved before each group.
*/
export function computeLayout (containerW: number): LayoutResult {
const tileLayout: LayoutEntry[] = new Array(state.items.length)
const newHeaders: HeaderEntry[] = []
const groups: GroupSpec[] = state.groupByDate
? groupItemsByMonth()
: [{ label: null, indices: itemIndices() }]
const isMobile = containerW < MOBILE_BREAKPOINT
let y = 0
for (let g = 0; g < groups.length; g++) {
const group = groups[g]
if (group.label) {
newHeaders.push({ label: group.label, top: y, height: HEADER_HEIGHT })
y += HEADER_HEIGHT
}
y = isMobile
? layoutSquareGroup(containerW, group.indices, y, tileLayout)
: layoutJustifiedGroup(containerW, group.indices, y, tileLayout)
if (g < groups.length - 1) y += GROUP_GAP
}
return {
layout: tileLayout,
headers: newHeaders,
totalHeight: Math.max(0, y)
}
}
function itemIndices (): number[] {
const out = new Array(state.items.length)
for (let i = 0; i < state.items.length; i++) out[i] = i
return out
}
function groupItemsByMonth (): GroupSpec[] {
// Preserve item order (already sorted desc by render.ts when grouping is on)
const map = new Map<string, GroupSpec>()
for (let i = 0; i < state.items.length; i++) {
const key = (state.items[i].fileCreatedAt || '').slice(0, 7) || 'undated'
let g = map.get(key)
if (!g) {
g = { label: monthLabel(key), indices: [] }
map.set(key, g)
}
g.indices.push(i)
}
return Array.from(map.values())
}
function monthLabel (key: string): string {
if (key === 'undated') return 'Undated'
const parts = key.split('-')
const y = Number(parts[0])
const m = Number(parts[1])
if (!y || !m) return key
// Intl.DateTimeFormat picks up the browser's locale; UTC timeZone keeps
// the displayed month consistent with the UTC YYYY-MM bucket key.
return new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'long',
timeZone: 'UTC'
}).format(new Date(Date.UTC(y, m - 1, 1)))
}
/**
* Lay out one group as a fixed-column square grid (mobile path).
* Writes positions into `tileLayout` in place.
*
* @returns The y position past the last tile in this group (no trailing gap).
*/
function layoutSquareGroup (containerW: number, indices: number[], startY: number, tileLayout: LayoutEntry[]): number {
const tileSize = Math.floor((containerW - (MOBILE_COLS - 1) * GAP) / MOBILE_COLS)
let col = 0
let x = 0
let y = startY
for (const idx of indices) {
tileLayout[idx] = { index: idx, left: x, top: y, width: tileSize, height: tileSize }
col++
if (col === MOBILE_COLS) {
col = 0
x = 0
y += tileSize + GAP
} else {
x += tileSize + GAP
}
}
// If the last row was partial, advance y to past it
if (col > 0) y += tileSize
// Otherwise back off the trailing inter-row gap
else if (y > startY) y -= GAP
return y
}
/**
* Lay out one group as justified rows (desktop path): tiles in each row are
* scaled so their combined width fills the container exactly. The final row
* keeps the target height instead of stretching to fill, which avoids the
* "huge last row" look when there are only one or two trailing tiles.
*
* @returns The y position past the last tile in this group (no trailing gap).
*/
function layoutJustifiedGroup (containerW: number, indices: number[], startY: number, tileLayout: LayoutEntry[]): number {
let rowItems: Array<{ idx: number, aspect: number }> = []
let aspectSum = 0
let y = startY
const applyRow = (rowItems: Array<{ idx: number, aspect: number }>, height: number, isLastRow: boolean) => {
const intHeight = Math.floor(height)
let x = 0
rowItems.forEach(({ idx, aspect }, i) => {
const isFinalInRow = i === rowItems.length - 1
const w = (!isLastRow && isFinalInRow)
? containerW - x
: Math.floor(aspect * height)
tileLayout[idx] = { index: idx, left: x, top: y, width: w, height: intHeight }
x += w + GAP
})
y += intHeight + GAP
}
for (const idx of indices) {
const item = state.items[idx]
const w = item.width || 1
const h = item.height || 1
const aspect = w / h
rowItems.push({ idx, aspect })
aspectSum += aspect
const projectedH = (containerW - (rowItems.length - 1) * GAP) / aspectSum
if (projectedH <= TARGET_ROW_HEIGHT) {
applyRow(rowItems, projectedH, false)
rowItems = []
aspectSum = 0
}
}
if (rowItems.length) applyRow(rowItems, TARGET_ROW_HEIGHT, true)
// y advanced past the last row's trailing gap; back off
return y > startY ? y - GAP : y
}
+157
View File
@@ -0,0 +1,157 @@
// PhotoSwipe UI element registrations: back button, caption (description),
// download button, fullscreen toggle. Each is gated by config or feature
// detection. The info sidebar lives in `sidebar.ts`.
import { state, ICON_BACK, ICON_DOWNLOAD, ICON_FULLSCREEN, ICON_FULLSCREEN_EXIT } from './state.js'
// PhotoSwipe types are not bundled with the project. These two interfaces
// describe just enough of the surface we touch to keep the rest of the file
// type-checked.
interface PswpUiElementConfig {
name: string
order: number
isButton: boolean
tagName?: string
ariaLabel?: string
appendTo?: string
html?: string
// eslint-disable-next-line no-use-before-define
onInit?: (el: HTMLElement, pswp: PswpInstance) => void
}
interface PswpInstance {
currIndex: number
element: HTMLElement
ui: {
registerElement: (config: PswpUiElementConfig) => void
}
on: (event: string, cb: () => void) => void
close: () => void
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type LightboxInstance = any
/**
* Register the top-left back button that closes the lightbox and returns
* to the gallery grid. Matches Immich's native asset-viewer affordance
* (back arrow, no top-right X). Order 1 puts it at the leftmost slot of
* the toolbar. The default PhotoSwipe close button is hidden via CSS in
* `photoswipe-overrides.css`.
*/
export function registerBackButton (lightbox: LightboxInstance) {
lightbox.on('uiRegister', () => {
lightbox.pswp.ui.registerElement({
name: 'back-button',
order: 1,
isButton: true,
ariaLabel: 'Back to gallery',
html: ICON_BACK,
onInit: (el: HTMLElement, pswp: PswpInstance) => {
el.addEventListener('click', () => pswp.close())
}
})
})
}
/**
* Register the description-caption UI element. Content is plain text from
* the server; the client uses `textContent` so any HTML-significant
* characters in the description render as literal text (not markup).
*
* Caller is responsible for only invoking this when
* `metadataConfig.descriptionInCaption` is true.
*/
export function registerCaption (lightbox: LightboxInstance) {
lightbox.on('uiRegister', () => {
lightbox.pswp.ui.registerElement({
name: 'caption',
order: 9,
isButton: false,
appendTo: 'root',
onInit: (el: HTMLElement, pswp: PswpInstance) => {
el.classList.add('pswp__caption')
const render = () => {
const item = state.items[pswp.currIndex]
const text = (item && item.description) || ''
el.textContent = text
el.hidden = !text
}
render()
pswp.on('change', render)
}
})
})
}
/**
* Register the download button. Only called when the share allows downloads
* AND the config enables the lightbox button.
*/
export function registerDownloadButton (lightbox: LightboxInstance) {
lightbox.on('uiRegister', () => {
lightbox.pswp.ui.registerElement({
name: 'download-button',
order: 8,
isButton: true,
tagName: 'a',
ariaLabel: 'Download',
html: ICON_DOWNLOAD,
onInit: (el: HTMLElement, pswp: PswpInstance) => {
const link = el as HTMLAnchorElement
link.setAttribute('target', '_blank')
link.setAttribute('rel', 'noopener')
const update = () => {
const item = state.items[pswp.currIndex]
if (item && item.downloadUrl) {
link.href = item.downloadUrl
link.setAttribute('download', item.downloadFilename || '')
} else {
link.removeAttribute('href')
}
}
update()
pswp.on('change', update)
}
})
})
}
/**
* Register the fullscreen toggle. Skipped on browsers without Fullscreen API
* support for arbitrary elements (notably iOS Safari on iPhone).
*/
export function registerFullscreenButton (lightbox: LightboxInstance) {
if (!document.fullscreenEnabled) return
lightbox.on('uiRegister', () => {
lightbox.pswp.ui.registerElement({
name: 'fullscreen-button',
order: 9,
isButton: true,
html: ICON_FULLSCREEN,
onInit: (el: HTMLElement, pswp: PswpInstance) => {
const update = () => {
const active = document.fullscreenElement === pswp.element
el.innerHTML = active ? ICON_FULLSCREEN_EXIT : ICON_FULLSCREEN
el.setAttribute('aria-label', active ? 'Exit fullscreen' : 'Fullscreen')
el.setAttribute('title', active ? 'Exit fullscreen' : 'Fullscreen')
}
update()
el.addEventListener('click', () => {
if (document.fullscreenElement) {
document.exitFullscreen().catch(() => {})
} else {
pswp.element.requestFullscreen().catch(() => {})
}
})
document.addEventListener('fullscreenchange', update)
pswp.on('destroy', () => {
document.removeEventListener('fullscreenchange', update)
if (document.fullscreenElement === pswp.element) {
document.exitFullscreen().catch(() => {})
}
})
}
})
})
}
+203
View File
@@ -0,0 +1,203 @@
// PhotoSwipe instantiation, data-source construction, history / hash
// navigation. Individual UI elements (caption, download, fullscreen,
// sidebar) live in lightbox-ui.ts and sidebar.ts.
// Runtime URL resolved by Express static, not a TS-resolvable module path.
// @ts-expect-error - browser-only ESM URL
import PhotoSwipeLightbox from '/share/static/photoswipe/photoswipe-lightbox.esm.js' // eslint-disable-line import/no-absolute-path
import { state, SIDEBAR_WIDTH, MOBILE_BREAKPOINT } from './state.js'
import type { GalleryItem } from '../shared/types.js'
import {
registerBackButton,
registerCaption,
registerDownloadButton,
registerFullscreenButton
} from './lightbox-ui.js'
import { registerSidebar } from './sidebar.js'
/**
* Replace the current history entry with the same URL minus any hash.
* No-op when there is no hash. Used by the lightbox-close paths so the
* browser bar shows a clean gallery URL after the lightbox dismisses,
* even when the entry we land on came from a `#assetId` deep link.
*/
function clearHashIfPresent () {
if (window.location.hash) {
history.replaceState(null, '', window.location.pathname + window.location.search)
}
}
function parseVideoData (item: GalleryItem): { src: string, type: string } {
try {
const data = JSON.parse(item.videoData || '{}')
const source = (data.source && data.source[0]) || {}
return { src: source.src || '', type: source.type || 'video/mp4' }
} catch (e) {
return { src: '', type: 'video/mp4' }
}
}
function escapeAttr (s: string): string {
return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
/**
* Translate `state.items` into PhotoSwipe's dataSource array. Images use
* `src`/`width`/`height`; videos use the `html` slide with a `<video>`
* element so PhotoSwipe streams from the server's `/share/video/...` URL.
*/
function buildDataSource () {
return state.items.map(item => {
if (item.type === 'VIDEO') {
const v = parseVideoData(item)
return {
html:
'<div class="pswp__video-wrap">' +
'<video controls playsinline poster="' + escapeAttr(item.thumbnailUrl) + '">' +
'<source src="' + escapeAttr(v.src) + '" type="' + escapeAttr(v.type) + '">' +
'</video>' +
'</div>'
}
}
return {
src: item.previewUrl,
width: item.width || 1600,
height: item.height || 1200,
msrc: item.thumbnailUrl,
alt: item.description || ''
}
})
}
/**
* Construct the PhotoSwipe lightbox, register its UI elements, set up hash
* navigation, and call `init()`. Reads config from `state.lightboxConfig`
* and writes the instance back to `state.lightbox`.
*
* Browser history is integrated so the mobile back gesture closes the
* lightbox, and the URL hash tracks the current slide for shareable
* deep-links.
*/
export function initLightbox () {
const { options = {} } = state.lightboxConfig
state.lightbox = new PhotoSwipeLightbox({
bgOpacity: 1,
showHideAnimationType: 'fade',
closeOnVerticalDrag: true,
arrowKeys: true,
loop: false,
// paddingFn lets the sidebar shrink the slide viewport when open. On a
// narrow viewport the sidebar overlays instead, so we leave padding
// alone in that case.
paddingFn: () => ({
top: 56,
bottom: 56,
left: 16,
right: state.sidebarOpen && window.innerWidth >= MOBILE_BREAKPOINT
? SIDEBAR_WIDTH + 16
: 16
}),
...options,
dataSource: buildDataSource(),
// @ts-expect-error - runtime URL resolved by Express static
pswpModule: () => import('/share/static/photoswipe/photoswipe.esm.js') // eslint-disable-line import/no-absolute-path
})
registerBackButton(state.lightbox)
if (state.lightboxConfig.showDownload) registerDownloadButton(state.lightbox)
registerFullscreenButton(state.lightbox)
if (state.metadataConfig.descriptionInCaption) registerCaption(state.lightbox)
if (state.metadataConfig.sidebarHasContent) registerSidebar(state.lightbox)
// Hash navigation + back-button handling: push a history entry on open so
// the mobile back gesture closes the lightbox; sync the hash with the
// current slide as the user pages through.
state.lightbox.on('uiRegister', () => {
const pswp = state.lightbox.pswp
const item = state.items[pswp.currIndex]
if (item) {
history.pushState({ pswp: true }, '', '#' + item.id)
state.lightboxPushedHistory = true
}
pswp.on('change', () => {
const it = state.items[pswp.currIndex]
if (it) history.replaceState({ pswp: state.lightboxPushedHistory }, '', '#' + it.id)
})
pswp.on('close', () => {
scrollToCurrentSlide(pswp.currIndex)
const wasFromHistory = state.closingFromHistory
state.closingFromHistory = false
if (wasFromHistory) {
// popstate already moved us back to the prior entry. If that entry
// still has a hash (e.g. the user arrived via a #assetId deep link
// and we pushed on top of it), strip it now.
state.lightboxPushedHistory = false
clearHashIfPresent()
} else if (state.lightboxPushedHistory) {
// UI close (button / Esc / swipe-down): consume our pushed entry.
// The popstate handler below clears any leftover hash on the entry
// we land on.
state.closingFromHistory = true
state.lightboxPushedHistory = false
history.back()
} else {
history.replaceState(null, '', window.location.pathname + window.location.search)
}
})
})
window.addEventListener('popstate', () => {
if (state.closingFromHistory) {
// Our own history.back() during a UI-driven close. The current entry
// (which we just navigated to) may still carry a hash from a deep
// link; strip it for a clean exit URL.
state.closingFromHistory = false
clearHashIfPresent()
return
}
if (state.lightbox && state.lightbox.pswp && state.lightboxPushedHistory) {
state.closingFromHistory = true
state.lightbox.pswp.close()
}
})
// Optional control hiding (defaults match Immich's behavior)
const docEl = document.documentElement
if (!state.lightboxConfig.showArrows) docEl.classList.add('pswp-no-arrows')
if (!state.lightboxConfig.mobileArrows) docEl.classList.add('pswp-no-mobile-arrows')
state.lightbox.init()
}
/**
* Open the lightbox to the item at `index` (0-based into `state.items`).
* No-op if the lightbox hasn't been initialised yet.
*/
export function openLightbox (index: number) {
if (state.lightbox) state.lightbox.loadAndOpen(index)
}
/**
* Scroll the page so the tile for the given item is comfortably in view.
* Called from the lightbox close handler - if the user navigated prev/next
* inside the lightbox, or arrived via a #asset-id deep link, the tile they
* end on may be far from the original scroll position. We only scroll when
* the tile is genuinely off-screen, so closing on a still-visible tile
* doesn't jiggle the page.
*/
function scrollToCurrentSlide (index: number) {
if (!state.container || index == null || !state.layout[index]) return
const entry = state.layout[index]
const containerTop = state.container.getBoundingClientRect().top + window.scrollY
const tileTop = containerTop + entry.top
const tileBottom = tileTop + entry.height
const viewportTop = window.scrollY
const viewportBottom = viewportTop + window.innerHeight
// Already mostly visible - leave the scroll alone
if (tileTop >= viewportTop && tileBottom <= viewportBottom) return
// Center the tile vertically in the viewport
const targetScroll = tileTop - (window.innerHeight - entry.height) / 2
window.scrollTo({ top: Math.max(0, targetScroll), behavior: 'instant' })
}
+129
View File
@@ -0,0 +1,129 @@
// Selection mode (long-press to enter, checkmarks on tiles, toolbar at the
// bottom). Selected IDs are POSTed to /share/:key/download for a server-side
// zip, or downloaded directly for a single selection.
import { state } from './state.js'
/**
* Activate selection mode. Tiles show their checkmark control, the bottom
* toolbar reveals itself, and tap on a tile toggles selection instead of
* opening the lightbox. No-op if already active.
*/
export function enterSelectMode () {
if (state.selectMode) return
state.selectMode = true
if (state.container) state.container.classList.add('select-mode')
if (state.toolbarEl) state.toolbarEl.hidden = false
}
/**
* Leave selection mode and clear the selection. Removes the visual marker
* from every tile currently in the DOM. No-op if not in select mode.
*/
export function exitSelectMode () {
if (!state.selectMode) return
state.selectMode = false
// Clear DOM markers on the tiles currently in the DOM
for (const a of state.renderedTiles.values()) a.classList.remove('selected')
state.selected.clear()
if (state.container) state.container.classList.remove('select-mode')
if (state.toolbarEl) state.toolbarEl.hidden = true
updateSelectionUI()
}
/**
* Add or remove an item from the selection set. Updates the matching tile's
* visual marker if that tile is currently rendered, and exits selection
* mode automatically when the last item is deselected.
*/
export function toggleSelection (id: string) {
if (state.selected.has(id)) state.selected.delete(id)
else state.selected.add(id)
const idx = state.items.findIndex(it => it.id === id)
const tile = idx >= 0 ? state.renderedTiles.get(idx) : null
if (tile) tile.classList.toggle('selected', state.selected.has(id))
// Auto-exit if user deselected the last item
if (state.selected.size === 0 && state.selectMode) exitSelectMode()
else updateSelectionUI()
}
function updateSelectionUI () {
if (state.countEl) {
state.countEl.textContent = state.selected.size + ' selected'
}
if (state.downloadBtn) state.downloadBtn.disabled = state.selected.size === 0
if (state.selectAllBtn) {
state.selectAllBtn.textContent =
state.selected.size === state.items.length ? 'Deselect all' : 'Select all'
}
}
function selectAllOrNone () {
if (state.selected.size === state.items.length) {
// Deselect all but keep select mode active
for (const a of state.renderedTiles.values()) a.classList.remove('selected')
state.selected.clear()
updateSelectionUI()
} else {
if (!state.selectMode) enterSelectMode()
for (const item of state.items) state.selected.add(item.id)
for (const a of state.renderedTiles.values()) a.classList.add('selected')
updateSelectionUI()
}
}
/**
* Send the current selection to the download endpoint. A single selection
* downloads the asset directly (no one-entry zip); two or more selections
* POST to /share/:key/download and the server streams a zip back.
*/
function downloadSelected () {
if (state.selected.size === 0) return
// Single selection: download the file directly so the user gets the image
// (or video) instead of a one-entry zip.
if (state.selected.size === 1) {
const id = state.selected.values().next().value
const item = state.items.find(it => it.id === id)
if (item && item.downloadUrl) {
const a = document.createElement('a')
a.href = item.downloadUrl
a.download = item.downloadFilename || ''
document.body.appendChild(a)
a.click()
a.remove()
return
}
}
// Form POST so the browser handles streaming the zip directly to disk.
const form = document.createElement('form')
form.method = 'POST'
form.action = window.location.pathname + '/download'
const input = document.createElement('input')
input.type = 'hidden'
input.name = 'assets'
input.value = JSON.stringify(Array.from(state.selected))
form.appendChild(input)
document.body.appendChild(form)
form.submit()
form.remove()
}
/**
* Look up the selection toolbar in the DOM and wire its buttons (cancel,
* select-all, download). Called once at init time. If the toolbar element
* isn't on the page (the share doesn't allow downloads), this short-circuits
* and selection-related code paths never activate.
*/
export function setupToolbar () {
state.toolbarEl = document.getElementById('select-toolbar')
// No toolbar means downloads aren't allowed for this share; nothing to wire
if (!state.toolbarEl) return
state.countEl = document.getElementById('select-count')
state.selectAllBtn = document.getElementById('select-all') as HTMLButtonElement | null
state.cancelBtn = document.getElementById('select-cancel') as HTMLButtonElement | null
state.downloadBtn = document.getElementById('select-download') as HTMLButtonElement | null
if (state.cancelBtn) state.cancelBtn.addEventListener('click', exitSelectMode)
if (state.selectAllBtn) state.selectAllBtn.addEventListener('click', selectAllOrNone)
if (state.downloadBtn) state.downloadBtn.addEventListener('click', downloadSelected)
updateSelectionUI()
}
+372
View File
@@ -0,0 +1,372 @@
// Info sidebar that surfaces description + EXIF + location metadata for the
// current lightbox slide. Modelled on Immich's native DetailPanel:
// docked to the right (image shrinks to fit), slide-in transition, close
// button top-left, sections only render when their data is present. Toggled
// by the toolbar info button or the `i` key, persisted via localStorage.
import { state, ICON_INFO, ICON_CLOSE, ICON_IMAGE, ICON_CAMERA, ICON_IRIS, ICON_MAP, SIDEBAR_STORAGE_KEY } from './state.js'
import type { GalleryItem, GalleryExif } from '../shared/types.js'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type LightboxInstance = any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PswpInstance = any
interface PswpUiElementConfig {
name: string
order: number
isButton: boolean
tagName?: string
ariaLabel?: string
appendTo?: string
html?: string
onInit?: (el: HTMLElement, pswp: PswpInstance) => void
}
/**
* Register the sidebar panel + toolbar toggle button + `i` keybinding.
* Called once from initLightbox after the lightbox is constructed.
*/
export function registerSidebar (lightbox: LightboxInstance) {
lightbox.on('uiRegister', () => {
lightbox.pswp.ui.registerElement({
name: 'sidebar',
order: 100,
isButton: false,
appendTo: 'root',
onInit: (el: HTMLElement, pswp: PswpInstance) => {
el.classList.add('ipp-sidebar')
el.setAttribute('aria-label', 'Photo information')
const renderSidebar = () => renderContents(el, state.items[pswp.currIndex])
renderSidebar()
pswp.on('change', renderSidebar)
pswp.on('destroy', () => {
document.documentElement.classList.remove('ipp-sidebar-open')
})
applyOpenState(pswp)
}
} as PswpUiElementConfig)
lightbox.pswp.ui.registerElement({
name: 'sidebar-toggle',
order: 7,
isButton: true,
ariaLabel: 'Info',
html: ICON_INFO,
onInit: (el: HTMLElement, pswp: PswpInstance) => {
el.addEventListener('click', () => toggleSidebar(pswp))
}
} as PswpUiElementConfig)
// Restore persisted state on open
state.sidebarOpen = readPersistedState()
applyOpenState(lightbox.pswp)
})
// `i` toggles the sidebar while the lightbox is open. Escape closes the
// sidebar first on press; PhotoSwipe handles a second Escape to close
// the lightbox. We attach to window because PhotoSwipe doesn't expose a
// keypress hook for arbitrary keys.
window.addEventListener('keydown', (e) => {
if (!state.lightbox || !state.lightbox.pswp) return
if (e.key === 'i' || e.key === 'I') {
// Don't steal `i` from text inputs (none exist in the lightbox today,
// but better safe).
const target = e.target as HTMLElement | null
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return
e.preventDefault()
toggleSidebar(state.lightbox.pswp)
} else if (e.key === 'Escape' && state.sidebarOpen) {
// Close the sidebar but let PhotoSwipe still see the Escape on the
// next press (we don't stopPropagation here).
setSidebarOpen(state.lightbox.pswp, false)
}
})
}
function toggleSidebar (pswp: PswpInstance) {
setSidebarOpen(pswp, !state.sidebarOpen)
}
function setSidebarOpen (pswp: PswpInstance, open: boolean) {
if (state.sidebarOpen === open) return
state.sidebarOpen = open
writePersistedState(open)
applyOpenState(pswp)
}
function applyOpenState (pswp: PswpInstance) {
const root = document.documentElement
if (state.sidebarOpen) root.classList.add('ipp-sidebar-open')
else root.classList.remove('ipp-sidebar-open')
// Recalculate slide size so the image fits in the new container width.
if (pswp && typeof pswp.updateSize === 'function') {
pswp.updateSize(true)
}
}
function readPersistedState (): boolean {
try {
return localStorage.getItem(SIDEBAR_STORAGE_KEY) === '1'
} catch (e) {
return false
}
}
function writePersistedState (open: boolean) {
try {
localStorage.setItem(SIDEBAR_STORAGE_KEY, open ? '1' : '0')
} catch (e) {
// Quota exceeded / private mode - ignore, state stays in memory only.
}
}
// ----- content rendering ---------------------------------------------------
function renderContents (root: HTMLElement, item: GalleryItem | undefined) {
root.replaceChildren()
if (!item) return
root.appendChild(renderHeader())
const showDescription = state.metadataConfig.descriptionInSidebar && !!item.description
if (showDescription && item.description) {
root.appendChild(renderSection('description', renderDescription(item.description)))
}
const exif = item.exif
if (exif && hasAnyExifField(exif)) {
root.appendChild(renderSection('details', ...renderDetailRows(exif)))
}
if (exif && hasAnyLocationField(exif)) {
root.appendChild(renderSection('location', renderLocation(exif)))
}
const noExifShown = !exif || (!hasAnyExifField(exif) && !hasAnyLocationField(exif))
if (!showDescription && noExifShown) {
const empty = document.createElement('p')
empty.className = 'ipp-sidebar-empty'
empty.textContent = 'No metadata available'
root.appendChild(empty)
}
}
function renderHeader (): HTMLElement {
const header = document.createElement('header')
header.className = 'ipp-sidebar-header'
const close = document.createElement('button')
close.type = 'button'
close.className = 'ipp-sidebar-close'
close.setAttribute('aria-label', 'Close info')
close.innerHTML = ICON_CLOSE
close.addEventListener('click', () => {
if (state.lightbox && state.lightbox.pswp) setSidebarOpen(state.lightbox.pswp, false)
})
header.appendChild(close)
const title = document.createElement('span')
title.className = 'ipp-sidebar-title'
title.textContent = 'Info'
header.appendChild(title)
return header
}
function renderSection (className: string, ...children: HTMLElement[]): HTMLElement {
const section = document.createElement('section')
section.className = 'ipp-sidebar-section ipp-sidebar-' + className
for (const child of children) section.appendChild(child)
return section
}
function renderDescription (description: string): HTMLElement {
const el = document.createElement('p')
el.className = 'ipp-sidebar-description'
el.textContent = description
return el
}
function renderDetailRows (exif: GalleryExif): HTMLElement[] {
const heading = document.createElement('h3')
heading.className = 'ipp-sidebar-heading'
heading.textContent = 'Details'
const rows: HTMLElement[] = [heading]
if (exif.dateTimeOriginal) {
rows.push(renderDateRow(exif.dateTimeOriginal))
}
const fileRow = renderFileRow(exif)
if (fileRow) rows.push(fileRow)
const cameraRow = renderCameraRow(exif)
if (cameraRow) rows.push(cameraRow)
const lensRow = renderLensRow(exif)
if (lensRow) rows.push(lensRow)
return rows
}
function renderDateRow (iso: string): HTMLElement {
const row = document.createElement('div')
row.className = 'ipp-sidebar-row ipp-sidebar-date'
row.textContent = formatDate(iso)
return row
}
function renderFileRow (exif: GalleryExif): HTMLElement | null {
if (!exif.fileName && !exif.width && !exif.fileSizeInByte) return null
const row = makeRow(ICON_IMAGE)
const body = row.querySelector('.ipp-sidebar-row-body') as HTMLElement
if (exif.fileName) {
const name = document.createElement('p')
name.className = 'ipp-sidebar-filename'
name.textContent = exif.fileName
body.appendChild(name)
}
if (exif.width && exif.height) {
const stats = document.createElement('div')
stats.className = 'ipp-sidebar-stats'
const mp = Math.round((exif.width * exif.height) / 1_000_000)
if (mp >= 1) stats.appendChild(makeStat(mp + ' MP'))
stats.appendChild(makeStat(exif.width + ' x ' + exif.height))
if (exif.fileSizeInByte) stats.appendChild(makeStat(formatBytes(exif.fileSizeInByte)))
body.appendChild(stats)
} else if (exif.fileSizeInByte) {
const stats = document.createElement('div')
stats.className = 'ipp-sidebar-stats'
stats.appendChild(makeStat(formatBytes(exif.fileSizeInByte)))
body.appendChild(stats)
}
return row
}
function renderCameraRow (exif: GalleryExif): HTMLElement | null {
if (!exif.make && !exif.model && exif.exposureTime == null && exif.iso == null) return null
const row = makeRow(ICON_CAMERA)
const body = row.querySelector('.ipp-sidebar-row-body') as HTMLElement
const label = [exif.make, exif.model].filter(Boolean).join(' ').trim()
if (label) {
const p = document.createElement('p')
p.textContent = label
body.appendChild(p)
}
const stats = document.createElement('div')
stats.className = 'ipp-sidebar-stats'
if (exif.exposureTime) stats.appendChild(makeStat(exif.exposureTime + ' s'))
if (exif.iso != null) stats.appendChild(makeStat('ISO ' + exif.iso))
if (stats.childElementCount) body.appendChild(stats)
return row
}
function renderLensRow (exif: GalleryExif): HTMLElement | null {
if (!exif.lensModel && exif.fNumber == null && exif.focalLength == null) return null
const row = makeRow(ICON_IRIS)
const body = row.querySelector('.ipp-sidebar-row-body') as HTMLElement
if (exif.lensModel) {
const p = document.createElement('p')
p.className = 'ipp-sidebar-lens'
p.textContent = exif.lensModel
body.appendChild(p)
}
const stats = document.createElement('div')
stats.className = 'ipp-sidebar-stats'
if (exif.fNumber != null) stats.appendChild(makeStat('f/' + exif.fNumber))
if (exif.focalLength != null) stats.appendChild(makeStat(exif.focalLength + ' mm'))
if (stats.childElementCount) body.appendChild(stats)
return row
}
function renderLocation (exif: GalleryExif): HTMLElement {
const wrap = document.createElement('div')
wrap.className = 'ipp-sidebar-row'
const icon = document.createElement('div')
icon.className = 'ipp-sidebar-row-icon'
icon.innerHTML = ICON_MAP
wrap.appendChild(icon)
const body = document.createElement('div')
body.className = 'ipp-sidebar-row-body'
const parts = [exif.city, exif.state, exif.country].filter(Boolean) as string[]
if (parts.length) {
const place = document.createElement('p')
place.textContent = parts.join(', ')
body.appendChild(place)
}
if (exif.latitude != null && exif.longitude != null) {
const coords = document.createElement('p')
coords.className = 'ipp-sidebar-coords'
coords.textContent = exif.latitude.toFixed(5) + ', ' + exif.longitude.toFixed(5)
body.appendChild(coords)
const link = document.createElement('a')
link.className = 'ipp-sidebar-osm'
link.href = 'https://www.openstreetmap.org/?mlat=' + exif.latitude +
'&mlon=' + exif.longitude +
'#map=15/' + exif.latitude + '/' + exif.longitude
link.target = '_blank'
link.rel = 'noopener'
link.textContent = 'Open in OpenStreetMap'
body.appendChild(link)
}
wrap.appendChild(body)
return wrap
}
// ----- helpers -------------------------------------------------------------
function makeRow (iconSvg: string): HTMLElement {
const row = document.createElement('div')
row.className = 'ipp-sidebar-row'
const icon = document.createElement('div')
icon.className = 'ipp-sidebar-row-icon'
icon.innerHTML = iconSvg
row.appendChild(icon)
const body = document.createElement('div')
body.className = 'ipp-sidebar-row-body'
row.appendChild(body)
return row
}
function makeStat (text: string): HTMLElement {
const span = document.createElement('span')
span.textContent = text
return span
}
function hasAnyExifField (exif: GalleryExif): boolean {
return !!(exif.dateTimeOriginal || exif.fileName || exif.width || exif.fileSizeInByte ||
exif.make || exif.model || exif.lensModel ||
exif.exposureTime != null || exif.iso != null ||
exif.fNumber != null || exif.focalLength != null)
}
function hasAnyLocationField (exif: GalleryExif): boolean {
return !!(exif.city || exif.state || exif.country ||
(exif.latitude != null && exif.longitude != null))
}
function formatDate (iso: string): string {
const d = new Date(iso)
if (isNaN(d.getTime())) return iso
try {
return new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
}).format(d)
} catch (e) {
return iso
}
}
function formatBytes (bytes: number): string {
if (bytes < 1024) return bytes + ' B'
const kb = bytes / 1024
if (kb < 1024) return kb.toFixed(1) + ' KB'
const mb = kb / 1024
if (mb < 1024) return mb.toFixed(1) + ' MB'
return (mb / 1024).toFixed(2) + ' GB'
}
+105
View File
@@ -0,0 +1,105 @@
// Shared mutable state for the client gallery. Every module that touches
// gallery-wide state goes through `state` rather than holding its own
// top-level `let`s. Constants and icon strings live here too because they
// are read by multiple modules.
import type { GalleryItem, LightboxConfig, MetadataConfig } from '../shared/types.js'
// ----- layout / scroll tuning ----------------------------------------------
// Justified-rows target row height (matches Immich's main view)
export const TARGET_ROW_HEIGHT = 235
export const GAP = 4
export const MOBILE_BREAKPOINT = 640
export const MOBILE_COLS = 3
export const IMAGE_LOAD_MARGIN_PX = 300
export const SCROLL_SETTLE_MS = 100
export const BUFFER_VIEWPORTS = 1
// Height reserved for each month header (must agree with .group-header CSS)
export const HEADER_HEIGHT = 48
// Vertical gap between groups
export const GROUP_GAP = 16
// Long-press threshold for entering select mode via touch/mouse
export const LONG_PRESS_MS = 500
// ----- icons ----------------------------------------------------------------
// MDI icons (Apache 2.0). Same icon set Immich uses for its viewer.
export const ICON_DOWNLOAD = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"/></svg>'
export const ICON_FULLSCREEN = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,5H10V7H7V10H5V5M14,5H19V10H17V7H14V5M17,14H19V19H14V17H17V14M10,17V19H5V14H7V17H10Z"/></svg>'
export const ICON_FULLSCREEN_EXIT = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M14,14H19V16H16V19H14V14M5,14H10V19H8V16H5V14M8,5H10V10H5V8H8V5M19,8V10H14V5H16V8H19Z"/></svg>'
export const ICON_INFO = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M11,9H13V7H11M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M11,17H13V11H11V17Z"/></svg>'
export const ICON_BACK = '<svg class="pswp__icn" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z"/></svg>'
export const ICON_CLOSE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"/></svg>'
// MDI camera / iris / image icons for the sidebar field rows
export const ICON_IMAGE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M8.5,13.5L11,16.5L14.5,12L19,18H5M21,19V5C21,3.89 20.1,3 19,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19Z"/></svg>'
export const ICON_CAMERA = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M4,4H7L9,2H15L17,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7M12,9A3,3 0 0,1 15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9Z"/></svg>'
export const ICON_IRIS = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M5,5H10.5L7.9,11H4L5,5M11.5,5H17L15.4,11H9.9L11.5,5M18,5H20.93L20.61,7H17.4L18,5M3.66,13H7.41L7,15.5L8.5,18.83L8,22L4.31,19L2.34,16.38L3.66,13M9.42,13H14.58L15.58,15.4L13.4,22H10.6L8.42,15.4L9.42,13M16.59,13H21.34L20.92,16.92L16.5,21.5L15.5,18.5L17,15.4L16.59,13Z"/></svg>'
export const ICON_MAP = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z"/></svg>'
// Inline SVG for the check icon shown inside selected tiles' checkmark circle
export const CHECK_SVG = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"/></svg>'
// localStorage key for sidebar open state
export const SIDEBAR_STORAGE_KEY = 'ipp-sidebar-open'
// Width of the sidebar when docked (must match the CSS rule)
export const SIDEBAR_WIDTH = 360
// ----- mutable state -------------------------------------------------------
export interface LayoutEntry {
index: number
left: number
top: number
width: number
height: number
}
export interface HeaderEntry {
label: string
top: number
height: number
}
export interface GroupSpec {
label: string | null
indices: number[]
}
// PhotoSwipeLightbox is an external module with no TS types in this project.
// Typing it as `unknown` would push casts to every call site; `any` is the
// pragmatic choice and stays scoped to this single state slot.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PhotoSwipeLightboxInstance = any
export const state = {
items: [] as GalleryItem[],
layout: [] as LayoutEntry[],
headers: [] as HeaderEntry[],
groupByDate: false,
container: null as HTMLElement | null,
lightbox: null as PhotoSwipeLightboxInstance,
lightboxConfig: {} as Partial<LightboxConfig>,
metadataConfig: {
descriptionInCaption: false,
descriptionInSidebar: false,
sidebarHasContent: false
} as MetadataConfig,
// True while our pushed history entry is live
lightboxPushedHistory: false,
// Guards against re-entering the popstate handler during our own history.back()
closingFromHistory: false,
lastContainerW: 0,
renderedTiles: new Map<number, HTMLAnchorElement>(),
renderedHeaders: new Map<string, HTMLElement>(),
// Selection mode (mode-toggle UX: hidden checkmarks until activated)
selectMode: false,
selected: new Set<string>(),
toolbarEl: null as HTMLElement | null,
countEl: null as HTMLElement | null,
selectAllBtn: null as HTMLButtonElement | null,
cancelBtn: null as HTMLButtonElement | null,
downloadBtn: null as HTMLButtonElement | null,
// Info sidebar open/closed. Persisted to localStorage so the choice
// survives navigation between slides and gallery reloads.
sidebarOpen: false
}
+152
View File
@@ -0,0 +1,152 @@
// Per-tile DOM construction: anchor, image, thumbhash blur background, video
// play icon, selection checkmark, click + long-press handlers.
// Runtime URL resolved by Express static, not a TS-resolvable module path.
// @ts-expect-error - browser-only ESM URL
import { thumbHashToDataURL } from '/share/static/thumbhash/thumbhash.js' // eslint-disable-line import/no-absolute-path
import { state, CHECK_SVG, LONG_PRESS_MS } from './state.js'
import { enterSelectMode, toggleSelection } from './selection.js'
import { openLightbox } from './lightbox.js'
function onThumbError (this: HTMLImageElement) {
this.closest('a')?.classList.add('thumb-error')
}
// Cache of decoded thumbhash → PNG data URL. Same thumbhash on multiple
// tile-creations (revisits during virtualization) reuses the same URL.
const thumbhashCache = new Map<string, string | null>()
function decodeThumbhash (base64: string): string | null {
const cached = thumbhashCache.get(base64)
if (cached !== undefined) return cached
try {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < bytes.length; i++) bytes[i] = binary.charCodeAt(i)
const url = thumbHashToDataURL(bytes) as string
thumbhashCache.set(base64, url)
return url
} catch (e) {
thumbhashCache.set(base64, null)
return null
}
}
/**
* Build the anchor element for one tile at the given index in `state.items`.
* Positioning is taken from the precomputed `state.layout`.
*
* The tile shows the thumbhash blur as a background, an `<img>` whose `src`
* is held back until the tile enters the viewport (see
* `loadVisibleTiles`), a play overlay for videos, and a selection
* checkmark + long-press handler if the share allows downloads.
*
* Click opens the lightbox unless selection mode is active, in which case
* it toggles the item's selection.
*/
export function createTile (index: number): HTMLAnchorElement {
const item = state.items[index]
const l = state.layout[index]
const a = document.createElement('a')
a.dataset.index = String(index)
if (item.type !== 'VIDEO') a.href = item.previewUrl
a.style.left = l.left + 'px'
a.style.top = l.top + 'px'
a.style.width = l.width + 'px'
a.style.height = l.height + 'px'
if (item.thumbhash) {
const url = decodeThumbhash(item.thumbhash)
if (url) a.style.backgroundImage = 'url(' + url + ')'
}
const img = document.createElement('img')
// alt left empty: browsers paint alt text over the thumbhash background
// while the thumbnail downloads. Description (if any) is shown in the
// lightbox caption instead.
img.alt = ''
img.dataset.src = item.thumbnailUrl
img.onerror = onThumbError
// Mark the image as drawable once its bytes are decoded; the CSS rule
// `#gallery img.loaded` fades opacity from 0 to 1 so the thumbhash blurs
// into the sharp image instead of snapping (and masks Chrome/Edge's brief
// white flash between `img.src` being set and the bytes actually painting).
img.onload = () => img.classList.add('loaded')
a.appendChild(img)
if (item.type === 'VIDEO') {
const playIcon = document.createElement('div')
playIcon.className = 'play-icon'
a.appendChild(playIcon)
}
// Selection checkmark (rendered only when select mode is even possible -
// i.e. when the page included the toolbar element)
if (state.toolbarEl) {
const check = document.createElement('div')
check.className = 'tile-check'
check.innerHTML = CHECK_SVG
check.addEventListener('click', (e) => {
e.preventDefault()
e.stopPropagation()
if (!state.selectMode) enterSelectMode()
toggleSelection(item.id)
})
a.appendChild(check)
if (state.selected.has(item.id)) a.classList.add('selected')
attachLongPress(a, item.id)
}
a.addEventListener('click', (e) => {
e.preventDefault()
if (state.selectMode) {
toggleSelection(item.id)
} else {
openLightbox(index)
}
})
return a
}
/**
* Wire press-and-hold on a tile to enter selection mode and toggle the
* tile's item. Cancels on pointer movement above a small threshold (so a
* scroll gesture doesn't trigger it) and suppresses the synthetic click
* that follows a successful long-press (so the lightbox doesn't open).
*/
function attachLongPress (tile: HTMLAnchorElement, id: string) {
let timer: ReturnType<typeof setTimeout> | null = null
let pressed = false
const cancel = () => {
if (timer) { clearTimeout(timer); timer = null }
}
tile.addEventListener('pointerdown', (e) => {
// Ignore right/middle clicks
if (e.button !== undefined && e.button !== 0) return
pressed = false
timer = setTimeout(() => {
timer = null
pressed = true
if (!state.selectMode) enterSelectMode()
toggleSelection(id)
}, LONG_PRESS_MS)
})
tile.addEventListener('pointerup', cancel)
tile.addEventListener('pointercancel', cancel)
tile.addEventListener('pointerleave', cancel)
tile.addEventListener('pointermove', (e) => {
// Cancel long-press if pointer moves significantly (scroll, drag)
if (Math.abs(e.movementX) + Math.abs(e.movementY) > 6) cancel()
})
// Swallow the synthetic click that follows a successful long-press so it
// doesn't open the lightbox.
tile.addEventListener('click', (e) => {
if (pressed) {
pressed = false
e.preventDefault()
e.stopImmediatePropagation()
}
}, true)
}
+172
View File
@@ -0,0 +1,172 @@
// Viewport-based tile / header lifecycle. Only tiles within viewport ± 1
// viewport-height buffer exist in the DOM at any moment. The image-src
// lifecycle (lazy load / unload of `img.src`) is part of the same loop.
import {
state,
IMAGE_LOAD_MARGIN_PX,
SCROLL_SETTLE_MS,
BUFFER_VIEWPORTS,
type HeaderEntry
} from './state.js'
import { computeLayout } from './layout.js'
import { createTile } from './tiles.js'
function getVisibleRange () {
if (!state.container) return { top: 0, bottom: 0 }
const containerTop = state.container.getBoundingClientRect().top
const viewportTopInContainer = -containerTop
const viewportBottomInContainer = viewportTopInContainer + window.innerHeight
const buffer = window.innerHeight * BUFFER_VIEWPORTS
return {
top: viewportTopInContainer - buffer,
bottom: viewportBottomInContainer + buffer
}
}
function createHeader (header: HeaderEntry): HTMLElement {
const el = document.createElement('h2')
el.className = 'group-header'
el.style.top = header.top + 'px'
el.textContent = header.label
return el
}
/**
* Bring the DOM in line with the current visible range: create tiles and
* headers that should now be on screen, remove ones that have scrolled out.
* Idempotent; safe to call multiple times per frame (scroll handler does).
*/
export function virtualize () {
if (!state.container || !state.layout.length) return
const { top, bottom } = getVisibleRange()
// Tiles
const neededTiles = new Set<number>()
for (const l of state.layout) {
if (!l) continue
if (l.top + l.height < top) continue
if (l.top > bottom) break
neededTiles.add(l.index)
}
for (const [index, el] of state.renderedTiles) {
if (!neededTiles.has(index)) {
el.remove()
state.renderedTiles.delete(index)
}
}
for (const index of neededTiles) {
if (state.renderedTiles.has(index)) continue
const tile = createTile(index)
state.container.appendChild(tile)
state.renderedTiles.set(index, tile)
}
// Group headers (when grouping is enabled; headers is empty otherwise)
const neededHeaders = new Set<string>()
for (const h of state.headers) {
if (h.top + h.height < top) continue
if (h.top > bottom) break
neededHeaders.add(h.label)
}
for (const [label, el] of state.renderedHeaders) {
if (!neededHeaders.has(label)) {
el.remove()
state.renderedHeaders.delete(label)
}
}
for (const label of neededHeaders) {
if (state.renderedHeaders.has(label)) continue
const h = state.headers.find(x => x.label === label)
if (!h) continue
const el = createHeader(h)
state.container.appendChild(el)
state.renderedHeaders.set(label, el)
}
}
/**
* Recompute the layout when the container width has actually changed, then
* re-virtualize and load images for the visible range. If the width is the
* same as last time (e.g. a resize fired but the gallery column is unchanged)
* the cached layout is reused and only virtualize runs.
*
* Called from the ResizeObserver in init.ts.
*/
export function computeLayoutAndRender () {
if (!state.container) return
const containerW = state.container.clientWidth
if (containerW <= 0) return
if (containerW === state.lastContainerW) {
virtualize()
return
}
state.lastContainerW = containerW
const result = computeLayout(containerW)
state.layout = result.layout
state.headers = result.headers
state.container.style.height = result.totalHeight + 'px'
for (const [, el] of state.renderedTiles) el.remove()
state.renderedTiles.clear()
for (const [, el] of state.renderedHeaders) el.remove()
state.renderedHeaders.clear()
virtualize()
loadVisibleTiles()
}
/**
* Walk the currently rendered tiles and toggle their `<img>` src based on
* proximity to the viewport. Tiles within IMAGE_LOAD_MARGIN_PX get their
* `data-src` promoted to `src` (browser fetches the thumbnail); tiles far
* off-screen with an unfinished load have their `src` parked back into
* `data-src` so the browser cancels the fetch.
*
* Run after scroll has settled, not on every scroll tick.
*/
export function loadVisibleTiles () {
if (!state.container) return
const vpHeight = window.innerHeight
const containerTop = state.container.getBoundingClientRect().top
for (const a of state.renderedTiles.values()) {
const img = a.firstElementChild
if (!(img instanceof HTMLImageElement)) continue
const aTopInVp = containerTop + parseFloat(a.style.top || '0')
const aHeight = parseFloat(a.style.height || '0')
const isFar = aTopInVp + aHeight < -IMAGE_LOAD_MARGIN_PX ||
aTopInVp > vpHeight + IMAGE_LOAD_MARGIN_PX
if (isFar) {
if (img.src && !img.complete) {
img.dataset.src = img.src
img.removeAttribute('src')
}
} else if (img.dataset.src) {
img.src = img.dataset.src
img.removeAttribute('data-src')
}
}
}
let scrollFrame: number | null = null
let loadTimer: ReturnType<typeof setTimeout> | null = null
/**
* Window scroll handler. Coalesces virtualize calls into the next animation
* frame and debounces the more expensive image-src lifecycle by
* SCROLL_SETTLE_MS so we don't thrash `img.src` during fast flings.
*/
export function onScroll () {
if (scrollFrame == null) {
scrollFrame = requestAnimationFrame(() => {
scrollFrame = null
virtualize()
})
}
if (loadTimer) clearTimeout(loadTimer)
loadTimer = setTimeout(() => {
loadTimer = null
loadVisibleTiles()
}, SCROLL_SETTLE_MS)
}