diff --git a/frontend/lib/registry/components/modal-repeater-table/ModalRepeaterTableComponent.tsx b/frontend/lib/registry/components/modal-repeater-table/ModalRepeaterTableComponent.tsx index 6177f647..c7d7c8b6 100644 --- a/frontend/lib/registry/components/modal-repeater-table/ModalRepeaterTableComponent.tsx +++ b/frontend/lib/registry/components/modal-repeater-table/ModalRepeaterTableComponent.tsx @@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react"; import { Button } from "@/components/ui/button"; -import { Plus } from "lucide-react"; +import { Plus, Columns } from "lucide-react"; import { ItemSelectionModal } from "./ItemSelectionModal"; import { RepeaterTable } from "./RepeaterTable"; import { ModalRepeaterTableProps, RepeaterColumnConfig, JoinCondition, DynamicDataSourceOption } from "./types"; @@ -331,6 +331,9 @@ export function ModalRepeaterTableComponent({ // 체크박스 선택 상태 const [selectedRows, setSelectedRows] = useState>(new Set()); + // 균등 분배 트리거 (값이 변경되면 RepeaterTable에서 균등 분배 실행) + const [equalizeWidthsTrigger, setEqualizeWidthsTrigger] = useState(0); + // 🆕 납기일 일괄 적용 플래그 (딱 한 번만 실행) const [isDeliveryDateApplied, setIsDeliveryDateApplied] = useState(false); @@ -820,9 +823,23 @@ export function ModalRepeaterTableComponent({
{/* 추가 버튼 */}
-
- {localValue.length > 0 && `${localValue.length}개 항목`} - {selectedRows.size > 0 && ` (${selectedRows.size}개 선택됨)`} +
+ + {localValue.length > 0 && `${localValue.length}개 항목`} + {selectedRows.size > 0 && ` (${selectedRows.size}개 선택됨)`} + + {columns.length > 0 && ( + + )}
{selectedRows.size > 0 && ( @@ -855,6 +872,7 @@ export function ModalRepeaterTableComponent({ onDataSourceChange={handleDataSourceChange} selectedRows={selectedRows} onSelectionChange={setSelectedRows} + equalizeWidthsTrigger={equalizeWidthsTrigger} /> {/* 항목 선택 모달 */} diff --git a/frontend/lib/registry/components/modal-repeater-table/RepeaterTable.tsx b/frontend/lib/registry/components/modal-repeater-table/RepeaterTable.tsx index 1badecf9..4d6c9086 100644 --- a/frontend/lib/registry/components/modal-repeater-table/RepeaterTable.tsx +++ b/frontend/lib/registry/components/modal-repeater-table/RepeaterTable.tsx @@ -1,14 +1,68 @@ "use client"; -import React, { useState, useEffect } from "react"; +import React, { useState, useEffect, useRef } from "react"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; -import { ChevronDown, Check } from "lucide-react"; +import { ChevronDown, Check, GripVertical } from "lucide-react"; import { Checkbox } from "@/components/ui/checkbox"; import { RepeaterColumnConfig } from "./types"; import { cn } from "@/lib/utils"; +// @dnd-kit imports +import { + DndContext, + closestCenter, + KeyboardSensor, + PointerSensor, + useSensor, + useSensors, + DragEndEvent, +} from "@dnd-kit/core"; +import { + SortableContext, + sortableKeyboardCoordinates, + verticalListSortingStrategy, + useSortable, + arrayMove, +} from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; + +// SortableRow 컴포넌트 - 드래그 가능한 테이블 행 +interface SortableRowProps { + id: string; + children: (props: { + attributes: React.HTMLAttributes; + listeners: React.HTMLAttributes | undefined; + isDragging: boolean; + }) => React.ReactNode; + className?: string; +} + +function SortableRow({ id, children, className }: SortableRowProps) { + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id }); + + const style: React.CSSProperties = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.5 : 1, + backgroundColor: isDragging ? "#f0f9ff" : undefined, + }; + + return ( + + {children({ attributes, listeners, isDragging })} + + ); +} + interface RepeaterTableProps { columns: RepeaterColumnConfig[]; data: any[]; @@ -21,6 +75,8 @@ interface RepeaterTableProps { // 체크박스 선택 관련 selectedRows: Set; // 선택된 행 인덱스 onSelectionChange: (selectedRows: Set) => void; // 선택 변경 콜백 + // 균등 분배 트리거 + equalizeWidthsTrigger?: number; // 값이 변경되면 균등 분배 실행 } export function RepeaterTable({ @@ -33,7 +89,58 @@ export function RepeaterTable({ onDataSourceChange, selectedRows, onSelectionChange, + equalizeWidthsTrigger, }: RepeaterTableProps) { + // 컨테이너 ref - 실제 너비 측정용 + const containerRef = useRef(null); + + // 균등 분배 모드 상태 (true일 때 테이블이 컨테이너에 맞춤) + const [isEqualizedMode, setIsEqualizedMode] = useState(false); + + // DnD 센서 설정 + const sensors = useSensors( + useSensor(PointerSensor, { + activationConstraint: { + distance: 8, // 8px 이동해야 드래그 시작 (클릭과 구분) + }, + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates, + }) + ); + + // 드래그 종료 핸들러 + const handleDragEnd = (event: DragEndEvent) => { + const { active, over } = event; + + if (over && active.id !== over.id) { + const oldIndex = data.findIndex((_, idx) => `row-${idx}` === active.id); + const newIndex = data.findIndex((_, idx) => `row-${idx}` === over.id); + + if (oldIndex !== -1 && newIndex !== -1) { + const newData = arrayMove(data, oldIndex, newIndex); + onDataChange(newData); + + // 선택된 행 인덱스도 업데이트 + if (selectedRows.size > 0) { + const newSelectedRows = new Set(); + selectedRows.forEach((oldIdx) => { + if (oldIdx === oldIndex) { + newSelectedRows.add(newIndex); + } else if (oldIdx > oldIndex && oldIdx <= newIndex) { + newSelectedRows.add(oldIdx - 1); + } else if (oldIdx < oldIndex && oldIdx >= newIndex) { + newSelectedRows.add(oldIdx + 1); + } else { + newSelectedRows.add(oldIdx); + } + }); + onSelectionChange(newSelectedRows); + } + } + } + }; + const [editingCell, setEditingCell] = useState<{ rowIndex: number; field: string; @@ -71,15 +178,100 @@ export function RepeaterTable({ startX: e.clientX, startWidth: columnWidths[field] || 120, }); + // 수동 조정 시 균등 분배 모드 해제 + setIsEqualizedMode(false); }; - // 더블클릭으로 기본 너비로 리셋 - const handleDoubleClick = (field: string) => { - setColumnWidths((prev) => ({ - ...prev, - [field]: defaultWidths[field] || 120, - })); + // 컬럼 확장 상태 추적 (토글용) + const [expandedColumns, setExpandedColumns] = useState>(new Set()); + + // 데이터 기준 최적 너비 계산 + const calculateAutoFitWidth = (field: string): number => { + const column = columns.find(col => col.field === field); + if (!column) return 120; + + // 헤더 텍스트 길이 (대략 8px per character + padding) + const headerWidth = (column.label?.length || field.length) * 8 + 40; + + // 데이터 중 가장 긴 텍스트 찾기 + let maxDataWidth = 0; + data.forEach(row => { + const value = row[field]; + if (value !== undefined && value !== null) { + let displayText = String(value); + + // 숫자는 천단위 구분자 포함 + if (typeof value === 'number') { + displayText = value.toLocaleString(); + } + // 날짜는 yyyy-mm-dd 형식 + if (column.type === 'date' && displayText.includes('T')) { + displayText = displayText.split('T')[0]; + } + + // 대략적인 너비 계산 (8px per character + padding) + const textWidth = displayText.length * 8 + 32; + maxDataWidth = Math.max(maxDataWidth, textWidth); + } + }); + + // 헤더와 데이터 중 큰 값 사용, 최소 60px, 최대 400px + const optimalWidth = Math.max(headerWidth, maxDataWidth); + return Math.min(Math.max(optimalWidth, 60), 400); }; + + // 더블클릭으로 auto-fit / 기본 너비 토글 + const handleDoubleClick = (field: string) => { + // 개별 컬럼 조정 시 균등 분배 모드 해제 + setIsEqualizedMode(false); + + setExpandedColumns(prev => { + const newSet = new Set(prev); + if (newSet.has(field)) { + // 확장 상태 → 기본 너비로 복구 + newSet.delete(field); + setColumnWidths(prevWidths => ({ + ...prevWidths, + [field]: defaultWidths[field] || 120, + })); + } else { + // 기본 상태 → 데이터 기준 auto-fit + newSet.add(field); + const autoWidth = calculateAutoFitWidth(field); + setColumnWidths(prevWidths => ({ + ...prevWidths, + [field]: autoWidth, + })); + } + return newSet; + }); + }; + + // 균등 분배 트리거 감지 + useEffect(() => { + if (equalizeWidthsTrigger === undefined || equalizeWidthsTrigger === 0) return; + if (!containerRef.current) return; + + // 실제 컨테이너 너비 측정 + const containerWidth = containerRef.current.offsetWidth; + + // 체크박스 컬럼 너비(40px) + 테이블 border(2px) 제외한 가용 너비 계산 + const checkboxColumnWidth = 40; + const borderWidth = 2; + const availableWidth = containerWidth - checkboxColumnWidth - borderWidth; + + // 컬럼 수로 나눠서 균등 분배 (최소 60px 보장) + const equalWidth = Math.max(60, Math.floor(availableWidth / columns.length)); + + const newWidths: Record = {}; + columns.forEach((col) => { + newWidths[col.field] = equalWidth; + }); + + setColumnWidths(newWidths); + setExpandedColumns(new Set()); // 확장 상태 초기화 + setIsEqualizedMode(true); // 균등 분배 모드 활성화 + }, [equalizeWidthsTrigger, columns]); useEffect(() => { if (!resizing) return; @@ -176,7 +368,7 @@ export function RepeaterTable({ onChange={(e) => handleCellEdit(rowIndex, column.field, parseFloat(e.target.value) || 0) } - className="h-8 text-xs border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-none" + className="h-8 text-xs border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-none min-w-0 w-full" /> ); @@ -204,7 +396,7 @@ export function RepeaterTable({ type="date" value={formatDateValue(value)} onChange={(e) => handleCellEdit(rowIndex, column.field, e.target.value)} - className="h-8 text-xs border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-none" + className="h-8 text-xs border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-none min-w-0 w-full" /> ); @@ -216,7 +408,7 @@ export function RepeaterTable({ handleCellEdit(rowIndex, column.field, newValue) } > - + @@ -235,30 +427,49 @@ export function RepeaterTable({ type="text" value={value || ""} onChange={(e) => handleCellEdit(rowIndex, column.field, e.target.value)} - className="h-8 text-xs border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-none" + className="h-8 text-xs border-gray-200 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-none min-w-0 w-full" /> ); } }; + // 드래그 아이템 ID 목록 + const sortableItems = data.map((_, idx) => `row-${idx}`); + return ( -
-
- - - - + +
+
+
- -
+ + + {/* 드래그 핸들 헤더 */} + + {/* 체크박스 헤더 */} + {columns.map((col) => { const hasDynamicSource = col.dynamicDataSource?.enabled && col.dynamicDataSource.options.length > 0; const activeOptionId = activeDataSources[col.field] || col.dynamicDataSource?.defaultOptionId; @@ -266,13 +477,15 @@ export function RepeaterTable({ ? col.dynamicDataSource!.options.find(opt => opt.id === activeOptionId) || col.dynamicDataSource!.options[0] : null; + const isExpanded = expandedColumns.has(col.field); + return ( ); })} - - - - {data.length === 0 ? ( - - - ) : ( - data.map((row, rowIndex) => ( - - - {columns.map((col) => ( - + {data.length === 0 ? ( + + - ))} - - )) - )} - -
+ 순서 + + + handleDoubleClick(col.field)} - title="더블클릭하여 기본 너비로 되돌리기" + title={isExpanded ? "더블클릭하여 기본 너비로 복구" : "더블클릭하여 내용에 맞게 확장"} >
@@ -344,46 +557,74 @@ export function RepeaterTable({
- 추가된 항목이 없습니다 -
- handleRowSelect(rowIndex, !!checked)} - className="border-gray-400" - /> - - {renderCell(row, col, rowIndex)} + + +
+ 추가된 항목이 없습니다
+ + ) : ( + data.map((row, rowIndex) => ( + + {({ attributes, listeners, isDragging }) => ( + <> + {/* 드래그 핸들 */} + + + + {/* 체크박스 */} + + handleRowSelect(rowIndex, !!checked)} + className="border-gray-400" + /> + + {/* 데이터 컬럼들 */} + {columns.map((col) => ( + + {renderCell(row, col, rowIndex)} + + ))} + + )} + + )) + )} + + + +
-
+ ); }