{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-page-header",
  "type": "registry:ui",
  "title": "react-tw/page-header.tsx",
  "description": "Carbon `PageHeader` as React + Tailwind, the look and rules of `<ui-page-header>`: the top of a page — a 40px 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": [],
  "registryDependencies": [
    "@kanok-ui/core-overflow",
    "@kanok-ui/tw-button",
    "@kanok-ui/tw-dom",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-icon-button",
    "@kanok-ui/tw-menu",
    "@kanok-ui/tw-modal",
    "@kanok-ui/tw-popover",
    "@kanok-ui/tw-refs",
    "@kanok-ui/tw-search",
    "@kanok-ui/tw-tag",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-truncated-text",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/page-header.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/page-header.tsx",
      "content": "import { Children, createContext, isValidElement, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type CSSProperties, type ReactNode, type RefObject } from 'react';\nimport { visibleCount } from '../core/overflow.ts';\nimport { Button } from './button.tsx';\nimport { IconButton } from './icon-button.tsx';\nimport { MenuItem, OverflowMenu } from './menu.tsx';\nimport { Modal } from './modal.tsx';\nimport { Popover } from './popover.tsx';\nimport { Search } from './search.tsx';\nimport { Tag, type TagType } from './tag.tsx';\nimport { TruncatedText } from './truncated-text.tsx';\nimport { naturalWidth, revealForMeasure } from './lib/dom.ts';\nimport { useTranslation } from './lib/i18n.ts';\nimport { useMergedRefs } from './lib/refs.ts';\nimport { cn } from './lib/utils.ts';\n\n/** How far the header has scrolled away (Carbon's observers). */\nexport interface PageHeaderState {\n    fullyCollapsed: boolean;\n    titleClipped: boolean;\n    contentActionsClipped: boolean;\n}\n\ninterface PageHeaderContextValue {\n    state: PageHeaderState;\n    withContent: boolean;\n    fullWidthGrid: boolean;\n    narrowGrid: boolean;\n    contentRef: RefObject<HTMLDivElement | null>;\n    titleRef: RefObject<HTMLHeadingElement | null>;\n    actionsRef: RefObject<HTMLDivElement | null>;\n    registerContent: (on: boolean) => void;\n    /** The tab bar doesn't stick (`disableStickyTabBar`): the header scrolls away, the bar is fixed. */\n    isStatic: boolean;\n    setStatic: (on: boolean) => void;\n}\n\nconst NO_STATE: PageHeaderState = { fullyCollapsed: false, titleClipped: false, contentActionsClipped: false };\nconst PageHeaderContext = createContext<PageHeaderContextValue | null>(null);\nconst usePageHeader = () => useContext(PageHeaderContext);\n\n/** The scrolling box `el` sits in: an ancestor that scrolls, else the document. */\nfunction scrollParent(el: Element): Element {\n    for (let node = el.parentElement; node; node = node.parentElement) {\n        if (node === document.body || node === document.documentElement) break;\n        if (/(auto|scroll)/.test(getComputedStyle(node).overflowY)) return node;\n    }\n    return document.scrollingElement ?? document.documentElement;\n}\n\n/** How far the header sits below the top of its scrolling box (a fixed UI shell above it), at rest. */\nfunction headerOffset(el: Element): number {\n    const box = scrollParent(el);\n    const boxTop = box === document.scrollingElement ? 0 : box.getBoundingClientRect().top;\n    return Math.max(el.getBoundingClientRect().top - boxTop, 0);\n}\n\n/** Carbon's 2x grid as the page header uses it: one full-width column, 1584px at most, margin 0 / 16 / 24px plus half a gutter. */\nfunction rowClasses(context: PageHeaderContextValue | null, padding: 'column' | 'margin' = 'column') {\n    return cn(\n        'box-border w-full max-w-[1584px] mx-auto [--_m:0px] min-[42rem]:[--_m:16px] min-[99rem]:[--_m:24px]',\n        padding === 'column' ? 'px-[calc(var(--_m)+16px)]' : 'px-(--_m)',\n        padding === 'column' && context?.narrowGrid && 'ps-(--_m)',\n        context?.fullWidthGrid && 'max-w-none',\n    );\n}\n\n/** Watches `target` scroll all the way under the bar (1px more: a box edge-to-edge with the bar still counts as intersecting). */\nfunction useClipped(target: RefObject<Element | null>, root: RefObject<HTMLElement | null>, enabled: boolean, onChange: (clipped: boolean) => void) {\n    const latest = useRef(onChange);\n    useLayoutEffect(() => {\n        latest.current = onChange;\n    });\n    useEffect(() => {\n        const el = target.current;\n        if (!enabled || !el || !root.current || typeof IntersectionObserver === 'undefined') return;\n        // measured in the scrolling box the header sits in (Carbon watches the viewport, wrong for a box lower on the page)\n        const box = scrollParent(root.current);\n        const observer = new IntersectionObserver((entries) => entries.forEach((entry) => latest.current(!entry.isIntersecting)), {\n            root: box === document.scrollingElement ? null : box,\n            rootMargin: `${(headerOffset(root.current) + 40 + 1) * -1}px 0px 0px 0px`,\n        });\n        observer.observe(el);\n        return () => observer.disconnect();\n    }, [target, root, enabled]);\n}\n\nexport interface PageHeaderProps extends ComponentProps<'div'> {\n    /** No 1584px cap on the grid. */\n    fullWidthGrid?: boolean;\n    /** Hang the text on the grid margin. */\n    narrowGrid?: boolean;\n    onContentFullyCollapsed?: (collapsed: boolean) => void;\n    onTitleClipped?: (clipped: boolean) => void;\n    onContentActionsClipped?: (clipped: boolean) => void;\n}\n\n/**\n * Carbon `PageHeader` as React + Tailwind, the look and rules of `<ui-page-header>`: the top of a page — a 40px\n * `PageHeaderBreadcrumbBar`, the `PageHeaderContent` (heading-04 title, icon, contextual and page actions,\n * `PageHeaderContentText`), and a `PageHeaderTabBar`, on layer-01 with a line below. It sticks as the page scrolls:\n * the content slides under the bar, which stays (as do the tabs); once the title has gone `PageHeaderTitleBreadcrumb`\n * appears, and the content's page actions give way to the bar's `contentActions`. `PageHeaderScrollButton`\n * collapses / expands it.\n */\nexport function PageHeader({ fullWidthGrid = false, narrowGrid = false, onContentFullyCollapsed, onTitleClipped, onContentActionsClipped, className, style, ref, children, ...rest }: Readonly<PageHeaderProps>) {\n    const root = useRef<HTMLDivElement>(null);\n    const rootRef = useMergedRefs(root, ref);\n    const contentRef = useRef<HTMLDivElement>(null);\n    const titleRef = useRef<HTMLHeadingElement>(null);\n    const actionsRef = useRef<HTMLDivElement>(null);\n    const [withContent, setWithContent] = useState(false);\n    const [isStatic, setStatic] = useState(false);\n    const [state, setState] = useState<PageHeaderState>(NO_STATE);\n    const [offsets, setOffsets] = useState({ top: 0, bar: 0 });\n\n    // where the header and its bar stick: up by the content's height, under whatever sits above the header\n    useLayoutEffect(() => {\n        const el = root.current;\n        if (!el || typeof ResizeObserver === 'undefined') return;\n        const measure = () => {\n            const offset = headerOffset(el);\n            setOffsets({ top: (Math.round(contentRef.current?.offsetHeight ?? 0) - offset) * -1, bar: offset });\n        };\n        const observer = new ResizeObserver(measure);\n        observer.observe(el);\n        return () => observer.disconnect();\n    }, []);\n\n    const update = (key: keyof PageHeaderState, value: boolean, report?: (value: boolean) => void) => {\n        setState((prev) => (prev[key] === value ? prev : { ...prev, [key]: value }));\n        report?.(value);\n    };\n    useClipped(contentRef, root, withContent, (v) => update('fullyCollapsed', v, onContentFullyCollapsed));\n    useClipped(titleRef, root, withContent, (v) => update('titleClipped', v, onTitleClipped));\n    useClipped(actionsRef, root, withContent, (v) => update('contentActionsClipped', v, onContentActionsClipped));\n\n    const value = useMemo<PageHeaderContextValue>(() => ({ state, withContent, fullWidthGrid, narrowGrid, contentRef, titleRef, actionsRef, registerContent: setWithContent, isStatic, setStatic }), [state, withContent, fullWidthGrid, narrowGrid, isStatic]);\n    return (\n        <PageHeaderContext.Provider value={value}>\n            <div\n                {...rest}\n                ref={rootRef}\n                style={{ '--ui-page-header-top': `${offsets.top}px`, '--ui-page-header-bar-top': `${offsets.bar}px`, ...style } as CSSProperties}\n                className={cn('z-[1] block border-0 border-b border-solid border-border-subtle-2 bg-layer-1', isStatic ? 'static pt-10' : 'sticky top-(--ui-page-header-top)', className)}\n            >\n                {children}\n            </div>\n        </PageHeaderContext.Provider>\n    );\n}\n\nexport interface PageHeaderBreadcrumbBarProps extends Omit<ComponentProps<'div'>, 'children'> {\n    /** The line under the bar. */\n    border?: boolean;\n    /** A 16px icon before the trail. */\n    icon?: ReactNode;\n    /** The content's page actions again, shown once they have scrolled away. */\n    contentActions?: ReactNode;\n    /** No 12px gap after the content actions. */\n    contentActionsFlush?: boolean;\n    /** Actions for the whole page. */\n    pageActions?: ReactNode;\n    /** The page actions reach the screen's edge. */\n    pageActionsFlush?: boolean;\n    actionsAriaLabel?: string;\n    lang?: string;\n    /** The breadcrumb trail. */\n    children?: ReactNode;\n}\n\n/** The page header's 40px breadcrumb bar, the look of `<ui-page-header-breadcrumb>`. */\nexport function PageHeaderBreadcrumbBar({ border = true, icon, contentActions, contentActionsFlush = false, pageActions, pageActionsFlush = false, actionsAriaLabel, lang, className, children, ...rest }: Readonly<PageHeaderBreadcrumbBarProps>) {\n    const context = usePageHeader();\n    const t = useTranslation(lang).common;\n    const show = !!context?.state.contentActionsClipped;\n    return (\n        // Carbon --disable-sticky-tab-bar: the bar is fixed at the top (the header's padding keeps its room)\n        <div {...rest} className={cn('z-[2] box-border block h-10 bg-layer-1', context?.isStatic ? 'fixed inset-x-0 top-0' : 'sticky top-(--ui-page-header-bar-top,0px)', border && 'border-0 border-b border-solid border-border-subtle-2', className)}>\n            <div className={cn(rowClasses(context), pageActionsFlush && 'pe-0')}>\n                <div className=\"flex h-full min-h-10 min-w-0 items-center justify-between gap-2\">\n                    <div className=\"flex min-w-0 flex-[1_1_75%] items-center min-[42rem]:max-w-[60%] min-[42rem]:flex-[1_1_auto] [&>:is(nav,ui-breadcrumb)]:min-w-0 [&>:is(nav,ui-breadcrumb)]:flex-[1_1_0%] [&>:is(nav,ui-breadcrumb)]:[--ui-breadcrumb-wrap:nowrap]\">\n                        {icon ? <span className=\"me-2 flex flex-none\" aria-hidden=\"true\">{icon}</span> : null}\n                        {children}\n                    </div>\n                    {contentActions || pageActions ? (\n                        <div role=\"toolbar\" aria-label={actionsAriaLabel || t.pageHeaderActions} className=\"flex max-w-1/4 min-w-0 flex-[0_1_25%] items-center justify-end gap-2 min-[42rem]:max-w-none min-[42rem]:flex-[0_0_auto]\">\n                            <div className={cn('hidden min-w-0 overflow-hidden min-[42rem]:flex', show ? 'visible opacity-100 transition-opacity duration-(--ui-duration-moderate-01) ease-carbon' : 'invisible opacity-0', !contentActionsFlush && 'min-[42rem]:[&>*]:me-3')}>{contentActions}</div>\n                            {/* a PageHeaderActions in it shrinks into its overflow menu */}\n                            <div className=\"flex min-w-0 flex-auto items-center justify-end\">{pageActions}</div>\n                        </div>\n                    ) : null}\n                </div>\n            </div>\n        </div>\n    );\n}\n\nexport interface PageHeaderContentProps extends Omit<ComponentProps<'div'>, 'title'> {\n    /** The page's title (Carbon `title`). */\n    heading: ReactNode;\n    /** The title's element. */\n    headingAs?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';\n    /** An icon before the title. */\n    icon?: ReactNode;\n    /** Next to the title (e.g. a tag). */\n    contextualActions?: ReactNode;\n    /** At the end of the title row. */\n    pageActions?: ReactNode;\n}\n\n/** The page header's content, the look of `<ui-page-header-content>`. */\nexport function PageHeaderContent({ heading, headingAs: Heading = 'h1', icon, contextualActions, pageActions, className, ref, children, ...rest }: Readonly<PageHeaderContentProps>) {\n    const context = usePageHeader();\n    const ownRef = useRef<HTMLDivElement>(null);\n    const merged = useMergedRefs(context?.contentRef ?? ownRef, ref);\n    const register = context?.registerContent;\n    useEffect(() => {\n        register?.(true);\n        return () => register?.(false);\n    }, [register]);\n    const clipped = !!context?.state.contentActionsClipped;\n    return (\n        <div {...rest} ref={merged} className={cn('block pt-12', className)}>\n            <div className={rowClasses(context)}>\n                <div className=\"mb-4 flex min-h-10 flex-col gap-4 min-[42rem]:grid min-[42rem]:grid-cols-[auto_minmax(auto,auto)]\">\n                    <div className=\"flex flex-wrap gap-4\">\n                        <div className=\"flex\">\n                            {icon ? <span className=\"me-4 flex flex-none\" aria-hidden=\"true\">{icon}</span> : null}\n                            <Heading ref={context?.titleRef} className=\"m-0 max-w-[640px] type-heading-04\">\n                                {typeof heading === 'string' ? <TruncatedText value={heading} lines={contextualActions ? 1 : 2} placement=\"bottom\" /> : heading}\n                            </Heading>\n                        </div>\n                        {contextualActions ? <div className=\"flex items-center\">{contextualActions}</div> : null}\n                    </div>\n                    <div ref={context?.actionsRef} className={cn('flex justify-self-end transition-opacity duration-(--ui-duration-moderate-02) ease-carbon max-[41.98rem]:justify-start', clipped && 'invisible opacity-0')}>\n                        {pageActions}\n                    </div>\n                </div>\n                {children}\n            </div>\n        </div>\n    );\n}\n\nexport interface PageHeaderContentTextProps extends ComponentProps<'div'> {\n    subtitle?: ReactNode;\n    subtitleAs?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';\n}\n\n/** The page header's text under the title, the look of `<ui-page-header-content-text>`. */\nexport function PageHeaderContentText({ subtitle, subtitleAs: Subtitle = 'h2', className, children, ...rest }: Readonly<PageHeaderContentTextProps>) {\n    return (\n        <div {...rest} className={cn('block max-w-[640px] pb-6 type-body-01', className)}>\n            {subtitle ? <Subtitle className=\"m-0 mb-2 tracking-normal type-heading-03\">{subtitle}</Subtitle> : null}\n            {children}\n        </div>\n    );\n}\n\nexport interface PageHeaderHeroImageProps extends ComponentProps<'div'> {\n    objectFit?: 'cover' | 'contain';\n}\n\n/** A hero image beside the page header's content: 3:2, 2:1 from lg, the look of `<ui-page-header-hero-image>`. */\nexport function PageHeaderHeroImage({ objectFit = 'cover', className, children, ...rest }: Readonly<PageHeaderHeroImageProps>) {\n    return (\n        <div {...rest} className={cn('block aspect-[3/2] overflow-hidden min-[66rem]:aspect-[2/1] [&>img]:block [&>img]:size-full [&>img]:object-center', objectFit === 'contain' ? '[&>img]:object-contain' : '[&>img]:object-cover', className)}>\n            {children}\n        </div>\n    );\n}\n\nexport interface PageHeaderTabBarProps extends ComponentProps<'div'> {\n    /** Tags at the end. */\n    tags?: ReactNode;\n    /** The collapse / expand button. */\n    scroller?: ReactNode;\n    /** Let the header scroll away; the breadcrumb bar is fixed at the top instead (Carbon). */\n    disableStickyTabBar?: boolean;\n}\n\n/** The page header's tab bar, the look of `<ui-page-header-tabs>`. */\nexport function PageHeaderTabBar({ tags, scroller, disableStickyTabBar = false, className, children, ...rest }: Readonly<PageHeaderTabBarProps>) {\n    const context = usePageHeader();\n    const setStatic = context?.setStatic;\n    useEffect(() => {\n        setStatic?.(disableStickyTabBar);\n    }, [disableStickyTabBar, setStatic]);\n    return (\n        <div {...rest} className={cn('z-[1] block bg-layer-1', disableStickyTabBar ? 'static' : 'sticky top-(--ui-page-header-bar-top,0px)', className)}>\n            <div className=\"flex items-center\">\n                <div className={rowClasses(context, 'margin')}>\n                    <div className=\"flex min-w-0 flex-1 items-center [&>:first-child]:min-w-0 [&>:first-child]:flex-[1_1_auto]\">\n                        {children}\n                        {tags ? <div className=\"ms-auto inline-flex w-2/5 min-w-0 items-center justify-end\">{tags}</div> : null}\n                    </div>\n                </div>\n                {scroller}\n            </div>\n        </div>\n    );\n}\n\nexport interface PageHeaderScrollButtonProps extends Omit<ComponentProps<'button'>, 'children'> {\n    collapseText?: string;\n    expandText?: string;\n    lang?: string;\n}\n\n/** The page header's collapse / expand button, the look of `<ui-page-header-scroller>`. */\nexport function PageHeaderScrollButton({ collapseText, expandText, lang, onClick, ...rest }: Readonly<PageHeaderScrollButtonProps>) {\n    const context = usePageHeader();\n    const t = useTranslation(lang).common;\n    const collapsed = !!context?.state.fullyCollapsed;\n    return (\n        <IconButton\n            {...rest}\n            kind=\"ghost\"\n            size=\"md\"\n            tooltipPlacement=\"top\"\n            label={collapsed ? (expandText ?? t.expand) : (collapseText ?? t.collapse)}\n            onClick={(event) => {\n                onClick?.(event);\n                const content = context?.contentRef.current;\n                if (content) scrollParent(content).scrollTo({ top: collapsed ? 0 : content.offsetHeight, behavior: 'smooth' });\n            }}\n        >\n            {/* Carbon .cds--page-header--scroller-button-icon: $transition-base (250ms) with the browser's ease */}\n            <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\" className={cn('transition-transform duration-250 ease-[ease] motion-reduce:transition-none', collapsed && 'rotate-180')}>\n                <path d=\"M8 5 13 10 12.3 10.7 8 6.4 3.7 10.7 3 10z\" />\n            </svg>\n        </IconButton>\n    );\n}\n\n/**\n * The page header's title as the last crumb, the rules of `<ui-page-header-title-breadcrumb>`: hidden (and out of\n * the tab order) until the title has scrolled under the bar; always shown without a `PageHeaderContent`. Put it last\n * in the `Breadcrumb`; a long title ends in an ellipsis.\n */\nexport function PageHeaderTitleBreadcrumb({ className, children, ...rest }: Readonly<ComponentProps<'li'>>) {\n    const context = usePageHeader();\n    const show = !context?.withContent || context.state.titleClipped;\n    return (\n        <li\n            {...rest}\n            aria-hidden={show ? undefined : true}\n            inert={!show}\n            className={cn(\n                'inline-flex min-w-0 flex-[0_1_auto] items-center font-sans type-body-sm transition-[transform,opacity] duration-(--ui-duration-moderate-01) ease-carbon',\n                show ? 'translate-y-0 opacity-100' : 'translate-y-4 opacity-0 motion-reduce:translate-y-0',\n                className,\n            )}\n        >\n            <span aria-current=\"page\" className=\"overflow-hidden text-ellipsis whitespace-nowrap text-ink\">\n                {children}\n            </span>\n        </li>\n    );\n}\n\n/** Measure on every resize of `target` (in the next frame, as Carbon's handler). */\nfunction useResizeMeasure(target: RefObject<HTMLElement | null>, measure: (el: HTMLElement) => void, deps: readonly unknown[]) {\n    const latest = useRef(measure);\n    useLayoutEffect(() => {\n        latest.current = measure;\n    });\n    useLayoutEffect(() => {\n        const el = target.current;\n        if (!el) return;\n        let frame = 0;\n        const schedule = () => {\n            cancelAnimationFrame(frame);\n            frame = requestAnimationFrame(() => latest.current(el));\n        };\n        const observer = new ResizeObserver(schedule);\n        observer.observe(el);\n        schedule();\n        return () => {\n            observer.disconnect();\n            cancelAnimationFrame(frame);\n        };\n        // eslint-disable-next-line react-hooks/exhaustive-deps -- re-measured when what is shown changes\n    }, [target, ...deps]);\n}\n\n/** An action's name in the menu: its button's accessible name, else its text. */\nfunction actionName(slot: Element, index: number) {\n    const button = slot.querySelector('button, a');\n    return button?.getAttribute('aria-label') || slot.textContent?.trim() || `Action ${index + 1}`;\n}\n\nexport interface PageHeaderActionsProps extends ComponentProps<'div'> {\n    /** The overflow menu's name (default: the translation's \"More actions\"). */\n    overflowLabel?: string;\n    lang?: string;\n}\n\n/**\n * Carbon for IBM Products `PageHeaderActionsSet`, as `<ui-page-header-actions>`: the page's buttons side by side; those\n * that don't fit — from the end — go into a \"⋮\" overflow menu (48px kept for it), choosing one clicks its button. Put\n * it in `PageHeaderBreadcrumbBar`'s or `PageHeaderContent`'s `pageActions`.\n */\nexport function PageHeaderActions({ overflowLabel, lang, className, children, ref, ...rest }: Readonly<PageHeaderActionsProps>) {\n    const t = useTranslation(lang).common;\n    const row = useRef<HTMLDivElement>(null);\n    const items = Children.toArray(children).filter(isValidElement);\n    const [visible, setVisible] = useState(items.length);\n    const [names, setNames] = useState<string[]>([]);\n    const slots = (el: HTMLElement) => [...el.querySelectorAll<HTMLElement>(':scope > [data-action]')];\n    useResizeMeasure(\n        row,\n        (el) => {\n            const all = slots(el);\n            const restore = revealForMeasure(all);\n            const sizes = all.map(naturalWidth);\n            const container = el.clientWidth;\n            restore();\n            setVisible(visibleCount({ container, sizes, offset: 48, keepFirst: false }));\n            setNames(all.map((slot, index) => actionName(slot, index)));\n        },\n        [items.length],\n    );\n    const pick = (index: number) => {\n        const slot = row.current ? slots(row.current)[index] : undefined;\n        slot?.querySelector<HTMLElement>('button, a')?.click();\n    };\n    return (\n        <div {...rest} ref={useMergedRefs(row, ref)} className={cn('flex min-w-0 max-w-full flex-auto items-center', className)}>\n            {items.map((item, index) => (\n                <div key={item.key ?? index} data-action=\"\" data-hidden={index >= visible || undefined} className=\"flex shrink-0 data-hidden:hidden\">\n                    {item}\n                </div>\n            ))}\n            {visible < items.length ? (\n                // Carbon: the buttons from the start, the menu at the end\n                <OverflowMenu className=\"ms-auto shrink-0\" size=\"md\" placement=\"bottom-end\" label={overflowLabel ?? 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        </div>\n    );\n}\n\n/** A tag of `PageHeaderTags` (Carbon `tagsData`). */\nexport interface PageHeaderTagItem {\n    text: string;\n    type?: TagType;\n    size?: 'sm' | 'md' | 'lg';\n    /** With a close button: `onDismiss` hears it. */\n    dismissible?: boolean;\n    /** Your key for it (else its text). */\n    id?: string;\n}\n\n/** At most this many hidden tags in the popover; more, and a \"View all tags\" button opens them all in a modal. */\nconst POPOVER_TAGS = 10;\n\nexport interface PageHeaderTagsProps extends Omit<ComponentProps<'div'>, 'children'> {\n    tags: readonly PageHeaderTagItem[];\n    /** A dismissible tag was dismissed: remove it from `tags` (Carbon removes it itself; `<ui-page-header-tags>` does too). */\n    onDismiss?: (tag: PageHeaderTagItem, index: number) => void;\n    lang?: string;\n}\n\n/**\n * Carbon for IBM Products `PageHeaderTagsSet`, as `<ui-page-header-tags>`: the page's tags on one line, at the end; those\n * that don't fit — from the end — make a \"+N\" operational tag that opens them in a high-contrast popover (ten at most:\n * past ten, \"View all tags\" opens a small modal of them all, with a search). \"N more tags\" is announced. Put it in\n * `PageHeaderTabBar`'s `tags`.\n */\nexport function PageHeaderTags({ tags, onDismiss, lang, className, ...rest }: Readonly<PageHeaderTagsProps>) {\n    const t = useTranslation(lang).common;\n    const row = useRef<HTMLDivElement>(null);\n    const [visible, setVisible] = useState(tags.length);\n    const [open, setOpen] = useState(false);\n    const [all, setAll] = useState(false);\n    const [query, setQuery] = useState('');\n    useResizeMeasure(\n        row,\n        (el) => {\n            const items = [...el.querySelectorAll<HTMLElement>(':scope > [data-tag]')];\n            const more = el.querySelector<HTMLElement>(':scope > [data-more]');\n            if (!more) return;\n            const gap = 8;\n            const restore = revealForMeasure([more, ...items]);\n            const sizes = items.map((item) => naturalWidth(item) + gap);\n            const offset = naturalWidth(more) + gap;\n            restore();\n            setVisible(visibleCount({ container: el.clientWidth, sizes, offset, gap, keepFirst: false }));\n        },\n        [tags],\n    );\n    const hidden = tags.slice(visible);\n    const more = t.moreTags.replace('{count}', String(hidden.length));\n    const key = (tag: PageHeaderTagItem, index: number) => tag.id ?? `${tag.text}-${index}`;\n    const dismiss = (tag: PageHeaderTagItem) => {\n        if (hidden.length <= 1) setOpen(false);\n        onDismiss?.(tag, tags.indexOf(tag));\n    };\n    const tag = (item: PageHeaderTagItem, className?: string) => (\n        <Tag type={item.type ?? 'gray'} size={item.size ?? 'md'} dismissible={item.dismissible} onDismiss={() => dismiss(item)} lang={lang} className={className}>\n            {item.text}\n        </Tag>\n    );\n    const matches = tags.filter((item) => item.text.toLowerCase().includes(query.trim().toLowerCase()));\n    return (\n        <div {...rest} className={cn('flex w-full min-w-0 justify-end', className)}>\n            <div ref={row} className=\"flex w-full min-w-0 items-center justify-end gap-2 whitespace-nowrap\">\n                {tags.map((item, index) => (\n                    <span key={key(item, index)} data-tag=\"\" data-hidden={index >= visible || undefined} className=\"inline-flex shrink-0 data-hidden:hidden\">\n                        {tag(item)}\n                    </span>\n                ))}\n                <span data-more=\"\" data-hidden={hidden.length === 0 || undefined} className=\"inline-flex shrink-0 data-hidden:hidden\">\n                    <Popover\n                        open={open}\n                        onOpenChange={setOpen}\n                        autoClose\n                        highContrast\n                        placement=\"bottom-end\"\n                        trigger={\n                            <Tag operational size={tags[0]?.size ?? 'md'} aria-label={more} aria-haspopup=\"true\" onClick={() => setOpen((was) => !was)} lang={lang}>\n                                {`+${hidden.length}`}\n                            </Tag>\n                        }\n                    >\n                        {/* Carbon: the hidden tags one under the other, 4px apart, 16px in; each as wide as the box, its text centred in label-02 */}\n                        <div className=\"flex flex-col gap-1 p-4\">\n                            {hidden.slice(0, POPOVER_TAGS).map((item, index) => (\n                                <span key={key(item, visible + index)} className=\"flex\">\n                                    {tag(item, 'w-full max-w-none justify-center type-body-sm leading-[18px]!')}\n                                </span>\n                            ))}\n                            {hidden.length > POPOVER_TAGS ? (\n                                <Button\n                                    kind=\"ghost\"\n                                    size=\"sm\"\n                                    // on the high-contrast box: the inverse link colour\n                                    className=\"mt-2 flex text-link-inverse hover:text-link-inverse\"\n                                    onClick={() => {\n                                        setOpen(false);\n                                        setQuery('');\n                                        setAll(true);\n                                    }}\n                                >\n                                    {t.viewAllTags}\n                                </Button>\n                            ) : null}\n                        </div>\n                    </Popover>\n                </span>\n                <output className=\"sr-only\">{hidden.length ? more : ''}</output>\n            </div>\n            {tags.length > POPOVER_TAGS ? (\n                <Modal size=\"sm\" open={all} onClose={() => setAll(false)} heading={t.allTags} lang={lang}>\n                    <Search className=\"mb-4\" size=\"lg\" label={t.searchAllTags} placeholder={t.searchAllTags} value={query} onChange={(event) => setQuery(event.target.value)} onClear={() => setQuery('')} lang={lang} />\n                    <div className=\"flex flex-wrap gap-x-2 gap-y-1\">\n                        {matches.map((item, index) => (\n                            <span key={key(item, index)} className=\"inline-flex\">\n                                {tag(item)}\n                            </span>\n                        ))}\n                    </div>\n                </Modal>\n            ) : null}\n        </div>\n    );\n}\n"
    }
  ]
}
