page-path-rename-utils.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { useCallback } from 'react';
  2. import type { IPagePopulatedToShowRevision } from '@growi/core';
  3. import { useTranslation } from 'next-i18next';
  4. import { apiv3Put } from '~/client/util/apiv3-client';
  5. import { toastSuccess, toastError } from '~/client/util/toastr';
  6. import { useSWRMUTxCurrentPage } from '~/stores/page';
  7. import { mutatePageTree, mutatePageList } from '~/stores/page-listing';
  8. import { useIsUntitledPage } from '~/stores/ui';
  9. type PagePathRenameHandler = (newPagePath: string, onRenameFinish?: () => void, onRenameFailure?: () => void, onRenamedSkipped?: () => void) => Promise<void>
  10. export const usePagePathRenameHandler = (
  11. currentPage?: IPagePopulatedToShowRevision | null,
  12. ): PagePathRenameHandler => {
  13. const { t } = useTranslation();
  14. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  15. const { mutate: mutateIsUntitledPage } = useIsUntitledPage();
  16. const pagePathRenameHandler = useCallback(async(newPagePath, onRenameFinish, onRenameFailure) => {
  17. if (currentPage == null) {
  18. return;
  19. }
  20. if (newPagePath === currentPage.path || newPagePath === '') {
  21. onRenameFinish?.();
  22. return;
  23. }
  24. const onRenamed = (fromPath: string | undefined, toPath: string) => {
  25. mutatePageTree();
  26. mutatePageList();
  27. mutateIsUntitledPage(false);
  28. if (currentPage.path === fromPath || currentPage.path === toPath) {
  29. mutateCurrentPage();
  30. }
  31. };
  32. try {
  33. await apiv3Put('/pages/rename', {
  34. pageId: currentPage._id,
  35. revisionId: currentPage.revision?._id,
  36. newPagePath,
  37. });
  38. onRenamed(currentPage.path, newPagePath);
  39. onRenameFinish?.();
  40. toastSuccess(t('renamed_pages', { path: currentPage.path }));
  41. }
  42. catch (err) {
  43. onRenameFailure?.();
  44. toastError(err);
  45. }
  46. }, [currentPage, mutateCurrentPage, mutateIsUntitledPage, t]);
  47. return pagePathRenameHandler;
  48. };