hooks.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { useCallback, useState } from 'react';
  2. import type { IPagePopulatedToShowRevision } from '@growi/core';
  3. import { useRouter } from 'next/router';
  4. import { createPage, exist } from '~/client/services/page-operation';
  5. import { toastError } from '~/client/util/toastr';
  6. export const useOnNewButtonClicked = (
  7. isLoading: boolean,
  8. currentPage?: IPagePopulatedToShowRevision | null,
  9. ): {
  10. onClickHandler: () => Promise<void>,
  11. isPageCreating: boolean
  12. } => {
  13. const router = useRouter();
  14. const [isPageCreating, setIsPageCreating] = useState(false);
  15. const onClickHandler = useCallback(async() => {
  16. if (isLoading) return;
  17. try {
  18. setIsPageCreating(true);
  19. const parentPath = currentPage == null
  20. ? '/'
  21. : currentPage.path;
  22. const params = {
  23. isSlackEnabled: false,
  24. slackChannels: '',
  25. grant: 4,
  26. // grant: currentPage?.grant || 1,
  27. // grantUserGroupId: currentPage?.grantedGroup?._id,
  28. shouldGeneratePath: true,
  29. };
  30. const response = await createPage(parentPath, '', params);
  31. router.push(`${response.page.id}#edit`);
  32. }
  33. catch (err) {
  34. toastError(err);
  35. }
  36. finally {
  37. setIsPageCreating(false);
  38. }
  39. }, [currentPage, isLoading, router]);
  40. return { onClickHandler, isPageCreating };
  41. };
  42. export const useOnTodaysButtonClicked = (
  43. todaysPath: string | null,
  44. ): {
  45. onClickHandler: () => Promise<void>,
  46. isPageCreating: boolean
  47. } => {
  48. const router = useRouter();
  49. const [isPageCreating, setIsPageCreating] = useState(false);
  50. const onClickHandler = useCallback(async() => {
  51. if (todaysPath == null) {
  52. return;
  53. }
  54. try {
  55. setIsPageCreating(true);
  56. // TODO: get grant, grantUserGroupId data from parent page
  57. // https://redmine.weseek.co.jp/issues/133892
  58. const params = {
  59. isSlackEnabled: false,
  60. slackChannels: '',
  61. grant: 4,
  62. };
  63. const res = await exist(JSON.stringify([todaysPath]));
  64. if (!res.pages[todaysPath]) {
  65. await createPage(todaysPath, '', params);
  66. }
  67. router.push(`${todaysPath}#edit`);
  68. }
  69. catch (err) {
  70. toastError(err);
  71. }
  72. finally {
  73. setIsPageCreating(false);
  74. }
  75. }, [router, todaysPath]);
  76. return { onClickHandler, isPageCreating };
  77. };