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.
This commit is contained in:
commit
9d406d6d2a
81 files changed
+14240
No files matched your search
@@ -0,0 +1,42 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Accordion } from './Accordion'
|
||||
|
||||
const meta = {
|
||||
title: 'Navigation/Accordion',
|
||||
component: Accordion,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component: 'A controlled-friendly disclosure primitive for showing related content without overwhelming the page.',
|
||||
},
|
||||
},
|
||||
},
|
||||
args: {
|
||||
items: [
|
||||
{
|
||||
title: 'What is a component story?',
|
||||
content: 'A focused example of one component with specific props, states, and surrounding context.',
|
||||
},
|
||||
{
|
||||
title: 'Why document states?',
|
||||
content: 'A component is only complete when its loading, empty, error, and success states are clear.',
|
||||
},
|
||||
{
|
||||
title: 'How do I add my own?',
|
||||
content: 'Create a .stories.tsx file beside the component and use the same Meta and StoryObj patterns.',
|
||||
},
|
||||
],
|
||||
},
|
||||
} satisfies Meta<typeof Accordion>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
export const Default: Story = {}
|
||||
|
||||
export const Multiple: Story = {
|
||||
args: {
|
||||
allowMultiple: true,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useId, useState, type ReactNode } from 'react'
|
||||
|
||||
export type AccordionItem = {
|
||||
title: string
|
||||
content: ReactNode
|
||||
}
|
||||
|
||||
export type AccordionProps = {
|
||||
items: AccordionItem[]
|
||||
defaultOpenIndex?: number
|
||||
allowMultiple?: boolean
|
||||
}
|
||||
|
||||
function Chevron() {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 transition-transform duration-200"
|
||||
fill="none"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path
|
||||
d="m5 7.5 5 5 5-5"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.8"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function Accordion({ items, defaultOpenIndex = 0, allowMultiple = false }: AccordionProps) {
|
||||
const [openItems, setOpenItems] = useState<number[]>(
|
||||
defaultOpenIndex < 0 ? [] : [defaultOpenIndex],
|
||||
)
|
||||
const baseId = useId()
|
||||
|
||||
function toggle(index: number) {
|
||||
setOpenItems((current) => {
|
||||
if (allowMultiple) {
|
||||
return current.includes(index)
|
||||
? current.filter((item) => item !== index)
|
||||
: [...current, index]
|
||||
}
|
||||
|
||||
return current.includes(index) ? [] : [index]
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-slate-200 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
|
||||
{items.map((item, index) => {
|
||||
const isOpen = openItems.includes(index)
|
||||
const triggerId = `${baseId}-trigger-${index}`
|
||||
const panelId = `${baseId}-panel-${index}`
|
||||
|
||||
return (
|
||||
<div key={item.title}>
|
||||
<h3>
|
||||
<button
|
||||
id={triggerId}
|
||||
type="button"
|
||||
aria-expanded={isOpen}
|
||||
aria-controls={panelId}
|
||||
onClick={() => toggle(index)}
|
||||
className="flex w-full items-center justify-between gap-5 px-5 py-4 text-left text-sm font-bold text-slate-900 transition hover:bg-slate-50"
|
||||
>
|
||||
<span>{item.title}</span>
|
||||
<span className={isOpen ? 'rotate-180 text-primary-500' : 'text-slate-400'}>
|
||||
<Chevron />
|
||||
</span>
|
||||
</button>
|
||||
</h3>
|
||||
{isOpen && (
|
||||
<div id={panelId} role="region" aria-labelledby={triggerId} className="px-5 pb-5">
|
||||
<div className="border-l-2 border-primary-100 pl-4 text-sm leading-6 text-slate-600">
|
||||
{item.content}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useState, type ReactElement } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Alert } from './Alert'
|
||||
|
||||
const meta = {
|
||||
title: 'Feedback/Alert',
|
||||
component: Alert,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Inline, dismissible status message. `iconName` takes any Lucide icon name as a string, so the icon is controllable without importing the module.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
color: { control: 'select', options: ['success', 'info', 'warning', 'error'] },
|
||||
variant: { control: 'select', options: ['default', 'filled', 'outlined', 'gradient'] },
|
||||
iconName: {
|
||||
control: 'text',
|
||||
description: 'Lucide icon name, e.g. "Info", "CheckCircle2", "TriangleAlert".',
|
||||
},
|
||||
showCloseButton: { control: 'boolean' },
|
||||
showMessage: { control: 'boolean' },
|
||||
closeOnOutsideClick: { control: 'boolean' },
|
||||
autoClose: {
|
||||
control: { type: 'number', min: 0, step: 500 },
|
||||
description: 'Auto-close delay in ms. 0 disables.',
|
||||
},
|
||||
width: { control: 'text' },
|
||||
height: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
title: 'Payroll run approved',
|
||||
message: 'March 2026 payroll was approved and queued for disbursement.',
|
||||
iconName: 'CheckCircle2',
|
||||
variant: 'default',
|
||||
color: 'success',
|
||||
showCloseButton: true,
|
||||
showMessage: true,
|
||||
closeOnOutsideClick: false,
|
||||
autoClose: 0,
|
||||
width: 'w-full',
|
||||
height: 'h-auto',
|
||||
},
|
||||
} satisfies Meta<typeof Alert>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
/**
|
||||
* Dismissing unmounts the Alert, so this wrapper remounts it via a changing key.
|
||||
* Declared as a named component so the rules-of-hooks lint accepts the hook call.
|
||||
*/
|
||||
function Remountable({ children, note }: { children: ReactElement; note?: string }) {
|
||||
const [key, setKey] = useState(0)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div key={key}>{children}</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKey((k) => k + 1)}
|
||||
className="text-xs font-semibold text-primary-600 underline"
|
||||
>
|
||||
Remount
|
||||
</button>
|
||||
{note && <p className="text-xs text-gray-500">{note}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => <Remountable><Alert {...args} /></Remountable>,
|
||||
}
|
||||
|
||||
export const Colors: Story = {
|
||||
render: () => (
|
||||
<div className="space-y-3">
|
||||
<Alert color="success" title="Approved" message="Queued for disbursement." iconName="CheckCircle2" />
|
||||
<Alert color="info" title="Processing" message="Validating statutory contributions." iconName="Info" />
|
||||
<Alert color="warning" title="Review needed" message="2 employees have incomplete bank details." iconName="TriangleAlert" />
|
||||
<Alert color="error" title="Failed" message="Bank rejected the transfer file." iconName="XCircle" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Variants: Story = {
|
||||
render: () => (
|
||||
<div className="space-y-3">
|
||||
<Alert variant="default" color="info" title="Default" message="Tinted surface, semantic text." />
|
||||
<Alert variant="filled" color="info" title="Filled" message="Solid semantic background." />
|
||||
<Alert variant="outlined" color="info" title="Outlined" message="Transparent with a border." />
|
||||
<Alert variant="gradient" title="Gradient" message="Green-to-primary gradient, brand moment." />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithoutCloseButton: Story = {
|
||||
render: () => (
|
||||
<Alert
|
||||
color="info"
|
||||
title="Persistent notice"
|
||||
message="This alert cannot be dismissed."
|
||||
showCloseButton={false}
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const TitleOnly: Story = {
|
||||
render: () => <Alert color="warning" title="12 items need attention" showCloseButton={false} />,
|
||||
}
|
||||
|
||||
/** Auto-closes after 2s; the Remount button brings it back. */
|
||||
export const AutoClose: Story = {
|
||||
render: (args) => (
|
||||
<Remountable note="Dismisses itself after 2000ms.">
|
||||
<Alert {...args} autoClose={2000} />
|
||||
</Remountable>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
forwardRef,
|
||||
type HTMLAttributes,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import * as Icons from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import {
|
||||
ALERT_COLORS,
|
||||
ALERT_GRADIENT,
|
||||
type AlertColor,
|
||||
type AlertVariant,
|
||||
} from './alert.tokens'
|
||||
|
||||
/**
|
||||
* Dismissible inline alert.
|
||||
*
|
||||
* Ported from the original `Alert` component.
|
||||
*
|
||||
* `iconName` takes a Lucide icon name as a string (looked up on the module), so
|
||||
* the icon is controllable from Storybook without importing every icon.
|
||||
*/
|
||||
|
||||
export type AlertProps = HTMLAttributes<HTMLDivElement> & {
|
||||
title?: string
|
||||
message?: ReactNode
|
||||
/** Name of a Lucide icon, e.g. `"Info"`, `"CheckCircle2"`. Falls back to `Info`. */
|
||||
iconName?: string
|
||||
onClose?: () => void
|
||||
variant?: AlertVariant
|
||||
color?: AlertColor
|
||||
showCloseButton?: boolean
|
||||
width?: string
|
||||
height?: string
|
||||
closeOnOutsideClick?: boolean
|
||||
/** Auto-close delay in ms. `0` disables. */
|
||||
autoClose?: number
|
||||
showMessage?: boolean
|
||||
customClose?: ReactNode
|
||||
}
|
||||
|
||||
export const Alert = forwardRef<HTMLDivElement, AlertProps>(function Alert(
|
||||
{
|
||||
title,
|
||||
message,
|
||||
iconName = 'Info',
|
||||
onClose,
|
||||
variant = 'default',
|
||||
color = 'success',
|
||||
className = '',
|
||||
showCloseButton = true,
|
||||
width = 'w-full',
|
||||
height = 'h-auto',
|
||||
closeOnOutsideClick = false,
|
||||
autoClose = 0,
|
||||
showMessage = true,
|
||||
customClose,
|
||||
...props
|
||||
},
|
||||
forwardedRef,
|
||||
) {
|
||||
const [visible, setVisible] = useState(true)
|
||||
const internalRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
setVisible(false)
|
||||
onClose?.()
|
||||
}, [onClose])
|
||||
|
||||
// Mirror the internal node onto the forwarded ref.
|
||||
useEffect(() => {
|
||||
const node = internalRef.current
|
||||
if (typeof forwardedRef === 'function') forwardedRef(node)
|
||||
else if (forwardedRef) forwardedRef.current = node
|
||||
}, [forwardedRef])
|
||||
|
||||
useEffect(() => {
|
||||
if (autoClose > 0) {
|
||||
const timer = setTimeout(handleClose, autoClose)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [autoClose, handleClose])
|
||||
|
||||
useEffect(() => {
|
||||
if (!closeOnOutsideClick) return
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (internalRef.current && !internalRef.current.contains(event.target as Node)) {
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [closeOnOutsideClick, handleClose])
|
||||
|
||||
if (!visible) return null
|
||||
|
||||
const iconMap = Icons as unknown as Record<string, Icons.LucideIcon>
|
||||
const LucideIcon = (iconName && iconMap[iconName]) || Icons.Info
|
||||
const theme = ALERT_COLORS[color] ?? ALERT_COLORS.success
|
||||
|
||||
let variantClasses: string
|
||||
if (variant === 'filled') {
|
||||
variantClasses = cn(theme.bg, 'text-white')
|
||||
} else if (variant === 'outlined') {
|
||||
variantClasses = cn('bg-transparent', theme.text, theme.border, 'border')
|
||||
} else if (variant === 'gradient') {
|
||||
variantClasses = ALERT_GRADIENT
|
||||
} else {
|
||||
variantClasses = cn(theme.lightBg, theme.text)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={internalRef}
|
||||
role="alert"
|
||||
className={cn(
|
||||
'rounded-md p-3 transition-all duration-300',
|
||||
width,
|
||||
height,
|
||||
variantClasses,
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex justify-between gap-3">
|
||||
<div className="flex items-start gap-3 w-full">
|
||||
{LucideIcon && <LucideIcon className="w-5 h-5 mt-0.5 shrink-0" aria-hidden="true" />}
|
||||
|
||||
<div className="flex flex-col gap-1 w-full">
|
||||
{title && <h5 className="font-semibold text-sm leading-tight">{title}</h5>}
|
||||
{showMessage && message && <p className="text-sm opacity-90 leading-normal">{message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showCloseButton && (
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="shrink-0 p-1 rounded-md hover:bg-black/10 transition-colors cursor-pointer"
|
||||
type="button"
|
||||
aria-label="Close alert"
|
||||
>
|
||||
{customClose ?? <Icons.X className="w-4 h-4" />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Alert
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Bell, Inbox, Settings } from 'lucide-react'
|
||||
import { Badge } from './Badge'
|
||||
|
||||
const meta = {
|
||||
title: 'Display/Badge',
|
||||
component: Badge,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Status count or label. `floating` pins to a corner of its child; `default` renders a standalone chip. `colorRanges` colours the badge by numeric value.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
type: { control: 'radio', options: ['floating', 'default'] },
|
||||
color: {
|
||||
control: 'select',
|
||||
options: ['primary', 'info', 'gray', 'danger', 'success', 'warning'],
|
||||
},
|
||||
floatingPosition: {
|
||||
control: 'select',
|
||||
options: ['top_right', 'top_left', 'bottom_right', 'bottom_left'],
|
||||
},
|
||||
floatingSize: { control: 'select', options: ['xs', 'sm', 'md', 'lg'] },
|
||||
defaultSize: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
defaultBorder: { control: 'select', options: ['sm', 'md', 'lg', 'full'] },
|
||||
pulse: { control: 'boolean' },
|
||||
content: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
type: 'floating',
|
||||
color: 'danger',
|
||||
content: '5',
|
||||
floatingPosition: 'top_right',
|
||||
floatingSize: 'sm',
|
||||
defaultSize: 'sm',
|
||||
defaultBorder: 'lg',
|
||||
pulse: false,
|
||||
},
|
||||
} satisfies Meta<typeof Badge>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
const BellIcon = () => <Bell className="h-6 w-6 text-gray-600" />
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => (
|
||||
<Badge {...args}>
|
||||
<BellIcon />
|
||||
</Badge>
|
||||
),
|
||||
}
|
||||
|
||||
export const FloatingPositions: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-10">
|
||||
{(['top_right', 'top_left', 'bottom_right', 'bottom_left'] as const).map((pos) => (
|
||||
<div key={pos} className="flex flex-col items-center gap-2">
|
||||
<Badge content="9" floatingPosition={pos} color="primary">
|
||||
<BellIcon />
|
||||
</Badge>
|
||||
<code className="text-[10px] text-gray-500">{pos}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const FloatingSizes: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-10">
|
||||
{(['xs', 'sm', 'md', 'lg'] as const).map((size) => (
|
||||
<div key={size} className="flex flex-col items-center gap-2">
|
||||
<Badge content={12} floatingSize={size} color="danger">
|
||||
<Inbox className="h-6 w-6 text-gray-600" />
|
||||
</Badge>
|
||||
<code className="text-[10px] text-gray-500">{size}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Colors: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{(['primary', 'info', 'gray', 'danger', 'success', 'warning'] as const).map((color) => (
|
||||
<Badge key={color} type="default" color={color}>
|
||||
{color}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** Colours by numeric content — the pending-approval pattern from the source app. */
|
||||
export const ColorRanges: Story = {
|
||||
render: () => {
|
||||
const ranges = [
|
||||
{ min: 0, max: 2, color: 'success' },
|
||||
{ min: 3, max: 7, color: 'warning' },
|
||||
{ min: 8, max: 99, color: 'danger' },
|
||||
]
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-6">
|
||||
{[1, 5, 12].map((n) => (
|
||||
<div key={n} className="flex flex-col items-center gap-2">
|
||||
<Badge content={n} colorRanges={ranges}>
|
||||
<Inbox className="h-6 w-6 text-gray-600" />
|
||||
</Badge>
|
||||
<code className="text-[10px] text-gray-500">{n} pending</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
export const Pulse: Story = {
|
||||
render: () => (
|
||||
<Badge content="Live" color="danger" pulse>
|
||||
<BellIcon />
|
||||
</Badge>
|
||||
),
|
||||
}
|
||||
|
||||
/** `default` type renders a standalone chip; children take precedence over content. */
|
||||
export const ChipWithIcon: Story = {
|
||||
render: () => (
|
||||
<Badge type="default" color="primary" defaultBorder="full" defaultSize="md">
|
||||
<Settings className="mr-1.5 h-3.5 w-3.5" aria-hidden="true" />
|
||||
Configured
|
||||
</Badge>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import {
|
||||
BADGE_COLORS,
|
||||
BADGE_COLOR_ALIAS,
|
||||
BADGE_POSITIONS,
|
||||
BADGE_ROUNDED,
|
||||
BADGE_SIZES,
|
||||
DEFAULT_BADGE_SIZES,
|
||||
resolveBadgeColor,
|
||||
type BadgeBorder,
|
||||
type BadgeColor,
|
||||
type BadgeDefaultSize,
|
||||
type BadgeFloatingPosition,
|
||||
type BadgeFloatingSize,
|
||||
type BadgeType,
|
||||
type ColorRange,
|
||||
} from './badge.tokens'
|
||||
|
||||
/**
|
||||
* Status indicator / count badge.
|
||||
*
|
||||
* Ported from the original `Badge` component.
|
||||
*
|
||||
* Two shapes:
|
||||
* - `floating` (default) — pins the badge to a corner of its child (an icon or
|
||||
* avatar), so the child wraps it.
|
||||
* - `default` — a standalone inline chip.
|
||||
*
|
||||
* `colorRanges` maps a numeric `content` onto a colour band, which is how the
|
||||
* source app colours pending-approval counts without a per-row className.
|
||||
*/
|
||||
|
||||
export type BadgeProps = Omit<HTMLAttributes<HTMLDivElement>, 'content'> & {
|
||||
type?: BadgeType
|
||||
/** The count or label. Accepts a number — counts arrive as numbers in the source app. */
|
||||
content?: ReactNode | number
|
||||
color?: BadgeColor | string
|
||||
/** Colour the badge by numeric value, e.g. `[{min:5,max:9,color:'warning'}]`. */
|
||||
colorRanges?: ColorRange[]
|
||||
floatingPosition?: BadgeFloatingPosition
|
||||
floatingSize?: BadgeFloatingSize
|
||||
defaultSize?: BadgeDefaultSize
|
||||
defaultBorder?: BadgeBorder
|
||||
/** Remix-icon class name, e.g. `"ri-home-line"`. Needs the Remix font. */
|
||||
defaultIcon?: string
|
||||
pulse?: boolean
|
||||
}
|
||||
|
||||
export const Badge = forwardRef<HTMLDivElement, BadgeProps>(function Badge(
|
||||
{
|
||||
type = 'floating',
|
||||
content,
|
||||
color = 'danger',
|
||||
colorRanges,
|
||||
children,
|
||||
floatingPosition = 'top_right',
|
||||
floatingSize = 'sm',
|
||||
pulse = false,
|
||||
className = '',
|
||||
defaultSize = 'sm',
|
||||
defaultBorder = 'lg',
|
||||
defaultIcon,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const normalized = BADGE_COLOR_ALIAS[color] ?? (color as BadgeColor)
|
||||
const computed =
|
||||
type === 'floating' ? resolveBadgeColor(color, content, colorRanges) : normalized
|
||||
const theme = BADGE_COLORS[computed] ?? BADGE_COLORS[normalized] ?? BADGE_COLORS.danger
|
||||
|
||||
if (type === 'default') {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center font-medium transition-colors',
|
||||
BADGE_ROUNDED[defaultBorder] ?? BADGE_ROUNDED.lg,
|
||||
DEFAULT_BADGE_SIZES[defaultSize] ?? DEFAULT_BADGE_SIZES.sm,
|
||||
theme,
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{defaultIcon && <i className={cn(defaultIcon, 'mr-1.5')} aria-hidden="true" />}
|
||||
{children ?? content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex">
|
||||
{children}
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'absolute z-10 inline-flex items-center justify-center rounded-full font-semibold',
|
||||
BADGE_POSITIONS[floatingPosition] ?? BADGE_POSITIONS.top_right,
|
||||
BADGE_SIZES[floatingSize] ?? BADGE_SIZES.sm,
|
||||
theme,
|
||||
pulse && 'animate-pulse',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
</span>
|
||||
)
|
||||
})
|
||||
|
||||
export default Badge
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Button, LinkButton } from './Button'
|
||||
|
||||
const meta = {
|
||||
title: 'Actions/Button',
|
||||
component: Button,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component: 'A reusable button with visual variants and size tokens. Use semantic variants rather than ad-hoc colors.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
variant: {
|
||||
control: 'select',
|
||||
options: ['primary', 'secondary', 'outline', 'ghost', 'danger'],
|
||||
},
|
||||
size: {
|
||||
control: 'select',
|
||||
options: ['sm', 'md', 'lg'],
|
||||
},
|
||||
},
|
||||
args: {
|
||||
children: 'Continue',
|
||||
variant: 'primary',
|
||||
size: 'md',
|
||||
},
|
||||
} satisfies Meta<typeof Button>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
export const Playground: Story = {}
|
||||
|
||||
export const Variants: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button>Primary</Button>
|
||||
<Button variant="secondary">Secondary</Button>
|
||||
<Button variant="outline">Outline</Button>
|
||||
<Button variant="ghost">Ghost</Button>
|
||||
<Button variant="danger">Danger</Button>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button size="sm">Small</Button>
|
||||
<Button size="md">Medium</Button>
|
||||
<Button size="lg">Large</Button>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Disabled: Story = {
|
||||
args: {
|
||||
disabled: true,
|
||||
children: 'Unavailable',
|
||||
},
|
||||
}
|
||||
|
||||
export const AsLink: Story = {
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story: '`LinkButton` renders an anchor with the same variants and sizes. Use it for navigation so the page keeps real links.',
|
||||
},
|
||||
},
|
||||
},
|
||||
render: () => (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<LinkButton href="#">Browse components</LinkButton>
|
||||
<LinkButton href="#" variant="outline">Read the guide</LinkButton>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { AnchorHTMLAttributes, ButtonHTMLAttributes, ReactNode } from 'react'
|
||||
|
||||
export type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger'
|
||||
export type ButtonSize = 'sm' | 'md' | 'lg'
|
||||
|
||||
type ButtonStyleProps = {
|
||||
variant?: ButtonVariant
|
||||
size?: ButtonSize
|
||||
icon?: ReactNode
|
||||
}
|
||||
|
||||
export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & ButtonStyleProps
|
||||
|
||||
/** A navigation link that looks like a Button. Use it wherever the action is "go somewhere". */
|
||||
export type LinkButtonProps = AnchorHTMLAttributes<HTMLAnchorElement> & ButtonStyleProps & {
|
||||
href: string
|
||||
}
|
||||
|
||||
const variantClasses: Record<ButtonVariant, string> = {
|
||||
primary:
|
||||
'border-primary-500 bg-primary-500 text-white shadow-sm hover:border-primary-600 hover:bg-primary-600',
|
||||
secondary:
|
||||
'border-slate-200 bg-slate-100 text-slate-800 hover:border-slate-300 hover:bg-slate-200',
|
||||
outline:
|
||||
'border-slate-300 bg-white text-slate-700 hover:border-primary-500 hover:bg-primary-50 hover:text-primary-700',
|
||||
ghost:
|
||||
'border-transparent bg-transparent text-slate-600 hover:bg-slate-100 hover:text-slate-950',
|
||||
danger:
|
||||
'border-red-600 bg-red-600 text-white shadow-sm shadow-red-200 hover:border-red-700 hover:bg-red-700',
|
||||
}
|
||||
|
||||
const sizeClasses: Record<ButtonSize, string> = {
|
||||
sm: 'min-h-9 gap-1.5 rounded-lg px-3 text-sm',
|
||||
md: 'min-h-11 gap-2 rounded-xl px-4 text-sm',
|
||||
lg: 'min-h-12 gap-2.5 rounded-xl px-5 text-base',
|
||||
}
|
||||
|
||||
function buttonClasses(variant: ButtonVariant, size: ButtonSize, className: string) {
|
||||
return `inline-flex items-center justify-center border font-semibold transition duration-200 disabled:cursor-not-allowed disabled:opacity-50 ${variantClasses[variant]} ${sizeClasses[size]} ${className}`
|
||||
}
|
||||
|
||||
export function Button({
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
icon,
|
||||
className = '',
|
||||
children,
|
||||
type = 'button',
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
return (
|
||||
<button type={type} className={buttonClasses(variant, size, className)} {...props}>
|
||||
{icon}
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export function LinkButton({
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
icon,
|
||||
className = '',
|
||||
children,
|
||||
...props
|
||||
}: LinkButtonProps) {
|
||||
return (
|
||||
<a className={buttonClasses(variant, size, className)} {...props}>
|
||||
{children}
|
||||
{icon}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Card } from './Card'
|
||||
|
||||
const meta = {
|
||||
title: 'Layout/Card',
|
||||
component: Card,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Surface container with a compound API: `Card.Header`, `Card.Title`, `Card.Body`, `Card.Footer`. Theme and layout are passed down to children automatically.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
theme: {
|
||||
control: 'select',
|
||||
options: ['primary', 'secondary', 'success', 'danger', 'no-preset'],
|
||||
},
|
||||
layout: { control: 'radio', options: ['vertical', 'horizontal'] },
|
||||
shadow: { control: 'select', options: ['none', 'sm', 'md', 'lg', 'xl'] },
|
||||
rounded: { control: 'select', options: ['none', 'sm', 'md', 'lg', 'xl', 'full'] },
|
||||
},
|
||||
args: { theme: 'primary', layout: 'vertical', shadow: 'md', rounded: 'lg' },
|
||||
} satisfies Meta<typeof Card>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => (
|
||||
<Card {...args} className="max-w-sm">
|
||||
<Card.Header>
|
||||
<Card.Title>Payroll run</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Body>March 2026 · 148 employees · ₹42,10,550 net</Card.Body>
|
||||
<Card.Footer>Processed 2 hours ago</Card.Footer>
|
||||
</Card>
|
||||
),
|
||||
}
|
||||
|
||||
export const Themes: Story = {
|
||||
render: () => (
|
||||
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{(['primary', 'secondary', 'success', 'danger'] as const).map((theme) => (
|
||||
<Card key={theme} theme={theme}>
|
||||
<Card.Header>
|
||||
<Card.Title className="text-base capitalize">{theme}</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Body className="text-sm">Surface tinted for the {theme} state.</Card.Body>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Shadows: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-start gap-6">
|
||||
{(['none', 'sm', 'md', 'lg', 'xl'] as const).map((shadow) => (
|
||||
<div key={shadow} className="flex flex-col items-center gap-2">
|
||||
<Card shadow={shadow} className="w-40 p-6 text-center text-sm">
|
||||
{shadow}
|
||||
</Card>
|
||||
<code className="text-[10px] text-gray-500">{shadow}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Rounded: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-start gap-6">
|
||||
{(['none', 'sm', 'md', 'lg', 'xl', 'full'] as const).map((rounded) => (
|
||||
<div key={rounded} className="flex flex-col items-center gap-2">
|
||||
<Card rounded={rounded} className="w-32 p-6 text-center text-sm">
|
||||
{rounded}
|
||||
</Card>
|
||||
<code className="text-[10px] text-gray-500">{rounded}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** `horizontal` splits into a 2-column grid; `fullRow` makes a child span both. */
|
||||
export const HorizontalLayout: Story = {
|
||||
render: () => (
|
||||
<Card layout="horizontal" className="max-w-lg">
|
||||
<Card.Header>
|
||||
<Card.Title>Employee breakdown</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Body>
|
||||
<div className="grid gap-1 text-sm">
|
||||
<span>Full-time · 132</span>
|
||||
<span>Part-time · 11</span>
|
||||
<span>Contract · 5</span>
|
||||
</div>
|
||||
</Card.Body>
|
||||
<Card.Footer className="text-xs text-gray-500">As of 31 Mar 2026</Card.Footer>
|
||||
</Card>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
Children,
|
||||
cloneElement,
|
||||
forwardRef,
|
||||
isValidElement,
|
||||
type ForwardRefExoticComponent,
|
||||
type HTMLAttributes,
|
||||
type ReactElement,
|
||||
type RefAttributes,
|
||||
} from 'react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import {
|
||||
CARD_THEMES,
|
||||
ROUNDED_SIZES,
|
||||
SHADOW_SIZES,
|
||||
type CardLayout,
|
||||
type CardRounded,
|
||||
type CardShadow,
|
||||
type CardTheme,
|
||||
} from './card.tokens'
|
||||
|
||||
/**
|
||||
* Surface container with a header / body / footer compound API.
|
||||
*
|
||||
* Ported from the original `Card` component.
|
||||
*
|
||||
* Note: the original used `dark:` variants throughout. Those are dropped here
|
||||
* because this showcase renders on a light canvas and Storybook backgrounds are
|
||||
* controlled independently — leaving them in produced dark rules that could
|
||||
* never be inspected. Add them back per-component if dark mode returns.
|
||||
*/
|
||||
|
||||
type SpanProps = {
|
||||
layout?: CardLayout
|
||||
fullRow?: boolean
|
||||
fullCol?: boolean
|
||||
}
|
||||
|
||||
/** Grid span helper shared by header / body / footer. */
|
||||
function spanClasses({ layout, fullRow, fullCol }: SpanProps): string {
|
||||
if (layout === 'horizontal') {
|
||||
if (fullRow) return 'col-span-2'
|
||||
if (fullCol) return 'row-span-2'
|
||||
return 'col-span-1'
|
||||
}
|
||||
return 'col-span-1'
|
||||
}
|
||||
|
||||
export type CardProps = HTMLAttributes<HTMLDivElement> & {
|
||||
theme?: CardTheme
|
||||
layout?: CardLayout
|
||||
shadow?: CardShadow
|
||||
rounded?: CardRounded
|
||||
}
|
||||
|
||||
type CardComponent = ForwardRefExoticComponent<CardProps & RefAttributes<HTMLDivElement>> & {
|
||||
Header: typeof CardHeader
|
||||
Title: typeof CardTitle
|
||||
Body: typeof CardBody
|
||||
Content: typeof CardBody
|
||||
Footer: typeof CardFooter
|
||||
}
|
||||
|
||||
const CardBase = forwardRef<HTMLDivElement, CardProps>(function Card(
|
||||
{
|
||||
children,
|
||||
theme = 'primary',
|
||||
layout = 'vertical',
|
||||
shadow = 'md',
|
||||
rounded = 'lg',
|
||||
className = '',
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
|
||||
const gridCols = layout === 'horizontal' ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1'
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'grid overflow-hidden relative',
|
||||
gridCols,
|
||||
SHADOW_SIZES[shadow] ?? SHADOW_SIZES.md,
|
||||
ROUNDED_SIZES[rounded] ?? ROUNDED_SIZES.lg,
|
||||
themeData.card,
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* Pass theme/layout down so nested header/body/footer stay in sync. */}
|
||||
{Children.map(children, (child) => {
|
||||
if (!isValidElement(child)) return null
|
||||
const childProps = child.props as SpanProps & { theme?: CardTheme; layout?: CardLayout }
|
||||
return cloneElement(child as ReactElement<Record<string, unknown>>, {
|
||||
theme: childProps.theme ?? theme,
|
||||
layout: childProps.layout ?? layout,
|
||||
})
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export function CardHeader({
|
||||
children,
|
||||
className = '',
|
||||
theme = 'primary',
|
||||
layout = 'vertical',
|
||||
fullRow = false,
|
||||
fullCol = false,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
|
||||
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
|
||||
return (
|
||||
<div
|
||||
className={cn(themeData.header, spanClasses({ layout, fullRow, fullCol }), className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CardTitle({ children, className = '', ...props }: HTMLAttributes<HTMLHeadingElement>) {
|
||||
return (
|
||||
<h3 className={cn('text-lg font-bold leading-none tracking-tight', className)} {...props}>
|
||||
{children}
|
||||
</h3>
|
||||
)
|
||||
}
|
||||
|
||||
export function CardBody({
|
||||
children,
|
||||
className = '',
|
||||
theme = 'primary',
|
||||
layout = 'vertical',
|
||||
fullRow = false,
|
||||
fullCol = false,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
|
||||
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
|
||||
return (
|
||||
<div
|
||||
className={cn(themeData.body, spanClasses({ layout, fullRow, fullCol }), className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const CardContent = CardBody
|
||||
|
||||
export function CardFooter({
|
||||
children,
|
||||
className = '',
|
||||
theme = 'primary',
|
||||
layout = 'vertical',
|
||||
fullRow = false,
|
||||
fullCol = false,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
|
||||
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
|
||||
return (
|
||||
<div
|
||||
className={cn(themeData.footer, spanClasses({ layout, fullRow, fullCol }), className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Card = Object.assign(CardBase, {
|
||||
Header: CardHeader,
|
||||
Title: CardTitle,
|
||||
Body: CardBody,
|
||||
Content: CardContent,
|
||||
Footer: CardFooter,
|
||||
}) as CardComponent
|
||||
|
||||
export default Card
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Checkbox } from './Checkbox'
|
||||
|
||||
const meta = {
|
||||
title: 'Forms/Checkbox',
|
||||
component: Checkbox,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Checkbox with an optional label, help tooltip and error message. The checked colour uses the native `accent-*` property, so it follows the palette tokens rather than a fixed hex.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
theme: {
|
||||
control: 'select',
|
||||
options: ['primary', 'secondary', 'success', 'danger', 'warning', 'info'],
|
||||
},
|
||||
label: { control: 'text' },
|
||||
disabled: { control: 'boolean' },
|
||||
tooltip: { control: 'text', description: 'Help text shown in a tooltip beside the label.' },
|
||||
helpText: { control: 'text', description: 'Alias for tooltip; tooltip wins if both are set.' },
|
||||
error: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
label: 'Send payroll summary email',
|
||||
size: 'md',
|
||||
theme: 'primary',
|
||||
disabled: false,
|
||||
tooltip: '',
|
||||
helpText: '',
|
||||
error: '',
|
||||
},
|
||||
} satisfies Meta<typeof Checkbox>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
/** Checkbox state lives with the caller, so it is controlled here. */
|
||||
/**
|
||||
* Wraps Checkbox with local state so it is interactive.
|
||||
*
|
||||
* `initial` matters: supplying `checked` at all makes the component controlled,
|
||||
* so `defaultChecked` on the same element would be ignored. Stories that need to
|
||||
* show the checked appearance set the initial value here.
|
||||
*/
|
||||
function ControlledCheckbox({
|
||||
initial = false,
|
||||
...args
|
||||
}: React.ComponentProps<typeof Checkbox> & { initial?: boolean }) {
|
||||
const [checked, setChecked] = useState(initial)
|
||||
return <Checkbox {...args} checked={checked} onChange={(e) => setChecked(e.target.checked)} />
|
||||
}
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => <ControlledCheckbox {...args} />,
|
||||
}
|
||||
|
||||
export const Uncontrolled: Story = {
|
||||
render: (args) => <Checkbox {...args} defaultChecked />,
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: (args) => (
|
||||
<div className="flex flex-col gap-4">
|
||||
{(['sm', 'md', 'lg'] as const).map((size) => (
|
||||
<ControlledCheckbox key={size} {...args} size={size} label={`Size ${size}`} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Themes: Story = {
|
||||
render: () => (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{(['primary', 'secondary', 'success', 'danger', 'warning', 'info'] as const).map((theme) => (
|
||||
<ControlledCheckbox key={theme} theme={theme} label={theme} initial />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithTooltip: Story = {
|
||||
args: { tooltip: 'Recipients can be configured per entity in Settings → Notifications.' },
|
||||
render: (args) => <ControlledCheckbox {...args} />,
|
||||
}
|
||||
|
||||
export const WithError: Story = {
|
||||
args: { error: 'You must acknowledge the policy before continuing.' },
|
||||
render: (args) => <ControlledCheckbox {...args} />,
|
||||
}
|
||||
|
||||
/** Error accepts an object too, matching a form-library error shape. */
|
||||
export const ErrorAsObject: Story = {
|
||||
render: () => (
|
||||
<Checkbox
|
||||
label="Acknowledge policy"
|
||||
error={{ message: 'This field is required' }}
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const Disabled: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Checkbox label="Unchecked and disabled" disabled />
|
||||
<Checkbox label="Checked and disabled" defaultChecked disabled />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** No label — a bare control for use inside a table row or toolbar. */
|
||||
export const WithoutLabel: Story = {
|
||||
render: () => <ControlledCheckbox label="" />
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { forwardRef, type InputHTMLAttributes } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CHECKBOX_SIZES, CHECKBOX_THEMES, type CheckboxSize, type CheckboxTheme } from './checkbox.tokens'
|
||||
|
||||
/**
|
||||
* Checkbox with an optional label, error message and help tooltip.
|
||||
*
|
||||
* Ported from the original `Checkbox` component.
|
||||
*
|
||||
* The checked colour uses the native `accent-*` property, so the browser paints
|
||||
* it — that means `theme` follows the CSS custom properties, not a hard-coded hex.
|
||||
*
|
||||
* The `register` / `validation` props are React Hook Form plumbing and are not
|
||||
* part of a design-system component; they are left out here. Pass `name`,
|
||||
* `checked` and `onChange` directly.
|
||||
*/
|
||||
|
||||
// `size` and `type` are omitted from the DOM props: `InputHTMLAttributes` declares
|
||||
// `size` as a number, which would collide with the visual-size token below.
|
||||
export type CheckboxProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'size'> & {
|
||||
label?: string
|
||||
size?: CheckboxSize
|
||||
theme?: CheckboxTheme
|
||||
/** Error text, or an object carrying a `message`. */
|
||||
error?: string | { message?: string }
|
||||
tooltip?: string
|
||||
tooltipIcon?: LucideIcon
|
||||
helpText?: string
|
||||
}
|
||||
|
||||
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Checkbox(
|
||||
{
|
||||
name,
|
||||
label,
|
||||
size = 'md',
|
||||
disabled = false,
|
||||
theme = 'primary',
|
||||
error,
|
||||
className,
|
||||
checked,
|
||||
onChange,
|
||||
tooltip,
|
||||
tooltipIcon,
|
||||
helpText,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const sizeClass = CHECKBOX_SIZES[size] ?? CHECKBOX_SIZES.md
|
||||
const themeClass = CHECKBOX_THEMES[theme] ?? CHECKBOX_THEMES.primary
|
||||
const errorMessage = typeof error === 'string' ? error : error?.message
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col items-start space-y-1', className)}>
|
||||
<label
|
||||
htmlFor={name ? `checkbox-${name}` : undefined}
|
||||
className={cn(
|
||||
'inline-flex items-center space-x-2',
|
||||
disabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
id={name ? `checkbox-${name}` : undefined}
|
||||
name={name}
|
||||
type="checkbox"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'peer rounded border-gray-300',
|
||||
'focus:ring-0 focus:ring-offset-0',
|
||||
themeClass,
|
||||
sizeClass,
|
||||
)}
|
||||
checked={checked}
|
||||
onChange={onChange}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
{label && (
|
||||
<div className="flex items-center gap-1.5 ml-2">
|
||||
<span className="text-sm text-slate-600 select-none">{label}</span>
|
||||
{(tooltip || helpText) && (
|
||||
<span className="inline-flex" onClick={(e) => e.preventDefault()}>
|
||||
<Tooltip
|
||||
content={tooltip ?? helpText ?? ''}
|
||||
size="sm"
|
||||
position="top"
|
||||
icon={tooltipIcon}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</label>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="text-sm text-red-500" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Checkbox
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useState } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Mail, Lock, User, Search } from 'lucide-react'
|
||||
import { FeaturedInput } from './FeaturedInput'
|
||||
|
||||
const meta: Meta<typeof FeaturedInput> = {
|
||||
title: 'Forms/FeaturedInput',
|
||||
component: FeaturedInput,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Input with an animated floating label, a built-in password show/hide toggle, and number-input hardening (blocks `e`/`+`/`-` and blurs on wheel). The floated label gets extra top padding here — the source omits it, which renders the text underneath the label.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
|
||||
variant: { control: 'select', options: ['outlined', 'underlined'] },
|
||||
type: { control: 'select', options: ['text', 'email', 'password', 'number', 'tel'] },
|
||||
shrink: { control: 'boolean' },
|
||||
required: { control: 'boolean' },
|
||||
disabled: { control: 'boolean' },
|
||||
showPasswordToggle: { control: 'boolean' },
|
||||
roundedFull: { control: 'boolean' },
|
||||
dashedBorder: { control: 'boolean' },
|
||||
label: { control: 'text' },
|
||||
placeholder: { control: 'text' },
|
||||
error: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
label: 'Full name',
|
||||
placeholder: 'Jane Doe',
|
||||
type: 'text',
|
||||
size: 'md',
|
||||
theme: 'primary',
|
||||
variant: 'outlined',
|
||||
shrink: false,
|
||||
required: false,
|
||||
disabled: false,
|
||||
showPasswordToggle: true,
|
||||
roundedFull: false,
|
||||
dashedBorder: false,
|
||||
error: '',
|
||||
},
|
||||
}
|
||||
|
||||
export default meta
|
||||
|
||||
function ControlledFeatured({
|
||||
initial = '',
|
||||
...args
|
||||
}: React.ComponentProps<typeof FeaturedInput> & { initial?: string }) {
|
||||
const [value, setValue] = useState(initial)
|
||||
return (
|
||||
<FeaturedInput {...args} value={value} onChange={(e) => setValue(e.target.value)} />
|
||||
)
|
||||
}
|
||||
|
||||
export const FeaturedPlayground: StoryObj<typeof FeaturedInput> = {
|
||||
render: (args) => (
|
||||
<div className="max-w-md">
|
||||
<ControlledFeatured {...args} />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const FloatingStates: StoryObj<typeof FeaturedInput> = {
|
||||
name: 'Floating states',
|
||||
render: () => (
|
||||
<div className="flex max-w-md flex-col gap-8 pb-4">
|
||||
<div>
|
||||
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Resting (empty)</p>
|
||||
<ControlledFeatured label="Full name" placeholder="Jane Doe" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Floated (has value)</p>
|
||||
<ControlledFeatured label="Full name" initial="Jane Doe" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Forced (shrink)</p>
|
||||
<ControlledFeatured label="Full name" shrink placeholder="Jane Doe" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Error</p>
|
||||
<ControlledFeatured label="Full name" error="This field is required." />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const PasswordWithToggle: StoryObj<typeof FeaturedInput> = {
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<ControlledFeatured type="password" label="SMTP password" placeholder="••••••••" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const PasswordToggleDisabled: StoryObj<typeof FeaturedInput> = {
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<ControlledFeatured
|
||||
type="password"
|
||||
label="Locked field"
|
||||
showPasswordToggle={false}
|
||||
initial="stored-secret"
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithLucideIcon: StoryObj<typeof FeaturedInput> = {
|
||||
render: () => (
|
||||
<div className="flex max-w-md flex-col gap-6">
|
||||
<ControlledFeatured label="Email" icon={Mail} placeholder="[email protected]" />
|
||||
<ControlledFeatured label="Username" icon={User} iconPosition="right" placeholder="jane" />
|
||||
<ControlledFeatured label="Search" icon={Search} placeholder="Search employees" />
|
||||
<ControlledFeatured label="API key" icon={Lock} type="password" placeholder="sk_live_…" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const NumberHardening: StoryObj<typeof FeaturedInput> = {
|
||||
name: 'Number hardening',
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<ControlledFeatured
|
||||
type="number"
|
||||
label="Annual CTC"
|
||||
placeholder="1200000"
|
||||
helpText="Blocks e, +, - and wheel scrolling."
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const FeaturedThemes: StoryObj<typeof FeaturedInput> = {
|
||||
name: 'Themes',
|
||||
render: () => (
|
||||
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
|
||||
{(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
|
||||
<ControlledFeatured key={theme} theme={theme} label={theme} initial="Filled" />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const FeaturedVariants: StoryObj<typeof FeaturedInput> = {
|
||||
name: 'Variants',
|
||||
render: () => (
|
||||
<div className="flex max-w-lg flex-col gap-8 pb-4">
|
||||
<ControlledFeatured variant="outlined" label="Outlined" initial="Value" />
|
||||
<ControlledFeatured variant="underlined" label="Underlined" initial="Value" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const FeaturedDisabled: StoryObj<typeof FeaturedInput> = {
|
||||
name: 'Disabled',
|
||||
render: () => (
|
||||
<div className="flex max-w-md flex-col gap-6">
|
||||
<ControlledFeatured label="Locked" initial="Cannot edit" disabled />
|
||||
<ControlledFeatured label="Locked password" type="password" initial="secret" disabled />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
import {
|
||||
forwardRef,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ChangeEvent,
|
||||
type FocusEvent,
|
||||
type InputHTMLAttributes,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
type WheelEvent,
|
||||
} from 'react'
|
||||
import { Eye, EyeOff, type LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { omit } from '@/lib/omit'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import {
|
||||
FLOATING_CONTENT_PADDING,
|
||||
FLOATING_LABEL_SIZES,
|
||||
ICON_SIZES,
|
||||
INPUT_HOVER_THEMES,
|
||||
INPUT_SIZES,
|
||||
INPUT_THEMES,
|
||||
INPUT_VARIANTS,
|
||||
LABEL_COLORS,
|
||||
LABEL_SIZES,
|
||||
type InputSize,
|
||||
type InputTheme,
|
||||
type InputVariant,
|
||||
} from './input.tokens'
|
||||
|
||||
/**
|
||||
* Input with an animated floating label.
|
||||
*
|
||||
* Ported from the original `Input/FeaturedInput` component.
|
||||
*
|
||||
* Upstream fixes kept:
|
||||
* - a `password` field gets a built-in show/hide toggle (IP-4091: dots with no
|
||||
* way to check what was typed);
|
||||
* - `type="number"` blocks `e`/`E`/`+`/`-` and blurs on wheel scroll, so the
|
||||
* value cannot change under the cursor.
|
||||
*
|
||||
* Fixes added here:
|
||||
* - the floated label needs top padding on the field, or the text renders
|
||||
* underneath it (see `FLOATING_CONTENT_PADDING`);
|
||||
* - a `LucideIcon` slot replaces the Remix-icon class name, which needs a font
|
||||
* this showcase does not load.
|
||||
*/
|
||||
|
||||
export type FeaturedInputProps = Omit<
|
||||
InputHTMLAttributes<HTMLInputElement>,
|
||||
'size' | 'value' | 'defaultValue'
|
||||
> & {
|
||||
label?: string
|
||||
value?: string
|
||||
size?: InputSize
|
||||
theme?: InputTheme
|
||||
variant?: InputVariant
|
||||
name?: string
|
||||
onChange?: (e: ChangeEvent<HTMLInputElement>) => void
|
||||
onBlur?: (e: FocusEvent<HTMLInputElement>) => void
|
||||
onKeyDown?: (e: KeyboardEvent<HTMLInputElement>) => void
|
||||
/** Keep the label floated even when the field is empty and unfocused. */
|
||||
shrink?: boolean
|
||||
roundedFull?: boolean
|
||||
dashedBorder?: boolean
|
||||
error?: string | { message?: string }
|
||||
/** Lucide icon rendered inside the field. */
|
||||
icon?: LucideIcon
|
||||
iconPosition?: 'left' | 'right'
|
||||
/** Adds a show/hide toggle when `type` is `password`. */
|
||||
showPasswordToggle?: boolean
|
||||
floatinglabelClass?: string
|
||||
tooltip?: string
|
||||
tooltipIcon?: LucideIcon
|
||||
helpText?: string
|
||||
isLoading?: boolean
|
||||
/** Rendered inside the field, before the password toggle. */
|
||||
trailing?: ReactNode
|
||||
}
|
||||
|
||||
export const FeaturedInput = forwardRef<HTMLInputElement, FeaturedInputProps>(
|
||||
function FeaturedInput(
|
||||
{
|
||||
type = 'text',
|
||||
label = '',
|
||||
disabled = false,
|
||||
required = false,
|
||||
icon: Icon,
|
||||
iconPosition = 'left',
|
||||
className = '',
|
||||
roundedFull = false,
|
||||
dashedBorder = false,
|
||||
size = 'md',
|
||||
variant = 'outlined',
|
||||
onKeyDown,
|
||||
onChange,
|
||||
onBlur,
|
||||
onFocus,
|
||||
theme = 'primary',
|
||||
name,
|
||||
error,
|
||||
value,
|
||||
floatinglabelClass,
|
||||
shrink = false,
|
||||
placeholder,
|
||||
showPasswordToggle = true,
|
||||
tooltip,
|
||||
tooltipIcon,
|
||||
helpText,
|
||||
isLoading = false,
|
||||
trailing,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const [isFocused, setIsFocused] = useState(false)
|
||||
const [isRevealed, setIsRevealed] = useState(false)
|
||||
const wrapperRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const isPassword = type === 'password'
|
||||
const hasRevealToggle = isPassword && showPasswordToggle
|
||||
const resolvedType = isPassword && isRevealed ? 'text' : type
|
||||
|
||||
const htmlProps = omit(props as Record<string, unknown>, [
|
||||
'isDynamic', 'valueKey', 'labelKey', 'endpoint', 'endpointParams', 'isMulti',
|
||||
'searchable', 'infiniteScroll', 'options', 'tooltip', 'tooltipIcon', 'helpText',
|
||||
'isLoading', 'showPasswordToggle', 'register', 'validation', 'floatinglabelClass',
|
||||
])
|
||||
|
||||
const errorMessage = typeof error === 'string' ? error : error?.message
|
||||
|
||||
const handleFocus = () => setIsFocused(true)
|
||||
|
||||
const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
|
||||
onBlur?.(e)
|
||||
// An empty field drops back to the resting label position.
|
||||
if (e.target.value === '' && !shrink) setIsFocused(false)
|
||||
}
|
||||
|
||||
const handleChange = (e: ChangeEvent<HTMLInputElement>) => onChange?.(e)
|
||||
|
||||
// A native number input still accepts e/E/+/-, so scientific notation can be
|
||||
// typed into a field that only takes plain numbers. The caller's handler
|
||||
// still runs.
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (type === 'number' && ['e', 'E', '+', '-'].includes(e.key)) e.preventDefault()
|
||||
onKeyDown?.(e)
|
||||
}
|
||||
|
||||
// Prevent a wheel scroll from silently changing a focused number field.
|
||||
const handleWheel = (e: WheelEvent<HTMLInputElement>) => {
|
||||
if (type === 'number') e.currentTarget.blur()
|
||||
}
|
||||
|
||||
// A field rendered with a value is filled from the first paint, so the label
|
||||
// has to start floated — otherwise it sits on top of the value.
|
||||
useEffect(() => {
|
||||
const el = name ? document.getElementById(name) : null
|
||||
if (el && (el as HTMLInputElement).value) setIsFocused(true)
|
||||
}, [name])
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
|
||||
setTimeout(() => {
|
||||
const el = name ? (document.getElementById(name) as HTMLInputElement | null) : null
|
||||
if (el && !el.value) setIsFocused(false)
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [name])
|
||||
|
||||
const hasValue = value !== undefined && value !== null && value !== ''
|
||||
const shouldFloat = shrink || hasValue || isFocused || Boolean(errorMessage)
|
||||
|
||||
const labelColor = errorMessage
|
||||
? 'text-red-500'
|
||||
: isFocused || hasValue
|
||||
? (floatinglabelClass || LABEL_COLORS[theme] || LABEL_COLORS.primary)
|
||||
: 'text-slate-400'
|
||||
|
||||
const isUnderlined = variant === 'underlined'
|
||||
const variantTokens = INPUT_VARIANTS[variant] ?? INPUT_VARIANTS.outlined
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className={cn('relative w-full', isUnderlined && 'mt-4', className)}>
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex items-center transition-all duration-200',
|
||||
disabled ? 'cursor-not-allowed' : 'cursor-text',
|
||||
INPUT_SIZES[size] ?? INPUT_SIZES.md,
|
||||
variantTokens.wrapper,
|
||||
roundedFull ? 'rounded-full' : 'rounded',
|
||||
dashedBorder ? 'border-dashed' : 'border',
|
||||
isUnderlined ? '' : 'border',
|
||||
(isFocused || shouldFloat) && !errorMessage
|
||||
? cn(
|
||||
'border',
|
||||
INPUT_THEMES[theme] ?? INPUT_THEMES.primary,
|
||||
'focus:border-primary-500',
|
||||
)
|
||||
: 'border border-slate-300',
|
||||
!disabled && !isFocused && !errorMessage && INPUT_HOVER_THEMES[theme],
|
||||
errorMessage && 'border-red-500 focus:border-red-500 focus:ring-red-500',
|
||||
disabled && 'bg-gray-100 opacity-60',
|
||||
// The floated label chip needs the field's own background behind it.
|
||||
shouldFloat && !isUnderlined && FLOATING_CONTENT_PADDING[size],
|
||||
)}
|
||||
>
|
||||
{Icon && iconPosition === 'left' && (
|
||||
<Icon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'absolute left-3 text-gray-500 pointer-events-none',
|
||||
ICON_SIZES[size],
|
||||
shouldFloat && 'top-2 -translate-y-0',
|
||||
)}
|
||||
size={16}
|
||||
/>
|
||||
)}
|
||||
|
||||
<input
|
||||
id={name}
|
||||
ref={ref}
|
||||
name={name}
|
||||
type={resolvedType}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
autoComplete="off"
|
||||
aria-invalid={Boolean(errorMessage)}
|
||||
onFocus={(e) => {
|
||||
handleFocus()
|
||||
onFocus?.(e)
|
||||
}}
|
||||
onBlur={handleBlur}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onWheel={handleWheel}
|
||||
className={cn(
|
||||
'w-full bg-transparent text-gray-800 placeholder:text-transparent',
|
||||
'focus:outline-none transition-all duration-200',
|
||||
'disabled:text-slate-400',
|
||||
Icon && iconPosition === 'left' ? 'pl-9' : 'pl-3',
|
||||
hasRevealToggle || Icon || trailing || isLoading ? 'pr-10' : 'pr-3',
|
||||
)}
|
||||
{...htmlProps}
|
||||
/>
|
||||
|
||||
<div className="absolute right-3 flex items-center gap-1.5">
|
||||
{isLoading && <span className="text-[10px] text-gray-400">…</span>}
|
||||
{trailing}
|
||||
{hasRevealToggle && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsRevealed((v) => !v)}
|
||||
aria-label={isRevealed ? 'Hide password' : 'Show password'}
|
||||
className="text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
{isRevealed ? <EyeOff size={15} /> : <Eye size={15} />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{Icon && iconPosition === 'right' && (
|
||||
<Icon aria-hidden="true" size={16} className="absolute right-8 text-gray-500 pointer-events-none" />
|
||||
)}
|
||||
|
||||
{label && (
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'absolute transition-all duration-200 pointer-events-none',
|
||||
isUnderlined ? 'left-0' : 'left-3',
|
||||
shouldFloat
|
||||
? cn(
|
||||
'-top-2.5 z-10',
|
||||
variantTokens.labelFloating,
|
||||
FLOATING_LABEL_SIZES[size] ?? FLOATING_LABEL_SIZES.md,
|
||||
labelColor,
|
||||
)
|
||||
: cn(
|
||||
'top-1/2 -translate-y-1/2',
|
||||
LABEL_SIZES[size] ?? LABEL_SIZES.md,
|
||||
'text-slate-400',
|
||||
),
|
||||
)}
|
||||
>
|
||||
<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>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="mt-1 text-sm text-red-500" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export default FeaturedInput
|
||||
@@ -0,0 +1,470 @@
|
||||
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
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useState } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Input } from './Input'
|
||||
|
||||
const meta = {
|
||||
title: 'Forms/Input',
|
||||
component: Input,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Plain input with a label above. For a floating label, a built-in password toggle, and a Lucide icon slot, see the **FeaturedInput** story group — both are exported from here.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
|
||||
type: { control: 'select', options: ['text', 'email', 'password', 'number', 'tel', 'url', 'date'] },
|
||||
iconPosition: { control: 'radio', options: ['left', 'right'] },
|
||||
roundedFull: { control: 'boolean' },
|
||||
dashedBorder: { control: 'boolean' },
|
||||
required: { control: 'boolean' },
|
||||
disabled: { control: 'boolean' },
|
||||
label: { control: 'text' },
|
||||
placeholder: { control: 'text' },
|
||||
error: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
label: 'Legal entity name',
|
||||
placeholder: 'Acme Corporation',
|
||||
type: 'text',
|
||||
size: 'md',
|
||||
theme: 'primary',
|
||||
iconPosition: 'left',
|
||||
roundedFull: false,
|
||||
dashedBorder: false,
|
||||
required: false,
|
||||
disabled: false,
|
||||
error: '',
|
||||
},
|
||||
} satisfies Meta<typeof Input>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
function ControlledInput({
|
||||
initial = '',
|
||||
...args
|
||||
}: React.ComponentProps<typeof Input> & { initial?: string }) {
|
||||
const [value, setValue] = useState(initial)
|
||||
return <Input {...args} value={value} onChange={(e) => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => (
|
||||
<div className="max-w-md">
|
||||
<ControlledInput {...args} />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Types: Story = {
|
||||
render: () => (
|
||||
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
|
||||
<Input label="Full name" placeholder="Jane Doe" />
|
||||
<Input label="Email" type="email" placeholder="[email protected]" />
|
||||
<Input label="Phone" type="tel" placeholder="+91 98450 00000" />
|
||||
<Input label="Annual CTC" type="number" placeholder="1200000" />
|
||||
<Input label="Website" type="url" placeholder="https://example.com" />
|
||||
<Input label="Joining date" type="date" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: () => (
|
||||
<div className="flex max-w-md flex-col gap-5">
|
||||
{(['sm', 'md', 'lg'] as const).map((size) => (
|
||||
<ControlledInput key={size} size={size} label={`Size ${size}`} placeholder="Enter a value" />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Themes: Story = {
|
||||
render: () => (
|
||||
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
|
||||
{(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
|
||||
<ControlledInput key={theme} theme={theme} label={theme} placeholder="Focus me" />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithError: Story = {
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<Input
|
||||
label="PAN number"
|
||||
placeholder="ABCDE1234F"
|
||||
error="Enter a valid PAN number."
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Required: Story = {
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<Input label="Entity name" required placeholder="Required field" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Disabled: Story = {
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<Input label="Entity ID" value="ENT-000142" disabled onChange={() => {}} />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const BorderStyles: Story = {
|
||||
render: () => (
|
||||
<div className="grid max-w-xl gap-5 sm:grid-cols-3">
|
||||
<Input label="Default" placeholder="Solid" />
|
||||
<Input label="Dashed" placeholder="Dashed" dashedBorder />
|
||||
<Input label="Pill" placeholder="Rounded" roundedFull />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** Requires the Remix Icon font; the `FeaturedInput` group below uses Lucide instead. */
|
||||
export const WithIconClass: Story = {
|
||||
args: { icon: 'ri-mail-line', placeholder: 'Email' },
|
||||
render: (args) => (
|
||||
<div className="max-w-md">
|
||||
<Input {...args} label="Email" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { forwardRef, type InputHTMLAttributes, type ReactNode } from 'react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { omit } from '@/lib/omit'
|
||||
import {
|
||||
ICON_SIZES,
|
||||
INPUT_SIZES,
|
||||
INPUT_THEMES,
|
||||
LABEL_SIZES,
|
||||
type InputSize,
|
||||
type InputTheme,
|
||||
} from './input.tokens'
|
||||
|
||||
/**
|
||||
* Text input with a label above, optional icon, and error state.
|
||||
*
|
||||
* Ported from the original `Input` component.
|
||||
*
|
||||
* The source sets `opacity-90!` on the field, which dims the user's own typed
|
||||
* text; that is dropped here. `register` / `validation` (React Hook Form) are
|
||||
* not ported either — pass standard DOM props.
|
||||
*
|
||||
* `icon` is a class-name string (the source app uses Remix Icon, e.g.
|
||||
* `"ri-mail-line"`). Loading that font is a project-level choice, so the
|
||||
* showcase's stories use `FeaturedInput`'s Lucide slot instead where an icon is
|
||||
* really needed.
|
||||
*/
|
||||
|
||||
export type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> & {
|
||||
label?: string
|
||||
size?: InputSize
|
||||
theme?: InputTheme
|
||||
/** Icon class name, e.g. `"ri-mail-line"`. Needs the icon font loaded. */
|
||||
icon?: string
|
||||
iconPosition?: 'left' | 'right'
|
||||
roundedFull?: boolean
|
||||
dashedBorder?: boolean
|
||||
error?: string | { message?: string }
|
||||
/** Rendered after the input, inside the field row. */
|
||||
trailing?: ReactNode
|
||||
}
|
||||
|
||||
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
|
||||
{
|
||||
type = 'text',
|
||||
label = '',
|
||||
placeholder = '',
|
||||
disabled = false,
|
||||
required = false,
|
||||
icon,
|
||||
iconPosition = 'left',
|
||||
roundedFull = false,
|
||||
dashedBorder = false,
|
||||
size = 'md',
|
||||
theme = 'primary',
|
||||
className = '',
|
||||
name,
|
||||
error,
|
||||
trailing,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const htmlProps = omit(props as Record<string, unknown>, ['hasMore', 'control', 'allValues', 'shrink'])
|
||||
const errorMessage = typeof error === 'string' ? error : error?.message
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full">
|
||||
{label && (
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn('inline-block text-left w-full text-gray-800', LABEL_SIZES[size] ?? LABEL_SIZES.md)}
|
||||
>
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="relative flex items-center">
|
||||
{icon && iconPosition === 'left' && (
|
||||
<i
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'absolute left-3 top-1/2 text-gray-900 transform -translate-y-1/2 pointer-events-none',
|
||||
ICON_SIZES[size],
|
||||
icon,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<input
|
||||
id={name}
|
||||
ref={ref}
|
||||
type={type}
|
||||
name={name}
|
||||
autoComplete="off"
|
||||
required={required}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
aria-invalid={Boolean(errorMessage)}
|
||||
className={cn(
|
||||
'w-full bg-white text-gray-800 placeholder:text-slate-400 placeholder:font-medium',
|
||||
'focus:outline-none transition duration-150',
|
||||
'disabled:bg-gray-200 disabled:border-slate-300 disabled:text-slate-400 disabled:cursor-not-allowed',
|
||||
// Indent to clear a leading icon.
|
||||
icon ? (iconPosition === 'left' ? 'pl-9' : 'pr-10') : 'pl-3',
|
||||
roundedFull ? 'rounded-full' : 'rounded',
|
||||
dashedBorder ? 'border-dashed' : 'border',
|
||||
'border',
|
||||
INPUT_SIZES[size] ?? INPUT_SIZES.md,
|
||||
// Error wins over the theme's focus colours.
|
||||
errorMessage
|
||||
? 'border-red-500 focus:border-red-500 focus:ring-red-500'
|
||||
: cn('border-slate-300', INPUT_THEMES[theme] ?? INPUT_THEMES.primary),
|
||||
className,
|
||||
)}
|
||||
{...htmlProps}
|
||||
/>
|
||||
|
||||
{icon && iconPosition === 'right' && (
|
||||
<i
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'absolute right-3 top-1/2 text-gray-900 transform -translate-y-1/2 pointer-events-none',
|
||||
ICON_SIZES[size],
|
||||
icon,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{trailing && (
|
||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center">
|
||||
{trailing}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="mt-1 text-sm text-start text-red-500" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Input
|
||||
@@ -0,0 +1,192 @@
|
||||
import { forwardRef, useState, type ChangeEvent, type FocusEvent } from 'react'
|
||||
import { ChevronDown, X } from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { omit } from '@/lib/omit'
|
||||
import { Spinner } from './Spinner'
|
||||
import {
|
||||
LABEL_SIZES,
|
||||
SELECT_SIZES,
|
||||
SELECT_THEME_CLASSES,
|
||||
SELECT_VARIANTS,
|
||||
SELECT_WIDTHS,
|
||||
type SelectSize,
|
||||
type SelectTheme,
|
||||
type SelectVariant,
|
||||
type SelectWidth,
|
||||
} from './select.tokens'
|
||||
|
||||
/**
|
||||
* Select over a native `<select>`.
|
||||
*
|
||||
* Ported from the source app's `Select/components/NativeSelect`, and used by
|
||||
* `Select` when `featured` is false.
|
||||
*
|
||||
* The source writes its themed border as `` `border-${themeColor}-500` ``, which
|
||||
* Tailwind's scanner cannot see — so the focused state had no styling. Here the
|
||||
* classes come from a static map, and `border` / `ring` colour utilities are set
|
||||
* per element so they survive Tailwind's tree.
|
||||
*/
|
||||
|
||||
export type SelectOption = { label: string; value: string; disabled?: boolean }
|
||||
|
||||
export type NativeSelectProps = Omit<
|
||||
React.SelectHTMLAttributes<HTMLSelectElement>,
|
||||
'size' | 'value' | 'onChange'
|
||||
> & {
|
||||
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
|
||||
}
|
||||
|
||||
export const NativeSelect = forwardRef<HTMLSelectElement, NativeSelectProps>(
|
||||
function NativeSelect(
|
||||
{
|
||||
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,
|
||||
className = '',
|
||||
onFocus,
|
||||
onBlur,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const [isFocused, setIsFocused] = useState(false)
|
||||
|
||||
// Strip props that must not reach the DOM node.
|
||||
const htmlProps = omit(props as Record<string, unknown>, [
|
||||
'shrink', 'helpText', 'helperText', 'tooltip', 'tooltipIcon', 'control', 'allValues',
|
||||
'isDynamic', 'valueKey', 'labelKey', 'endpoint', 'endpointParams',
|
||||
'isMulti', 'searchable', 'infiniteScroll', 'hasMore', 'hasMoreKey',
|
||||
'onMenuScroll', 'onSearchChange', 'initialSearch', 'initialSearchTerm',
|
||||
'initialQuery', 'debounceTime', 'actionButton', 'isEditMode', 'isClearable',
|
||||
'themeColor', 'sizeClass', 'variantClass', 'widthClass', 'floatinglabelClass',
|
||||
'renderOption', 'placement', 'scrollToSelected',
|
||||
])
|
||||
|
||||
const themeClasses = SELECT_THEME_CLASSES[theme] ?? SELECT_THEME_CLASSES.primary
|
||||
const errorMessage = typeof error === 'string' ? error : error?.message
|
||||
|
||||
const handleChange = (e: ChangeEvent<HTMLSelectElement>) => onChange?.(e.target.value)
|
||||
|
||||
const handleClear = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
onChange?.('')
|
||||
}
|
||||
|
||||
// Deliberately explicit rather than `isClearable && value && ...`: a numeric 0
|
||||
// is a legitimate selection, and `&&` on a falsy number yields the number
|
||||
// itself, which React renders as stray text in the icon slot (IP-3617).
|
||||
const showClear =
|
||||
isClearable && !disabled && value !== '' && value !== null && value !== undefined
|
||||
|
||||
return (
|
||||
<div className={cn('relative w-full', SELECT_WIDTHS[width] ?? SELECT_WIDTHS.full, className)}>
|
||||
{label && (
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn('block text-gray-800 font-medium mb-1', LABEL_SIZES[size] ?? LABEL_SIZES.md)}
|
||||
>
|
||||
{label}
|
||||
{required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="relative">
|
||||
<select
|
||||
id={name}
|
||||
name={name}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
aria-invalid={Boolean(errorMessage)}
|
||||
onChange={handleChange}
|
||||
onFocus={(e: FocusEvent<HTMLSelectElement>) => {
|
||||
setIsFocused(true)
|
||||
onFocus?.(e)
|
||||
}}
|
||||
onBlur={(e: FocusEvent<HTMLSelectElement>) => {
|
||||
setIsFocused(false)
|
||||
onBlur?.(e)
|
||||
}}
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'appearance-none block w-full pl-3 pr-10 bg-white text-gray-700 font-medium',
|
||||
'focus:outline-none transition duration-150 ease-in-out',
|
||||
SELECT_SIZES[size] ?? SELECT_SIZES.md,
|
||||
SELECT_VARIANTS[variant] ?? SELECT_VARIANTS.outlined,
|
||||
// Border/ring colour utilities are written per element: a `border-red-500`
|
||||
// class would otherwise be stripped by Tailwind's tree as redundant.
|
||||
isFocused
|
||||
? ['border', themeClasses.focus]
|
||||
: 'border border-slate-300',
|
||||
isFocused && 'ring-1',
|
||||
disabled && 'bg-gray-200 cursor-not-allowed opacity-70',
|
||||
errorMessage && 'border-red-500 ring-red-500 focus:border-red-500 focus:ring-red-500',
|
||||
variant !== 'underlined' && 'rounded',
|
||||
)}
|
||||
{...htmlProps}
|
||||
>
|
||||
<option value="" disabled hidden>
|
||||
{placeholder}
|
||||
</option>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value} disabled={opt.disabled}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<div className="absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
|
||||
{showClear && (
|
||||
<X
|
||||
className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-pointer z-20 mr-1"
|
||||
onClick={handleClear}
|
||||
/>
|
||||
)}
|
||||
<div className="pointer-events-none flex items-center">
|
||||
{isLoading ? (
|
||||
<Spinner size="xs" />
|
||||
) : (
|
||||
<ChevronDown className={cn('h-4 w-4', !isFocused && 'opacity-50')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="mt-1 text-sm text-red-500" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export default NativeSelect
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useState } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Radio } from './Radio'
|
||||
|
||||
const meta = {
|
||||
title: 'Forms/Radio',
|
||||
component: Radio,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Radio group. The native input is visually hidden and the ring + dot are drawn in CSS, so the selected state follows the palette. A real radio input is still used underneath, so keyboard and form semantics are intact.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
theme: {
|
||||
control: 'select',
|
||||
options: ['blue', 'green', 'red', 'yellow', 'teal', 'purple', 'amber', 'gray'],
|
||||
},
|
||||
label: { control: 'text' },
|
||||
required: { control: 'boolean' },
|
||||
disabled: { control: 'boolean' },
|
||||
value: { control: 'text' },
|
||||
helpText: { control: 'text' },
|
||||
error: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
name: 'payroll_frequency',
|
||||
options: ['Monthly', 'Fortnightly', 'Weekly'],
|
||||
size: 'md',
|
||||
theme: 'blue',
|
||||
label: 'Payroll frequency',
|
||||
required: false,
|
||||
disabled: false,
|
||||
value: 'Monthly',
|
||||
helpText: '',
|
||||
error: '',
|
||||
},
|
||||
} satisfies Meta<typeof Radio>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
/**
|
||||
* Wraps Radio with local state so the group is interactive.
|
||||
*
|
||||
* `initial` selects the starting option. The themes grid needs one selected to
|
||||
* show the ring and dot in each colour, so it passes a value rather than ''.
|
||||
*/
|
||||
function ControlledRadio({
|
||||
initial = '',
|
||||
...args
|
||||
}: React.ComponentProps<typeof Radio> & { initial?: string }) {
|
||||
const [value, setValue] = useState(args.value ?? initial)
|
||||
return <Radio {...args} value={value} onChange={setValue} />
|
||||
}
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => <ControlledRadio {...args} />,
|
||||
}
|
||||
|
||||
/** No `value` or `onChange` — the component tracks its own selection. */
|
||||
export const Uncontrolled: Story = {
|
||||
render: (args) => <Radio {...args} />,
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: (args) => (
|
||||
<div className="flex flex-col gap-6">
|
||||
{(['sm', 'md', 'lg'] as const).map((size) => (
|
||||
<ControlledRadio key={size} {...args} size={size} label={`Size ${size}`} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Themes: Story = {
|
||||
render: () => (
|
||||
<div className="grid gap-5 sm:grid-cols-2">
|
||||
{(['blue', 'green', 'red', 'yellow', 'teal', 'purple', 'amber', 'gray'] as const).map((theme) => (
|
||||
<ControlledRadio
|
||||
key={theme}
|
||||
name={`theme-${theme}`}
|
||||
theme={theme}
|
||||
options={['Option A', 'Option B']}
|
||||
label={theme}
|
||||
initial="Option A"
|
||||
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** Options may carry their own disabled state. */
|
||||
export const DisabledOptions: Story = {
|
||||
render: () => (
|
||||
<ControlledRadio
|
||||
name="leave_type"
|
||||
label="Leave type"
|
||||
options={[
|
||||
{ label: 'Casual leave', value: 'casual' },
|
||||
{ label: 'Sick leave', value: 'sick' },
|
||||
{ label: 'Parental leave (unavailable)', value: 'parental', disabled: true },
|
||||
]}
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const RequiredWithError: Story = {
|
||||
render: () => (
|
||||
<ControlledRadio
|
||||
name="employment_type"
|
||||
label="Employment type"
|
||||
required
|
||||
options={['Full-time', 'Part-time', 'Contract']}
|
||||
error="Select an employment type to continue."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithTooltip: Story = {
|
||||
render: () => (
|
||||
<ControlledRadio
|
||||
name="pay_cycle"
|
||||
label="Pay cycle"
|
||||
options={['Monthly', 'Fortnightly', 'Weekly']}
|
||||
helpText="Changing this affects every future payroll run in the entity."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const Horizontal: Story = {
|
||||
render: () => (
|
||||
<ControlledRadio
|
||||
name="invoice_type"
|
||||
options={['Standard', 'Proforma', 'Credit note']}
|
||||
/>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useEffect, useState, type HTMLAttributes, type ReactNode } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { RADIO_COLORS, RADIO_SIZES, type RadioSize, type RadioTheme } from './radio.tokens'
|
||||
|
||||
/**
|
||||
* Radio group with a generated ring + dot indicator.
|
||||
*
|
||||
* Ported from the original `Radio` component.
|
||||
*
|
||||
* The native input is visually hidden; the ring and dot are drawn in CSS, which
|
||||
* is what lets the selected state follow palette tokens. A real `radio` input is
|
||||
* still used underneath, so keyboard and form semantics are intact.
|
||||
*
|
||||
* `register` / `validation` (React Hook Form) are intentionally not ported —
|
||||
* pass `value` and `onChange` directly.
|
||||
*/
|
||||
|
||||
export type RadioOption = string | { label: ReactNode; value: string; disabled?: boolean }
|
||||
|
||||
export type RadioProps = Omit<HTMLAttributes<HTMLDivElement>, 'onChange' | 'defaultValue'> & {
|
||||
name?: string
|
||||
options?: RadioOption[]
|
||||
size?: RadioSize
|
||||
theme?: RadioTheme
|
||||
/** Disables every option in the group. */
|
||||
disabled?: boolean
|
||||
label?: ReactNode
|
||||
/** Appends the mandatory asterisk to the group label. */
|
||||
required?: boolean
|
||||
/** Controlled selection. */
|
||||
value?: string
|
||||
onChange?: (value: string) => void
|
||||
error?: string | { message?: string }
|
||||
/** Icon class name shown in place of the dot when selected, e.g. `"ri-check"`. */
|
||||
icon?: string
|
||||
tooltip?: string
|
||||
tooltipIcon?: LucideIcon
|
||||
helpText?: string
|
||||
}
|
||||
|
||||
export const Radio = function Radio({
|
||||
name = '',
|
||||
options = [],
|
||||
size = 'md',
|
||||
theme = 'blue',
|
||||
disabled = false,
|
||||
icon,
|
||||
error,
|
||||
label,
|
||||
required = false,
|
||||
helpText,
|
||||
tooltip,
|
||||
tooltipIcon,
|
||||
value,
|
||||
onChange,
|
||||
className = '',
|
||||
...props
|
||||
}: RadioProps) {
|
||||
const [localValue, setLocalValue] = useState(value ?? '')
|
||||
|
||||
useEffect(() => {
|
||||
if (value !== undefined) setLocalValue(value)
|
||||
}, [value])
|
||||
|
||||
const sizeData = RADIO_SIZES[size] ?? RADIO_SIZES.md
|
||||
const themeData = RADIO_COLORS[theme] ?? RADIO_COLORS.blue
|
||||
|
||||
const handleChange = (next: string) => {
|
||||
setLocalValue(next)
|
||||
onChange?.(next)
|
||||
}
|
||||
|
||||
const errorMessage =
|
||||
error == null ? null : typeof error === 'string' ? error : (error.message ?? 'This field is required')
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-2', className)} role="radiogroup" {...props}>
|
||||
{label && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={cn('font-medium', sizeData.label)}>
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</span>
|
||||
{(tooltip || helpText) && (
|
||||
<Tooltip
|
||||
content={tooltip ?? helpText ?? ''}
|
||||
size="sm"
|
||||
position="top"
|
||||
icon={tooltipIcon}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{options.map((opt, index) => {
|
||||
const option = typeof opt === 'string' ? { label: opt, value: opt } : opt
|
||||
const isChecked = localValue === option.value
|
||||
const isDisabled = disabled || Boolean(option.disabled)
|
||||
|
||||
return (
|
||||
<label
|
||||
key={option.value || index}
|
||||
htmlFor={`${name}-${option.value}`}
|
||||
className={cn(
|
||||
'inline-flex items-center space-x-2 mr-4',
|
||||
isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
id={`${name}-${option.value}`}
|
||||
name={name}
|
||||
value={option.value}
|
||||
className="peer sr-only"
|
||||
checked={isChecked}
|
||||
onChange={() => handleChange(option.value)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
|
||||
{/* Decorative ring + dot; the input above carries the semantics. */}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
'relative flex items-center justify-center rounded-full border transition-all duration-200',
|
||||
sizeData.container,
|
||||
isChecked ? cn(themeData.border, 'border-2') : 'border-gray-300',
|
||||
!isDisabled && 'hover:border-gray-400',
|
||||
)}
|
||||
>
|
||||
{isChecked &&
|
||||
(icon ? (
|
||||
<i className={cn(icon, themeData.text)} />
|
||||
) : (
|
||||
<span className={cn('absolute rounded-full', sizeData.dot, themeData.bg)} />
|
||||
))}
|
||||
</span>
|
||||
|
||||
<span className={cn('text-gray-700', sizeData.label)}>{option.label}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="mt-1 text-sm text-red-500" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Radio
|
||||
@@ -0,0 +1,240 @@
|
||||
import { useState } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Select, type SelectOption } from './Select'
|
||||
|
||||
const COUNTRIES: SelectOption[] = [
|
||||
{ label: 'India', value: 'in' },
|
||||
{ label: 'United Kingdom', value: 'gb' },
|
||||
{ label: 'United States', value: 'us' },
|
||||
{ label: 'Germany', value: 'de' },
|
||||
{ label: 'Singapore', value: 'sg' },
|
||||
{ label: 'United Arab Emirates', value: 'ae' },
|
||||
{ label: 'Australia', value: 'au' },
|
||||
{ label: 'Canada', value: 'ca' },
|
||||
]
|
||||
|
||||
const DEPARTMENTS: SelectOption[] = [
|
||||
{ label: 'Engineering', value: 'eng' },
|
||||
{ label: 'Finance', value: 'fin' },
|
||||
{ label: 'People & Culture', value: 'hr' },
|
||||
{ label: 'Operations', value: 'ops' },
|
||||
{ label: 'Sales', value: 'sales' },
|
||||
]
|
||||
|
||||
const meta = {
|
||||
title: 'Forms/Select',
|
||||
component: Select,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Dispatches to a native `<select>` by default, or a searchable portalled dropdown with a floating label when `featured` is set. The source built its themed classes as template strings, which Tailwind cannot scan; here they come from a static map so every theme actually renders.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
|
||||
variant: { control: 'select', options: ['outlined', 'filled', 'standard', 'underlined'] },
|
||||
width: { control: 'select', options: ['full', 'half', 'small', 'xs', 'large'] },
|
||||
featured: { control: 'boolean' },
|
||||
label: { control: 'text' },
|
||||
placeholder: { control: 'text' },
|
||||
required: { control: 'boolean' },
|
||||
disabled: { control: 'boolean' },
|
||||
isLoading: { control: 'boolean' },
|
||||
isClearable: { control: 'boolean' },
|
||||
searchable: { control: 'boolean' },
|
||||
value: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
options: COUNTRIES,
|
||||
value: '',
|
||||
label: 'Country of registration',
|
||||
placeholder: 'Select a country',
|
||||
size: 'md',
|
||||
theme: 'primary',
|
||||
variant: 'outlined',
|
||||
width: 'full',
|
||||
featured: false,
|
||||
required: false,
|
||||
disabled: false,
|
||||
isLoading: false,
|
||||
isClearable: true,
|
||||
searchable: true,
|
||||
},
|
||||
} satisfies Meta<typeof Select>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
/**
|
||||
* Select is a controlled component: it reports a value, it does not hold one.
|
||||
*/
|
||||
function ControlledSelect({
|
||||
initial = '',
|
||||
...args
|
||||
}: React.ComponentProps<typeof Select> & { initial?: string }) {
|
||||
const [value, setValue] = useState(initial)
|
||||
return (
|
||||
<div className="max-w-md">
|
||||
<Select {...args} value={value} onChange={setValue} />
|
||||
<p className="mt-2 text-xs text-gray-500">value = {JSON.stringify(value)}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => <ControlledSelect {...args} />,
|
||||
}
|
||||
|
||||
export const Featured: Story = {
|
||||
args: { featured: true },
|
||||
render: (args) => <ControlledSelect {...args} />,
|
||||
}
|
||||
|
||||
export const FeaturedWithValue: Story = {
|
||||
args: { featured: true },
|
||||
render: (args) => <ControlledSelect {...args} initial="in" />,
|
||||
}
|
||||
|
||||
export const FeaturedRequired: Story = {
|
||||
args: { featured: true, required: true },
|
||||
render: (args) => <ControlledSelect {...args} />,
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: () => (
|
||||
<div className="flex max-w-md flex-col gap-5">
|
||||
{(['sm', 'md', 'lg'] as const).map((size) => (
|
||||
<ControlledSelect key={size} size={size} label={`Size ${size}`} options={DEPARTMENTS} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/**
|
||||
* The themed states are the point of this story: the source could not render
|
||||
* them because its classes were built dynamically.
|
||||
*/
|
||||
export const Themes: Story = {
|
||||
render: () => (
|
||||
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
|
||||
{(['primary', 'secondary', 'success', 'warning', 'info', 'error'] as const).map((theme) => (
|
||||
<ControlledSelect
|
||||
key={theme}
|
||||
featured
|
||||
theme={theme}
|
||||
label={theme}
|
||||
options={DEPARTMENTS}
|
||||
initial="eng"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Variants: Story = {
|
||||
render: () => (
|
||||
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
|
||||
{(['outlined', 'filled', 'standard', 'underlined'] as const).map((variant) => (
|
||||
<ControlledSelect
|
||||
key={variant}
|
||||
featured
|
||||
variant={variant}
|
||||
label={variant}
|
||||
options={DEPARTMENTS}
|
||||
initial="fin"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Widths: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-end gap-4">
|
||||
{(['xs', 'small', 'large', 'half'] as const).map((width) => (
|
||||
<ControlledSelect key={width} width={width} label={width} options={DEPARTMENTS} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Loading: Story = {
|
||||
args: { isLoading: true },
|
||||
render: (args) => <ControlledSelect {...args} />,
|
||||
}
|
||||
|
||||
export const Disabled: Story = {
|
||||
args: { disabled: true, value: 'in' },
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<Select label="Country" options={COUNTRIES} value="in" disabled onChange={() => {}} />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithError: Story = {
|
||||
args: { error: 'Select the country where the entity is registered.' },
|
||||
render: (args) => <ControlledSelect {...args} />,
|
||||
}
|
||||
|
||||
/** An empty filter list, where the "all" option has an empty value. */
|
||||
export const AllOptionsFilter: Story = {
|
||||
render: () => (
|
||||
<ControlledSelect
|
||||
featured
|
||||
searchable
|
||||
label="Department filter"
|
||||
options={[{ label: 'All departments', value: '' }, ...DEPARTMENTS]}
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithActionButton: Story = {
|
||||
render: () => (
|
||||
<div className="max-w-md">
|
||||
<Select
|
||||
featured
|
||||
label="Department"
|
||||
options={DEPARTMENTS}
|
||||
actionButton={{ label: '+ Create department', onClick: () => {} }}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** Renders each option with a custom node. */
|
||||
export const CustomOptionRenderer: Story = {
|
||||
render: () => (
|
||||
<ControlledSelect
|
||||
featured
|
||||
label="Department"
|
||||
options={DEPARTMENTS}
|
||||
renderOption={(opt) => (
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-primary-500" />
|
||||
{opt.label}
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithTooltip: Story = {
|
||||
render: () => (
|
||||
<ControlledSelect
|
||||
featured
|
||||
label="Country of registration"
|
||||
options={COUNTRIES}
|
||||
helpText="Determines the statutory rules applied to payroll in this entity."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const NonSearchable: Story = {
|
||||
args: { featured: true, searchable: false },
|
||||
render: (args) => <ControlledSelect {...args} />,
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { forwardRef } from 'react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { NativeSelect, type SelectOption } from './NativeSelect'
|
||||
import { FeaturedSelect } from './FeaturedSelect'
|
||||
import type { DropdownPlacement } from '@/lib/useDropdownPosition'
|
||||
import type {
|
||||
SelectSize,
|
||||
SelectTheme,
|
||||
SelectVariant,
|
||||
SelectWidth,
|
||||
} from './select.tokens'
|
||||
|
||||
/**
|
||||
* Select dispatcher: a native `<select>` by default, or the custom searchable
|
||||
* dropdown when `featured` is set.
|
||||
*
|
||||
* Ported from the original `Select` component.
|
||||
*
|
||||
* Form-library props (`register`, `validation`) are not ported — pass `value`
|
||||
* and `onChange` directly.
|
||||
*/
|
||||
|
||||
export type SelectProps = {
|
||||
options?: SelectOption[]
|
||||
value?: string
|
||||
onChange?: (value: string) => void
|
||||
/** Renders the custom dropdown with a floating label instead of a native select. */
|
||||
featured?: boolean
|
||||
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
|
||||
className?: string
|
||||
floatinglabelClass?: string
|
||||
shrink?: boolean
|
||||
searchable?: boolean
|
||||
onSearchChange?: (term: string) => void
|
||||
scrollToSelected?: boolean
|
||||
placement?: DropdownPlacement
|
||||
initialSearchTerm?: string
|
||||
actionButton?: { label: string; onClick: () => void; icon?: React.ReactNode }
|
||||
renderOption?: (opt: SelectOption) => React.ReactNode
|
||||
tooltip?: string
|
||||
tooltipIcon?: React.ComponentProps<typeof import('./Tooltip').Tooltip>['icon']
|
||||
helpText?: string
|
||||
}
|
||||
|
||||
export const Select = forwardRef<HTMLDivElement, SelectProps>(function Select({
|
||||
featured = false,
|
||||
className = '',
|
||||
...props
|
||||
}, ref) {
|
||||
if (featured) {
|
||||
return <FeaturedSelect ref={ref} {...props} className={className} />
|
||||
}
|
||||
|
||||
return (
|
||||
<NativeSelect
|
||||
ref={ref as React.Ref<HTMLSelectElement>}
|
||||
{...props}
|
||||
className={cn(className)}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export type { SelectOption }
|
||||
export default Select
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Spinner } from './Spinner'
|
||||
|
||||
const meta = {
|
||||
title: 'Feedback/Spinner',
|
||||
component: Spinner,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Loading indicator. The `primary` variant reads from the palette tokens, so it re-colours with the toolbar switcher.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['xs', 'sm', 'md', 'lg', 'xl'] },
|
||||
variant: {
|
||||
control: 'select',
|
||||
options: ['primary', 'secondary', 'white', 'success', 'danger', 'warning'],
|
||||
},
|
||||
label: { control: 'text', description: 'Accessible label announced to screen readers.' },
|
||||
},
|
||||
args: { size: 'md', variant: 'primary', label: 'Loading' },
|
||||
} satisfies Meta<typeof Spinner>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
export const Playground: Story = {}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-6">
|
||||
{(['xs', 'sm', 'md', 'lg', 'xl'] as const).map((size) => (
|
||||
<div key={size} className="flex flex-col items-center gap-2">
|
||||
<Spinner size={size} />
|
||||
<code className="text-[10px] text-gray-500">{size}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Variants: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-6">
|
||||
{(['primary', 'secondary', 'success', 'danger', 'warning'] as const).map((variant) => (
|
||||
<div key={variant} className="flex flex-col items-center gap-2">
|
||||
<Spinner variant={variant} />
|
||||
<code className="text-[10px] text-gray-500">{variant}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** The `white` variant is only legible on a dark surface. */
|
||||
export const OnDarkSurface: Story = {
|
||||
render: () => (
|
||||
<div className="flex items-center gap-6 rounded-xl bg-zink-800 p-8">
|
||||
<Spinner variant="white" size="lg" />
|
||||
<Spinner variant="white" size="md" />
|
||||
<Spinner variant="white" size="sm" />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { forwardRef, type HTMLAttributes } from 'react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { SPINNER_SIZES, SPINNER_VARIANTS, type SpinnerSize, type SpinnerVariant } from './spinner.tokens'
|
||||
|
||||
/**
|
||||
* Loading spinner.
|
||||
*
|
||||
* Ported from the original `Spinner` component.
|
||||
* The colour token is a palette-driven `primary-500`, so it re-themes with the
|
||||
* Storybook palette switcher.
|
||||
*/
|
||||
|
||||
export type SpinnerProps = HTMLAttributes<HTMLDivElement> & {
|
||||
size?: SpinnerSize
|
||||
variant?: SpinnerVariant
|
||||
/** Accessible label announced while loading. */
|
||||
label?: string
|
||||
}
|
||||
|
||||
export const Spinner = forwardRef<HTMLDivElement, SpinnerProps>(function Spinner(
|
||||
{ size = 'md', variant = 'primary', label = 'Loading', className, ...props },
|
||||
ref,
|
||||
) {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
role="status"
|
||||
aria-label={label}
|
||||
className={cn(
|
||||
'inline-block rounded-full animate-spin',
|
||||
SPINNER_SIZES[size] ?? SPINNER_SIZES.md,
|
||||
SPINNER_VARIANTS[variant] ?? SPINNER_VARIANTS.primary,
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="sr-only">{label}...</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Spinner
|
||||
@@ -0,0 +1,128 @@
|
||||
import { useState } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Switch } from './Switch'
|
||||
|
||||
const meta = {
|
||||
title: 'Forms/Switch',
|
||||
component: Switch,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Toggle switch with an optional label, description and help tooltip. Works controlled (`checked` + `onChange`) or uncontrolled. When `checked` is supplied the prop always wins, so a parent re-render can never silently discard the toggle state.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
color: {
|
||||
control: 'select',
|
||||
options: ['blue', 'red', 'green', 'yellow', 'teal', 'indigo', 'purple', 'pink'],
|
||||
},
|
||||
label: { control: 'text' },
|
||||
description: { control: 'text' },
|
||||
required: { control: 'boolean' },
|
||||
disabled: { control: 'boolean' },
|
||||
tooltip: { control: 'text' },
|
||||
helpText: { control: 'text' },
|
||||
error: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
label: 'Enable automatic payslip delivery',
|
||||
description: 'Sends a PDF to each employee on disbursement.',
|
||||
size: 'md',
|
||||
color: 'blue',
|
||||
required: false,
|
||||
disabled: false,
|
||||
tooltip: '',
|
||||
helpText: '',
|
||||
error: '',
|
||||
},
|
||||
} satisfies Meta<typeof Switch>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
/**
|
||||
* Wraps Switch with local state so the toggle is interactive.
|
||||
*
|
||||
* `initial` matters: passing `checked` at all makes the component controlled,
|
||||
* so a `defaultChecked` on the same element is ignored. The Colors story needs
|
||||
* the switch to start ON, so the initial value has to live here.
|
||||
*/
|
||||
function ControlledSwitch({
|
||||
initial = false,
|
||||
...args
|
||||
}: React.ComponentProps<typeof Switch> & { initial?: boolean }) {
|
||||
const [checked, setChecked] = useState(initial)
|
||||
return <Switch {...args} checked={checked} onChange={(e) => setChecked(e.target.checked)} />
|
||||
}
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => <ControlledSwitch {...args} />,
|
||||
}
|
||||
|
||||
export const Uncontrolled: Story = {
|
||||
render: (args) => <Switch {...args} defaultChecked />,
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-col gap-5">
|
||||
{(['sm', 'md', 'lg'] as const).map((size) => (
|
||||
<ControlledSwitch key={size} size={size} label={`Size ${size}`} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Colors: Story = {
|
||||
render: () => (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{(['blue', 'red', 'green', 'yellow', 'teal', 'indigo', 'purple', 'pink'] as const).map((color) => (
|
||||
<ControlledSwitch key={color} color={color} label={color} initial />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithDescription: Story = {
|
||||
render: () => (
|
||||
<ControlledSwitch
|
||||
label="Enable automatic payslip delivery"
|
||||
description="Sends a PDF to each employee on disbursement."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const Required: Story = {
|
||||
render: () => <ControlledSwitch label="I accept the terms" required />,
|
||||
}
|
||||
|
||||
export const WithTooltip: Story = {
|
||||
render: () => (
|
||||
<ControlledSwitch
|
||||
label="Lock completed payroll runs"
|
||||
tooltip="Prevents any edit to a run once it is marked disbursed."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithError: Story = {
|
||||
render: () => (
|
||||
<ControlledSwitch
|
||||
label="Lock completed payroll runs"
|
||||
error="This setting is required by your compliance policy."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const Disabled: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Switch label="Off and disabled" disabled />
|
||||
<Switch label="On and disabled" defaultChecked disabled />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import {
|
||||
forwardRef,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ChangeEvent,
|
||||
type InputHTMLAttributes,
|
||||
type Ref,
|
||||
} from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { SWITCH_COLORS, SWITCH_SIZES, type SwitchColor, type SwitchSize } from './switch.tokens'
|
||||
|
||||
/**
|
||||
* Toggle switch with an optional label, description and help tooltip.
|
||||
*
|
||||
* Ported from the original `Switch` component, keeping its
|
||||
* controlled/uncontrolled handling: a duplicated internal copy of `checked`
|
||||
* drifts from whatever the caller holds, so the prop wins whenever it is
|
||||
* supplied and local state is used only for genuinely uncontrolled use.
|
||||
*
|
||||
* `register` / `validation` (React Hook Form) are intentionally not ported —
|
||||
* pass `checked` and `onChange` directly.
|
||||
*/
|
||||
|
||||
export type SwitchProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'size'> & {
|
||||
name?: string
|
||||
size?: SwitchSize
|
||||
color?: SwitchColor
|
||||
label?: string
|
||||
description?: string
|
||||
/** Appends the mandatory asterisk to the label. */
|
||||
required?: boolean
|
||||
error?: string | { message?: string }
|
||||
tooltip?: string
|
||||
tooltipIcon?: LucideIcon
|
||||
helpText?: string
|
||||
}
|
||||
|
||||
export const Switch = forwardRef(function Switch(
|
||||
{
|
||||
name,
|
||||
size = 'md',
|
||||
disabled = false,
|
||||
color = 'blue',
|
||||
label,
|
||||
description,
|
||||
checked,
|
||||
defaultChecked,
|
||||
required = false,
|
||||
onChange,
|
||||
error,
|
||||
className = '',
|
||||
value,
|
||||
tooltip,
|
||||
tooltipIcon,
|
||||
helpText,
|
||||
...props
|
||||
}: SwitchProps & { ref?: Ref<HTMLInputElement> },
|
||||
ref,
|
||||
) {
|
||||
// `checked` has a default below, so the destructured value cannot distinguish
|
||||
// an omitted prop from an explicit `false` — read the raw props instead.
|
||||
const isControlled = checked !== undefined
|
||||
const [uncontrolledChecked, setUncontrolledChecked] = useState(Boolean(defaultChecked))
|
||||
const internalRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const isChecked = isControlled ? Boolean(checked) : uncontrolledChecked
|
||||
|
||||
// Keep uncontrolled state in step with a native form reset, which restores
|
||||
// `defaultChecked` just as it would on a plain checkbox.
|
||||
useEffect(() => {
|
||||
const form = internalRef.current?.form
|
||||
if (!form) return
|
||||
const handleReset = () => setUncontrolledChecked(Boolean(defaultChecked))
|
||||
form.addEventListener('reset', handleReset)
|
||||
return () => form.removeEventListener('reset', handleReset)
|
||||
}, [defaultChecked])
|
||||
|
||||
const sizeData = SWITCH_SIZES[size] ?? SWITCH_SIZES.md
|
||||
const colorClass = SWITCH_COLORS[color] ?? SWITCH_COLORS.blue
|
||||
const errorMessage = typeof error === 'string' ? error : error?.message
|
||||
|
||||
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
if (!isControlled) setUncontrolledChecked(e.target.checked)
|
||||
onChange?.(e)
|
||||
}
|
||||
|
||||
const handleRef = (el: HTMLInputElement | null) => {
|
||||
internalRef.current = el
|
||||
if (typeof ref === 'function') ref(el)
|
||||
else if (ref) ref.current = el
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col items-start space-y-1', className)}>
|
||||
<label
|
||||
htmlFor={name ? `switch-${name}` : undefined}
|
||||
className={cn(
|
||||
'relative inline-flex shrink-0 items-center',
|
||||
disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
id={name ? `switch-${name}` : undefined}
|
||||
name={name}
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
aria-checked={isChecked}
|
||||
className="sr-only peer"
|
||||
disabled={disabled}
|
||||
checked={isChecked}
|
||||
onChange={handleChange}
|
||||
value={value}
|
||||
ref={handleRef}
|
||||
{...props}
|
||||
/>
|
||||
|
||||
{/* Track + knob are decorative; the input above carries the semantics. */}
|
||||
<span className="relative shrink-0" aria-hidden="true">
|
||||
<span
|
||||
className={cn(
|
||||
'block rounded-full shadow-inner transition-colors duration-300',
|
||||
sizeData.toggle,
|
||||
isChecked ? colorClass : 'bg-gray-300',
|
||||
)}
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
'absolute top-1 left-[0.15rem] block rounded-full bg-white shadow-sm transition-transform duration-300',
|
||||
sizeData.dot,
|
||||
isChecked ? sizeData.translate : 'translate-x-0',
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
|
||||
{(label || description) && (
|
||||
<span className="ml-3 flex flex-col justify-center">
|
||||
{label && (
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</span>
|
||||
{(tooltip || helpText) && (
|
||||
<span onClick={(e) => e.preventDefault()}>
|
||||
<Tooltip
|
||||
content={tooltip ?? helpText ?? ''}
|
||||
size="sm"
|
||||
position="top"
|
||||
icon={tooltipIcon}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{description && <span className="text-xs text-gray-500">{description}</span>}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="mt-1 text-sm text-red-500" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default Switch
|
||||
@@ -0,0 +1,159 @@
|
||||
import { useState } from 'react'
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { TextArea } from './TextArea'
|
||||
|
||||
const meta = {
|
||||
title: 'Forms/TextArea',
|
||||
component: TextArea,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Multi-line input. `featured` renders the label inside the field and floats it above the border on focus, on value, or when `shrink` is set.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
theme: {
|
||||
control: 'select',
|
||||
options: ['primary', 'secondary', 'success', 'warning', 'info', 'error'],
|
||||
},
|
||||
rows: { control: { type: 'number', min: 1, max: 12 } },
|
||||
featured: { control: 'boolean' },
|
||||
shrink: { control: 'boolean' },
|
||||
roundedFull: { control: 'boolean' },
|
||||
dashedBorder: { control: 'boolean' },
|
||||
resize: { control: 'boolean' },
|
||||
required: { control: 'boolean' },
|
||||
disabled: { control: 'boolean' },
|
||||
label: { control: 'text' },
|
||||
placeholder: { control: 'text' },
|
||||
helpText: { control: 'text' },
|
||||
error: { control: 'text' },
|
||||
},
|
||||
args: {
|
||||
label: 'Reason for adjustment',
|
||||
placeholder: 'Describe why this payroll run needs a correction…',
|
||||
rows: 4,
|
||||
size: 'md',
|
||||
theme: 'primary',
|
||||
featured: false,
|
||||
shrink: false,
|
||||
roundedFull: false,
|
||||
dashedBorder: false,
|
||||
resize: true,
|
||||
required: false,
|
||||
disabled: false,
|
||||
helpText: '',
|
||||
error: '',
|
||||
},
|
||||
} satisfies Meta<typeof TextArea>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
function ControlledTextArea(args: React.ComponentProps<typeof TextArea>) {
|
||||
const [value, setValue] = useState(args.value ?? '')
|
||||
return <TextArea {...args} value={value} onChange={(e) => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => <ControlledTextArea {...args} />,
|
||||
}
|
||||
|
||||
export const Uncontrolled: Story = {
|
||||
render: (args) => <TextArea {...args} defaultValue="March payroll was short by ₹1,240 due to a missing attendance import." />,
|
||||
}
|
||||
|
||||
/** Floating label: floats on focus, on value, or immediately with `shrink`. */
|
||||
export const Featured: Story = {
|
||||
args: { featured: true },
|
||||
render: (args) => <ControlledTextArea {...args} />,
|
||||
}
|
||||
|
||||
export const FeaturedPrefilled: Story = {
|
||||
args: { featured: true },
|
||||
render: (args) => (
|
||||
<TextArea
|
||||
{...args}
|
||||
defaultValue="Statutory contributions were recalculated after the FY update."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const FeaturedShrunk: Story = {
|
||||
args: { featured: true, shrink: true },
|
||||
render: (args) => <TextArea {...args} />,
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: (args) => (
|
||||
<div className="flex flex-col gap-5">
|
||||
{(['sm', 'md', 'lg'] as const).map((size) => (
|
||||
<ControlledTextArea key={size} {...args} size={size} label={`Size ${size}`} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Themes: Story = {
|
||||
render: (args) => (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{(['primary', 'secondary', 'success', 'warning', 'info', 'error'] as const).map((theme) => (
|
||||
<ControlledTextArea key={theme} {...args} theme={theme} label={theme} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const BorderStyles: Story = {
|
||||
render: (args) => (
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<ControlledTextArea {...args} label="Solid" />
|
||||
<ControlledTextArea {...args} label="Dashed" dashedBorder />
|
||||
<ControlledTextArea {...args} label="Pill" roundedFull />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Resize: Story = {
|
||||
render: (args) => (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<ControlledTextArea {...args} label="Resizable" resize />
|
||||
<ControlledTextArea {...args} label="Fixed height" resize={false} rows={4} />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithTooltip: Story = {
|
||||
render: (args) => (
|
||||
<ControlledTextArea
|
||||
{...args}
|
||||
helpText="Visible to approvers only. Never shown on the payslip itself."
|
||||
/>
|
||||
),
|
||||
}
|
||||
|
||||
export const WithError: Story = {
|
||||
render: (args) => (
|
||||
<ControlledTextArea {...args} required error="A reason is required for every adjustment." />
|
||||
),
|
||||
}
|
||||
|
||||
export const FeaturedWithError: Story = {
|
||||
render: (args) => (
|
||||
<ControlledTextArea {...args} featured required error="A reason is required for every adjustment." />
|
||||
),
|
||||
}
|
||||
|
||||
export const Disabled: Story = {
|
||||
render: (args) => (
|
||||
<TextArea
|
||||
{...args}
|
||||
disabled
|
||||
defaultValue="Locked after this run was approved."
|
||||
/>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import { forwardRef, useState, type ChangeEvent, type FocusEvent, type TextareaHTMLAttributes } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import { omit } from '@/lib/omit'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import {
|
||||
FLOATING_CONTENT_PADDING,
|
||||
FLOATING_LABEL_SIZES,
|
||||
LABEL_SIZES,
|
||||
TEXTAREA_SIZES,
|
||||
TEXTAREA_THEMES,
|
||||
type TextAreaSize,
|
||||
type TextAreaTheme,
|
||||
} from './textarea.tokens'
|
||||
|
||||
/**
|
||||
* Multi-line text input, with an optional floating label.
|
||||
*
|
||||
* Ported from the original `TextArea` component.
|
||||
*
|
||||
* `featured` renders the label inside the field and floats it above the border
|
||||
* once the field is focused, holds a value, or `shrink` is set. The floating
|
||||
* label paints its own background so it cuts through the border cleanly.
|
||||
*
|
||||
* Form-library props are filtered out before spreading, so nothing internal
|
||||
* leaks onto the DOM node.
|
||||
*/
|
||||
|
||||
export type TextAreaProps = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'rows'> & {
|
||||
label?: string
|
||||
rows?: number
|
||||
size?: TextAreaSize
|
||||
theme?: TextAreaTheme
|
||||
/** Render the label inside the field and float it on focus/value. */
|
||||
featured?: boolean
|
||||
/** Float the label even when the field is empty and unfocused. */
|
||||
shrink?: boolean
|
||||
roundedFull?: boolean
|
||||
dashedBorder?: boolean
|
||||
resize?: boolean
|
||||
error?: string | { message?: string }
|
||||
tooltip?: string
|
||||
tooltipIcon?: LucideIcon
|
||||
helpText?: string
|
||||
}
|
||||
|
||||
export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(function TextArea(
|
||||
{
|
||||
label = '',
|
||||
placeholder = '',
|
||||
disabled = false,
|
||||
required = false,
|
||||
className = '',
|
||||
roundedFull = false,
|
||||
dashedBorder = false,
|
||||
size = 'md',
|
||||
theme = 'primary',
|
||||
rows = 4,
|
||||
name,
|
||||
error,
|
||||
onChange,
|
||||
onBlur,
|
||||
onFocus,
|
||||
featured = false,
|
||||
value,
|
||||
resize = true,
|
||||
shrink = false,
|
||||
helpText,
|
||||
tooltip,
|
||||
tooltipIcon,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const [isFocused, setIsFocused] = useState(false)
|
||||
// The floating label needs to know whether the field holds content. Track it
|
||||
// locally so uncontrolled usage floats correctly too.
|
||||
//
|
||||
// `defaultValue` counts as content: an uncontrolled field rendered with
|
||||
// `defaultValue` is visibly filled but `value` is undefined, so seeding only
|
||||
// from `value` left the label sitting on top of the text. The source
|
||||
// component has the same gap.
|
||||
const [hasValue, setHasValue] = useState(
|
||||
Boolean(value) || Boolean(props.defaultValue),
|
||||
)
|
||||
|
||||
// Strip form-library plumbing that must not reach the DOM.
|
||||
const htmlProps = omit(props as Record<string, unknown>, [
|
||||
'control',
|
||||
'allValues',
|
||||
'isDynamic',
|
||||
'valueKey',
|
||||
'labelKey',
|
||||
'endpoint',
|
||||
'endpointParams',
|
||||
'isMulti',
|
||||
'searchable',
|
||||
'infiniteScroll',
|
||||
'register',
|
||||
'validation',
|
||||
])
|
||||
|
||||
const handleFocus = (e: FocusEvent<HTMLTextAreaElement>) => {
|
||||
setIsFocused(true)
|
||||
onFocus?.(e)
|
||||
}
|
||||
|
||||
const handleBlur = (e: FocusEvent<HTMLTextAreaElement>) => {
|
||||
setIsFocused(false)
|
||||
onBlur?.(e)
|
||||
}
|
||||
|
||||
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setHasValue(Boolean(e.target.value))
|
||||
onChange?.(e)
|
||||
}
|
||||
|
||||
const shouldFloat = featured && (shrink || isFocused || hasValue || Boolean(value))
|
||||
const themeClass = TEXTAREA_THEMES[theme] ?? TEXTAREA_THEMES.primary
|
||||
const errorMessage = typeof error === 'string' ? error : error?.message
|
||||
|
||||
return (
|
||||
<div className="w-full relative flex flex-col">
|
||||
{!featured && label && (
|
||||
<div className="mb-1 flex items-center gap-1.5">
|
||||
<label htmlFor={name} className={cn('text-gray-800', LABEL_SIZES[size])}>
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</label>
|
||||
{(tooltip || helpText) && (
|
||||
<Tooltip
|
||||
content={tooltip ?? helpText ?? ''}
|
||||
size="sm"
|
||||
position="top"
|
||||
icon={tooltipIcon}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative w-full">
|
||||
<textarea
|
||||
id={name}
|
||||
ref={ref}
|
||||
name={name}
|
||||
rows={rows}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
placeholder={featured && !shouldFloat ? '' : placeholder}
|
||||
autoComplete="off"
|
||||
aria-invalid={Boolean(errorMessage)}
|
||||
className={cn(
|
||||
'w-full outline-none transition-all duration-200 bg-white text-gray-800',
|
||||
TEXTAREA_SIZES[size],
|
||||
roundedFull ? 'rounded-3xl' : 'rounded-md',
|
||||
dashedBorder ? 'border-dashed' : 'border-solid',
|
||||
resize ? 'resize-y' : 'resize-none',
|
||||
'border',
|
||||
// Once the label floats it occupies the top ~1rem of the field, so
|
||||
// the first line of text needs to clear it. The source component
|
||||
// never adds this padding, which puts the label and the first line
|
||||
// of text on top of each other — visible in any prefilled or
|
||||
// focused featured textarea. Sized off the label's own height.
|
||||
featured && shouldFloat && FLOATING_CONTENT_PADDING[size],
|
||||
disabled
|
||||
? 'bg-gray-100 border-slate-200 text-slate-400 cursor-not-allowed'
|
||||
: cn(
|
||||
isFocused ? themeClass : 'border-slate-300',
|
||||
'hover:border-slate-400',
|
||||
),
|
||||
// Error wins over the theme's focus colours.
|
||||
errorMessage && 'border-red-500 focus:border-red-500 focus:ring-red-500',
|
||||
className,
|
||||
)}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
onChange={handleChange}
|
||||
value={value}
|
||||
{...htmlProps}
|
||||
/>
|
||||
|
||||
{featured && label && (
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'absolute pointer-events-none transition-all duration-200 left-3 px-1',
|
||||
shouldFloat
|
||||
? cn(
|
||||
'-top-2 bg-white transform',
|
||||
FLOATING_LABEL_SIZES[size],
|
||||
errorMessage
|
||||
? 'text-red-500'
|
||||
: isFocused
|
||||
? 'text-primary-500'
|
||||
: 'text-slate-400',
|
||||
)
|
||||
: cn('top-3', LABEL_SIZES[size], 'text-slate-400'),
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span>
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</span>
|
||||
{(tooltip || helpText) && (
|
||||
<span
|
||||
className="pointer-events-auto inline-flex shrink-0"
|
||||
onClick={(e) => e.preventDefault()}
|
||||
>
|
||||
<Tooltip
|
||||
content={tooltip ?? helpText ?? ''}
|
||||
size="sm"
|
||||
position="top"
|
||||
icon={tooltipIcon}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{errorMessage && (
|
||||
<p className="mt-1 text-sm text-red-500" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default TextArea
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { TextField } from './TextField'
|
||||
|
||||
const meta = {
|
||||
title: 'Data entry/Text field',
|
||||
component: TextField,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component: 'A labeled form field with optional help text and accessible validation feedback.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
error: {
|
||||
control: 'text',
|
||||
},
|
||||
},
|
||||
args: {
|
||||
label: 'Email address',
|
||||
hint: 'Use an address you can check today.',
|
||||
placeholder: '[email protected]',
|
||||
},
|
||||
} satisfies Meta<typeof TextField>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
export const Default: Story = {}
|
||||
|
||||
export const WithError: Story = {
|
||||
args: {
|
||||
error: 'Enter a valid email address.',
|
||||
defaultValue: 'not-an-email',
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useId, useState, type InputHTMLAttributes } from 'react'
|
||||
|
||||
export type TextFieldProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> & {
|
||||
label: string
|
||||
hint?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export function TextField({ label, hint, error, className = '', ...props }: TextFieldProps) {
|
||||
const id = useId()
|
||||
const descriptionId = `${id}-description`
|
||||
const errorId = `${id}-error`
|
||||
const [value, setValue] = useState(props.defaultValue ?? '')
|
||||
|
||||
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
|
||||
setValue(event.target.value)
|
||||
props.onChange?.(event)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`space-y-2 ${className}`}>
|
||||
<label htmlFor={id} className="block text-sm font-bold text-slate-800">
|
||||
{label}
|
||||
{props.required && <span className="ml-1 text-red-600">*</span>}
|
||||
</label>
|
||||
<input
|
||||
{...props}
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
aria-invalid={Boolean(error)}
|
||||
aria-describedby={
|
||||
[hint ? descriptionId : null, error ? errorId : null].filter(Boolean).join(' ') || undefined
|
||||
}
|
||||
className={`min-h-11 w-full rounded-xl border bg-white px-3.5 text-sm text-slate-950 outline-none transition placeholder:text-slate-400 focus:border-primary-500 focus:ring-4 focus:ring-primary-100 ${
|
||||
error ? 'border-red-300' : 'border-slate-200'
|
||||
}`}
|
||||
/>
|
||||
{hint && !error && (
|
||||
<p id={descriptionId} className="text-xs leading-5 text-slate-500">
|
||||
{hint}
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p id={errorId} role="alert" className="text-xs font-semibold leading-5 text-red-600">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite'
|
||||
import { Tooltip } from './Tooltip'
|
||||
|
||||
const meta = {
|
||||
title: 'Overlays/Tooltip',
|
||||
component: Tooltip,
|
||||
tags: ['autodocs'],
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Portal-rendered tooltip with viewport clamping. String content renders a themed bubble with an arrow; a React node renders an interactive panel that stays open while the pointer is over it.',
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
position: {
|
||||
control: 'select',
|
||||
options: [
|
||||
'top', 'top-start', 'top-end',
|
||||
'bottom', 'bottom-start', 'bottom-end',
|
||||
'left', 'left-start', 'left-end',
|
||||
'right', 'right-start', 'right-end',
|
||||
],
|
||||
},
|
||||
theme: {
|
||||
control: 'select',
|
||||
options: ['dark', 'light', 'primary', 'success', 'danger', 'warning', 'info', 'soft', 'custom', 'gradient'],
|
||||
},
|
||||
size: { control: 'select', options: ['sm', 'md', 'lg'] },
|
||||
delay: { control: { type: 'number', min: 0, step: 100 }, description: 'Hover delay in ms.' },
|
||||
arrow: { control: 'boolean' },
|
||||
shadow: { control: 'boolean' },
|
||||
rounded: { control: 'boolean' },
|
||||
},
|
||||
args: {
|
||||
content: 'Employees are onboarded per country.',
|
||||
position: 'top',
|
||||
theme: 'dark',
|
||||
size: 'md',
|
||||
delay: 0,
|
||||
arrow: true,
|
||||
shadow: false,
|
||||
rounded: true,
|
||||
},
|
||||
} satisfies Meta<typeof Tooltip>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
export const Playground: Story = {
|
||||
render: (args) => (
|
||||
<div className="flex justify-center py-16">
|
||||
<Tooltip {...args}>
|
||||
<button type="button" className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm font-semibold text-gray-700 hover:border-gray-400">
|
||||
Hover me
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** No children — falls back to the trigger icon. */
|
||||
export const IconTrigger: Story = {
|
||||
args: { content: 'This field is required for statutory reporting.' },
|
||||
render: (args) => (
|
||||
<div className="py-16">
|
||||
<Tooltip {...args} />
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Themes: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-6 py-16">
|
||||
{(['dark', 'light', 'primary', 'success', 'danger', 'warning', 'info', 'soft', 'custom', 'gradient'] as const).map(
|
||||
(theme) => (
|
||||
<div key={theme} className="flex flex-col items-center gap-2">
|
||||
<Tooltip content={`${theme} tooltip`} theme={theme}>
|
||||
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
|
||||
{theme}
|
||||
</span>
|
||||
</Tooltip>
|
||||
<code className="text-[10px] text-gray-500">{theme}</code>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Positions: Story = {
|
||||
render: () => (
|
||||
<div className="flex items-center justify-center py-24">
|
||||
<div className="relative h-40 w-96">
|
||||
{(['top', 'top-start', 'top-end', 'bottom', 'bottom-start', 'bottom-end', 'left', 'left-start', 'left-end', 'right', 'right-start', 'right-end'] as const).map(
|
||||
(position) => (
|
||||
<Tooltip key={position} content={position} position={position} size="sm">
|
||||
<span className="absolute cursor-pointer rounded bg-primary-500 px-2 py-1 text-[10px] font-semibold text-white">
|
||||
{position}
|
||||
</span>
|
||||
</Tooltip>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: () => (
|
||||
<div className="flex flex-wrap items-center gap-8 py-16">
|
||||
{(['sm', 'md', 'lg'] as const).map((size) => (
|
||||
<div key={size} className="flex flex-col items-center gap-2">
|
||||
<Tooltip content={`${size} size tooltip`} size={size}>
|
||||
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
|
||||
{size}
|
||||
</span>
|
||||
</Tooltip>
|
||||
<code className="text-[10px] text-gray-500">{size}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** Node content renders an interactive light panel that survives hover travel. */
|
||||
export const RichContent: Story = {
|
||||
render: () => (
|
||||
<div className="py-16">
|
||||
<Tooltip
|
||||
content={
|
||||
<div className="space-y-1.5 p-1">
|
||||
<p className="text-xs font-semibold text-gray-900">Statutory basis</p>
|
||||
<p className="text-[11px] text-gray-600">
|
||||
Applies to all entities registered in India.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="mt-1 w-full rounded bg-primary-600 px-2 py-1 text-[11px] font-semibold text-white"
|
||||
>
|
||||
Open settings
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm font-semibold text-gray-700 hover:border-gray-400"
|
||||
>
|
||||
Rich tooltip
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
export const NoArrow: Story = {
|
||||
args: { arrow: false, content: 'Tooltip without an arrow.' },
|
||||
render: (args) => (
|
||||
<div className="flex justify-center py-16">
|
||||
<Tooltip {...args}>
|
||||
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
|
||||
Hover
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
|
||||
/** Long copy scrolls inside the bubble instead of stretching past the viewport. */
|
||||
export const LongContent: Story = {
|
||||
render: () => (
|
||||
<div className="py-16">
|
||||
<Tooltip
|
||||
content="Payroll runs are computed in the tenant's base currency. Re-runs after approval are blocked unless a supervisor raises a correction request, which is recorded in the audit trail with the reason and the requesting user."
|
||||
size="md"
|
||||
>
|
||||
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
|
||||
Hover for long copy
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import {
|
||||
isValidElement,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
forwardRef,
|
||||
type CSSProperties,
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
} from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { AlertCircle, type LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/cn'
|
||||
import {
|
||||
ARROW_POSITION_COLORS,
|
||||
BASE_ARROW_CLASSES,
|
||||
BASE_ARROW_CLASSES_OUTER,
|
||||
TOOLTIP_COLORS,
|
||||
TOOLTIP_SIZES,
|
||||
WHITE_BORDER_MAP,
|
||||
type TooltipPosition,
|
||||
type TooltipSize,
|
||||
type TooltipTheme,
|
||||
} from './tooltip.tokens'
|
||||
|
||||
/**
|
||||
* Portal-rendered tooltip with viewport clamping.
|
||||
*
|
||||
* Ported from the original `Tooltip` component.
|
||||
* Every form control in the source app renders one of these for its help text,
|
||||
* so it is ported first as a shared dependency.
|
||||
*
|
||||
* String content gets a themed bubble with an arrow. React-node content gets a
|
||||
* light panel sized to fit its content (a wider arrow sits behind it) and
|
||||
* stays open while the pointer is over it, so interactive menus work.
|
||||
*/
|
||||
|
||||
const MAX_WIDTH = 280
|
||||
|
||||
function directionOf(position: TooltipPosition): 't' | 'b' | 'l' | 'r' {
|
||||
if (position.startsWith('top')) return 't'
|
||||
if (position.startsWith('bottom')) return 'b'
|
||||
if (position.startsWith('left')) return 'l'
|
||||
return 'r'
|
||||
}
|
||||
|
||||
export type TooltipProps = {
|
||||
/** String renders a themed bubble; a React node renders an interactive panel. */
|
||||
content: ReactNode
|
||||
position?: TooltipPosition
|
||||
children?: ReactNode
|
||||
size?: TooltipSize
|
||||
theme?: TooltipTheme
|
||||
rounded?: boolean
|
||||
arrow?: boolean
|
||||
shadow?: boolean
|
||||
/** Hover delay in ms before the tooltip appears. */
|
||||
delay?: number
|
||||
className?: string
|
||||
triggerClassName?: string
|
||||
iconClassName?: string
|
||||
/** Overrides the default `AlertCircle` trigger icon. */
|
||||
icon?: LucideIcon
|
||||
}
|
||||
|
||||
export const Tooltip = forwardRef(function Tooltip(
|
||||
{
|
||||
content,
|
||||
position = 'top',
|
||||
children,
|
||||
size = 'md',
|
||||
theme = 'dark',
|
||||
rounded = true,
|
||||
arrow = true,
|
||||
shadow = false,
|
||||
delay = 0,
|
||||
className = '',
|
||||
triggerClassName = '',
|
||||
iconClassName = 'text-orange-500 cursor-pointer hover:text-orange-600 transition-colors',
|
||||
icon,
|
||||
}: TooltipProps,
|
||||
ref: Ref<HTMLDivElement>,
|
||||
) {
|
||||
const [isHovered, setIsHovered] = useState(false)
|
||||
const [showTooltip, setShowTooltip] = useState(false)
|
||||
const [coords, setCoords] = useState({ x: 0, y: 0, width: 0, height: 0 })
|
||||
|
||||
const triggerRef = useRef<HTMLDivElement>(null)
|
||||
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const lastRectRef = useRef<DOMRect | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const node = triggerRef.current
|
||||
if (typeof ref === 'function') ref(node)
|
||||
else if (ref) ref.current = node
|
||||
}, [ref])
|
||||
|
||||
const isStringContent = typeof content === 'string' && content.trim().length > 0
|
||||
const isNodeContent = isValidElement(content)
|
||||
const shouldShow = isStringContent || isNodeContent
|
||||
const isShortText = typeof content === 'string' && content.length <= 33
|
||||
const ResolvedIcon: LucideIcon = icon ?? AlertCircle
|
||||
|
||||
const updatePosition = useCallback(() => {
|
||||
const node = triggerRef.current
|
||||
if (!node) return
|
||||
|
||||
const rect = node.getBoundingClientRect()
|
||||
const last = lastRectRef.current
|
||||
// Skip a re-measure when nothing moved — otherwise hovering over a static
|
||||
// trigger would keep resetting coords on every mouse event.
|
||||
if (
|
||||
last &&
|
||||
Math.abs(last.top - rect.top) < 0.5 &&
|
||||
Math.abs(last.left - rect.left) < 0.5
|
||||
) {
|
||||
return
|
||||
}
|
||||
lastRectRef.current = rect
|
||||
setCoords({ x: rect.left, y: rect.top, width: rect.width, height: rect.height })
|
||||
}, [])
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
updatePosition()
|
||||
setIsHovered(true)
|
||||
if (closeTimer.current) {
|
||||
clearTimeout(closeTimer.current)
|
||||
closeTimer.current = null
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
if (isNodeContent) {
|
||||
// Grace period so the pointer can travel from trigger to panel.
|
||||
closeTimer.current = setTimeout(() => setIsHovered(false), 200)
|
||||
} else {
|
||||
setIsHovered(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleMenuMouseEnter = () => {
|
||||
if (closeTimer.current) {
|
||||
clearTimeout(closeTimer.current)
|
||||
closeTimer.current = null
|
||||
}
|
||||
}
|
||||
|
||||
const handleMenuMouseLeave = () => {
|
||||
closeTimer.current = setTimeout(() => {
|
||||
setIsHovered(false)
|
||||
setShowTooltip(false)
|
||||
}, 200)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (isHovered) {
|
||||
const timer = setTimeout(() => setShowTooltip(true), delay)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
setShowTooltip(false)
|
||||
}, [isHovered, delay])
|
||||
|
||||
useEffect(() => {
|
||||
if (!showTooltip) return
|
||||
const reposition = () => updatePosition()
|
||||
window.addEventListener('scroll', reposition, true)
|
||||
window.addEventListener('resize', reposition)
|
||||
return () => {
|
||||
window.removeEventListener('scroll', reposition, true)
|
||||
window.removeEventListener('resize', reposition)
|
||||
}
|
||||
}, [showTooltip, updatePosition])
|
||||
|
||||
const direction = directionOf(position)
|
||||
const arrowColorClass = isNodeContent
|
||||
? WHITE_BORDER_MAP[direction]
|
||||
: ARROW_POSITION_COLORS[position]?.[theme] ?? ''
|
||||
|
||||
const positionStyle = (): CSSProperties => {
|
||||
const { x, y, width, height } = coords
|
||||
const viewportWidth = typeof window !== 'undefined' ? window.innerWidth : 0
|
||||
const viewportHeight = typeof window !== 'undefined' ? window.innerHeight : 0
|
||||
const clampX = (v: number) => (viewportWidth ? Math.min(Math.max(v, 8), viewportWidth - 8) : v)
|
||||
const clampY = (v: number) => (viewportHeight ? Math.min(Math.max(v, 8), viewportHeight - 8) : v)
|
||||
const base: CSSProperties = { position: 'fixed', zIndex: 9999, maxWidth: `${MAX_WIDTH}px` }
|
||||
|
||||
switch (position) {
|
||||
case 'top':
|
||||
return { ...base, top: clampY(y - 8), left: clampX(x + width / 2), transform: 'translateX(-50%) translateY(-100%)' }
|
||||
case 'top-start':
|
||||
return { ...base, top: clampY(y - 8), left: clampX(x), transform: 'translateY(-100%)' }
|
||||
case 'top-end':
|
||||
return { ...base, top: clampY(y - 8), left: clampX(x + width), transform: 'translateX(-100%) translateY(-100%)' }
|
||||
case 'bottom':
|
||||
return { ...base, top: clampY(y + height + 8), left: clampX(x + width / 2), transform: 'translateX(-50%)' }
|
||||
case 'bottom-start':
|
||||
return { ...base, top: clampY(y + height + 8), left: clampX(x) }
|
||||
case 'bottom-end':
|
||||
return { ...base, top: clampY(y + height + 8), left: clampX(x + width), transform: 'translateX(-100%)' }
|
||||
case 'left':
|
||||
return { ...base, top: clampY(y + height / 2), left: clampX(x - 8), transform: 'translateY(-50%) translateX(-100%)' }
|
||||
case 'left-start':
|
||||
return { ...base, top: clampY(y), left: clampX(x - 8), transform: 'translateX(-100%)' }
|
||||
case 'left-end':
|
||||
return { ...base, top: clampY(y + height), left: clampX(x - 8), transform: 'translateY(-100%) translateX(-100%)' }
|
||||
case 'right':
|
||||
return { ...base, top: clampY(y + height / 2), left: clampX(x + width + 8), transform: 'translateY(-50%)' }
|
||||
case 'right-start':
|
||||
return { ...base, top: clampY(y), left: clampX(x + width + 8) }
|
||||
case 'right-end':
|
||||
return { ...base, top: clampY(y + height), left: clampX(x + width + 8), transform: 'translateY(-100%)' }
|
||||
default:
|
||||
return { ...base, top: clampY(y), left: clampX(x) }
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={triggerRef}
|
||||
className={cn('relative inline-block', triggerClassName)}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
{children ?? <ResolvedIcon size={16} className={cn(iconClassName)} />}
|
||||
</div>
|
||||
|
||||
{showTooltip &&
|
||||
shouldShow &&
|
||||
createPortal(
|
||||
<div
|
||||
role="tooltip"
|
||||
onMouseEnter={isNodeContent ? handleMenuMouseEnter : undefined}
|
||||
onMouseLeave={isNodeContent ? handleMenuMouseLeave : undefined}
|
||||
style={positionStyle()}
|
||||
className={cn(
|
||||
TOOLTIP_SIZES[size] ?? TOOLTIP_SIZES.md,
|
||||
isStringContent
|
||||
? (TOOLTIP_COLORS[theme] ?? TOOLTIP_COLORS.dark)
|
||||
: 'bg-white text-slate-700 border border-slate-200',
|
||||
shadow && 'shadow-lg',
|
||||
rounded ? 'rounded-lg' : 'rounded',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'block text-start max-h-[250px] align-top overflow-auto',
|
||||
isShortText && isStringContent ? 'max-w-[210px] w-auto whitespace-nowrap' : '',
|
||||
!isStringContent ? 'min-w-[210px]' : '',
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
|
||||
{arrow && (
|
||||
<>
|
||||
{isNodeContent && (
|
||||
<div
|
||||
className={cn(
|
||||
BASE_ARROW_CLASSES_OUTER[position],
|
||||
ARROW_POSITION_COLORS[position]?.[theme] ?? '',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<div className={cn(BASE_ARROW_CLASSES[position], arrowColorClass)} />
|
||||
</>
|
||||
)}
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
)
|
||||
})
|
||||
|
||||
export default Tooltip
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Alert style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type AlertColor = 'success' | 'info' | 'warning' | 'error'
|
||||
export type AlertVariant = 'default' | 'filled' | 'outlined' | 'gradient'
|
||||
|
||||
export type AlertTheme = {
|
||||
bg: string
|
||||
text: string
|
||||
border: string
|
||||
lightBg: string
|
||||
}
|
||||
|
||||
export const ALERT_COLORS: Record<AlertColor, AlertTheme> = {
|
||||
success: {
|
||||
bg: 'bg-green-600',
|
||||
text: 'text-green-700',
|
||||
border: 'border-green-600',
|
||||
lightBg: 'bg-green-100',
|
||||
},
|
||||
info: {
|
||||
bg: 'bg-sky-600',
|
||||
text: 'text-sky-700',
|
||||
border: 'border-sky-600',
|
||||
lightBg: 'bg-sky-100',
|
||||
},
|
||||
warning: {
|
||||
bg: 'bg-orange-500',
|
||||
text: 'text-orange-700',
|
||||
border: 'border-orange-500',
|
||||
lightBg: 'bg-orange-100',
|
||||
},
|
||||
error: {
|
||||
bg: 'bg-red-600',
|
||||
text: 'text-red-700',
|
||||
border: 'border-red-600',
|
||||
lightBg: 'bg-red-100',
|
||||
},
|
||||
}
|
||||
|
||||
export const ALERT_GRADIENT = 'bg-gradient-to-r from-green-400 to-primary-500 text-white'
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Badge style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export type BadgeColor = 'info' | 'gray' | 'danger' | 'success' | 'warning' | 'primary'
|
||||
export type BadgeType = 'floating' | 'default'
|
||||
export type BadgeFloatingPosition = 'top_right' | 'top_left' | 'bottom_right' | 'bottom_left'
|
||||
export type BadgeFloatingSize = 'xs' | 'sm' | 'md' | 'lg'
|
||||
export type BadgeDefaultSize = 'sm' | 'md' | 'lg'
|
||||
export type BadgeBorder = 'sm' | 'md' | 'lg' | 'full'
|
||||
|
||||
export type ColorRange = { min: number; max: number; color: BadgeColor | string }
|
||||
|
||||
export const BADGE_SIZES: Record<BadgeFloatingSize, string> = {
|
||||
xs: 'text-[10px] px-1.5 py-0.5 min-w-[16px] h-[16px]',
|
||||
sm: 'text-xs px-1.5 py-0.5 min-w-[18px] h-[18px]',
|
||||
md: 'text-sm px-2 py-0.5 min-w-[20px] h-[20px]',
|
||||
lg: 'text-base px-2 py-1 min-w-[24px] h-[24px]',
|
||||
}
|
||||
|
||||
export const DEFAULT_BADGE_SIZES: Record<BadgeDefaultSize, string> = {
|
||||
sm: 'text-xs px-2 py-0.5',
|
||||
md: 'text-sm px-2.5 py-1',
|
||||
lg: 'text-base px-3 py-1.5',
|
||||
}
|
||||
|
||||
export const BADGE_COLORS: Record<BadgeColor, string> = {
|
||||
info: 'bg-cyan-100 text-cyan-800 border border-cyan-200',
|
||||
gray: 'bg-gray-100 text-gray-800 border border-gray-200',
|
||||
danger: 'bg-red-100 text-red-800 border border-red-200',
|
||||
success: 'bg-green-100 text-green-800 border border-green-200',
|
||||
warning: 'bg-yellow-100 text-yellow-800 border border-yellow-200',
|
||||
primary: 'bg-primary-100 text-primary-700 border border-primary-200',
|
||||
}
|
||||
|
||||
export const BADGE_POSITIONS: Record<BadgeFloatingPosition, string> = {
|
||||
top_right: 'top-0 right-0 translate-x-1/2 -translate-y-1/2',
|
||||
top_left: 'top-0 left-0 -translate-x-1/2 -translate-y-1/2',
|
||||
bottom_right: 'bottom-0 right-0 translate-x-1/2 translate-y-1/2',
|
||||
bottom_left: 'bottom-0 left-0 -translate-x-1/2 translate-y-1/2',
|
||||
}
|
||||
|
||||
export const BADGE_ROUNDED: Record<BadgeBorder, string> = {
|
||||
sm: 'rounded-sm',
|
||||
md: 'rounded-md',
|
||||
lg: 'rounded-lg',
|
||||
full: 'rounded-full',
|
||||
}
|
||||
|
||||
/** Legacy colour names the source app still passes through. */
|
||||
export const BADGE_COLOR_ALIAS: Record<string, BadgeColor> = {
|
||||
green: 'success',
|
||||
red: 'danger',
|
||||
default: 'gray',
|
||||
blue: 'primary',
|
||||
}
|
||||
|
||||
/** Colour the badge by numeric content, e.g. pending-approval counts. */
|
||||
export function resolveBadgeColor(
|
||||
color: string,
|
||||
content: ReactNode | number,
|
||||
ranges: ColorRange[] | undefined,
|
||||
): BadgeColor {
|
||||
const normalized = BADGE_COLOR_ALIAS[color] ?? (color as BadgeColor)
|
||||
|
||||
if (!ranges || !Array.isArray(ranges)) return normalized
|
||||
|
||||
const num = Number(content)
|
||||
if (Number.isNaN(num)) return normalized
|
||||
|
||||
for (const range of ranges) {
|
||||
if (num >= range.min && num <= range.max) {
|
||||
return BADGE_COLOR_ALIAS[range.color] ?? (range.color as BadgeColor)
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Card style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type CardTheme = 'primary' | 'secondary' | 'success' | 'danger' | 'no-preset'
|
||||
export type CardLayout = 'vertical' | 'horizontal'
|
||||
export type CardShadow = 'none' | 'sm' | 'md' | 'lg' | 'xl'
|
||||
export type CardRounded = 'none' | 'sm' | 'md' | 'lg' | 'xl' | 'full'
|
||||
|
||||
export const SHADOW_SIZES: Record<CardShadow, string> = {
|
||||
none: 'shadow-none',
|
||||
sm: 'shadow-sm',
|
||||
md: 'shadow-md',
|
||||
lg: 'shadow-lg',
|
||||
xl: 'shadow-xl',
|
||||
}
|
||||
|
||||
export const ROUNDED_SIZES: Record<CardRounded, string> = {
|
||||
none: 'rounded-none',
|
||||
sm: 'rounded-sm',
|
||||
md: 'rounded-md',
|
||||
lg: 'rounded-lg',
|
||||
xl: 'rounded-xl',
|
||||
full: 'rounded-[2rem]',
|
||||
}
|
||||
|
||||
export type CardThemeData = {
|
||||
card: string
|
||||
header: string
|
||||
body: string
|
||||
footer: string
|
||||
}
|
||||
|
||||
export const CARD_THEMES: Record<CardTheme, CardThemeData> = {
|
||||
primary: {
|
||||
card: 'bg-white text-slate-800 border border-gray-200',
|
||||
header: 'text-lg font-bold p-4 border-b border-gray-100',
|
||||
body: 'p-4 text-gray-600',
|
||||
footer: 'p-4 border-t border-gray-100 bg-gray-50/50',
|
||||
},
|
||||
secondary: {
|
||||
card: 'bg-gray-50 text-gray-900 border border-gray-200',
|
||||
header: 'text-lg font-bold p-4 text-gray-700 border-b border-gray-200',
|
||||
body: 'p-4 text-gray-600',
|
||||
footer: 'p-4 border-t border-gray-200',
|
||||
},
|
||||
success: {
|
||||
card: 'bg-green-50 text-green-900 border border-green-200',
|
||||
header: 'text-lg font-bold p-4 text-green-700 border-b border-green-100',
|
||||
body: 'p-4 text-green-800',
|
||||
footer: 'p-4 border-t border-green-100',
|
||||
},
|
||||
danger: {
|
||||
card: 'bg-red-50 text-red-900 border border-red-200',
|
||||
header: 'text-lg font-bold p-4 text-red-700 border-b border-red-100',
|
||||
body: 'p-4 text-red-800',
|
||||
footer: 'p-4 border-t border-red-100',
|
||||
},
|
||||
'no-preset': { card: '', header: '', body: '', footer: '' },
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Checkbox style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type CheckboxSize = 'sm' | 'md' | 'lg'
|
||||
export type CheckboxTheme =
|
||||
| 'primary'
|
||||
| 'secondary'
|
||||
| 'success'
|
||||
| 'danger'
|
||||
| 'warning'
|
||||
| 'info'
|
||||
| 'amber'
|
||||
| 'purple'
|
||||
| 'blue'
|
||||
| 'green'
|
||||
| 'red'
|
||||
| 'yellow'
|
||||
| 'teal'
|
||||
|
||||
export const CHECKBOX_SIZES: Record<CheckboxSize, string> = {
|
||||
sm: 'h-4 w-4',
|
||||
md: 'h-5 w-5',
|
||||
lg: 'h-6 w-6',
|
||||
}
|
||||
|
||||
/** Uses the native `accent-*` property, so the browser paints the checked box. */
|
||||
export const CHECKBOX_THEMES: Record<CheckboxTheme, string> = {
|
||||
primary: 'accent-primary-500',
|
||||
secondary: 'accent-gray-500',
|
||||
success: 'accent-green-500',
|
||||
danger: 'accent-red-500',
|
||||
warning: 'accent-yellow-500',
|
||||
info: 'accent-cyan-500',
|
||||
// Legacy names the source app still passes through.
|
||||
amber: 'accent-amber-500',
|
||||
purple: 'accent-purple-500',
|
||||
blue: 'accent-primary-500',
|
||||
green: 'accent-green-500',
|
||||
red: 'accent-red-500',
|
||||
yellow: 'accent-yellow-500',
|
||||
teal: 'accent-teal-500',
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Input style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type InputSize = 'sm' | 'md' | 'lg'
|
||||
export type InputTheme = 'primary' | 'secondary' | 'success' | 'error' | 'warning' | 'info'
|
||||
export type InputVariant = 'outlined' | 'underlined'
|
||||
|
||||
export const INPUT_SIZES: Record<InputSize, string> = {
|
||||
sm: 'px-3 py-2 text-xs',
|
||||
md: 'px-3 py-2 h-[2.5rem] text-sm',
|
||||
lg: 'px-3 py-3 text-base',
|
||||
}
|
||||
|
||||
export const ICON_SIZES: Record<InputSize, string> = {
|
||||
sm: 'text-sm',
|
||||
md: 'text-[1rem]',
|
||||
lg: 'text-lg',
|
||||
}
|
||||
|
||||
export const LABEL_SIZES: Record<InputSize, string> = {
|
||||
sm: 'text-[0.7rem] font-medium leading-loose',
|
||||
md: 'text-[0.8rem] font-medium leading-loose',
|
||||
lg: 'text-base font-medium leading-loose',
|
||||
}
|
||||
|
||||
/** Label type size once it has floated above the border. */
|
||||
export const FLOATING_LABEL_SIZES: Record<InputSize, string> = {
|
||||
sm: 'text-[0.6rem] font-medium leading-loose',
|
||||
md: 'text-[0.65rem] font-medium leading-loose',
|
||||
lg: 'text-sm',
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra top padding for a `featured` input once its label floats.
|
||||
*
|
||||
* The floated label is a chip sitting on the top border; without this the text
|
||||
* sits underneath it. The source never adds it, which is why a prefilled
|
||||
* featured input renders its text under the label.
|
||||
*/
|
||||
export const FLOATING_CONTENT_PADDING: Record<InputSize, string> = {
|
||||
sm: 'pt-5',
|
||||
md: 'pt-6',
|
||||
lg: 'pt-7',
|
||||
}
|
||||
|
||||
export const INPUT_THEMES: Record<InputTheme, string> = {
|
||||
primary: 'focus:border-primary-500 focus:ring-primary-500',
|
||||
secondary: 'focus:border-purple-500 focus:ring-purple-500',
|
||||
success: 'focus:border-green-500 focus:ring-green-500',
|
||||
warning: 'focus:border-yellow-500 focus:ring-yellow-500',
|
||||
info: 'focus:border-cyan-500 focus:ring-cyan-500',
|
||||
error: 'border-red-500 focus:border-red-500 focus:ring-red-500',
|
||||
}
|
||||
|
||||
export const INPUT_HOVER_THEMES: Record<InputTheme, string> = {
|
||||
primary: 'hover:border-primary-500',
|
||||
secondary: 'hover:border-purple-500',
|
||||
success: 'hover:border-green-500',
|
||||
// The error state owns its own hover behaviour.
|
||||
error: '',
|
||||
warning: 'hover:border-yellow-500',
|
||||
info: 'hover:border-cyan-500',
|
||||
}
|
||||
|
||||
export const LABEL_COLORS: Record<InputTheme, string> = {
|
||||
primary: 'text-primary-500',
|
||||
secondary: 'text-purple-500',
|
||||
success: 'text-green-500',
|
||||
warning: 'text-yellow-500',
|
||||
info: 'text-cyan-500',
|
||||
error: 'text-red-500',
|
||||
}
|
||||
|
||||
export const INPUT_VARIANTS: Record<
|
||||
InputVariant,
|
||||
{ wrapper: string; labelFloating: string }
|
||||
> = {
|
||||
outlined: { wrapper: 'border bg-white', labelFloating: 'bg-white px-1' },
|
||||
underlined: {
|
||||
wrapper: 'border-b border-t-0 border-x-0 bg-transparent rounded-none',
|
||||
labelFloating: 'bg-transparent px-0',
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Radio style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type RadioSize = 'sm' | 'md' | 'lg'
|
||||
export type RadioTheme =
|
||||
| 'blue'
|
||||
| 'green'
|
||||
| 'red'
|
||||
| 'yellow'
|
||||
| 'teal'
|
||||
| 'purple'
|
||||
| 'amber'
|
||||
| 'gray'
|
||||
|
||||
export type RadioSizeData = {
|
||||
/** Outer ring. */
|
||||
container: string
|
||||
label: string
|
||||
/** Inner dot. */
|
||||
dot: string
|
||||
}
|
||||
|
||||
export const RADIO_SIZES: Record<RadioSize, RadioSizeData> = {
|
||||
sm: { container: 'h-3.5 w-3.5', label: 'text-xs', dot: 'h-1.5 w-1.5' },
|
||||
md: { container: 'h-4 w-4', label: 'text-sm', dot: 'h-2 w-2' },
|
||||
lg: { container: 'h-5 w-5', label: 'text-base', dot: 'h-2.5 w-2.5' },
|
||||
}
|
||||
|
||||
export type RadioColorData = {
|
||||
/** Inner dot fill. */
|
||||
bg: string
|
||||
/** Ring border when selected. */
|
||||
border: string
|
||||
text: string
|
||||
}
|
||||
|
||||
export const RADIO_COLORS: Record<RadioTheme, RadioColorData> = {
|
||||
blue: { bg: 'bg-primary-600', border: 'border-primary-400', text: 'text-primary-500' },
|
||||
green: { bg: 'bg-green-600', border: 'border-green-400', text: 'text-green-500' },
|
||||
red: { bg: 'bg-red-600', border: 'border-red-400', text: 'text-red-500' },
|
||||
yellow: { bg: 'bg-yellow-500', border: 'border-yellow-400', text: 'text-yellow-500' },
|
||||
teal: { bg: 'bg-teal-600', border: 'border-teal-400', text: 'text-teal-500' },
|
||||
purple: { bg: 'bg-purple-600', border: 'border-purple-400', text: 'text-purple-500' },
|
||||
amber: { bg: 'bg-amber-500', border: 'border-amber-400', text: 'text-amber-500' },
|
||||
gray: { bg: 'bg-gray-600', border: 'border-gray-400', text: 'text-gray-500' },
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Select style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type SelectSize = 'sm' | 'md' | 'lg'
|
||||
export type SelectTheme = 'primary' | 'secondary' | 'success' | 'error' | 'warning' | 'info'
|
||||
export type SelectVariant = 'outlined' | 'filled' | 'standard' | 'underlined'
|
||||
export type SelectWidth = 'full' | 'half' | 'small' | 'xs' | 'large'
|
||||
|
||||
export const SELECT_SIZES: Record<SelectSize, string> = {
|
||||
sm: 'px-3 py-2 text-xs',
|
||||
md: 'px-3 py-2 h-[2.5rem] text-sm',
|
||||
lg: 'px-3 py-3 text-base',
|
||||
}
|
||||
|
||||
export const SELECT_VARIANTS: Record<SelectVariant, string> = {
|
||||
outlined: 'border bg-white',
|
||||
filled: 'border-b bg-gray-100',
|
||||
standard: 'border-b bg-transparent',
|
||||
underlined: 'border-b border-t-0 border-x-0 bg-transparent rounded-none',
|
||||
}
|
||||
|
||||
export const SELECT_WIDTHS: Record<SelectWidth, string> = {
|
||||
full: 'w-full',
|
||||
half: 'w-1/2',
|
||||
small: 'w-48',
|
||||
xs: 'w-24',
|
||||
large: 'w-64',
|
||||
}
|
||||
|
||||
export const LABEL_SIZES: Record<SelectSize, string> = {
|
||||
sm: 'text-[0.7rem] font-medium leading-loose',
|
||||
md: 'text-[0.8rem] font-medium leading-loose',
|
||||
lg: 'text-md',
|
||||
}
|
||||
|
||||
export const FLOATING_LABEL_SIZES: Record<SelectSize, string> = {
|
||||
sm: 'text-[0.6rem] font-medium leading-loose',
|
||||
md: 'text-[0.7rem] font-medium leading-loose',
|
||||
lg: 'text-sm',
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-theme class maps, written out in full.
|
||||
*
|
||||
* The source builds these as template strings — `` `border-${themeColor}-500` `` —
|
||||
* which Tailwind's scanner can never see, so the generated rules are missing and
|
||||
* the themed states render unstyled. Every class here is a literal so it is
|
||||
* picked up at build time.
|
||||
*/
|
||||
|
||||
export type ThemeClasses = {
|
||||
/** Border + ring while focused. */
|
||||
focus: string
|
||||
/** Label text while floated. */
|
||||
label: string
|
||||
/** Search input border while focused. */
|
||||
searchFocus: string
|
||||
/** Selected row in the dropdown. */
|
||||
selected: string
|
||||
/** Hover border on the control. */
|
||||
hover: string
|
||||
}
|
||||
|
||||
export const SELECT_THEME_CLASSES: Record<SelectTheme, ThemeClasses> = {
|
||||
primary: {
|
||||
focus: 'border-primary-500 ring-primary-500',
|
||||
label: 'text-primary-500',
|
||||
searchFocus: 'focus:border-primary-500',
|
||||
selected: 'bg-primary-50 text-primary-600',
|
||||
hover: 'hover:border-primary-500',
|
||||
},
|
||||
secondary: {
|
||||
focus: 'border-purple-500 ring-purple-500',
|
||||
label: 'text-purple-500',
|
||||
searchFocus: 'focus:border-purple-500',
|
||||
selected: 'bg-purple-50 text-purple-600',
|
||||
hover: 'hover:border-purple-500',
|
||||
},
|
||||
success: {
|
||||
focus: 'border-green-500 ring-green-500',
|
||||
label: 'text-green-500',
|
||||
searchFocus: 'focus:border-green-500',
|
||||
selected: 'bg-green-50 text-green-600',
|
||||
hover: 'hover:border-green-500',
|
||||
},
|
||||
error: {
|
||||
focus: 'border-red-500 ring-red-500',
|
||||
label: 'text-red-500',
|
||||
searchFocus: 'focus:border-red-500',
|
||||
selected: 'bg-red-50 text-red-600',
|
||||
hover: 'hover:border-red-500',
|
||||
},
|
||||
warning: {
|
||||
focus: 'border-yellow-500 ring-yellow-500',
|
||||
label: 'text-yellow-500',
|
||||
searchFocus: 'focus:border-yellow-500',
|
||||
selected: 'bg-yellow-50 text-yellow-600',
|
||||
hover: 'hover:border-yellow-500',
|
||||
},
|
||||
info: {
|
||||
focus: 'border-cyan-500 ring-cyan-500',
|
||||
label: 'text-cyan-500',
|
||||
searchFocus: 'focus:border-cyan-500',
|
||||
selected: 'bg-cyan-50 text-cyan-600',
|
||||
hover: 'hover:border-cyan-500',
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Spinner style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type SpinnerSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
|
||||
export type SpinnerVariant = 'primary' | 'secondary' | 'white' | 'success' | 'danger' | 'warning'
|
||||
|
||||
export const SPINNER_SIZES: Record<SpinnerSize, string> = {
|
||||
xs: 'w-4 h-4 border-2',
|
||||
sm: 'w-5 h-5 border-2',
|
||||
md: 'w-8 h-8 border-4',
|
||||
lg: 'w-12 h-12 border-4',
|
||||
xl: 'w-16 h-16 border-4',
|
||||
}
|
||||
|
||||
export const SPINNER_VARIANTS: Record<SpinnerVariant, string> = {
|
||||
primary: 'border-gray-200 border-t-primary-500',
|
||||
secondary: 'border-gray-200 border-t-secondary-500',
|
||||
white: 'border-white/30 border-t-white',
|
||||
success: 'border-green-200 border-t-green-500',
|
||||
danger: 'border-red-200 border-t-red-500',
|
||||
warning: 'border-yellow-200 border-t-yellow-500',
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Switch style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type SwitchSize = 'sm' | 'md' | 'lg'
|
||||
export type SwitchColor = 'blue' | 'red' | 'green' | 'yellow' | 'teal' | 'indigo' | 'purple' | 'pink'
|
||||
|
||||
export type SwitchSizeData = {
|
||||
/** Track pill. */
|
||||
toggle: string
|
||||
/** Knob, including its resting offset from the track edge. */
|
||||
dot: string
|
||||
/** Travel distance of the knob when checked. */
|
||||
translate: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Every knob sits on a fixed 0.25rem inset from the track edge, so it can never
|
||||
* render outside the pill. Travel = trackWidth - knobWidth - (2 * inset).
|
||||
*/
|
||||
export const SWITCH_SIZES: Record<SwitchSize, SwitchSizeData> = {
|
||||
sm: { toggle: 'w-10 h-6 shrink-0', dot: 'w-4 h-4 left-1', translate: 'translate-x-4' },
|
||||
md: { toggle: 'w-12 h-7 shrink-0', dot: 'w-5 h-5 left-1', translate: 'translate-x-5' },
|
||||
lg: { toggle: 'w-[3.75rem] h-8 shrink-0', dot: 'w-6 h-6 left-1', translate: 'translate-x-7' },
|
||||
}
|
||||
|
||||
export const SWITCH_COLORS: Record<SwitchColor, string> = {
|
||||
blue: 'bg-primary-500',
|
||||
red: 'bg-red-500',
|
||||
green: 'bg-green-500',
|
||||
yellow: 'bg-yellow-500',
|
||||
teal: 'bg-teal-500',
|
||||
indigo: 'bg-indigo-500',
|
||||
purple: 'bg-purple-500',
|
||||
pink: 'bg-pink-500',
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* TextArea style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type TextAreaSize = 'sm' | 'md' | 'lg'
|
||||
export type TextAreaTheme = 'primary' | 'secondary' | 'success' | 'error' | 'warning' | 'info'
|
||||
|
||||
export const TEXTAREA_SIZES: Record<TextAreaSize, string> = {
|
||||
sm: 'px-3 py-1 text-xs',
|
||||
md: 'px-4 py-2 text-sm',
|
||||
lg: 'px-5 py-3 text-base',
|
||||
}
|
||||
|
||||
export const LABEL_SIZES: Record<TextAreaSize, string> = {
|
||||
sm: 'text-[0.7rem] font-medium leading-loose',
|
||||
md: 'text-[0.8rem] font-medium leading-loose',
|
||||
lg: 'text-base font-medium leading-loose',
|
||||
}
|
||||
|
||||
/** Type size for the label once it has floated above the border. */
|
||||
export const FLOATING_LABEL_SIZES: Record<TextAreaSize, string> = {
|
||||
sm: 'text-[0.6rem]',
|
||||
md: 'text-[0.65rem]',
|
||||
lg: 'text-xs',
|
||||
}
|
||||
|
||||
export const TEXTAREA_THEMES: Record<TextAreaTheme, string> = {
|
||||
primary: 'focus:border-primary-500 focus:ring-primary-500 border-slate-300',
|
||||
secondary: 'focus:border-purple-500 focus:ring-purple-500 border-slate-300',
|
||||
success: 'focus:border-green-500 focus:ring-green-500 border-slate-300',
|
||||
warning: 'focus:border-yellow-500 focus:ring-yellow-500 border-slate-300',
|
||||
info: 'focus:border-cyan-500 focus:ring-cyan-500 border-slate-300',
|
||||
error: 'focus:border-red-500 focus:ring-red-500 border-red-500',
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra top padding applied to a `featured` TextArea once its label floats.
|
||||
*
|
||||
* Without it the floated label (which sits just above the top border) overlaps
|
||||
* the first line of text. Present as a token so the correction is visible
|
||||
* rather than buried in the class list.
|
||||
*/
|
||||
export const FLOATING_CONTENT_PADDING: Record<TextAreaSize, string> = {
|
||||
sm: 'pt-5',
|
||||
md: 'pt-6',
|
||||
lg: 'pt-7',
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Tooltip style tokens.
|
||||
*
|
||||
* Kept in a separate module from the component so the file only exports
|
||||
* components — mixing the two breaks Vite's fast refresh.
|
||||
*/
|
||||
|
||||
export type TooltipPosition =
|
||||
| 'top'
|
||||
| 'top-start'
|
||||
| 'top-end'
|
||||
| 'bottom'
|
||||
| 'bottom-start'
|
||||
| 'bottom-end'
|
||||
| 'left'
|
||||
| 'left-start'
|
||||
| 'left-end'
|
||||
| 'right'
|
||||
| 'right-start'
|
||||
| 'right-end'
|
||||
|
||||
export type TooltipTheme =
|
||||
| 'custom'
|
||||
| 'soft'
|
||||
| 'primary'
|
||||
| 'success'
|
||||
| 'danger'
|
||||
| 'warning'
|
||||
| 'info'
|
||||
| 'light'
|
||||
| 'dark'
|
||||
| 'gradient'
|
||||
|
||||
export type TooltipSize = 'sm' | 'md' | 'lg'
|
||||
|
||||
export const TOOLTIP_COLORS: Record<TooltipTheme, string> = {
|
||||
custom: 'text-white bg-primary-600',
|
||||
soft: 'bg-primary-200 text-primary-900',
|
||||
primary: 'bg-primary-500 text-white',
|
||||
success: 'bg-green-500 text-white',
|
||||
danger: 'bg-red-500 text-white',
|
||||
warning: 'bg-yellow-500 text-white',
|
||||
info: 'bg-cyan-500 text-white',
|
||||
light: 'bg-gray-200 text-gray-900 border-2',
|
||||
dark: 'bg-gray-800 text-white',
|
||||
gradient: 'bg-gradient-to-b from-purple-400 to-red-500 text-white',
|
||||
}
|
||||
|
||||
type ArrowSet = Record<TooltipTheme, string>
|
||||
|
||||
const topArrows: ArrowSet = {
|
||||
custom: 'border-t-primary-600',
|
||||
soft: 'border-t-primary-200',
|
||||
primary: 'border-t-primary-500',
|
||||
success: 'border-t-green-500',
|
||||
danger: 'border-t-red-500',
|
||||
warning: 'border-t-yellow-500',
|
||||
info: 'border-t-cyan-500',
|
||||
light: 'border-t-gray-200',
|
||||
dark: 'border-t-gray-800',
|
||||
gradient: 'border-t-red-500',
|
||||
}
|
||||
|
||||
const bottomArrows: ArrowSet = {
|
||||
custom: 'border-b-primary-600',
|
||||
soft: 'border-b-primary-200',
|
||||
primary: 'border-b-primary-500',
|
||||
success: 'border-b-green-500',
|
||||
danger: 'border-b-red-500',
|
||||
warning: 'border-b-yellow-500',
|
||||
info: 'border-b-cyan-500',
|
||||
light: 'border-b-gray-200',
|
||||
dark: 'border-b-gray-800',
|
||||
gradient: 'border-b-purple-400',
|
||||
}
|
||||
|
||||
const rightArrows: ArrowSet = {
|
||||
custom: 'border-r-primary-600',
|
||||
soft: 'border-r-primary-200',
|
||||
primary: 'border-r-primary-500',
|
||||
success: 'border-r-green-500',
|
||||
danger: 'border-r-red-500',
|
||||
warning: 'border-r-yellow-500',
|
||||
info: 'border-r-cyan-500',
|
||||
light: 'border-r-gray-200',
|
||||
dark: 'border-r-gray-800',
|
||||
gradient: 'border-r-red-500',
|
||||
}
|
||||
|
||||
const leftArrows: ArrowSet = {
|
||||
custom: 'border-l-primary-600',
|
||||
soft: 'border-l-primary-200',
|
||||
primary: 'border-l-primary-500',
|
||||
success: 'border-l-green-500',
|
||||
danger: 'border-l-red-500',
|
||||
warning: 'border-l-yellow-500',
|
||||
info: 'border-l-cyan-500',
|
||||
light: 'border-l-gray-200',
|
||||
dark: 'border-l-gray-800',
|
||||
gradient: 'border-l-red-500',
|
||||
}
|
||||
|
||||
export const ARROW_POSITION_COLORS: Record<TooltipPosition, ArrowSet> = {
|
||||
top: topArrows,
|
||||
'top-start': topArrows,
|
||||
'top-end': topArrows,
|
||||
bottom: bottomArrows,
|
||||
'bottom-start': bottomArrows,
|
||||
'bottom-end': bottomArrows,
|
||||
right: rightArrows,
|
||||
'right-start': rightArrows,
|
||||
'right-end': rightArrows,
|
||||
left: leftArrows,
|
||||
'left-start': leftArrows,
|
||||
'left-end': leftArrows,
|
||||
}
|
||||
|
||||
export const BASE_ARROW_CLASSES: Record<TooltipPosition, string> = {
|
||||
top: 'absolute left-1/2 bottom-0 -translate-x-1/2 translate-y-full border-l-4 border-r-4 border-t-4 border-transparent',
|
||||
'top-start': 'absolute left-4 bottom-0 translate-y-full border-l-4 border-r-4 border-t-4 border-transparent',
|
||||
'top-end': 'absolute left-4 bottom-0 translate-y-full border-l-4 border-r-4 border-t-4 border-transparent',
|
||||
|
||||
bottom: 'absolute left-1/2 top-0 -translate-x-1/2 -translate-y-full border-l-4 border-r-4 border-b-4 border-transparent',
|
||||
'bottom-start': 'absolute left-4 top-0 -translate-y-full border-l-4 border-r-4 border-b-4 border-transparent',
|
||||
'bottom-end': 'absolute right-4 top-0 -translate-y-full border-l-4 border-r-4 border-b-4 border-transparent',
|
||||
|
||||
left: 'absolute right-0 top-1/2 -translate-y-1/2 translate-x-full border-t-4 border-b-4 border-l-4 border-transparent',
|
||||
'left-start': 'absolute top-4 left-full bottom-2 mr-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
|
||||
'left-end': 'absolute left-full bottom-4 mr-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
|
||||
|
||||
right: 'absolute left-0 top-1/2 -translate-y-1/2 -translate-x-full border-t-4 border-b-4 border-r-4 border-transparent',
|
||||
'right-start': 'absolute right-full top-2 ml-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
|
||||
'right-end': 'absolute right-full bottom-2 ml-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
|
||||
}
|
||||
|
||||
/** Wider arrow used behind rich (node) content. */
|
||||
export const BASE_ARROW_CLASSES_OUTER: Record<TooltipPosition, string> = {
|
||||
top: 'absolute left-1/2 bottom-0 -translate-x-1/2 translate-y-full border-l-8 border-r-8 border-t-8 border-transparent',
|
||||
'top-start': 'absolute left-3 bottom-0 translate-y-full border-l-8 border-r-8 border-t-8 border-transparent',
|
||||
'top-end': 'absolute left-3 bottom-0 translate-y-full border-l-8 border-r-8 border-t-8 border-transparent',
|
||||
|
||||
bottom: 'absolute left-1/2 top-0 -translate-x-1/2 -translate-y-full border-l-8 border-r-8 border-b-8 border-transparent',
|
||||
'bottom-start': 'absolute left-3 top-0 -translate-y-full border-l-8 border-r-8 border-b-8 border-transparent',
|
||||
'bottom-end': 'absolute right-3 top-0 -translate-y-full border-l-8 border-r-8 border-b-8 border-transparent',
|
||||
|
||||
left: 'absolute right-0 top-1/2 -translate-y-1/2 translate-x-full border-t-8 border-b-8 border-l-8 border-transparent',
|
||||
'left-start': 'absolute top-3 left-full bottom-1 mr-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
|
||||
'left-end': 'absolute left-full bottom-3 mr-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
|
||||
|
||||
right: 'absolute left-0 top-1/2 -translate-y-1/2 -translate-x-full border-t-8 border-b-8 border-r-8 border-transparent',
|
||||
'right-start': 'absolute right-full top-1 ml-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
|
||||
'right-end': 'absolute right-full bottom-1 ml-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
|
||||
}
|
||||
|
||||
export const WHITE_BORDER_MAP = {
|
||||
t: 'border-t-white',
|
||||
b: 'border-b-white',
|
||||
l: 'border-l-white',
|
||||
r: 'border-r-white',
|
||||
}
|
||||
|
||||
export const TOOLTIP_SIZES: Record<TooltipSize, string> = {
|
||||
sm: 'text-xs px-2 py-1',
|
||||
md: 'text-sm px-3 py-1.5',
|
||||
lg: 'text-base px-4 py-2',
|
||||
}
|
||||
Reference in new issue
Block a user