feat(WEB): 입력 컴포넌트 공통화 및 UI 개선
- 숫자/통화/전화번호/사업자번호 등 특수 입력 컴포넌트 추가 - MobileCard 컴포넌트 통합 (ListMobileCard 제거) - IntegratedListTemplateV2 페이지네이션 버그 수정 (NaN 이슈) - IntegratedDetailTemplate 타이틀 중복 수정 - 문서 시스템 컴포넌트 추가 - 헤더 벨 아이콘 포커스 스타일 개선 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
94
src/components/ui/account-number-input.tsx
Normal file
94
src/components/ui/account-number-input.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatAccountNumber, parseAccountNumber } from "@/lib/formatters";
|
||||
|
||||
export interface AccountNumberInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
error?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* AccountNumberInput - 계좌번호 자동 포맷팅 입력 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - 입력 시 4자리마다 자동 하이픈 삽입 (1234-5678-9012-34)
|
||||
* - 숫자만 입력 허용 (최대 16자리)
|
||||
* - onChange에는 숫자만 전달 (DB 저장용)
|
||||
* - 복사/붙여넣기 시 숫자만 추출
|
||||
*
|
||||
* @example
|
||||
* <AccountNumberInput
|
||||
* value={accountNumber}
|
||||
* onChange={setAccountNumber}
|
||||
* placeholder="계좌번호를 입력하세요"
|
||||
* />
|
||||
*/
|
||||
const AccountNumberInput = React.forwardRef<HTMLInputElement, AccountNumberInputProps>(
|
||||
({ className, value, onChange, error, ...props }, ref) => {
|
||||
// 표시용 포맷된 값
|
||||
const displayValue = React.useMemo(() => formatAccountNumber(value || ""), [value]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const inputValue = e.target.value;
|
||||
// 숫자만 추출하여 전달
|
||||
const numbersOnly = parseAccountNumber(inputValue);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// 숫자, 백스페이스, 탭, 화살표, 복사/붙여넣기 허용
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자가 아니면 차단
|
||||
if (!/^\d$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
e.preventDefault();
|
||||
const pastedText = e.clipboardData.getData("text");
|
||||
const numbersOnly = parseAccountNumber(pastedText);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
AccountNumberInput.displayName = "AccountNumberInput";
|
||||
|
||||
export { AccountNumberInput };
|
||||
114
src/components/ui/business-number-input.tsx
Normal file
114
src/components/ui/business-number-input.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatBusinessNumber, parseBusinessNumber, validateBusinessNumber } from "@/lib/formatters";
|
||||
import { CheckCircle, XCircle } from "lucide-react";
|
||||
|
||||
export interface BusinessNumberInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
error?: boolean;
|
||||
showValidation?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* BusinessNumberInput - 사업자번호 자동 포맷팅 입력 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - 입력 시 자동 하이픈 삽입 (000-00-00000)
|
||||
* - 숫자만 입력 허용 (최대 10자리)
|
||||
* - onChange에는 숫자만 전달 (DB 저장용)
|
||||
* - 선택적 유효성 검사 표시
|
||||
*
|
||||
* @example
|
||||
* <BusinessNumberInput
|
||||
* value={businessNumber}
|
||||
* onChange={setBusinessNumber}
|
||||
* showValidation
|
||||
* />
|
||||
*/
|
||||
const BusinessNumberInput = React.forwardRef<HTMLInputElement, BusinessNumberInputProps>(
|
||||
({ className, value, onChange, error, showValidation = false, ...props }, ref) => {
|
||||
// 표시용 포맷된 값
|
||||
const displayValue = React.useMemo(() => formatBusinessNumber(value || ""), [value]);
|
||||
|
||||
// 유효성 검사 결과
|
||||
const isValid = React.useMemo(() => {
|
||||
if (!showValidation || !value || value.length !== 10) return null;
|
||||
return validateBusinessNumber(value);
|
||||
}, [value, showValidation]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const inputValue = e.target.value;
|
||||
// 숫자만 추출하여 전달
|
||||
const numbersOnly = parseBusinessNumber(inputValue);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// 숫자, 백스페이스, 탭, 화살표, 복사/붙여넣기 허용
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자가 아니면 차단
|
||||
if (!/^\d$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
e.preventDefault();
|
||||
const pastedText = e.clipboardData.getData("text");
|
||||
const numbersOnly = parseBusinessNumber(pastedText);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
showValidation && "pr-10",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
{...props}
|
||||
/>
|
||||
{showValidation && isValid !== null && (
|
||||
<div className="absolute right-3 top-1/2 -translate-y-1/2">
|
||||
{isValid ? (
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
BusinessNumberInput.displayName = "BusinessNumberInput";
|
||||
|
||||
export { BusinessNumberInput };
|
||||
94
src/components/ui/card-number-input.tsx
Normal file
94
src/components/ui/card-number-input.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatCardNumber, parseCardNumber } from "@/lib/formatters";
|
||||
|
||||
export interface CardNumberInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
error?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* CardNumberInput - 카드번호 자동 포맷팅 입력 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - 입력 시 자동 하이픈 삽입 (0000-0000-0000-0000)
|
||||
* - 숫자만 입력 허용 (최대 16자리)
|
||||
* - onChange에는 숫자만 전달 (DB 저장용)
|
||||
* - 복사/붙여넣기 시 숫자만 추출
|
||||
*
|
||||
* @example
|
||||
* <CardNumberInput
|
||||
* value={cardNumber}
|
||||
* onChange={setCardNumber}
|
||||
* placeholder="카드번호를 입력하세요"
|
||||
* />
|
||||
*/
|
||||
const CardNumberInput = React.forwardRef<HTMLInputElement, CardNumberInputProps>(
|
||||
({ className, value, onChange, error, ...props }, ref) => {
|
||||
// 표시용 포맷된 값
|
||||
const displayValue = React.useMemo(() => formatCardNumber(value || ""), [value]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const inputValue = e.target.value;
|
||||
// 숫자만 추출하여 전달
|
||||
const numbersOnly = parseCardNumber(inputValue);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// 숫자, 백스페이스, 탭, 화살표, 복사/붙여넣기 허용
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자가 아니면 차단
|
||||
if (!/^\d$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
e.preventDefault();
|
||||
const pastedText = e.clipboardData.getData("text");
|
||||
const numbersOnly = parseCardNumber(pastedText);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
CardNumberInput.displayName = "CardNumberInput";
|
||||
|
||||
export { CardNumberInput };
|
||||
219
src/components/ui/currency-input.tsx
Normal file
219
src/components/ui/currency-input.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatNumber, removeLeadingZeros } from "@/lib/formatters";
|
||||
|
||||
export interface CurrencyInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: number | string | undefined;
|
||||
onChange: (value: number | undefined) => void;
|
||||
error?: boolean;
|
||||
/** 통화 기호 (기본: ₩) */
|
||||
currency?: "₩" | "$" | "¥" | "€";
|
||||
/** 통화 기호 표시 (기본: true) */
|
||||
showCurrency?: boolean;
|
||||
/** 음수 허용 (기본: false) */
|
||||
allowNegative?: boolean;
|
||||
/** 빈 값 허용 (기본: true) */
|
||||
allowEmpty?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* CurrencyInput - 금액 입력 전용 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - 항상 천단위 콤마 표시
|
||||
* - 정수만 허용 (소수점 없음)
|
||||
* - 통화 기호 표시 (₩, $, ¥, €)
|
||||
* - Leading zero 자동 제거
|
||||
*
|
||||
* @example
|
||||
* // 기본 (원화)
|
||||
* <CurrencyInput value={price} onChange={setPrice} />
|
||||
*
|
||||
* // 달러
|
||||
* <CurrencyInput value={usdPrice} onChange={setUsdPrice} currency="$" />
|
||||
*
|
||||
* // 음수 허용 (환불 등)
|
||||
* <CurrencyInput value={refund} onChange={setRefund} allowNegative />
|
||||
*/
|
||||
const CurrencyInput = React.forwardRef<HTMLInputElement, CurrencyInputProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
currency = "₩",
|
||||
showCurrency = true,
|
||||
allowNegative = false,
|
||||
allowEmpty = true,
|
||||
onFocus,
|
||||
onBlur,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [isFocused, setIsFocused] = React.useState(false);
|
||||
const [displayValue, setDisplayValue] = React.useState<string>("");
|
||||
|
||||
// 외부 value 변경 시 displayValue 동기화
|
||||
React.useEffect(() => {
|
||||
if (!isFocused) {
|
||||
if (value === undefined || value === null || value === "") {
|
||||
setDisplayValue("");
|
||||
} else {
|
||||
const numValue = typeof value === "string" ? parseFloat(value) : value;
|
||||
if (!isNaN(numValue)) {
|
||||
setDisplayValue(formatNumber(numValue, { useComma: true }));
|
||||
} else {
|
||||
setDisplayValue("");
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [value, isFocused]);
|
||||
|
||||
// 입력값 정제
|
||||
const sanitizeInput = (input: string): string => {
|
||||
let result = input;
|
||||
|
||||
// 숫자와 음수 기호만 허용
|
||||
if (allowNegative) {
|
||||
result = result.replace(/[^\d\-]/g, "");
|
||||
// 음수 기호는 맨 앞에만
|
||||
if (result.includes("-")) {
|
||||
const isNegative = result.startsWith("-");
|
||||
result = result.replace(/-/g, "");
|
||||
if (isNegative) result = "-" + result;
|
||||
}
|
||||
} else {
|
||||
result = result.replace(/\D/g, "");
|
||||
}
|
||||
|
||||
// Leading zero 제거
|
||||
if (result) {
|
||||
result = removeLeadingZeros(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// 값을 숫자로 변환
|
||||
const parseValue = (input: string): number | undefined => {
|
||||
if (!input || input === "-") {
|
||||
return allowEmpty ? undefined : 0;
|
||||
}
|
||||
|
||||
const num = parseInt(input, 10);
|
||||
return isNaN(num) ? (allowEmpty ? undefined : 0) : num;
|
||||
};
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const rawValue = e.target.value;
|
||||
// 콤마 제거
|
||||
const withoutComma = rawValue.replace(/,/g, "");
|
||||
const sanitized = sanitizeInput(withoutComma);
|
||||
|
||||
setDisplayValue(sanitized);
|
||||
|
||||
// 입력 중 "-"만 있으면 onChange 호출 안함
|
||||
if (sanitized === "-") return;
|
||||
|
||||
const numValue = parseValue(sanitized);
|
||||
onChange(numValue);
|
||||
};
|
||||
|
||||
const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(true);
|
||||
|
||||
// 포커스 시 콤마 제거된 순수 숫자로 표시
|
||||
if (value !== undefined && value !== null && value !== "") {
|
||||
const numValue = typeof value === "string" ? parseFloat(value) : value;
|
||||
if (!isNaN(numValue)) {
|
||||
setDisplayValue(String(Math.floor(numValue)));
|
||||
}
|
||||
}
|
||||
|
||||
onFocus?.(e);
|
||||
};
|
||||
|
||||
const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(false);
|
||||
|
||||
const sanitized = sanitizeInput(displayValue);
|
||||
const numValue = parseValue(sanitized);
|
||||
|
||||
onChange(numValue);
|
||||
|
||||
// 포맷팅된 값으로 표시
|
||||
if (numValue !== undefined) {
|
||||
setDisplayValue(formatNumber(numValue, { useComma: true }));
|
||||
} else {
|
||||
setDisplayValue("");
|
||||
}
|
||||
|
||||
onBlur?.(e);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자 허용
|
||||
if (/^\d$/.test(e.key)) return;
|
||||
|
||||
// 음수 허용 (맨 앞에만)
|
||||
if (allowNegative && e.key === "-" && !displayValue.includes("-")) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
if (input.selectionStart === 0) return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{/* 통화 기호 (왼쪽) */}
|
||||
{showCurrency && (
|
||||
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm pointer-events-none">
|
||||
{currency}
|
||||
</span>
|
||||
)}
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
showCurrency && "pl-8",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
CurrencyInput.displayName = "CurrencyInput";
|
||||
|
||||
export { CurrencyInput };
|
||||
280
src/components/ui/number-input.tsx
Normal file
280
src/components/ui/number-input.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatNumber, removeLeadingZeros } from "@/lib/formatters";
|
||||
|
||||
export interface NumberInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: number | string | undefined;
|
||||
onChange: (value: number | undefined) => void;
|
||||
error?: boolean;
|
||||
/** 소수점 허용 (기본: false) */
|
||||
allowDecimal?: boolean;
|
||||
/** 소수점 자릿수 제한 */
|
||||
decimalPlaces?: number;
|
||||
/** 음수 허용 (기본: false) */
|
||||
allowNegative?: boolean;
|
||||
/** 천단위 콤마 표시 (기본: false, 포커스 해제 시 적용) */
|
||||
useComma?: boolean;
|
||||
/** 접미사 (원, 개, % 등) */
|
||||
suffix?: string;
|
||||
/** 최소값 */
|
||||
min?: number;
|
||||
/** 최대값 */
|
||||
max?: number;
|
||||
/** 빈 값 허용 (기본: true, false면 빈 값 시 0 반환) */
|
||||
allowEmpty?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* NumberInput - 개선된 숫자 입력 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - Leading zero 자동 제거 (01 → 1)
|
||||
* - 소수점 허용/자릿수 제한 옵션
|
||||
* - 음수 허용 옵션
|
||||
* - 천단위 콤마 표시 (포커스 해제 시)
|
||||
* - 접미사 지원 (원, 개, % 등)
|
||||
* - min/max 범위 제한
|
||||
* - onChange에는 항상 number 타입 반환
|
||||
*
|
||||
* @example
|
||||
* // 정수만 (수량)
|
||||
* <NumberInput value={qty} onChange={setQty} />
|
||||
*
|
||||
* // 금액 (천단위 콤마)
|
||||
* <NumberInput value={price} onChange={setPrice} useComma suffix="원" />
|
||||
*
|
||||
* // 소수점 2자리 (비율)
|
||||
* <NumberInput value={rate} onChange={setRate} allowDecimal decimalPlaces={2} />
|
||||
*
|
||||
* // 퍼센트 (0-100 제한)
|
||||
* <NumberInput value={percent} onChange={setPercent} min={0} max={100} suffix="%" />
|
||||
*/
|
||||
const NumberInput = React.forwardRef<HTMLInputElement, NumberInputProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
allowDecimal = false,
|
||||
decimalPlaces,
|
||||
allowNegative = false,
|
||||
useComma = false,
|
||||
suffix,
|
||||
min,
|
||||
max,
|
||||
allowEmpty = true,
|
||||
onFocus,
|
||||
onBlur,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [isFocused, setIsFocused] = React.useState(false);
|
||||
const [displayValue, setDisplayValue] = React.useState<string>("");
|
||||
|
||||
// 외부 value 변경 시 displayValue 동기화
|
||||
React.useEffect(() => {
|
||||
if (!isFocused) {
|
||||
if (value === undefined || value === null || value === "") {
|
||||
setDisplayValue("");
|
||||
} else {
|
||||
const numValue = typeof value === "string" ? parseFloat(value) : value;
|
||||
if (!isNaN(numValue)) {
|
||||
setDisplayValue(
|
||||
formatNumber(numValue, {
|
||||
useComma,
|
||||
decimalPlaces,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
setDisplayValue("");
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [value, isFocused, useComma, decimalPlaces]);
|
||||
|
||||
// 입력값 유효성 검사 및 정제
|
||||
const sanitizeInput = (input: string): string => {
|
||||
let result = input;
|
||||
|
||||
// 허용 문자만 남기기
|
||||
if (allowDecimal && allowNegative) {
|
||||
result = result.replace(/[^\d.\-]/g, "");
|
||||
} else if (allowDecimal) {
|
||||
result = result.replace(/[^\d.]/g, "");
|
||||
} else if (allowNegative) {
|
||||
result = result.replace(/[^\d\-]/g, "");
|
||||
} else {
|
||||
result = result.replace(/\D/g, "");
|
||||
}
|
||||
|
||||
// 음수 기호는 맨 앞에만
|
||||
if (allowNegative && result.includes("-")) {
|
||||
const isNegative = result.startsWith("-");
|
||||
result = result.replace(/-/g, "");
|
||||
if (isNegative) result = "-" + result;
|
||||
}
|
||||
|
||||
// 소수점은 하나만
|
||||
if (allowDecimal && result.includes(".")) {
|
||||
const parts = result.split(".");
|
||||
result = parts[0] + "." + parts.slice(1).join("");
|
||||
|
||||
// 소수점 자릿수 제한
|
||||
if (decimalPlaces !== undefined && parts[1]) {
|
||||
result = parts[0] + "." + parts[1].slice(0, decimalPlaces);
|
||||
}
|
||||
}
|
||||
|
||||
// Leading zero 제거 (소수점 앞 제외)
|
||||
if (result && !result.startsWith("0.") && !result.startsWith("-0.")) {
|
||||
result = removeLeadingZeros(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// 값을 숫자로 변환하고 범위 적용
|
||||
const parseAndClamp = (input: string): number | undefined => {
|
||||
if (!input || input === "-" || input === ".") {
|
||||
return allowEmpty ? undefined : 0;
|
||||
}
|
||||
|
||||
let num = parseFloat(input);
|
||||
|
||||
if (isNaN(num)) {
|
||||
return allowEmpty ? undefined : 0;
|
||||
}
|
||||
|
||||
// 범위 제한
|
||||
if (min !== undefined && num < min) num = min;
|
||||
if (max !== undefined && num > max) num = max;
|
||||
|
||||
return num;
|
||||
};
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const rawValue = e.target.value;
|
||||
|
||||
// 콤마 제거 (붙여넣기 대응)
|
||||
const withoutComma = rawValue.replace(/,/g, "");
|
||||
const sanitized = sanitizeInput(withoutComma);
|
||||
|
||||
setDisplayValue(sanitized);
|
||||
|
||||
// 입력 중에는 "-", ".", "-." 같은 중간 상태 허용
|
||||
if (sanitized === "-" || sanitized === "." || sanitized === "-.") {
|
||||
return;
|
||||
}
|
||||
|
||||
const numValue = parseAndClamp(sanitized);
|
||||
onChange(numValue);
|
||||
};
|
||||
|
||||
const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(true);
|
||||
|
||||
// 포커스 시 콤마 제거된 순수 숫자로 표시
|
||||
if (value !== undefined && value !== null && value !== "") {
|
||||
const numValue = typeof value === "string" ? parseFloat(value) : value;
|
||||
if (!isNaN(numValue)) {
|
||||
setDisplayValue(String(numValue));
|
||||
}
|
||||
}
|
||||
|
||||
onFocus?.(e);
|
||||
};
|
||||
|
||||
const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(false);
|
||||
|
||||
// 블러 시 최종 값 정리 및 포맷팅
|
||||
const sanitized = sanitizeInput(displayValue);
|
||||
const numValue = parseAndClamp(sanitized);
|
||||
|
||||
onChange(numValue);
|
||||
|
||||
// 포맷팅된 값으로 표시
|
||||
if (numValue !== undefined) {
|
||||
setDisplayValue(
|
||||
formatNumber(numValue, {
|
||||
useComma,
|
||||
decimalPlaces,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
setDisplayValue("");
|
||||
}
|
||||
|
||||
onBlur?.(e);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// 허용되는 키들
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자 허용
|
||||
if (/^\d$/.test(e.key)) return;
|
||||
|
||||
// 소수점 허용 (한 번만)
|
||||
if (allowDecimal && e.key === "." && !displayValue.includes(".")) return;
|
||||
|
||||
// 음수 허용 (맨 앞에만)
|
||||
if (allowNegative && e.key === "-" && !displayValue.includes("-")) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
if (input.selectionStart === 0) return;
|
||||
}
|
||||
|
||||
// 그 외 차단
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
inputMode={allowDecimal ? "decimal" : "numeric"}
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
suffix && "pr-10",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
{...props}
|
||||
/>
|
||||
{suffix && !isFocused && displayValue && (
|
||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm pointer-events-none">
|
||||
{suffix}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
NumberInput.displayName = "NumberInput";
|
||||
|
||||
export { NumberInput };
|
||||
100
src/components/ui/personal-number-input.tsx
Normal file
100
src/components/ui/personal-number-input.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatPersonalNumber, formatPersonalNumberMasked, parsePersonalNumber } from "@/lib/formatters";
|
||||
|
||||
export interface PersonalNumberInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
error?: boolean;
|
||||
maskBack?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* PersonalNumberInput - 주민번호 자동 포맷팅 입력 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - 입력 시 자동 하이픈 삽입 (000000-0000000)
|
||||
* - 숫자만 입력 허용 (최대 13자리)
|
||||
* - onChange에는 숫자만 전달 (DB 저장용)
|
||||
* - 뒷자리 마스킹 옵션 (000000-*******)
|
||||
*
|
||||
* @example
|
||||
* <PersonalNumberInput
|
||||
* value={personalNumber}
|
||||
* onChange={setPersonalNumber}
|
||||
* maskBack
|
||||
* />
|
||||
*/
|
||||
const PersonalNumberInput = React.forwardRef<HTMLInputElement, PersonalNumberInputProps>(
|
||||
({ className, value, onChange, error, maskBack = false, ...props }, ref) => {
|
||||
// 표시용 포맷된 값
|
||||
const displayValue = React.useMemo(() => {
|
||||
if (!value) return "";
|
||||
return maskBack
|
||||
? formatPersonalNumberMasked(value)
|
||||
: formatPersonalNumber(value);
|
||||
}, [value, maskBack]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const inputValue = e.target.value;
|
||||
// 숫자만 추출하여 전달
|
||||
const numbersOnly = parsePersonalNumber(inputValue);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// 숫자, 백스페이스, 탭, 화살표, 복사/붙여넣기 허용
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자가 아니면 차단
|
||||
if (!/^\d$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
e.preventDefault();
|
||||
const pastedText = e.clipboardData.getData("text");
|
||||
const numbersOnly = parsePersonalNumber(pastedText);
|
||||
onChange(numbersOnly);
|
||||
};
|
||||
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
PersonalNumberInput.displayName = "PersonalNumberInput";
|
||||
|
||||
export { PersonalNumberInput };
|
||||
95
src/components/ui/phone-input.tsx
Normal file
95
src/components/ui/phone-input.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatPhoneNumber, parsePhoneNumber } from "@/lib/formatters";
|
||||
|
||||
export interface PhoneInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
error?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* PhoneInput - 전화번호 자동 포맷팅 입력 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - 입력 시 자동 하이픈 삽입 (010-1234-5678)
|
||||
* - 숫자만 입력 허용
|
||||
* - onChange에는 숫자만 전달 (DB 저장용)
|
||||
* - 복사/붙여넣기 시 숫자만 추출
|
||||
*
|
||||
* @example
|
||||
* <PhoneInput
|
||||
* value={phoneNumber}
|
||||
* onChange={setPhoneNumber}
|
||||
* placeholder="전화번호를 입력하세요"
|
||||
* />
|
||||
*/
|
||||
const PhoneInput = React.forwardRef<HTMLInputElement, PhoneInputProps>(
|
||||
({ className, value, onChange, error, ...props }, ref) => {
|
||||
// 표시용 포맷된 값
|
||||
const displayValue = React.useMemo(() => formatPhoneNumber(value || ""), [value]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const inputValue = e.target.value;
|
||||
// 숫자만 추출하여 전달
|
||||
const numbersOnly = parsePhoneNumber(inputValue);
|
||||
// 최대 11자리 (휴대폰 번호 기준)
|
||||
onChange(numbersOnly.slice(0, 11));
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// 숫자, 백스페이스, 탭, 화살표, 복사/붙여넣기 허용
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자가 아니면 차단
|
||||
if (!/^\d$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
e.preventDefault();
|
||||
const pastedText = e.clipboardData.getData("text");
|
||||
const numbersOnly = parsePhoneNumber(pastedText);
|
||||
onChange(numbersOnly.slice(0, 11));
|
||||
};
|
||||
|
||||
return (
|
||||
<input
|
||||
type="tel"
|
||||
inputMode="numeric"
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
PhoneInput.displayName = "PhoneInput";
|
||||
|
||||
export { PhoneInput };
|
||||
268
src/components/ui/quantity-input.tsx
Normal file
268
src/components/ui/quantity-input.tsx
Normal file
@@ -0,0 +1,268 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { removeLeadingZeros } from "@/lib/formatters";
|
||||
import { Minus, Plus } from "lucide-react";
|
||||
|
||||
export interface QuantityInputProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
|
||||
value: number | string | undefined;
|
||||
onChange: (value: number | undefined) => void;
|
||||
error?: boolean;
|
||||
/** 최소값 (기본: 0) */
|
||||
min?: number;
|
||||
/** 최대값 */
|
||||
max?: number;
|
||||
/** 증감 단위 (기본: 1) */
|
||||
step?: number;
|
||||
/** +/- 버튼 표시 (기본: false) */
|
||||
showButtons?: boolean;
|
||||
/** 단위 접미사 (개, EA, 박스 등) */
|
||||
suffix?: string;
|
||||
/** 빈 값 허용 (기본: true) */
|
||||
allowEmpty?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* QuantityInput - 수량 입력 전용 컴포넌트
|
||||
*
|
||||
* 특징:
|
||||
* - 정수만 허용
|
||||
* - 기본 최소값 0 (음수 불가)
|
||||
* - 선택적 +/- 버튼
|
||||
* - 단위 접미사 지원
|
||||
* - Leading zero 자동 제거
|
||||
*
|
||||
* @example
|
||||
* // 기본
|
||||
* <QuantityInput value={qty} onChange={setQty} />
|
||||
*
|
||||
* // +/- 버튼 포함
|
||||
* <QuantityInput value={qty} onChange={setQty} showButtons />
|
||||
*
|
||||
* // 단위 표시
|
||||
* <QuantityInput value={qty} onChange={setQty} suffix="개" />
|
||||
*
|
||||
* // 범위 제한
|
||||
* <QuantityInput value={qty} onChange={setQty} min={1} max={100} />
|
||||
*/
|
||||
const QuantityInput = React.forwardRef<HTMLInputElement, QuantityInputProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
min = 0,
|
||||
max,
|
||||
step = 1,
|
||||
showButtons = false,
|
||||
suffix,
|
||||
allowEmpty = true,
|
||||
disabled,
|
||||
onFocus,
|
||||
onBlur,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [isFocused, setIsFocused] = React.useState(false);
|
||||
const [displayValue, setDisplayValue] = React.useState<string>("");
|
||||
|
||||
// 외부 value 변경 시 displayValue 동기화
|
||||
React.useEffect(() => {
|
||||
if (!isFocused) {
|
||||
if (value === undefined || value === null || value === "") {
|
||||
setDisplayValue("");
|
||||
} else {
|
||||
const numValue = typeof value === "string" ? parseInt(value, 10) : Math.floor(value);
|
||||
if (!isNaN(numValue)) {
|
||||
setDisplayValue(String(numValue));
|
||||
} else {
|
||||
setDisplayValue("");
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [value, isFocused]);
|
||||
|
||||
// 값 클램핑
|
||||
const clampValue = (num: number): number => {
|
||||
let result = num;
|
||||
if (min !== undefined && result < min) result = min;
|
||||
if (max !== undefined && result > max) result = max;
|
||||
return result;
|
||||
};
|
||||
|
||||
// 입력값 정제
|
||||
const sanitizeInput = (input: string): string => {
|
||||
// 숫자만 허용
|
||||
let result = input.replace(/\D/g, "");
|
||||
// Leading zero 제거
|
||||
if (result) {
|
||||
result = removeLeadingZeros(result);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// 값을 숫자로 변환
|
||||
const parseValue = (input: string): number | undefined => {
|
||||
if (!input) {
|
||||
return allowEmpty ? undefined : min;
|
||||
}
|
||||
|
||||
const num = parseInt(input, 10);
|
||||
if (isNaN(num)) {
|
||||
return allowEmpty ? undefined : min;
|
||||
}
|
||||
|
||||
return clampValue(num);
|
||||
};
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const rawValue = e.target.value;
|
||||
const sanitized = sanitizeInput(rawValue);
|
||||
|
||||
setDisplayValue(sanitized);
|
||||
|
||||
const numValue = parseValue(sanitized);
|
||||
onChange(numValue);
|
||||
};
|
||||
|
||||
const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(true);
|
||||
onFocus?.(e);
|
||||
};
|
||||
|
||||
const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
setIsFocused(false);
|
||||
|
||||
const sanitized = sanitizeInput(displayValue);
|
||||
const numValue = parseValue(sanitized);
|
||||
|
||||
onChange(numValue);
|
||||
|
||||
if (numValue !== undefined) {
|
||||
setDisplayValue(String(numValue));
|
||||
} else {
|
||||
setDisplayValue("");
|
||||
}
|
||||
|
||||
onBlur?.(e);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
const allowedKeys = [
|
||||
"Backspace", "Delete", "Tab", "Escape", "Enter",
|
||||
"ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
|
||||
"Home", "End"
|
||||
];
|
||||
|
||||
if (allowedKeys.includes(e.key)) return;
|
||||
|
||||
// Ctrl/Cmd + A, C, V, X 허용
|
||||
if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 숫자만 허용
|
||||
if (/^\d$/.test(e.key)) return;
|
||||
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
// +/- 버튼 핸들러
|
||||
const handleIncrement = () => {
|
||||
if (disabled) return;
|
||||
const currentValue = value !== undefined && value !== null && value !== ""
|
||||
? (typeof value === "string" ? parseInt(value, 10) : Math.floor(value))
|
||||
: min;
|
||||
const newValue = clampValue((isNaN(currentValue) ? min : currentValue) + step);
|
||||
onChange(newValue);
|
||||
};
|
||||
|
||||
const handleDecrement = () => {
|
||||
if (disabled) return;
|
||||
const currentValue = value !== undefined && value !== null && value !== ""
|
||||
? (typeof value === "string" ? parseInt(value, 10) : Math.floor(value))
|
||||
: min;
|
||||
const newValue = clampValue((isNaN(currentValue) ? min : currentValue) - step);
|
||||
onChange(newValue);
|
||||
};
|
||||
|
||||
const isAtMin = value !== undefined && typeof value === "number" && value <= min;
|
||||
const isAtMax = max !== undefined && value !== undefined && typeof value === "number" && value >= max;
|
||||
|
||||
return (
|
||||
<div className={cn("relative flex items-center", showButtons && "gap-1")}>
|
||||
{/* 감소 버튼 */}
|
||||
{showButtons && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDecrement}
|
||||
disabled={disabled || isAtMin}
|
||||
className={cn(
|
||||
"flex h-9 w-9 items-center justify-center rounded-md border border-input bg-background text-sm font-medium transition-colors",
|
||||
"hover:bg-accent hover:text-accent-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
"disabled:pointer-events-none disabled:opacity-50"
|
||||
)}
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="relative flex-1">
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
ref={ref}
|
||||
data-slot="input"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
|
||||
showButtons && "text-center",
|
||||
suffix && !showButtons && "pr-10",
|
||||
className
|
||||
)}
|
||||
value={displayValue}
|
||||
onChange={handleChange}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
{...props}
|
||||
/>
|
||||
{/* 접미사 (버튼 없을 때만) */}
|
||||
{suffix && !showButtons && !isFocused && displayValue && (
|
||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm pointer-events-none">
|
||||
{suffix}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 증가 버튼 */}
|
||||
{showButtons && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleIncrement}
|
||||
disabled={disabled || isAtMax}
|
||||
className={cn(
|
||||
"flex h-9 w-9 items-center justify-center rounded-md border border-input bg-background text-sm font-medium transition-colors",
|
||||
"hover:bg-accent hover:text-accent-foreground",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
|
||||
"disabled:pointer-events-none disabled:opacity-50"
|
||||
)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
QuantityInput.displayName = "QuantityInput";
|
||||
|
||||
export { QuantityInput };
|
||||
Reference in New Issue
Block a user