ReviewOS

stacks/stx

components: add <SafeImage> — declarative broken-image fallback with optional class swap

#1732
Closed glennmichael123 opened this 23 days ago · 0 comments
23 days ago

Problem

Third-party image URLs (avatars from external CDNs, photos pointing at user content that gets deleted, seed data pointing at unsplash links that disappeared) 404 frequently in production. Without intervention the browser draws the alt text inside whatever layout frame the <img> was given — round avatar frames in particular look like garbage.

Today this is handled per-project by hand-rolling a delegated capture-phase listener:

// In some component IIFE — globally, once
if (!window.__brokenImageHandler) {
  window.__brokenImageHandler = true
  document.addEventListener('error', (e) => {
    const t = e.target
    if (!t || t.tagName !== 'IMG') return
    const img = t
    if (img.__fallback_applied) return
    img.__fallback_applied = true
    img.src = '/images/avatars/default-user.svg'
    img.classList.remove('grayscale', 'filter')  // ← bench-review-specific
  }, true)
}

Three things wrong with this pattern:

  1. Global side effect in component lifecycle. Lives inside a component's IIFE because that's the only place to register browser-level handlers at boot. Survives across SPA navs but the registration race depends on which component is mounted first.
  2. Capture-phase delegation only catches errors AFTER load attempt. error events don't bubble, so the listener must be in capture. But if the <img> has already errored before the listener attaches (cached 404s, offline first paint), it misses.
  3. Per-image config is impossible. The handler hardcodes the fallback URL and the class swap. Every distinct fallback URL or class-swap behaviour needs its own hand-rolled handler.

Proposed component

<SafeImage> — drop-in <img> replacement that takes its fallback URL and optional class swap declaratively:

<SafeImage :src="judge.photo"
           :alt="judge.name"
           className="h-12 w-12 rounded-full grayscale filter"
           fallbackClassName="h-12 w-12 rounded-full"
           fallback="/images/avatars/default-judge.svg" />

Implementation sketch (already running in production at bench-review)

<script server>
export const src = $props.src || ''
export const alt = $props.alt || ''
export const fallback = $props.fallback || '/images/safe-image-default.svg'
export const className = $props.className || ''
export const fallbackClassName = $props.fallbackClassName || ''
</script>

<script client>
  if (typeof window !== 'undefined' && !window.__stxSafeImageHandler) {
    window.__stxSafeImageHandler = (img) => {
      if (img.__stx_fallback_applied) return
      img.__stx_fallback_applied = true
      const fb = img.dataset.fallback || '/images/safe-image-default.svg'
      const swapCls = img.dataset.fallbackClass
      img.src = fb
      if (swapCls != null && swapCls !== '') img.className = swapCls
    }
  }
</script>

<img
  src="{⁠{ src }}"
  alt="{⁠{ alt }}"
  class="{⁠{ className }}"
  data-fallback="{⁠{ fallback }}"
  data-fallback-class="{⁠{ fallbackClassName }}"
  onerror="window.__stxSafeImageHandler(this)"
/>

Why inline onerror= rather than @error directive

error events don't bubble. A capture-phase listener attached by the component's <script client> IIFE runs AFTER the element's first load attempt, so cached 404s and offline first paint slip past. The inline HTML onerror= attribute is parsed-and-attached synchronously with the element by the browser's HTML parser, before the image request fires. This is the only race-free option for the error path.

Why a single window-level function rather than per-instance inline closures

Keeps the rendered HTML small (a 10-byte attribute vs. a 100-byte inline function body per <img>). The function is registered once on first SafeImage hydration; subsequent mounts no-op. Per-instance config travels via data-* attributes on the <img>, so the function stays stateless.

Why @stacksjs/stx (or the components package within stx)

  • It's a primitive HTML wrapper, not a domain-specific UI piece — every Stacks app eventually wants this.
  • The implementation is purely template + a tiny client snippet — no project-specific dependencies.
  • Pairing with the existing <Notification>, <Icon>, <StxLink> set keeps the "framework-provided component library" surface coherent.

API surface

PropDefaultNotes
src''required in practice
alt''passthrough
fallbackconfigurable framework default (e.g. /images/safe-image-default.svg)per-instance override
className''class string at load time
fallbackClassName'' (empty → keep className)class string to swap to on error — useful for grayscale/blur-up-style load classes that shouldn't apply to the placeholder

Test surface (minimal)

  • src that returns 200 → renders as <img src=... class=...>, no swap.
  • src that 404s → onerror fires, src swaps to fallback, className swaps if fallbackClassName provided.
  • fallback that also 404s → guarded by __stx_fallback_applied, no infinite loop.
  • Multiple instances on the page → only one window handler registered.

What this lets the framework deprecate

The global broken-image-handler pattern that every Stacks app reinvents. Bench-review removed ~25 lines of IIFE code from a layout component once the migration was complete.

Happy to open a PR if there's interest — the file is already written and battle-tested locally.

Sign in to comment on this issue.