Certainly! Below are the completed implementations of the handleChange and handleSave functions within your Feedbacks component (feedbacks.tsx) and the necessary modifications to your Feedback component (feedback.tsx) to integrate these functions effectively.
feedbacks.tsx
Updated Feedbacks Component
"use client";
import { IQuestionBranch } from "@/app/actions/server/default.action";
import useVisibleElements from "@/hooks/visible-elements.hook";
import React, { useCallback, useMemo, useState, useEffect } from "react";
import Feedback from "./feedback";
import { IContent } from "@/database/schemas/content.schema";
import { createHierarchicalLabel } from "@/lib/utils";
import { AnimatePresence } from "framer-motion";
interface IProps {
question: IQuestionBranch;
dependency: { [key: string]: string };
}
const Feedbacks = ({ question, dependency }: IProps) => {
const visibleElementIds = useVisibleElements();
const [feedbacks, setFeedbacks] = useState<IFeedback[]>(initFeedbacks(question));
const [activeFeedback, setActiveFeedback] = useState<string | null>(null);
const visibleQuestionIds = useMemo(
() => getVisibleQuestionIds(dependency, visibleElementIds),
[visibleElementIds, dependency]
);
const visibleFeedbacks = feedbacks.filter((el) => visibleQuestionIds.includes(el.questionId));
/**
* handleSave:
* Simulates saving feedback to a server by introducing a delay.
* After saving, it clears the timeoutId to indicate that saving is complete.
*
* @param questionId - The ID of the question whose feedback is being saved.
*/
const handleSave = useCallback(async (questionId: string) => {
try {
// Simulate a network delay (e.g., 1 second)
await new Promise((resolve) => setTimeout(resolve, 1000));
// TODO: Replace the above simulation with actual server-side save logic.
// After saving, clear the timeoutId to indicate that saving is done.
setFeedbacks((prevFeedbacks) =>
prevFeedbacks.map((fb) =>
fb.questionId === questionId ? { ...fb, timeoutId: null } : fb
)
);
console.log(`Feedback for question ${questionId} saved successfully.`);
} catch (error) {
console.error(`Error saving feedback for question ${questionId}:`, error);
// Optionally, handle error states here.
}
}, []);
/**
* handleChange:
* Updates the feedback state when a user modifies the grade or feedback content.
* It also sets up a debounced save operation that triggers after 2 seconds of inactivity.
*
* @param questionId - The ID of the question being updated.
* @param grade - (Optional) The new grade value.
* @param feedback - (Optional) The new feedback content.
*/
const handleChange = useCallback(
(questionId: string, grade?: string, feedback?: IContent[]) => {
setFeedbacks((prevFeedbacks) =>
prevFeedbacks.map((fb) => {
if (fb.questionId === questionId) {
// Clear existing timeout if any to prevent multiple saves
if (fb.timeoutId) {
clearTimeout(fb.timeoutId);
}
// Set a new timeout to save after 2 seconds
const newTimeoutId = setTimeout(() => handleSave(questionId), 2000);
return {
...fb,
grade: grade !== undefined ? grade : fb.grade,
feedback: feedback !== undefined ? feedback : fb.feedback,
timeoutId: newTimeoutId,
};
}
return fb;
})
);
},
[handleSave]
);
/**
* Cleanup all timeouts when the component unmounts to prevent memory leaks.
*/
useEffect(() => {
return () => {
feedbacks.forEach((fb) => {
if (fb.timeoutId) {
clearTimeout(fb.timeoutId);
}
});
};
}, [feedbacks]);
return (
<AnimatePresence>
{visibleFeedbacks.map((el) => (
<Feedback
key={`question-${el.questionId}-feedback`}
isActive={activeFeedback === el.questionId}
onClick={() =>
setActiveFeedback((prev) => (prev === el.questionId ? null : el.questionId))
}
onChange={handleChange}
{...el}
/>
))}
</AnimatePresence>
);
};
export default Feedbacks;
export interface IFeedback {
questionId: string;
label: string;
grade: string;
feedback: IContent[];
timeoutId: ReturnType<typeof setTimeout> | null; // Updated type for browser compatibility
}
const initFeedbacks = (question: IQuestionBranch): IFeedback[] => {
const newFeedbacks: IFeedback[] = [];
const addFeedback = (
feedbacks: IFeedback[],
questionBranch: IQuestionBranch,
trail: number[] = []
): void => {
if (questionBranch.grade === undefined || !questionBranch.feedback)
throw new Error("Invalid question branch data");
feedbacks.push({
questionId: questionBranch.id,
label: trail.length > 0 ? `Question ${createHierarchicalLabel(trail)}` : "Assessment",
grade: questionBranch.grade,
feedback: questionBranch.feedback,
timeoutId: null,
});
for (let i = 0; i < questionBranch.questions.length; i++) {
addFeedback(feedbacks, questionBranch.questions[i], [...trail, i]);
}
};
addFeedback(newFeedbacks, question);
return newFeedbacks;
};
const getVisibleQuestionIds = (
dependency: { [key: string]: string },
visibleElementIds: string[]
): string[] => {
// Convert the visibleElementIds array to a Set for efficient lookups
const visibleSet = new Set(visibleElementIds);
// Iterate over the keys of the dependency object
// and filter keys whose corresponding value is in the visibleSet
return Object.keys(dependency).filter((key) => visibleSet.has(dependency[key]));
};
Explanation of Changes
-
Implemented handleSave:
- Purpose: Simulates saving feedback to a server with a 1-second delay.
- Functionality: After the simulated save, it updates the corresponding
feedback in the state by setting timeoutId to null, indicating that the save operation is complete.
- Error Handling: Logs any errors encountered during the save operation.
-
Implemented handleChange:
- Purpose: Updates the feedback's
grade and/or feedback content in the state based on user input.
- Functionality:
- State Update: Locates the relevant
feedback entry by questionId and updates its grade and/or feedback fields.
- Debounce Mechanism: Clears any existing timeout to prevent multiple save operations and sets a new timeout to invoke
handleSave after 2 seconds of inactivity.
-
Added Cleanup with useEffect:
- Purpose: Ensures that all pending timeouts are cleared when the component unmounts, preventing potential memory leaks.
-
Updated IFeedback Interface:
- Changed
timeoutId type to ReturnType<typeof setTimeout> | null for better compatibility with browser environments.
-
Passed handleChange to the Feedback Component:
- Added the
onChange prop to each Feedback instance, allowing child components to notify the parent (Feedbacks) of any changes.
feedback.tsx
Updated Feedback Component
import ContentsView from "@/components/c-ui/contents/view";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import React, { useState, useEffect } from "react";
import { IFeedback } from "./feedbacks";
import { IContent } from "@/database/schemas/content.schema";
import { motion } from "framer-motion";
import {
LoaderCircleIcon,
PencilIcon,
PencilLineIcon,
PlusIcon,
} from "lucide-react";
interface IProps extends IFeedback {
isActive: boolean;
onClick: () => void;
onChange: (questionId: string, grade?: string, feedback?: IContent[]) => void;
}
const Feedback = ({
questionId,
label,
grade,
feedback,
timeoutId,
isActive,
onClick,
onChange,
}: IProps) => {
const [localGrade, setLocalGrade] = useState<string>(grade);
const [localFeedback, setLocalFeedback] = useState<IContent[]>(feedback);
// Update local state when props change
useEffect(() => {
setLocalGrade(grade);
}, [grade]);
useEffect(() => {
setLocalFeedback(feedback);
}, [feedback]);
// Determine the state based on current status
const state: "empty" | "preview" | "active" | "saving" = !!timeoutId
? "saving"
: isActive
? "active"
: !grade && !feedback.length
? "empty"
: "preview";
let description: React.JSX.Element;
switch (state) {
case "empty":
description = (
<>
<PlusIcon className="h-4 w-4" />
<p>Add feedback</p>
</>
);
break;
case "preview":
description = (
<>
<PencilIcon className="h-4 w-4" />
<p>Edit feedback</p>
</>
);
break;
case "active":
description = (
<>
<PencilLineIcon className="h-4 w-4" />
<p>Updating feedback</p>
</>
);
break;
case "saving":
description = (
<>
<LoaderCircleIcon className="h-4 w-4 animate-spin" />
<p>Saving changes</p>
</>
);
break;
default:
throw new Error("Invalid state");
}
/**
* Handle grade change input.
*
* @param e - Event from the grade input field.
*/
const handleGradeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newGrade = e.target.value;
setLocalGrade(newGrade);
onChange(questionId, newGrade, localFeedback);
};
/**
* Handle feedback content change.
*
* @param newContents - The updated feedback content.
*/
const handleFeedbackChange = (newContents: IContent[]) => {
setLocalFeedback(newContents);
onChange(questionId, localGrade, newContents);
};
return (
<motion.div
initial={{ opacity: 0, x: -50 }} // Slide in from left
animate={{ opacity: 1, x: 0 }} // Slide to original position
exit={{ opacity: 0, x: 50 }} // Slide out to right
transition={{ duration: 0.3, ease: "easeOut" }} // Customize as needed
layout // Optional: Enables smooth layout transitions
>
<Card
className={`${
isActive ? "shadow-md" : "opacity-60 hover:opacity-100 cursor-pointer"
}`}
onClick={onClick}
>
<CardHeader>
<CardTitle>{label}</CardTitle>
<CardDescription className="flex gap-2 items-center">
{description}
</CardDescription>
</CardHeader>
{state === "preview" && <Preview questionId={questionId} grade={grade} feedback={feedback} />}
{isActive && (
<EditForm
grade={localGrade}
feedback={localFeedback}
onGradeChange={handleGradeChange}
onFeedbackChange={handleFeedbackChange}
saving={state === "saving"}
/>
)}
</Card>
</motion.div>
);
};
export default Feedback;
interface IPreviewProps {
questionId: string;
grade: string;
feedback: IContent[];
}
const Preview = ({ questionId, grade, feedback }: IPreviewProps) => {
return (
<CardContent className="h-fit w-full flex flex-col">
<p>
Grade: <span>{grade}</span>
</p>
<p>Feedback:</p>
<ContentsView keyPrefix={`question-${questionId}-feedback`} contents={feedback} />
</CardContent>
);
};
interface IEditFormProps {
grade: string;
feedback: IContent[];
onGradeChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
onFeedbackChange: (newContents: IContent[]) => void;
saving: boolean;
}
const EditForm = ({
grade,
feedback,
onGradeChange,
onFeedbackChange,
saving,
}: IEditFormProps) => {
const [localFeedback, setLocalFeedback] = useState<IContent[]>(feedback);
// Handle feedback content changes via ContentsView
const handleContentsUpdate = (newContents: IContent[]) => {
setLocalFeedback(newContents);
onFeedbackChange(newContents);
};
return (
<CardContent className="h-fit w-full flex flex-col space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700">Grade</label>
<input
type="text"
value={grade}
onChange={onGradeChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
disabled={saving}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">Feedback</label>
<ContentsView
keyPrefix={`edit-feedback-${questionId}`}
contents={localFeedback}
onChange={handleContentsUpdate}
disabled={saving}
/>
</div>
{saving && (
<div className="flex items-center space-x-2">
<LoaderCircleIcon className="h-5 w-5 animate-spin" />
<span>Saving...</span>
</div>
)}
</CardContent>
);
};
Explanation of Changes
-
Added onChange Prop to IProps:
- The
Feedback component now accepts an onChange prop, which is a function used to notify the parent (Feedbacks) of any changes to the grade or feedback content.
-
Local State Management for Grade and Feedback:
- Purpose: To manage form inputs locally within the
Feedback component before propagating changes to the parent.
- Implementation:
localGrade: Holds the current value of the grade input.
localFeedback: Holds the current feedback content.
-
Synchronization with Parent State:
- Utilizes
useEffect hooks to keep the local state in sync with props received from the parent.
-
Input Handlers:
handleGradeChange:
- Updates the local
grade state when the grade input changes.
- Calls
onChange to notify the parent about the grade update.
handleFeedbackChange:
- Updates the local
feedback state when the feedback content changes.
- Calls
onChange to notify the parent about the feedback update.
-
State-Based Rendering:
state Variable: Determines the current state (empty, preview, active, saving) based on whether there's an active timeout, if the feedback is active, and if grade/feedback content exists.
- Descriptions: Updates the UI descriptions based on the current state.
-
Conditional Rendering of Forms:
- When
isActive is true, an EditForm component is rendered, allowing users to edit the grade and feedback content.
- The
EditForm includes input fields for the grade and a ContentsView component for feedback content.
Summary
With these implementations:
-
Debounced Saving: Whenever a user updates the grade or feedback content, the changes are reflected immediately in the UI. However, the actual save operation to the server is debounced by 2 seconds, meaning it will only occur after the user stops typing or making changes for 2 seconds. This reduces unnecessary network requests during rapid input.
-
Visual Feedback: The UI provides clear indications of the current state:
- Empty: No grade or feedback content exists.
- Preview: Displaying existing feedback.
- Active: Currently editing the feedback.
- Saving: Feedback is in the process of being saved.
-
Clean State Management: By managing timeouts within each feedback entry and ensuring they're cleared upon component unmounting, the implementation avoids potential memory leaks and ensures consistent behavior.
Feel free to integrate these changes into your project. Ensure that any additional functionalities, such as actual server-side saving, are implemented where the TODO comments indicate.