use-create-template-page.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { useCallback } from 'react';
  2. import { Origin } from '@growi/core';
  3. import { isCreatablePage } from '@growi/core/dist/utils/page-path-utils';
  4. import { normalizePath } from '@growi/core/dist/utils/path-utils';
  5. import type { LabelType } from '~/interfaces/template';
  6. import { useCurrentPagePath } from '~/stores/page';
  7. import { useCreatePageAndTransit } from './use-create-page-and-transit';
  8. type UseCreateTemplatePage = () => {
  9. isCreatable: boolean,
  10. isCreating: boolean,
  11. createTemplate?: (label: LabelType) => Promise<void>,
  12. }
  13. export const useCreateTemplatePage: UseCreateTemplatePage = () => {
  14. const { data: currentPagePath, isLoading: isLoadingPagePath } = useCurrentPagePath();
  15. const { isCreating, createAndTransit } = useCreatePageAndTransit();
  16. const isCreatable = currentPagePath != null && isCreatablePage(normalizePath(`${currentPagePath}/_template`));
  17. const createTemplate = useCallback(async(label: LabelType) => {
  18. if (isLoadingPagePath || !isCreatable) return;
  19. return createAndTransit(
  20. { path: normalizePath(`${currentPagePath}/${label}`), wip: false, origin: Origin.View },
  21. { shouldCheckPageExists: true },
  22. );
  23. }, [currentPagePath, isCreatable, isLoadingPagePath, createAndTransit]);
  24. return {
  25. isCreatable,
  26. isCreating,
  27. createTemplate: isCreatable ? createTemplate : undefined,
  28. };
  29. };