{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-card",
  "type": "registry:ui",
  "title": "react-tw/card.tsx",
  "description": "Carbon `Card` (preview in Carbon) as React + Tailwind components, the look and rules of `<ui-card>`: a `$layer` box Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [
    "@purpurabog/ui@^2.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/core-overflow",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-icon-button",
    "@kanok-ui/tw-menu",
    "@kanok-ui/tw-refs",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/card.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/card.tsx",
      "content": "import { Children, createContext, isValidElement, useContext, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ComponentProps, type KeyboardEvent, type MouseEvent, type ReactElement, type ReactNode, type Ref } from 'react';\nimport { Card as CardPrimitive } from '@purpurabog/ui/headless';\nimport { visibleCount } from '../core/overflow.ts';\nimport { IconButton } from './icon-button.tsx';\nimport { useTranslation } from './lib/i18n.ts';\nimport { useMergedRefs } from './lib/refs.ts';\nimport { cn } from './lib/utils.ts';\nimport { MenuItem, OverflowMenu } from './menu.tsx';\n\n/**\n * Carbon `Card` (preview in Carbon) as React + Tailwind components, the look and rules of `<ui-card>`: a `$layer` box\n * — no border, no shadow, square — built from `CardMedia`, `CardHeader` (`CardHeaderMedia`, `CardTitleMedia`,\n * `CardTitle`, `CardActions`), `CardBody` and `CardFooter` (`CardAction`s); it follows the `Layer` it sits on.\n * Beyond Carbon (whose card has no chosen state): `selected` gives a clickable card a checked `SelectableTile`'s look\n * (the same `--ui-tile-selected-*` tokens) and `aria-pressed` — the app toggles it — and `hideFooterIcon` drops the arrow.\n */\n\nexport type CardDensity = 'productive' | 'expressive';\nexport type CardMediaRatio = '16x9' | '9x16' | '2x1' | '1x2' | '4x3' | '3x4' | '3x2' | '2x3' | '1x1';\n\ninterface CardState {\n    /** Linked or clickable: the whole card is one control (no footer, as Carbon; header actions still show, against Carbon's guideline). */\n    linked: boolean;\n    disabled: boolean;\n    horizontal: boolean;\n    density: CardDensity;\n}\nconst CardContext = createContext<CardState>({ linked: false, disabled: false, horizontal: false, density: 'productive' });\n\ninterface HeaderState {\n    afterMedia: boolean;\n    besideActions: boolean;\n}\nconst HeaderContext = createContext<HeaderState>({ afterMedia: false, besideActions: false });\n\nexport interface CardProps extends Omit<ComponentProps<'div'>, 'ref' | 'onClick'> {\n    /** The card: its `<a>` with `href`, else the box. */\n    ref?: Ref<HTMLElement>;\n    /** Makes the whole card one link. */\n    href?: string;\n    target?: '_self' | '_blank';\n    /** Makes the whole card one button (`onClick`, Enter, Space). Name it with `aria-label`. */\n    clickable?: boolean;\n    onClick?: (event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>) => void;\n    disabled?: boolean;\n    density?: CardDensity;\n    /** The media beside the content. */\n    horizontal?: boolean;\n    mediaPosition?: 'start' | 'end';\n    /** Replaces the clickable card's arrow. */\n    footerIcon?: ReactNode;\n    /** Removes the clickable card's arrow footer (beyond Carbon). */\n    hideFooterIcon?: boolean;\n    /** A clickable card shown chosen, as a checked selectable tile, with `aria-pressed` (beyond Carbon; the app toggles it). */\n    selected?: boolean;\n    lang?: string;\n}\n\n// Carbon's ArrowRight (16)\nconst arrowRight = (\n    <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" className=\"block size-4 fill-current\">\n        <path d=\"M9.3 3.7 13.1 7.5H1v1h12.1l-3.8 3.8.7.7 5-5-5-5z\" />\n    </svg>\n);\n\nconst isMedia = (child: ReactNode) => isValidElement(child) && child.type === CardMedia;\n\n/** A horizontal card: the media beside a column of the rest. */\nfunction besideMedia(children: ReactNode, mediaPosition: 'start' | 'end') {\n    const all = Children.toArray(children);\n    const media = all.filter(isMedia);\n    const content = (\n        <div key=\"content\" className=\"flex min-w-0 flex-1 basis-0 flex-col\">\n            {all.filter((child) => !isMedia(child))}\n        </div>\n    );\n    return mediaPosition === 'end' ? [content, ...media] : [...media, content];\n}\n\n/** Carbon .cds--card: a layer box; clickable adds the tile border, hover / active fills and the ring on focus. */\nfunction cardClasses({ clickable, disabled, horizontal, selected, className }: { clickable: boolean; disabled: boolean; horizontal: boolean; selected: boolean; className?: string }) {\n    const chosen = clickable && !disabled && selected;\n    return cn(\n        // Carbon: square, a border only when clickable; the card settings (--ui-card-*) let a design round and outline every card\n        'relative box-border block h-full ui-card-edge rounded-[var(--ui-card-radius,0px)] [overflow:var(--ui-card-overflow,visible)] bg-[var(--ui-card-background,var(--ui-surface-1))] text-ink ui-card-type no-underline outline-[length:var(--ui-focus-width,2px)] outline-solid outline-transparent forced-colors:border forced-colors:border-solid forced-colors:border-[CanvasText]',\n        clickable && !disabled && 'cursor-pointer [border:var(--ui-card-clickable-border,1px_solid_var(--ui-border-tile-1))] transition-[background-color] duration-(--ui-duration-moderate) ease-carbon hover:bg-ghost-hover focus:outline-focus focus:not-focus-visible:outline-[color:var(--ui-pointer-focus,var(--ui-focus))] focus:outline-offset-0 active:bg-ghost-active',\n        // selected (beyond Carbon): the chosen look of a checked SelectableTile, its tokens and values\n        chosen &&\n            '[border:1px_solid_var(--ui-tile-selected-border,var(--ui-layer-selected-inverse))] bg-[color:var(--ui-tile-selected-background,var(--ui-highlight,var(--ui-card-background)))] hover:bg-[color:var(--ui-tile-selected-hover,var(--ui-tile-selected-background,var(--ui-highlight,var(--ui-card-background))))] active:bg-[color:var(--ui-tile-selected-hover,var(--ui-tile-selected-background,var(--ui-highlight,var(--ui-card-background))))]',\n        disabled && 'cursor-not-allowed border-border-disabled text-ink-disabled',\n        horizontal && 'flex flex-row items-stretch',\n        className,\n    );\n}\n\n/** Carbon `Card`. */\nexport function Card({ href, target = '_self', clickable = false, onClick, disabled = false, density = 'productive', horizontal = false, mediaPosition = 'start', footerIcon, hideFooterIcon = false, selected, lang, className, children, ref, ...rest }: Readonly<CardProps>) {\n    const t = useTranslation(lang).common;\n    const linked = clickable || !!href;\n    const state = useMemo<CardState>(() => ({ linked, disabled, horizontal, density }), [linked, disabled, horizontal, density]);\n    const classes = cardClasses({ clickable, disabled, horizontal, selected: !!selected, className });\n    // aria-pressed on the button (not a link), only once `selected` is used: else the markup stays as Carbon's\n    const asButton = clickable && !(href && !disabled);\n    const pressed = asButton && selected !== undefined ? { 'aria-pressed': selected } : {};\n    const inner = (\n        <>\n            {horizontal ? besideMedia(children, mediaPosition) : children}\n            {clickable && !hideFooterIcon ? (\n                <div aria-hidden=\"true\" className={cn('flex items-center justify-end p-4 text-icon-interactive', disabled && 'text-icon-disabled', '[&_svg]:block [&_svg]:size-4 [&_svg]:fill-current')}>\n                    {footerIcon ?? arrowRight}\n                </div>\n            ) : null}\n        </>\n    );\n    const external = !!href && !disabled && target === '_blank';\n    return (\n        <CardContext.Provider value={state}>\n            <CardPrimitive.Root {...rest} {...pressed} ref={ref} href={href} target={target} clickable={clickable} onClick={onClick} disabled={disabled} className={classes}>\n                {inner}\n                {external ? <span className=\"sr-only\">{t.opensInNewTab}</span> : null}\n            </CardPrimitive.Root>\n        </CardContext.Provider>\n    );\n}\n\nexport interface CardMediaProps extends ComponentProps<'div'> {\n    ratio?: CardMediaRatio;\n    /** A horizontal card's media width (Carbon's default 33.33%). */\n    mediaWidth?: string;\n}\n\n/** Carbon `CardMedia`: an image or video filling the card's width at `ratio`, or beside the content. */\nexport function CardMedia({ ratio, mediaWidth = '33.33%', className, style, children, ...rest }: Readonly<CardMediaProps>) {\n    const { horizontal } = useContext(CardContext);\n    const own: CSSProperties = horizontal ? { flexBasis: mediaWidth } : { aspectRatio: ratio ? ratio.replace('x', ' / ') : undefined };\n    return (\n        <div {...rest} style={{ ...own, ...style }} className={cn('block w-full [&>*]:block [&>*]:size-full [&>*]:object-cover', horizontal && 'w-auto shrink-0 self-stretch overflow-hidden', className)}>\n            {children}\n        </div>\n    );\n}\n\n/** Carbon `CardHeader`: media, title media, the title and its actions on a grid. */\nexport function CardHeader({ className, children, ...rest }: Readonly<ComponentProps<'div'>>) {\n    const all = Children.toArray(children);\n    const has = (type: unknown) => all.some((child) => isValidElement(child) && child.type === type);\n    const afterMedia = has(CardTitleMedia);\n    const besideActions = has(CardActions);\n    const value = useMemo(() => ({ afterMedia, besideActions }), [afterMedia, besideActions]);\n    return (\n        <HeaderContext.Provider value={value}>\n            <div {...rest} className={cn('relative grid grid-cols-[auto_minmax(0,1fr)] gap-y-0 [container-type:inline-size]', className)}>\n                {children}\n            </div>\n        </HeaderContext.Provider>\n    );\n}\n\n/** Carbon `CardHeaderMedia`: media across the top of the header (16px in, at most 64px tall). */\nexport function CardHeaderMedia({ className, ...rest }: Readonly<ComponentProps<'div'>>) {\n    return <div {...rest} className={cn('col-span-full my-4 ms-4 flex max-h-16 items-start justify-start', className)} />;\n}\n\n/** Carbon `CardTitleMedia`: media before the title, e.g. a 48–64px logo. */\nexport function CardTitleMedia({ className, ...rest }: Readonly<ComponentProps<'div'>>) {\n    return <div {...rest} className={cn('col-start-1 mt-4 flex max-h-16 shrink-0 items-start justify-center px-4', className)} />;\n}\n\n/** false = wrap, true = one line with an ellipsis, a number = that many lines. */\ntype Truncate = boolean | number;\nconst truncateClasses = (value: Truncate) => cn(value === true && 'truncate', typeof value === 'number' && 'line-clamp-(--_lines)');\nconst linesStyle = (value: Truncate) => (typeof value === 'number' ? ({ '--_lines': String(value) } as CSSProperties) : undefined);\n\nexport interface CardTitleProps extends Omit<ComponentProps<'div'>, 'ref'> {\n    ref?: Ref<HTMLDivElement>;\n    label?: ReactNode;\n    description?: ReactNode;\n    titleTruncate?: Truncate;\n    labelTruncate?: Truncate;\n    descriptionTruncate?: Truncate;\n    /** A truncated title's widest. */\n    maxWidth?: string;\n    /** An icon before / after the title. */\n    titleStart?: ReactNode;\n    titleEnd?: ReactNode;\n}\n\n/** Carbon `CardTitle`: a label above, the title (heading-compact-02, or heading-03 when expressive) and a description below. */\nexport function CardTitle({ label, description, titleTruncate = false, labelTruncate = false, descriptionTruncate = false, maxWidth = '100%', titleStart, titleEnd, className, children, ref, ...rest }: Readonly<CardTitleProps>) {\n    const { density, disabled } = useContext(CardContext);\n    const { afterMedia, besideActions } = useContext(HeaderContext);\n    const muted = cn('text-ink-muted type-caption leading-4!', disabled && 'text-ink-disabled');\n    const titleType = density === 'expressive' ? 'type-subhead' : 'text-base leading-[22px] font-semibold tracking-normal';\n    return (\n        <div\n            {...rest}\n            ref={ref}\n            className={cn('col-start-2 m-4 flex min-w-0 flex-col gap-0.5', afterMedia && 'ms-0', besideActions && 'max-w-[calc(50cqw-8px)]', className)}\n        >\n            {label ? (\n                <div className={cn(muted, truncateClasses(labelTruncate))} style={linesStyle(labelTruncate)}>\n                    {label}\n                </div>\n            ) : null}\n            <span\n                className={cn('block text-ink', titleType, disabled && 'text-ink-disabled', titleStart != null && 'flex items-start gap-2', truncateClasses(titleTruncate))}\n                style={titleTruncate === false ? undefined : { maxWidth, ...linesStyle(titleTruncate) }}\n            >\n                {/* Carbon keeps the (empty) start-icon box with its 2px top margin, so the row is 2px taller than its line */}\n                <span className=\"mt-0.5 flex shrink-0\">{titleStart}</span>\n                {children}\n                {titleEnd == null ? null : <span className=\"ms-2 inline-flex items-center align-middle\">{titleEnd}</span>}\n            </span>\n            {description ? (\n                <div className={cn(muted, truncateClasses(descriptionTruncate))} style={linesStyle(descriptionTruncate)}>\n                    {description}\n                </div>\n            ) : null}\n        </div>\n    );\n}\n\nexport interface CardBodyProps extends ComponentProps<'div'> {\n    /** No padding. */\n    isFlush?: boolean;\n}\n\n/** Carbon `CardBody`: body-compact-01 with 16px padding. */\nexport function CardBody({ isFlush = false, className, ...rest }: Readonly<CardBodyProps>) {\n    const { disabled, horizontal } = useContext(CardContext);\n    return <div {...rest} className={cn('block text-ink type-body-sm leading-[18px]!', !isFlush && 'p-4', disabled && 'text-ink-disabled', horizontal && 'flex-[1_0_auto]', className)} />;\n}\n\n/** Carbon `CardFooter`: content with 16px padding, or a row of `CardAction`s under a `border-subtle` line. Not in a linked or clickable card. */\nexport function CardFooter({ className, children, ...rest }: Readonly<ComponentProps<'div'>>) {\n    const { linked } = useContext(CardContext);\n    if (linked) return null;\n    const actions = Children.toArray(children).some((child) => isValidElement(child) && child.type === CardAction);\n    return (\n        <div {...rest} className={cn('flex items-center', actions ? 'justify-end gap-[var(--ui-card-actions-gap,1px)] overflow-hidden border-0 border-t border-solid border-hairline p-[var(--ui-card-actions-padding,0px)]' : 'p-4', className)}>\n            {children}\n        </div>\n    );\n}\n\nexport interface CardActionProps extends ComponentProps<'div'> {\n    /** Its name in the header's overflow menu (else the button's label or text). */\n    label?: string;\n}\n\nconst iconOnly = (children: ReactNode) => Children.toArray(children).some((child) => isValidElement(child) && child.type === IconButton);\n\n/** Carbon `CardAction`: in the footer a `Button` stretches to share the row, an `IconButton` keeps its size at the end. */\nexport function CardAction({ label, className, children, ...rest }: Readonly<CardActionProps>) {\n    const icon = iconOnly(children);\n    return (\n        <div {...rest} data-label={label} className={cn('inline-flex min-w-0', icon ? 'flex-none' : 'flex-[1_0_0] [&>*]:w-full [&>*]:max-w-none [&>*]:flex-1', className)}>\n            {children}\n        </div>\n    );\n}\n\nexport interface CardActionsProps extends Omit<ComponentProps<'div'>, 'ref'> {\n    ref?: Ref<HTMLDivElement>;\n    /** The overflow menu's name (default: the translation's \"More actions\"). */\n    overflowMenuLabel?: string;\n    lang?: string;\n}\n\n/** An action's name: its `label`, else its button's accessible name or text. */\nfunction actionName(item: Element, index: number) {\n    const button = item.querySelector('button, a');\n    return (item.firstElementChild as HTMLElement | null)?.dataset.label || button?.getAttribute('aria-label') || button?.textContent?.trim() || `Action ${index + 1}`;\n}\n\n/**\n * Carbon `CardActions`: small buttons in the header's top-end corner, 4px apart, in at most half the header; those that\n * don't fit move to an overflow menu (choosing an item clicks that action's button).\n */\nexport function CardActions({ overflowMenuLabel, lang, className, children, ref, ...rest }: Readonly<CardActionsProps>) {\n    const t = useTranslation(lang).common;\n    const row = useRef<HTMLDivElement>(null);\n    const items = Children.toArray(children).filter(isValidElement) as ReactElement[];\n    const [visible, setVisible] = useState(items.length);\n    const [names, setNames] = useState<string[]>([]);\n    // which actions fit beside the overflow button (core/overflow, as Carbon's createOverflowHandler)\n    useLayoutEffect(() => {\n        const el = row.current;\n        if (!el) return;\n        let frame = 0;\n        const measure = () => {\n            const slots = [...el.querySelectorAll<HTMLElement>(':scope > [data-action]')];\n            const gap = 4;\n            const sizes = slots.map((slot) => {\n                const hidden = 'hidden' in slot.dataset;\n                delete slot.dataset.hidden;\n                const width = slot.getBoundingClientRect().width + gap;\n                if (hidden) slot.dataset.hidden = '';\n                return width;\n            });\n            const count = visibleCount({ container: el.clientWidth, sizes, offset: 32 + gap, gap });\n            setVisible(count);\n            setNames(slots.map((slot, index) => actionName(slot, index)));\n        };\n        const schedule = () => {\n            cancelAnimationFrame(frame);\n            frame = requestAnimationFrame(measure);\n        };\n        const observer = new ResizeObserver(schedule);\n        observer.observe(el);\n        return () => {\n            observer.disconnect();\n            cancelAnimationFrame(frame);\n        };\n    }, [items.length]);\n    const pick = (index: number) => row.current?.querySelectorAll<HTMLElement>(':scope > [data-action]')[index]?.querySelector<HTMLElement>('button, a')?.click();\n    return (\n        <CardPrimitive.Actions\n            {...rest}\n            ref={useMergedRefs(row, ref)}\n            // marked data-card-actions: a click on an action is the action's own, the card leaves it alone\n            className={cn('absolute end-2 top-2 flex h-8 w-[calc(50%-8px)] max-w-[calc(50%-8px)] items-center justify-end gap-1', className)}\n        >\n            {items.map((item, index) => (\n                <div key={item.key ?? index} data-action=\"\" data-hidden={index >= visible || undefined} className=\"inline-flex data-hidden:hidden\">\n                    {item}\n                </div>\n            ))}\n            {visible < items.length ? (\n                <OverflowMenu size=\"sm\" placement=\"bottom-end\" label={overflowMenuLabel ?? t.moreActions} lang={lang}>\n                    {items.slice(visible).map((item, offset) => (\n                        <MenuItem key={item.key ?? visible + offset} label={names[visible + offset] ?? `Action ${visible + offset + 1}`} onClick={() => pick(visible + offset)} />\n                    ))}\n                </OverflowMenu>\n            ) : null}\n        </CardPrimitive.Actions>\n    );\n}\n"
    }
  ]
}
