# Tag

> Tinted capsule label for category and status, with a removable variant.

Docs: https://plumbago.ochotzas.com/components/tag

## Installation

```sh
npx plumbago add tag
```

This copies `components/ui/tag.tsx` into your project, along with `cn`, `spring`.

## Usage

```tsx
import { Tag } from "@/components/ui/tag"

<Tag variant="success">Paid</Tag>
```

## Examples

### Preview

```tsx
import { Tag } from "@/components/ui/tag"
import { Check, Clock, Info, TriangleAlert } from "lucide-react"

export default function TagDemo() {
  return (
    <div className="flex flex-wrap justify-center gap-2">
      <Tag variant="success" icon={<Check strokeWidth={2} aria-hidden="true" />}>
        Paid
      </Tag>
      <Tag variant="warning" icon={<Clock strokeWidth={2} aria-hidden="true" />}>
        Due soon
      </Tag>
      <Tag variant="danger" icon={<TriangleAlert strokeWidth={2} aria-hidden="true" />}>
        Overdue
      </Tag>
      <Tag variant="info" icon={<Info strokeWidth={2} aria-hidden="true" />}>
        New
      </Tag>
      <Tag variant="neutral">Draft</Tag>
    </div>
  )
}
```

### Categories

```tsx
import { Tag } from "@/components/ui/tag"

export default function TagCategories() {
  return (
    <div className="flex flex-wrap justify-center gap-2">
      <Tag variant="slate">Lunch</Tag>
      <Tag variant="sage">Vegan</Tag>
      <Tag variant="sand">Bakery</Tag>
      <Tag variant="clay">Grill</Tag>
      <Tag variant="rose">Dessert</Tag>
      <Tag variant="lilac">Seasonal</Tag>
    </div>
  )
}
```

### Removable

```tsx
import { Button } from "@/components/ui/button"
import { Tag } from "@/components/ui/tag"
import { useState } from "react"

const initialDiets = ["Vegan", "Gluten free", "Nut free", "Halal"]

export default function TagRemovable() {
  const [diets, setDiets] = useState(initialDiets)

  return (
    <div className="flex min-h-11 flex-wrap items-center justify-center gap-2">
      {diets.map((diet) => (
        <Tag key={diet} variant="sage" onRemove={() => setDiets((current) => current.filter((item) => item !== diet))}>
          {diet}
        </Tag>
      ))}
      {diets.length === 0 && (
        <Button variant="plain" size="sm" onClick={() => setDiets(initialDiets)}>
          Reset diets
        </Button>
      )}
    </div>
  )
}
```

### In list rows

```tsx
import { Island, ListRow, ListRowSubtitle, ListRowText, ListRowTitle } from "@/components/ui/island"
import { Tag } from "@/components/ui/tag"
import { Check, Clock } from "lucide-react"
import { useState } from "react"

const startingMenus = [
  { id: "tasting", name: "Tasting menu, seven courses", when: "Friday and Saturday", live: true },
  { id: "autumn", name: "Autumn dessert menu", when: "Starts next week", live: false },
  { id: "brunch", name: "Weekend brunch", when: "Saturday and Sunday", live: true },
]

export default function TagInListRows() {
  const [menus, setMenus] = useState(startingMenus)

  const toggle = (id: string) => {
    setMenus((current) => current.map((menu) => (menu.id === id ? { ...menu, live: !menu.live } : menu)))
  }

  return (
    <Island variant="list" className="w-full max-w-md">
      {menus.map((menu) => (
        <ListRow key={menu.id} render={<button type="button" />} onClick={() => toggle(menu.id)}>
          <ListRowText>
            <ListRowTitle>{menu.name}</ListRowTitle>
            <ListRowSubtitle>{menu.when}</ListRowSubtitle>
          </ListRowText>
          {menu.live ? (
            <Tag variant="success" icon={<Check strokeWidth={2} aria-hidden="true" />}>
              Live
            </Tag>
          ) : (
            <Tag variant="warning" icon={<Clock strokeWidth={2} aria-hidden="true" />}>
              Soon
            </Tag>
          )}
        </ListRow>
      ))}
    </Island>
  )
}
```

## Source

```tsx
import { cn } from "@/lib/cn"
import { springEasing } from "@/lib/spring"
import { type ComponentProps, type ReactNode, useId, useLayoutEffect, useRef, useState } from "react"

const leaveMs = 260
const changeMs = 350

const prefersReducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

function neighbourRemoveButton(tag: HTMLElement) {
  const tags = [...(tag.parentElement?.querySelectorAll<HTMLElement>(":scope > [data-slot=tag]:not([data-leaving])") ?? [])]
  const index = tags.indexOf(tag)
  const neighbour = tags[index + 1] ?? tags[index - 1]
  return neighbour?.querySelector<HTMLButtonElement>("[data-slot=tag-remove]") ?? null
}

const variants = {
  neutral: "bg-track text-ink",
  slate: "bg-cat-slate-tint text-cat-slate-text",
  sage: "bg-cat-sage-tint text-cat-sage-text",
  sand: "bg-cat-sand-tint text-cat-sand-text",
  clay: "bg-cat-clay-tint text-cat-clay-text",
  rose: "bg-cat-rose-tint text-cat-rose-text",
  lilac: "bg-cat-lilac-tint text-cat-lilac-text",
  success: "bg-success-tint text-success",
  warning: "bg-warning-tint text-warning",
  danger: "bg-danger-tint text-danger",
  info: "bg-accent-tint text-accent",
}

export type TagVariant = keyof typeof variants

export type TagProps = Omit<ComponentProps<"span">, "className"> & {
  variant?: TagVariant
  icon?: ReactNode
  onRemove?: () => void
  removeLabel?: string
  className?: string
}

export function Tag({ variant = "neutral", icon, onRemove, removeLabel, className, children, ...props }: TagProps) {
  const rootRef = useRef<HTMLSpanElement>(null)
  const [leaving, setLeaving] = useState(false)
  const removable = onRemove !== undefined
  const text = typeof children === "string" || typeof children === "number" ? String(children) : null
  const label = removeLabel ?? text ?? "tag"
  const look = `${variant}:${text ?? ""}`
  const previousLook = useRef(look)

  useLayoutEffect(() => {
    const root = rootRef.current
    if (previousLook.current === look) return
    previousLook.current = look
    if (!root || typeof root.animate !== "function") return
    const keyframes = prefersReducedMotion()
      ? [{ opacity: 0.4 }, { opacity: 1 }]
      : [
          { opacity: 0.4, filter: "blur(3px)", transform: "scale(0.92)" },
          { opacity: 1, filter: "blur(0px)", transform: "none" },
        ]
    root.animate(keyframes, { duration: changeMs, easing: springEasing(root) })
  }, [look])

  function remove() {
    const root = rootRef.current
    if (!root || leaving || !onRemove) return
    const focusTarget = root.contains(document.activeElement) ? neighbourRemoveButton(root) : null
    const finish = () => {
      onRemove()
      focusTarget?.focus()
    }
    setLeaving(true)
    if (typeof root.animate !== "function") {
      finish()
      return
    }
    const gap = Number.parseFloat(getComputedStyle(root.parentElement ?? root).columnGap) || 0
    const width = root.offsetWidth
    const { paddingInlineStart, paddingInlineEnd } = getComputedStyle(root)
    const keyframes = prefersReducedMotion()
      ? [{ opacity: 1 }, { opacity: 0 }]
      : [
          { opacity: 1, filter: "blur(0px)", transform: "scale(1)", width: `${width}px`, paddingInlineStart, paddingInlineEnd, marginInlineEnd: "0px" },
          {
            opacity: 0,
            filter: "blur(3px)",
            transform: "scale(0.9)",
            width: "0px",
            paddingInlineStart: "0px",
            paddingInlineEnd: "0px",
            marginInlineEnd: `${-gap}px`,
          },
        ]
    const leave = root.animate(keyframes, { duration: leaveMs, easing: "cubic-bezier(0.4, 0, 0.2, 1)", fill: "forwards" })
    leave.finished.then(finish, () => {})
  }

  return (
    <span
      ref={rootRef}
      data-slot="tag"
      data-variant={variant}
      data-leaving={leaving ? "" : undefined}
      className={cn(
        "inline-flex items-center gap-1 rounded-full font-semibold tracking-[0.01em] whitespace-nowrap transition-colors duration-base ease-out data-leaving:pointer-events-none data-leaving:overflow-hidden",
        removable ? "h-7 pr-1 pl-2.5 text-[13px] leading-none" : "h-[22px] px-2 text-caption leading-none",
        variants[variant],
        className,
      )}
      {...props}
    >
      {icon && (
        <span
          aria-hidden="true"
          className="-ml-px grid shrink-0 place-items-center [&_svg]:size-3 [&_svg]:fill-none [&_svg]:stroke-current [&_svg]:[stroke-width:2.2]"
        >
          {icon}
        </span>
      )}
      {children}
      {removable && <TagRemove label={label} onRemove={remove} />}
    </span>
  )
}

function TagRemove({ label, onRemove }: { label: string; onRemove: () => void }) {
  const maskId = useId()
  return (
    <button
      type="button"
      data-slot="tag-remove"
      aria-label={`Remove ${label}`}
      onClick={onRemove}
      className="group/remove relative grid size-5 shrink-0 cursor-pointer place-items-center rounded-full after:absolute after:-inset-3 after:content-['']"
    >
      <svg
        viewBox="0 0 16 16"
        aria-hidden="true"
        className="size-4 opacity-55 transition-opacity duration-fast ease-out group-hover/remove:opacity-85 group-active/remove:opacity-100"
      >
        <mask id={maskId}>
          <rect width="16" height="16" fill="white" />
          <path d="m5.5 5.5 5 5m0-5-5 5" stroke="black" strokeWidth="1.6" strokeLinecap="round" />
        </mask>
        <circle cx="8" cy="8" r="8" fill="currentColor" mask={`url(#${maskId})`} />
      </svg>
    </button>
  )
}
```
