{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"resizable-text","type":"registry:component","title":"Resizable Text","description":"Words in a sentence you resize like a text layer in a design tool.","author":"DiMaac (HankTheTank) <https://dimaac.com>","dependencies":[],"files":[{"path":"registry/dimaac/resizable-text/resizable-text.tsx","type":"registry:component","target":"components/dimaac/resizable-text.tsx","content":"\"use client\";\n\nimport { useLayoutEffect, useRef, useState, type CSSProperties, type PointerEvent } from \"react\";\n\n// Words shown as a selected text layer in a design tool. Pull a corner and the text grows, push it back and it shrinks.\n// Hover it for a small toolbar above it that switches the font: the box glides to the new width while the old letters\n// fade out and the new ones fade in. A size readout sits under the box, like in Figma. The letters can arrive in\n// colour first and settle into ink.\n//\n// While a corner is held, the size is written straight onto the element once per frame (no re-render, no easing), so\n// the corner stays under the pointer. The words sit in a sentence, so they always grow to the right, and they stop\n// growing at the end of their line: they are never pushed down onto the next line, by a drag or by a wider font.\n\nexport type ResizableTextFont = {\n  /** A short id, e.g. \"serif\". */\n  id: string;\n  /** Its name for screen readers, e.g. \"Serif\". */\n  label: string;\n  /** The CSS font-family. */\n  family: string;\n  /** \"italic\" for an italic face. */\n  style?: \"normal\" | \"italic\";\n  /** Letter spacing, e.g. \"-0.01em\". */\n  letterSpacing?: string;\n};\n\nexport type ResizableTextProps = {\n  /** The words in the layer. */\n  children: string;\n  /** The starting size in px. A drag never makes it smaller than this. */\n  size?: number;\n  /** The largest size a drag can reach, in px. It also stops where the words would wrap. */\n  max?: number;\n  /** The fonts the toolbar switches between. The first one is the starting font. */\n  fonts?: ResizableTextFont[];\n  /** The colour of the frame, the corner handles and the size readout. */\n  color?: string;\n  /** The letters arrive as soft colour first, then settle into ink. */\n  reveal?: boolean;\n  /** Extra classes on the layer. */\n  className?: string;\n};\n\nexport const resizableTextFonts: ResizableTextFont[] = [\n  { id: \"serif\", label: \"Serif\", family: 'ui-serif, Georgia, \"Times New Roman\", serif', style: \"italic\", letterSpacing: \"0\" },\n  { id: \"sans\", label: \"Sans\", family: 'ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif', letterSpacing: \"-0.01em\" },\n  { id: \"mono\", label: \"Mono\", family: \"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\", letterSpacing: \"-0.03em\" },\n];\n\nconst MORPH = 450; // ms for the box to glide to a new font's width\nconst PAD = 8; // the layer's side padding (4 px each side) does not grow with the text\n\nconst corners = [\n  { id: \"tl\", x: -1, y: -1, cursor: \"nwse-resize\" },\n  { id: \"tr\", x: 1, y: -1, cursor: \"nesw-resize\" },\n  { id: \"bl\", x: -1, y: 1, cursor: \"nesw-resize\" },\n  { id: \"br\", x: 1, y: 1, cursor: \"nwse-resize\" },\n] as const;\n\nconst faceOf = (font: ResizableTextFont): CSSProperties => ({ fontFamily: font.family, fontStyle: font.style ?? \"normal\", letterSpacing: font.letterSpacing ?? \"normal\" });\n\nexport function ResizableText({ children, size: start = 17, max = 72, fonts = resizableTextFonts, color = \"#3b82f6\", reveal = true, className = \"\" }: ResizableTextProps) {\n  const list = fonts.length ? fonts : resizableTextFonts;\n  const [size, setSize] = useState(start);\n  const [dragging, setDragging] = useState(false);\n  const [base, setBase] = useState({ width: 0, height: 0 });\n  const [fontId, setFontId] = useState(list[0]!.id);\n  const [swaps, setSwaps] = useState(0);\n  const [ghost, setGhost] = useState<{ font: ResizableTextFont; id: number } | null>(null);\n  const box = useRef<HTMLSpanElement>(null);\n  const readout = useRef<HTMLSpanElement>(null);\n  const drag = useRef({ pointer: -1, size: start, from: start, sx: 1, sy: 1, w: 0, h: 0, startX: 0, startY: 0, x: 0, y: 0, max, frame: 0 });\n  const before = useRef<DOMRect | null>(null);\n  const settle = useRef<(() => void) | null>(null);\n  const font = list.find((option) => option.id === fontId) ?? list[0]!;\n\n  // Let go of a font glide early, so a resize never fights a fixed width\n  const release = () => settle.current?.();\n\n  const describe = (value: number, measured = base) =>\n    measured.width > 0 && value > start + 0.05 ? `${Math.round((measured.width * value) / start)} × ${Math.round((measured.height * value) / start)}` : \"Hug × Hug\";\n\n  // The size and the readout belong to the element itself, so nothing else ever writes over a drag in progress\n  useLayoutEffect(() => {\n    if (box.current && drag.current.pointer === -1) box.current.style.fontSize = `${size}px`;\n  }, [size]);\n  useLayoutEffect(() => {\n    if (readout.current && drag.current.pointer === -1) readout.current.textContent = describe(drag.current.size);\n  });\n\n  // One frame's worth of pointer movement: the drag along the box's diagonal decides how much wider it gets\n  const apply = () => {\n    const state = drag.current;\n    state.frame = 0;\n    const node = box.current;\n    if (!node || state.pointer === -1) return;\n    const dx = (state.x - state.startX) * state.sx;\n    const dy = (state.y - state.startY) * state.sy;\n    const grow = ((dx * state.w + dy * state.h) * state.w) / (state.w * state.w + state.h * state.h);\n    const next = Math.min(state.max, Math.max(start, (state.from * (state.w + grow - PAD)) / (state.w - PAD)));\n    if (Math.abs(next - state.size) < 0.01) return;\n    state.size = next;\n    node.style.fontSize = `${next}px`;\n    if (readout.current) readout.current.textContent = describe(next, { width: (state.w * start) / state.from, height: (state.h * start) / state.from });\n  };\n\n  const grab = (event: PointerEvent<HTMLElement>, dirX: number, dirY: number) => {\n    release();\n    const node = box.current;\n    const line = node?.parentElement;\n    if (!node || !line) return;\n    const state = drag.current;\n    cancelAnimationFrame(state.frame); // a drag whose release was missed never blocks the next one\n    event.preventDefault();\n    try {\n      event.currentTarget.setPointerCapture(event.pointerId);\n    } catch {\n      return; // not a live pointer, so there is nothing to follow\n    }\n    const rect = node.getBoundingClientRect();\n    const now = state.size;\n    const lineEnd = line.getBoundingClientRect().right;\n    Object.assign(state, {\n      pointer: event.pointerId,\n      from: now,\n      sx: dirX,\n      sy: dirY,\n      w: rect.width,\n      h: rect.height,\n      startX: event.clientX,\n      startY: event.clientY,\n      x: event.clientX,\n      y: event.clientY,\n      frame: 0,\n      // as wide as the rest of its line allows (3 px spare, so text rounding never tips it onto the next line)\n      max: Math.max(now, Math.min(max, (now * (lineEnd - rect.left - 3 - PAD)) / (rect.width - PAD))),\n    });\n    setBase({ width: (rect.width * start) / now, height: (rect.height * start) / now });\n    setDragging(true);\n  };\n\n  const pull = (event: PointerEvent<HTMLElement>) => {\n    const state = drag.current;\n    if (state.pointer !== event.pointerId) return;\n    state.x = event.clientX;\n    state.y = event.clientY;\n    if (!state.frame) state.frame = requestAnimationFrame(apply);\n  };\n\n  const letGo = (event: PointerEvent<HTMLElement>) => {\n    const state = drag.current;\n    if (state.pointer !== event.pointerId) return;\n    if (state.frame) {\n      cancelAnimationFrame(state.frame);\n      apply(); // the last movement still counts\n    }\n    state.pointer = -1;\n    setSize(state.size);\n    setDragging(false);\n  };\n\n  // The readout shows the layer's real size, measured when the pointer comes over it and again after a font switch\n  const measure = () => {\n    const rect = box.current?.getBoundingClientRect();\n    if (rect && drag.current.pointer === -1) setBase({ width: (rect.width * start) / drag.current.size, height: (rect.height * start) / drag.current.size });\n  };\n\n  // Remember the box as it is now, and the layout effect below glides it to the new font's size\n  const pick = (next: ResizableTextFont) => {\n    if (next.id === font.id || !box.current) return;\n    release();\n    before.current = box.current.getBoundingClientRect();\n    setGhost({ font, id: swaps + 1 });\n    setFontId(next.id);\n    setSwaps((count) => count + 1);\n  };\n\n  useLayoutEffect(() => {\n    const node = box.current;\n    const from = before.current;\n    if (!node || !from) return;\n    before.current = null;\n    node.style.transition = \"none\";\n    node.style.width = \"\";\n    node.style.height = \"\";\n    // Fonts are not the same width: at the same size a wider one may no longer fit on the line the words sit on. Then\n    // it comes down to the largest size that still fits there, so a font switch never drops the words onto the next\n    // line (or lifts them back up), whatever size they were dragged to.\n    const line = node.parentElement;\n    if (line) {\n      const room = line.getBoundingClientRect().right - from.left - 3;\n      const natural = node.getBoundingClientRect().width;\n      const now = drag.current.size;\n      const fit = Math.max(start, (now * (room - PAD)) / (natural - PAD));\n      if (natural > room + 0.5 && fit < now - 0.01) {\n        drag.current.size = fit;\n        node.style.fontSize = `${fit}px`;\n      }\n    }\n    const to = node.getBoundingClientRect();\n    const moves = Math.abs(to.width - from.width) > 0.5 ? \"width\" : Math.abs(to.height - from.height) > 0.5 ? \"height\" : null;\n    let fallback = 0;\n\n    // When the glide is over, the box goes back to sizing itself and the readout is measured again\n    const done = () => {\n      settle.current = null;\n      window.clearTimeout(fallback);\n      node.removeEventListener(\"transitionend\", ended);\n      node.classList.remove(\"is-morphing\");\n      node.style.transition = \"\";\n      node.style.width = \"\";\n      node.style.height = \"\";\n      const rect = node.getBoundingClientRect();\n      if (drag.current.pointer === -1) setBase({ width: (rect.width * start) / drag.current.size, height: (rect.height * start) / drag.current.size });\n    };\n    const ended = (event: TransitionEvent) => {\n      if (event.target === node && event.propertyName === moves) done();\n    };\n    if (!moves) {\n      done();\n      return;\n    }\n\n    node.classList.add(\"is-morphing\");\n    node.style.width = `${from.width}px`;\n    node.style.height = `${from.height}px`;\n    void node.offsetWidth; // start from the old size\n    node.style.transition = `width ${MORPH}ms var(--rt-glide), height ${MORPH}ms var(--rt-glide)`;\n    node.style.width = `${to.width}px`;\n    node.style.height = `${to.height}px`;\n    node.addEventListener(\"transitionend\", ended);\n    fallback = window.setTimeout(done, MORPH * 4); // in case the end event never comes\n    settle.current = done;\n    return () => {\n      window.clearTimeout(fallback);\n      node.removeEventListener(\"transitionend\", ended);\n    };\n  }, [fontId, start]);\n\n  return (\n    <span\n      ref={box}\n      className={`rt-layer ${dragging ? \"is-dragging\" : \"\"} ${className}`}\n      style={{ ...faceOf(font), \"--rt-color\": color } as CSSProperties}\n      onPointerEnter={measure}\n    >\n      <style href=\"dimaac-resizable-text\" precedence=\"default\">\n        {css}\n      </style>\n      <span className=\"rt-sr\">{children}</span>\n      <span className=\"rt-text\">\n        <span aria-hidden=\"true\" className={swaps ? (swaps % 2 ? \"rt-swap-a\" : \"rt-swap-b\") : undefined}>\n          {[...children].map((letter, index) => (\n            <span key={index} className={reveal ? \"rt-letter\" : undefined} style={{ \"--i\": index } as CSSProperties}>\n              {letter}\n            </span>\n          ))}\n        </span>\n        {ghost ? (\n          <span key={ghost.id} aria-hidden=\"true\" className=\"rt-ghost\" style={faceOf(ghost.font)} onAnimationEnd={() => setGhost(null)}>\n            {children}\n          </span>\n        ) : null}\n      </span>\n      {corners.map((corner) => (\n        <i\n          key={corner.id}\n          aria-hidden=\"true\"\n          className={`rt-handle rt-handle-${corner.id}`}\n          style={{ cursor: corner.cursor }}\n          onPointerDown={(event) => grab(event, corner.x, corner.y)}\n          onPointerMove={pull}\n          onPointerUp={letGo}\n          onPointerCancel={letGo}\n          onLostPointerCapture={letGo}\n        />\n      ))}\n      {list.length > 1 ? (\n        <span className=\"rt-bar\">\n          <span className=\"rt-fonts\" role=\"group\" aria-label=\"Font\">\n            {list.map((option) => (\n              <button key={option.id} type=\"button\" aria-pressed={font.id === option.id} aria-label={option.label} style={faceOf(option)} onClick={() => pick(option)}>\n                Aa\n              </button>\n            ))}\n          </span>\n        </span>\n      ) : null}\n      <span ref={readout} className=\"rt-readout\" aria-hidden=\"true\" />\n    </span>\n  );\n}\n\nconst DARK = `:where(html[data-theme=\"dark\"],html.dark)`;\n\nconst css = `\n.rt-layer {\n  --rt-glide: cubic-bezier(0.2, 0.8, 0.2, 1);\n  position: relative;\n  display: inline-block;\n  padding: 0 4px;\n  line-height: 1.05;\n  white-space: nowrap;\n  box-shadow: 0 0 0 1px var(--rt-color);\n  transition: opacity 0.3s;\n}\n.rt-layer:hover,\n.rt-layer.is-dragging {\n  z-index: 6;\n}\n.rt-sr {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  overflow: hidden;\n  clip-path: inset(50%);\n  white-space: nowrap;\n}\n.rt-text {\n  position: relative;\n  display: block;\n}\n.rt-layer.is-morphing .rt-text {\n  overflow: clip;\n  overflow-clip-margin: 3px;\n}\n.rt-letter {\n  animation:\n    rt-tint-fade 0.3s ease-out backwards,\n    rt-tint-in 0.7s cubic-bezier(0.55, 0.085, 0.68, 0.53) backwards;\n  animation-delay: calc(0.4s + var(--i) * 0.03s);\n}\n@keyframes rt-tint-fade {\n  from { opacity: 0; }\n}\n@keyframes rt-tint-in {\n  from {\n    color: transparent;\n    text-shadow: 0 0 8px hsl(calc(180 + var(--i) * 15) 100% 60%);\n  }\n}\n.rt-swap-a { animation: rt-swap-a 0.4s var(--rt-glide); }\n.rt-swap-b { animation: rt-swap-b 0.4s var(--rt-glide); }\n@keyframes rt-swap-a {\n  from { opacity: 0.3; filter: blur(5px); }\n}\n@keyframes rt-swap-b {\n  from { opacity: 0.3; filter: blur(5px); }\n}\n.rt-ghost {\n  position: absolute;\n  top: 0;\n  left: 0;\n  white-space: nowrap;\n  pointer-events: none;\n  animation: rt-ghost-out 0.32s ease-out forwards;\n}\n@keyframes rt-ghost-out {\n  to { opacity: 0; filter: blur(4px); }\n}\n.rt-bar {\n  position: absolute;\n  bottom: 100%;\n  left: 50%;\n  z-index: 7;\n  display: flex;\n  padding-bottom: 12px;\n  font-size: 11px;\n  line-height: 1;\n  letter-spacing: 0;\n  white-space: nowrap;\n  opacity: 0;\n  pointer-events: none;\n  transform: translate(-50%, 3px);\n  transition: opacity 0.2s, transform 0.3s var(--rt-glide);\n}\n.rt-layer:hover .rt-bar,\n.rt-layer.is-dragging .rt-bar,\n.rt-layer:has(:focus-visible) .rt-bar {\n  opacity: 1;\n  pointer-events: auto;\n  transform: translate(-50%, 0);\n}\n.rt-fonts {\n  display: flex;\n  gap: 2px;\n  padding: 3px;\n  border-radius: 9px;\n  background: #fff;\n  box-shadow: 0 0 0 1px rgb(0 0 0 / 0.08), 0 8px 18px -10px rgb(0 0 0 / 0.3);\n}\n.rt-fonts button {\n  display: grid;\n  place-items: center;\n  width: 28px;\n  height: 22px;\n  padding: 0;\n  border: 0;\n  border-radius: 6px;\n  background: none;\n  color: #a1a19d;\n  font-size: 12px;\n  line-height: 1;\n  cursor: pointer;\n  transition: background-color 0.2s, color 0.2s;\n}\n.rt-fonts button:hover,\n.rt-fonts button[aria-pressed=\"true\"] {\n  color: #161615;\n}\n.rt-fonts button[aria-pressed=\"true\"] {\n  background: #f2f2ef;\n}\n.rt-handle {\n  position: absolute;\n  z-index: 8;\n  width: 7px;\n  height: 7px;\n  border: 1px solid var(--rt-color);\n  background: #fff;\n  touch-action: none;\n}\n.rt-handle::before {\n  content: \"\";\n  position: absolute;\n  inset: -9px;\n}\n.rt-handle-tl { top: -4px; left: -4px; }\n.rt-handle-tr { top: -4px; right: -4px; }\n.rt-handle-bl { bottom: -4px; left: -4px; }\n.rt-handle-br { right: -4px; bottom: -4px; }\n.rt-readout {\n  position: absolute;\n  top: calc(100% + 7px);\n  left: 50%;\n  z-index: 7;\n  padding: 3px 5px;\n  border-radius: 3px;\n  background: var(--rt-color);\n  color: #fff;\n  font: normal 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;\n  letter-spacing: 0;\n  white-space: nowrap;\n  pointer-events: none;\n  opacity: 0;\n  transform: translate(-50%, -2px);\n  transition: opacity 0.2s, transform 0.3s var(--rt-glide);\n}\n.rt-layer:hover .rt-readout,\n.rt-layer.is-dragging .rt-readout,\n.rt-layer:has(:focus-visible) .rt-readout {\n  opacity: 1;\n  transform: translate(-50%, 0);\n}\n${DARK} .rt-fonts {\n  background: #1f1f1d;\n  box-shadow: 0 0 0 1px rgb(255 255 255 / 0.1), 0 8px 18px -10px rgb(0 0 0 / 0.6);\n}\n${DARK} .rt-fonts button {\n  color: #7d7d78;\n}\n${DARK} .rt-fonts button:hover,\n${DARK} .rt-fonts button[aria-pressed=\"true\"] {\n  color: #ededea;\n}\n${DARK} .rt-fonts button[aria-pressed=\"true\"] {\n  background: #2c2c2a;\n}\n${DARK} .rt-handle {\n  background: #111110;\n}\n@media (prefers-reduced-motion: reduce) {\n  .rt-letter, .rt-swap-a, .rt-swap-b { animation: none; }\n  .rt-ghost { display: none; }\n  .rt-layer, .rt-bar, .rt-readout, .rt-fonts button { transition-duration: 0.01ms; }\n}\n`;\n"}],"categories":["text","resize","typography","design-tool","interactive"],"docs":"import { ResizableText } from \"@/components/dimaac/resizable-text\". Give its parent a size: it fills it. Docs, playground and props: https://ui.dimaac.com/components/resizable-text","meta":{"tier":"free","preview":"https://ui.dimaac.com/components/resizable-text","credits":[]}}