"use client"; import { useEffect, useRef } from "react"; import { cn } from "@/lib/utils"; function selectHourCode(time: number) { document.getElementById("hour-" + (time).toString())?.getElementsByClassName("edit-hour-code")[0].focus(); } function selectHourComment(time: number) { document.getElementById("hour-" + (time).toString())?.getElementsByClassName("edit-hour-comment")[0].focus(); } export function EditableHourCode({ className = "", originalText, hour, onSubmit, i }) { const ref = useRef(null); useEffect(() => { if (ref.current) { ref.current.value = originalText; } }, [ref]); const submit = () => { let newCode: string | null = ref.current?.value ?? null; console.log(`Original ${originalText}, new ${newCode}`); if (originalText === newCode) { // Nothing to do here console.log("Skipping."); selectHourCode(i + 1); return; } if (newCode == "") { if (originalText == null) { // Set value to previous hour's value newCode = document.getElementById("hour-" + (i - 1).toString())?.getElementsByClassName("edit-hour-code")[0].value; ref.current.value = newCode; } else { newCode = null; } } onSubmit({ date: hour.date, hourTime: hour.time, dayId: hour.dayId, code: newCode ?? "", comment: hour.comment, i: i }) selectHourCode(i + 1); }; return ( <> {/* The below is a gross hack because I don't understand why including it makes the component refresh, but without it, it won't update */}
{originalText}
{ if (e.key === "Enter") { e.preventDefault(); submit(); } if (e.key == "ArrowDown") { e.preventDefault(); selectHourCode(i + 1); } if (e.key == "ArrowUp") { e.preventDefault(); selectHourCode(i - 1); } if (e.key == "ArrowRight") { e.preventDefault(); selectHourComment(i); } }} onClick={(e) => { e.target.select(); }} onFocus={(e) => { e.target.select(); }} /> // { // if (e.key === "Enter") { // e.preventDefault(); // onSave(); // } // }} // value={originalText.originalText ?? ""} // /> ); }