Skip to content

Commit

Permalink
ref: Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
meltyshev committed Oct 27, 2024
1 parent 2067a1a commit 4749ea1
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions client/src/components/CardModal/Tasks/Add.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const DEFAULT_DATA = {
name: '',
};

const MULTIPLE_REGEX = /\s*\r?\n\s*/;

const Add = React.forwardRef(({ children, onCreate }, ref) => {
const [t] = useTranslation();
const [isOpened, setIsOpened] = useState(false);
Expand All @@ -29,22 +31,34 @@ const Add = React.forwardRef(({ children, onCreate }, ref) => {
setIsOpened(false);
}, []);

const submit = useCallback(() => {
const cleanData = {
...data,
name: data.name.trim(),
};
const submit = useCallback(
(isMultiple = false) => {
const cleanData = {
...data,
name: data.name.trim(),
};

if (!cleanData.name) {
nameField.current.ref.current.select();
return;
}
if (!cleanData.name) {
nameField.current.ref.current.select();
return;
}

onCreate(cleanData);
if (isMultiple) {
cleanData.name.split(MULTIPLE_REGEX).forEach((name) => {
onCreate({
...cleanData,
name,
});
});
} else {
onCreate(cleanData);
}

setData(DEFAULT_DATA);
focusNameField();
}, [onCreate, data, setData, focusNameField]);
setData(DEFAULT_DATA);
focusNameField();
},
[onCreate, data, setData, focusNameField],
);

useImperativeHandle(
ref,
Expand All @@ -61,17 +75,12 @@ const Add = React.forwardRef(({ children, onCreate }, ref) => {

const handleFieldKeyDown = useCallback(
(event) => {
if (event.ctrlKey && event.key === 'Enter') {
event.preventDefault();
const lines = data.name.split('\n').filter(line => line.trim() !== '');
lines.forEach(line => onCreate({ name: line.trim() }));
setData({ ...data, name: '' });
} else if (event.key === 'Enter') {
if (event.key === 'Enter') {
event.preventDefault();
submit();
submit(event.ctrlKey);
}
},
[data, onCreate, submit],
[submit],
);

const [handleFieldBlur, handleControlMouseOver, handleControlMouseOut] = useClosableForm(
Expand Down

0 comments on commit 4749ea1

Please sign in to comment.