refactor: hooks useConfirm (#998)

This commit is contained in:
Himself65 2023-02-14 18:49:18 -06:00 committed by GitHub
parent 3b9caadaac
commit 78c164463f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 92 additions and 54 deletions

View File

@ -21,7 +21,7 @@ const PopoverContent = () => {
const { editor } = useAppState(); const { editor } = useAppState();
const { toggleFavoritePage, toggleDeletePage } = usePageHelper(); const { toggleFavoritePage, toggleDeletePage } = usePageHelper();
const { changePageMode } = usePageHelper(); const { changePageMode } = usePageHelper();
const { confirm } = useConfirm(); const confirm = useConfirm(store => store.confirm);
const { t } = useTranslation(); const { t } = useTranslation();
const { const {
mode = 'page', mode = 'page',

View File

@ -10,7 +10,7 @@ export const TrashButtonGroup = () => {
const { permanentlyDeletePage } = usePageHelper(); const { permanentlyDeletePage } = usePageHelper();
const { currentWorkspace } = useAppState(); const { currentWorkspace } = useAppState();
const { toggleDeletePage } = usePageHelper(); const { toggleDeletePage } = usePageHelper();
const { confirm } = useConfirm(); const confirm = useConfirm(store => store.confirm);
const router = useRouter(); const router = useRouter();
const { id = '' } = useCurrentPageMeta() || {}; const { id = '' } = useCurrentPageMeta() || {};
const { t } = useTranslation(); const { t } = useTranslation();

View File

@ -19,7 +19,7 @@ export const OperationCell = ({ pageMeta }: { pageMeta: PageMeta }) => {
const { id, favorite } = pageMeta; const { id, favorite } = pageMeta;
const { openPage } = usePageHelper(); const { openPage } = usePageHelper();
const { toggleFavoritePage, toggleDeletePage } = usePageHelper(); const { toggleFavoritePage, toggleDeletePage } = usePageHelper();
const { confirm } = useConfirm(); const confirm = useConfirm(store => store.confirm);
const { t } = useTranslation(); const { t } = useTranslation();
const OperationMenu = ( const OperationMenu = (
<> <>
@ -77,7 +77,7 @@ export const TrashOperationCell = ({ pageMeta }: { pageMeta: PageMeta }) => {
const { id } = pageMeta; const { id } = pageMeta;
const { openPage, getPageMeta } = usePageHelper(); const { openPage, getPageMeta } = usePageHelper();
const { toggleDeletePage, permanentlyDeletePage } = usePageHelper(); const { toggleDeletePage, permanentlyDeletePage } = usePageHelper();
const { confirm } = useConfirm(); const confirm = useConfirm(store => store.confirm);
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<FlexWrapper> <FlexWrapper>

View File

@ -33,7 +33,7 @@ export const MembersPage = ({ workspace }: { workspace: WorkspaceUnit }) => {
const { members, removeMember, loaded } = useMembers(); const { members, removeMember, loaded } = useMembers();
const { triggerEnableWorkspaceModal } = useModal(); const { triggerEnableWorkspaceModal } = useModal();
const { t } = useTranslation(); const { t } = useTranslation();
const { confirm } = useConfirm(); const confirm = useConfirm(store => store.confirm);
if (workspace.provider === 'affine') { if (workspace.provider === 'affine') {
return ( return (

View File

@ -1,37 +1,38 @@
import { createContext, useContext, useState, ReactNode } from 'react'; import { createContext, useContext, useMemo } from 'react';
import type { PropsWithChildren } from 'react'; import type { PropsWithChildren } from 'react';
import { Confirm, ConfirmProps } from '@affine/component'; import { Confirm, ConfirmProps } from '@affine/component';
import { createStore, useStore } from 'zustand';
import { combine, subscribeWithSelector } from 'zustand/middleware';
import { UseBoundStore } from 'zustand/react';
type ConfirmContextValue = { type ConfirmActions = {
confirm: (props: ConfirmProps) => Promise<boolean>; confirm: (props: ConfirmProps) => Promise<boolean>;
}; };
type ConfirmContextProps = PropsWithChildren<Record<string, unknown>>;
export const ConfirmContext = createContext<ConfirmContextValue>({ type ConfirmState = {
confirm: () => Promise.resolve(false), record: Record<string, JSX.Element>;
}); };
export const useConfirm = () => useContext(ConfirmContext); const create = () =>
createStore(
export const ConfirmProvider = ({ subscribeWithSelector(
children, combine<ConfirmState, ConfirmActions>(
}: PropsWithChildren<ConfirmContextProps>) => { {
const [confirmRecord, setConfirmRecord] = useState<Record<string, ReactNode>>( record: {},
{} },
); (set, get) => ({
return (
<ConfirmContext.Provider
value={{
confirm: ({ onCancel, onConfirm, ...props }: ConfirmProps) => { confirm: ({ onCancel, onConfirm, ...props }: ConfirmProps) => {
return new Promise(resolve => { return new Promise(resolve => {
const confirmRecord = { ...get().record };
const confirmId = String(Date.now()); const confirmId = String(Date.now());
const closeHandler = () => { const closeHandler = () => {
delete confirmRecord[confirmId]; delete confirmRecord[confirmId];
setConfirmRecord({ ...confirmRecord }); set({ record: { ...confirmRecord } });
}; };
setConfirmRecord(oldConfirmRecord => { set(({ record }) => {
return { return {
...oldConfirmRecord, record: {
...record,
[confirmId]: ( [confirmId]: (
<Confirm <Confirm
{...props} {...props}
@ -47,16 +48,53 @@ export const ConfirmProvider = ({
}} }}
/> />
), ),
},
}; };
}); });
}); });
}, },
}} })
> )
{children} )
{Object.entries(confirmRecord).map(([confirmId, confirmNode]) => { );
type Store = ReturnType<typeof create>;
export const ConfirmContext = createContext<Store | null>(null);
export const useConfirmApi = () => {
const api = useContext(ConfirmContext);
if (!api) {
throw new Error('cannot find confirm context');
}
return api;
};
export const useConfirm: UseBoundStore<Store> = ((
selector: Parameters<UseBoundStore<Store>>[0],
equals: Parameters<UseBoundStore<Store>>[1]
) => {
const api = useConfirmApi();
return useStore(api, selector, equals);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any;
function Records() {
const conform = useConfirm(store => store.record);
return (
<>
{Object.entries(conform).map(([confirmId, confirmNode]) => {
return <div key={confirmId}>{confirmNode}</div>; return <div key={confirmId}>{confirmNode}</div>;
})} })}
</>
);
}
export const ConfirmProvider = ({ children }: PropsWithChildren) => {
return (
<ConfirmContext.Provider value={useMemo(() => create(), [])}>
{children}
<Records />
</ConfirmContext.Provider> </ConfirmContext.Provider>
); );
}; };