components/linyi/textarea.tsx
class-variance-authority
"use client"; import * as React from "react";import { cva, type VariantProps } from "class-variance-authority";import { cn } from "@/lib/cn"; const useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect; export const textareaContainerVariants = cva( [ "flex flex-col w-full rounded-control border transition-colors text-fg", "has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-accent/35 has-[:focus-visible]:border-accent", "has-[:disabled]:opacity-50 has-[:disabled]:cursor-not-allowed", ].join(" "), { variants: { variant: { surface: "bg-surface border-line hover:border-line-strong", well: "bg-well border-line-well hover:border-line-strong", ghost: "bg-transparent border-transparent hover:bg-well/70", }, size: { sm: "text-xs", md: "text-xs", lg: "text-sm", }, invalid: { true: "border-danger hover:border-danger has-[:focus-visible]:border-danger has-[:focus-visible]:ring-danger/30", false: "", }, }, defaultVariants: { variant: "surface", size: "md", invalid: false, }, }); export const textareaFieldVariants = cva( "w-full min-w-0 bg-transparent text-inherit placeholder:text-fg-muted outline-none focus-visible:outline-none disabled:cursor-not-allowed leading-relaxed", { variants: { size: { sm: "px-2.5 py-2", md: "px-3 py-2.5", lg: "px-3.5 py-3", }, resize: { none: "resize-none", vertical: "resize-y", auto: "resize-none", }, }, defaultVariants: { size: "md", resize: "vertical", }, }); export interface TextareaProps extends Omit<React.ComponentPropsWithRef<"textarea">, "size">, VariantProps<typeof textareaContainerVariants> { autoResize?: boolean; minRows?: number; maxRows?: number; showCount?: boolean; resize?: "none" | "vertical" | "auto"; footer?: React.ReactNode; containerClassName?: string;} function mergeRefs<T>(...refs: Array<React.Ref<T> | undefined>) { return (node: T | null) => { for (const ref of refs) { if (!ref) continue; if (typeof ref === "function") { ref(node); } else { (ref as React.MutableRefObject<T | null>).current = node; } } };} export function Textarea({ className, containerClassName, variant = "surface", size = "md", invalid = false, autoResize = false, minRows = 3, maxRows = 8, showCount = false, resize, footer, value, defaultValue, maxLength, rows, disabled, onChange, ref, ...props}: TextareaProps) { const innerRef = React.useRef<HTMLTextAreaElement | null>(null); const [internalCount, setInternalCount] = React.useState(() => defaultValue !== undefined ? String(defaultValue).length : 0 ); const charCount = value !== undefined ? String(value).length : internalCount; const resolvedResize = resize ?? (autoResize ? "none" : "vertical"); const resolvedRows = rows ?? minRows; const syncHeight = React.useCallback(() => { const el = innerRef.current; if (!el || !autoResize) return; const styles = window.getComputedStyle(el); const lineHeight = parseFloat(styles.lineHeight) || 20; const paddingTop = parseFloat(styles.paddingTop) || 0; const paddingBottom = parseFloat(styles.paddingBottom) || 0; const minHeight = lineHeight * minRows + paddingTop + paddingBottom; const maxHeight = lineHeight * maxRows + paddingTop + paddingBottom; el.style.height = "auto"; const nextHeight = Math.min(Math.max(el.scrollHeight, minHeight), maxHeight); el.style.height = `${nextHeight}px`; el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden"; }, [autoResize, minRows, maxRows]); useIsomorphicLayoutEffect(() => { const el = innerRef.current; if (!el) return; if (autoResize) { syncHeight(); } else { el.style.height = ""; el.style.overflowY = ""; } }, [autoResize, syncHeight, value, size, minRows, maxRows]); const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { if (value === undefined) { setInternalCount(event.target.value.length); } if (autoResize) { syncHeight(); } onChange?.(event); }; const hasFooter = Boolean(footer) || showCount; const atLimit = typeof maxLength === "number" && charCount >= maxLength; return ( <div data-invalid={invalid ? "true" : undefined} data-disabled={disabled ? "true" : undefined} className={cn( textareaContainerVariants({ variant, size, invalid }), containerClassName )} > <textarea ref={mergeRefs(innerRef, ref)} rows={resolvedRows} value={value} defaultValue={defaultValue} maxLength={maxLength} disabled={disabled} aria-invalid={invalid || undefined} onChange={handleChange} className={cn( textareaFieldVariants({ size, resize: resolvedResize }), className )} {...props} /> {hasFooter && ( <div className="flex items-center justify-between gap-2 border-t border-line/60 px-3 py-1.5 text-[11px] text-fg-muted"> <div className="min-w-0 flex-1 truncate">{footer}</div> {showCount && ( <span className={cn( "shrink-0 font-mono-num", atLimit && "text-warning font-medium", invalid && "text-danger" )} aria-live="polite" > {typeof maxLength === "number" ? `${charCount} / ${maxLength}` : `${charCount} 字`} </span> )} </div> )} </div> );}