Connected addTask component to store, fixed cursor position on autofocus of text fields

This commit is contained in:
2021-10-17 18:20:49 +03:00
parent 3edf5edaec
commit 0b730b8b2d
4 changed files with 32 additions and 7 deletions

View File

@ -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 (
<TrapFocus open={open}>
<SwipeableDrawer
@ -46,10 +57,15 @@ export const AddTask: React.FC = () => {
fullWidth
placeholder="New task"
autoFocus={open}
value={value}
onFocus={(e) => {
e.currentTarget.setSelectionRange(value.length, value.length);
}}
onChange={(e) => onChange(e.currentTarget.value)}
multiline
/>
<Box sx={{ paddingTop: (theme) => theme.spacing(1) }}>
<Button variant="text" sx={{ float: "right" }}>
<Button onClick={save} variant="text" sx={{ float: "right" }}>
Save
</Button>
</Box>

View File

@ -36,7 +36,10 @@ export const TodoItem: React.FC<TodoItemProps> = ({ 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();