ant-design/components/modal/useModal/index.tsx
dependabot[bot] 775d1800bb
chore(deps-dev): bump eslint-config-prettier from 6.15.0 to 7.0.0 (#28253)
* chore(deps-dev): bump eslint-config-prettier from 6.15.0 to 7.0.0

Bumps [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) from 6.15.0 to 7.0.0.
- [Release notes](https://github.com/prettier/eslint-config-prettier/releases)
- [Changelog](https://github.com/prettier/eslint-config-prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/eslint-config-prettier/compare/v6.15.0...v7.0.0)

Signed-off-by: dependabot[bot] <support@github.com>

* chore: fix eslint style

* chore: prettier code style

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: afc163 <afc163@gmail.com>
2020-12-09 17:12:32 +08:00

88 lines
2.1 KiB
TypeScript

import * as React from 'react';
import { ModalFuncProps } from '../Modal';
import usePatchElement from '../../_util/hooks/usePatchElement';
import HookModal, { HookModalRef } from './HookModal';
import {
withConfirm,
ModalStaticFunctions,
withInfo,
withSuccess,
withError,
withWarn,
} from '../confirm';
let uuid = 0;
interface ElementsHolderRef {
patchElement: ReturnType<typeof usePatchElement>[1];
}
const ElementsHolder = React.memo(
React.forwardRef<ElementsHolderRef>((_props, ref) => {
const [elements, patchElement] = usePatchElement();
React.useImperativeHandle(
ref,
() => ({
patchElement,
}),
[],
);
return <>{elements}</>;
}),
);
export default function useModal(): [Omit<ModalStaticFunctions, 'warn'>, React.ReactElement] {
const holderRef = React.useRef<ElementsHolderRef>(null as any);
const getConfirmFunc = React.useCallback(
(withFunc: (config: ModalFuncProps) => ModalFuncProps) =>
function hookConfirm(config: ModalFuncProps) {
uuid += 1;
const modalRef = React.createRef<HookModalRef>();
let closeFunc: Function;
const modal = (
<HookModal
key={`modal-${uuid}`}
config={withFunc(config)}
ref={modalRef}
afterClose={() => {
closeFunc();
}}
/>
);
closeFunc = holderRef.current?.patchElement(modal);
return {
destroy: () => {
if (modalRef.current) {
modalRef.current.destroy();
}
},
update: (newConfig: ModalFuncProps) => {
if (modalRef.current) {
modalRef.current.update(newConfig);
}
},
};
},
[],
);
const fns = React.useMemo(
() => ({
info: getConfirmFunc(withInfo),
success: getConfirmFunc(withSuccess),
error: getConfirmFunc(withError),
warning: getConfirmFunc(withWarn),
confirm: getConfirmFunc(withConfirm),
}),
[],
);
// eslint-disable-next-line react/jsx-key
return [fns, <ElementsHolder ref={holderRef} />];
}