page-path-rename-utils.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. type PagePathRenameHandler = (newPagePath: string, onRenameFinish?: () => void, onRenameFailure?: () => void) => Promise<void>
  9. export const usePagePathRenameHandler = (
  10. currentPage?: IPagePopulatedToShowRevision | null,
  11. ): PagePathRenameHandler => {
  12. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  13. const { t } = useTranslation();
  14. const pagePathRenameHandler = useCallback(async(newPagePath, onRenameFinish, onRenameFailure) => {
  15. if (currentPage == null) {
  16. return;
  17. }
  18. const onRenamed = (fromPath: string | undefined, toPath: string) => {
  19. mutatePageTree();
  20. mutatePageList();
  21. if (currentPage.path === fromPath || currentPage.path === toPath) {
  22. mutateCurrentPage();
  23. }
  24. };
  25. if (newPagePath === currentPage.path || newPagePath === '') {
  26. onRenameFinish?.();
  27. return;
  28. }
  29. try {
  30. await apiv3Put('/pages/rename', {
  31. pageId: currentPage._id,
  32. revisionId: currentPage.revision?._id,
  33. newPagePath,
  34. });
  35. onRenamed(currentPage.path, newPagePath);
  36. onRenameFinish?.();
  37. toastSuccess(t('renamed_pages', { path: currentPage.path }));
  38. }
  39. catch (err) {
  40. onRenameFailure?.();
  41. toastError(err);
  42. }
  43. }, [currentPage, mutateCurrentPage, t]);
  44. return pagePathRenameHandler;
  45. };