{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"text-reveal-preloader","type":"registry:component","title":"Text Reveal Preloader","description":"Words rise in letter by letter with a kinetic skew and swap one after another. The last word holds, lifts away, and the screen reveals your page.","dependencies":["framer-motion"],"files":[{"path":"registry/dot/text-reveal-preloader.tsx","type":"registry:component","target":"components/dot/text-reveal-preloader.tsx","content":"\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion, type TargetAndTransition } from \"framer-motion\";\n\nexport type TextRevealExitStyle = \"swipe-up\" | \"curtain-up\" | \"center-split\" | \"scale-through\" | \"fade-out\";\nexport type TextRevealSpeed = \"hyper\" | \"fast\" | \"editorial\" | \"relaxed\";\n\nexport interface TextRevealPreloaderProps {\n  /** Words shown one after another; the last one holds before the reveal */\n  words?: string[];\n  /** Pacing preset, or exact seconds per word */\n  speed?: TextRevealSpeed | number;\n  /** Seconds between letters rising in */\n  letterStagger?: number;\n  /** Degrees of skew and tilt on each letter as it rises; 0 for a clean rise */\n  skew?: number;\n  /** Seconds the last word rests once fully in */\n  holdDuration?: number;\n  /** Seconds after the last word starts lifting away before the reveal begins; below 0.5 they overlap */\n  revealDelay?: 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  /** Text size in px on a 1440px-wide screen; it scales down on narrower screens and never overflows */\n  fontSize?: number;\n  /** Line height in em */\n  lineHeight?: number;\n  /** Space between letters in em */\n  letterSpacing?: number;\n  /** Where the word sits horizontally */\n  align?: \"left\" | \"center\" | \"right\";\n  textTransform?: \"uppercase\" | \"none\" | \"lowercase\" | \"capitalize\";\n  backgroundColor?: string;\n  textColor?: string;\n  exitStyle?: TextRevealExitStyle;\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 DEFAULT_WORDS = [\"Uno\", \"dos\", \"tres\", \"Hala Madrid!\"];\nconst SPEEDS: Record<TextRevealSpeed, number> = { hyper: 0.52, fast: 0.72, editorial: 0.95, relaxed: 1.3 };\n\nconst ENTER_EASE = [0.22, 1, 0.36, 1] as const;\nconst LEAVE_EASE = [0.76, 0, 0.24, 1] as const;\nconst REVEAL_EASE = [0.85, 0, 0.15, 1] as const;\nconst LETTER_DURATION = 0.68;\nconst WORD_LEAVE = 0.5;\n\n// Inter by default: a next/font Inter variable when the site has one, else \"Inter\", else system sans\nconst INTER = 'var(--font-inter, \"Inter\"), system-ui, sans-serif';\n\nconst SESSION_KEY = \"dot-text-reveal-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\n// Adds the Google Fonts stylesheet once per family and weight; retries without the weight if the\n// family doesn't have it\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 so\n// text never becomes tiny\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\nfunction transform(word: string, mode: TextRevealPreloaderProps[\"textTransform\"]) {\n  if (mode === \"uppercase\") return word.toUpperCase();\n  if (mode === \"lowercase\") return word.toLowerCase();\n  if (mode === \"capitalize\") return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();\n  return word;\n}\n\n/** Width of the widest word in em, measured in the real font; re-measured when web fonts load */\nfunction useWidestWordEm(words: string[], font: string, weight: number, letterSpacing: number) {\n  const [em, setEm] = useState<number | null>(null);\n  const key = words.join(\"\\u0000\");\n  useLayoutEffect(() => {\n    const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n    if (!ctx) return;\n    const measure = () => {\n      ctx.font = `${weight} 100px ${font}`;\n      const widest = Math.max(...key.split(\"\\u0000\").map((w) => ctx.measureText(w).width / 100 + w.length * letterSpacing), 1);\n      setEm(widest);\n    };\n    measure();\n    document.fonts?.addEventListener(\"loadingdone\", measure);\n    return () => document.fonts?.removeEventListener(\"loadingdone\", measure);\n  }, [key, font, weight, letterSpacing]);\n  return em;\n}\n\ntype Phase = \"words\" | \"leaving\" | \"revealing\" | \"done\";\n\n/**\n * Fullscreen preloader: words rise in letter by letter with a kinetic skew, swap one after another,\n * the last one holds and lifts away, then the screen reveals the page. Pauses while offscreen.\n */\nexport function TextRevealPreloader({\n  words = DEFAULT_WORDS,\n  speed = \"editorial\",\n  letterStagger = 0.045,\n  skew = 6,\n  holdDuration = 0.8,\n  revealDelay = 0.4,\n  googleFont = \"BBH Bogle\",\n  fontFamily = INTER,\n  fontWeight = 400,\n  fontSize = 76,\n  lineHeight = 0.94,\n  letterSpacing = 0,\n  align = \"center\",\n  textTransform = \"uppercase\",\n  backgroundColor = \"#780116\",\n  textColor = \"#F7B538\",\n  exitStyle = \"curtain-up\",\n  exitDuration = 0.95,\n  fullscreen = true,\n  lockScroll = true,\n  showOncePerSession = false,\n  zIndex = 9999,\n  onComplete,\n  className,\n}: TextRevealPreloaderProps) {\n  const reduceMotion = useReducedMotion() ?? false;\n  const deck = words.map((w) => w.trim()).filter(Boolean);\n  const list = (deck.length ? deck : DEFAULT_WORDS).map((w) => transform(w, textTransform));\n  const last = list.length - 1;\n  const perWord = typeof speed === \"number\" ? Math.max(0.2, speed) : SPEEDS[speed] ?? SPEEDS.editorial;\n\n  const [index, setIndex] = useState(0);\n  const [phase, setPhase] = useState<Phase>(\"words\");\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 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  // Largest size at which the widest word still fits 88% of the width\n  const widest = useWidestWordEm(list, font, fontWeight, letterSpacing);\n  const widestEm = widest ?? Math.max(...list.map((w) => w.length)) * 0.7;\n  const fitWidth = (88 / widestEm).toFixed(2);\n  const size = `clamp(24px, min(${fitWidth}cqw, ${fluidCss(fontSize, 0.35)}, 30cqh), ${fontSize}px)`;\n\n  const shownThisSession = useSyncExternalStore(noopSubscribe, readShownThisSession, () => false);\n  const skipped = showOncePerSession && shownThisSession && phase === \"words\" && index === 0;\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  // Pause the words while offscreen; once leaving, always finish (a curtain or scale exit moves the\n  // preloader itself out of view, which must not stall or restart it)\n  const paused = phase === \"words\" && !inView;\n\n  // One step at a time: next word → hold the last → lift it away → reveal → done\n  useEffect(() => {\n    if (skipped || paused || phase === \"done\") return;\n    let ms: number;\n    let next: () => void;\n    if (phase === \"words\" && index < last) {\n      ms = perWord * 1000;\n      next = () => setIndex((i) => i + 1);\n    } else if (phase === \"words\") {\n      const entrance = reduceMotion ? 0.3 : LETTER_DURATION + Math.max(0, list[last].length - 1) * letterStagger;\n      ms = (entrance + holdDuration) * 1000;\n      next = () => setPhase(\"leaving\");\n    } else if (phase === \"leaving\") {\n      // Measured from the start of the lift, so the reveal follows the word without an empty pause\n      ms = Math.max(0, revealDelay) * 1000;\n      next = () => setPhase(\"revealing\");\n    } else {\n      ms = exitDuration * 1000 + 80;\n      next = () => {\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      };\n    }\n    const timer = setTimeout(next, ms);\n    return () => clearTimeout(timer);\n    // list[last] only matters through its length\n  }, [phase, index, last, paused, skipped, perWord, holdDuration, revealDelay, exitDuration, letterStagger, reduceMotion, showOncePerSession, list[last]?.length]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  if (phase === \"done\" || skipped) return null;\n\n  const revealing = phase === \"revealing\";\n  const split = exitStyle === \"center-split\";\n  const reveal: TargetAndTransition = !revealing\n    ? { clipPath: \"inset(0% 0% 0% 0%)\", y: \"0%\", scale: 1, opacity: 1 }\n    : reduceMotion || exitStyle === \"fade-out\"\n      ? { opacity: 0 }\n      : exitStyle === \"swipe-up\"\n        ? { clipPath: \"inset(0% 0% 100% 0%)\" }\n        : exitStyle === \"curtain-up\"\n          ? { y: \"-100%\" }\n          : exitStyle === \"scale-through\"\n            ? { scale: 1.25, opacity: 0 }\n            : {};\n\n  const panel: CSSProperties = { height: \"100%\", background: backgroundColor, willChange: \"transform\" };\n  const word = list[Math.min(index, last)];\n\n  return (\n    <motion.div\n      ref={rootRef}\n      role=\"status\"\n      aria-live=\"polite\"\n      aria-label=\"Loading\"\n      aria-busy={!revealing}\n      className={className}\n      initial={false}\n      animate={reveal}\n      transition={{ duration: revealing ? exitDuration : 0, ease: exitStyle === \"scale-through\" ? ENTER_EASE : REVEAL_EASE }}\n      style={{\n        position: fullscreen ? \"fixed\" : \"absolute\",\n        inset: 0,\n        zIndex,\n        overflow: \"hidden\",\n        containerType: \"size\",\n        background: split ? \"transparent\" : backgroundColor,\n        userSelect: \"none\",\n        WebkitUserSelect: \"none\",\n        pointerEvents: revealing ? \"none\" : \"auto\",\n        willChange: \"clip-path, transform, opacity\",\n      }}\n    >\n      {split && (\n        <div aria-hidden style={{ position: \"absolute\", inset: 0, display: \"flex\" }}>\n          <motion.div\n            initial={false}\n            animate={{ x: revealing && !reduceMotion ? \"-100%\" : \"0%\", opacity: revealing && reduceMotion ? 0 : 1 }}\n            transition={{ duration: exitDuration, ease: REVEAL_EASE }}\n            style={{ ...panel, width: \"calc(50% + 1.5px)\", marginRight: -1.5 }}\n          />\n          <motion.div\n            initial={false}\n            animate={{ x: revealing && !reduceMotion ? \"100%\" : \"0%\", opacity: revealing && reduceMotion ? 0 : 1 }}\n            transition={{ duration: exitDuration, ease: REVEAL_EASE }}\n            style={{ ...panel, width: \"50%\" }}\n          />\n        </div>\n      )}\n\n      <div\n        style={{\n          position: \"absolute\",\n          inset: 0,\n          zIndex: 1,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: align === \"left\" ? \"flex-start\" : align === \"right\" ? \"flex-end\" : \"center\",\n          padding: \"0 clamp(16px, 5cqw, 72px)\",\n          pointerEvents: \"none\",\n        }}\n      >\n        <AnimatePresence mode=\"wait\">\n          {phase !== \"revealing\" && (\n            <motion.div\n              key={index}\n              aria-label={word}\n              initial={false}\n              animate={phase === \"leaving\" ? { y: \"-125%\", opacity: 0 } : { y: \"0%\", opacity: 1 }}\n              exit={{ y: \"-125%\", opacity: 0, transition: { duration: 0.45, ease: LEAVE_EASE } }}\n              transition={{ duration: WORD_LEAVE, ease: LEAVE_EASE }}\n              style={{\n                display: \"flex\",\n                overflow: \"hidden\",\n                // Room for descenders and overhangs inside the mask\n                padding: \"0.06em 0.05em 0.1em\",\n                fontFamily: font,\n                fontWeight,\n                fontSize: size,\n                lineHeight,\n                letterSpacing: `${letterSpacing}em`,\n                color: textColor,\n                whiteSpace: \"pre\",\n                willChange: \"transform, opacity\",\n              }}\n            >\n              {[...word].map((char, i) => (\n                <motion.span\n                  key={i}\n                  aria-hidden\n                  initial={\n                    reduceMotion\n                      ? { opacity: 0 }\n                      : { y: \"135%\", skewY: skew, rotate: skew > 0 ? (i % 2 === 0 ? 3 : -3) : 0, scale: 0.9, opacity: 0 }\n                  }\n                  animate={{ y: \"0%\", skewY: 0, rotate: 0, scale: 1, opacity: 1 }}\n                  transition={\n                    reduceMotion ? { duration: 0.3 } : { duration: LETTER_DURATION, ease: ENTER_EASE, delay: i * letterStagger }\n                  }\n                  style={{ display: \"inline-block\", transformOrigin: \"bottom center\", willChange: \"transform, opacity\" }}\n                >\n                  {char === \" \" ? \" \" : char}\n                </motion.span>\n              ))}\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </motion.div>\n  );\n}\n"}],"docs":"Text Reveal Preloader is ready. Props and a live canvas: https://bydot.co/component/text-reveal-preloader","meta":{"tier":"free","category":"Preloaders","version":"1.0.0"}}