use-start-editing.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { useCallback } from 'react';
  2. import { Origin } from '@growi/core';
  3. import { getParentPath } from '@growi/core/dist/utils/path-utils';
  4. import { useCreatePage } from '~/client/services/create-page';
  5. import { usePageNotFound } from '~/states/page';
  6. import { EditorMode, useEditorMode } from '~/states/ui/editor';
  7. import { shouldCreateWipPage } from '../../utils/should-create-wip-page';
  8. export const useStartEditing = (): ((path?: string) => Promise<void>) => {
  9. const isNotFound = usePageNotFound();
  10. const { setEditorMode } = useEditorMode();
  11. const { create } = useCreatePage();
  12. return useCallback(
  13. async (path?: string) => {
  14. if (!isNotFound) {
  15. setEditorMode(EditorMode.Editor);
  16. return;
  17. }
  18. // Create a new page if it does not exist and transit to the editor mode
  19. try {
  20. const parentPath = path != null ? getParentPath(path) : undefined; // does not have to exist
  21. await create({
  22. path,
  23. parentPath,
  24. wip: shouldCreateWipPage(path),
  25. origin: Origin.View,
  26. });
  27. setEditorMode(EditorMode.Editor);
  28. } catch (err) {
  29. throw new Error(err);
  30. }
  31. },
  32. [create, isNotFound, setEditorMode],
  33. );
  34. };