import { Box, Button, Fade, Flex, IconButton, SlideFade, Stack, } from '@chakra-ui/react' import { TrashIcon, PlusIcon } from '@/components/icons' import { createId } from '@paralleldrive/cuid2' import React, { useState } from 'react' type ItemWithId = T & { id: string } export type TableListItemProps = { item: T onItemChange: (item: T) => void } type Props = { initialItems: ItemWithId[] isOrdered?: boolean addLabel?: string Item: (props: TableListItemProps) => JSX.Element ComponentBetweenItems?: (props: unknown) => JSX.Element onItemsChange: (items: ItemWithId[]) => void } export const TableList = ({ initialItems, isOrdered, addLabel = 'Add', Item, ComponentBetweenItems, onItemsChange, }: Props) => { const [items, setItems] = useState(initialItems) const [showDeleteIndex, setShowDeleteIndex] = useState(null) const createItem = () => { const id = createId() const newItem = { id } as ItemWithId setItems([...items, newItem]) onItemsChange([...items, newItem]) } const insertItem = (itemIndex: number) => () => { const id = createId() const newItem = { id } as ItemWithId const newItems = [...items] newItems.splice(itemIndex + 1, 0, newItem) setItems(newItems) onItemsChange(newItems) } const updateItem = (itemIndex: number, updates: Partial) => { const newItems = items.map((item, idx) => idx === itemIndex ? { ...item, ...updates } : item ) setItems(newItems) onItemsChange(newItems) } const deleteItem = (itemIndex: number) => () => { const newItems = [...items] newItems.splice(itemIndex, 1) setItems([...newItems]) onItemsChange([...newItems]) } const handleMouseEnter = (itemIndex: number) => () => setShowDeleteIndex(itemIndex) const handleCellChange = (itemIndex: number) => (item: T) => updateItem(itemIndex, item) const handleMouseLeave = () => setShowDeleteIndex(null) return ( {items.map((item, itemIndex) => ( {itemIndex !== 0 && ComponentBetweenItems && ( )} } aria-label="Remove cell" onClick={deleteItem(itemIndex)} size="sm" shadow="md" /> {isOrdered && ( <> {itemIndex === 0 && ( } size="xs" shadow="md" colorScheme="blue" onClick={insertItem(itemIndex - 1)} /> )} } size="xs" shadow="md" colorScheme="blue" onClick={insertItem(itemIndex)} /> )} ))} {!isOrdered && ( )} ) }