Просмотр исходного кода

refactor useCreatePageAndTransit

Yuki Takei 2 лет назад
Родитель
Сommit
a0657951b3

+ 54 - 66
apps/app/src/client/services/use-create-page-and-transit.tsx

@@ -1,9 +1,10 @@
-import { useCallback } from 'react';
+import { useCallback, useState } from 'react';
 
 
 import { useRouter } from 'next/router';
 import { useRouter } from 'next/router';
 
 
-import { createPage } from '~/client/services/page-operation';
-import { useIsNotFound, useSWRxCurrentPage } from '~/stores/page';
+import { createPage, exist } from '~/client/services/page-operation';
+import type { IApiv3PageCreateParams } from '~/interfaces/apiv3';
+import { useCurrentPagePath } from '~/stores/page';
 import { EditorMode, useEditorMode } from '~/stores/ui';
 import { EditorMode, useEditorMode } from '~/stores/ui';
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
@@ -17,107 +18,94 @@ type OnCreated = () => void;
  * Invoked when either creation or transition has aborted
  * Invoked when either creation or transition has aborted
  */
  */
 type OnAborted = () => void;
 type OnAborted = () => void;
-/**
- * Invoked when an error is occured
- */
-type OnError = (err) => void;
 /**
 /**
  * Always invoked after processing is terminated
  * Always invoked after processing is terminated
  */
  */
 type OnTerminated = () => void;
 type OnTerminated = () => void;
 
 
 type CreatePageAndTransitOpts = {
 type CreatePageAndTransitOpts = {
+  shouldCheckPageExists?: boolean,
   onCreationStart?: OnCreated,
   onCreationStart?: OnCreated,
   onCreated?: OnCreated,
   onCreated?: OnCreated,
   onAborted?: OnAborted,
   onAborted?: OnAborted,
-  onError?: OnError,
   onTerminated?: OnTerminated,
   onTerminated?: OnTerminated,
 }
 }
 
 
 type CreatePageAndTransit = (
 type CreatePageAndTransit = (
-  pagePath: string | undefined,
-  // grant?: number,
-  // grantUserGroupId?: string,
+  params: IApiv3PageCreateParams,
   opts?: CreatePageAndTransitOpts,
   opts?: CreatePageAndTransitOpts,
 ) => Promise<void>;
 ) => Promise<void>;
 
 
-export const useCreatePageAndTransit = (): CreatePageAndTransit => {
+type UseCreatePageAndTransit = () => {
+  isCreating: boolean,
+  createAndTransit: CreatePageAndTransit,
+};
+
+export const useCreatePageAndTransit: UseCreatePageAndTransit = () => {
 
 
   const router = useRouter();
   const router = useRouter();
 
 
-  const { data: isNotFound } = useIsNotFound();
-  const { data: currentPage, isLoading } = useSWRxCurrentPage();
+  const { data: currentPagePath } = useCurrentPagePath();
   const { mutate: mutateEditorMode } = useEditorMode();
   const { mutate: mutateEditorMode } = useEditorMode();
 
 
-  // const {
-  //   path: currentPagePath,
-  //   grant: currentPageGrant,
-  //   grantedGroups: currentPageGrantedGroups,
-  // } = currentPage ?? {};
-
-  return useCallback(async(pagePath, opts = {}) => {
-    if (isLoading) {
-      return;
-    }
+  const [isCreating, setCreating] = useState(false);
 
 
+  const createAndTransit: CreatePageAndTransit = useCallback(async(params, opts = {}) => {
     const {
     const {
-      onCreationStart, onCreated, onAborted, onError, onTerminated,
+      shouldCheckPageExists,
+      onCreationStart, onCreated, onAborted, onTerminated,
     } = opts;
     } = opts;
 
 
-    if (isNotFound == null || !isNotFound || pagePath == null) {
-      mutateEditorMode(EditorMode.Editor);
-
-      onAborted?.();
-      onTerminated?.();
-      return;
+    // check the page existence
+    if (shouldCheckPageExists && params.path != null) {
+      const pagePath = params.path;
+
+      try {
+        const res = await exist(JSON.stringify([pagePath]));
+        const isExists = res.pages[pagePath];
+
+        if (isExists) {
+          // routing
+          if (pagePath !== currentPagePath) {
+            await router.push(`${pagePath}#edit`);
+          }
+          mutateEditorMode(EditorMode.Editor);
+          onAborted?.();
+          return;
+        }
+      }
+      catch (err) {
+        throw err;
+      }
+      finally {
+        onTerminated?.();
+      }
     }
     }
 
 
+    // create and transit
     try {
     try {
+      setCreating(true);
       onCreationStart?.();
       onCreationStart?.();
 
 
-      /**
-       * !! NOTICE !! - Verification of page createable or not is checked on the server side.
-       * since the new page path is not generated on the client side.
-       * need shouldGeneratePath flag.
-       */
-      // const shouldCreateUnderRoot = currentPagePath == null || currentPageGrant == null;
-      // const parentPath = shouldCreateUnderRoot
-      //   ? '/'
-      //   : currentPagePath;
-
-      // const params = {
-      //   isSlackEnabled: false,
-      //   slackChannels: '',
-      //   grant: shouldCreateUnderRoot ? 1 : currentPageGrant,
-      //   grantUserGroupIds: shouldCreateUnderRoot ? undefined : currentPageGrantedGroups,
-      //   shouldGeneratePath: true,
-      // };
-
-      // !! NOTICE !! - if shouldGeneratePath is flagged, send the parent page path
-      // const response = await createPage(parentPath, '', params);
-
-      const params = {
-        isSlackEnabled: false,
-        slackChannels: '',
-        grant: 4,
-        // grant,
-        // grantUserGroupId,
-      };
-
-      const response = await createPage(pagePath, '', params);
-
-      await router.push(`${response.page.id}#edit`);
+      const response = await createPage(params);
+
+      await router.push(`${response.page._id}#edit`);
       mutateEditorMode(EditorMode.Editor);
       mutateEditorMode(EditorMode.Editor);
 
 
       onCreated?.();
       onCreated?.();
     }
     }
     catch (err) {
     catch (err) {
-      logger.warn(err);
-      onError?.(err);
+      throw err;
     }
     }
     finally {
     finally {
       onTerminated?.();
       onTerminated?.();
+      setCreating(false);
     }
     }
 
 
-  }, [isLoading, isNotFound, mutateEditorMode, router]);
+  }, [currentPagePath, mutateEditorMode, router]);
+
+  return {
+    isCreating,
+    createAndTransit,
+  };
 };
 };

+ 21 - 20
apps/app/src/components/Navbar/PageEditorModeManager.tsx

@@ -1,9 +1,9 @@
-import React, { type ReactNode, useCallback, useState } from 'react';
+import React, { type ReactNode, useCallback } from 'react';
 
 
-import type { IGrantedGroup } from '@growi/core';
 import { useTranslation } from 'next-i18next';
 import { useTranslation } from 'next-i18next';
 
 
 import { toastError } from '~/client/util/toastr';
 import { toastError } from '~/client/util/toastr';
+import { useIsNotFound } from '~/stores/page';
 import { EditorMode, useEditorMode, useIsDeviceLargerThanMd } from '~/stores/ui';
 import { EditorMode, useEditorMode, useIsDeviceLargerThanMd } from '~/stores/ui';
 
 
 import { useCreatePageAndTransit } from '../../client/services/use-create-page-and-transit';
 import { useCreatePageAndTransit } from '../../client/services/use-create-page-and-transit';
@@ -47,9 +47,6 @@ type Props = {
   editorMode: EditorMode | undefined,
   editorMode: EditorMode | undefined,
   isBtnDisabled: boolean,
   isBtnDisabled: boolean,
   path?: string,
   path?: string,
-  grant?: number,
-  // grantUserGroupId?: string
-  grantUserGroupIds?: IGrantedGroup[]
 }
 }
 
 
 export const PageEditorModeManager = (props: Props): JSX.Element => {
 export const PageEditorModeManager = (props: Props): JSX.Element => {
@@ -57,30 +54,34 @@ export const PageEditorModeManager = (props: Props): JSX.Element => {
     editorMode = EditorMode.View,
     editorMode = EditorMode.View,
     isBtnDisabled,
     isBtnDisabled,
     path,
     path,
-    // grant,
-    // grantUserGroupId,
   } = props;
   } = props;
 
 
   const { t } = useTranslation('common');
   const { t } = useTranslation('common');
-  const [isCreating, setIsCreating] = useState(false);
 
 
+  const { data: isNotFound } = useIsNotFound();
   const { mutate: mutateEditorMode } = useEditorMode();
   const { mutate: mutateEditorMode } = useEditorMode();
   const { data: isDeviceLargerThanMd } = useIsDeviceLargerThanMd();
   const { data: isDeviceLargerThanMd } = useIsDeviceLargerThanMd();
 
 
-  const _isBtnDisabled = isCreating || isBtnDisabled;
-
-  const createPageAndTransit = useCreatePageAndTransit();
+  const { isCreating, createAndTransit } = useCreatePageAndTransit();
 
 
   const editButtonClickedHandler = useCallback(() => {
   const editButtonClickedHandler = useCallback(() => {
-    createPageAndTransit(
-      path,
-      {
-        onCreationStart: () => { setIsCreating(true) },
-        onError: () => { toastError(t('toaster.create_failed', { target: path })) },
-        onTerminated: () => { setIsCreating(false) },
-      },
-    );
-  }, [createPageAndTransit, path, t]);
+    if (isNotFound == null || isNotFound === false) {
+      mutateEditorMode(EditorMode.Editor);
+      return;
+    }
+
+    try {
+      createAndTransit(
+        { path },
+        { shouldCheckPageExists: true },
+      );
+    }
+    catch (err) {
+      toastError(t('toaster.create_failed', { target: path }));
+    }
+  }, [createAndTransit, isNotFound, mutateEditorMode, path, t]);
+
+  const _isBtnDisabled = isCreating || isBtnDisabled;
 
 
   return (
   return (
     <>
     <>