import { useEffect, useRef, useState } from "react"; import { HighlightedCell } from "./HighlightedCell"; import { parseEther } from "viem"; import { useWriteContract } from "wagmi"; import { ArrowPathIcon, PencilIcon } from "@heroicons/react/24/outline"; import { SIMPLE_ORACLE_ABI } from "~~/utils/constants"; import { notification } from "~~/utils/scaffold-eth"; type EditableCellProps = { value: string | number; address: string; highlightColor?: string; }; export const EditableCell = ({ value, address, highlightColor = "" }: EditableCellProps) => { const [isEditing, setIsEditing] = useState(false); const [isRefreshing, setIsRefreshing] = useState(false); const [editValue, setEditValue] = useState(Number(value.toString()) || ""); const inputRef = useRef(null); const { writeContractAsync } = useWriteContract(); // Update edit value when prop value changes useEffect(() => { if (!isEditing) { setEditValue(Number(value.toString()) || ""); } }, [value, isEditing]); // Focus input when editing starts useEffect(() => { if (isEditing && inputRef.current) { inputRef.current.focus(); inputRef.current.select(); } }, [isEditing]); const handleSubmit = async () => { const parsedValue = Number(editValue); if (isNaN(parsedValue)) { notification.error("Invalid number"); return; } try { await writeContractAsync({ abi: SIMPLE_ORACLE_ABI, address: address, functionName: "setPrice", args: [parseEther(parsedValue.toString())], }); setIsEditing(false); } catch (error) { console.error("Submit failed:", error); } }; // Resubmits the currently displayed value without entering edit mode const handleRefresh = async () => { const parsedValue = Number(value.toString()); if (isNaN(parsedValue)) { notification.error("Invalid number"); return; } try { await writeContractAsync({ abi: SIMPLE_ORACLE_ABI, address: address, functionName: "setPrice", args: [parseEther(parsedValue.toString())], }); } catch (error) { console.error("Refresh failed:", error); } }; const handleCancel = () => { setIsEditing(false); }; const startEditing = () => { setIsEditing(true); }; return (
{/* 70% width for value display/editing */}
{isEditing ? (
setEditValue(e.target.value)} className="w-full text-sm bg-secondary rounded-md" />
) : (
{value}
)}
{/* 30% width for action buttons */}
{isEditing && (
)}
); };