Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

18.8 KB
Raw Blame
{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tabs",
  "title": "Tabs",
  "description": "Horizontal tab navigation with fluid hover, animated pill selection indicator, and fluid font-weight transitions. Radix flavor.",
  "dependencies": [
    "@radix-ui/react-tabs",
    "motion",
    "lucide-react"
  ],
  "registryDependencies": [
    "utils",
    "https://www.fluidfunctionalism.com/r/springs.json",
    "https://www.fluidfunctionalism.com/r/font-weight.json",
    "https://www.fluidfunctionalism.com/r/shape-context.json",
    "https://www.fluidfunctionalism.com/r/icon-context.json",
    "https://www.fluidfunctionalism.com/r/use-fluid-hover.json",
    "https://www.fluidfunctionalism.com/r/size-context.json",
    "https://www.fluidfunctionalism.com/r/tokens.json"
  ],
  "files": [
    {
      "path": "registry/radix/tabs.tsx",
      "content": "\"use client\";\n\nimport {\n  useRef,\n  useState,\n  useCallback,\n  useEffect,\n  createContext,\n  useContext,\n  forwardRef,\n  type ReactNode,\n  type HTMLAttributes,\n} from \"react\";\nimport * as TabsPrimitive from \"@radix-ui/react-tabs\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport type { IconComponent } from \"@/lib/icon-context\";\nimport { cn } from \"@/lib/utils\";\nimport { spring } from \"@/lib/springs\";\nimport { fontWeights } from \"@/lib/font-weight\";\nimport { useShape } from \"@/lib/shape-context\";\nimport { SizeProvider, useSize, type SizeVariant } from \"@/lib/size-context\";\nimport { useFluidHover } from \"@/hooks/use-fluid-hover\";\n\ninterface TabsContextValue {\n  registerTab: (index: number, element: HTMLElement | null) => void;\n  hoveredIndex: number | null;\n  selectedIndex: number;\n  idPrefix: string | undefined;\n  activeLabel: boolean;\n}\n\nconst TabsContext = createContext<TabsContextValue | null>(null);\n\nfunction useTabs() {\n  const ctx = useContext(TabsContext);\n  if (!ctx) throw new Error(\"useTabs must be used within a Tabs\");\n  return ctx;\n}\n\ninterface TabsProps extends Omit<HTMLAttributes<HTMLDivElement>, \"onSelect\"> {\n  children: ReactNode;\n  selectedIndex: number;\n  onSelect: (index: number) => void;\n  idPrefix?: string;\n  /** When true, only the selected tab shows its text label. Requires icons on tabs. */\n  activeLabel?: boolean;\n  /** Pins the tabs to one step of the size ladder (default 36px, compact\n   *  28px — see /docs/sizes). Omitted, they follow the surrounding\n   *  SizeProvider. */\n  size?: SizeVariant;\n}\n\nconst Tabs = forwardRef<HTMLDivElement, TabsProps>(\n  ({ children, selectedIndex, onSelect, idPrefix, activeLabel = false, size, className, ...props }, ref) => {\n    const containerRef = useRef<HTMLDivElement>(null);\n    // Whether the pointer is over the list: a ref for blur, which reads it at\n    // the moment it runs, and the same flag as state for the render, which\n    // picks the hover pill's exit from it. Both flip in the same handlers.\n    const isMouseInside = useRef(false);\n    const [mouseInside, setMouseInside] = useState(false);\n    const shape = useShape();\n\n    const {\n      activeIndex: hoveredIndex,\n      setActiveIndex: setHoveredIndex,\n      itemRects: tabRects,\n      handlers,\n      registerItem,\n      measureItems: measureTabs,\n    } = useFluidHover(containerRef, { axis: \"x\" });\n\n    // Track tab elements locally so we can observe their individual resizes\n    const tabElementsRef = useRef(new Map<number, HTMLElement>());\n    const registerTab = useCallback(\n      (index: number, element: HTMLElement | null) => {\n        registerItem(index, element);\n        if (element) {\n          tabElementsRef.current.set(index, element);\n        } else {\n          tabElementsRef.current.delete(index);\n        }\n      },\n      [registerItem]\n    );\n\n    useEffect(() => {\n      measureTabs();\n    }, [measureTabs, children]);\n\n    // Observe individual tab buttons for resize (label expand/collapse in activeLabel mode)\n    useEffect(() => {\n      const elements = tabElementsRef.current;\n      if (elements.size === 0) return;\n      const ro = new ResizeObserver(() => measureTabs());\n      elements.forEach((el) => ro.observe(el));\n      return () => ro.disconnect();\n    }, [measureTabs, children]);\n\n    // Wrap handlers to track isMouseInside\n    const handleMouseMove = useCallback(\n      (e: React.MouseEvent) => {\n        isMouseInside.current = true;\n        setMouseInside(true);\n        handlers.onMouseMove(e);\n      },\n      [handlers]\n    );\n\n    const handleMouseLeave = useCallback(() => {\n      isMouseInside.current = false;\n      setMouseInside(false);\n      handlers.onMouseLeave();\n    }, [handlers]);\n\n    const [focusedIndex, setFocusedIndex] = useState<number | null>(null);\n\n    const selectedRect = tabRects[selectedIndex];\n    const hoverRect =\n      hoveredIndex !== null ? tabRects[hoveredIndex] : null;\n    const focusRect = focusedIndex !== null ? tabRects[focusedIndex] : null;\n    const isHoveringSelected = hoveredIndex === selectedIndex;\n    const isHovering = hoveredIndex !== null && !isHoveringSelected;\n\n    const root = (\n      <TabsContext.Provider\n        value={{ registerTab, hoveredIndex, selectedIndex, idPrefix, activeLabel }}\n      >\n        {/* Root is merged into List via `asChild` so a single <div> is\n            emitted. Radix owns\n            role=\"tablist\", roving tabindex, and Arrow/Home/End keyboard\n            navigation. Radix tab values are strings, so the numeric\n            selectedIndex is mapped through String()/Number().\n            `activationMode=\"manual\"` keeps manual activation: arrows move\n            focus, Enter/Space selects. */}\n        <TabsPrimitive.Root\n          asChild\n          value={String(selectedIndex)}\n          onValueChange={(value) => onSelect(Number(value))}\n          activationMode=\"manual\"\n        >\n          <TabsPrimitive.List\n            ref={(node: HTMLDivElement | null) => {\n              containerRef.current = node;\n              if (typeof ref === \"function\") ref(node);\n              else if (ref) (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;\n            }}\n            onMouseMove={handleMouseMove}\n            onMouseLeave={handleMouseLeave}\n            onFocus={(e: React.FocusEvent<HTMLDivElement>) => {\n              const indexAttr = (e.target as HTMLElement)\n                .closest(\"[data-fluid-hover-index]\")\n                ?.getAttribute(\"data-fluid-hover-index\");\n              if (indexAttr != null) {\n                const idx = Number(indexAttr);\n                setHoveredIndex(idx);\n                setFocusedIndex(\n                  (e.target as HTMLElement).matches(\":focus-visible\") ? idx : null\n                );\n              }\n            }}\n            onBlur={(e: React.FocusEvent<HTMLDivElement>) => {\n              if (containerRef.current?.contains(e.relatedTarget as Node)) return;\n              setFocusedIndex(null);\n              if (isMouseInside.current) return;\n              setHoveredIndex(null);\n            }}\n            className={cn(\n              // -mx-1 px-1 / -my-1 py-1 give the 2px-outset focus ring room\n              // to draw without being clipped by overflow-x-auto. The\n              // max-width allows for the negative margins: fit-content\n              // parents size against the margin box (8px narrower than the\n              // border box), so a plain max-w-full would clamp the list 8px\n              // too small and clip the first/last tab's ring.\n              \"relative flex items-center select-none overflow-x-auto max-w-[calc(100%_+_8px)] scrollbar-hide -mx-1 px-1 -my-1 py-1\",\n              className\n            )}\n            {...props}\n          >\n            {/* Selected pill */}\n            {selectedRect && (\n              <motion.div\n                className={cn(\"absolute bg-active pointer-events-none\", shape.bg)}\n                initial={false}\n                animate={{\n                  left: selectedRect.left,\n                  width: selectedRect.width,\n                  top: selectedRect.top,\n                  height: selectedRect.height,\n                  opacity: isHovering ? 0.8 : 1,\n                }}\n                transition={{\n                  ...spring.moderate,\n                  opacity: { duration: 0.08 },\n                }}\n              />\n            )}\n\n            {/* Hover pill */}\n            <AnimatePresence>\n              {hoverRect && !isHoveringSelected && selectedRect && (\n                <motion.div\n                  className={cn(\"absolute bg-active pointer-events-none\", shape.bg)}\n                  initial={{\n                    left: selectedRect.left,\n                    width: selectedRect.width,\n                    top: selectedRect.top,\n                    height: selectedRect.height,\n                    opacity: 0,\n                  }}\n                  animate={{\n                    left: hoverRect.left,\n                    width: hoverRect.width,\n                    top: hoverRect.top,\n                    height: hoverRect.height,\n                    opacity: 0.4,\n                  }}\n                  exit={\n                    !mouseInside && selectedRect\n                      ? {\n                          left: selectedRect.left,\n                          width: selectedRect.width,\n                          top: selectedRect.top,\n                          height: selectedRect.height,\n                          opacity: 0,\n                          transition: { ...spring.moderate, opacity: { duration: 0.06 } },\n                        }\n                      : { opacity: 0, transition: spring.fast.exit }\n                  }\n                  transition={{\n                    ...spring.fast,\n                    opacity: { duration: 0.08 },\n                  }}\n                />\n              )}\n            </AnimatePresence>\n\n            {/* Focus ring */}\n            <AnimatePresence>\n              {focusRect && (\n                <motion.div\n                  className={cn(\"absolute pointer-events-none z-20 border border-[color:var(--focus-ring,#6B97FF)]\", shape.focusRing)}\n                  initial={false}\n                  animate={{\n                    left: focusRect.left - 2,\n                    top: focusRect.top - 2,\n                    width: focusRect.width + 4,\n                    height: focusRect.height + 4,\n                  }}\n                  exit={{ opacity: 0, transition: spring.fast.exit }}\n                  transition={{\n                    ...spring.fast,\n                    opacity: { duration: 0.08 },\n                  }}\n                />\n              )}\n            </AnimatePresence>\n\n            {children}\n          </TabsPrimitive.List>\n        </TabsPrimitive.Root>\n      </TabsContext.Provider>\n    );\n\n    // A size prop pins every tab to one ladder step.\n    return size ? <SizeProvider size={size}>{root}</SizeProvider> : root;\n  }\n);\n\nTabs.displayName = \"Tabs\";\n\ninterface TabsItemProps extends HTMLAttributes<HTMLButtonElement> {\n  icon?: IconComponent;\n  label: string;\n  index: number;\n}\n\nconst TabsItem = forwardRef<HTMLButtonElement, TabsItemProps>(\n  ({ icon: Icon, label, index, className, ...props }, ref) => {\n    const internalRef = useRef<HTMLButtonElement | null>(null);\n    // The collapsing label animates to a MEASURED layout width, not \"auto\":\n    // framer resolves an \"auto\" target from the element's *visual*\n    // (transformed) size, so under a scaled ancestor (e.g. /demo's card) the\n    // spring overshoots to scale-x the real width and snaps when \"auto\"\n    // lands. offsetWidth and ResizeObserver are transform-immune — same\n    // setup as the accordions' height animation.\n    const [labelWidth, setLabelWidth] = useState<number | null>(null);\n    const labelRoRef = useRef<ResizeObserver | null>(null);\n    const measureLabel = useCallback((el: HTMLSpanElement | null) => {\n      labelRoRef.current?.disconnect();\n      labelRoRef.current = null;\n      if (!el) return;\n      const update = () => setLabelWidth(el.offsetWidth);\n      update();\n      labelRoRef.current = new ResizeObserver(update);\n      labelRoRef.current.observe(el);\n    }, []);\n    const shape = useShape();\n    const sizeClasses = useSize();\n    const { registerTab, hoveredIndex, selectedIndex, idPrefix, activeLabel } =\n      useTabs();\n\n    useEffect(() => {\n      registerTab(index, internalRef.current);\n      return () => registerTab(index, null);\n    }, [index, registerTab]);\n\n    const isSelected = selectedIndex === index;\n    const isActive = hoveredIndex === index || isSelected;\n    const collapseLabel = activeLabel && !!Icon;\n    const showLabel = !collapseLabel || isSelected;\n\n    const labelContent = (\n      // Both stacked spans carry the text-box trim so the invisible bold\n      // sizer and the visible label keep identical boxes.\n      <span\n        ref={measureLabel}\n        className={cn(\"inline-grid whitespace-nowrap\", sizeClasses.text)}\n      >\n        <span\n          className=\"col-start-1 row-start-1 invisible [text-box:trim-both_cap_alphabetic]\"\n          style={{ fontVariationSettings: fontWeights.semibold }}\n          aria-hidden=\"true\"\n        >\n          {label}\n        </span>\n        <span\n          className={cn(\n            \"col-start-1 row-start-1 transition-[color,font-variation-settings] duration-80 [text-box:trim-both_cap_alphabetic]\",\n            isActive ? \"text-foreground\" : \"text-muted-foreground\"\n          )}\n          style={{\n            fontVariationSettings: isSelected\n              ? fontWeights.semibold\n              : fontWeights.normal,\n          }}\n        >\n          {label}\n        </span>\n      </span>\n    );\n\n    return (\n      // Radix Trigger renders a native <button type=\"button\"> and wires\n      // role=\"tab\", aria-selected, roving tabindex, and activation for us.\n      // id/aria-controls are only overridden when an idPrefix is supplied so\n      // externally rendered TabsPanel elements stay linked.\n      <TabsPrimitive.Trigger\n        ref={(node: HTMLButtonElement | null) => {\n          internalRef.current = node;\n          if (typeof ref === \"function\") ref(node);\n          else if (ref) (ref as React.MutableRefObject<HTMLButtonElement | null>).current = node;\n        }}\n        value={String(index)}\n        data-fluid-hover-index={index}\n        id={idPrefix ? `${idPrefix}-tab-${index}` : undefined}\n        aria-controls={idPrefix ? `${idPrefix}-panel-${index}` : undefined}\n        aria-label={collapseLabel && !showLabel ? label : undefined}\n        className={cn(\n          // Fixed heights (was py-2 around a 19.5px line box ≈ 35.5px) so the\n          // text-box trim on the label doesn't shrink the tab. Standalone\n          // pills sit directly on the ladder's control height.\n          \"relative z-10 flex items-center cursor-pointer bg-transparent border-none outline-none\",\n          sizeClasses.control,\n          sizeClasses.px,\n          !collapseLabel && sizeClasses.gap,\n          shape.bg,\n          className\n        )}\n        {...props}\n      >\n        {Icon && (\n          <Icon\n            size={sizeClasses.icon}\n            strokeWidth={isActive ? 2 : 1.5}\n            className={cn(\n              \"shrink-0 transition-[color,stroke-width] duration-80\",\n              isActive ? \"text-foreground\" : \"text-muted-foreground\"\n            )}\n          />\n        )}\n        {collapseLabel ? (\n          <AnimatePresence initial={false}>\n            {showLabel && (\n              <motion.span\n                key=\"label\"\n                className=\"overflow-hidden\"\n                // Until the measurement lands, let CSS resolve the width\n                // instead of handing framer \"auto\": framer resolves an \"auto\"\n                // target from the element's *visual* size, so under a scaled\n                // ancestor (the /demo card, ~1.76x) it writes back a layout\n                // width that much too wide, then springs back down when the\n                // measured value arrives — the selected tab visibly pulses on\n                // arrival. Plain CSS auto is the true layout width, and the\n                // measured number that follows matches it exactly.\n                style={labelWidth == null ? { width: \"auto\" } : undefined}\n                initial={{ width: 0, opacity: 0, marginLeft: 0 }}\n                animate={{\n                  ...(labelWidth != null ? { width: labelWidth } : null),\n                  opacity: 1,\n                  // 8px matches the ladder's icon-to-label gap (gap-2); the\n                  // compact 6px is its own value, 2px wider than gap-1.\n                  marginLeft: sizeClasses.variant === \"compact\" ? 6 : 8,\n                }}\n                exit={{ width: 0, opacity: 0, marginLeft: 0 }}\n                transition={{\n                  ...spring.fast,\n                  opacity: { duration: 0.06 },\n                }}\n              >\n                {labelContent}\n              </motion.span>\n            )}\n          </AnimatePresence>\n        ) : (\n          labelContent\n        )}\n      </TabsPrimitive.Trigger>\n    );\n  }\n);\n\nTabsItem.displayName = \"TabsItem\";\n\ninterface TabsPanelProps extends HTMLAttributes<HTMLDivElement> {\n  index: number;\n  selectedIndex: number;\n  idPrefix: string;\n  children: ReactNode;\n}\n\n// Rendered outside <Tabs> at every call site, so it cannot use Radix's\n// Tabs.Content (which requires the Tabs.Root context). It stays a plain\n// tabpanel linked to its tab through the shared idPrefix.\nconst TabsPanel = forwardRef<HTMLDivElement, TabsPanelProps>(\n  ({ index, selectedIndex, idPrefix, children, className, ...props }, ref) => {\n    const isSelected = selectedIndex === index;\n\n    return (\n      <div\n        ref={ref}\n        id={`${idPrefix}-panel-${index}`}\n        role=\"tabpanel\"\n        aria-labelledby={`${idPrefix}-tab-${index}`}\n        hidden={!isSelected}\n        tabIndex={-1}\n        className={cn(\"outline-none\", className)}\n        {...props}\n      >\n        {isSelected && children}\n      </div>\n    );\n  }\n);\n\nTabsPanel.displayName = \"TabsPanel\";\n\nexport { Tabs, TabsItem, TabsPanel };\nexport default Tabs;\n",
      "type": "registry:ui",
      "target": "components/ui/tabs.tsx"
    }
  ],
  "css": {
    ".scrollbar-hide": {
      "-ms-overflow-style": "none",
      "scrollbar-width": "none"
    },
    ".scrollbar-hide::-webkit-scrollbar": {
      "display": "none"
    }
  },
  "docs": "Docs & live playground: https://www.fluidfunctionalism.com/docs/tabs. Craft notes, the color, layout and motion decisions to keep when you change it: https://github.com/mickadesign/fluid-functionalism/blob/main/skills/fluid-functionalism/references/craft.md#tabs.",
  "categories": [
    "components"
  ],
  "type": "registry:ui"
}