Files
tansy-ui/src/components/FeaturedSelect.tsx
T
thekhalidsha 9d406d6d2a Tansy UI: a themeable React component kit
Tansy UI is a React component kit by OpenKhalix, named after the tansy
flower ("golden buttons"). It has two surfaces:

- A landing page built entirely from the kit's own components, with
  five featured parts, a palette-switching playground form, and links
  into Storybook
- A Storybook workshop with Tansy branding, a Welcome page, palette
  toolbar and accessibility checks

Includes 15 components with colocated tokens and stories, seven brand
palettes, a palette-aware logo, a Docker/nginx image, a scripted
cPanel deploy, and a generator that keeps the landing page catalogue
in sync with Storybook.
2026-09-28 17:09:57 +05:30

471 lines
17 KiB
TypeScript

import {
useEffect,
useMemo,
useRef,
useState,
forwardRef,
type KeyboardEvent,
type FocusEvent as ReactFocusEvent,
type ReactNode,
} from 'react'
import { createPortal } from 'react-dom'
import { ChevronDown, ChevronUp, X } from 'lucide-react'
import { cn } from '@/lib/cn'
import { omit } from '@/lib/omit'
import { useClickOutside } from '@/lib/useClickOutside'
import { useDropdownPosition, type DropdownPlacement } from '@/lib/useDropdownPosition'
import { Spinner } from './Spinner'
import { Tooltip } from './Tooltip'
import type { SelectOption } from './NativeSelect'
import {
FLOATING_LABEL_SIZES,
LABEL_SIZES,
SELECT_SIZES,
SELECT_THEME_CLASSES,
SELECT_VARIANTS,
SELECT_WIDTHS,
type SelectSize,
type SelectTheme,
type SelectVariant,
type SelectWidth,
} from './select.tokens'
/**
* Custom select with a portalled dropdown, search, and a floating label.
*
* Ported from the source app's `Select/components/FeaturedSelect`.
*
* Two upstream bugs are corrected here, both flagged in comments at the point of
* change: the themed classes were built as template strings (so Tailwind emitted
* no rules for them), and a "cleared but still matching option" value kept the
* control looking filled.
*/
export type FeaturedSelectProps = Omit<
React.HTMLAttributes<HTMLDivElement>,
'onChange' | 'onSelect' | 'defaultValue' | 'placeholder'
> & {
options?: SelectOption[]
value?: string
onChange?: (value: string) => void
label?: string
name?: string
placeholder?: string
size?: SelectSize
theme?: SelectTheme
variant?: SelectVariant
width?: SelectWidth
disabled?: boolean
required?: boolean
error?: string | { message?: string }
isLoading?: boolean
isClearable?: boolean
searchable?: boolean
onSearchChange?: (term: string) => void
/** Scrolls the selected option to the middle of the open list. */
scrollToSelected?: boolean
placement?: DropdownPlacement
/** Stored label for a value whose option has not loaded yet. */
initialSearchTerm?: string
/** Floats the label even when the control is empty and unfocused. */
shrink?: boolean
floatinglabelClass?: string
tooltip?: string
tooltipIcon?: React.ComponentProps<typeof Tooltip>['icon']
helpText?: string
actionButton?: { label: string; onClick: () => void; icon?: ReactNode }
renderOption?: (opt: SelectOption) => ReactNode
onBlur?: (e: ReactFocusEvent<HTMLDivElement>) => void
}
export const FeaturedSelect = forwardRef<HTMLDivElement, FeaturedSelectProps>(
function FeaturedSelect(
{
options = [],
value = '',
onChange,
label,
name,
placeholder = 'Select an option',
size = 'md',
theme = 'primary',
variant = 'outlined',
width = 'full',
disabled = false,
required = false,
error,
isLoading = false,
isClearable = true,
searchable = true,
onSearchChange,
scrollToSelected = false,
placement = 'auto',
initialSearchTerm = '',
shrink = false,
floatinglabelClass = '',
tooltip,
tooltipIcon,
helpText,
actionButton,
renderOption,
className = '',
onBlur,
...props
},
ref,
) {
const htmlProps = omit(props as Record<string, unknown>, [
'shrink', 'hasMore', 'hasMoreKey', 'labelKey', 'valueKey', 'isMulti',
'staticOptions', 'endpoint', 'endpointParams', 'infiniteScroll',
'initialSearch', 'initialSearchTerm', 'initialQuery', 'searchBy',
'control', 'onMenuScroll', 'debounceTime', 'helpText', 'tooltip', 'tooltipIcon',
'isClearable', 'renderOption', 'onBlur',
])
const [isOpen, setIsOpen] = useState(false)
const [isFocused, setIsFocused] = useState(false)
const [searchTerm, setSearchTerm] = useState(initialSearchTerm)
// `initialSearchTerm` is the stored label for the ONE value the field was
// seeded with, so it stops being true the moment the user picks something
// else. Tracking it beats comparing against `value`, because the seeded value
// and its label arrive over several renders.
const [hasUserSelected, setHasUserSelected] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const dropdownRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (initialSearchTerm) setSearchTerm(initialSearchTerm)
// A new seed means a new record in the same mounted field (the next row
// opened in a reused modal): the earlier pick no longer describes it.
setHasUserSelected(false)
}, [initialSearchTerm])
useEffect(() => {
const node = containerRef.current
if (typeof ref === 'function') ref(node)
else if (ref) ref.current = node
}, [ref])
// React's onBlur is focusout and bubbles. Opening the dropdown moves focus to
// its autoFocus search input, which would otherwise read as a blur to the
// consumer — validating a field the user has only just clicked into. The
// dropdown is portalled, so it is not a descendant of containerRef: check
// both roots.
const handleContainerBlur = (event: ReactFocusEvent<HTMLDivElement>) => {
if (!onBlur) return
const next = event.relatedTarget
if (
next instanceof Node &&
(containerRef.current?.contains(next) || dropdownRef.current?.contains(next))
) {
return
}
onBlur(event)
}
const safeOptions = Array.isArray(options) ? options : []
const selectedOption = safeOptions.find((opt) => opt.value === value)
const hasSelectedValue = value !== undefined && value !== null && value !== ''
// Prefer the resolved option; fall back to the caller-supplied label for a
// value whose option has not been fetched yet.
const displayLabel =
selectedOption?.label || (hasSelectedValue && !hasUserSelected ? initialSearchTerm : '') || ''
const filteredOptions = useMemo(() => {
// A server-side search hands us the filtered list; don't filter again.
if (onSearchChange) return safeOptions
return searchable && searchTerm
? safeOptions.filter((opt) => opt.label.toLowerCase().includes(searchTerm.toLowerCase()))
: safeOptions
}, [safeOptions, searchable, searchTerm, onSearchChange])
// A long list opens at the top, leaving the current value scrolled out of
// sight. Centred rather than 'nearest', which would pin the option to the
// bottom edge with no surrounding years visible.
useEffect(() => {
if (!isOpen || !scrollToSelected) return
const frame = requestAnimationFrame(() => {
const list = dropdownRef.current
const selected = list?.querySelector('[data-selected="true"]')
selected?.scrollIntoView?.({ block: 'center' })
})
return () => cancelAnimationFrame(frame)
}, [isOpen, scrollToSelected])
useClickOutside(
[containerRef, dropdownRef],
() => {
setIsOpen(false)
setIsFocused(false)
},
isOpen,
)
const { dropdownPosition, calculateInitialPosition } = useDropdownPosition(
isOpen,
containerRef,
{ placement },
)
const handleToggle = () => {
if (disabled) return
if (!isOpen) calculateInitialPosition()
setIsOpen((open) => !open)
}
const handleSelect = (val: string) => {
onChange?.(val)
setHasUserSelected(true)
setIsOpen(false)
setIsFocused(false)
}
// Derived from `value` alone. The source OR'd in the matched option, so an
// option whose own value is '' (an "All departments" filter) kept the control
// looking filled after the value was cleared — the field showed a label and a
// clear button while the form held '', so a required field read as answered.
const hasValue = hasSelectedValue
// `displayLabel`, not `hasValue`: the all-pass option resolves to a label and
// renders as text, so floating on hasValue alone left the label sitting on
// top of that text. `required` floats too — a mandatory field's label carries
// the asterisk and help icon, which read as content inside the box, and an
// unfloated one leaves a column of required fields misaligned (Taiga #4140).
const isFloating =
shrink || hasValue || Boolean(displayLabel) || isFocused || isOpen || Boolean(error) || required
const isUnderlined = variant === 'underlined'
const themeClasses = SELECT_THEME_CLASSES[theme] ?? SELECT_THEME_CLASSES.primary
const errorMessage = typeof error === 'string' ? error : error?.message
// The floated label is a chip sitting on the border, which only reads against
// a boxed outline. On the underlined variant there is no side border to punch
// through, so lift it clear and drop the chip styling.
const labelClass = isFloating
? cn(
isUnderlined ? '-top-2.5 px-0 bg-transparent z-10' : 'top-[-0.6rem] px-1 bg-white z-10',
FLOATING_LABEL_SIZES[size] ?? FLOATING_LABEL_SIZES.md,
errorMessage ? 'text-red-500' : themeClasses.label,
floatinglabelClass,
)
: cn(
'top-1/2 -translate-y-1/2',
LABEL_SIZES[size] ?? LABEL_SIZES.md,
'text-slate-400 pointer-events-none',
)
const dropdownContent = (
<div
ref={dropdownRef}
style={{
position: 'fixed',
top: dropdownPosition.top,
bottom: dropdownPosition.bottom,
left: dropdownPosition.left,
width: dropdownPosition.width,
maxHeight: dropdownPosition.maxHeight,
zIndex: 10000,
}}
className="bg-white border border-gray-200 rounded-lg shadow-xl overflow-auto"
role="listbox"
aria-expanded={isOpen}
>
{searchable && (
<div className="sticky top-0 z-10 p-2 bg-white border-b border-gray-200">
<input
autoFocus
type="text"
className={cn(
'w-full px-2 py-1 text-sm border rounded focus:outline-none',
themeClasses.searchFocus,
)}
placeholder="Search..."
value={searchTerm}
onChange={(e) => {
const next = e.target.value
setSearchTerm(next)
onSearchChange?.(next)
}}
onClick={(e) => e.stopPropagation()}
/>
</div>
)}
{filteredOptions.length > 0 ? (
filteredOptions.map((opt) => {
const isSelected = opt.value === value
return (
<div
key={opt.value}
role="option"
aria-selected={isSelected}
data-selected={scrollToSelected && isSelected ? 'true' : undefined}
className={cn(
'px-3 py-2 text-sm transition-colors',
opt.disabled
? 'text-slate-300 cursor-not-allowed bg-slate-50/30'
: 'cursor-pointer',
isSelected && !opt.disabled
? themeClasses.selected
: !opt.disabled && 'text-gray-700 hover:bg-gray-50',
)}
onClick={() => !opt.disabled && handleSelect(opt.value)}
>
{renderOption ? renderOption(opt) : opt.label}
</div>
)
})
) : (
!isLoading && (
<div className="px-3 py-4 text-sm text-center text-gray-500">No options found</div>
)
)}
{isLoading && filteredOptions.length > 0 && (
<div className="px-3 py-3 text-center border-t border-gray-200 bg-gray-50/50 flex items-center justify-center gap-2">
<Spinner size="xs" />
<span className="text-[11px] text-gray-500 font-medium tracking-wide">
LOADING MORE...
</span>
</div>
)}
{actionButton && (
<div className="p-2">
<button
type="button"
onClick={(e) => {
e.stopPropagation()
actionButton.onClick()
setIsOpen(false)
}}
className="w-full rounded bg-primary-600 px-2 py-1.5 text-xs font-semibold text-white"
>
{actionButton.label}
</button>
</div>
)}
</div>
)
return (
<div
ref={containerRef}
className={cn(
'relative outline-none',
// Matches the underlined variant's need for room for the floated label.
isUnderlined && 'mt-4',
SELECT_WIDTHS[width] ?? SELECT_WIDTHS.full,
className,
)}
tabIndex={disabled ? -1 : 0}
onKeyDown={(e: KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Enter') handleToggle()
if (e.key === 'Escape') setIsOpen(false)
}}
onBlur={handleContainerBlur}
{...htmlProps}
>
<div
onClick={handleToggle}
className={cn(
'relative flex items-center justify-between transition-all duration-200',
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
SELECT_SIZES[size] ?? SELECT_SIZES.md,
SELECT_VARIANTS[variant] ?? SELECT_VARIANTS.outlined,
'bg-transparent',
isUnderlined ? '' : 'rounded',
(isFocused || isOpen)
? cn('border', isUnderlined ? themeClasses.focus.split(' ')[0] : themeClasses.focus,
isUnderlined ? '' : 'ring-1')
: 'border border-slate-300',
!disabled && !isOpen && !isFocused && themeClasses.hover,
errorMessage && 'border-red-500 ring-red-500',
disabled && 'bg-gray-100 cursor-not-allowed opacity-60',
)}
>
{/* Options load asynchronously (paginated + server-searched), so a saved
value is often absent from `options` on first paint.
`initialSearchTerm` carries the stored label for exactly that case —
without it the field renders blank even though a value is set. */}
<span className={cn('block truncate px-0.5', !displayLabel && 'text-transparent')}>
{displayLabel || placeholder}
</span>
<div className="flex items-center gap-2">
{isLoading && <Spinner size="xs" />}
{isClearable && hasValue && !disabled && (
<X
className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-pointer z-20"
onClick={(e) => {
e.stopPropagation()
// onSearchChange first, so a consumer that sets its own term
// inside onChange still wins.
onSearchChange?.('')
onChange?.('')
setSearchTerm('')
setHasUserSelected(true)
}}
/>
)}
{isOpen ? (
<ChevronUp className="h-4 w-4 text-gray-500" />
) : (
<ChevronDown className="h-4 w-4 text-gray-500" />
)}
</div>
{label && (
<label
className={cn(
'absolute transition-all duration-200',
// Only `left` is set, so the label shrink-wraps to the field and a
// long one wraps to a second line — floated, that line carries the
// label's own opaque background over the selected value. Keep it on
// one line and ellipsize.
'max-w-[calc(100%-1.5rem)] truncate',
isUnderlined ? 'left-0' : 'left-2',
labelClass,
)}
>
<span className="flex items-center gap-1.5">
<span className="truncate">
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</span>
{(tooltip || helpText) && (
<span
className="pointer-events-auto inline-flex shrink-0"
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.preventDefault()}
>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</span>
</label>
)}
</div>
{isOpen && !disabled && createPortal(dropdownContent, document.body)}
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
},
)
export default FeaturedSelect