page-path-rename-utils.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 { toastError, toastSuccess } from '~/client/util/toastr';
  6. import { useFetchCurrentPage, useSetIsUntitledPage } from '~/states/page';
  7. import {
  8. mutatePageList,
  9. mutatePageTree,
  10. mutateRecentlyUpdated,
  11. } from '~/stores/page-listing';
  12. type PagePathRenameHandler = (
  13. newPagePath: string,
  14. onRenameFinish?: () => void,
  15. onRenameFailure?: () => void,
  16. onRenamedSkipped?: () => void,
  17. ) => Promise<void>;
  18. export const usePagePathRenameHandler = (
  19. currentPage?: IPagePopulatedToShowRevision | null,
  20. ): PagePathRenameHandler => {
  21. const { t } = useTranslation();
  22. const { fetchCurrentPage } = useFetchCurrentPage();
  23. const setIsUntitledPage = useSetIsUntitledPage();
  24. const pagePathRenameHandler = useCallback(
  25. async (newPagePath, onRenameFinish, onRenameFailure) => {
  26. if (currentPage == null) {
  27. return;
  28. }
  29. if (newPagePath === currentPage.path || newPagePath === '') {
  30. onRenameFinish?.();
  31. return;
  32. }
  33. const onRenamed = (fromPath: string | undefined, toPath: string) => {
  34. mutatePageTree();
  35. mutateRecentlyUpdated();
  36. mutatePageList();
  37. setIsUntitledPage(false);
  38. if (currentPage.path === fromPath || currentPage.path === toPath) {
  39. fetchCurrentPage({ force: true });
  40. }
  41. };
  42. try {
  43. await apiv3Put('/pages/rename', {
  44. pageId: currentPage._id,
  45. revisionId: currentPage.revision?._id,
  46. newPagePath,
  47. });
  48. onRenamed(currentPage.path, newPagePath);
  49. onRenameFinish?.();
  50. toastSuccess(t('renamed_pages', { path: currentPage.path }));
  51. } catch (err) {
  52. onRenameFailure?.();
  53. toastError(err);
  54. }
  55. },
  56. [currentPage, fetchCurrentPage, setIsUntitledPage, t],
  57. );
  58. return pagePathRenameHandler;
  59. };