1 import type { ChangeEvent, FocusEvent } from 'react';
2 import { useState } from 'react';
4 import { c } from 'ttag';
6 import { Button } from '@proton/atoms';
7 import type { ModalStateProps } from '@proton/components';
19 } from '@proton/components';
20 import { useLoading } from '@proton/hooks';
21 import noop from '@proton/utils/noop';
23 import { formatLinkName, splitLinkName, validateLinkNameField } from '../../store';
27 onSubmit: (formattedName: string) => Promise<void>;
32 const RenameModal = ({ isFile, name: linkName, onClose, onSubmit, ...modalProps }: Props & ModalStateProps) => {
33 const [name, setName] = useState(linkName);
34 const [loading, withLoading] = useLoading();
35 const [autofocusDone, setAutofocusDone] = useState(false);
37 const selectNamePart = (e: FocusEvent<HTMLInputElement>) => {
41 setAutofocusDone(true);
42 const [namePart] = splitLinkName(linkName);
43 if (!namePart || !isFile) {
44 return e.target.select();
46 e.target.setSelectionRange(0, namePart.length);
49 const handleBlur = ({ target }: FocusEvent<HTMLInputElement>) => {
50 setName(formatLinkName(target.value));
53 const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => {
54 setName(target.value);
57 const handleSubmit = async (e: React.FormEvent) => {
60 const formattedName = formatLinkName(name);
61 setName(formattedName);
63 await onSubmit(formattedName);
67 const validationError = validateLinkNameField(name);
72 disableCloseOnEscape={loading}
74 onSubmit={(e: React.FormEvent) => withLoading(handleSubmit(e)).catch(noop)}
79 closeButtonProps={{ disabled: loading }}
80 title={!isFile ? c('Title').t`Rename a folder` : c('Title').t`Rename a file`}
83 <Row className="my-4">
84 <Label>{!isFile ? c('Label').t`Folder name` : c('Label').t`File name`}</Label>
90 placeholder={c('Placeholder').t`New name`}
91 onChange={handleChange}
93 onFocus={selectNamePart}
94 error={validationError}
96 data-testid="input-rename"
102 <Button type="button" onClick={onClose} disabled={loading}>
103 {c('Action').t`Cancel`}
105 <PrimaryButton type="submit" loading={loading}>
106 {c('Action').t`Rename`}
113 export default RenameModal;
115 export const useRenameModal = () => {
116 return useModalTwoStatic(RenameModal);