aboutsummaryrefslogtreecommitdiffstats
path: root/src/features/workspaces/index.js
blob: 26cadea6434507184893f2a699fafb309ceaf850 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { reaction, runInAction } from 'mobx';
import WorkspacesStore from './store';
import api from './api';
import { workspacesState, resetState } from './state';

const debug = require('debug')('Franz:feature:workspaces');

let store = null;

export const filterServicesByActiveWorkspace = (services) => {
  const { isFeatureActive, activeWorkspace } = workspacesState;
  if (isFeatureActive && activeWorkspace) {
    return services.filter(s => activeWorkspace.services.includes(s.id));
  }
  return services;
};

export const getActiveWorkspaceServices = services => (
  filterServicesByActiveWorkspace(services)
);

export default function initWorkspaces(stores, actions) {
  const { features, user } = stores;

  // Toggle workspace feature
  reaction(
    () => (
      features.features.isWorkspaceEnabled && (
        !features.features.isWorkspacePremiumFeature || user.data.isPremium
      )
    ),
    (isEnabled) => {
      if (isEnabled) {
        debug('Initializing `workspaces` feature');
        store = new WorkspacesStore(stores, api, actions, workspacesState);
        store.initialize();
        runInAction(() => { workspacesState.isFeatureActive = true; });
      } else if (store) {
        debug('Disabling `workspaces` feature');
        runInAction(() => { workspacesState.isFeatureActive = false; });
        store.teardown();
        store = null;
        resetState(); // Reset state to default
      }
    },
    {
      fireImmediately: true,
    },
  );

  // Update active service on workspace switches
  reaction(() => ({
    isFeatureActive: workspacesState.isFeatureActive,
    activeWorkspace: workspacesState.activeWorkspace,
  }), ({ isFeatureActive, activeWorkspace }) => {
    if (!isFeatureActive) return;
    if (activeWorkspace) {
      const services = stores.services.allDisplayed;
      const activeService = services.find(s => s.isActive);
      const workspaceServices = filterServicesByActiveWorkspace(services);
      const isActiveServiceInWorkspace = workspaceServices.includes(activeService);
      if (!isActiveServiceInWorkspace) {
        actions.service.setActive({ serviceId: workspaceServices[0].id });
      }
    }
  });
}