{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"image-scroll-preloader","type":"registry:component","title":"Image Scroll Preloader","description":"Two columns of images scroll upward on either half of the screen while a small counter rises from bottom to top. At 100 the halves part to reveal your page.","dependencies":["framer-motion"],"files":[{"path":"registry/dot/image-scroll-preloader.tsx","type":"registry:component","target":"components/dot/image-scroll-preloader.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from \"react\";\nimport { animate, motion, useMotionValue, useReducedMotion, useTransform, type TargetAndTransition } from \"framer-motion\";\n\nexport type ImageScrollExitStyle = \"center-split\" | \"vertical-split\" | \"wipe-up\" | \"slide-down\" | \"zoom-blur\" | \"fade-out\";\nexport type ImageScrollSpeed = \"hyper\" | \"fast\" | \"editorial\" | \"relaxed\";\n\nexport interface ImageScrollPreloaderProps {\n  /** Images in the left column, top to bottom */\n  leftImages?: string[];\n  /** Images in the right column, top to bottom */\n  rightImages?: string[];\n  /** Speed preset, or exact seconds to count 0 → 100 */\n  speed?: ImageScrollSpeed | number;\n  /** Seconds to rest on 100 before the reveal */\n  holdDuration?: number;\n  /** Any Google Fonts family name, e.g. \"Space Grotesk\" — loaded automatically */\n  googleFont?: string;\n  /** CSS font stack, for fonts you load yourself (ignored when googleFont is set) */\n  fontFamily?: string;\n  fontWeight?: number;\n  /** Counter size in px on a 1440px-wide screen; it scales down on narrower screens */\n  counterFontSize?: number;\n  /** Line height in em */\n  lineHeight?: number;\n  /** Space between characters in em */\n  letterSpacing?: number;\n  counterColor?: string;\n  /** \"0%\" or \"00%\" */\n  counterFormat?: \"unpadded\" | \"padded\";\n  counterSuffix?: string;\n  /** Where the counter starts, in % from the top */\n  counterStart?: number;\n  /** Where the counter ends at 100, in % from the top */\n  counterEnd?: number;\n  /** Image width as a share of each half, in % */\n  columnWidth?: number;\n  /** Largest gap from the outer edge to the images, in px */\n  sidePadding?: number;\n  /** Vertical gap between images, as % of the height */\n  cardGap?: number;\n  /** Where the left column starts, as % of the height */\n  leftOffset?: number;\n  /** Where the right column starts, as % of the height */\n  rightOffset?: number;\n  /** Image width ÷ height */\n  aspectRatio?: number;\n  backgroundColor?: string;\n  exitStyle?: ImageScrollExitStyle;\n  /** Seconds for the reveal */\n  exitDuration?: number;\n  /** Cover the viewport (true) or fill the nearest positioned parent (false) */\n  fullscreen?: boolean;\n  /** Prevent page scrolling while the preloader is visible (fullscreen only) */\n  lockScroll?: boolean;\n  showOncePerSession?: boolean;\n  zIndex?: number;\n  onComplete?: () => void;\n  className?: string;\n}\n\nconst unsplash = (id: string) => `https://images.unsplash.com/${id}?q=80&w=1200&auto=format&fit=crop`;\nconst DEFAULT_LEFT_IMAGES = [unsplash(\"photo-1513694203232-719a280e022f\"), unsplash(\"photo-1486406146926-c627a92ad1ab\")];\nconst DEFAULT_RIGHT_IMAGES = [unsplash(\"photo-1544816155-12df9643f363\"), unsplash(\"photo-1509631179647-0177331693ae\")];\n\nconst SPEEDS: Record<ImageScrollSpeed, number> = { hyper: 1.6, fast: 2.4, editorial: 3.4, relaxed: 4.6 };\nconst EASE = [0.76, 0, 0.24, 1] as const;\n// How far the columns travel over the whole count, in heights of the preloader\nconst TRAVEL = 3.2;\n\nconst INTER = 'var(--font-inter, \"Inter\"), system-ui, sans-serif';\n\nconst SESSION_KEY = \"dot-image-scroll-preloader-shown\";\nconst noopSubscribe = () => () => {};\nfunction readShownThisSession() {\n  try {\n    return sessionStorage.getItem(SESSION_KEY) === \"true\";\n  } catch {\n    return false; // storage blocked: just play\n  }\n}\n\nconst googleFontUrl = (family: string, weight?: number) =>\n  `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family).replace(/%20/g, \"+\")}${weight ? `:wght@${weight}` : \"\"}&display=swap`;\n\nfunction loadGoogleFont(family: string, weight: number) {\n  const id = `dot-google-font-${family.toLowerCase().replace(/[^a-z0-9]+/g, \"-\")}-${weight}`;\n  if (document.getElementById(id)) return;\n  const link = document.createElement(\"link\");\n  link.id = id;\n  link.rel = \"stylesheet\";\n  link.href = googleFontUrl(family, weight);\n  link.onerror = () => {\n    link.onerror = null;\n    link.href = googleFontUrl(family);\n  };\n  document.head.appendChild(link);\n}\n\n// Sizes are set for a 1440px-wide screen and shrink with the container, keeping a fixed share\nconst DESIGN_WIDTH = 1440;\nconst fluidCss = (px: number, fixed: number) =>\n  `calc(${(px * fixed).toFixed(1)}px + ${((px * (1 - fixed) * 100) / DESIGN_WIDTH).toFixed(3)}cqw)`;\n\ntype Phase = \"counting\" | \"exiting\" | \"done\";\n\n/** Where each half goes when the page is revealed */\nfunction panelExit(style: ImageScrollExitStyle, side: \"left\" | \"right\", reduce: boolean): TargetAndTransition {\n  if (reduce || style === \"fade-out\") return { opacity: 0 };\n  switch (style) {\n    case \"center-split\":\n      return { x: side === \"left\" ? \"-100%\" : \"100%\" };\n    case \"vertical-split\":\n      return { y: side === \"left\" ? \"-100%\" : \"100%\" };\n    case \"wipe-up\":\n      return { y: \"-100%\" };\n    case \"slide-down\":\n      return { y: \"100%\" };\n    case \"zoom-blur\":\n      return { scale: 1.08, opacity: 0, filter: \"blur(12px)\" };\n  }\n}\n\n/**\n * Fullscreen preloader: two columns of images scroll upward on either half of the screen while a\n * small percentage counter rises from the bottom to the top. At 100 the halves part to reveal the\n * page. Sized to its own box, so it also works inline.\n */\nexport function ImageScrollPreloader({\n  leftImages = DEFAULT_LEFT_IMAGES,\n  rightImages = DEFAULT_RIGHT_IMAGES,\n  speed = \"editorial\",\n  holdDuration = 0.3,\n  googleFont,\n  fontFamily = INTER,\n  fontWeight = 600,\n  counterFontSize = 13,\n  lineHeight = 1,\n  letterSpacing = 0.1,\n  counterColor = \"#111116\",\n  counterFormat = \"unpadded\",\n  counterSuffix = \"%\",\n  counterStart = 92,\n  counterEnd = 8,\n  columnWidth = 72,\n  sidePadding = 64,\n  cardGap = 120,\n  leftOffset = 6,\n  rightOffset = 58,\n  aspectRatio = 1,\n  backgroundColor = \"#FFFFFF\",\n  exitStyle = \"vertical-split\",\n  exitDuration = 0.95,\n  fullscreen = true,\n  lockScroll = true,\n  showOncePerSession = false,\n  zIndex = 9999,\n  onComplete,\n  className,\n}: ImageScrollPreloaderProps) {\n  const reduceMotion = useReducedMotion() ?? false;\n  const duration = typeof speed === \"number\" ? Math.max(0.3, speed) : SPEEDS[speed] ?? SPEEDS.editorial;\n\n  const [phase, setPhase] = useState<Phase>(\"counting\");\n  const [display, setDisplay] = useState(0);\n  const [inView, setInView] = useState(true);\n  const rootRef = useRef<HTMLDivElement | null>(null);\n  const onCompleteRef = useRef(onComplete);\n  useEffect(() => {\n    onCompleteRef.current = onComplete;\n  });\n\n  const progress = useMotionValue(0);\n  const counterTop = useTransform(progress, (v) => `${counterStart - (v / 100) * (counterStart - counterEnd)}%`);\n  // Columns travel TRAVEL heights over the count; cqh keeps it relative to the preloader's own box\n  const columnY = useTransform(progress, (v) => `${-(v / 100) * TRAVEL * 100}cqh`);\n\n  const googleFamily = googleFont?.trim();\n  useEffect(() => {\n    if (googleFamily) loadGoogleFont(googleFamily, fontWeight);\n  }, [googleFamily, fontWeight]);\n  const font = googleFamily ? `\"${googleFamily.replace(/\"/g, \"\")}\", system-ui, sans-serif` : fontFamily;\n\n  const shownThisSession = useSyncExternalStore(noopSubscribe, readShownThisSession, () => false);\n  const skipped = showOncePerSession && shownThisSession && phase === \"counting\";\n  useEffect(() => {\n    if (skipped) onCompleteRef.current?.();\n  }, [skipped]);\n\n  useEffect(() => {\n    const node = rootRef.current;\n    if (!node || typeof IntersectionObserver === \"undefined\") return;\n    const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting), { threshold: 0.05 });\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  useEffect(() => {\n    if (!fullscreen || !lockScroll || phase === \"done\" || skipped) return;\n    const html = document.documentElement;\n    const previous = html.style.overflow;\n    html.style.overflow = \"hidden\";\n    return () => {\n      html.style.overflow = previous;\n    };\n  }, [fullscreen, lockScroll, phase, skipped]);\n\n  // Count 0 → 100 (resuming where it left off if it was paused offscreen), hold, then reveal\n  useEffect(() => {\n    if (phase !== \"counting\" || !inView || skipped) return;\n    let hold: ReturnType<typeof setTimeout> | undefined;\n    const unsubscribe = progress.on(\"change\", (v) => setDisplay(Math.min(100, Math.floor(v))));\n    const controls = animate(progress, 100, {\n      duration: Math.max(0.1, duration * (1 - progress.get() / 100)),\n      ease: EASE,\n      onComplete: () => {\n        setDisplay(100);\n        hold = setTimeout(() => setPhase(\"exiting\"), holdDuration * 1000);\n      },\n    });\n    return () => {\n      unsubscribe();\n      controls.stop();\n      clearTimeout(hold);\n    };\n  }, [phase, inView, skipped, progress, duration, holdDuration]);\n\n  useEffect(() => {\n    if (phase !== \"exiting\") return;\n    const timer = setTimeout(() => {\n      if (showOncePerSession) {\n        try {\n          sessionStorage.setItem(SESSION_KEY, \"true\");\n        } catch {\n          // ignore: worst case it shows again\n        }\n      }\n      setPhase(\"done\");\n      onCompleteRef.current?.();\n    }, exitDuration * 1000 + 80);\n    return () => clearTimeout(timer);\n  }, [phase, exitDuration, showOncePerSession]);\n\n  if (phase === \"done\" || skipped) return null;\n\n  const exiting = phase === \"exiting\";\n  const counterText = `${counterFormat === \"padded\" ? String(display).padStart(2, \"0\") : display}${counterSuffix}`;\n  const transition = { duration: exitDuration, ease: exitStyle === \"fade-out\" || reduceMotion ? (\"easeOut\" as const) : EASE };\n\n  const half = (side: \"left\" | \"right\") => {\n    const images = side === \"left\" ? leftImages : rightImages;\n    const column: CSSProperties = {\n      position: \"absolute\",\n      top: 0,\n      [side]: `clamp(12px, 4cqw, ${sidePadding}px)`,\n      width: `clamp(96px, ${columnWidth}%, 440px)`,\n      display: \"flex\",\n      flexDirection: \"column\",\n      gap: `${cardGap}cqh`,\n      paddingTop: `${side === \"left\" ? leftOffset : rightOffset}cqh`,\n      pointerEvents: \"none\",\n    };\n    return (\n      <motion.div\n        key={side}\n        initial={false}\n        animate={exiting ? panelExit(exitStyle, side, reduceMotion) : { x: \"0%\", y: \"0%\", scale: 1, opacity: 1, filter: \"blur(0px)\" }}\n        transition={exiting ? transition : { duration: 0 }}\n        style={{\n          position: \"absolute\",\n          top: 0,\n          [side]: 0,\n          // 1px overlap hides a hairline seam between the halves\n          width: side === \"left\" ? \"calc(50% + 1px)\" : \"50%\",\n          height: \"100%\",\n          background: backgroundColor,\n          overflow: \"hidden\",\n          willChange: \"transform, opacity\",\n        }}\n      >\n        <motion.div style={{ ...column, y: reduceMotion ? 0 : columnY, willChange: \"transform\" }}>\n          {images.map((src, i) => (\n            <div key={`${i}-${src}`} style={{ width: \"100%\", aspectRatio: String(aspectRatio), overflow: \"hidden\", background: \"rgba(0,0,0,0.05)\", flexShrink: 0 }}>\n              {/* eslint-disable-next-line @next/next/no-img-element -- any image URL, also in Framer */}\n              <img src={src} alt=\"\" draggable={false} loading=\"eager\" decoding=\"async\" style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\", display: \"block\" }} />\n            </div>\n          ))}\n        </motion.div>\n      </motion.div>\n    );\n  };\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"progressbar\"\n      aria-label=\"Loading\"\n      aria-valuemin={0}\n      aria-valuemax={100}\n      aria-valuenow={display}\n      aria-busy={!exiting}\n      className={className}\n      style={{\n        position: fullscreen ? \"fixed\" : \"absolute\",\n        inset: 0,\n        zIndex,\n        overflow: \"hidden\",\n        containerType: \"size\",\n        pointerEvents: exiting ? \"none\" : \"auto\",\n        userSelect: \"none\",\n        WebkitUserSelect: \"none\",\n      }}\n    >\n      {half(\"left\")}\n      {half(\"right\")}\n\n      <motion.div\n        aria-hidden\n        initial={false}\n        animate={exiting ? { opacity: 0, scale: 0.88 } : { opacity: 1, scale: 1 }}\n        transition={{ duration: exiting ? 0.35 : 0, ease: \"easeOut\" }}\n        style={{\n          position: \"absolute\",\n          left: \"50%\",\n          top: counterTop,\n          x: \"-50%\",\n          y: \"-50%\",\n          zIndex: 1,\n          color: counterColor,\n          fontFamily: font,\n          fontWeight,\n          fontSize: `clamp(${Math.min(11, counterFontSize)}px, ${fluidCss(counterFontSize, 0.6)}, ${counterFontSize}px)`,\n          lineHeight,\n          letterSpacing: `${letterSpacing}em`,\n          whiteSpace: \"nowrap\",\n          fontVariantNumeric: \"tabular-nums\",\n          pointerEvents: \"none\",\n          willChange: \"transform, opacity\",\n        }}\n      >\n        {counterText}\n      </motion.div>\n    </div>\n  );\n}\n"}],"docs":"Image Scroll Preloader is ready. Props and a live canvas: https://bydot.co/component/image-scroll-preloader","meta":{"tier":"free","category":"Preloaders","version":"1.0.0"}}