Commit 6a9f84e2 by Sujeeth AV

Update Input.jsx

parent 3887296f
import React, { createContext, useState, useRef, useEffect } from 'react';
import React, { createContext, useState, useRef, useEffect, useCallback } from 'react';
import './Input.css';
import { getTodo, addTodo, delTodo, uptTodo } from '../API/Api';
import { MdCancel } from "react-icons/md";
import { Header } from '../Header/Header';
import { Checkbox } from './Checkbox';
import { ErrorBoundary } from '../ErrorBoundary';
export const MyTask = createContext();
const debounce = (func, delay) => {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
};
export const Input = () => {
const [task, setTask] = useState("");
const [store, setStore] = useState([]);
const [editIndex, setEditIndex] = useState(null);
const [editedTask, setEditedTask] = useState("");
const [loading, setLoading] = useState(false);
const editableRef = useRef(null);
const lastCursorPos = useRef(0);
useEffect(() => {
getTodo().then(res => setStore(res.data));
const fetchTodos = useCallback(async () => {
try {
setLoading(true);
const res = await getTodo();
setStore(res.data || []);
} catch (error) {
console.error("Failed to fetch todos:", error);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchTodos();
}, [fetchTodos]);
const saveCursorPosition = () => {
try {
if (editableRef.current) {
const selection = window.getSelection();
if (selection.rangeCount > 0) {
......@@ -30,15 +54,17 @@ export const Input = () => {
lastCursorPos.current = preCaretRange.toString().length;
}
}
} catch (error) {
console.error("Error saving cursor position:", error);
}
};
const restoreCursorPosition = () => {
try {
if (editableRef.current) {
const textNode = editableRef.current.firstChild || editableRef.current;
const range = document.createRange();
const selection = window.getSelection();
let pos = 0;
let found = false;
const findPosition = (node, remainingPos) => {
if (node.nodeType === Node.TEXT_NODE) {
......@@ -67,111 +93,182 @@ export const Input = () => {
selection.removeAllRanges();
selection.addRange(range);
}
} catch (error) {
console.error("Error restoring cursor position:", error);
}
};
useEffect(() => {
if (editableRef.current && editIndex !== null) {
try {
editableRef.current.focus();
setTimeout(restoreCursorPosition, 0);
} catch (error) {
console.error("Error focusing editable element:", error);
setEditIndex(null);
}
}
}, [editIndex, editedTask]);
const Change = (e) => setTask(e.target.value);
const debouncedSave = useCallback(
debounce(async (id, newTask) => {
try {
const todo = store.find(item => item.id === id);
if (todo && todo.task !== newTask) {
await uptTodo(id, {
id: todo.id,
task: newTask,
completed: todo.completed
});
}
} catch (error) {
console.error("Error saving todo:", error);
}
}, 500),
[store]
);
const handleChange = (e) => setTask(e.target.value);
const handleEdit = (e) => {
try {
saveCursorPosition();
const newValue = e.currentTarget.textContent;
setEditedTask(newValue);
const newStore = [...store];
newStore[editIndex] = { ...newStore[editIndex], task: newValue };
setStore(newStore);
debouncedSave(store[editIndex].id, newValue);
} catch (error) {
console.error("Error during edit:", error);
setEditIndex(null);
}
};
const startEdit = (index) => {
try {
setEditIndex(index);
setEditedTask(store[index].task);
} catch (error) {
console.error("Error starting edit:", error);
setEditIndex(null);
}
};
const endEdit = () => {
setEditIndex(null);
};
const Add = async () => {
if (task.trim() === '') return;
try {
const res = await addTodo(task);
setStore([...store, res.data]);
setTask("");
} catch (error) {
console.error("Error adding todo:", error);
}
};
const Delete = async (id) => {
const confirmDelete = window.confirm("Are you sure you want to delete?");
if (confirmDelete) {
try {
await delTodo(id);
setStore(store.filter(item => item.id !== id));
} catch (error) {
console.error("Error deleting todo:", error);
}
}
};
const startEdit = (index) => {
const toggleComplete = async (index) => {
try {
setEditIndex(index);
setEditedTask(store[index].task);
const newStore = [...store];
newStore[index] = {
...newStore[index],
completed: !newStore[index].completed
};
setStore(newStore);
await uptTodo(newStore[index].id, newStore[index]);
} catch (error) {
console.error("Error in startEdit:", error);
setEditIndex(null);
console.error("Error toggling complete:", error);
fetchTodos();
}
};
const saveEdit = async (index) => {
const renderEditableContent = () => {
try {
if (!editedTask.trim()) return;
const todo = store[index];
const updated = { ...todo, task: editedTask };
await uptTodo(todo.id, updated);
const newStore = [...store];
newStore[index] = updated;
setStore(newStore);
setEditIndex(null);
return (
<div
ref={editableRef}
contentEditable
suppressContentEditableWarning
onBlur={endEdit}
onInput={handleEdit}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.currentTarget.blur();
}
}}
className={`task ${store[editIndex]?.completed ? 'completed' : ''}`}
>
{editedTask}
</div>
);
} catch (error) {
console.error("Error saving edit:", error);
console.error("Error rendering editable content:", error);
return (
<span
className={`task ${store[editIndex]?.completed ? 'completed' : ''}`}
onClick={() => startEdit(editIndex)}
>
{typeof store[editIndex]?.task === 'string'
? store[editIndex].task
: JSON.stringify(store[editIndex]?.task)}
</span>
);
}
};
const handleEditInput = (e) => {
saveCursorPosition();
setEditedTask(e.currentTarget.textContent);
};
const toggleComplete = (index) => {
const newStore = [...store];
newStore[index].completed = !newStore[index].completed;
setStore(newStore);
};
return (
<MyTask.Provider value={{ store, setStore }}>
<>
<div className="todo-container">
<Header />
<ul className='scroll'>
{store.map((item, index) => (
{store.map((item, index) => {
console.log("Rendering task:", item.task);
return (
<li key={item.id} className={`todo ${item.completed ? "completed" : ""}`}>
<div className="check">
<Checkbox
checked={item.completed}
onChange={() => toggleComplete(index)}
id={item.id}
/>
<ErrorBoundary>
{editIndex === index ? (
<span
ref={editableRef}
contentEditable
suppressContentEditableWarning
onBlur={() => saveEdit(index)}
onInput={(e) => setEditedTask(e.currentTarget.textContent)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.currentTarget.blur();
}
}}
className={`task ${item.completed ? 'completed' : ''}`}
dangerouslySetInnerHTML={{ __html: editedTask }}
/>
{editIndex === index ? (
renderEditableContent()
) : (
<span
className={`task ${item.completed ? 'completed' : ''}`}
onClick={() => startEdit(index)}
>
{item.task}
{typeof item.task === 'string'
? item.task
: JSON.stringify(item.task)}
</span>
)}
</ErrorBoundary>
</div>
<button className="delete" onClick={() => Delete(item.id)}>
<MdCancel />
</button>
</li>
))}
);
})}
</ul>
<form onSubmit={(e) => e.preventDefault()}>
......@@ -181,14 +278,19 @@ export const Input = () => {
className="input"
placeholder="Enter Items"
value={task}
onChange={Change}
onChange={handleChange}
disabled={loading}
/>
<button onClick={Add} className="button">
Submit
<button
onClick={Add}
className="button"
disabled={loading || !task.trim()}
>
{loading ? 'Adding...' : 'Submit'}
</button>
</div>
</form>
</>
</div>
</MyTask.Provider>
);
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment