'use client';
// =============================================================================
// Bộ thành phần giao diện dùng chung (Tailwind v4)
// =============================================================================
import React, { createContext, useCallback, useContext, useEffect, useId, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { AlertTriangle, CheckCircle2, Info, Loader2, X, XCircle } from 'lucide-react';
export function cn(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(' ');
}
// -----------------------------------------------------------------------------
// Bố cục
// -----------------------------------------------------------------------------
export function Card({
title,
icon,
actions,
children,
className,
bodyClassName,
}: {
title?: React.ReactNode;
icon?: React.ReactNode;
actions?: React.ReactNode;
children: React.ReactNode;
className?: string;
bodyClassName?: string;
}) {
return (
{(title || actions) && (
{icon}
{title}
{actions && {actions}
}
)}
{children}
);
}
export function PageHeader({ title, description, actions }: { title: string; description?: string; actions?: React.ReactNode }) {
return (
{title}
{description &&
{description}
}
{actions &&
{actions}
}
);
}
// -----------------------------------------------------------------------------
// Nút
// -----------------------------------------------------------------------------
type ButtonVariant = 'primary' | 'secondary' | 'danger' | 'ghost' | 'success';
const buttonStyles: Record = {
primary: 'bg-blue-600 text-white hover:bg-blue-700 shadow-xs',
secondary: 'bg-white text-slate-700 border border-slate-300 hover:bg-slate-50',
danger: 'bg-rose-600 text-white hover:bg-rose-700 shadow-xs',
ghost: 'text-slate-600 hover:bg-slate-100',
success: 'bg-emerald-600 text-white hover:bg-emerald-700 shadow-xs',
};
export function Button({
variant = 'secondary',
size = 'md',
loading,
icon,
className,
children,
disabled,
type = 'button',
...rest
}: React.ButtonHTMLAttributes & {
variant?: ButtonVariant;
size?: 'sm' | 'md';
loading?: boolean;
icon?: React.ReactNode;
}) {
return (
);
}
export function IconButton({
label,
className,
children,
tone = 'default',
...rest
}: React.ButtonHTMLAttributes & { label: string; tone?: 'default' | 'danger' }) {
return (
);
}
// -----------------------------------------------------------------------------
// Ô nhập liệu
// -----------------------------------------------------------------------------
const inputBase =
'w-full rounded-lg border border-slate-300 bg-white px-2.5 py-2 sm:py-1.5 text-base sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500 disabled:bg-slate-50 disabled:text-slate-500';
export function Field({
label,
hint,
error,
children,
className,
htmlFor,
}: {
label?: React.ReactNode;
hint?: React.ReactNode;
error?: string | null;
children: React.ReactNode;
className?: string;
htmlFor?: string;
}) {
return (
{label && (
)}
{children}
{error ?
{error}
: hint ?
{hint}
: null}
);
}
export const TextInput = React.forwardRef>(function TextInput(
{ className, ...rest },
ref
) {
return ;
});
export function Textarea({ className, ...rest }: React.TextareaHTMLAttributes) {
return ;
}
export function Select({ className, children, ...rest }: React.SelectHTMLAttributes) {
return (
);
}
/**
* Ô nhập số: cho phép xoá trắng / gõ dở mà không bị nhảy giá trị.
* Khi rời ô, giá trị được kẹp trong [min, max].
*/
export function NumberInput({
value,
onChange,
min,
max,
step,
suffix,
className,
inputClassName,
id,
disabled,
placeholder,
allowDecimal = true,
}: {
value: number;
onChange: (n: number) => void;
min?: number;
max?: number;
step?: number;
suffix?: string;
className?: string;
inputClassName?: string;
id?: string;
disabled?: boolean;
placeholder?: string;
allowDecimal?: boolean;
}) {
const [draft, setDraft] = useState(null);
const clamp = (n: number) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n));
const parse = (s: string) => Number(s.replace(/\s/g, '').replace(',', '.'));
return (
{
setDraft(Number.isFinite(value) ? String(value) : '');
e.currentTarget.select();
}}
onChange={(e) => {
const s = e.target.value;
if (!/^-?[\d\s]*[.,]?\d*$/.test(s)) return;
setDraft(s);
const n = parse(s);
if (s.trim() !== '' && Number.isFinite(n) && (min === undefined || n >= min) && (max === undefined || n <= max)) {
onChange(allowDecimal ? n : Math.round(n));
}
}}
onBlur={() => {
const n = parse(draft ?? '');
if (draft !== null && draft.trim() !== '' && Number.isFinite(n)) onChange(clamp(allowDecimal ? n : Math.round(n)));
setDraft(null);
}}
onKeyDown={(e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
const delta = (step ?? 1) * (e.key === 'ArrowUp' ? 1 : -1);
const next = clamp((Number.isFinite(value) ? value : 0) + delta);
onChange(next);
setDraft(String(next));
}
if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
}}
className={cn(inputBase, 'tabular-nums', suffix && 'pr-10', inputClassName)}
/>
{suffix && {suffix}}
);
}
export function Checkbox({
checked,
onChange,
label,
description,
disabled,
}: {
checked: boolean;
onChange: (v: boolean) => void;
label: React.ReactNode;
description?: React.ReactNode;
disabled?: boolean;
}) {
const id = useId();
return (
);
}
export function Segmented({
options,
value,
onChange,
className,
size = 'md',
}: {
options: { value: T; label: React.ReactNode; title?: string }[];
value: T;
onChange: (v: T) => void;
className?: string;
size?: 'sm' | 'md';
}) {
return (
{options.map((o) => (
))}
);
}
// -----------------------------------------------------------------------------
// Hiển thị
// -----------------------------------------------------------------------------
type Tone = 'slate' | 'blue' | 'green' | 'amber' | 'red' | 'purple' | 'sky' | 'teal';
const badgeTones: Record = {
slate: 'bg-slate-100 text-slate-700 border-slate-200',
blue: 'bg-blue-50 text-blue-700 border-blue-200',
green: 'bg-emerald-50 text-emerald-700 border-emerald-200',
amber: 'bg-amber-50 text-amber-800 border-amber-200',
red: 'bg-rose-50 text-rose-700 border-rose-200',
purple: 'bg-purple-50 text-purple-700 border-purple-200',
sky: 'bg-sky-50 text-sky-700 border-sky-200',
teal: 'bg-teal-50 text-teal-700 border-teal-200',
};
export function Badge({ tone = 'slate', children, className }: { tone?: Tone; children: React.ReactNode; className?: string }) {
return (
{children}
);
}
export function Spinner({ className }: { className?: string }) {
return ;
}
export function LoadingBlock({ text = 'Đang tải…' }: { text?: string }) {
return (
{text}
);
}
export function EmptyState({ icon, title, description, action }: { icon?: React.ReactNode; title: string; description?: string; action?: React.ReactNode }) {
return (
{icon &&
{icon}
}
{title}
{description &&
{description}
}
{action &&
{action}
}
);
}
export function Alert({
tone = 'info',
title,
children,
className,
}: {
tone?: 'info' | 'warning' | 'error' | 'success';
title?: React.ReactNode;
children?: React.ReactNode;
className?: string;
}) {
const styles = {
info: ['bg-blue-50 border-blue-200 text-blue-900', Info],
warning: ['bg-amber-50 border-amber-200 text-amber-900', AlertTriangle],
error: ['bg-rose-50 border-rose-200 text-rose-900', XCircle],
success: ['bg-emerald-50 border-emerald-200 text-emerald-900', CheckCircle2],
} as const;
const [cls, Icon] = styles[tone];
return (
{title &&
{title}
}
{children &&
{children}
}
);
}
// -----------------------------------------------------------------------------
// Modal
// -----------------------------------------------------------------------------
export function Modal({
open,
onClose,
title,
children,
footer,
size = 'md',
bodyClassName,
}: {
open: boolean;
onClose: () => void;
title?: React.ReactNode;
children: React.ReactNode;
footer?: React.ReactNode;
size?: 'sm' | 'md' | 'lg' | 'xl';
bodyClassName?: string;
}) {
const onCloseRef = useRef(onClose);
useEffect(() => {
onCloseRef.current = onClose;
});
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onCloseRef.current();
document.addEventListener('keydown', onKey);
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.removeEventListener('keydown', onKey);
document.body.style.overflow = prev;
};
}, [open]);
if (!open || typeof document === 'undefined') return null;
const widths = { sm: 'max-w-md', md: 'max-w-xl', lg: 'max-w-3xl', xl: 'max-w-5xl' };
return createPortal(
{title && (
{title}
)}
{children}
{footer && (
{footer}
)}
,
document.body
);
}
// -----------------------------------------------------------------------------
// Thông báo nổi (toast)
// -----------------------------------------------------------------------------
type ToastItem = { id: number; tone: 'success' | 'error' | 'info'; message: string };
const ToastContext = createContext<{ show: (tone: ToastItem['tone'], message: string) => void } | null>(null);
export function ToastProvider({ children }: { children: React.ReactNode }) {
const [items, setItems] = useState([]);
const counter = useRef(0);
const show = useCallback((tone: ToastItem['tone'], message: string) => {
const id = ++counter.current;
setItems((prev) => [...prev, { id, tone, message }]);
setTimeout(() => setItems((prev) => prev.filter((t) => t.id !== id)), tone === 'error' ? 6000 : 3500);
}, []);
return (
{children}
{items.map((t) => (
{t.tone === 'success' ? (
) : t.tone === 'error' ? (
) : (
)}
{t.message}
))}
);
}
export function useToast() {
const ctx = useContext(ToastContext);
return {
success: (m: string) => ctx?.show('success', m),
error: (m: string) => ctx?.show('error', m),
info: (m: string) => ctx?.show('info', m),
};
}
// -----------------------------------------------------------------------------
// Bảng
// -----------------------------------------------------------------------------
export function Table({ children, className }: { children: React.ReactNode; className?: string }) {
return (
);
}
export const th = 'px-3 py-2.5 text-[11px] font-semibold uppercase tracking-wide text-slate-500 bg-slate-50 border-b border-slate-200 whitespace-nowrap';
export const td = 'px-3 py-2.5 border-b border-slate-100 align-middle';