Aspect-Ratio-Preserving Justified Web Gallery, 5-Slot Lightbox & Normalized EXIF Sample Feed
When designing PhotoJob—a vertical platform connecting commercial photographers, photo assistants, and rental studios through concrete gear and space specifications—the very first frontend challenge we ran into was a deceptively ordinary component: the portfolio photo grid. Making a neat layout is trivial if you follow general-purpose social feeds by cropping every frame into a 1:1 square and floating translucent black badges over the corners. For a commercial photographer, however, framing is the grammar of the image itself; an arbitrary crop destroys the author's intended composition.
An even trickier requirement sits at the boundary between public discovery and production confidentiality. Photographers want their final published shots to be discoverable in public sample feeds indexed by camera body and lens. At the exact same time, the pre-production document behind that shoot—the Con-book containing lighting CAD plots, client creative briefs, and call sheets with crew phone numbers and email addresses—must remain strictly private.
This post walks through the four architectural pillars powering PhotoJob's media pipeline at the code level: ① Josef Albers pure-frame cards, ② a justified row-packing engine engineered to converge on zero CLS, ③ a non-circular 5-slot darkroom lightbox, and ④ a 6-step EXIF gear normalizer paired with 3-tier Con-book access control.
1. Why 1:1 Cropped Grids Break Commercial Photography: The Albers Pure-Frame Principle
A commercial shoot almost never delivers a single aspect ratio. Inside one portfolio, 3:2 frames from full-frame DSLRs and mirrorless bodies sit alongside 4:3 captures from medium-format digital backs (Phase One, Hasselblad), vertical 4:5 frames cut for fashion editorials and magazine covers, and 16:9 or panoramic key visuals built for campaign billboards.
Force that mix into 1:1 square tiles with object-fit: cover, and the damage is immediate. Full-body vertical lookbook portraits lose the model's head and shoes, while wide studio set shots lose the lighting context along the left and right edges. Layer a dark gradient scrim and floating tag chips on top of the thumbnail, and you distort the photograph's contrast curve and perceived color balance as well.
To prevent that degradation, PhotoJob encodes the pure-frame discipline of Dieter Rams and Josef Albers directly into app/components/gallery/AlbersPhotoCard.vue:
- 99:1 Achromatic Matte and
0pxRadius: Every photograph sits inside an#EEEEECgallery matte (padding: 32px 24px 16px,1px solid #CFCFCBhairline) on a#F6F6F4light canvas—or directly on a#16181Bdarkroom stage—withborder-radius: 0pxandbox-shadow: noneenforced across every state, preserving the restraint of a printed exhibition monograph. - Zero Overlays on the Image Surface: Not a single pixel of
position: absolutetext, status badge, or translucent scrim is allowed over the photograph itself. Titles, concise metadata summaries, and dominant color readouts live cleanly below the frame in a dedicated catalog caption band. - Safe-Range Clamped Dominant Color (
dominantHex): To stop pure black (#000000) or pure white (#FFFFFF) from violating the visual grammar, each sRGB channel is clamped to[24..246]. Before an image finishes decoding, its placeholder background uses a desaturated, low-chroma neutral blend (mixAchromaticLowChromaPlaceholder) so loading states never flash harsh saturated blocks across the viewport.
2. Aspect-Ratio-Preserving Justified Row Packing & Zero-CLS Convergence
Preserving natural aspect ratios does not mean accepting the ragged bottom edges and broken reading rhythm of naive column masonry. Justified row packing preserves every photograph's exact aspectRatio = width / height while scaling each horizontal row to fill the container width edge to edge with crisp vertical alignment.
2.1. Linear Row Packing (computeJustifiedRows) and Capping Final-Row Blowup
Implemented in shared/portfolio/gridAndPalette.ts as a pure, side-effect-free TypeScript function, computeJustifiedRows produces identical geometric coordinates during server-side rendering and client hydration. The algorithm runs in three deterministic stages:
- Safe Aspect-Ratio Clamping: Each item's
width / heightratio is clamped to[0.2, 5.0]so an extreme panoramic strip or ultra-tall banner cannot destabilize a row's math. - Natural Width Accumulation and Row Flushing: Items are pushed into the pending row while accumulating
aspectSum. OnceaspectSum * targetRowHeightPx + (n - 1) * gapPx >= containerWidthPx, the row flushes and its exact height is solved back asavailableWidthPx / aspectSum. - Subpixel Error Absorption and Final-Row Stretch Cap: Rounding each item width to two decimal places can accumulate roughly
1pxof drift across a row; the last item in every full row absorbssafeContainerW - cursorLeftPxso the right margin snaps razor-straight. Equally critical is the final orphan row: if a single portrait frame lands on the last row, stretching it across the full container width would turn it into a giant poster. SettingmaxFinalRowStretchRatio = 0.3(wasStretchCapped) caps any partial final row at1.3×the target height and snaps it cleanly back totargetRowHeightPxwhen exceeded.
// shared/portfolio/gridAndPalette.ts (Core justified row-packing excerpt)
export function computeJustifiedRows<T extends GridMeasurableItem>(
items: readonly T[],
containerWidthPx: number,
targetRowHeightPx = 320,
gapPx = 12,
maxFinalRowStretchRatio = 0.3,
): JustifiedRowLayout[] {
if (!items.length) return []
const safeContainerW = Math.max(120, containerWidthPx || 1200)
const safeTargetH = Math.max(48, targetRowHeightPx || 320)
const safeGap = Math.max(0, gapPx)
const safeMaxStretch = Math.max(0, maxFinalRowStretchRatio)
const rows: JustifiedRowLayout[] = []
let pending: Array<{ id: string; index: number; aspectRatio: number }> = []
let aspectSum = 0
let runningTopPx = 0
const flushRow = (isFinalPartialRow: boolean) => {
if (!pending.length) return
const totalGapsPx = (pending.length - 1) * safeGap
const availableWidthPx = Math.max(1, safeContainerW - totalGapsPx)
const rawJustifiedHeight = availableWidthPx / Math.max(0.01, aspectSum)
// Prevent 1-2 orphan photos in the final partial row from blowing up to full width
let rowHeightPx = rawJustifiedHeight
let wasStretchCapped = false
if (isFinalPartialRow && rawJustifiedHeight > safeTargetH * (1 + safeMaxStretch)) {
rowHeightPx = safeTargetH
wasStretchCapped = true
}
const roundedRowHeight = Number(rowHeightPx.toFixed(2))
let cursorLeftPx = 0
const rowItems = pending.map((entry, idxInRow) => {
const isLastInJustifiedRow = !wasStretchCapped && idxInRow === pending.length - 1
const widthPx = isLastInJustifiedRow
? Number(Math.max(1, safeContainerW - cursorLeftPx).toFixed(2))
: Number((entry.aspectRatio * rowHeightPx).toFixed(2))
const leftPx = Number(cursorLeftPx.toFixed(2))
cursorLeftPx += widthPx + safeGap
return { ...entry, widthPx, heightPx: roundedRowHeight, leftPx }
})
const topPx = Number(runningTopPx.toFixed(2))
const bottomPx = Number((topPx + roundedRowHeight).toFixed(2))
rows.push({
rowIndex: rows.length, topPx, heightPx: roundedRowHeight, bottomPx,
isLastRow: false, wasStretchCapped, items: rowItems,
})
runningTopPx = bottomPx + safeGap
pending = []
aspectSum = 0
}
// ... iterate items, call flushRow(false) on width overflow, then flushRow(true) for trailing items
return rows
}
2.2. Driving CLS to Zero and Virtualizing Large Portfolios
Even mathematically exact row geometry will tank Cumulative Layout Shift (CLS) if DOM heights jump as images trickle in over the network. PhotoJob closes that gap with four interlocking mechanisms:
- Database-Backed
aspect-ratioReservation: The upload pipeline extractswidthandheightat ingest and ships them in the API payload, letting every card reserve its exact frame box (aspectRatio: "${width} / ${height}") before the<img>byte stream starts. - Instant ThumbHash
<canvas>Decoding with Immediate Memory Reclamation: Compact 20–30 byte Base64 ThumbHash strings are decoded directly in pure TypeScript via a DCT decoder (decodeThumbHashB64ToRgba) to paint an instant blurred preview. The moment the actual image fires@load,releaseThumbCanvas()zeroescanvas.width = 0; canvas.height = 0, immediately freeing the backing bitmap buffer from GPU and system RAM. - CSS
content-visibility: autoandO(log N)Binary-Search Virtual Windowing: Individual cards applycontent-visibility: autoto skip offscreen paint work. For multi-hundred-frame portfolios,buildRowBottomPrefixSumsstores cumulative row bottom offsets in aFloat64Array, andqueryVirtualWindowBinaryperforms anO(log N)binary search on scroll so only rows within a2-viewport overscan band above and below the screen stay mounted in the DOM.
3. Designing a Non-Circular 5-Slot Darkroom Lightbox (ReflexRingLightbox)
The full-screen viewer that opens when clicking a grid frame is where commercial clients inspect retouching, skin texture, and lighting falloff. Lightbox implementations typically stumble into one of two opposite traps: mounting all 200 high-resolution images inside a carousel at once—causing mobile Safari tabs to get jetsam-killed for memory bloat—or mounting only the single active frame, which produces an ugly blank flash on every swipe.
app/components/gallery/ReflexRingLightbox.vue splits the difference with a Non-Circular 5-Slot Ring architecture.
3.1. Bounded [center - 2 .. center + 2] DOM and 2-Tier Progressive Resolution Upgrade
Centered on the active index (center), the lightbox keeps at most five slots mounted in the DOM: from Math.max(0, center - 2) through Math.min(total - 1, center + 2). Two frames ahead and two behind are already decoded for zero-latency swiping, while total DOM node count and GPU texture memory remain strictly bounded to five slots regardless of portfolio length.
// app/components/gallery/ReflexRingLightbox.vue (5-slot window & progressive loader excerpt)
const ringSlots = computed(() => {
const total = props.items.length
if (total === 0) return []
const center = clampedActiveIndex.value
const start = Math.max(0, center - 2)
const end = Math.min(total - 1, center + 2)
const slots = []
for (let idx = start; idx <= end; idx++) {
const item = props.items[idx]
if (!item) continue
slots.push({ slotIndex: idx, offset: idx - center, slotKey: `${idx}-${item.id}`, item })
}
return slots
})
Inside the #16181B darkroom stage, each slot renders through a 3-stage visual stack: ThumbHash Canvas → Layer 1 (stage1024Url) → Layer 2 (stage2048Url). During rapid mobile flicking, the 1024px stage derivative snaps into crisp focus immediately; when the viewer pauses to inspect fine details, the 2048px high-resolution layer finishes decoding in the background and swaps in seamlessly without flicker.
3.2. Blocking Accidental Swipes During Mobile Pinch-Zoom
When a photographer or art director pinches to 200% zoom on mobile to check fabric weave or focus falloff and then pans across the frame, misinterpreting that drag as a "next photo" swipe is a classic UX failure.
// app/components/gallery/ReflexRingLightbox.vue (Pinch-zoom collision latch)
const isPinchZoomActive = (): boolean => {
const vpZoomed =
typeof window !== 'undefined' && window.visualViewport
? window.visualViewport.scale > 1.01
: false
return vpZoomed || visualViewportScale.value > 1.01 || activeTouchCount.value >= 2
}
const onStageTouchEnd = (event: TouchEvent) => {
const blockedByPinch = pinchLatched || isPinchZoomActive()
activeTouchCount.value = event.touches.length
if (activeTouchCount.value === 0) pinchLatched = false
if (blockedByPinch || !swipeTracking) {
swipeTracking = false
return
}
// Evaluate horizontal swipe threshold (|dx| >= 48 && |dx| > |dy| * 1.2) only for unzoomed single-touch gestures
}
Whenever window.visualViewport.scale > 1.01 or 2 or more simultaneous touch pointers are detected, pinchLatched engages immediately and locks out both horizontal slide transitions and 25%/75% edge-tap navigation until every finger leaves the screen.
4. 6-Step EXIF Gear Normalization Feed & Owner-Only Con-book Access Control
Presenting photographs with fidelity solves only half the product problem. The other half is drawing a clean line between gear-based public discoverability and commercial production secrecy.
4.1. 6-Step EXIF Slug Normalization (normalizeGearSlug) and Palette Filtering
Raw EXIF Make and Model strings emitted by cameras and lenses are notoriously inconsistent across vendors and firmware generations. Strings like "Nikon Corporation" vs. "NIKON", the mathematical function glyph ƒ (\u0192) in "NIKKOR Z 40mm ƒ/2", umlauts such as ä in "Voigtländer", or redundant maker prefixes like "Canon EOS R5" under maker "Canon" will shatter a gear directory into dozens of duplicate URLs if slugified naively.
normalizeGearSlug in shared/gear/exifSlugNormalizer.ts collapses those variants through a pure TypeScript 6-step deterministic normalization pipeline into a single canonical route (/explore/{cameras|lenses}/{makerSlug}/{modelSlug}):
- Unicode NFD Decomposition & Diacritic Stripping: Removes combining diacritical marks (
[\u0300-\u036f]), turningVoigtländerintoVoigtlander. - Optical, Greek, and Ligature Transliteration: Maps
ƒ→f,α→a,ß→ss,ø→o,æ→ae, and&→' and '. - Lowercase Normalization: Converts the string to lowercase while preserving Roman numeral generation tokens (
II,III,IV) as distinct segments. - Corporate Suffix & Redundant Maker Prefix Stripping: Strips corporate tails (
Imaging Corp.,Co., Ltd.) viaCORPORATE_MAKER_SUFFIX_REandMAKER_CANONICAL_OVERRIDES, then trims duplicated maker prefixes from model slugs (canon-eos-r5→eos-r5) while explicitly preserving distinct optical sub-brands such asnikkor-z-40mm-f-2undernikon. - Non-Alphanumeric Hyphen Collapse & Edge Trimming: Collapses runs of
[^a-z0-9]+into a single-and trims leading/trailing hyphens.
Whenever an unrecognized camera body or third-party lens enters the system, it lands in an admin moderation queue (exif_gear_aliases, transitioning PENDING → VERIFIED) so new variants merge safely into the canonical catalog. On the discovery side, the explore feed layers an sRGB Euclidean color-distance filter (srgbEuclideanDistance / matchesPaletteFilter, default radius 48), enabling visitors to narrow sample photos by up to five target color chips in real time.
4.2. Public EXIF Feed vs. Private Con-book Permission Boundaries
A photograph enters the public gear feed only when the photographer explicitly opts in on final deliverables (final_outputs) by setting allow_public_gear_feed = true. Even then, location coordinates are scrubbed (gps_stripped = true) to protect studio and private-shoot locations, and raw object storage keys (storageObjectKey) are never exposed—images are served exclusively through the proxy route /media/showcase/{id}.webp?preset=stage1024|stage2048.
Conversely, the Con-book—which aggregates sensitive pre- and post-production assets—enforces 3-tier visibility and field-level redaction strictly on the server inside server/api/conbooks/[id].get.ts:
| Visibility Tier / Condition | HTTP Response & Auth Verification | Media Signing & Sensitive Field Masking Policy |
|---|---|---|
PRIVATE | 401 if unauthenticated, 403 for non-owners (isResourceOwnerOrAdmin) | Restricted strictly to author/admin; lighting CAD, briefs, and call sheets completely blocked |
UNLISTED | Validates shareToken in constant time via safeCompareToken; returns 410 Gone past expiresAt | Strips shareToken, storageObjectKey, crew phone/email, and rsvpInviteToken for all non-owners |
PUBLIC / Opt-in | Publicly readable, but only allow_public_gear_feed = true final outputs surface in EXIF feeds | Serves shareEpoch-signed URLs (resignConbookMediaUrl); lighting plots and crew contacts remain hidden |
// server/api/conbooks/[id].get.ts (Authorization boundary & field-level redaction excerpt)
const authUser = await getOptionalAuthUser(event)
const isOwner = isResourceOwnerOrAdmin(authUser, conbook.userId)
const isExpired = Boolean(conbook.expiresAt && new Date(conbook.expiresAt) < new Date())
// 1. PRIVATE visibility check (401 unauthenticated, 403 non-owner)
if (conbook.visibility === 'PRIVATE') {
if (!authUser) throw createError({ statusCode: 401, statusMessage: 'Authentication required.' })
if (!isOwner) throw createError({ statusCode: 403, statusMessage: 'Only the owner can view this Con-book.' })
}
// 2. Expiration check & constant-time shareToken validation for UNLISTED access
if (!isOwner && isExpired) {
throw createError({ statusCode: 410, statusMessage: 'This shared Con-book link has expired.' })
}
const hasValidShareToken = safeCompareToken(conbook.shareToken, String(queryToken || ''))
if (conbook.visibility === 'UNLISTED' && !isOwner && !hasValidShareToken) {
throw createError({ statusCode: 403, statusMessage: 'A valid share token is required.' })
}
// 3. Redact raw storage keys, share tokens, and crew PII (phone, email) for non-owner responses
const crewCalls = (conbook.crewCalls || []).map((row) => serializeCrewCallRow(row, isOwner))
Key Takeaway: Enforcing the split between the public EXIF sample feed and private commercial Con-books across both database opt-in flags and server-side response serializers lets photographers earn organic discovery from their gear portfolio without risking client NDA breaches or leaking crew PII.
Wrapping Up: Engineering for Both Photographic Framing and Production Secrecy
Building PhotoJob's gallery, EXIF gear feed, and Con-book authorization boundary reinforced four practical systems principles:
- Encode domain visual grammar as hard UI constraints: Pairing the Albers pure-frame card (no
1:1crops, zero image-surface overlays) withcomputeJustifiedRowspreserves3:2,4:3,4:5, and panoramic framing without sacrificing grid order. - Guarantee layout stability and memory ceilings through geometry: Server-stored
width/heightreservations lock CLS at0, while immediate ThumbHash canvas teardown, the bounded 5-slotReflexRingLightbox, and the pinch-zoom swipe latch keep high-resolution inspection fluid even on memory-constrained mobile Safari tabs. - Turn messy EXIF strings into deterministic URL schemas: Running camera and lens metadata through the 6-step
normalizeGearSlugpipeline and an admin alias queue collapses fragmented manufacturer strings into clean/explore/{cameras|lenses}/{maker}/{model}feeds. - Separate public discovery from production confidentiality at the server boundary: Combining
PRIVATEandUNLISTED(safeCompareToken+410 Gone) enforcement, explicitallow_public_gear_feedopt-in, and field-level serialization ensures finished frames stay searchable while lighting plots and crew contact sheets stay strictly fenced off.
You can explore the full platform architecture and related engineering build logs on the PhotoJob project overview page.