lifetracker/apps/web/components/dashboard/hours/EditableHourCode.tsx

115 lines
3.5 KiB
TypeScript

"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<HTMLInputElement>(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 */}
<div className="hidden">
{originalText}
</div>
<input
className={cn("text-center edit-hour-code", className)}
style={{
background: hour.background ?? "inherit", color: hour.foreground ?? "inherit", fontFamily: "inherit",
borderColor: hour.foreground ?? "inherit"
}}
ref={ref}
defaultValue={originalText}
onKeyDown={(e) => {
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();
}}
/></>
// <input type="text"
// className="w-10 bg-inherit border-b-2 text-center"
// style={{ color: "inherit", borderColor: "inherit" }}
// onKeyDown={(e) => {
// if (e.key === "Enter") {
// e.preventDefault();
// onSave();
// }
// }}
// value={originalText.originalText ?? ""}
// />
);
}