{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tw-side-panel",
  "type": "registry:ui",
  "title": "react-tw/side-panel.tsx",
  "description": "Carbon for IBM Products `SidePanel` as React + Tailwind, the look and rules of `<ui-side-panel>`: a panel sliding in 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-action-set",
    "@kanok-ui/core-motion",
    "@kanok-ui/core-position",
    "@kanok-ui/tw-action-set",
    "@kanok-ui/tw-i18n",
    "@kanok-ui/tw-icon-button",
    "@kanok-ui/tw-layer",
    "@kanok-ui/tw-refs",
    "@kanok-ui/tw-theme",
    "@kanok-ui/tw-utils"
  ],
  "files": [
    {
      "path": "src/react-tw/side-panel.tsx",
      "type": "registry:ui",
      "target": "components/ui/react-tw/side-panel.tsx",
      "content": "import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps, type CSSProperties, type ReactNode, type RefObject, type UIEvent } from 'react';\nimport type { Placement } from '../core/position.ts';\nimport { willStack, type ActionSetSize } from '../core/action-set.ts';\nimport { cssDuration } from '../core/motion.ts';\nimport { SidePanel as SidePanelPrimitive } from '@purpurabog/ui/headless';\nimport { ActionButtons, actionRowClasses, stackedClasses, type ActionSetAction } from './action-set.tsx';\nimport { IconButton } from './icon-button.tsx';\nimport { Layer } from './layer.tsx';\nimport { useTranslation } from './lib/i18n.ts';\nimport { useMergedRefs } from './lib/refs.ts';\nimport { cn } from './lib/utils.ts';\n\nexport type SidePanelSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';\nexport type SidePanelCloseReason = SidePanelPrimitive.SidePanelCloseReason;\n\nconst SIZE: Record<SidePanelSize, string> = { xs: '16rem', sm: '20rem', md: '30rem', lg: '40rem', xl: '65rem', '2xl': '80rem' };\n\nexport interface SidePanelProps extends Omit<ComponentProps<'aside'>, 'title' | 'children'> {\n    open: boolean;\n    /** Esc, ×, or a click on the overlay asked to close; set `open` to false to close (Carbon `onRequestClose`). */\n    onRequestClose?: (reason: SidePanelCloseReason) => void;\n    /** After it closed: the panel has slid out (Lit `ui-close`). */\n    onClose?: () => void;\n    /** The heading (Carbon `title`); also the panel's accessible name. */\n    heading?: string;\n    /** A small label above the heading. */\n    labelText?: string;\n    subtitle?: ReactNode;\n    /** Content above the label and heading (Lit slot `above-title`). */\n    aboveTitle?: ReactNode;\n    /** Content under the subtitle (Lit slot `below-title`). */\n    belowTitle?: ReactNode;\n    /** Small buttons under the header (Carbon `actionToolbarButtons`). */\n    actionToolbar?: ReactNode;\n    /** Up to four action buttons at the foot, as Carbon's ActionSet for the panel's size. */\n    actions?: readonly ActionSetAction[];\n    /** xs 16rem, sm 20rem, md 30rem, lg 40rem, xl 65rem, 2xl 80rem. */\n    size?: SidePanelSize;\n    placement?: 'right' | 'left';\n    /** Push the page aside (`selectorPageContent`) instead of covering it; no focus trap, no Esc. */\n    slideIn?: boolean;\n    /** Dim the page; a click on it asks to close (unless `preventCloseOnClickOutside`). */\n    includeOverlay?: boolean;\n    preventCloseOnClickOutside?: boolean;\n    /** What takes focus on open (Carbon `selectorPrimaryFocus`), else the first control. */\n    selectorInitialFocus?: string;\n    /** The page element a slide-in panel pushes aside. */\n    selectorPageContent?: string;\n    hideCloseButton?: boolean;\n    closeIconDescription?: string;\n    closeIconTooltipAlignment?: Placement;\n    navigationBackIconDescription?: string;\n    /** Above 0 shows the back button. */\n    currentStep?: number;\n    onNavigationBack?: () => void;\n    /** 48px action buttons instead of 64px. */\n    condensedActions?: boolean;\n    /** Shrink the heading as the content scrolls (Carbon's default). */\n    animateTitle?: boolean;\n    lang?: string;\n    children?: ReactNode;\n}\n\nconst durationOf = (el: Element, name: string) => cssDuration(getComputedStyle(el).getPropertyValue(name));\n\n/** Carbon animates the title only with something to fade and enough to scroll: then the header and content scroll together. */\nfunction useAnimatedTitle(enabled: boolean, open: boolean, panel: RefObject<HTMLElement | null>) {\n    const [animated, setAnimated] = useState(false);\n    useLayoutEffect(() => {\n        const el = panel.current;\n        if (!open || !el) return;\n        const measure = () => {\n            const label = el.querySelector<HTMLElement>('[data-part=\"label\"]');\n            const subtitle = el.querySelector<HTMLElement>('[data-part=\"subtitle\"]');\n            const title = el.querySelector<HTMLElement>('[data-part=\"title\"]');\n            const toolbar = el.querySelector('[data-part=\"toolbar\"]');\n            const border = toolbar && title ? title.offsetHeight - title.clientHeight : 0;\n            const distance = (label?.offsetHeight ?? 0) + (subtitle?.offsetHeight ?? 0) + border;\n            el.style.setProperty('--_distance', String(distance));\n            const scroller = el.querySelector<HTMLElement>('[data-scrolls]');\n            const room = scroller ? scroller.scrollHeight - scroller.clientHeight : 0;\n            const fades = !!label || !!subtitle || !!toolbar;\n            const next = enabled && durationOf(el, '--ui-duration-moderate-02') > 0 && !!title && fades && distance > 0 && room >= distance + 16;\n            if (!next) el.style.setProperty('--_progress', '0');\n            setAnimated(next);\n        };\n        measure();\n        if (typeof ResizeObserver === 'undefined') return;\n        const observer = new ResizeObserver(measure);\n        observer.observe(el);\n        return () => observer.disconnect();\n    }, [enabled, open, panel]);\n    return animated;\n}\n\ninterface PanelHeaderProps {\n    heading?: string;\n    labelText?: string;\n    subtitle?: ReactNode;\n    aboveTitle?: ReactNode;\n    belowTitle?: ReactNode;\n    actionToolbar?: ReactNode;\n    currentStep: number;\n    iconSize: 'sm' | 'md';\n    animated: boolean;\n    /** Absent: no × (`hideCloseButton`). */\n    closeLabel?: string;\n    closePlacement: Placement;\n    backLabel: string;\n    onBack?: () => void;\n}\n\n/** The heading and, while the title animates, its collapsed heading-compact-02 copy. */\nfunction PanelTitle({ heading, labelText, animated }: Readonly<{ heading: string; labelText?: string; animated: boolean }>) {\n    return (\n        <div data-part=\"title\" className={cn('relative z-[4] border-0 border-b-(length:--_title-pad-bottom) border-solid border-transparent bg-(--_surface)', animated && 'sticky top-4')}>\n                    <h2 className={cn('m-0 pe-(--_title-pad-end) opacity-[calc(1-var(--_progress))] type-heading-03', !labelText && 'translate-y-[calc(-16px*var(--_progress))]')}>{heading}</h2>\n                    {animated ? (\n                        <h2 aria-hidden=\"true\" className={cn('absolute top-0 m-0 pe-(--_title-pad-end) opacity-(--_progress) type-heading-compact-02', !labelText && 'translate-y-[calc(16px*(1-var(--_progress)))]')}>\n                            {heading}\n                        </h2>\n                    ) : null}\n                </div>\n    );\n}\n\n/** The back button, what goes above the title, the label, heading (and its collapsed copy), ×, subtitle, what goes below it and the toolbar. */\nfunction PanelHeader({ heading, labelText, subtitle, aboveTitle, belowTitle, actionToolbar, currentStep, iconSize, animated, closeLabel, closePlacement, backLabel, onBack }: Readonly<PanelHeaderProps>) {\n    const { requestClose } = SidePanelPrimitive.useSidePanelContext();\n    const toolbar = !!actionToolbar;\n    return (\n        <div\n            className={cn(\n                'relative z-[4] min-h-10 bg-(--_surface) px-4 pt-4',\n                heading && 'min-h-0',\n                currentStep > 0 && (iconSize === 'md' ? 'pt-10' : 'pt-8'),\n                toolbar && 'mb-2',\n                \"before:absolute before:start-0 before:bottom-0 before:z-[9] before:h-px before:w-full before:bg-border-subtle-2 before:content-['']\",\n                (!heading || toolbar) && 'before:content-none',\n                animated ? 'sticky top-[calc(-1px*var(--_distance,0))] before:opacity-(--_progress)' : 'before:opacity-100',\n            )}\n        >\n            {currentStep > 0 ? (\n                <div className=\"fixed start-0 top-0 z-[5] flex\">\n                    <IconButton label={backLabel} size={iconSize} tooltipPlacement=\"bottom-start\" onClick={onBack}>\n                        <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n                            <path d=\"M7 12.3 3.2 8.5H15v-1H3.2L7 3.7 6.3 3 1.3 8l5 5z\" />\n                        </svg>\n                    </IconButton>\n                </div>\n            ) : null}\n            {aboveTitle}\n            {heading && labelText ? (\n                <p data-part=\"label\" className=\"m-0 pe-(--_title-pad-end) opacity-[calc(1-var(--_progress))] type-caption\">\n                    {labelText}\n                </p>\n            ) : null}\n            {heading ? <PanelTitle heading={heading} labelText={labelText} animated={animated} /> : null}\n            <div className=\"fixed end-0 top-0 z-10 flex\">\n                {closeLabel ? (\n                    <IconButton label={closeLabel} size={iconSize} tooltipPlacement={closePlacement} onClick={() => requestClose('close-button')}>\n                        <svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n                            <path d=\"M12 4.7 11.3 4 8 7.3 4.7 4 4 4.7 7.3 8 4 11.3l.7.7L8 8.7l3.3 3.3.7-.7L8.7 8z\" />\n                        </svg>\n                    </IconButton>\n                ) : null}\n            </div>\n            {subtitle ? (\n                <p data-part=\"subtitle\" className=\"m-0 pe-(--_title-pad-end) pb-4 opacity-[calc(1-var(--_progress))] type-body-sm\">\n                    {subtitle}\n                </p>\n            ) : null}\n            {belowTitle}\n            {toolbar ? (\n                <div data-part=\"toolbar\" className=\"sticky z-[4] flex items-center bg-(--_surface) [&>:first-child]:me-2\">\n                    {actionToolbar}\n                </div>\n            ) : null}\n        </div>\n    );\n\n}\n\n/** Inside the Root, mounted while the panel shows: `onClose` once it has slid out (not when the whole panel goes away open). */\nfunction ClosedNotice({ onClose }: Readonly<{ onClose?: () => void }>) {\n    const { closing } = SidePanelPrimitive.useSidePanelContext();\n    const latest = useRef({ closing, onClose });\n    useLayoutEffect(() => {\n        latest.current = { closing, onClose };\n    });\n    useEffect(\n        () => () => {\n            if (latest.current.closing) latest.current.onClose?.();\n        },\n        [],\n    );\n    return null;\n}\n\n/** The panel's width and the room its heading keeps (more beside a toolbar; less below it with a subtitle). */\nconst panelVars = (size: SidePanelSize, toolbar: boolean, subtitle: boolean) => ({\n    '--_size': SIZE[size] ?? SIZE.md,\n    '--_title-pad-end': toolbar ? '64px' : '32px',\n    '--_title-pad-bottom': subtitle ? '8px' : '16px',\n    '--_progress': 0,\n});\n\nconst panelClasses = (animated: boolean, slideIn: boolean, placement: 'right' | 'left', className: string | undefined) =>\n    cn(\n        'layer-1 fixed top-(--ui-side-panel-top,3rem) z-[9000] box-border grid h-[calc(100%-var(--ui-side-panel-top,3rem))] w-[clamp(16rem,var(--_size),100%)] max-w-full min-w-[16rem] min-[42rem]:max-w-[75vw]',\n        // every band takes this surface; a design can raise it (--ui-overlay-background; Carbon: layer 1)\n        '[--_surface:var(--ui-overlay-background,var(--ui-layer-1))] translate-x-0 bg-(--_surface) text-ink',\n        animated ? 'grid-rows-[1fr_auto]' : 'grid-rows-[auto_1fr_auto]',\n        slideIn ? 'shadow-none' : 'shadow-[0_2px_4px_var(--ui-overlay)]',\n        placement === 'left' ? 'start-0 [border-block:0_solid_var(--ui-border-subtle-2)] [border-inline-start:0_solid_var(--ui-border-subtle-2)] [border-inline-end:var(--ui-overlay-border,1px_solid_var(--ui-border-subtle-2))]' : 'end-0 [border-block:0_solid_var(--ui-border-subtle-2)] [border-inline-end:0_solid_var(--ui-border-subtle-2)] [border-inline-start:var(--ui-overlay-border,1px_solid_var(--ui-border-subtle-2))]',\n        // the edge that faces the page can round (--ui-side-panel-radius; Carbon: square)\n        placement === 'left' ? 'rounded-se-[var(--ui-side-panel-radius,0px)] rounded-ee-[var(--ui-side-panel-radius,0px)]' : 'rounded-ss-[var(--ui-side-panel-radius,0px)] rounded-es-[var(--ui-side-panel-radius,0px)]',\n        'forced-colors:border forced-colors:border-[CanvasText]',\n        className,\n    );\n\n/** How far the header has collapsed (0 … 1) as the content scrolls. */\nfunction followScroll(panel: HTMLElement, scrollTop: number) {\n    const distance = Number(panel.style.getPropertyValue('--_distance')) || 1;\n    panel.style.setProperty('--_progress', String(Math.min(scrollTop, distance) / distance));\n}\n\n/** The action buttons: Carbon's ActionSet for the panel's size (xs counts as sm), 64px (48px condensed). */\nfunction PanelActions({ actions, size, condensed }: Readonly<{ actions: readonly ActionSetAction[]; size: SidePanelSize; condensed: boolean }>) {\n    if (actions.length === 0) return null;\n    const actionSize: ActionSetSize = size === 'xs' ? 'sm' : size;\n    const stacking = willStack(actionSize, actions.length);\n    return (\n        <div className={cn('sticky bottom-0 flex w-full justify-end border-0 border-t border-solid border-border-subtle-2 bg-(--_surface)', actionRowClasses, stacking && stackedClasses, condensed ? '[--ui-field-height-lg:48px]' : '[--ui-field-height-lg:64px]')}>\n            <ActionButtons actions={actions} size={actionSize} stacking={stacking} />\n        </div>\n    );\n}\n\n/**\n * Carbon for IBM Products `SidePanel` as React + Tailwind, the look and rules of `<ui-side-panel>`: a panel sliding in\n * from the right (or left) under the 48px UI shell header, xs 16rem … 2xl 80rem (at most 75vw from md screens).\n * Slide-over keeps Tab inside and closes on Esc; `includeOverlay` dims the page; `slideIn` pushes the page aside\n * instead. Header: `aboveTitle`, `labelText`, `heading`, `subtitle`, `belowTitle`, ×, a back button from `currentStep`\n * 1, `actionToolbar`; the label and subtitle fade and the heading shrinks as the content scrolls (`animateTitle`).\n * `actions`: Carbon's ActionSet for the panel's size (64px buttons; 48px `condensedActions`). The content sits on\n * layer 1. `onClose` follows once it has slid out.\n */\nexport function SidePanel({\n    open,\n    onRequestClose,\n    onClose,\n    heading,\n    labelText,\n    subtitle,\n    aboveTitle,\n    belowTitle,\n    actionToolbar,\n    actions = [],\n    size = 'md',\n    placement = 'right',\n    slideIn = false,\n    includeOverlay = false,\n    preventCloseOnClickOutside = false,\n    selectorInitialFocus,\n    selectorPageContent,\n    hideCloseButton = false,\n    closeIconDescription,\n    closeIconTooltipAlignment = 'left',\n    navigationBackIconDescription,\n    currentStep = 0,\n    onNavigationBack,\n    condensedActions = false,\n    animateTitle = true,\n    lang,\n    className,\n    style,\n    ref,\n    children,\n    ...rest\n}: Readonly<SidePanelProps>) {\n    const t = useTranslation(lang).common;\n    const panel = useRef<HTMLElement>(null);\n    const panelRef = useMergedRefs(panel, ref);\n    const animated = useAnimatedTitle(animateTitle && !!heading, open, panel);\n\n    // a new step starts at the top\n    useEffect(() => {\n        panel.current?.querySelector('[data-scrolls]')?.scrollTo?.({ top: 0 });\n    }, [currentStep]);\n\n    const onScroll = (event: UIEvent<HTMLElement>) => {\n        if (animated && panel.current) followScroll(panel.current, event.currentTarget.scrollTop);\n    };\n\n    // Carbon: 40px × and back buttons beside the actions of a large panel\n    const iconSize = actions.length > 0 && size.includes('l') ? 'md' : 'sm';\n    const toolbar = !!actionToolbar;\n    const vars = { ...panelVars(size, toolbar, !!subtitle), ...style } as CSSProperties;\n\n    return (\n        <SidePanelPrimitive.Root\n            open={open}\n            onRequestClose={onRequestClose}\n            placement={placement}\n            slideIn={slideIn}\n            closeOnOverlayClick={!preventCloseOnClickOutside}\n            selectorInitialFocus={selectorInitialFocus}\n            selectorPageContent={selectorPageContent}\n            // opened over a modal, the panel goes into a modal <dialog> of its own: it draws nothing itself\n            layerClassName=\"backdrop:bg-transparent\"\n        >\n            <ClosedNotice onClose={onClose} />\n            {includeOverlay ? <SidePanelPrimitive.Overlay className=\"fixed inset-0 z-[6000] bg-overlay\" /> : null}\n            <SidePanelPrimitive.Panel\n                {...rest}\n                ref={panelRef}\n                aria-label={heading || rest['aria-label']}\n                style={vars}\n                className={panelClasses(animated, slideIn, placement, className)}\n            >\n                <div data-scrolls={animated ? '' : undefined} onScroll={onScroll} className={animated ? 'grid grid-rows-[auto_1fr] overflow-x-hidden overflow-y-auto' : 'contents'}>\n                    <PanelHeader\n                        heading={heading}\n                        labelText={labelText}\n                        subtitle={subtitle}\n                        aboveTitle={aboveTitle}\n                        belowTitle={belowTitle}\n                        actionToolbar={actionToolbar}\n                        currentStep={currentStep}\n                        iconSize={iconSize}\n                        animated={animated}\n                        closeLabel={hideCloseButton ? undefined : (closeIconDescription ?? t.close)}\n                        closePlacement={closeIconTooltipAlignment}\n                        backLabel={navigationBackIconDescription ?? t.back}\n                        onBack={onNavigationBack}\n                    />\n                    <div data-scrolls={animated ? undefined : ''} className={cn('min-h-0 px-4 pb-4', !animated && 'overflow-x-hidden overflow-y-auto', toolbar && 'pt-2')}>\n                        <Layer level={1} className=\"contents\">\n                            {children}\n                        </Layer>\n                    </div>\n                </div>\n                <PanelActions actions={actions} size={size} condensed={condensedActions} />\n            </SidePanelPrimitive.Panel>\n        </SidePanelPrimitive.Root>\n    );\n}\n"
    }
  ]
}
