feat(ui): searchable MultiSelect (cmdk) + DateRangePicker (react-day-picker)

This commit is contained in:
Александр Зимин
2026-05-12 13:55:35 +00:00
parent 9073229c0e
commit 21d95613fc
11 changed files with 533 additions and 92 deletions
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useForm, Controller, type Path, type SubmitHandler } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import Ajv, { type ErrorObject } from 'ajv'
@@ -30,6 +30,7 @@ import {
parseFormDate,
} from '@/lib/dates'
import { pickLocalized } from '@/lib/locales'
import { cn } from '@/lib/utils'
type FormValues = {
businessKey: string
@@ -361,21 +362,112 @@ export const SchemaDrivenForm = ({
// strip сверху (sticky), он же выполняет функцию quick-jump.
const formContainerRef = useRef<HTMLFormElement>(null)
// Scroll-spy: IntersectionObserver следит за section anchors, highlight'ит
// chip активной секции (= видимая ближе всего к верху scroll viewport'а).
// rootMargin '-44px 0px -60% 0px' создаёт «detection band» в верхней 40%
// viewport'а: header sticky ~44px сверху, section считается «активной»
// если её top попадает в этот диапазон. Это даёт ощущение «active = что
// юзер сейчас читает», а не «что в самом верху». threshold 0 — fires при
// любом пересечении границы, дешевле чем массив тысяч threshold'ов.
//
// Сохраняем Map<id, isIntersecting> и считаем active как первую секцию
// в sectionOrder у которой isIntersecting=true. Это устойчивее чем
// «entries[0].target.id» — observer callback приходит batched и порядок
// entries не гарантирован.
const [activeSection, setActiveSection] = useState<SectionId | null>(null)
const intersectingRef = useRef<Map<SectionId, boolean>>(new Map())
const handleIntersect = useCallback(
(entries: IntersectionObserverEntry[]) => {
const map = intersectingRef.current
for (const entry of entries) {
const id = (entry.target as HTMLElement).dataset.sectionId as SectionId | undefined
if (!id) continue
map.set(id, entry.isIntersecting)
}
// Pick first in sectionOrder that is currently intersecting. Fallback —
// оставляем предыдущий active (избегаем «мигания» в null когда юзер
// между секциями в gap-промежутке).
for (const id of sectionOrder) {
if (map.get(id)) {
setActiveSection(id)
return
}
}
},
[sectionOrder],
)
useEffect(() => {
if (!showAllSections) {
setActiveSection(null)
intersectingRef.current.clear()
return
}
const form = formContainerRef.current
if (!form) return
// root: ближайший scrollable ancestor — drawer body. null = viewport,
// но для embedded drawer'а правильнее scoped root. Ищем через closest
// overflow-y-auto. Если не найдено — fallback на null (window scroll).
let root: Element | null = form.parentElement
while (root && root !== document.body) {
const style = window.getComputedStyle(root)
if (
style.overflowY === 'auto' ||
style.overflowY === 'scroll' ||
style.overflowY === 'overlay'
) {
break
}
root = root.parentElement
}
const observer = new IntersectionObserver(handleIntersect, {
root: root && root !== document.body ? root : null,
// Top 44px reserved для chip strip sticky. Bottom -60% — секция
// считается active пока её top в верхних 40% viewport'а.
rootMargin: '-44px 0px -60% 0px',
threshold: 0,
})
// Observe все section anchor divs (data-section-id). Querying inside
// form ref scope чтобы не зацепить чужие элементы.
const anchors = form.querySelectorAll<HTMLElement>('[data-section-id]')
anchors.forEach((el) => observer.observe(el))
return () => {
observer.disconnect()
intersectingRef.current.clear()
}
// sectionOrder в deps чтобы при изменении schema'ы observer'ы пересоздались
// для новых anchor'ов.
}, [showAllSections, handleIntersect, sectionOrder])
const sectionsChipStrip = showAllSections ? (
<div className="flex flex-wrap items-center gap-1.5 sticky top-0 bg-surface pb-2 -mt-1 z-10">
{visibleTabs.map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => scrollToSection(tab.id)}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-sm bg-surface-2 border border-line hover:bg-accent-bg hover:border-accent text-cap text-ink-2 hover:text-accent transition-colors"
>
{tab.label}
<span className="text-mono text-mute">
{filteredBuckets[tab.id]?.length ?? 0}
</span>
</button>
))}
<div
className="flex flex-wrap items-center gap-1.5 sticky top-0 bg-surface pb-2 -mt-1 z-10"
role="navigation"
aria-label={t('drawer.sectionsNav', { defaultValue: 'Секции формы' })}
>
{visibleTabs.map((tab) => {
const isActive = activeSection === tab.id
return (
<button
key={tab.id}
type="button"
onClick={() => scrollToSection(tab.id)}
aria-current={isActive ? 'location' : undefined}
className={cn(
'inline-flex items-center gap-1.5 px-2.5 py-1 rounded-sm border text-cap transition-colors',
isActive
? 'bg-accent-bg border-accent text-accent'
: 'bg-surface-2 border-line text-ink-2 hover:bg-accent-bg/40 hover:border-accent/60 hover:text-accent',
)}
>
{tab.label}
<span className={cn('text-mono', isActive ? 'text-accent/80' : 'text-mute')}>
{filteredBuckets[tab.id]?.length ?? 0}
</span>
</button>
)
})}
</div>
) : null
@@ -411,6 +503,7 @@ export const SchemaDrivenForm = ({
<div
key={id}
id={`form-section-${formId ?? 'default'}-${id}`}
data-section-id={id}
className={sectionVisible(id) ? 'block scroll-mt-12' : 'hidden'}
>
{showAllSections && (isIdentity || fields.length > 0) && (
@@ -37,11 +37,17 @@ import { cn } from '@/lib/utils'
* localStorage key {@code ord-drawer-wide}.</li>
* </ul>
*
* <p>Phase 1 (current): drawer shell + width toggle + sticky chrome.
* Phase 2 (TODO Stage 3.5b): section anchor chips, wide-mode ToC rail
* (180px), search field, "только заполненные" toggle. Требует {@code x-section}
* metadata в schemaJson — пока секционирование делает SchemaDrivenForm своими
* 3 tabs.
* <p>Status (v2.12+):
* <ul>
* <li>✅ Drawer shell + width toggle + sticky chrome (Phase 1).</li>
* <li>✅ Toolbar: search полей + «только заполненные» (props.toolbar).</li>
* <li>✅ Section anchor chips + scroll-spy active highlight — рендерит
* SchemaDrivenForm в sections layout (sticky chip strip с
* IntersectionObserver).</li>
* <li>❌ Wide-mode left ToC rail — отклонено по user feedback
* («в редакторе записей левая навигация лишняя»); chip strip
* выполняет ту же функцию quick-jump компактнее.</li>
* </ul>
*
* <p>Drives form submit через атрибут {@code form={formId}} на footer Save
* button. SchemaDrivenForm должен получить тот же {@code formId} prop и
@@ -226,9 +232,9 @@ export function RecordDrawer({
)}
{/* === BODY (scrolling) ===
* Phase B остатки (deferred — требует x-section schema metadata):
* - section anchor chips strip над form sections
* - wide-mode left ToC rail (180px) в CSS grid 180px/1fr layout */}
* SchemaDrivenForm в sections layout рендерит свой sticky chip
* strip + IntersectionObserver scroll-spy. Drawer body — просто
* overflow-y-auto контейнер, scroll root для observer'а. */}
<div className="flex-1 overflow-y-auto px-5 py-4">{children}</div>
{/* === FOOTER (sticky bottom) === */}
+10
View File
@@ -161,6 +161,7 @@ i18n
'webhooks.field.dictionaryFilterHint': 'Через запятую: spacecraft, satellite_type. Пусто = все',
'webhooks.field.eventTypeFilter': 'Типы событий',
'webhooks.field.eventTypeFilterHint': 'Record*, Definition*, SchemaDraft*. Пусто = все события.',
'webhooks.field.eventTypeSearch': 'Поиск типа события',
'webhooks.field.description': 'Описание',
'webhooks.field.createdBy': 'Создатель',
'webhooks.error.nameUrlRequired': 'Имя и URL обязательны',
@@ -234,6 +235,7 @@ i18n
'audit.filter.businessKey': 'Бизнес-ключ',
'audit.filter.from': 'С',
'audit.filter.to': 'По',
'audit.filter.range': 'Период',
'audit.filter.reset': 'Сбросить',
'audit.filter.apply': 'Применить',
'audit.filter.active': 'Активные фильтры',
@@ -381,6 +383,9 @@ i18n
'drawer.close': 'Закрыть',
'drawer.captionEdit': 'редактирование записи · {{dict}}',
'drawer.captionCreate': 'новая запись · {{dict}}',
'drawer.sectionsNav': 'Секции формы',
'drawer.searchPlaceholder': 'Поиск полей',
'drawer.onlyFilled': 'только заполненные',
'scope.PUBLIC': 'PUBLIC — публичный',
'scope.INTERNAL': 'INTERNAL — внутренний',
'scope.RESTRICTED': 'RESTRICTED — ограниченный',
@@ -843,6 +848,7 @@ i18n
'webhooks.field.dictionaryFilterHint': 'Comma-separated: spacecraft, satellite_type. Empty = all',
'webhooks.field.eventTypeFilter': 'Event types',
'webhooks.field.eventTypeFilterHint': 'Record*, Definition*, SchemaDraft*. Empty = all events.',
'webhooks.field.eventTypeSearch': 'Search event type',
'webhooks.field.description': 'Description',
'webhooks.field.createdBy': 'Created by',
'webhooks.error.nameUrlRequired': 'Name and URL are required',
@@ -914,6 +920,7 @@ i18n
'audit.filter.businessKey': 'Business key',
'audit.filter.from': 'From',
'audit.filter.to': 'To',
'audit.filter.range': 'Date range',
'audit.filter.reset': 'Reset',
'audit.filter.apply': 'Apply',
'audit.filter.active': 'Active filters',
@@ -1052,6 +1059,9 @@ i18n
'drawer.close': 'Close',
'drawer.captionEdit': 'edit record · {{dict}}',
'drawer.captionCreate': 'new record · {{dict}}',
'drawer.sectionsNav': 'Form sections',
'drawer.searchPlaceholder': 'Search fields',
'drawer.onlyFilled': 'only filled',
'form.error.required': 'Required field',
'scope.PUBLIC': 'PUBLIC',
'scope.INTERNAL': 'INTERNAL',
+24 -29
View File
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'
import {
Badge,
Button,
DatePicker,
DateRangePicker,
EmptyState,
IconButton,
LoadingBlock,
@@ -380,34 +380,29 @@ function FilterPanel({
onChange={(e) => set('businessKey', e.target.value || undefined)}
onKeyDown={handleEnter}
/>
<DatePicker
label={t('audit.filter.from')}
value={fromDate}
onChange={(d) =>
set(
'from',
d
? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
d.getDate(),
).padStart(2, '0')}T00:00:00${localTzOffset(d)}`
: undefined,
)
}
/>
<DatePicker
label={t('audit.filter.to')}
value={toDate}
onChange={(d) =>
set(
'to',
d
? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
d.getDate(),
).padStart(2, '0')}T23:59:59${localTzOffset(d)}`
: undefined,
)
}
/>
{/* DateRangePicker заменяет пару отдельных DatePicker'ов — один
* popover с двумя месяцами, выбор start/end в одном UI. ISO sтроки
* c local TZ offset формируются здесь, чтобы backend получал
* правильный bounds (T00:00:00 для from, T23:59:59 для to). */}
<div className="md:col-span-2">
<DateRangePicker
label={t('audit.filter.range', { defaultValue: 'Период' })}
value={{ from: fromDate ?? undefined, to: toDate ?? undefined }}
onChange={({ from, to }) => {
const fromIso = from
? `${from.getFullYear()}-${String(from.getMonth() + 1).padStart(2, '0')}-${String(
from.getDate(),
).padStart(2, '0')}T00:00:00${localTzOffset(from)}`
: undefined
const toIso = to
? `${to.getFullYear()}-${String(to.getMonth() + 1).padStart(2, '0')}-${String(
to.getDate(),
).padStart(2, '0')}T23:59:59${localTzOffset(to)}`
: undefined
onChange({ ...filters, from: fromIso, to: toIso })
}}
/>
</div>
</div>
<div className="flex justify-end gap-2 pt-2 border-t border-line">
<Button type="button" variant="secondary" onClick={onReset}>
@@ -331,6 +331,10 @@ function CreateWebhookDialog({ open, onClose, onSuccess }: CreateDialogProps) {
value={eventTypeFilter}
onChange={(ids) => setEventTypeFilter(ids as string[])}
hint={t('webhooks.field.eventTypeFilterHint')}
searchable
searchPlaceholder={t('webhooks.field.eventTypeSearch', {
defaultValue: 'Поиск типа события',
})}
/>
<TextArea
label={t('webhooks.field.description')}
@@ -0,0 +1,194 @@
import * as React from 'react'
import { CalendarBlankIcon, XIcon } from '@phosphor-icons/react'
import * as PopoverPrimitive from '@radix-ui/react-popover'
import type { DateRange } from 'react-day-picker'
import { Popover, PopoverTrigger, PopoverContent } from './popover'
import { FieldLabel, FieldHint, FieldError } from './field'
import { cn } from '@/lib/utils'
/**
* DateRangePicker — single popover trigger c react-day-picker calendar внутри,
* выбор start/end в одном UI. Stage 3.8b: замена пары двух DatePicker'ов
* (audit page from/to) на компактный range picker.
*
* <p>react-day-picker загружается lazily через React.lazy — модуль ~80kb gz
* чтобы не утяжелять main bundle (DateRangePicker используется только на
* audit page + filtering screens, не в каждом form'е).
*
* <p>Trigger показывает «{from} — {to}», или placeholder если пусто.
* Clear button (X) появляется когда есть выбор.
*
* <p>API:
* <ul>
* <li>value: {from?: Date, to?: Date} — undefined start/end OK (open range).</li>
* <li>onChange: ({from, to}) => void.</li>
* <li>locale: ru (default) или en — формат шапки месяца и weekday labels.</li>
* </ul>
*/
// Lazy react-day-picker — компонент Suspense'ит calendar UI на open. До open
// bundle не подтягивается. Trigger button + state работают eager.
const DayPickerLazy = React.lazy(async () => {
// Подгружаем компонент И стили (vite bundles css side-effect через `?inline`?
// нет — обычный import достаточен, vite collect'ит css в build pipeline).
const [{ DayPicker }] = await Promise.all([
import('react-day-picker'),
import('react-day-picker/style.css'),
])
return { default: DayPicker }
})
export type DateRangePickerValue = {
from?: Date
to?: Date
}
export type DateRangePickerProps = {
label?: React.ReactNode
hint?: React.ReactNode
error?: React.ReactNode
required?: boolean
/** Range value. undefined = пустой пик, partial = open-ended. */
value?: DateRangePickerValue
onChange?: (value: DateRangePickerValue) => void
/** ru (default) или en — для weekday/month labels. */
locale?: 'ru' | 'en'
/** Min / max bounds. Calendar disables вне диапазона. */
fromDate?: Date
toDate?: Date
/** Placeholder когда range пустой. */
placeholder?: string
/** Trigger button id. */
id?: string
disabled?: boolean
rootClassName?: string
triggerClassName?: string
}
const formatDateLabel = (d: Date | undefined, locale: 'ru' | 'en' = 'ru'): string => {
if (!d) return ''
return d.toLocaleDateString(locale === 'ru' ? 'ru-RU' : 'en-US', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
}
export function DateRangePicker({
label,
hint,
error,
required,
value,
onChange,
locale = 'ru',
fromDate,
toDate,
placeholder,
id,
disabled,
rootClassName,
triggerClassName,
}: DateRangePickerProps) {
const autoId = React.useId()
const triggerId = id ?? autoId
const hintId = hint ? `${triggerId}-hint` : undefined
const errorId = error ? `${triggerId}-error` : undefined
const fromLabel = formatDateLabel(value?.from, locale)
const toLabel = formatDateLabel(value?.to, locale)
const hasValue = Boolean(value?.from || value?.to)
const display = hasValue
? `${fromLabel || '…'}${toLabel || '…'}`
: placeholder ?? (locale === 'ru' ? 'Выберите период' : 'Pick a range')
// react-day-picker DateRange type uses `from`/`to` тоже — direct passthrough.
const dpRange: DateRange | undefined = hasValue
? { from: value?.from, to: value?.to }
: undefined
const handleSelect = (next: DateRange | undefined) => {
if (!next) {
onChange?.({})
return
}
onChange?.({ from: next.from, to: next.to })
}
const handleClear = (e: React.MouseEvent) => {
e.stopPropagation()
e.preventDefault()
onChange?.({})
}
return (
<div className={cn('flex flex-col gap-1', rootClassName)}>
{label && (
<FieldLabel htmlFor={triggerId} required={required}>
{label}
</FieldLabel>
)}
<Popover>
<PopoverTrigger asChild>
<button
type="button"
id={triggerId}
disabled={disabled}
aria-invalid={error ? true : undefined}
aria-describedby={[hintId, errorId].filter(Boolean).join(' ') || undefined}
className={cn(
'flex items-center justify-between gap-2 h-9 w-full rounded-md border border-line bg-surface px-3 text-body text-ink',
'hover:border-line-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
'disabled:cursor-not-allowed disabled:opacity-50',
error && 'border-pink focus-visible:ring-pink/40',
triggerClassName,
)}
>
<span className="flex items-center gap-2 flex-1 min-w-0">
<CalendarBlankIcon size={14} weight="regular" className="shrink-0 text-mute" />
<span className={cn('truncate', !hasValue && 'text-mute')}>{display}</span>
</span>
{hasValue && !disabled && (
<span
role="button"
aria-label={locale === 'ru' ? 'Очистить' : 'Clear'}
onClick={handleClear}
className="shrink-0 rounded-sm p-0.5 text-mute hover:text-ink hover:bg-surface-2"
>
<XIcon size={12} weight="bold" />
</span>
)}
</button>
</PopoverTrigger>
<PopoverContent align="start" className="p-3">
<PopoverPrimitive.Close className="hidden" />
<React.Suspense
fallback={
<div className="h-64 w-64 flex items-center justify-center text-mute text-cap">
{locale === 'ru' ? 'Загрузка календаря…' : 'Loading calendar…'}
</div>
}
>
<DayPickerLazy
mode="range"
selected={dpRange}
onSelect={handleSelect}
numberOfMonths={2}
showOutsideDays
startMonth={fromDate}
endMonth={toDate}
weekStartsOn={1}
// ISO 8601 weekday order matches RU calendar convention; en тоже
// OK (просто Monday first). Если когда-нибудь нужен Sunday-first
// — отдельный prop.
className="ord-day-picker"
/>
</React.Suspense>
</PopoverContent>
</Popover>
{hint && !error && <FieldHint id={hintId}>{hint}</FieldHint>}
{error && <FieldError id={errorId}>{error}</FieldError>}
</div>
)
}
@@ -1,6 +1,7 @@
import * as React from 'react'
import { CheckIcon, CaretDownIcon } from '@phosphor-icons/react'
import { CheckIcon, CaretDownIcon, MagnifyingGlassIcon } from '@phosphor-icons/react'
import * as PopoverPrimitive from '@radix-ui/react-popover'
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from 'cmdk'
import { Popover, PopoverTrigger, PopoverContent } from './popover'
import { FieldLabel, FieldHint, FieldError } from './field'
import { Badge } from './badge'
@@ -10,11 +11,15 @@ import { cn } from '@/lib/utils'
* MultiSelect — popover с inline checkboxes. Замена @nstart/ui MultiSelect.
*
* <p>Trigger показывает count selected + первые 2 selected labels.
* Popover — список с checkboxes. Click toggle. Поиск НЕ implemented (handoff
* MultiSelect не требует) — для search-heavy lists используй cmdk Combobox
* (Stage 3.8b TODO).
* Popover — список с checkboxes. Click toggle.
*
* <p>API: options [{value, label}], value string[], onChange (ids: string[]).
* <p><b>Searchable mode</b> (opt-in): {@code searchable=true} включает
* cmdk Combobox c keyword filter + keyboard navigation (↑/↓/Enter/Esc).
* Имеет смысл когда options 10+ или labels длинные. Cmdk фильтрует на
* клиенте по substring match label'а — для server-side search будущий
* follow-up (async loader prop).
*
* <p>API: options [{id, label}], value string[], onChange (ids: string[]).
*/
/** nstart-compat: {id, label}. Use `id` key. */
@@ -39,6 +44,12 @@ export type MultiSelectProps = {
rootClassName?: string
/** Compact display (no badges, just count). */
compact?: boolean
/** Включает cmdk-powered поиск (input + keyboard nav). Default false. */
searchable?: boolean
/** Placeholder for search input (только если searchable). */
searchPlaceholder?: string
/** Message when filter yields zero results (только если searchable). */
emptyMessage?: React.ReactNode
}
export function MultiSelect({
@@ -53,6 +64,9 @@ export function MultiSelect({
disabled,
rootClassName,
compact,
searchable,
searchPlaceholder,
emptyMessage,
}: MultiSelectProps) {
const autoId = React.useId()
const triggerId = autoId
@@ -118,44 +132,108 @@ export function MultiSelect({
</PopoverTrigger>
<PopoverContent align="start" className="p-1 min-w-[var(--radix-popover-trigger-width)]">
<PopoverPrimitive.Close className="hidden" />
<ul role="listbox" aria-multiselectable className="max-h-64 overflow-y-auto">
{options.map((opt) => {
const checked = valueSet.has((opt.id ?? opt.value ?? ''))
return (
<li
key={(opt.id ?? opt.value ?? '')}
role="option"
aria-selected={checked}
tabIndex={0}
onClick={() => toggle((opt.id ?? opt.value ?? ''))}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
toggle((opt.id ?? opt.value ?? ''))
}
}}
className={cn(
'flex items-center gap-2 px-2.5 py-1.5 rounded-sm cursor-pointer text-body',
'hover:bg-surface-2 focus:bg-surface-2 focus:outline-none',
checked && 'text-ink',
)}
>
<span
{searchable ? (
<Command
// cmdk использует label option'а как searchable value через
// `value={String(label)}` — но options могут иметь React.ReactNode
// label'ы (мы поддерживаем JSX в label, см. webhooks). Чтобы
// фильтр работал, передаём value явно — toString() от label если
// оно strings, иначе id. Custom filter handle ниже.
filter={(itemValue, search) => {
if (!search) return 1
return itemValue.toLowerCase().includes(search.toLowerCase()) ? 1 : 0
}}
className="flex flex-col"
>
<div className="flex items-center gap-2 px-2 border-b border-line">
<MagnifyingGlassIcon size={14} weight="regular" className="shrink-0 text-mute" />
<CommandInput
placeholder={searchPlaceholder ?? 'Поиск…'}
className="flex-1 h-8 bg-transparent border-0 outline-none text-body text-ink placeholder:text-mute"
/>
</div>
<CommandList className="max-h-64 overflow-y-auto p-1">
<CommandEmpty className="px-2.5 py-4 text-body text-mute text-center">
{emptyMessage ?? 'Ничего не найдено'}
</CommandEmpty>
<CommandGroup>
{options.map((opt) => {
const optId = opt.id ?? opt.value ?? ''
const checked = valueSet.has(optId)
// cmdk использует value для filter + keyboard match.
// Передаём labels-as-string + id чтобы оба варианта поиска
// работали ("admin" найдёт ADMIN, и "ADMIN" тоже).
const searchValue = `${typeof opt.label === 'string' ? opt.label : ''} ${optId}`.trim()
return (
<CommandItem
key={optId}
value={searchValue}
onSelect={() => toggle(optId)}
className={cn(
'flex items-center gap-2 px-2.5 py-1.5 rounded-sm cursor-pointer text-body',
'aria-selected:bg-surface-2 data-[selected=true]:bg-surface-2',
'hover:bg-surface-2 focus:bg-surface-2 outline-none',
checked && 'text-ink',
)}
>
<span
className={cn(
'inline-flex items-center justify-center size-4 rounded-sm border',
checked
? 'bg-accent border-accent text-on-accent'
: 'border-line-2 bg-surface',
)}
aria-hidden="true"
>
{checked && <CheckIcon size={10} weight="bold" />}
</span>
<span className="flex-1 truncate">{opt.label}</span>
</CommandItem>
)
})}
</CommandGroup>
</CommandList>
</Command>
) : (
<ul role="listbox" aria-multiselectable className="max-h-64 overflow-y-auto">
{options.map((opt) => {
const checked = valueSet.has((opt.id ?? opt.value ?? ''))
return (
<li
key={(opt.id ?? opt.value ?? '')}
role="option"
aria-selected={checked}
tabIndex={0}
onClick={() => toggle((opt.id ?? opt.value ?? ''))}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
toggle((opt.id ?? opt.value ?? ''))
}
}}
className={cn(
'inline-flex items-center justify-center size-4 rounded-sm border',
checked
? 'bg-accent border-accent text-on-accent'
: 'border-line-2 bg-surface',
'flex items-center gap-2 px-2.5 py-1.5 rounded-sm cursor-pointer text-body',
'hover:bg-surface-2 focus:bg-surface-2 focus:outline-none',
checked && 'text-ink',
)}
aria-hidden="true"
>
{checked && <CheckIcon size={10} weight="bold" />}
</span>
<span className="flex-1 truncate">{opt.label}</span>
</li>
)
})}
</ul>
<span
className={cn(
'inline-flex items-center justify-center size-4 rounded-sm border',
checked
? 'bg-accent border-accent text-on-accent'
: 'border-line-2 bg-surface',
)}
aria-hidden="true"
>
{checked && <CheckIcon size={10} weight="bold" />}
</span>
<span className="flex-1 truncate">{opt.label}</span>
</li>
)
})}
</ul>
)}
</PopoverContent>
</Popover>
{hint && !error && <FieldHint id={hintId}>{hint}</FieldHint>}
+5
View File
@@ -57,6 +57,11 @@ export {
} from './components/field'
export { FormActions, type FormActionsProps } from './components/form-actions'
export { DatePicker, type DatePickerProps } from './components/date-picker'
export {
DateRangePicker,
type DateRangePickerProps,
type DateRangePickerValue,
} from './components/date-range-picker'
export {
MultiSelect,
type MultiSelectOption,