{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "expandable-text",
  "title": "Expandable Text",
  "author": "ilinxa",
  "description": "Truncating text block — plain or rich children — that shows its toggle only when text overflows; configurable clamp, bidi-safe, controlled or uncontrolled.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/components/data/expandable-text/expandable-text.tsx",
      "content": "\"use client\";\n\nimport { memo, useCallback, useId, useMemo, useState } from \"react\";\nimport type { FocusEvent, ReactNode } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  defaultExpandableTextLabels,\n  type ExpandableTextLabels,\n  type ExpandableTextProps,\n} from \"./types\";\nimport { useLineClampDetect } from \"./hooks/use-line-clamp-detect\";\n\n/** Nothing React would render (`null`, `false`, `\"\"`, empty arrays…). */\nconst isEmptyNode = (node: ReactNode): boolean =>\n  node === null ||\n  node === undefined ||\n  typeof node === \"boolean\" ||\n  node === \"\" ||\n  (Array.isArray(node) && node.every(isEmptyNode));\n\nconst UNCLAMP_WITHOUT_TOGGLE =\n  \"print:overflow-visible! print:max-h-none! print:[-webkit-line-clamp:unset]! [@media(scripting:none)]:overflow-visible! [@media(scripting:none)]:max-h-none! [@media(scripting:none)]:[-webkit-line-clamp:unset]!\";\n\n/** Merge `labels` over the defaults — an `undefined` key never erases a default (C2). */\nfunction resolveLabels(labels: ExpandableTextLabels | undefined): Required<ExpandableTextLabels> {\n  return {\n    showMore: labels?.showMore ?? defaultExpandableTextLabels.showMore,\n    showLess: labels?.showLess ?? defaultExpandableTextLabels.showLess,\n  };\n}\n\nfunction ExpandableTextInner({\n  content,\n  children,\n  measureKey,\n  maxLines = 3,\n  dir = \"auto\",\n  expanded: expandedProp,\n  defaultExpanded = false,\n  onExpandedChange,\n  labels: labelsProp,\n  renderToggle,\n  className,\n  contentClassName,\n  toggleClassName,\n}: ExpandableTextProps) {\n  const labels = useMemo(() => resolveLabels(labelsProp), [labelsProp]);\n\n  const isControlled = expandedProp !== undefined;\n  const [expandedState, setExpandedState] = useState(defaultExpanded);\n  const expanded = isControlled ? expandedProp : expandedState;\n\n  const setExpanded = useCallback(\n    (next: boolean) => {\n      if (!isControlled) setExpandedState(next);\n      onExpandedChange?.(next);\n    },\n    [isControlled, onExpandedChange],\n  );\n\n  const rich = !isEmptyNode(children);\n  // Re-measure on a new `content` or `measureKey`; rich children are also watched for DOM changes.\n  const measureTrigger = useMemo(() => [content, measureKey], [content, measureKey]);\n  const { ref, isTruncated, isMeasured } = useLineClampDetect({\n    maxLines,\n    content: measureTrigger,\n    observeMutations: rich,\n  });\n  const contentId = useId();\n\n  // Clamped from the first paint (the server cannot measure) — no full-text flash and layout\n  // shift on hydration. After measuring, text that fits is unclamped (nothing to clip).\n  const isClamped = !expanded && (isTruncated || !isMeasured);\n  const showToggle = isTruncated;\n\n  // Keyboard focus moving onto a link BELOW the clamp would land on hidden content: expand instead\n  // (controlled: ask the parent). A link on a visible line, or a mouse click, does not expand.\n  const handleFocus = useCallback(\n    (e: FocusEvent<HTMLElement>) => {\n      if (expanded || !isTruncated) return;\n      const target = e.target as Element;\n      let keyboard = false;\n      try {\n        keyboard = target.matches(\":focus-visible\");\n      } catch {\n        // `:focus-visible` unsupported — treat as pointer focus.\n      }\n      if (!keyboard) return;\n      const box = e.currentTarget;\n      // Browsers scroll the clipped box to reveal the focused element BEFORE `focus` fires, so a\n      // scrolled box is the signal; the geometry check covers engines that do not scroll it.\n      const hidden =\n        box.scrollTop > 0 || target.getBoundingClientRect().bottom > box.getBoundingClientRect().bottom + 1;\n      if (!hidden) return;\n      box.scrollTop = 0;\n      setExpanded(true);\n    },\n    [expanded, isTruncated, setExpanded],\n  );\n\n  if (!rich && !content) return null;\n\n  const Content = rich ? \"div\" : \"p\";\n\n  return (\n    <div className={cn(className)}>\n      <Content\n        ref={ref}\n        id={contentId}\n        dir={dir}\n        onFocus={handleFocus}\n        className={cn(\n          \"text-sm leading-relaxed whitespace-pre-wrap wrap-break-word\",\n          // Printing, or a browser without scripting (no toggle can run): show everything.\n          UNCLAMP_WITHOUT_TOGGLE,\n          contentClassName,\n        )}\n        style={{\n          display: \"-webkit-box\",\n          WebkitBoxOrient: \"vertical\",\n          WebkitLineClamp: isClamped ? maxLines : \"unset\",\n          // `-webkit-line-clamp` does not hold for block children (two <p> clamp at ~4.6 lines):\n          // bound rich content by its line height too. Inline children keep the ellipsis.\n          maxHeight: isClamped && rich ? `${maxLines}lh` : undefined,\n          overflow: isClamped ? \"hidden\" : \"visible\",\n        }}\n      >\n        {rich ? children : content}\n      </Content>\n      {showToggle &&\n        (renderToggle ? (\n          renderToggle({ isExpanded: expanded, setExpanded })\n        ) : (\n          <button\n            type=\"button\"\n            onClick={() => setExpanded(!expanded)}\n            aria-expanded={expanded}\n            aria-controls={contentId}\n            className={cn(\n              \"mt-1 rounded-sm text-sm font-medium text-muted-foreground motion-safe:transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n              toggleClassName,\n            )}\n          >\n            {expanded ? labels.showLess : labels.showMore}\n          </button>\n        ))}\n    </div>\n  );\n}\n\nconst ExpandableText = memo(ExpandableTextInner);\nExpandableText.displayName = \"ExpandableText\";\n\nexport { ExpandableText };\nexport default ExpandableText;\n",
      "type": "registry:component",
      "target": "components/expandable-text/expandable-text.tsx"
    },
    {
      "path": "src/registry/components/data/expandable-text/index.ts",
      "content": "export { default as ExpandableText } from \"./expandable-text\";\n\nexport type {\n  ExpandableTextProps,\n  ExpandableTextLabels,\n  ExpandableTextToggleRenderProps,\n} from \"./types\";\n\nexport { DEFAULT_EXPANDABLE_TEXT_LABELS, defaultExpandableTextLabels } from \"./types\";\n\nexport {\n  useLineClampDetect,\n  type UseLineClampDetectOptions,\n  type UseLineClampDetectResult,\n} from \"./hooks/use-line-clamp-detect\";\n\n// @ilinxa/expandable-text 0.3.0\n",
      "type": "registry:component",
      "target": "components/expandable-text/index.ts"
    },
    {
      "path": "src/registry/components/data/expandable-text/types.ts",
      "content": "import type { ReactNode } from \"react\";\n\nexport interface ExpandableTextLabels {\n  /** Default: \"Show more\". Toggle button label when collapsed. */\n  showMore?: string;\n  /** Default: \"Show less\". Toggle button label when expanded. */\n  showLess?: string;\n}\n\nexport interface ExpandableTextToggleRenderProps {\n  /** Current expanded state. */\n  isExpanded: boolean;\n  /** Setter — handles controlled-or-uncontrolled internally. */\n  setExpanded: (next: boolean) => void;\n}\n\nexport interface ExpandableTextProps {\n  /**\n   * Plain-text content. Rendered in a `<p>`. Ignored when `children` is given. The component renders\n   * nothing when there is neither non-empty `content` nor renderable `children`.\n   */\n  content?: string | null;\n\n  /**\n   * Rich content — your own link / mention renderer. Wins over `content`. Rendered in a `<div>`, so block\n   * children (a `<p>` per paragraph) are valid. Changes inside it are re-measured automatically; pass\n   * `measureKey` for changes that alter no DOM (a web font finishing loading).\n   */\n  children?: ReactNode;\n\n  /** Re-measure the clamp whenever this value changes. */\n  measureKey?: unknown;\n\n  /** Number of lines before truncation. Default: 3. */\n  maxLines?: number;\n\n  /** Text direction of the content element. Default: \"auto\" (bidi isolation — an Arabic post in an LTR feed starts at the right). */\n  dir?: \"auto\" | \"ltr\" | \"rtl\";\n\n  // ─── Controlled-or-uncontrolled expanded state ──────────────────\n  /** Controlled expanded state — wins on every render. Pair with `onExpandedChange`. */\n  expanded?: boolean;\n  /** Initial uncontrolled expanded state. Default: false. Ignored when `expanded` is provided. */\n  defaultExpanded?: boolean;\n  /**\n   * Fires on every requested expand/collapse with the NEXT state — the toggle, and keyboard focus moving\n   * into clamped content (which asks to expand, so focus never lands on hidden text).\n   */\n  onExpandedChange?: (next: boolean) => void;\n\n  // ─── Customization ────────────────────────────────\n  /** Localized labels. Defaults are English; an `undefined` key keeps its default. */\n  labels?: ExpandableTextLabels;\n  /** Custom toggle renderer — full takeover. Receives current state + setter. */\n  renderToggle?: (props: ExpandableTextToggleRenderProps) => ReactNode;\n\n  // ─── Style overrides ─────────────────────────────\n  /** Override classes for the wrapping <div>. */\n  className?: string;\n  /** Override classes for the content element (`<p>` for `content`, `<div>` for `children`). */\n  contentClassName?: string;\n  /** Override classes for the default toggle <button>. Ignored when `renderToggle` is provided. */\n  toggleClassName?: string;\n}\n\n/** Default English labels — exported for consumer composition. */\nexport const defaultExpandableTextLabels: Required<ExpandableTextLabels> = {\n  showMore: \"Show more\",\n  showLess: \"Show less\",\n};\n\n/** @deprecated Use `defaultExpandableTextLabels` — the same object under its old name. */\nexport const DEFAULT_EXPANDABLE_TEXT_LABELS: Required<ExpandableTextLabels> = defaultExpandableTextLabels;\n",
      "type": "registry:component",
      "target": "components/expandable-text/types.ts"
    },
    {
      "path": "src/registry/components/data/expandable-text/hooks/use-line-clamp-detect.ts",
      "content": "import { useEffect, useLayoutEffect, useState } from \"react\";\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nexport interface UseLineClampDetectOptions {\n  maxLines: number;\n  /**\n   * Re-measurement trigger. Hook never reads the value — only uses its\n   * identity to detect when re-measurement is needed. Pass a primitive\n   * (string, number), a content hash, or any stable identity that changes\n   * when the underlying text changes.\n   */\n  content: unknown;\n  /**\n   * Also re-measure when the element's DOM changes (text or children) — for rich\n   * children whose changes do not resize a clamped box. Default: false.\n   */\n  observeMutations?: boolean;\n}\n\nexport interface UseLineClampDetectResult {\n  /** Pass to your measured element: `<p ref={ref}>...</p>`. */\n  ref: (node: HTMLElement | null) => void;\n  /** True when the element's natural height exceeds `maxLines × lineHeight`. */\n  isTruncated: boolean;\n  /** False until the first measurement ran (always false on the server). */\n  isMeasured: boolean;\n}\n\n/** `line-height: normal` has no px value — approximate it the way browsers do (~1.2 × font size). */\nfunction lineHeightOf(el: HTMLElement): number {\n  const style = getComputedStyle(el);\n  const lh = parseFloat(style.lineHeight);\n  if (lh && !Number.isNaN(lh)) return lh;\n  const fs = parseFloat(style.fontSize);\n  return fs && !Number.isNaN(fs) ? fs * 1.2 : 0;\n}\n\n/**\n * Detect whether content overflows a line-clamp threshold.\n *\n * Measures `scrollHeight` against `lineHeight × maxLines` after mount and on\n * every container resize (via `ResizeObserver`), and — with `observeMutations` —\n * on DOM changes inside the element. Returns `isTruncated: true` only when the\n * content's natural height exceeds the budget — so consumers can hide their\n * \"show more\" toggle when content fits.\n *\n * The element is tracked via `useState` (not a `useRef` capture) so identity\n * changes — e.g., consumer attaches the ref to a `<p>` inside a list with\n * keys → re-mounts on reorder — re-trigger the observer setup.\n */\nexport function useLineClampDetect({\n  maxLines,\n  content,\n  observeMutations = false,\n}: UseLineClampDetectOptions): UseLineClampDetectResult {\n  const [el, setEl] = useState<HTMLElement | null>(null);\n  const [isTruncated, setIsTruncated] = useState(false);\n  const [isMeasured, setIsMeasured] = useState(false);\n\n  // Layout effect: the first measurement (and one after a content change) lands before paint, so\n  // text that grew while unclamped never paints a frame at full length.\n  useIsoLayoutEffect(() => {\n    if (!el) return;\n\n    const measure = () => {\n      const lineHeight = lineHeightOf(el);\n      // No usable line height (no layout engine, `font-size: 0`): treat as not truncated, so a\n      // caller that clamps until measured never leaves text cut off with no way to expand it.\n      const next = lineHeight ? el.scrollHeight > lineHeight * maxLines + 1 : false; // +1 sub-pixel slop\n      setIsTruncated((prev) => (prev === next ? prev : next));\n      setIsMeasured(true);\n    };\n\n    measure(); // initial synchronous measurement\n    const resize = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(measure);\n    resize?.observe(el);\n    const mutation =\n      observeMutations && typeof MutationObserver !== \"undefined\" ? new MutationObserver(measure) : null;\n    mutation?.observe(el, { childList: true, subtree: true, characterData: true });\n    return () => {\n      resize?.disconnect();\n      mutation?.disconnect();\n    };\n  }, [el, content, maxLines, observeMutations]);\n\n  return { ref: setEl, isTruncated, isMeasured };\n}\n",
      "type": "registry:component",
      "target": "components/expandable-text/hooks/use-line-clamp-detect.ts"
    }
  ],
  "meta": {
    "version": "0.3.0",
    "status": "alpha"
  },
  "categories": [
    "data"
  ],
  "type": "registry:block"
}