import { FC, forwardRef, useEffect, useMemo, useRef, useState } from 'react'; import { Input, InputRef, Form, Switch } from 'antd'; import { useEditable } from './EditableContext'; import { DataType } from './types'; import tw from '../../tw'; interface Item { key: string; [k: string]: any; } interface EditableCellProps { title: React.ReactNode; editable: boolean; children: React.ReactNode; dataIndex: keyof Item; record: Item; type: DataType; handleSave: (record: Item) => void; value: any; } const TypesAutoEdit = ['boolean']; const TypesEditable = ['string', 'number', 'boolean', 'date']; const CellInput = forwardRef( ( { dataIndex, title, save, type, value }: EditableCellProps & { save: any }, ref ) => { if (type === 'boolean') { return ; } return ( ); } ); const EditableCell: FC = ({ title, editable, children, dataIndex, record, handleSave, type, ...restProps }) => { const [editing, setEditing] = useState(TypesAutoEdit.includes(type)); const inputRef = useRef(null); const form = useEditable(); const canEdit = TypesEditable.includes(type); useEffect(() => { if (editing) { inputRef.current?.focus(); } }, [editing]); const toggleEdit = () => { setEditing(!editing); form && form.setFieldsValue({ [dataIndex]: record[dataIndex] }); }; const save = async () => { try { const values = form && (await form.validateFields()); if (!TypesAutoEdit.includes(type)) { toggleEdit(); } handleSave({ ...record, ...values }); } catch {} }; const childNode = useMemo(() => { if (canEdit && editable) { return editing ? ( ) : (
{children}
); } return children; }, [editable, editing, title, children, dataIndex]); return {childNode}; }; export default EditableCell;