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"sourcesContent":["@import \"575a5a16650d7070\";\n@import \"7a0058ba44ec735a\";\n@import \"ea0c0ad20f1e1c01\";\n@import \"1a91a7d853a67795\";\n@import \"b645d7882760dc18\";\n@import \"5aa00674bbf9e612\";\n@import \"9d65793a05791106\";\n@import \"2976d7d1f8a0759d\";\n@import \"713e94facc5ee3f3\";\n@import \"64129d49d07323ce\";\n@import \"5458e36ec7f2a11f\";\n","/*\n * Copyright 2024 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n TabListProps as AriaTabListProps,\n TabPanel as AriaTabPanel,\n TabPanelProps as AriaTabPanelProps,\n TabProps as AriaTabProps,\n TabsProps as AriaTabsProps,\n ContextValue,\n Group,\n Provider,\n Tab as RACTab,\n TabList as RACTabList,\n Tabs as RACTabs,\n SelectionIndicator,\n TabListStateContext,\n TabRenderProps\n} from 'react-aria-components';\nimport {baseColor, focusRing, size, style} from '../style' with {type: 'macro'};\nimport {centerBaseline} from './CenterBaseline';\nimport {Collection, DOMRef, DOMRefValue, GlobalDOMAttributes, Key, Node, Orientation, RefObject} from '@react-types/shared';\nimport {CollectionBuilder} from '@react-aria/collections';\nimport {createContext, forwardRef, ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';\nimport {getAllowedOverrides, StyleProps, StylesPropWithHeight, UnsafeStyles} from './style-utils' with {type: 'macro'};\nimport {IconContext} from './Icon';\nimport {inertValue, useEffectEvent, useId, useLabels, useLayoutEffect, useResizeObserver} from '@react-aria/utils';\nimport {Picker, PickerItem} from './TabsPicker';\nimport {Text, TextContext} from './Content';\nimport {useControlledState} from '@react-stately/utils';\nimport {useDOMRef} from '@react-spectrum/utils';\nimport {useHasTabbableChild} from '@react-aria/focus';\nimport {useLocale} from '@react-aria/i18n';\nimport {useSpectrumContextProps} from './useSpectrumContextProps';\n\nexport interface TabsProps extends Omit<AriaTabsProps, 'className' | 'style' | 'children' | keyof GlobalDOMAttributes>, UnsafeStyles {\n /** Spectrum-defined styles, returned by the `style()` macro. */\n styles?: StylesPropWithHeight,\n /** The content to display in the tabs. */\n children: ReactNode,\n /**\n * The amount of space between the tabs.\n * @default 'regular'\n */\n density?: 'compact' | 'regular',\n /**\n * Defines if the text within the tabs should be hidden and only the icon should be shown.\n * The text is always visible when the item is collapsed into a picker.\n * @default 'show'\n */\n labelBehavior?: 'show' | 'hide'\n}\n\nexport interface TabProps extends Omit<AriaTabProps, 'children' | 'style' | 'className' | 'onClick' | keyof GlobalDOMAttributes>, StyleProps {\n /** The content to display in the tab. */\n children: ReactNode\n}\n\nexport interface TabListProps<T> extends Omit<AriaTabListProps<T>, 'style' | 'className' | 'aria-label' | 'aria-labelledby' | keyof GlobalDOMAttributes>, StyleProps {\n /** The content to display in the tablist. */\n children: ReactNode | ((item: T) => ReactNode)\n}\n\nexport interface TabPanelProps extends Omit<AriaTabPanelProps, 'children' | 'style' | 'className' | keyof GlobalDOMAttributes>, UnsafeStyles {\n /** Spectrum-defined styles, returned by the `style()` macro. */\n styles?: StylesPropWithHeight,\n /** The content to display in the tab panels. */\n children: ReactNode\n}\n\nexport const TabsContext = createContext<ContextValue<Partial<TabsProps>, DOMRefValue<HTMLDivElement>>>(null);\nconst InternalTabsContext = createContext<Partial<TabsProps> & {\n tablistRef?: RefObject<HTMLDivElement | null>,\n selectedKey?: Key | null\n}>({});\n\ninterface CollapseContextType {\n showTabs: boolean,\n menuId: string,\n valueId: string,\n ariaLabel?: string | undefined,\n ariaDescribedBy?: string | undefined,\n tabs: Array<Node<any>>,\n listRef?: RefObject<HTMLDivElement | null>,\n onSelectionChange?: (key: Key) => void\n}\n\nconst CollapseContext = createContext<CollapseContextType>({\n showTabs: true,\n menuId: '',\n valueId: '',\n tabs: []\n});\n\nconst tabs = style({\n position: 'relative',\n display: 'flex',\n flexShrink: 0,\n font: 'ui',\n flexDirection: {\n orientation: {\n horizontal: 'column'\n }\n }\n}, getAllowedOverrides({height: true}));\n\n/**\n * Tabs organize content into multiple sections and allow users to navigate between them. The content under the set of tabs should be related and form a coherent unit.\n */\nexport const Tabs = forwardRef(function Tabs(props: TabsProps, ref: DOMRef<HTMLDivElement>) {\n [props, ref] = useSpectrumContextProps(props, ref, TabsContext);\n let {\n density = 'regular',\n isDisabled,\n disabledKeys,\n orientation = 'horizontal',\n labelBehavior = 'show'\n } = props;\n let domRef = useDOMRef(ref);\n let [value, setValue] = useControlledState(props.selectedKey, props.defaultSelectedKey ?? null!, props.onSelectionChange);\n\n if (!props['aria-label'] && !props['aria-labelledby']) {\n throw new Error('An aria-label or aria-labelledby prop is required on Tabs for accessibility.');\n }\n\n let tablistRef = useRef<HTMLDivElement | null>(null);\n\n return (\n <Provider\n values={[\n [InternalTabsContext, {\n density,\n isDisabled,\n orientation,\n disabledKeys,\n selectedKey: value,\n tablistRef,\n onSelectionChange: setValue,\n labelBehavior,\n 'aria-label': props['aria-label'],\n 'aria-labelledby': props['aria-labelledby']\n }]\n ]}>\n <CollectionBuilder content={props.children}>\n {collection => (\n <CollapsingTabs\n {...props}\n selectedKey={value}\n onSelectionChange={setValue}\n collection={collection}\n containerRef={domRef} />\n )}\n </CollectionBuilder>\n </Provider>\n );\n});\n\nconst tablist = style({\n display: 'flex',\n gap: {\n orientation: {\n horizontal: {\n density: {\n compact: 24,\n regular: 32\n },\n labelBehavior: {\n hide: {\n density: {\n compact: 16,\n regular: 24\n }\n }\n }\n }\n }\n },\n flexDirection: {\n orientation: {\n vertical: 'column'\n }\n },\n marginEnd: {\n orientation: {\n vertical: 20\n }\n },\n marginStart: {\n orientation: {\n vertical: 12\n }\n },\n minWidth: 'min'\n});\n\nconst tablistWrapper = style({\n position: 'relative',\n minWidth: 0,\n flexShrink: 0,\n flexGrow: 0\n}, getAllowedOverrides());\n\nexport function TabList<T extends object>(props: TabListProps<T>): ReactNode | null {\n let {showTabs, menuId, valueId, tabs, listRef, onSelectionChange, ariaLabel, ariaDescribedBy} = useContext(CollapseContext) ?? {};\n let {density, orientation, labelBehavior} = useContext(InternalTabsContext);\n\n if (showTabs) {\n return <TabListInner {...props} />;\n }\n\n return (\n <div className={tablistWrapper(null, props.styles)}>\n {listRef && <div className={tablist({orientation, labelBehavior, density})}>\n <HiddenTabs items={tabs} density={density} listRef={listRef} />\n </div>}\n <TabsMenu\n id={menuId}\n valueId={valueId}\n items={tabs}\n onSelectionChange={onSelectionChange}\n aria-label={ariaLabel}\n aria-describedby={ariaDescribedBy} />\n </div>\n );\n}\n\nfunction TabListInner<T extends object>(props: TabListProps<T>) {\n let {\n tablistRef,\n orientation,\n density,\n labelBehavior,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy\n } = useContext(InternalTabsContext) ?? {};\n let {tabs, listRef} = useContext(CollapseContext) ?? {};\n\n return (\n <div\n style={props.UNSAFE_style}\n className={\n (props.UNSAFE_className || '') +\n tablistWrapper(null, props.styles)}>\n {listRef && <div className={tablist({orientation, labelBehavior, density})}>\n <HiddenTabs items={tabs} density={density} listRef={listRef} />\n </div>}\n <RACTabList\n {...props}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n ref={tablistRef}\n className={renderProps => tablist({...renderProps, labelBehavior, density})} />\n </div>\n );\n}\n\nconst selectedIndicator = style<{isDisabled: boolean, orientation?: Orientation}>({\n position: 'absolute',\n backgroundColor: {\n default: 'neutral',\n isDisabled: 'disabled',\n forcedColors: {\n default: 'Highlight',\n isDisabled: 'GrayText'\n }\n },\n height: {\n default: 'full',\n orientation: {\n horizontal: '[2px]'\n }\n },\n width: {\n default: 'full',\n orientation: {\n vertical: '[2px]'\n }\n },\n contain: 'strict',\n transition: {\n default: '[translate,width,height]',\n '@media (prefers-reduced-motion: reduce)': 'none'\n },\n transitionDuration: 200,\n transitionTimingFunction: 'out',\n bottom: {\n default: 0\n },\n top: {\n orientation: {\n vertical: 0\n }\n },\n left: {\n orientation: {\n horizontal: 0\n }\n },\n insetStart: {\n orientation: {\n vertical: -12\n }\n },\n borderStyle: 'none',\n borderRadius: 'full'\n});\n\nconst tab = style<TabRenderProps & {density?: 'compact' | 'regular', labelBehavior?: 'show' | 'hide', orientation?: Orientation}>({\n ...focusRing(),\n display: 'flex',\n color: {\n default: baseColor('neutral-subdued'),\n isSelected: baseColor('neutral'),\n isDisabled: 'disabled',\n forcedColors: {\n isSelected: 'Highlight',\n isDisabled: 'GrayText'\n }\n },\n borderRadius: 'sm',\n gap: 'text-to-visual',\n height: {\n orientation: {\n horizontal: {\n density: {\n compact: 32,\n regular: 48\n }\n }\n }\n },\n minHeight: {\n orientation: {\n vertical: {\n density: {\n compact: 32,\n regular: 48\n }\n }\n }\n },\n alignItems: 'center',\n position: 'relative',\n cursor: 'default',\n textDecoration: 'none',\n flexShrink: 0,\n transition: 'default',\n paddingX: {\n labelBehavior: {\n hide: size(6)\n }\n },\n disableTapHighlight: true\n}, getAllowedOverrides());\n\nconst icon = style({\n display: 'block',\n flexShrink: 0,\n '--iconPrimary': {\n type: 'fill',\n value: 'currentColor'\n }\n});\n\nexport function Tab(props: TabProps): ReactNode {\n let {density, orientation, labelBehavior} = useContext(InternalTabsContext) ?? {};\n\n let contentId = useId();\n let ariaLabelledBy = props['aria-labelledby'] || '';\n\n return (\n <RACTab\n {...props}\n // @ts-ignore\n originalProps={props}\n aria-labelledby={`${labelBehavior === 'hide' ? contentId : ''} ${ariaLabelledBy}`}\n style={props.UNSAFE_style}\n className={renderProps => (props.UNSAFE_className || '') + tab({...renderProps, density, labelBehavior, orientation}, props.styles)}>\n {({\n // @ts-ignore\n isMenu,\n isDisabled\n }) => {\n if (isMenu) {\n return props.children;\n } else {\n return (\n <Provider\n values={[\n [TextContext, {\n id: contentId,\n styles:\n style({\n order: 1,\n display: {\n labelBehavior: {\n hide: 'none'\n }\n }\n })({labelBehavior})\n }],\n [IconContext, {\n render: centerBaseline({slot: 'icon', styles: style({order: 0})}),\n styles: icon\n }]\n ]}>\n <TabInner\n orientation={orientation!}\n isDisabled={isDisabled}>\n {typeof props.children === 'string' ? <Text>{props.children}</Text> : props.children}\n </TabInner>\n </Provider>\n );\n }\n }}\n </RACTab>\n );\n}\n\nfunction TabInner({isDisabled, orientation, children}: {\n isDisabled: boolean,\n orientation: Orientation,\n children: ReactNode\n}) {\n let ref = useRef<HTMLDivElement | null>(null);\n let isHidden = useContext(HiddenTabsContext);\n\n return (\n <>\n {!isHidden && <SelectionIndicator ref={ref} className={selectedIndicator({isDisabled, orientation})} />}\n {children}\n </>\n );\n}\n\n\nconst tabPanel = style({\n ...focusRing(),\n marginTop: 4,\n color: 'gray-800',\n flexGrow: 1,\n minHeight: 0,\n display: {\n default: 'block',\n isInert: 'none'\n }\n}, getAllowedOverrides({height: true}));\n\nexport function TabPanel(props: TabPanelProps): ReactNode | null {\n let {showTabs} = useContext(CollapseContext);\n let {selectedKey} = useContext(InternalTabsContext);\n if (showTabs) {\n return (\n <AriaTabPanel\n {...props}\n style={props.UNSAFE_style}\n className={renderProps => (props.UNSAFE_className ?? '') + tabPanel(renderProps, props.styles)} />\n );\n }\n\n if (props.id !== selectedKey) {\n return null;\n }\n\n return <CollapsedTabPanel {...props} />;\n}\n\nfunction CollapsedTabPanel(props: TabPanelProps) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n let {UNSAFE_style, UNSAFE_className = '', id, shouldForceMount, ...otherProps} = props;\n let {menuId, valueId} = useContext(CollapseContext);\n let ref = useRef(null);\n let tabIndex = useHasTabbableChild(ref) ? undefined : 0;\n\n return (\n <Group\n {...otherProps}\n ref={ref}\n aria-labelledby={menuId + ' ' + valueId}\n tabIndex={tabIndex}\n style={UNSAFE_style}\n className={renderProps => UNSAFE_className + tabPanel(renderProps, props.styles)} />\n );\n}\n\nfunction isEveryTabDisabled<T>(collection: Collection<Node<T>> | undefined, disabledKeys: Set<Key>) {\n let testKey: Key | null = null;\n if (collection && collection.size > 0) {\n testKey = collection.getFirstKey();\n\n let index = 0;\n while (testKey && index < collection.size) {\n // We have to check if the item in the collection has a key in disabledKeys or has the isDisabled prop set directly on it\n if (!disabledKeys.has(testKey) && !collection.getItem(testKey)?.props?.isDisabled) {\n return false;\n }\n\n testKey = collection.getKeyAfter(testKey);\n index++;\n }\n return true;\n }\n return false;\n}\n\nconst HiddenTabsContext = createContext(false);\n\nlet HiddenTabs = function (props: {\n listRef: RefObject<HTMLDivElement | null>,\n items: Array<Node<any>>,\n size?: string,\n density?: 'compact' | 'regular'\n}) {\n let {listRef, items = [], size, density} = props;\n\n return (\n <div\n // @ts-ignore\n inert={inertValue(true)}\n ref={listRef}\n className={style({\n display: 'inherit',\n flexDirection: 'inherit',\n gap: 'inherit',\n flexWrap: 'inherit',\n position: 'absolute',\n inset: 0,\n visibility: 'hidden',\n overflow: 'hidden',\n opacity: 0\n })}>\n <HiddenTabsContext.Provider value>\n {items.map((item) => {\n // pull off individual props as an allow list, don't want refs or other props getting through\n return (\n <div\n data-hidden-tab\n style={item.props.UNSAFE_style}\n key={item.key}\n className={item.props.className({size, density})}>\n {item.props.children({size, density})}\n </div>\n );\n })}\n </HiddenTabsContext.Provider>\n </div>\n );\n};\n\nlet TabsMenu = (props: {valueId: string, items: Array<Node<any>>, onSelectionChange: TabsProps['onSelectionChange']} & Omit<TabsProps, 'children'>) => {\n let {id, items, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, valueId} = props;\n let {density, onSelectionChange: _onSelectionChange, selectedKey, isDisabled, disabledKeys, labelBehavior} = useContext(InternalTabsContext);\n let onSelectionChange = useCallback((key: Key | null) => {\n if (key != null) {\n _onSelectionChange?.(key);\n }\n }, [_onSelectionChange]);\n let state = useContext(TabListStateContext);\n let allKeysDisabled = useMemo(() => {\n return isEveryTabDisabled(state?.collection, disabledKeys ? new Set(disabledKeys) : new Set());\n }, [state?.collection, disabledKeys]);\n let labelProps = useLabels({\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy\n });\n\n return (\n <div\n className={style({\n display: 'flex',\n flexShrink: 0,\n alignItems: 'center',\n height: {\n density: {\n compact: 32,\n regular: 48\n }\n }})({density})}>\n <Picker\n id={id}\n valueId={valueId}\n {...labelProps}\n aria-describedby={props['aria-describedby']}\n aria-details={props['aria-details']}\n isDisabled={isDisabled || allKeysDisabled}\n density={density!}\n labelBehavior={labelBehavior}\n items={items}\n disabledKeys={disabledKeys}\n selectedKey={selectedKey}\n onSelectionChange={onSelectionChange}>\n {(item: Node<any>) => {\n return (\n <PickerItem\n {...item.props.originalProps}\n isDisabled={isDisabled || allKeysDisabled}\n key={item.key}>\n {item.props.children({density, isMenu: true})}\n </PickerItem>\n );\n }}\n </Picker>\n </div>\n );\n};\n\nlet CollapsingTabs = ({collection, containerRef, ...props}: {collection: Collection<Node<unknown>>, containerRef: any} & TabsProps) => {\n let {orientation = 'horizontal', onSelectionChange} = props;\n let [showItems, _setShowItems] = useState(true);\n showItems = orientation === 'vertical' ? true : showItems;\n let setShowItems = useCallback((value: boolean) => {\n if (orientation === 'vertical') {\n // if orientation is vertical, we always show the items\n _setShowItems(true);\n } else {\n _setShowItems(value);\n }\n }, [orientation]);\n\n let {direction} = useLocale();\n\n let children = useMemo(() => [...collection], [collection]);\n\n let listRef = useRef<HTMLDivElement | null>(null);\n\n let updateOverflow = () => {\n if (orientation === 'vertical' || !listRef.current || !containerRef?.current) {\n return;\n }\n let container = listRef.current;\n let containerRect = container.getBoundingClientRect();\n let tabs = container.querySelectorAll('[data-hidden-tab]');\n let lastTab = tabs[tabs.length - 1];\n let lastTabRect = lastTab.getBoundingClientRect();\n if (direction === 'ltr') {\n setShowItems?.(lastTabRect.right <= containerRect.right);\n } else {\n setShowItems?.(lastTabRect.left >= containerRect.left);\n }\n };\n\n let updateOverflowEffect = useEffectEvent(updateOverflow);\n\n useResizeObserver({ref: containerRef, onResize: updateOverflow});\n\n useLayoutEffect(() => {\n if (collection.size > 0) {\n queueMicrotask(updateOverflowEffect);\n }\n }, [collection.size]);\n\n // start with null so that the first render won't have a flicker\n let prevOrientation = useRef<Orientation | null>(null);\n useLayoutEffect(() => {\n if (collection.size > 0 && prevOrientation.current !== orientation) {\n updateOverflowEffect();\n }\n prevOrientation.current = orientation;\n }, [collection.size, orientation]);\n\n useEffect(() => {\n // Recalculate visible tags when fonts are loaded.\n document.fonts?.ready.then(() => updateOverflowEffect());\n }, []);\n\n let menuId = useId();\n let valueId = useId();\n\n let contents: ReactNode;\n if (showItems) {\n contents = (\n <RACTabs\n {...props}\n className=\"\"\n style={{display: 'contents'}}>\n {props.children}\n </RACTabs>\n );\n } else {\n contents = (\n <>\n <CollapseContext.Provider value={{showTabs: false, tabs: children, menuId, valueId, listRef: listRef, onSelectionChange, ariaLabel: props['aria-label'], ariaDescribedBy: props['aria-labelledby']}}>\n {props.children}\n </CollapseContext.Provider>\n </>\n );\n }\n\n return (\n <div style={props.UNSAFE_style} className={(props.UNSAFE_className || '') + tabs({orientation}, props.styles)} ref={containerRef}>\n <CollapseContext.Provider value={{showTabs: true, menuId, valueId, tabs: children, listRef: listRef}}>\n {contents}\n </CollapseContext.Provider>\n </div>\n );\n};\n"],"names":[],"version":3,"file":"Tabs.css.map"}