lifetracker/apps/web/components/dashboard/hours/EditableHourComment.tsx
2024-12-03 21:30:40 -08:00

90 lines
2.6 KiB
TypeScript

"use client";
import { or } from "drizzle-orm";
import { useEffect, useRef } from "react";
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 EditableHourComment({
originalText,
hour,
onSubmit,
i
}) {
// console.log(`Hello from ${hour.time}, where the categoryDesc is ${hour.categoryDesc}`);
const ref = useRef<HTMLInputElement>(null);
useEffect(() => {
if (ref.current) {
ref.current.value = originalText;
}
}, [ref]);
const submit = () => {
let newComment: string | null = ref.current?.value ?? null;
if (originalText == newComment) {
// Nothing to do here
selectHourComment(hour.time + 1);
return;
}
if (newComment == "") {
if (originalText == null) {
// Set value to previous hour's value
newComment = document.getElementById("hour-" + (i - 1).toString())?.getElementsByClassName("edit-hour-comment")[0].value;
}
else {
newComment = null;
}
}
onSubmit({
date: hour.date,
hourTime: hour.time,
dayId: hour.dayId,
comment: newComment,
code: hour.categoryCode.toString(),
})
selectHourComment(hour.time + 1);
};
return (
<input
className="w-full text-left edit-hour-comment"
style={{
background: hour.background ?? "inherit", color: hour.foreground ?? "inherit", fontFamily: "inherit",
}}
ref={ref}
value={originalText ?? ""}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
submit();
}
if (e.key == "ArrowDown") {
e.preventDefault();
selectHourComment(i + 1);
}
if (e.key == "ArrowUp") {
e.preventDefault();
selectHourComment(i - 1);
}
if (e.key == "ArrowLeft") {
e.preventDefault();
selectHourCode(i);
}
}}
onClick={(e) => {
e.target.select();
}}
onFocus={(e) => {
e.target.select();
}}
/>
);
}