@spark-ui/components 18.2.2 → 18.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("class-variance-authority"),t=require("react"),n=require("react/jsx-runtime"),r=require("@spark-ui/hooks/use-merge-refs"),i=require("@spark-ui/components/form-field");var a=(0,e.cva)([`default:self-start`,`group inline-flex flex-wrap`,`relative items-stretch min-w-max`,`rounded-xl p-sm`,`bg-surface border-sm border-outline`]),o=(0,e.cva)([`relative z-raised min-h-sz-44 focus-visible:outline-none`,`flex flex-auto items-center justify-center gap-md`,`default:px-lg default:py-md`,`rounded-[20px]`,`cursor-pointer select-none`,`font-medium`,`transition-colors duration-150`,`outline-none`,`focus-visible:u-outline`,`data-disabled:cursor-not-allowed data-disabled:opacity-dim-3`,`data-checked:text-on-support-container`,`data-checked:[&>[data-spark-segmented-control-text]]:[text-shadow:0.35px_0_currentColor,-0.35px_0_currentColor]`]),s=(0,e.cva)([`absolute z-base`,`rounded-[20px]`,`bg-support-container border-md border-support`,`group-has-focus-visible:border-focus`,`transition-[left,top,width,height] duration-200 ease-in-out`,`pointer-events-none`]),c=(0,t.createContext)({}),l=()=>{let e=(0,t.useContext)(c);if(!e)throw Error(`useSegmentedControlContext must be used within a SegmentedControlContext Provider`);return e},u=({itemValues:e,containerRef:t,onValueChange:n})=>({handleKeyDown:r=>{let i=r.target.getAttribute(`data-value`);if(!i)return;let a=e.indexOf(i);if(a===-1)return;let o=null;if(o=d(r.key,a,e.length),o!==null&&o!==a){r.preventDefault();let i=0,a=e.length;for(;i<a;){let a=e[o];if(!a)return;let s=t.current?.querySelector(`[data-value="${CSS.escape(a)}"]`);if(s&&!s.hasAttribute(`data-disabled`)){s.focus(),n(a);return}let c=r.key===`ArrowRight`||r.key===`ArrowDown`?1:-1;o=(o+c+e.length)%e.length,i++}}}});function d(e,t,n){switch(e){case`ArrowRight`:case`ArrowDown`:return(t+1)%n;case`ArrowLeft`:case`ArrowUp`:return(t-1+n)%n;default:return null}}var f=e=>{let n=null;return t.Children.forEach(e,e=>{n===null&&(0,t.isValidElement)(e)&&typeof e.props.value==`string`&&(n=e.props.value)}),n},p=({value:e,defaultValue:o,onValueChange:s,className:l,children:d,rowLength:p,name:m,ref:h,...g})=>{let _=(0,t.useRef)(null),v=(0,r.useMergeRefs)(_,h),y=f(d),b=e!==void 0,[x,S]=(0,t.useState)(()=>o??y),C=b?e??null:x,w=e=>{b||S(e),s?.(e)},{labelId:T,description:E,isRequired:D,isInvalid:O,name:k}=(0,i.useFormFieldControl)(),A=m??k,j=[];t.Children.forEach(d,e=>{(0,t.isValidElement)(e)&&typeof e.props.value==`string`&&j.push(e.props.value)});let{handleKeyDown:M}=u({itemValues:j,containerRef:_,onValueChange:w}),N=p?{"--segmented-control-cols":p,rowGap:`var(--spacing-md)`}:void 0;return(0,n.jsx)(c,{value:{checkedValue:C,containerRef:_,onValueChange:w,name:A,rowLength:p,itemValues:j},children:(0,n.jsx)(`div`,{ref:v,role:`radiogroup`,"data-spark-component":`segmented-control`,className:a({className:l}),style:N,"aria-labelledby":T,"aria-describedby":E,"aria-required":D||void 0,"aria-invalid":O||void 0,onKeyDown:M,...g,children:d})})};p.displayName=`SegmentedControl`;var m=({className:e,ref:r,...i})=>{let{checkedValue:a,containerRef:o}=l(),[c,u]=(0,t.useState)(null)
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("class-variance-authority"),t=require("react"),n=require("react/jsx-runtime"),r=require("@spark-ui/hooks/use-merge-refs"),i=require("@spark-ui/components/form-field");var a=(0,e.cva)([`default:self-start`,`group inline-flex flex-wrap`,`relative items-stretch min-w-max`,`rounded-xl p-sm`,`bg-surface border-sm border-outline`]),o=(0,e.cva)([`relative z-raised min-h-sz-44 focus-visible:outline-none`,`flex flex-auto items-center justify-center gap-md`,`default:px-lg default:py-md`,`rounded-[20px]`,`cursor-pointer select-none`,`font-medium`,`transition-colors duration-150`,`outline-none`,`focus-visible:u-outline`,`data-disabled:cursor-not-allowed data-disabled:opacity-dim-3`,`data-checked:text-on-support-container`,`data-checked:[&>[data-spark-segmented-control-text]]:[text-shadow:0.35px_0_currentColor,-0.35px_0_currentColor]`]),s=(0,e.cva)([`absolute z-base`,`rounded-[20px]`,`bg-support-container border-md border-support`,`group-has-focus-visible:border-focus`,`transition-[left,top,width,height] duration-200 ease-in-out`,`pointer-events-none`]),c=(0,t.createContext)({}),l=()=>{let e=(0,t.useContext)(c);if(!e)throw Error(`useSegmentedControlContext must be used within a SegmentedControlContext Provider`);return e},u=({itemValues:e,containerRef:t,onValueChange:n})=>({handleKeyDown:r=>{let i=r.target.getAttribute(`data-value`);if(!i)return;let a=e.indexOf(i);if(a===-1)return;let o=null;if(o=d(r.key,a,e.length),o!==null&&o!==a){r.preventDefault();let i=0,a=e.length;for(;i<a;){let a=e[o];if(!a)return;let s=t.current?.querySelector(`[data-value="${CSS.escape(a)}"]`);if(s&&!s.hasAttribute(`data-disabled`)){s.focus(),n(a);return}let c=r.key===`ArrowRight`||r.key===`ArrowDown`?1:-1;o=(o+c+e.length)%e.length,i++}}}});function d(e,t,n){switch(e){case`ArrowRight`:case`ArrowDown`:return(t+1)%n;case`ArrowLeft`:case`ArrowUp`:return(t-1+n)%n;default:return null}}var f=e=>{let n=null;return t.Children.forEach(e,e=>{n===null&&(0,t.isValidElement)(e)&&typeof e.props.value==`string`&&(n=e.props.value)}),n},p=({value:e,defaultValue:o,onValueChange:s,className:l,children:d,rowLength:p,name:m,ref:h,...g})=>{let _=(0,t.useRef)(null),v=(0,r.useMergeRefs)(_,h),y=f(d),b=e!==void 0,[x,S]=(0,t.useState)(()=>o??y),C=b?e??null:x,w=e=>{b||S(e),s?.(e)},{labelId:T,description:E,isRequired:D,isInvalid:O,name:k}=(0,i.useFormFieldControl)(),A=m??k,j=[];t.Children.forEach(d,e=>{(0,t.isValidElement)(e)&&typeof e.props.value==`string`&&j.push(e.props.value)});let{handleKeyDown:M}=u({itemValues:j,containerRef:_,onValueChange:w}),N=p?{"--segmented-control-cols":p,rowGap:`var(--spacing-md)`}:void 0;return(0,n.jsx)(c,{value:{checkedValue:C,containerRef:_,onValueChange:w,name:A,rowLength:p,itemValues:j},children:(0,n.jsx)(`div`,{ref:v,role:`radiogroup`,"data-spark-component":`segmented-control`,className:a({className:l}),style:N,"aria-labelledby":T,"aria-describedby":E,"aria-required":D||void 0,"aria-invalid":O||void 0,onKeyDown:M,...g,children:d})})};p.displayName=`SegmentedControl`;var m=(e,t)=>t?Array.from(e.querySelectorAll(`[data-value]`)).find(e=>e.dataset.value===t)??null:null,h=({className:e,ref:r,...i})=>{let{checkedValue:a,containerRef:o}=l(),[c,u]=(0,t.useState)(null);if((0,t.useEffect)(()=>{let e=o.current;if(!e)return;let t=m(e,a),n=()=>{let e=o.current;if(!e){u(null);return}let t=m(e,a);if(!t){u(null);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=t.offsetWidth>0?r.width/t.offsetWidth:1,s=t.offsetHeight>0?r.height/t.offsetHeight:1;u({left:(r.left-n.left)/i-e.clientLeft,top:(r.top-n.top)/s-e.clientTop,width:r.width/i,height:r.height/s})};n();let r=typeof ResizeObserver<`u`?new ResizeObserver(()=>{n()}):null;return r?.observe(e),t&&r?.observe(t),window.addEventListener(`resize`,n,{passive:!0}),window.visualViewport?.addEventListener(`resize`,n,{passive:!0}),()=>{r?.disconnect(),window.removeEventListener(`resize`,n),window.visualViewport?.removeEventListener(`resize`,n)}},[o,a]),!c)return null;let d={left:c.left,top:c.top,width:c.width,height:c.height};return(0,n.jsx)(`span`,{ref:r,"data-spark-component":`segmented-control-indicator`,"aria-hidden":!0,className:s({className:e}),style:d,...i})};h.displayName=`SegmentedControl.Indicator`;var g=({value:e,disabled:r=!1,children:i,className:a,ref:s,...c})=>{let{checkedValue:u,onValueChange:d,name:f,rowLength:p,itemValues:m}=l(),h=u===e,g=()=>{r||d(e)},_=t.Children.toArray(i).map((e,t)=>typeof e==`string`||typeof e==`number`?(0,n.jsx)(`span`,{"data-spark-segmented-control-text":!0,children:e},`text-${t}`):e),v=m.indexOf(e),y=p?{flexBasis:`calc(100% / var(--segmented-control-cols))`}:void 0,b=!1;if(p&&p>0&&v!==-1){let e=p,t=v%e;b=Math.floor(v/e)<Math.ceil(m.length/e)-1&&t===0}return(0,n.jsxs)(`button`,{ref:s,type:`button`,role:`radio`,"data-spark-component":`segmented-control-item`,"data-value":e,"aria-checked":h,"data-checked":h||void 0,"data-disabled":r||void 0,disabled:r,tabIndex:h?0:-1,className:o({className:a}),style:y,onClick:g,...c,children:[_,f&&h&&(0,n.jsx)(`input`,{type:`hidden`,name:f,value:e}),b&&p&&(0,n.jsx)(`div`,{className:`bg-outline/dim-3 -mx-sm absolute left-0 h-px`,style:{bottom:`calc(var(--spacing-md) / -2)`,width:`calc(${p*100}% + var(--spacing-sm) * 2)`},"aria-hidden":`true`})]})};g.displayName=`SegmentedControl.Item`;var _=Object.assign(p,{Item:g,Indicator:h});_.displayName=`SegmentedControl`,g.displayName=`SegmentedControl.Item`,h.displayName=`SegmentedControl.Indicator`,exports.SegmentedControl=_;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/segmented-control/SegmentedControl.styles.ts","../../src/segmented-control/SegmentedControlContext.tsx","../../src/segmented-control/useSegmentedControlNavigation.ts","../../src/segmented-control/SegmentedControl.tsx","../../src/segmented-control/SegmentedControlIndicator.tsx","../../src/segmented-control/SegmentedControlItem.tsx","../../src/segmented-control/index.ts"],"sourcesContent":["import { cva, VariantProps } from 'class-variance-authority'\n\nexport const rootStyles = cva([\n 'default:self-start',\n 'group inline-flex flex-wrap',\n 'relative items-stretch min-w-max',\n 'rounded-xl p-sm',\n 'bg-surface border-sm border-outline',\n])\n\nexport const itemStyles = cva([\n 'relative z-raised min-h-sz-44 focus-visible:outline-none',\n 'flex flex-auto items-center justify-center gap-md',\n 'default:px-lg default:py-md',\n 'rounded-[20px]',\n 'cursor-pointer select-none',\n 'font-medium',\n 'transition-colors duration-150',\n 'outline-none',\n 'focus-visible:u-outline',\n 'data-disabled:cursor-not-allowed data-disabled:opacity-dim-3',\n 'data-checked:text-on-support-container',\n // Avoid layout shift: simulate \"bold\" without changing font metrics.\n // Apply only to wrapped text nodes (not arbitrary nested JSX like Tag).\n 'data-checked:[&>[data-spark-segmented-control-text]]:[text-shadow:0.35px_0_currentColor,-0.35px_0_currentColor]',\n])\n\nexport const indicatorStyles = cva([\n 'absolute z-base',\n 'rounded-[20px]',\n 'bg-support-container border-md border-support',\n 'group-has-focus-visible:border-focus',\n 'transition-[left,top,width,height] duration-200 ease-in-out',\n 'pointer-events-none',\n])\n\nexport type SegmentedControlStylesProps = VariantProps<typeof itemStyles>\n","import { createContext, RefObject, useContext } from 'react'\n\nexport interface SegmentedControlContextInterface {\n checkedValue: string | null\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n name?: string\n rowLength?: number\n itemValues: string[]\n}\n\nexport const SegmentedControlContext = createContext<SegmentedControlContextInterface>(\n {} as SegmentedControlContextInterface\n)\n\nexport const useSegmentedControlContext = () => {\n const context = useContext(SegmentedControlContext)\n\n if (!context) {\n throw Error('useSegmentedControlContext must be used within a SegmentedControlContext Provider')\n }\n\n return context\n}\n","import { KeyboardEvent, RefObject } from 'react'\n\ninterface UseSegmentedControlNavigationProps {\n itemValues: string[]\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n}\n\n/**\n * Custom hook that handles keyboard navigation for SegmentedControl.\n * Uses sequential left/right navigation.\n */\nexport const useSegmentedControlNavigation = ({\n itemValues,\n containerRef,\n onValueChange,\n}: UseSegmentedControlNavigationProps) => {\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // Find the currently focused item (which may differ from checkedValue during keyboard navigation)\n const focusedElement = e.target as HTMLElement\n const focusedValue = focusedElement.getAttribute('data-value')\n\n if (!focusedValue) return\n\n const currentIndex = itemValues.indexOf(focusedValue)\n if (currentIndex === -1) return\n\n let nextIndex: number | null = null\n\n // Always use 1D sequential navigation (left/right only)\n nextIndex = calculate1DNavigation(e.key, currentIndex, itemValues.length)\n\n if (nextIndex !== null && nextIndex !== currentIndex) {\n e.preventDefault()\n\n // Skip disabled items\n let attempts = 0\n const maxAttempts = itemValues.length\n\n while (attempts < maxAttempts) {\n const nextValue = itemValues[nextIndex]\n if (!nextValue) return\n\n const nextItem = containerRef.current?.querySelector<HTMLElement>(\n `[data-value=\"${CSS.escape(nextValue)}\"]`\n )\n\n // If the item is not disabled, focus it and update the value\n if (nextItem && !nextItem.hasAttribute('data-disabled')) {\n nextItem.focus()\n onValueChange(nextValue)\n return\n }\n\n // If disabled, continue in the same direction\n const direction = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1\n nextIndex = (nextIndex + direction + itemValues.length) % itemValues.length\n attempts++\n }\n }\n }\n\n return { handleKeyDown }\n}\n\n/**\n * Calculate next index for 1D sequential navigation.\n * Navigation wraps around at the boundaries.\n */\nfunction calculate1DNavigation(\n key: string,\n currentIndex: number,\n totalItems: number\n): number | null {\n switch (key) {\n case 'ArrowRight':\n case 'ArrowDown':\n return (currentIndex + 1) % totalItems\n case 'ArrowLeft':\n case 'ArrowUp':\n return (currentIndex - 1 + totalItems) % totalItems\n default:\n return null\n }\n}\n","import { useFormFieldControl } from '@spark-ui/components/form-field'\nimport { useMergeRefs } from '@spark-ui/hooks/use-merge-refs'\nimport {\n Children,\n type ComponentProps,\n CSSProperties,\n isValidElement,\n Ref,\n useRef,\n useState,\n} from 'react'\n\nimport type { SegmentedControlStylesProps } from './SegmentedControl.styles'\nimport { rootStyles } from './SegmentedControl.styles'\nimport { SegmentedControlContext } from './SegmentedControlContext'\nimport { useSegmentedControlNavigation } from './useSegmentedControlNavigation'\n\nexport interface SegmentedControlProps\n extends Omit<ComponentProps<'div'>, 'onValueChange'>, SegmentedControlStylesProps {\n /**\n * The controlled selected value.\n */\n value?: string\n /**\n * The uncontrolled default selected value.\n */\n defaultValue?: string\n /**\n * Callback fired when the selected value changes.\n */\n onValueChange?: (value: string) => void\n /**\n * Number of items per row in multi-row layout.\n * When undefined, items display in a single row (default behavior).\n * @default undefined\n * @example\n * // Create 3-column grid with wrapping rows\n * <SegmentedControl rowLength={3}>\n */\n rowLength?: number\n /**\n * The name attribute for the radio group (used in form submissions).\n */\n name?: string\n ref?: Ref<HTMLDivElement>\n}\n\nconst getFirstItemValue = (children: React.ReactNode): string | null => {\n let firstValue: string | null = null\n\n Children.forEach(children, child => {\n if (firstValue !== null) return\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n firstValue = (child.props as { value: string }).value\n }\n })\n\n return firstValue\n}\n\nexport const SegmentedControl = ({\n value,\n defaultValue,\n onValueChange,\n className,\n children,\n rowLength,\n name: nameProp,\n ref,\n ...rest\n}: SegmentedControlProps) => {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const mergedRef = useMergeRefs(containerRef, ref)\n\n const firstValue = getFirstItemValue(children)\n\n const isControlled = value !== undefined\n const [internalValue, setInternalValue] = useState<string | null>(\n () => defaultValue ?? firstValue\n )\n const checkedValue = isControlled ? (value ?? null) : internalValue\n\n const handleValueChange = (newValue: string) => {\n if (!isControlled) {\n setInternalValue(newValue)\n }\n\n onValueChange?.(newValue)\n }\n\n const { labelId, description, isRequired, isInvalid, name: nameFromField } = useFormFieldControl()\n const name = nameProp ?? nameFromField\n\n // Get all item values in order\n const itemValues: string[] = []\n Children.forEach(children, child => {\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n itemValues.push((child.props as { value: string }).value)\n }\n })\n\n // Keyboard navigation (sequential left/right)\n const { handleKeyDown } = useSegmentedControlNavigation({\n itemValues,\n containerRef,\n onValueChange: handleValueChange,\n })\n\n // Compute dynamic flex styles for multi-row layout\n const flexStyles = rowLength\n ? ({\n '--segmented-control-cols': rowLength,\n rowGap: 'var(--spacing-md)',\n } as CSSProperties)\n : undefined\n\n return (\n <SegmentedControlContext\n value={{\n checkedValue,\n containerRef,\n onValueChange: handleValueChange,\n name,\n rowLength,\n itemValues,\n }}\n >\n <div\n ref={mergedRef}\n role=\"radiogroup\"\n data-spark-component=\"segmented-control\"\n className={rootStyles({ className })}\n style={flexStyles}\n aria-labelledby={labelId}\n aria-describedby={description}\n aria-required={isRequired || undefined}\n aria-invalid={isInvalid || undefined}\n onKeyDown={handleKeyDown}\n {...rest}\n >\n {children}\n </div>\n </SegmentedControlContext>\n )\n}\n\nSegmentedControl.displayName = 'SegmentedControl'\n","import { type ComponentProps, type CSSProperties, Ref, useEffect, useMemo, useState } from 'react'\n\nimport { indicatorStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\ninterface IndicatorRect {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport interface SegmentedControlIndicatorProps extends ComponentProps<'span'> {\n ref?: Ref<HTMLSpanElement>\n}\n\n/** The visual indicator that highlights the selected item. Renders a <span> element. */\nexport const SegmentedControlIndicator = ({\n className,\n ref,\n ...rest\n}: SegmentedControlIndicatorProps) => {\n const { checkedValue, containerRef } = useSegmentedControlContext()\n const [rect, setRect] = useState<IndicatorRect | null>(null)\n\n const selector = useMemo(\n () => (checkedValue ? `[data-value=\"${CSS.escape(checkedValue)}\"]` : null),\n [checkedValue]\n )\n\n useEffect(() => {\n const container = containerRef.current\n\n if (!container) {\n return\n }\n\n const selectedItem = selector ? container.querySelector<HTMLElement>(selector) : null\n\n const update = () => {\n const currentContainer = containerRef.current\n if (!currentContainer || !selector) {\n setRect(null)\n\n return\n }\n\n const currentSelected = currentContainer.querySelector<HTMLElement>(selector)\n if (!currentSelected) {\n setRect(null)\n\n return\n }\n\n const containerRect = currentContainer.getBoundingClientRect()\n const itemRect = currentSelected.getBoundingClientRect()\n\n // Storybook canvas \"zoom\" can be implemented via `transform: scale()`.\n // In that case, `getBoundingClientRect()` returns *scaled* values, but CSS positioning/sizing\n // expects unscaled layout pixels. We infer the scale factor from offset sizes and normalize.\n const scaleX =\n currentSelected.offsetWidth > 0 ? itemRect.width / currentSelected.offsetWidth : 1\n const scaleY =\n currentSelected.offsetHeight > 0 ? itemRect.height / currentSelected.offsetHeight : 1\n\n // `getBoundingClientRect()` is border-box; absolute positioning is relative to the padding box.\n setRect({\n left: (itemRect.left - containerRect.left) / scaleX - currentContainer.clientLeft,\n top: (itemRect.top - containerRect.top) / scaleY - currentContainer.clientTop,\n width: itemRect.width / scaleX,\n height: itemRect.height / scaleY,\n })\n }\n\n update()\n\n const ro =\n typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(() => {\n update()\n })\n : null\n\n ro?.observe(container)\n if (selectedItem) ro?.observe(selectedItem)\n\n window.addEventListener('resize', update, { passive: true })\n window.visualViewport?.addEventListener('resize', update, { passive: true })\n\n return () => {\n ro?.disconnect()\n window.removeEventListener('resize', update)\n window.visualViewport?.removeEventListener('resize', update)\n }\n }, [containerRef, selector])\n\n if (!rect) return null\n\n const style: CSSProperties = {\n left: rect.left,\n top: rect.top,\n width: rect.width,\n height: rect.height,\n }\n\n return (\n <span\n ref={ref}\n data-spark-component=\"segmented-control-indicator\"\n aria-hidden\n className={indicatorStyles({ className })}\n style={style}\n {...rest}\n />\n )\n}\n\nSegmentedControlIndicator.displayName = 'SegmentedControl.Indicator'\n","import { Children, type ComponentProps, Ref } from 'react'\n\nimport { itemStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\nexport interface SegmentedControlItemProps extends Omit<\n ComponentProps<'button'>,\n 'value' | 'onClick'\n> {\n /**\n * A unique value that identifies this item within the segmented control.\n */\n value: string\n /**\n * When true, prevents the user from interacting with this item.\n * @default false\n */\n disabled?: boolean\n ref?: Ref<HTMLButtonElement>\n}\n\n/** A selectable item in the segmented control. Renders a <button> element. */\nexport const SegmentedControlItem = ({\n value,\n disabled = false,\n children,\n className,\n ref,\n ...rest\n}: SegmentedControlItemProps) => {\n const { checkedValue, onValueChange, name, rowLength, itemValues } = useSegmentedControlContext()\n\n const isChecked = checkedValue === value\n\n const handleClick = () => {\n if (!disabled) {\n onValueChange(value)\n }\n }\n\n const content = Children.toArray(children).map((child, index) => {\n if (typeof child === 'string' || typeof child === 'number') {\n return (\n <span key={`text-${index}`} data-spark-segmented-control-text>\n {child}\n </span>\n )\n }\n\n return child\n })\n\n // Calculate flex-basis for multi-row layout and horizontal separator visibility\n const itemIndex = itemValues.indexOf(value)\n const itemStyle = rowLength\n ? { flexBasis: `calc(100% / var(--segmented-control-cols))` }\n : undefined\n\n let showHorizontalSeparator = false\n\n if (rowLength && rowLength > 0 && itemIndex !== -1) {\n const cols = rowLength\n const currentCol = itemIndex % cols\n const currentRow = Math.floor(itemIndex / cols)\n const totalRows = Math.ceil(itemValues.length / cols)\n\n // Show horizontal separator only on the first column of each row (except last row)\n showHorizontalSeparator = currentRow < totalRows - 1 && currentCol === 0\n }\n\n return (\n <button\n ref={ref}\n type=\"button\"\n role=\"radio\"\n data-spark-component=\"segmented-control-item\"\n data-value={value}\n aria-checked={isChecked}\n data-checked={isChecked || undefined}\n data-disabled={disabled || undefined}\n disabled={disabled}\n tabIndex={isChecked ? 0 : -1}\n className={itemStyles({ className })}\n style={itemStyle}\n onClick={handleClick}\n {...rest}\n >\n {content}\n {/* Hidden input for form submission */}\n {name && isChecked && <input type=\"hidden\" name={name} value={value} />}\n {/* Horizontal separator between rows (full width across all columns) */}\n {showHorizontalSeparator && rowLength && (\n <div\n className=\"bg-outline/dim-3 -mx-sm absolute left-0 h-px\"\n style={{\n bottom: 'calc(var(--spacing-md) / -2)',\n width: `calc(${rowLength * 100}% + var(--spacing-sm) * 2)`,\n }}\n aria-hidden=\"true\"\n />\n )}\n </button>\n )\n}\n\nSegmentedControlItem.displayName = 'SegmentedControl.Item'\n","import { SegmentedControl as Root } from './SegmentedControl'\nimport { SegmentedControlIndicator as Indicator } from './SegmentedControlIndicator'\nimport { SegmentedControlItem as Item } from './SegmentedControlItem'\n\n/**\n * A set of toggle buttons that allows users to select a single option from a group of related choices.\n */\nexport const SegmentedControl: typeof Root & {\n Item: typeof Item\n Indicator: typeof Indicator\n} = Object.assign(Root, {\n Item,\n Indicator,\n})\n\nSegmentedControl.displayName = 'SegmentedControl'\nItem.displayName = 'SegmentedControl.Item'\nIndicator.displayName = 'SegmentedControl.Indicator'\n\nexport type { SegmentedControlProps } from './SegmentedControl'\nexport type { SegmentedControlItemProps } from './SegmentedControlItem'\nexport type { SegmentedControlIndicatorProps } from './SegmentedControlIndicator'\n"],"mappings":"wPAEA,IAAa,GAAA,EAAA,EAAA,IAAA,CAAiB,CAC5B,qBACA,8BACA,mCACA,kBACA,qCACF,CAAC,EAEY,GAAA,EAAA,EAAA,IAAA,CAAiB,CAC5B,2DACA,oDACA,8BACA,iBACA,6BACA,cACA,iCACA,eACA,0BACA,+DACA,yCAGA,iHACF,CAAC,EAEY,GAAA,EAAA,EAAA,IAAA,CAAsB,CACjC,kBACA,iBACA,gDACA,uCACA,8DACA,qBACF,CAAC,ECvBY,GAAA,EAAA,EAAA,cAAA,CACX,CAAC,CACH,EAEa,MAAmC,CAC9C,IAAM,GAAA,EAAA,EAAA,WAAA,CAAqB,CAAuB,EAElD,GAAI,CAAC,EACH,MAAM,MAAM,mFAAmF,EAGjG,OAAO,CACT,ECXa,GAAiC,CAC5C,aACA,eACA,oBA+CO,CAAE,cA7Cc,GAAqC,CAG1D,IAAM,EADiB,EAAE,OACW,aAAa,YAAY,EAE7D,GAAI,CAAC,EAAc,OAEnB,IAAM,EAAe,EAAW,QAAQ,CAAY,EACpD,GAAI,IAAiB,GAAI,OAEzB,IAAI,EAA2B,KAK/B,GAFA,EAAY,EAAsB,EAAE,IAAK,EAAc,EAAW,MAAM,EAEpE,IAAc,MAAQ,IAAc,EAAc,CACpD,EAAE,eAAe,EAGjB,IAAI,EAAW,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ACnB,EAAU,YAAc"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/segmented-control/SegmentedControl.styles.ts","../../src/segmented-control/SegmentedControlContext.tsx","../../src/segmented-control/useSegmentedControlNavigation.ts","../../src/segmented-control/SegmentedControl.tsx","../../src/segmented-control/SegmentedControlIndicator.tsx","../../src/segmented-control/SegmentedControlItem.tsx","../../src/segmented-control/index.ts"],"sourcesContent":["import { cva, VariantProps } from 'class-variance-authority'\n\nexport const rootStyles = cva([\n 'default:self-start',\n 'group inline-flex flex-wrap',\n 'relative items-stretch min-w-max',\n 'rounded-xl p-sm',\n 'bg-surface border-sm border-outline',\n])\n\nexport const itemStyles = cva([\n 'relative z-raised min-h-sz-44 focus-visible:outline-none',\n 'flex flex-auto items-center justify-center gap-md',\n 'default:px-lg default:py-md',\n 'rounded-[20px]',\n 'cursor-pointer select-none',\n 'font-medium',\n 'transition-colors duration-150',\n 'outline-none',\n 'focus-visible:u-outline',\n 'data-disabled:cursor-not-allowed data-disabled:opacity-dim-3',\n 'data-checked:text-on-support-container',\n // Avoid layout shift: simulate \"bold\" without changing font metrics.\n // Apply only to wrapped text nodes (not arbitrary nested JSX like Tag).\n 'data-checked:[&>[data-spark-segmented-control-text]]:[text-shadow:0.35px_0_currentColor,-0.35px_0_currentColor]',\n])\n\nexport const indicatorStyles = cva([\n 'absolute z-base',\n 'rounded-[20px]',\n 'bg-support-container border-md border-support',\n 'group-has-focus-visible:border-focus',\n 'transition-[left,top,width,height] duration-200 ease-in-out',\n 'pointer-events-none',\n])\n\nexport type SegmentedControlStylesProps = VariantProps<typeof itemStyles>\n","import { createContext, RefObject, useContext } from 'react'\n\nexport interface SegmentedControlContextInterface {\n checkedValue: string | null\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n name?: string\n rowLength?: number\n itemValues: string[]\n}\n\nexport const SegmentedControlContext = createContext<SegmentedControlContextInterface>(\n {} as SegmentedControlContextInterface\n)\n\nexport const useSegmentedControlContext = () => {\n const context = useContext(SegmentedControlContext)\n\n if (!context) {\n throw Error('useSegmentedControlContext must be used within a SegmentedControlContext Provider')\n }\n\n return context\n}\n","import { KeyboardEvent, RefObject } from 'react'\n\ninterface UseSegmentedControlNavigationProps {\n itemValues: string[]\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n}\n\n/**\n * Custom hook that handles keyboard navigation for SegmentedControl.\n * Uses sequential left/right navigation.\n */\nexport const useSegmentedControlNavigation = ({\n itemValues,\n containerRef,\n onValueChange,\n}: UseSegmentedControlNavigationProps) => {\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // Find the currently focused item (which may differ from checkedValue during keyboard navigation)\n const focusedElement = e.target as HTMLElement\n const focusedValue = focusedElement.getAttribute('data-value')\n\n if (!focusedValue) return\n\n const currentIndex = itemValues.indexOf(focusedValue)\n if (currentIndex === -1) return\n\n let nextIndex: number | null = null\n\n // Always use 1D sequential navigation (left/right only)\n nextIndex = calculate1DNavigation(e.key, currentIndex, itemValues.length)\n\n if (nextIndex !== null && nextIndex !== currentIndex) {\n e.preventDefault()\n\n // Skip disabled items\n let attempts = 0\n const maxAttempts = itemValues.length\n\n while (attempts < maxAttempts) {\n const nextValue = itemValues[nextIndex]\n if (!nextValue) return\n\n const nextItem = containerRef.current?.querySelector<HTMLElement>(\n `[data-value=\"${CSS.escape(nextValue)}\"]`\n )\n\n // If the item is not disabled, focus it and update the value\n if (nextItem && !nextItem.hasAttribute('data-disabled')) {\n nextItem.focus()\n onValueChange(nextValue)\n return\n }\n\n // If disabled, continue in the same direction\n const direction = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1\n nextIndex = (nextIndex + direction + itemValues.length) % itemValues.length\n attempts++\n }\n }\n }\n\n return { handleKeyDown }\n}\n\n/**\n * Calculate next index for 1D sequential navigation.\n * Navigation wraps around at the boundaries.\n */\nfunction calculate1DNavigation(\n key: string,\n currentIndex: number,\n totalItems: number\n): number | null {\n switch (key) {\n case 'ArrowRight':\n case 'ArrowDown':\n return (currentIndex + 1) % totalItems\n case 'ArrowLeft':\n case 'ArrowUp':\n return (currentIndex - 1 + totalItems) % totalItems\n default:\n return null\n }\n}\n","import { useFormFieldControl } from '@spark-ui/components/form-field'\nimport { useMergeRefs } from '@spark-ui/hooks/use-merge-refs'\nimport {\n Children,\n type ComponentProps,\n CSSProperties,\n isValidElement,\n Ref,\n useRef,\n useState,\n} from 'react'\n\nimport type { SegmentedControlStylesProps } from './SegmentedControl.styles'\nimport { rootStyles } from './SegmentedControl.styles'\nimport { SegmentedControlContext } from './SegmentedControlContext'\nimport { useSegmentedControlNavigation } from './useSegmentedControlNavigation'\n\nexport interface SegmentedControlProps\n extends Omit<ComponentProps<'div'>, 'onValueChange'>, SegmentedControlStylesProps {\n /**\n * The controlled selected value.\n */\n value?: string\n /**\n * The uncontrolled default selected value.\n */\n defaultValue?: string\n /**\n * Callback fired when the selected value changes.\n */\n onValueChange?: (value: string) => void\n /**\n * Number of items per row in multi-row layout.\n * When undefined, items display in a single row (default behavior).\n * @default undefined\n * @example\n * // Create 3-column grid with wrapping rows\n * <SegmentedControl rowLength={3}>\n */\n rowLength?: number\n /**\n * The name attribute for the radio group (used in form submissions).\n */\n name?: string\n ref?: Ref<HTMLDivElement>\n}\n\nconst getFirstItemValue = (children: React.ReactNode): string | null => {\n let firstValue: string | null = null\n\n Children.forEach(children, child => {\n if (firstValue !== null) return\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n firstValue = (child.props as { value: string }).value\n }\n })\n\n return firstValue\n}\n\nexport const SegmentedControl = ({\n value,\n defaultValue,\n onValueChange,\n className,\n children,\n rowLength,\n name: nameProp,\n ref,\n ...rest\n}: SegmentedControlProps) => {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const mergedRef = useMergeRefs(containerRef, ref)\n\n const firstValue = getFirstItemValue(children)\n\n const isControlled = value !== undefined\n const [internalValue, setInternalValue] = useState<string | null>(\n () => defaultValue ?? firstValue\n )\n const checkedValue = isControlled ? (value ?? null) : internalValue\n\n const handleValueChange = (newValue: string) => {\n if (!isControlled) {\n setInternalValue(newValue)\n }\n\n onValueChange?.(newValue)\n }\n\n const { labelId, description, isRequired, isInvalid, name: nameFromField } = useFormFieldControl()\n const name = nameProp ?? nameFromField\n\n // Get all item values in order\n const itemValues: string[] = []\n Children.forEach(children, child => {\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n itemValues.push((child.props as { value: string }).value)\n }\n })\n\n // Keyboard navigation (sequential left/right)\n const { handleKeyDown } = useSegmentedControlNavigation({\n itemValues,\n containerRef,\n onValueChange: handleValueChange,\n })\n\n // Compute dynamic flex styles for multi-row layout\n const flexStyles = rowLength\n ? ({\n '--segmented-control-cols': rowLength,\n rowGap: 'var(--spacing-md)',\n } as CSSProperties)\n : undefined\n\n return (\n <SegmentedControlContext\n value={{\n checkedValue,\n containerRef,\n onValueChange: handleValueChange,\n name,\n rowLength,\n itemValues,\n }}\n >\n <div\n ref={mergedRef}\n role=\"radiogroup\"\n data-spark-component=\"segmented-control\"\n className={rootStyles({ className })}\n style={flexStyles}\n aria-labelledby={labelId}\n aria-describedby={description}\n aria-required={isRequired || undefined}\n aria-invalid={isInvalid || undefined}\n onKeyDown={handleKeyDown}\n {...rest}\n >\n {children}\n </div>\n </SegmentedControlContext>\n )\n}\n\nSegmentedControl.displayName = 'SegmentedControl'\n","import { type ComponentProps, type CSSProperties, Ref, useEffect, useState } from 'react'\n\nimport { indicatorStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\ninterface IndicatorRect {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport interface SegmentedControlIndicatorProps extends ComponentProps<'span'> {\n ref?: Ref<HTMLSpanElement>\n}\n\n/**\n * Finds an item by comparing `dataset.value` directly, rather than building a selector with\n * `CSS.escape` (a browser-only global that is unavailable during server-side rendering).\n */\nconst findItemByValue = (container: HTMLElement, value: string | null | undefined) => {\n if (!value) return null\n\n return (\n Array.from(container.querySelectorAll<HTMLElement>('[data-value]')).find(\n el => el.dataset.value === value\n ) ?? null\n )\n}\n\n/** The visual indicator that highlights the selected item. Renders a <span> element. */\nexport const SegmentedControlIndicator = ({\n className,\n ref,\n ...rest\n}: SegmentedControlIndicatorProps) => {\n const { checkedValue, containerRef } = useSegmentedControlContext()\n const [rect, setRect] = useState<IndicatorRect | null>(null)\n\n useEffect(() => {\n const container = containerRef.current\n\n if (!container) {\n return\n }\n\n const selectedItem = findItemByValue(container, checkedValue)\n\n const update = () => {\n const currentContainer = containerRef.current\n if (!currentContainer) {\n setRect(null)\n\n return\n }\n\n const currentSelected = findItemByValue(currentContainer, checkedValue)\n if (!currentSelected) {\n setRect(null)\n\n return\n }\n\n const containerRect = currentContainer.getBoundingClientRect()\n const itemRect = currentSelected.getBoundingClientRect()\n\n // Storybook canvas \"zoom\" can be implemented via `transform: scale()`.\n // In that case, `getBoundingClientRect()` returns *scaled* values, but CSS positioning/sizing\n // expects unscaled layout pixels. We infer the scale factor from offset sizes and normalize.\n const scaleX =\n currentSelected.offsetWidth > 0 ? itemRect.width / currentSelected.offsetWidth : 1\n const scaleY =\n currentSelected.offsetHeight > 0 ? itemRect.height / currentSelected.offsetHeight : 1\n\n // `getBoundingClientRect()` is border-box; absolute positioning is relative to the padding box.\n setRect({\n left: (itemRect.left - containerRect.left) / scaleX - currentContainer.clientLeft,\n top: (itemRect.top - containerRect.top) / scaleY - currentContainer.clientTop,\n width: itemRect.width / scaleX,\n height: itemRect.height / scaleY,\n })\n }\n\n update()\n\n const ro =\n typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(() => {\n update()\n })\n : null\n\n ro?.observe(container)\n if (selectedItem) ro?.observe(selectedItem)\n\n window.addEventListener('resize', update, { passive: true })\n window.visualViewport?.addEventListener('resize', update, { passive: true })\n\n return () => {\n ro?.disconnect()\n window.removeEventListener('resize', update)\n window.visualViewport?.removeEventListener('resize', update)\n }\n }, [containerRef, checkedValue])\n\n if (!rect) return null\n\n const style: CSSProperties = {\n left: rect.left,\n top: rect.top,\n width: rect.width,\n height: rect.height,\n }\n\n return (\n <span\n ref={ref}\n data-spark-component=\"segmented-control-indicator\"\n aria-hidden\n className={indicatorStyles({ className })}\n style={style}\n {...rest}\n />\n )\n}\n\nSegmentedControlIndicator.displayName = 'SegmentedControl.Indicator'\n","import { Children, type ComponentProps, Ref } from 'react'\n\nimport { itemStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\nexport interface SegmentedControlItemProps extends Omit<\n ComponentProps<'button'>,\n 'value' | 'onClick'\n> {\n /**\n * A unique value that identifies this item within the segmented control.\n */\n value: string\n /**\n * When true, prevents the user from interacting with this item.\n * @default false\n */\n disabled?: boolean\n ref?: Ref<HTMLButtonElement>\n}\n\n/** A selectable item in the segmented control. Renders a <button> element. */\nexport const SegmentedControlItem = ({\n value,\n disabled = false,\n children,\n className,\n ref,\n ...rest\n}: SegmentedControlItemProps) => {\n const { checkedValue, onValueChange, name, rowLength, itemValues } = useSegmentedControlContext()\n\n const isChecked = checkedValue === value\n\n const handleClick = () => {\n if (!disabled) {\n onValueChange(value)\n }\n }\n\n const content = Children.toArray(children).map((child, index) => {\n if (typeof child === 'string' || typeof child === 'number') {\n return (\n <span key={`text-${index}`} data-spark-segmented-control-text>\n {child}\n </span>\n )\n }\n\n return child\n })\n\n // Calculate flex-basis for multi-row layout and horizontal separator visibility\n const itemIndex = itemValues.indexOf(value)\n const itemStyle = rowLength\n ? { flexBasis: `calc(100% / var(--segmented-control-cols))` }\n : undefined\n\n let showHorizontalSeparator = false\n\n if (rowLength && rowLength > 0 && itemIndex !== -1) {\n const cols = rowLength\n const currentCol = itemIndex % cols\n const currentRow = Math.floor(itemIndex / cols)\n const totalRows = Math.ceil(itemValues.length / cols)\n\n // Show horizontal separator only on the first column of each row (except last row)\n showHorizontalSeparator = currentRow < totalRows - 1 && currentCol === 0\n }\n\n return (\n <button\n ref={ref}\n type=\"button\"\n role=\"radio\"\n data-spark-component=\"segmented-control-item\"\n data-value={value}\n aria-checked={isChecked}\n data-checked={isChecked || undefined}\n data-disabled={disabled || undefined}\n disabled={disabled}\n tabIndex={isChecked ? 0 : -1}\n className={itemStyles({ className })}\n style={itemStyle}\n onClick={handleClick}\n {...rest}\n >\n {content}\n {/* Hidden input for form submission */}\n {name && isChecked && <input type=\"hidden\" name={name} value={value} />}\n {/* Horizontal separator between rows (full width across all columns) */}\n {showHorizontalSeparator && rowLength && (\n <div\n className=\"bg-outline/dim-3 -mx-sm absolute left-0 h-px\"\n style={{\n bottom: 'calc(var(--spacing-md) / -2)',\n width: `calc(${rowLength * 100}% + var(--spacing-sm) * 2)`,\n }}\n aria-hidden=\"true\"\n />\n )}\n </button>\n )\n}\n\nSegmentedControlItem.displayName = 'SegmentedControl.Item'\n","import { SegmentedControl as Root } from './SegmentedControl'\nimport { SegmentedControlIndicator as Indicator } from './SegmentedControlIndicator'\nimport { SegmentedControlItem as Item } from './SegmentedControlItem'\n\n/**\n * A set of toggle buttons that allows users to select a single option from a group of related choices.\n */\nexport const SegmentedControl: typeof Root & {\n Item: typeof Item\n Indicator: typeof Indicator\n} = Object.assign(Root, {\n Item,\n Indicator,\n})\n\nSegmentedControl.displayName = 'SegmentedControl'\nItem.displayName = 'SegmentedControl.Item'\nIndicator.displayName = 'SegmentedControl.Indicator'\n\nexport type { SegmentedControlProps } from './SegmentedControl'\nexport type { SegmentedControlItemProps } from './SegmentedControlItem'\nexport type { SegmentedControlIndicatorProps } from './SegmentedControlIndicator'\n"],"mappings":"wPAEA,IAAa,GAAA,EAAA,EAAA,IAAA,CAAiB,CAC5B,qBACA,8BACA,mCACA,kBACA,qCACF,CAAC,EAEY,GAAA,EAAA,EAAA,IAAA,CAAiB,CAC5B,2DACA,oDACA,8BACA,iBACA,6BACA,cACA,iCACA,eACA,0BACA,+DACA,yCAGA,iHACF,CAAC,EAEY,GAAA,EAAA,EAAA,IAAA,CAAsB,CACjC,kBACA,iB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,eAAc,EACd,eAAc,GAAa,IAAA,GAC3B,gBAAe,GAAY,IAAA,GACjB,WACV,SAAU,EAAY,EAAI,GAC1B,UAAW,EAAW,CAAE,WAAU,CAAC,EACnC,MAAO,EACP,QAAS,EACT,GAAI,WAdN,CAgBG,EAEA,GAAQ,IAAa,EAAA,EAAA,IAAA,CAAC,QAAD,CAAO,KAAK,SAAe,OAAa,OAAQ,CAAA,EAErE,GAA2B,IAC1B,EAAA,EAAA,IAAA,CAAC,MAAD,CACE,UAAU,+CACV,MAAO,CACL,OAAQ,+BACR,MAAO,QAAQ,EAAY,IAAI,2BACjC,EACA,cAAY,MACb,CAAA,CAEG,GAEZ,EAEA,EAAqB,YAAc,wBClGnC,IAAa,EAGT,OAAO,OAAO,EAAM,CACtB,KAAA,EACA,UAAA,CACF,CAAC,EAED,EAAiB,YAAc,mBAC/B,EAAK,YAAc,wBACnB,EAAU,YAAc"}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { cva as e } from "class-variance-authority";
|
|
2
|
-
import { Children as t, createContext as n, isValidElement as r, useContext as i, useEffect as a,
|
|
3
|
-
import { jsx as
|
|
4
|
-
import { useMergeRefs as
|
|
5
|
-
import { useFormFieldControl as
|
|
2
|
+
import { Children as t, createContext as n, isValidElement as r, useContext as i, useEffect as a, useRef as o, useState as s } from "react";
|
|
3
|
+
import { jsx as c, jsxs as l } from "react/jsx-runtime";
|
|
4
|
+
import { useMergeRefs as u } from "@spark-ui/hooks/use-merge-refs";
|
|
5
|
+
import { useFormFieldControl as d } from "@spark-ui/components/form-field";
|
|
6
6
|
//#region src/segmented-control/SegmentedControl.styles.ts
|
|
7
|
-
var
|
|
7
|
+
var f = e([
|
|
8
8
|
"default:self-start",
|
|
9
9
|
"group inline-flex flex-wrap",
|
|
10
10
|
"relative items-stretch min-w-max",
|
|
11
11
|
"rounded-xl p-sm",
|
|
12
12
|
"bg-surface border-sm border-outline"
|
|
13
|
-
]),
|
|
13
|
+
]), p = e([
|
|
14
14
|
"relative z-raised min-h-sz-44 focus-visible:outline-none",
|
|
15
15
|
"flex flex-auto items-center justify-center gap-md",
|
|
16
16
|
"default:px-lg default:py-md",
|
|
@@ -23,24 +23,24 @@ var p = e([
|
|
|
23
23
|
"data-disabled:cursor-not-allowed data-disabled:opacity-dim-3",
|
|
24
24
|
"data-checked:text-on-support-container",
|
|
25
25
|
"data-checked:[&>[data-spark-segmented-control-text]]:[text-shadow:0.35px_0_currentColor,-0.35px_0_currentColor]"
|
|
26
|
-
]),
|
|
26
|
+
]), m = e([
|
|
27
27
|
"absolute z-base",
|
|
28
28
|
"rounded-[20px]",
|
|
29
29
|
"bg-support-container border-md border-support",
|
|
30
30
|
"group-has-focus-visible:border-focus",
|
|
31
31
|
"transition-[left,top,width,height] duration-200 ease-in-out",
|
|
32
32
|
"pointer-events-none"
|
|
33
|
-
]),
|
|
34
|
-
let e = i(
|
|
33
|
+
]), h = n({}), g = () => {
|
|
34
|
+
let e = i(h);
|
|
35
35
|
if (!e) throw Error("useSegmentedControlContext must be used within a SegmentedControlContext Provider");
|
|
36
36
|
return e;
|
|
37
|
-
},
|
|
37
|
+
}, _ = ({ itemValues: e, containerRef: t, onValueChange: n }) => ({ handleKeyDown: (r) => {
|
|
38
38
|
let i = r.target.getAttribute("data-value");
|
|
39
39
|
if (!i) return;
|
|
40
40
|
let a = e.indexOf(i);
|
|
41
41
|
if (a === -1) return;
|
|
42
42
|
let o = null;
|
|
43
|
-
if (o =
|
|
43
|
+
if (o = v(r.key, a, e.length), o !== null && o !== a) {
|
|
44
44
|
r.preventDefault();
|
|
45
45
|
let i = 0, a = e.length;
|
|
46
46
|
for (; i < a;) {
|
|
@@ -56,7 +56,7 @@ var p = e([
|
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
} });
|
|
59
|
-
function
|
|
59
|
+
function v(e, t, n) {
|
|
60
60
|
switch (e) {
|
|
61
61
|
case "ArrowRight":
|
|
62
62
|
case "ArrowDown": return (t + 1) % n;
|
|
@@ -67,98 +67,98 @@ function y(e, t, n) {
|
|
|
67
67
|
}
|
|
68
68
|
//#endregion
|
|
69
69
|
//#region src/segmented-control/SegmentedControl.tsx
|
|
70
|
-
var
|
|
70
|
+
var y = (e) => {
|
|
71
71
|
let n = null;
|
|
72
72
|
return t.forEach(e, (e) => {
|
|
73
73
|
n === null && r(e) && typeof e.props.value == "string" && (n = e.props.value);
|
|
74
74
|
}), n;
|
|
75
|
-
},
|
|
76
|
-
let
|
|
75
|
+
}, b = ({ value: e, defaultValue: n, onValueChange: i, className: a, children: l, rowLength: p, name: m, ref: g, ...v }) => {
|
|
76
|
+
let b = o(null), x = u(b, g), S = y(l), C = e !== void 0, [w, T] = s(() => n ?? S), E = C ? e ?? null : w, D = (e) => {
|
|
77
77
|
C || T(e), i?.(e);
|
|
78
|
-
}, { labelId: O, description: k, isRequired: A, isInvalid: j, name: M } =
|
|
79
|
-
t.forEach(
|
|
78
|
+
}, { labelId: O, description: k, isRequired: A, isInvalid: j, name: M } = d(), N = m ?? M, P = [];
|
|
79
|
+
t.forEach(l, (e) => {
|
|
80
80
|
r(e) && typeof e.props.value == "string" && P.push(e.props.value);
|
|
81
81
|
});
|
|
82
|
-
let { handleKeyDown: F } =
|
|
82
|
+
let { handleKeyDown: F } = _({
|
|
83
83
|
itemValues: P,
|
|
84
|
-
containerRef:
|
|
84
|
+
containerRef: b,
|
|
85
85
|
onValueChange: D
|
|
86
|
-
}), I =
|
|
87
|
-
"--segmented-control-cols":
|
|
86
|
+
}), I = p ? {
|
|
87
|
+
"--segmented-control-cols": p,
|
|
88
88
|
rowGap: "var(--spacing-md)"
|
|
89
89
|
} : void 0;
|
|
90
|
-
return /* @__PURE__ */
|
|
90
|
+
return /* @__PURE__ */ c(h, {
|
|
91
91
|
value: {
|
|
92
92
|
checkedValue: E,
|
|
93
|
-
containerRef:
|
|
93
|
+
containerRef: b,
|
|
94
94
|
onValueChange: D,
|
|
95
95
|
name: N,
|
|
96
|
-
rowLength:
|
|
96
|
+
rowLength: p,
|
|
97
97
|
itemValues: P
|
|
98
98
|
},
|
|
99
|
-
children: /* @__PURE__ */
|
|
99
|
+
children: /* @__PURE__ */ c("div", {
|
|
100
100
|
ref: x,
|
|
101
101
|
role: "radiogroup",
|
|
102
102
|
"data-spark-component": "segmented-control",
|
|
103
|
-
className:
|
|
103
|
+
className: f({ className: a }),
|
|
104
104
|
style: I,
|
|
105
105
|
"aria-labelledby": O,
|
|
106
106
|
"aria-describedby": k,
|
|
107
107
|
"aria-required": A || void 0,
|
|
108
108
|
"aria-invalid": j || void 0,
|
|
109
109
|
onKeyDown: F,
|
|
110
|
-
...
|
|
111
|
-
children:
|
|
110
|
+
...v,
|
|
111
|
+
children: l
|
|
112
112
|
})
|
|
113
113
|
});
|
|
114
114
|
};
|
|
115
|
-
|
|
115
|
+
b.displayName = "SegmentedControl";
|
|
116
116
|
//#endregion
|
|
117
117
|
//#region src/segmented-control/SegmentedControlIndicator.tsx
|
|
118
|
-
var S = ({ className: e, ref: t, ...n }) => {
|
|
119
|
-
let { checkedValue: r, containerRef: i } =
|
|
118
|
+
var x = (e, t) => t ? Array.from(e.querySelectorAll("[data-value]")).find((e) => e.dataset.value === t) ?? null : null, S = ({ className: e, ref: t, ...n }) => {
|
|
119
|
+
let { checkedValue: r, containerRef: i } = g(), [o, l] = s(null);
|
|
120
120
|
if (a(() => {
|
|
121
121
|
let e = i.current;
|
|
122
122
|
if (!e) return;
|
|
123
|
-
let t =
|
|
123
|
+
let t = x(e, r), n = () => {
|
|
124
124
|
let e = i.current;
|
|
125
|
-
if (!e
|
|
126
|
-
|
|
125
|
+
if (!e) {
|
|
126
|
+
l(null);
|
|
127
127
|
return;
|
|
128
128
|
}
|
|
129
|
-
let t = e
|
|
129
|
+
let t = x(e, r);
|
|
130
130
|
if (!t) {
|
|
131
|
-
|
|
131
|
+
l(null);
|
|
132
132
|
return;
|
|
133
133
|
}
|
|
134
|
-
let n = e.getBoundingClientRect(),
|
|
135
|
-
|
|
136
|
-
left: (
|
|
137
|
-
top: (
|
|
138
|
-
width:
|
|
139
|
-
height:
|
|
134
|
+
let n = e.getBoundingClientRect(), a = t.getBoundingClientRect(), o = t.offsetWidth > 0 ? a.width / t.offsetWidth : 1, s = t.offsetHeight > 0 ? a.height / t.offsetHeight : 1;
|
|
135
|
+
l({
|
|
136
|
+
left: (a.left - n.left) / o - e.clientLeft,
|
|
137
|
+
top: (a.top - n.top) / s - e.clientTop,
|
|
138
|
+
width: a.width / o,
|
|
139
|
+
height: a.height / s
|
|
140
140
|
});
|
|
141
141
|
};
|
|
142
142
|
n();
|
|
143
|
-
let
|
|
143
|
+
let a = typeof ResizeObserver < "u" ? new ResizeObserver(() => {
|
|
144
144
|
n();
|
|
145
145
|
}) : null;
|
|
146
|
-
return
|
|
147
|
-
|
|
146
|
+
return a?.observe(e), t && a?.observe(t), window.addEventListener("resize", n, { passive: !0 }), window.visualViewport?.addEventListener("resize", n, { passive: !0 }), () => {
|
|
147
|
+
a?.disconnect(), window.removeEventListener("resize", n), window.visualViewport?.removeEventListener("resize", n);
|
|
148
148
|
};
|
|
149
|
-
}, [i,
|
|
150
|
-
let
|
|
151
|
-
left:
|
|
152
|
-
top:
|
|
153
|
-
width:
|
|
154
|
-
height:
|
|
149
|
+
}, [i, r]), !o) return null;
|
|
150
|
+
let u = {
|
|
151
|
+
left: o.left,
|
|
152
|
+
top: o.top,
|
|
153
|
+
width: o.width,
|
|
154
|
+
height: o.height
|
|
155
155
|
};
|
|
156
|
-
return /* @__PURE__ */
|
|
156
|
+
return /* @__PURE__ */ c("span", {
|
|
157
157
|
ref: t,
|
|
158
158
|
"data-spark-component": "segmented-control-indicator",
|
|
159
159
|
"aria-hidden": !0,
|
|
160
|
-
className:
|
|
161
|
-
style:
|
|
160
|
+
className: m({ className: e }),
|
|
161
|
+
style: u,
|
|
162
162
|
...n
|
|
163
163
|
});
|
|
164
164
|
};
|
|
@@ -166,17 +166,17 @@ S.displayName = "SegmentedControl.Indicator";
|
|
|
166
166
|
//#endregion
|
|
167
167
|
//#region src/segmented-control/SegmentedControlItem.tsx
|
|
168
168
|
var C = ({ value: e, disabled: n = !1, children: r, className: i, ref: a, ...o }) => {
|
|
169
|
-
let { checkedValue: s, onValueChange:
|
|
170
|
-
n ||
|
|
171
|
-
}, v = t.toArray(r).map((e, t) => typeof e == "string" || typeof e == "number" ? /* @__PURE__ */
|
|
169
|
+
let { checkedValue: s, onValueChange: u, name: d, rowLength: f, itemValues: m } = g(), h = s === e, _ = () => {
|
|
170
|
+
n || u(e);
|
|
171
|
+
}, v = t.toArray(r).map((e, t) => typeof e == "string" || typeof e == "number" ? /* @__PURE__ */ c("span", {
|
|
172
172
|
"data-spark-segmented-control-text": !0,
|
|
173
173
|
children: e
|
|
174
|
-
}, `text-${t}`) : e), y =
|
|
174
|
+
}, `text-${t}`) : e), y = m.indexOf(e), b = f ? { flexBasis: "calc(100% / var(--segmented-control-cols))" } : void 0, x = !1;
|
|
175
175
|
if (f && f > 0 && y !== -1) {
|
|
176
176
|
let e = f, t = y % e;
|
|
177
|
-
x = Math.floor(y / e) < Math.ceil(
|
|
177
|
+
x = Math.floor(y / e) < Math.ceil(m.length / e) - 1 && t === 0;
|
|
178
178
|
}
|
|
179
|
-
return /* @__PURE__ */
|
|
179
|
+
return /* @__PURE__ */ l("button", {
|
|
180
180
|
ref: a,
|
|
181
181
|
type: "button",
|
|
182
182
|
role: "radio",
|
|
@@ -187,18 +187,18 @@ var C = ({ value: e, disabled: n = !1, children: r, className: i, ref: a, ...o }
|
|
|
187
187
|
"data-disabled": n || void 0,
|
|
188
188
|
disabled: n,
|
|
189
189
|
tabIndex: h ? 0 : -1,
|
|
190
|
-
className:
|
|
190
|
+
className: p({ className: i }),
|
|
191
191
|
style: b,
|
|
192
|
-
onClick:
|
|
192
|
+
onClick: _,
|
|
193
193
|
...o,
|
|
194
194
|
children: [
|
|
195
195
|
v,
|
|
196
|
-
d && h && /* @__PURE__ */
|
|
196
|
+
d && h && /* @__PURE__ */ c("input", {
|
|
197
197
|
type: "hidden",
|
|
198
198
|
name: d,
|
|
199
199
|
value: e
|
|
200
200
|
}),
|
|
201
|
-
x && f && /* @__PURE__ */
|
|
201
|
+
x && f && /* @__PURE__ */ c("div", {
|
|
202
202
|
className: "bg-outline/dim-3 -mx-sm absolute left-0 h-px",
|
|
203
203
|
style: {
|
|
204
204
|
bottom: "calc(var(--spacing-md) / -2)",
|
|
@@ -212,7 +212,7 @@ var C = ({ value: e, disabled: n = !1, children: r, className: i, ref: a, ...o }
|
|
|
212
212
|
C.displayName = "SegmentedControl.Item";
|
|
213
213
|
//#endregion
|
|
214
214
|
//#region src/segmented-control/index.ts
|
|
215
|
-
var w = Object.assign(
|
|
215
|
+
var w = Object.assign(b, {
|
|
216
216
|
Item: C,
|
|
217
217
|
Indicator: S
|
|
218
218
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/segmented-control/SegmentedControl.styles.ts","../../src/segmented-control/SegmentedControlContext.tsx","../../src/segmented-control/useSegmentedControlNavigation.ts","../../src/segmented-control/SegmentedControl.tsx","../../src/segmented-control/SegmentedControlIndicator.tsx","../../src/segmented-control/SegmentedControlItem.tsx","../../src/segmented-control/index.ts"],"sourcesContent":["import { cva, VariantProps } from 'class-variance-authority'\n\nexport const rootStyles = cva([\n 'default:self-start',\n 'group inline-flex flex-wrap',\n 'relative items-stretch min-w-max',\n 'rounded-xl p-sm',\n 'bg-surface border-sm border-outline',\n])\n\nexport const itemStyles = cva([\n 'relative z-raised min-h-sz-44 focus-visible:outline-none',\n 'flex flex-auto items-center justify-center gap-md',\n 'default:px-lg default:py-md',\n 'rounded-[20px]',\n 'cursor-pointer select-none',\n 'font-medium',\n 'transition-colors duration-150',\n 'outline-none',\n 'focus-visible:u-outline',\n 'data-disabled:cursor-not-allowed data-disabled:opacity-dim-3',\n 'data-checked:text-on-support-container',\n // Avoid layout shift: simulate \"bold\" without changing font metrics.\n // Apply only to wrapped text nodes (not arbitrary nested JSX like Tag).\n 'data-checked:[&>[data-spark-segmented-control-text]]:[text-shadow:0.35px_0_currentColor,-0.35px_0_currentColor]',\n])\n\nexport const indicatorStyles = cva([\n 'absolute z-base',\n 'rounded-[20px]',\n 'bg-support-container border-md border-support',\n 'group-has-focus-visible:border-focus',\n 'transition-[left,top,width,height] duration-200 ease-in-out',\n 'pointer-events-none',\n])\n\nexport type SegmentedControlStylesProps = VariantProps<typeof itemStyles>\n","import { createContext, RefObject, useContext } from 'react'\n\nexport interface SegmentedControlContextInterface {\n checkedValue: string | null\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n name?: string\n rowLength?: number\n itemValues: string[]\n}\n\nexport const SegmentedControlContext = createContext<SegmentedControlContextInterface>(\n {} as SegmentedControlContextInterface\n)\n\nexport const useSegmentedControlContext = () => {\n const context = useContext(SegmentedControlContext)\n\n if (!context) {\n throw Error('useSegmentedControlContext must be used within a SegmentedControlContext Provider')\n }\n\n return context\n}\n","import { KeyboardEvent, RefObject } from 'react'\n\ninterface UseSegmentedControlNavigationProps {\n itemValues: string[]\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n}\n\n/**\n * Custom hook that handles keyboard navigation for SegmentedControl.\n * Uses sequential left/right navigation.\n */\nexport const useSegmentedControlNavigation = ({\n itemValues,\n containerRef,\n onValueChange,\n}: UseSegmentedControlNavigationProps) => {\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // Find the currently focused item (which may differ from checkedValue during keyboard navigation)\n const focusedElement = e.target as HTMLElement\n const focusedValue = focusedElement.getAttribute('data-value')\n\n if (!focusedValue) return\n\n const currentIndex = itemValues.indexOf(focusedValue)\n if (currentIndex === -1) return\n\n let nextIndex: number | null = null\n\n // Always use 1D sequential navigation (left/right only)\n nextIndex = calculate1DNavigation(e.key, currentIndex, itemValues.length)\n\n if (nextIndex !== null && nextIndex !== currentIndex) {\n e.preventDefault()\n\n // Skip disabled items\n let attempts = 0\n const maxAttempts = itemValues.length\n\n while (attempts < maxAttempts) {\n const nextValue = itemValues[nextIndex]\n if (!nextValue) return\n\n const nextItem = containerRef.current?.querySelector<HTMLElement>(\n `[data-value=\"${CSS.escape(nextValue)}\"]`\n )\n\n // If the item is not disabled, focus it and update the value\n if (nextItem && !nextItem.hasAttribute('data-disabled')) {\n nextItem.focus()\n onValueChange(nextValue)\n return\n }\n\n // If disabled, continue in the same direction\n const direction = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1\n nextIndex = (nextIndex + direction + itemValues.length) % itemValues.length\n attempts++\n }\n }\n }\n\n return { handleKeyDown }\n}\n\n/**\n * Calculate next index for 1D sequential navigation.\n * Navigation wraps around at the boundaries.\n */\nfunction calculate1DNavigation(\n key: string,\n currentIndex: number,\n totalItems: number\n): number | null {\n switch (key) {\n case 'ArrowRight':\n case 'ArrowDown':\n return (currentIndex + 1) % totalItems\n case 'ArrowLeft':\n case 'ArrowUp':\n return (currentIndex - 1 + totalItems) % totalItems\n default:\n return null\n }\n}\n","import { useFormFieldControl } from '@spark-ui/components/form-field'\nimport { useMergeRefs } from '@spark-ui/hooks/use-merge-refs'\nimport {\n Children,\n type ComponentProps,\n CSSProperties,\n isValidElement,\n Ref,\n useRef,\n useState,\n} from 'react'\n\nimport type { SegmentedControlStylesProps } from './SegmentedControl.styles'\nimport { rootStyles } from './SegmentedControl.styles'\nimport { SegmentedControlContext } from './SegmentedControlContext'\nimport { useSegmentedControlNavigation } from './useSegmentedControlNavigation'\n\nexport interface SegmentedControlProps\n extends Omit<ComponentProps<'div'>, 'onValueChange'>, SegmentedControlStylesProps {\n /**\n * The controlled selected value.\n */\n value?: string\n /**\n * The uncontrolled default selected value.\n */\n defaultValue?: string\n /**\n * Callback fired when the selected value changes.\n */\n onValueChange?: (value: string) => void\n /**\n * Number of items per row in multi-row layout.\n * When undefined, items display in a single row (default behavior).\n * @default undefined\n * @example\n * // Create 3-column grid with wrapping rows\n * <SegmentedControl rowLength={3}>\n */\n rowLength?: number\n /**\n * The name attribute for the radio group (used in form submissions).\n */\n name?: string\n ref?: Ref<HTMLDivElement>\n}\n\nconst getFirstItemValue = (children: React.ReactNode): string | null => {\n let firstValue: string | null = null\n\n Children.forEach(children, child => {\n if (firstValue !== null) return\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n firstValue = (child.props as { value: string }).value\n }\n })\n\n return firstValue\n}\n\nexport const SegmentedControl = ({\n value,\n defaultValue,\n onValueChange,\n className,\n children,\n rowLength,\n name: nameProp,\n ref,\n ...rest\n}: SegmentedControlProps) => {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const mergedRef = useMergeRefs(containerRef, ref)\n\n const firstValue = getFirstItemValue(children)\n\n const isControlled = value !== undefined\n const [internalValue, setInternalValue] = useState<string | null>(\n () => defaultValue ?? firstValue\n )\n const checkedValue = isControlled ? (value ?? null) : internalValue\n\n const handleValueChange = (newValue: string) => {\n if (!isControlled) {\n setInternalValue(newValue)\n }\n\n onValueChange?.(newValue)\n }\n\n const { labelId, description, isRequired, isInvalid, name: nameFromField } = useFormFieldControl()\n const name = nameProp ?? nameFromField\n\n // Get all item values in order\n const itemValues: string[] = []\n Children.forEach(children, child => {\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n itemValues.push((child.props as { value: string }).value)\n }\n })\n\n // Keyboard navigation (sequential left/right)\n const { handleKeyDown } = useSegmentedControlNavigation({\n itemValues,\n containerRef,\n onValueChange: handleValueChange,\n })\n\n // Compute dynamic flex styles for multi-row layout\n const flexStyles = rowLength\n ? ({\n '--segmented-control-cols': rowLength,\n rowGap: 'var(--spacing-md)',\n } as CSSProperties)\n : undefined\n\n return (\n <SegmentedControlContext\n value={{\n checkedValue,\n containerRef,\n onValueChange: handleValueChange,\n name,\n rowLength,\n itemValues,\n }}\n >\n <div\n ref={mergedRef}\n role=\"radiogroup\"\n data-spark-component=\"segmented-control\"\n className={rootStyles({ className })}\n style={flexStyles}\n aria-labelledby={labelId}\n aria-describedby={description}\n aria-required={isRequired || undefined}\n aria-invalid={isInvalid || undefined}\n onKeyDown={handleKeyDown}\n {...rest}\n >\n {children}\n </div>\n </SegmentedControlContext>\n )\n}\n\nSegmentedControl.displayName = 'SegmentedControl'\n","import { type ComponentProps, type CSSProperties, Ref, useEffect, useMemo, useState } from 'react'\n\nimport { indicatorStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\ninterface IndicatorRect {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport interface SegmentedControlIndicatorProps extends ComponentProps<'span'> {\n ref?: Ref<HTMLSpanElement>\n}\n\n/** The visual indicator that highlights the selected item. Renders a <span> element. */\nexport const SegmentedControlIndicator = ({\n className,\n ref,\n ...rest\n}: SegmentedControlIndicatorProps) => {\n const { checkedValue, containerRef } = useSegmentedControlContext()\n const [rect, setRect] = useState<IndicatorRect | null>(null)\n\n const selector = useMemo(\n () => (checkedValue ? `[data-value=\"${CSS.escape(checkedValue)}\"]` : null),\n [checkedValue]\n )\n\n useEffect(() => {\n const container = containerRef.current\n\n if (!container) {\n return\n }\n\n const selectedItem = selector ? container.querySelector<HTMLElement>(selector) : null\n\n const update = () => {\n const currentContainer = containerRef.current\n if (!currentContainer || !selector) {\n setRect(null)\n\n return\n }\n\n const currentSelected = currentContainer.querySelector<HTMLElement>(selector)\n if (!currentSelected) {\n setRect(null)\n\n return\n }\n\n const containerRect = currentContainer.getBoundingClientRect()\n const itemRect = currentSelected.getBoundingClientRect()\n\n // Storybook canvas \"zoom\" can be implemented via `transform: scale()`.\n // In that case, `getBoundingClientRect()` returns *scaled* values, but CSS positioning/sizing\n // expects unscaled layout pixels. We infer the scale factor from offset sizes and normalize.\n const scaleX =\n currentSelected.offsetWidth > 0 ? itemRect.width / currentSelected.offsetWidth : 1\n const scaleY =\n currentSelected.offsetHeight > 0 ? itemRect.height / currentSelected.offsetHeight : 1\n\n // `getBoundingClientRect()` is border-box; absolute positioning is relative to the padding box.\n setRect({\n left: (itemRect.left - containerRect.left) / scaleX - currentContainer.clientLeft,\n top: (itemRect.top - containerRect.top) / scaleY - currentContainer.clientTop,\n width: itemRect.width / scaleX,\n height: itemRect.height / scaleY,\n })\n }\n\n update()\n\n const ro =\n typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(() => {\n update()\n })\n : null\n\n ro?.observe(container)\n if (selectedItem) ro?.observe(selectedItem)\n\n window.addEventListener('resize', update, { passive: true })\n window.visualViewport?.addEventListener('resize', update, { passive: true })\n\n return () => {\n ro?.disconnect()\n window.removeEventListener('resize', update)\n window.visualViewport?.removeEventListener('resize', update)\n }\n }, [containerRef, selector])\n\n if (!rect) return null\n\n const style: CSSProperties = {\n left: rect.left,\n top: rect.top,\n width: rect.width,\n height: rect.height,\n }\n\n return (\n <span\n ref={ref}\n data-spark-component=\"segmented-control-indicator\"\n aria-hidden\n className={indicatorStyles({ className })}\n style={style}\n {...rest}\n />\n )\n}\n\nSegmentedControlIndicator.displayName = 'SegmentedControl.Indicator'\n","import { Children, type ComponentProps, Ref } from 'react'\n\nimport { itemStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\nexport interface SegmentedControlItemProps extends Omit<\n ComponentProps<'button'>,\n 'value' | 'onClick'\n> {\n /**\n * A unique value that identifies this item within the segmented control.\n */\n value: string\n /**\n * When true, prevents the user from interacting with this item.\n * @default false\n */\n disabled?: boolean\n ref?: Ref<HTMLButtonElement>\n}\n\n/** A selectable item in the segmented control. Renders a <button> element. */\nexport const SegmentedControlItem = ({\n value,\n disabled = false,\n children,\n className,\n ref,\n ...rest\n}: SegmentedControlItemProps) => {\n const { checkedValue, onValueChange, name, rowLength, itemValues } = useSegmentedControlContext()\n\n const isChecked = checkedValue === value\n\n const handleClick = () => {\n if (!disabled) {\n onValueChange(value)\n }\n }\n\n const content = Children.toArray(children).map((child, index) => {\n if (typeof child === 'string' || typeof child === 'number') {\n return (\n <span key={`text-${index}`} data-spark-segmented-control-text>\n {child}\n </span>\n )\n }\n\n return child\n })\n\n // Calculate flex-basis for multi-row layout and horizontal separator visibility\n const itemIndex = itemValues.indexOf(value)\n const itemStyle = rowLength\n ? { flexBasis: `calc(100% / var(--segmented-control-cols))` }\n : undefined\n\n let showHorizontalSeparator = false\n\n if (rowLength && rowLength > 0 && itemIndex !== -1) {\n const cols = rowLength\n const currentCol = itemIndex % cols\n const currentRow = Math.floor(itemIndex / cols)\n const totalRows = Math.ceil(itemValues.length / cols)\n\n // Show horizontal separator only on the first column of each row (except last row)\n showHorizontalSeparator = currentRow < totalRows - 1 && currentCol === 0\n }\n\n return (\n <button\n ref={ref}\n type=\"button\"\n role=\"radio\"\n data-spark-component=\"segmented-control-item\"\n data-value={value}\n aria-checked={isChecked}\n data-checked={isChecked || undefined}\n data-disabled={disabled || undefined}\n disabled={disabled}\n tabIndex={isChecked ? 0 : -1}\n className={itemStyles({ className })}\n style={itemStyle}\n onClick={handleClick}\n {...rest}\n >\n {content}\n {/* Hidden input for form submission */}\n {name && isChecked && <input type=\"hidden\" name={name} value={value} />}\n {/* Horizontal separator between rows (full width across all columns) */}\n {showHorizontalSeparator && rowLength && (\n <div\n className=\"bg-outline/dim-3 -mx-sm absolute left-0 h-px\"\n style={{\n bottom: 'calc(var(--spacing-md) / -2)',\n width: `calc(${rowLength * 100}% + var(--spacing-sm) * 2)`,\n }}\n aria-hidden=\"true\"\n />\n )}\n </button>\n )\n}\n\nSegmentedControlItem.displayName = 'SegmentedControl.Item'\n","import { SegmentedControl as Root } from './SegmentedControl'\nimport { SegmentedControlIndicator as Indicator } from './SegmentedControlIndicator'\nimport { SegmentedControlItem as Item } from './SegmentedControlItem'\n\n/**\n * A set of toggle buttons that allows users to select a single option from a group of related choices.\n */\nexport const SegmentedControl: typeof Root & {\n Item: typeof Item\n Indicator: typeof Indicator\n} = Object.assign(Root, {\n Item,\n Indicator,\n})\n\nSegmentedControl.displayName = 'SegmentedControl'\nItem.displayName = 'SegmentedControl.Item'\nIndicator.displayName = 'SegmentedControl.Indicator'\n\nexport type { SegmentedControlProps } from './SegmentedControl'\nexport type { SegmentedControlItemProps } from './SegmentedControlItem'\nexport type { SegmentedControlIndicatorProps } from './SegmentedControlIndicator'\n"],"mappings":";;;;;;AAEA,IAAa,IAAa,EAAI;CAC5B;CACA;CACA;CACA;CACA;AACF,CAAC,GAEY,IAAa,EAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;AACF,CAAC,GAEY,IAAkB,EAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,GCvBY,IAA0B,EACrC,CAAC,CACH,GAEa,UAAmC;CAC9C,IAAM,IAAU,EAAW,CAAuB;CAElD,IAAI,CAAC,GACH,MAAM,MAAM,mFAAmF;CAGjG,OAAO;AACT,GCXa,KAAiC,EAC5C,eACA,iBACA,wBA+CO,EAAE,gBA7Cc,MAAqC;CAG1D,IAAM,IADiB,EAAE,OACW,aAAa,YAAY;CAE7D,IAAI,CAAC,GAAc;CAEnB,IAAM,IAAe,EAAW,QAAQ,CAAY;CACpD,IAAI,MAAiB,IAAI;CAEzB,IAAI,IAA2B;CAK/B,IAFA,IAAY,EAAsB,EAAE,KAAK,GAAc,EAAW,MAAM,GAEpE,MAAc,QAAQ,MAAc,GAAc;EACpD,EAAE,eAAe;EAGjB,IAAI,IAAW,GACT,IAAc,EAAW;EAE/B,OAAO,IAAW,IAAa;GAC7B,IAAM,IAAY,EAAW;GAC7B,IAAI,CAAC,GAAW;GAEhB,IAAM,IAAW,EAAa,SAAS,cACrC,gBAAgB,IAAI,OAAO,CAAS,EAAE,GACxC;GAGA,IAAI,KAAY,CAAC,EAAS,aAAa,eAAe,GAAG;IAEvD,AADA,EAAS,MAAM,GACf,EAAc,CAAS;IACvB;GACF;GAGA,IAAM,IAAY,EAAE,QAAQ,gBAAgB,EAAE,QAAQ,cAAc,IAAI;GAExE,AADA,KAAa,IAAY,IAAY,EAAW,UAAU,EAAW,QACrE;EAC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,OACE,kBAAC,UAAD;EACO;EACL,MAAK;EACL,MAAK;EACL,wBAAqB;EACrB,cAAY;EACZ,gBAAc;EACd,gBAAc,KAAa,KAAA;EAC3B,iBAAe,KAAY,KAAA;EACjB;EACV,UAAU,IAAY,IAAI;EAC1B,WAAW,EAAW,EAAE,aAAU,CAAC;EACnC,OAAO;EACP,SAAS;EACT,GAAI;YAdN;GAgBG;GAEA,KAAQ,KAAa,kBAAC,SAAD;IAAO,MAAK;IAAe;IAAa;GAAQ,CAAA;GAErE,KAA2B,KAC1B,kBAAC,OAAD;IACE,WAAU;IACV,OAAO;KACL,QAAQ;KACR,OAAO,QAAQ,IAAY,IAAI;IACjC;IACA,eAAY;GACb,CAAA;EAEG;;AAEZ;AAEA,EAAqB,cAAc;;;AClGnC,IAAa,IAGT,OAAO,OAAO,GAAM;CACtB,MAAA;CACA,WAAA;AACF,CAAC;AAED,EAAiB,cAAc,oBAC/B,EAAK,cAAc,yBACnB,EAAU,cAAc"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/segmented-control/SegmentedControl.styles.ts","../../src/segmented-control/SegmentedControlContext.tsx","../../src/segmented-control/useSegmentedControlNavigation.ts","../../src/segmented-control/SegmentedControl.tsx","../../src/segmented-control/SegmentedControlIndicator.tsx","../../src/segmented-control/SegmentedControlItem.tsx","../../src/segmented-control/index.ts"],"sourcesContent":["import { cva, VariantProps } from 'class-variance-authority'\n\nexport const rootStyles = cva([\n 'default:self-start',\n 'group inline-flex flex-wrap',\n 'relative items-stretch min-w-max',\n 'rounded-xl p-sm',\n 'bg-surface border-sm border-outline',\n])\n\nexport const itemStyles = cva([\n 'relative z-raised min-h-sz-44 focus-visible:outline-none',\n 'flex flex-auto items-center justify-center gap-md',\n 'default:px-lg default:py-md',\n 'rounded-[20px]',\n 'cursor-pointer select-none',\n 'font-medium',\n 'transition-colors duration-150',\n 'outline-none',\n 'focus-visible:u-outline',\n 'data-disabled:cursor-not-allowed data-disabled:opacity-dim-3',\n 'data-checked:text-on-support-container',\n // Avoid layout shift: simulate \"bold\" without changing font metrics.\n // Apply only to wrapped text nodes (not arbitrary nested JSX like Tag).\n 'data-checked:[&>[data-spark-segmented-control-text]]:[text-shadow:0.35px_0_currentColor,-0.35px_0_currentColor]',\n])\n\nexport const indicatorStyles = cva([\n 'absolute z-base',\n 'rounded-[20px]',\n 'bg-support-container border-md border-support',\n 'group-has-focus-visible:border-focus',\n 'transition-[left,top,width,height] duration-200 ease-in-out',\n 'pointer-events-none',\n])\n\nexport type SegmentedControlStylesProps = VariantProps<typeof itemStyles>\n","import { createContext, RefObject, useContext } from 'react'\n\nexport interface SegmentedControlContextInterface {\n checkedValue: string | null\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n name?: string\n rowLength?: number\n itemValues: string[]\n}\n\nexport const SegmentedControlContext = createContext<SegmentedControlContextInterface>(\n {} as SegmentedControlContextInterface\n)\n\nexport const useSegmentedControlContext = () => {\n const context = useContext(SegmentedControlContext)\n\n if (!context) {\n throw Error('useSegmentedControlContext must be used within a SegmentedControlContext Provider')\n }\n\n return context\n}\n","import { KeyboardEvent, RefObject } from 'react'\n\ninterface UseSegmentedControlNavigationProps {\n itemValues: string[]\n containerRef: RefObject<HTMLDivElement | null>\n onValueChange: (value: string) => void\n}\n\n/**\n * Custom hook that handles keyboard navigation for SegmentedControl.\n * Uses sequential left/right navigation.\n */\nexport const useSegmentedControlNavigation = ({\n itemValues,\n containerRef,\n onValueChange,\n}: UseSegmentedControlNavigationProps) => {\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // Find the currently focused item (which may differ from checkedValue during keyboard navigation)\n const focusedElement = e.target as HTMLElement\n const focusedValue = focusedElement.getAttribute('data-value')\n\n if (!focusedValue) return\n\n const currentIndex = itemValues.indexOf(focusedValue)\n if (currentIndex === -1) return\n\n let nextIndex: number | null = null\n\n // Always use 1D sequential navigation (left/right only)\n nextIndex = calculate1DNavigation(e.key, currentIndex, itemValues.length)\n\n if (nextIndex !== null && nextIndex !== currentIndex) {\n e.preventDefault()\n\n // Skip disabled items\n let attempts = 0\n const maxAttempts = itemValues.length\n\n while (attempts < maxAttempts) {\n const nextValue = itemValues[nextIndex]\n if (!nextValue) return\n\n const nextItem = containerRef.current?.querySelector<HTMLElement>(\n `[data-value=\"${CSS.escape(nextValue)}\"]`\n )\n\n // If the item is not disabled, focus it and update the value\n if (nextItem && !nextItem.hasAttribute('data-disabled')) {\n nextItem.focus()\n onValueChange(nextValue)\n return\n }\n\n // If disabled, continue in the same direction\n const direction = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1\n nextIndex = (nextIndex + direction + itemValues.length) % itemValues.length\n attempts++\n }\n }\n }\n\n return { handleKeyDown }\n}\n\n/**\n * Calculate next index for 1D sequential navigation.\n * Navigation wraps around at the boundaries.\n */\nfunction calculate1DNavigation(\n key: string,\n currentIndex: number,\n totalItems: number\n): number | null {\n switch (key) {\n case 'ArrowRight':\n case 'ArrowDown':\n return (currentIndex + 1) % totalItems\n case 'ArrowLeft':\n case 'ArrowUp':\n return (currentIndex - 1 + totalItems) % totalItems\n default:\n return null\n }\n}\n","import { useFormFieldControl } from '@spark-ui/components/form-field'\nimport { useMergeRefs } from '@spark-ui/hooks/use-merge-refs'\nimport {\n Children,\n type ComponentProps,\n CSSProperties,\n isValidElement,\n Ref,\n useRef,\n useState,\n} from 'react'\n\nimport type { SegmentedControlStylesProps } from './SegmentedControl.styles'\nimport { rootStyles } from './SegmentedControl.styles'\nimport { SegmentedControlContext } from './SegmentedControlContext'\nimport { useSegmentedControlNavigation } from './useSegmentedControlNavigation'\n\nexport interface SegmentedControlProps\n extends Omit<ComponentProps<'div'>, 'onValueChange'>, SegmentedControlStylesProps {\n /**\n * The controlled selected value.\n */\n value?: string\n /**\n * The uncontrolled default selected value.\n */\n defaultValue?: string\n /**\n * Callback fired when the selected value changes.\n */\n onValueChange?: (value: string) => void\n /**\n * Number of items per row in multi-row layout.\n * When undefined, items display in a single row (default behavior).\n * @default undefined\n * @example\n * // Create 3-column grid with wrapping rows\n * <SegmentedControl rowLength={3}>\n */\n rowLength?: number\n /**\n * The name attribute for the radio group (used in form submissions).\n */\n name?: string\n ref?: Ref<HTMLDivElement>\n}\n\nconst getFirstItemValue = (children: React.ReactNode): string | null => {\n let firstValue: string | null = null\n\n Children.forEach(children, child => {\n if (firstValue !== null) return\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n firstValue = (child.props as { value: string }).value\n }\n })\n\n return firstValue\n}\n\nexport const SegmentedControl = ({\n value,\n defaultValue,\n onValueChange,\n className,\n children,\n rowLength,\n name: nameProp,\n ref,\n ...rest\n}: SegmentedControlProps) => {\n const containerRef = useRef<HTMLDivElement | null>(null)\n const mergedRef = useMergeRefs(containerRef, ref)\n\n const firstValue = getFirstItemValue(children)\n\n const isControlled = value !== undefined\n const [internalValue, setInternalValue] = useState<string | null>(\n () => defaultValue ?? firstValue\n )\n const checkedValue = isControlled ? (value ?? null) : internalValue\n\n const handleValueChange = (newValue: string) => {\n if (!isControlled) {\n setInternalValue(newValue)\n }\n\n onValueChange?.(newValue)\n }\n\n const { labelId, description, isRequired, isInvalid, name: nameFromField } = useFormFieldControl()\n const name = nameProp ?? nameFromField\n\n // Get all item values in order\n const itemValues: string[] = []\n Children.forEach(children, child => {\n if (isValidElement(child) && typeof (child.props as { value?: string }).value === 'string') {\n itemValues.push((child.props as { value: string }).value)\n }\n })\n\n // Keyboard navigation (sequential left/right)\n const { handleKeyDown } = useSegmentedControlNavigation({\n itemValues,\n containerRef,\n onValueChange: handleValueChange,\n })\n\n // Compute dynamic flex styles for multi-row layout\n const flexStyles = rowLength\n ? ({\n '--segmented-control-cols': rowLength,\n rowGap: 'var(--spacing-md)',\n } as CSSProperties)\n : undefined\n\n return (\n <SegmentedControlContext\n value={{\n checkedValue,\n containerRef,\n onValueChange: handleValueChange,\n name,\n rowLength,\n itemValues,\n }}\n >\n <div\n ref={mergedRef}\n role=\"radiogroup\"\n data-spark-component=\"segmented-control\"\n className={rootStyles({ className })}\n style={flexStyles}\n aria-labelledby={labelId}\n aria-describedby={description}\n aria-required={isRequired || undefined}\n aria-invalid={isInvalid || undefined}\n onKeyDown={handleKeyDown}\n {...rest}\n >\n {children}\n </div>\n </SegmentedControlContext>\n )\n}\n\nSegmentedControl.displayName = 'SegmentedControl'\n","import { type ComponentProps, type CSSProperties, Ref, useEffect, useState } from 'react'\n\nimport { indicatorStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\ninterface IndicatorRect {\n left: number\n top: number\n width: number\n height: number\n}\n\nexport interface SegmentedControlIndicatorProps extends ComponentProps<'span'> {\n ref?: Ref<HTMLSpanElement>\n}\n\n/**\n * Finds an item by comparing `dataset.value` directly, rather than building a selector with\n * `CSS.escape` (a browser-only global that is unavailable during server-side rendering).\n */\nconst findItemByValue = (container: HTMLElement, value: string | null | undefined) => {\n if (!value) return null\n\n return (\n Array.from(container.querySelectorAll<HTMLElement>('[data-value]')).find(\n el => el.dataset.value === value\n ) ?? null\n )\n}\n\n/** The visual indicator that highlights the selected item. Renders a <span> element. */\nexport const SegmentedControlIndicator = ({\n className,\n ref,\n ...rest\n}: SegmentedControlIndicatorProps) => {\n const { checkedValue, containerRef } = useSegmentedControlContext()\n const [rect, setRect] = useState<IndicatorRect | null>(null)\n\n useEffect(() => {\n const container = containerRef.current\n\n if (!container) {\n return\n }\n\n const selectedItem = findItemByValue(container, checkedValue)\n\n const update = () => {\n const currentContainer = containerRef.current\n if (!currentContainer) {\n setRect(null)\n\n return\n }\n\n const currentSelected = findItemByValue(currentContainer, checkedValue)\n if (!currentSelected) {\n setRect(null)\n\n return\n }\n\n const containerRect = currentContainer.getBoundingClientRect()\n const itemRect = currentSelected.getBoundingClientRect()\n\n // Storybook canvas \"zoom\" can be implemented via `transform: scale()`.\n // In that case, `getBoundingClientRect()` returns *scaled* values, but CSS positioning/sizing\n // expects unscaled layout pixels. We infer the scale factor from offset sizes and normalize.\n const scaleX =\n currentSelected.offsetWidth > 0 ? itemRect.width / currentSelected.offsetWidth : 1\n const scaleY =\n currentSelected.offsetHeight > 0 ? itemRect.height / currentSelected.offsetHeight : 1\n\n // `getBoundingClientRect()` is border-box; absolute positioning is relative to the padding box.\n setRect({\n left: (itemRect.left - containerRect.left) / scaleX - currentContainer.clientLeft,\n top: (itemRect.top - containerRect.top) / scaleY - currentContainer.clientTop,\n width: itemRect.width / scaleX,\n height: itemRect.height / scaleY,\n })\n }\n\n update()\n\n const ro =\n typeof ResizeObserver !== 'undefined'\n ? new ResizeObserver(() => {\n update()\n })\n : null\n\n ro?.observe(container)\n if (selectedItem) ro?.observe(selectedItem)\n\n window.addEventListener('resize', update, { passive: true })\n window.visualViewport?.addEventListener('resize', update, { passive: true })\n\n return () => {\n ro?.disconnect()\n window.removeEventListener('resize', update)\n window.visualViewport?.removeEventListener('resize', update)\n }\n }, [containerRef, checkedValue])\n\n if (!rect) return null\n\n const style: CSSProperties = {\n left: rect.left,\n top: rect.top,\n width: rect.width,\n height: rect.height,\n }\n\n return (\n <span\n ref={ref}\n data-spark-component=\"segmented-control-indicator\"\n aria-hidden\n className={indicatorStyles({ className })}\n style={style}\n {...rest}\n />\n )\n}\n\nSegmentedControlIndicator.displayName = 'SegmentedControl.Indicator'\n","import { Children, type ComponentProps, Ref } from 'react'\n\nimport { itemStyles } from './SegmentedControl.styles'\nimport { useSegmentedControlContext } from './SegmentedControlContext'\n\nexport interface SegmentedControlItemProps extends Omit<\n ComponentProps<'button'>,\n 'value' | 'onClick'\n> {\n /**\n * A unique value that identifies this item within the segmented control.\n */\n value: string\n /**\n * When true, prevents the user from interacting with this item.\n * @default false\n */\n disabled?: boolean\n ref?: Ref<HTMLButtonElement>\n}\n\n/** A selectable item in the segmented control. Renders a <button> element. */\nexport const SegmentedControlItem = ({\n value,\n disabled = false,\n children,\n className,\n ref,\n ...rest\n}: SegmentedControlItemProps) => {\n const { checkedValue, onValueChange, name, rowLength, itemValues } = useSegmentedControlContext()\n\n const isChecked = checkedValue === value\n\n const handleClick = () => {\n if (!disabled) {\n onValueChange(value)\n }\n }\n\n const content = Children.toArray(children).map((child, index) => {\n if (typeof child === 'string' || typeof child === 'number') {\n return (\n <span key={`text-${index}`} data-spark-segmented-control-text>\n {child}\n </span>\n )\n }\n\n return child\n })\n\n // Calculate flex-basis for multi-row layout and horizontal separator visibility\n const itemIndex = itemValues.indexOf(value)\n const itemStyle = rowLength\n ? { flexBasis: `calc(100% / var(--segmented-control-cols))` }\n : undefined\n\n let showHorizontalSeparator = false\n\n if (rowLength && rowLength > 0 && itemIndex !== -1) {\n const cols = rowLength\n const currentCol = itemIndex % cols\n const currentRow = Math.floor(itemIndex / cols)\n const totalRows = Math.ceil(itemValues.length / cols)\n\n // Show horizontal separator only on the first column of each row (except last row)\n showHorizontalSeparator = currentRow < totalRows - 1 && currentCol === 0\n }\n\n return (\n <button\n ref={ref}\n type=\"button\"\n role=\"radio\"\n data-spark-component=\"segmented-control-item\"\n data-value={value}\n aria-checked={isChecked}\n data-checked={isChecked || undefined}\n data-disabled={disabled || undefined}\n disabled={disabled}\n tabIndex={isChecked ? 0 : -1}\n className={itemStyles({ className })}\n style={itemStyle}\n onClick={handleClick}\n {...rest}\n >\n {content}\n {/* Hidden input for form submission */}\n {name && isChecked && <input type=\"hidden\" name={name} value={value} />}\n {/* Horizontal separator between rows (full width across all columns) */}\n {showHorizontalSeparator && rowLength && (\n <div\n className=\"bg-outline/dim-3 -mx-sm absolute left-0 h-px\"\n style={{\n bottom: 'calc(var(--spacing-md) / -2)',\n width: `calc(${rowLength * 100}% + var(--spacing-sm) * 2)`,\n }}\n aria-hidden=\"true\"\n />\n )}\n </button>\n )\n}\n\nSegmentedControlItem.displayName = 'SegmentedControl.Item'\n","import { SegmentedControl as Root } from './SegmentedControl'\nimport { SegmentedControlIndicator as Indicator } from './SegmentedControlIndicator'\nimport { SegmentedControlItem as Item } from './SegmentedControlItem'\n\n/**\n * A set of toggle buttons that allows users to select a single option from a group of related choices.\n */\nexport const SegmentedControl: typeof Root & {\n Item: typeof Item\n Indicator: typeof Indicator\n} = Object.assign(Root, {\n Item,\n Indicator,\n})\n\nSegmentedControl.displayName = 'SegmentedControl'\nItem.displayName = 'SegmentedControl.Item'\nIndicator.displayName = 'SegmentedControl.Indicator'\n\nexport type { SegmentedControlProps } from './SegmentedControl'\nexport type { SegmentedControlItemProps } from './SegmentedControlItem'\nexport type { SegmentedControlIndicatorProps } from './SegmentedControlIndicator'\n"],"mappings":";;;;;;AAEA,IAAa,IAAa,EAAI;CAC5B;CACA;CACA;CACA;CACA;AACF,CAAC,GAEY,IAAa,EAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;AACF,CAAC,GAEY,IAAkB,EAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,GCvBY,IAA0B,EACrC,CAAC,CACH,GAEa,UAAmC;CAC9C,IAAM,IAAU,EAAW,CAAuB;CAElD,IAAI,CAAC,GACH,MAAM,MAAM,mFAAmF;CAGjG,OAAO;AACT,GCXa,KAAiC,EAC5C,eACA,iBACA,wBA+CO,EAAE,gBA7Cc,MAAqC;CAG1D,IAAM,IADiB,EAAE,OACW,aAAa,YAAY;CAE7D,IAAI,CAAC,GAAc;CAEnB,IAAM,IAAe,EAAW,QAAQ,CAAY;CACpD,IAAI,MAAiB,IAAI;CAEzB,IAAI,IAA2B;CAK/B,IAFA,IAAY,EAAsB,EAAE,KAAK,GAAc,EAAW,MAAM,GAEpE,MAAc,QAAQ,MAAc,GAAc;EACpD,EAAE,eAAe;EAGjB,IAAI,IAAW,GACT,IAAc,EAAW;EAE/B,OAAO,IAAW,IAAa;GAC7B,IAAM,IAAY,EAAW;GAC7B,IAAI,CAAC,GAAW;GAEhB,IAAM,IAAW,EAAa,SAAS,cACrC,gBAAgB,IAAI,OAAO,CAAS,EAAE,GACxC;GAGA,IAAI,KAAY,CAAC,EAAS,aAAa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C1D,KAAA,GAEA,IAA0B;CAE9B,IAAI,KAAa,IAAY,KAAK,MAAc,IAAI;EAClD,IAAM,IAAO,GACP,IAAa,IAAY;EAK/B,IAJmB,KAAK,MAAM,IAAY,CAIhB,IAHR,KAAK,KAAK,EAAW,SAAS,CAGT,IAAY,KAAK,MAAe;CACzE;CAEA,OACE,kBAAC,UAAD;EACO;EACL,MAAK;EACL,MAAK;EACL,wBAAqB;EACrB,cAAY;EACZ,gBAAc;EACd,gBAAc,KAAa,KAAA;EAC3B,iBAAe,KAAY,KAAA;EACjB;EACV,UAAU,IAAY,IAAI;EAC1B,WAAW,EAAW,EAAE,aAAU,CAAC;EACnC,OAAO;EACP,SAAS;EACT,GAAI;YAdN;GAgBG;GAEA,KAAQ,KAAa,kBAAC,SAAD;IAAO,MAAK;IAAe;IAAa;GAAQ,CAAA;GAErE,KAA2B,KAC1B,kBAAC,OAAD;IACE,WAAU;IACV,OAAO;KACL,QAAQ;KACR,OAAO,QAAQ,IAAY,IAAI;IACjC;IACA,eAAY;GACb,CAAA;EAEG;;AAEZ;AAEA,EAAqB,cAAc;;;AClGnC,IAAa,IAGT,OAAO,OAAO,GAAM;CACtB,MAAA;CACA,WAAA;AACF,CAAC;AAED,EAAiB,cAAc,oBAC/B,EAAK,cAAc,yBACnB,EAAU,cAAc"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spark-ui/components",
|
|
3
|
-
"version": "18.2.
|
|
3
|
+
"version": "18.2.3",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Spark (Leboncoin design system) components.",
|
|
6
6
|
"exports": {
|
|
@@ -53,9 +53,9 @@
|
|
|
53
53
|
"@react-types/checkbox": "^3.11.0",
|
|
54
54
|
"@react-types/grid": "^3.4.0",
|
|
55
55
|
"@react-types/shared": "^3.36.0",
|
|
56
|
-
"@spark-ui/hooks": "18.2.
|
|
57
|
-
"@spark-ui/icons": "18.2.
|
|
58
|
-
"@spark-ui/internal-utils": "18.2.
|
|
56
|
+
"@spark-ui/hooks": "18.2.3",
|
|
57
|
+
"@spark-ui/icons": "18.2.3",
|
|
58
|
+
"@spark-ui/internal-utils": "18.2.3",
|
|
59
59
|
"@zag-js/pagination": "1.30.0",
|
|
60
60
|
"@zag-js/react": "1.30.0",
|
|
61
61
|
"class-variance-authority": "0.7.1",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"react-snap-carousel": "0.5.1"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
|
-
"@spark-ui/theme-utils": "18.2.
|
|
70
|
+
"@spark-ui/theme-utils": "18.2.3",
|
|
71
71
|
"react": "19.2.4",
|
|
72
72
|
"react-dom": "19.2.4",
|
|
73
73
|
"tailwindcss": "4.1.18"
|