page-header-utils.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import type { Dispatch, SetStateAction } from 'react';
  2. import nodePath from 'path';
  3. import type { IPagePopulatedToShowRevision } from '@growi/core';
  4. import { pathUtils } from '@growi/core/dist/utils';
  5. import { useTranslation } from 'next-i18next';
  6. import { apiv3Put } from '~/client/util/apiv3-client';
  7. import { toastSuccess, toastError } from '~/client/util/toastr';
  8. import { useSWRMUTxCurrentPage } from '~/stores/page';
  9. import { mutatePageTree, mutatePageList } from '~/stores/page-listing';
  10. import { mutateSearching } from '~/stores/search';
  11. export const usePagePathSubmitHandler = (
  12. currentPage: IPagePopulatedToShowRevision, currentPagePath: string, setRenameInputShown: Dispatch<SetStateAction<boolean>>,
  13. ): (inputText: string) => Promise<void> => {
  14. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  15. const { t } = useTranslation();
  16. const onRenamed = (fromPath: string | undefined, toPath: string) => {
  17. mutatePageTree();
  18. mutateSearching();
  19. mutatePageList();
  20. if (currentPagePath === fromPath || currentPagePath === toPath) {
  21. mutateCurrentPage();
  22. }
  23. };
  24. const pagePathSubmitHandler = async(inputText: string) => {
  25. const parentPath = pathUtils.addTrailingSlash(nodePath.dirname(currentPage.path ?? ''));
  26. const newPagePath = nodePath.resolve(parentPath, inputText);
  27. if (newPagePath === currentPage.path) {
  28. setRenameInputShown(false);
  29. return;
  30. }
  31. try {
  32. setRenameInputShown(false);
  33. await apiv3Put('/pages/rename', {
  34. pageId: currentPage._id,
  35. revisionId: currentPage.revision._id,
  36. newPagePath,
  37. });
  38. onRenamed(currentPage.path, newPagePath);
  39. toastSuccess(t('renamed_pages', { path: currentPage.path }));
  40. }
  41. catch (err) {
  42. setRenameInputShown(true);
  43. toastError(err);
  44. }
  45. };
  46. return pagePathSubmitHandler;
  47. };