Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

11.9 KB
Raw Blame
import { useState, useEffect, useCallback, useRef } from 'react'
import { createPortal } from 'react-dom'
import { ChevronLeft, ChevronRight, Loader2, X, ZoomIn, ZoomOut } from 'lucide-react'
import VideoPlayer from './VideoPlayerLazy'
import { usePhotoZoom } from './usePhotoZoom'
import { Tooltip } from '../shared/Tooltip'
import { isRtlLanguage, useTranslation } from '../../i18n'
import { lockBodyScroll } from '../../utils/bodyScrollLock'

interface LightboxPhoto {
  id: string
  src: string
  /**
   * A small rendition of the same photo, usually cached already by the grid that
   * opened the lightbox. It stands in while the original loads, which on a slow
   * server or connection can take seconds (#2907).
   */
  thumbSrc?: string
  caption?: string | null
  /** Where the caption's credit points to (a photo's source page), opened in a new tab. */
  captionHref?: string | null
  provider?: string
  asset_id?: string | null
  owner_id?: number | null
  mediaType?: string | null
}

interface Props {
  photos: LightboxPhoto[]
  startIndex?: number
  onClose: () => void
  /** What the dialog is called for assistive tech. */
  label?: string
}

/** The round glass buttons of the top bar. */
const ROUND_BTN: React.CSSProperties = {
  background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
  width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center',
  color: '#fff', cursor: 'pointer', flex: 'none',
}

/** Close is the one every visitor needs: a little stronger than the rest. */
const CLOSE_BTN: React.CSSProperties = { ...ROUND_BTN, background: 'rgba(255,255,255,0.18)' }

/**
 * The device's insets, from whichever source reports them: env() in a browser,
 * the values Capacitor's SystemBars writes on Android, the ones the iOS app
 * measures itself. The viewer is portalled to <body>, outside the phone shell
 * that defines its own --m-safe-* tokens, so it reads the sources directly.
 */
const SAFE = (side: 'top' | 'bottom' | 'left' | 'right') =>
  `max(env(safe-area-inset-${side}, 0px), var(--safe-area-inset-${side}, 0px), var(--trek-native-safe-${side}, 0px))`

export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }: Props) {
  const [idx, setIdx] = useState(startIndex)
  const touchStart = useRef<{ x: number; y: number } | null>(null)
  const dialogRef = useRef<HTMLDivElement>(null)
  const { t, language } = useTranslation()
  // Right to left, the next photo lies to the left: the arrow keys and swipes follow the reading direction.
  // Taken from the language, not read off <html dir>, so it stays put across re-renders.
  const rtl = isRtlLanguage(language)

  // Focus moves into the dialog when it opens and back to what opened it when it closes.
  useEffect(() => {
    const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
    dialogRef.current?.focus()
    const unlock = lockBodyScroll()
    return () => {
      unlock()
      opener?.focus()
    }
  }, [])

  const photo = photos[idx]
  // Zoom starts over on every photo (#1484).
  const zoom = usePhotoZoom(photo?.id)
  const isImage = !!photo && photo.mediaType !== 'video'
  // The id whose original has finished (or failed) loading; any other photo is still on its way.
  const [loadedId, setLoadedId] = useState<string | null>(null)
  const loading = isImage && loadedId !== photo.id
  const hasPrev = idx > 0
  const hasNext = idx < photos.length - 1

  const prev = useCallback(() => { if (hasPrev) setIdx(i => i - 1) }, [hasPrev])
  const next = useCallback(() => { if (hasNext) setIdx(i => i + 1) }, [hasNext])

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
      if (e.key === 'ArrowLeft') (rtl ? next : prev)()
      if (e.key === 'ArrowRight') (rtl ? prev : next)()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [prev, next, onClose, rtl])

  // A pinch, a double tap or a pan of an enlarged photo belongs to the zoom; only
  // the rest is a swipe that turns the page or closes the lightbox.
  const onTouchStart = (e: React.TouchEvent) => {
    if (isImage && zoom.touchStart(e)) { touchStart.current = null; return }
    const t = e.touches[0]
    touchStart.current = { x: t.clientX, y: t.clientY }
  }

  const onTouchMove = (e: React.TouchEvent) => {
    if (isImage && zoom.touchMove(e)) touchStart.current = null
  }

  const onTouchEnd = (e: React.TouchEvent) => {
    if (isImage && zoom.touchEnd(e)) { touchStart.current = null; return }
    if (!touchStart.current) return
    const t = e.changedTouches[0]
    const dx = t.clientX - touchStart.current.x
    const dy = t.clientY - touchStart.current.y

    // swipe down to close
    if (dy > 80 && Math.abs(dx) < 60) {
      onClose()
      return
    }
    // horizontal swipe
    if (Math.abs(dx) > 50 && Math.abs(dy) < 80) {
      if (dx < 0 !== rtl) next()
      else prev()
    }
    touchStart.current = null
  }

  if (!photo) return null

  // Portalled to <body>: inside a transformed sheet or pane, `fixed` would be
  // relative to that box and the viewer would open as a small window in it.
  return createPortal(
    <div
      ref={dialogRef}
      role="dialog"
      aria-modal="true"
      aria-label={label}
      tabIndex={-1}
      style={{
        outline: 'none',
        position: 'fixed', inset: 0, zIndex: 'var(--z-modal)',
        background: 'rgba(0,0,0,0.92)', backdropFilter: 'blur(20px)',
        display: 'flex', flexDirection: 'column',
        paddingBottom: SAFE('bottom'),
        // The insets belong to the screen's sides, which right to left swaps.
        paddingInlineStart: SAFE(rtl ? 'right' : 'left'),
        paddingInlineEnd: SAFE(rtl ? 'left' : 'right'),
      }}
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onTouchEnd}
    >
      {/* Top bar: its own row below the status bar and a notch, so the close
          button is always there to tap and never sits over the photo. */}
      <div style={{
        flex: 'none', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        paddingBlock: `calc(${SAFE('top')} + 10px) 10px`, paddingInline: 16,
      }}>
        <span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
          {idx + 1} / {photos.length}
        </span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {isImage && (
            <>
              <Tooltip label={t('journey.lightbox.zoomOut')}>
                <button type="button" onClick={zoom.zoomOut} disabled={!zoom.zoomed} aria-label={t('journey.lightbox.zoomOut')} style={{ ...ROUND_BTN, opacity: zoom.zoomed ? 1 : 0.4 }}>
                  <ZoomOut size={17} />
                </button>
              </Tooltip>
              {zoom.zoomed && (
                <Tooltip label={t('journey.lightbox.zoomReset')}>
                  <button type="button" onClick={zoom.reset} aria-label={t('journey.lightbox.zoomReset')}
                    style={{ ...ROUND_BTN, width: 'auto', borderRadius: 99, padding: '0 12px', fontSize: 'calc(12px * var(--fs-scale-caption, 1))', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
                    {Math.round(zoom.zoom.scale * 100)}%
                  </button>
                </Tooltip>
              )}
              <Tooltip label={t('journey.lightbox.zoomIn')}>
                <button type="button" onClick={zoom.zoomIn} disabled={!zoom.canZoomIn} aria-label={t('journey.lightbox.zoomIn')} style={{ ...ROUND_BTN, opacity: zoom.canZoomIn ? 1 : 0.4 }}>
                  <ZoomIn size={17} />
                </button>
              </Tooltip>
            </>
          )}
          <button type="button" onClick={onClose} aria-label={t('common.close')} style={CLOSE_BTN}>
            <X size={20} />
          </button>
        </div>
      </div>

      {/* Photo area: what is left below the bar, with the page arrows over it. */}
      <div
        className="group/lightbox"
        style={{ flex: 1, minHeight: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden', padding: '0 8px 8px' }}
      >
        {/* Prev button — visible on hover (desktop), always visible (mobile) */}
        {hasPrev && (
          <button type="button" onClick={prev} aria-label={t('journey.lightbox.previous')} className="flex sm:opacity-0 sm:group-hover/lightbox:opacity-100 focus-visible:opacity-100 transition-opacity" style={{
            position: 'absolute', insetInlineStart: 16, zIndex: 5,
            width: 44, height: 44, borderRadius: '50%',
            background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(8px)',
            border: '1px solid rgba(255,255,255,0.1)',
            alignItems: 'center', justifyContent: 'center',
            color: '#fff', cursor: 'pointer',
          }}>
            <ChevronLeft size={22} className="rtl:rotate-180" />
          </button>
        )}

        {/* Photo or video */}
        {photo.mediaType === 'video' ? (
          <VideoPlayer key={photo.id} src={photo.src} />
        ) : (
          <img
            key={photo.id}
            ref={zoom.imgRef}
            src={photo.src}
            alt={photo.caption || ''}
            draggable={false}
            onLoad={() => setLoadedId(photo.id)}
            onError={() => setLoadedId(photo.id)}
            {...zoom.mouse}
            style={{
              maxWidth: '100%', maxHeight: '100%',
              objectFit: 'contain', borderRadius: 4,
              animation: 'fadeIn 0.15s ease',
              userSelect: 'none',
              ...zoom.style,
            }}
          />
        )}

        {loading && (
          <div data-testid="lightbox-loading" aria-hidden="true" style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
            {photo.thumbSrc && (
              <img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 4 }} />
            )}
            <span style={{ ...ROUND_BTN, position: 'absolute', cursor: 'default' }}>
              <Loader2 size={18} className="animate-spin" />
            </span>
          </div>
        )}

        {/* Next button */}
        {hasNext && (
          <button type="button" onClick={next} aria-label={t('journey.lightbox.next')} className="flex sm:opacity-0 sm:group-hover/lightbox:opacity-100 focus-visible:opacity-100 transition-opacity" style={{
            position: 'absolute', insetInlineEnd: 16, zIndex: 5,
            width: 44, height: 44, borderRadius: '50%',
            background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(8px)',
            border: '1px solid rgba(255,255,255,0.1)',
            alignItems: 'center', justifyContent: 'center',
            color: '#fff', cursor: 'pointer',
          }}>
            <ChevronRight size={22} className="rtl:rotate-180" />
          </button>
        )}

        {/* Caption — bottom center overlay */}
        {photo.caption && (
          <div style={{ position: 'absolute', bottom: 20, insetInline: 0, zIndex: 5, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }}>
            <p style={{
              fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontStyle: 'italic',
              color: 'rgba(255,255,255,0.75)', margin: 0, lineHeight: 1.5, maxWidth: '70%', textAlign: 'center',
              background: 'rgba(0,0,0,0.3)', backdropFilter: 'blur(8px)',
              padding: '6px 14px', borderRadius: 10, pointerEvents: 'auto',
            }}>
              {photo.captionHref ? (
                <a href={photo.captionHref} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit' }} className="hover:underline">
                  {photo.caption}
                </a>
              ) : photo.caption}
            </p>
          </div>
        )}
      </div>
    </div>,
    document.body,
  )
}