page-path-rename-utils.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, mutateRecentlyUpdated } 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. mutateRecentlyUpdated();
  27. mutatePageList();
  28. mutateIsUntitledPage(false);
  29. if (currentPage.path === fromPath || currentPage.path === toPath) {
  30. mutateCurrentPage();
  31. }
  32. };
  33. try {
  34. await apiv3Put('/pages/rename', {
  35. pageId: currentPage._id,
  36. revisionId: currentPage.revision?._id,
  37. newPagePath,
  38. });
  39. onRenamed(currentPage.path, newPagePath);
  40. onRenameFinish?.();
  41. toastSuccess(t('renamed_pages', { path: currentPage.path }));
  42. }
  43. catch (err) {
  44. onRenameFailure?.();
  45. toastError(err);
  46. }
  47. }, [currentPage, mutateCurrentPage, mutateIsUntitledPage, t]);
  48. return pagePathRenameHandler;
  49. };