diff --git a/src/components/AddTask.tsx b/src/components/AddTask.tsx index 0776c60..15c7382 100644 --- a/src/components/AddTask.tsx +++ b/src/components/AddTask.tsx @@ -6,16 +6,27 @@ import TrapFocus from "@mui/material/Unstable_TrapFocus"; import Box from "@mui/material/Box"; import Button from "@mui/material/Button"; -import { useAppDispatch, useAppSelector } from "../hooks"; +import { useAppDispatch, useAppSelector, useInputValue } from "../hooks"; import { open as openAction, close as closeAction, } from "../store/slices/uiState"; +import { add } from "../store/slices/todo"; export const AddTask: React.FC = () => { const open = useAppSelector((state) => state.uiState.addBarOpen); const dispatch = useAppDispatch(); + const { value, onChange, submit } = useInputValue("", (submitValue) => + dispatch(add(submitValue)) + ); + + const save = () => { + submit(); + onChange(""); + dispatch(closeAction()); + }; + return ( { fullWidth placeholder="New task" autoFocus={open} + value={value} + onFocus={(e) => { + e.currentTarget.setSelectionRange(value.length, value.length); + }} + onChange={(e) => onChange(e.currentTarget.value)} multiline /> theme.spacing(1) }}> - diff --git a/src/components/TodoItem.tsx b/src/components/TodoItem.tsx index d25a3de..cb95766 100644 --- a/src/components/TodoItem.tsx +++ b/src/components/TodoItem.tsx @@ -36,7 +36,10 @@ export const TodoItem: React.FC = ({ task, index }) => { variant="standard" value={value} autoFocus={true} - onChange={onChange} + onFocus={(e) => { + e.currentTarget.setSelectionRange(value.length, value.length); + }} + onChange={(e) => onChange(e.currentTarget.value)} onBlur={() => { setEditing(false); submit(); diff --git a/src/hooks.ts b/src/hooks.ts index cae27fc..d35e905 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -4,7 +4,7 @@ import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux"; import { AppDispatch, RootState } from "./store"; export type UseInputValueReturnT = { - onChange: ChangeEventHandler; + onChange: (value: string) => void; submit: () => void; value: string; }; @@ -16,7 +16,7 @@ export const useInputValue = ( const [value, setValue] = useState(initialValue); return { - onChange: (e) => setValue(e.currentTarget.value), + onChange: (value) => setValue(value), submit: () => onSubmit(value), value, }; diff --git a/src/store/slices/todo.ts b/src/store/slices/todo.ts index 3c459ce..9fed27e 100644 --- a/src/store/slices/todo.ts +++ b/src/store/slices/todo.ts @@ -13,8 +13,14 @@ export const todoSlice = createSlice({ name: "todo", initialState: initialState, reducers: { - add: (state, { payload }: PayloadAction) => { - state.tasks.push(payload); + add: (state, { payload }: PayloadAction) => { + const newId = state.tasks[state.tasks.length - 1]?.id ?? 0; + + state.tasks.push({ + done: false, + text: payload, + id: newId, + }); }, updateText: ( state,