aboutsummaryrefslogtreecommitdiffstats
path: root/src/features/workspaces/store.js
blob: ba48022c2aa8f17e31b8daaebd6cce3558c0534f (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import {
  computed,
  observable,
  action,
} from 'mobx';
import localStorage from 'mobx-localstorage';
import { matchRoute } from '../../helpers/routing-helpers';
import { workspaceActions } from './actions';
import { FeatureStore } from '../utils/FeatureStore';
import {
  createWorkspaceRequest,
  deleteWorkspaceRequest,
  getUserWorkspacesRequest,
  updateWorkspaceRequest,
} from './api';
import { WORKSPACES_ROUTES } from './index';

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

export default class WorkspacesStore extends FeatureStore {
  @observable isFeatureEnabled = false;

  @observable isFeatureActive = false;

  @observable isPremiumFeature = true;

  @observable isPremiumUpgradeRequired = true;

  @observable activeWorkspace = null;

  @observable nextWorkspace = null;

  @observable workspaceBeingEdited = null;

  @observable isSwitchingWorkspace = false;

  @observable isWorkspaceDrawerOpen = false;

  @observable isSettingsRouteActive = null;

  @computed get workspaces() {
    if (!this.isFeatureActive) return [];
    return getUserWorkspacesRequest.result || [];
  }

  @computed get settings() {
    return localStorage.getItem('workspaces') || {};
  }

  @computed get userHasWorkspaces() {
    return getUserWorkspacesRequest.wasExecuted && this.workspaces.length > 0;
  }

  start(stores, actions) {
    debug('WorkspacesStore::start');
    this.stores = stores;
    this.actions = actions;

    this._listenToActions([
      [workspaceActions.edit, this._edit],
      [workspaceActions.create, this._create],
      [workspaceActions.delete, this._delete],
      [workspaceActions.update, this._update],
      [workspaceActions.activate, this._setActiveWorkspace],
      [workspaceActions.deactivate, this._deactivateActiveWorkspace],
      [workspaceActions.toggleWorkspaceDrawer, this._toggleWorkspaceDrawer],
      [workspaceActions.openWorkspaceSettings, this._openWorkspaceSettings],
    ]);

    this._startReactions([
      this._setWorkspaceBeingEditedReaction,
      this._setActiveServiceOnWorkspaceSwitchReaction,
      this._setFeatureEnabledReaction,
      this._setIsPremiumFeatureReaction,
      this._activateLastUsedWorkspaceReaction,
      this._openDrawerWithSettingsReaction,
    ]);

    getUserWorkspacesRequest.execute();
    this.isFeatureActive = true;
  }

  stop() {
    debug('WorkspacesStore::stop');
    this.isFeatureActive = false;
    this.activeWorkspace = null;
    this.nextWorkspace = null;
    this.workspaceBeingEdited = null;
    this.isSwitchingWorkspace = false;
    this.isWorkspaceDrawerOpen = false;
  }

  filterServicesByActiveWorkspace = (services) => {
    const { activeWorkspace, isFeatureActive } = this;

    if (!isFeatureActive) return services;
    if (activeWorkspace) {
      return services.filter(s => (
        activeWorkspace.services.includes(s.id)
      ));
    }
    return services;
  };

  // ========== PRIVATE ========= //

  _wasDrawerOpenBeforeSettingsRoute = null;

  _getWorkspaceById = id => this.workspaces.find(w => w.id === id);

  _updateSettings = (changes) => {
    localStorage.setItem('workspaces', {
      ...this.settings,
      ...changes,
    });
  };

  // Actions

  @action _edit = ({ workspace }) => {
    this.stores.router.push(`/settings/workspaces/edit/${workspace.id}`);
  };

  @action _create = async ({ name }) => {
    try {
      const workspace = await createWorkspaceRequest.execute(name);
      await getUserWorkspacesRequest.result.push(workspace);
      this._edit({ workspace });
    } catch (error) {
      throw error;
    }
  };

  @action _delete = async ({ workspace }) => {
    try {
      await deleteWorkspaceRequest.execute(workspace);
      await getUserWorkspacesRequest.result.remove(workspace);
      this.stores.router.push('/settings/workspaces');
    } catch (error) {
      throw error;
    }
  };

  @action _update = async ({ workspace }) => {
    try {
      await updateWorkspaceRequest.execute(workspace);
      // Path local result optimistically
      const localWorkspace = this._getWorkspaceById(workspace.id);
      Object.assign(localWorkspace, workspace);
      this.stores.router.push('/settings/workspaces');
    } catch (error) {
      throw error;
    }
  };

  @action _setActiveWorkspace = ({ workspace }) => {
    // Indicate that we are switching to another workspace
    this.isSwitchingWorkspace = true;
    this.nextWorkspace = workspace;
    // Delay switching to next workspace so that the services loading does not drag down UI
    setTimeout(() => {
      this.activeWorkspace = workspace;
      this._updateSettings({ lastActiveWorkspace: workspace.id });
    }, 100);
    // Indicate that we are done switching to the next workspace
    setTimeout(() => {
      this.isSwitchingWorkspace = false;
      this.nextWorkspace = null;
    }, 1000);
  };

  @action _deactivateActiveWorkspace = () => {
    // Indicate that we are switching to default workspace
    this.isSwitchingWorkspace = true;
    this.nextWorkspace = null;
    this._updateSettings({ lastActiveWorkspace: null });
    // Delay switching to next workspace so that the services loading does not drag down UI
    setTimeout(() => {
      this.activeWorkspace = null;
    }, 100);
    // Indicate that we are done switching to the default workspace
    setTimeout(() => { this.isSwitchingWorkspace = false; }, 1000);
  };

  @action _toggleWorkspaceDrawer = () => {
    this.isWorkspaceDrawerOpen = !this.isWorkspaceDrawerOpen;
  };

  @action _openWorkspaceSettings = () => {
    this.actions.ui.openSettings({ path: 'workspaces' });
  };

  // Reactions

  _setFeatureEnabledReaction = () => {
    const { isWorkspaceEnabled } = this.stores.features.features;
    this.isFeatureEnabled = isWorkspaceEnabled;
  };

  _setIsPremiumFeatureReaction = () => {
    const { features, user } = this.stores;
    const { isPremium } = user.data;
    const { isWorkspacePremiumFeature } = features.features;
    this.isPremiumFeature = isWorkspacePremiumFeature;
    this.isPremiumUpgradeRequired = isWorkspacePremiumFeature && !isPremium;
  };

  _setWorkspaceBeingEditedReaction = () => {
    const { pathname } = this.stores.router.location;
    const match = matchRoute('/settings/workspaces/edit/:id', pathname);
    if (match) {
      this.workspaceBeingEdited = this._getWorkspaceById(match.id);
    }
  };

  _setActiveServiceOnWorkspaceSwitchReaction = () => {
    if (!this.isFeatureActive) return;
    if (this.activeWorkspace) {
      const services = this.stores.services.allDisplayed;
      const activeService = services.find(s => s.isActive);
      const workspaceServices = this.filterServicesByActiveWorkspace(services);
      const isActiveServiceInWorkspace = workspaceServices.includes(activeService);
      if (!isActiveServiceInWorkspace) {
        this.actions.service.setActive({ serviceId: workspaceServices[0].id });
      }
    }
  };

  _activateLastUsedWorkspaceReaction = () => {
    if (!this.activeWorkspace && this.userHasWorkspaces) {
      const { lastActiveWorkspace } = this.settings;
      if (lastActiveWorkspace) {
        const workspace = this._getWorkspaceById(lastActiveWorkspace);
        if (workspace) this._setActiveWorkspace({ workspace });
      }
    }
  };

  _openDrawerWithSettingsReaction = () => {
    const { router } = this.stores;
    const isWorkspaceSettingsRoute = router.location.pathname.includes(WORKSPACES_ROUTES.ROOT);
    const isSwitchingToSettingsRoute = !this.isSettingsRouteActive && isWorkspaceSettingsRoute;
    const isLeavingSettingsRoute = !isWorkspaceSettingsRoute && this.isSettingsRouteActive;

    if (isSwitchingToSettingsRoute) {
      this.isSettingsRouteActive = true;
      this._wasDrawerOpenBeforeSettingsRoute = this.isWorkspaceDrawerOpen;
      if (!this._wasDrawerOpenBeforeSettingsRoute) {
        workspaceActions.toggleWorkspaceDrawer();
      }
    } else if (isLeavingSettingsRoute) {
      this.isSettingsRouteActive = false;
      if (!this._wasDrawerOpenBeforeSettingsRoute && this.isWorkspaceDrawerOpen) {
        workspaceActions.toggleWorkspaceDrawer();
      }
    }
  };
}