page-header-utils.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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,
  11. ): PagePathRenameHandler => {
  12. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  13. const { t } = useTranslation();
  14. const currentPagePath = currentPage.path;
  15. const pagePathRenameHandler = useCallback(async(newPagePath, onRenameFinish, onRenameFailure) => {
  16. const onRenamed = (fromPath: string | undefined, toPath: string) => {
  17. mutatePageTree();
  18. mutatePageList();
  19. if (currentPagePath === fromPath || currentPagePath === toPath) {
  20. mutateCurrentPage();
  21. }
  22. };
  23. if (newPagePath === currentPage.path || newPagePath === '') {
  24. onRenameFinish?.();
  25. return;
  26. }
  27. console.log(newPagePath);
  28. console.log(currentPagePath);
  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._id, currentPage.path, currentPage.revision._id, currentPagePath, mutateCurrentPage, t]);
  44. return pagePathRenameHandler;
  45. };