page-header-utils.ts 1.7 KB

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