use-create-todays-memo.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { useCallback } from 'react';
  2. import { Origin } from '@growi/core';
  3. import { userHomepagePath } from '@growi/core/dist/utils/page-path-utils';
  4. import { format } from 'date-fns/format';
  5. import { useTranslation } from 'react-i18next';
  6. import { useCreatePageAndTransit } from '~/client/services/create-page';
  7. import { apiv3Get } from '~/client/util/apiv3-client';
  8. import { useCurrentUser } from '~/stores/context';
  9. type UseCreateTodaysMemo = () => {
  10. isCreating: boolean,
  11. todaysPath: string | null,
  12. createTodaysMemo: () => Promise<void>,
  13. }
  14. export const useCreateTodaysMemo: UseCreateTodaysMemo = () => {
  15. const { t } = useTranslation('commons');
  16. const { data: currentUser } = useCurrentUser();
  17. const { isCreating, createAndTransit } = useCreatePageAndTransit();
  18. const isCreatable = currentUser != null;
  19. const parentDirName = t('create_page_dropdown.todays.memo');
  20. const now = format(new Date(), 'yyyy/MM/dd');
  21. const todaysPath = isCreatable
  22. ? `${userHomepagePath(currentUser)}/${parentDirName}/${now}`
  23. : null;
  24. const createTodaysMemo = useCallback(async() => {
  25. if (!isCreatable || todaysPath == null) return;
  26. const res = await apiv3Get('/page/non-empty-closest-ancestor', { path: todaysPath });
  27. const parentPath = res.data.nonEmptyClosestAncestor?.path;
  28. return createAndTransit(
  29. {
  30. path: todaysPath, parentPath, wip: true, origin: Origin.View,
  31. },
  32. { shouldCheckPageExists: true },
  33. );
  34. }, [createAndTransit, isCreatable, todaysPath]);
  35. return {
  36. isCreating,
  37. todaysPath,
  38. createTodaysMemo,
  39. };
  40. };