Workspace.hooks.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { foldersActions } from '$app_reducers/folders/slice';
  2. import { useAppDispatch, useAppSelector } from '$app/stores/store';
  3. import { IPage, pagesActions } from '$app_reducers/pages/slice';
  4. import { workspaceActions } from '$app_reducers/workspace/slice';
  5. import { UserBackendService } from '$app/stores/effects/user/user_bd_svc';
  6. import { useEffect, useState } from 'react';
  7. import { WorkspaceBackendService } from '$app/stores/effects/folder/workspace/workspace_bd_svc';
  8. export const useWorkspace = () => {
  9. const currentUser = useAppSelector((state) => state.currentUser);
  10. const appDispatch = useAppDispatch();
  11. const [userService, setUserService] = useState<UserBackendService | null>(null);
  12. const [workspaceService, setWorkspaceService] = useState<WorkspaceBackendService | null>(null);
  13. const [isReady, setIsReady] = useState(false);
  14. useEffect(() => {
  15. if (currentUser.id) {
  16. setUserService(new UserBackendService(currentUser.id));
  17. }
  18. }, [currentUser]);
  19. useEffect(() => {
  20. if (!userService) return;
  21. void (async () => {
  22. try {
  23. const workspaceSettingPB = await userService.getCurrentWorkspace();
  24. const workspace = workspaceSettingPB.workspace;
  25. appDispatch(workspaceActions.updateWorkspace({ id: workspace.id, name: workspace.name }));
  26. appDispatch(foldersActions.clearFolders());
  27. appDispatch(pagesActions.clearPages());
  28. setWorkspaceService(new WorkspaceBackendService(workspace.id));
  29. } catch (e1) {
  30. // create workspace for first start
  31. const workspace = await userService.createWorkspace({ name: 'New Workspace', desc: '' });
  32. appDispatch(workspaceActions.updateWorkspace({ id: workspace.id, name: workspace.name }));
  33. appDispatch(foldersActions.clearFolders());
  34. appDispatch(pagesActions.clearPages());
  35. }
  36. })();
  37. }, [userService]);
  38. useEffect(() => {
  39. if (!workspaceService) return;
  40. void (async () => {
  41. const rootViews = await workspaceService.getAllViews();
  42. if (rootViews.ok) {
  43. appDispatch(
  44. pagesActions.addInsidePages({
  45. currentPageId: workspaceService.workspaceId,
  46. insidePages: rootViews.val.map<IPage>((v) => ({
  47. id: v.id,
  48. title: v.name,
  49. pageType: v.layout,
  50. showPagesInside: false,
  51. parentPageId: workspaceService.workspaceId,
  52. })),
  53. })
  54. );
  55. setIsReady(true);
  56. }
  57. })();
  58. }, [workspaceService]);
  59. return {};
  60. };