aboutsummaryrefslogtreecommitdiffstats
path: root/src/features/workspaces/store.ts
blob: 41bf5d6f42ed628a155f642e07f850b74981f9ad (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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { action, computed, makeObservable, observable } from 'mobx';
import localStorage from 'mobx-localstorage';
import matchRoute from '../../helpers/routing-helpers';
import { createReactions } from '../../stores/lib/Reaction';
import { createActionBindings } from '../utils/ActionBinding';
import FeatureStore from '../utils/FeatureStore';
import workspaceActions from './actions';
import {
  createWorkspaceRequest,
  deleteWorkspaceRequest,
  getUserWorkspacesRequest,
  updateWorkspaceRequest,
} from './api';
import { WORKSPACES_ROUTES } from './constants';

import type { Actions } from '../../actions/lib/actions';
import { KEEP_WS_LOADED_USID } from '../../config';
import type Workspace from './models/Workspace';

const debug = require('../../preload-safe-debug')(
  'Ferdium:feature:workspaces:store',
);

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

  @observable activeWorkspace: Workspace | undefined;

  @observable nextWorkspace: Workspace | undefined;

  @observable workspaceBeingEdited: any = null; // TODO: [TS DEBT] fix type later

  @observable isSwitchingWorkspace = false;

  @observable isWorkspaceDrawerOpen = false;

  @observable isSettingsRouteActive = false;

  stores: any; // TODO: [TS DEBT] fix type later

  actions: Actions | undefined;

  constructor() {
    super();

    makeObservable(this);
  }

  @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;
  }

  // eslint-disable-next-line @typescript-eslint/class-literal-property-style
  @computed get isUserAllowedToUseFeature() {
    return true;
  }

  @computed get isAnyWorkspaceActive() {
    return !!this.activeWorkspace;
  }

  // ========== PRIVATE PROPERTIES ========= //

  _wasDrawerOpenBeforeSettingsRoute = false;

  _allActions = [];

  _allReactions = [];

  // ========== PUBLIC API ========= //

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

    // ACTIONS

    this._allActions = createActionBindings([
      [workspaceActions.toggleWorkspaceDrawer, this._toggleWorkspaceDrawer],
      [workspaceActions.openWorkspaceSettings, this._openWorkspaceSettings],
      [workspaceActions.edit, this._edit],
      [workspaceActions.create, this._create],
      [workspaceActions.delete, this._delete],
      [workspaceActions.update, this._update],
      [workspaceActions.activate, this._setActivateWorkspace],
      [workspaceActions.deactivate, this._deactivateActiveWorkspace],
      [
        workspaceActions.toggleKeepAllWorkspacesLoadedSetting,
        this._toggleKeepAllWorkspacesLoadedSetting,
      ],
    ]);
    this._registerActions(this._allActions);

    // REACTIONS

    this._allReactions = createReactions([
      this._openDrawerWithSettingsReaction,
      this._cleanupInvalidServiceReferences,
      this._setActiveServiceOnWorkspaceSwitchReaction,
      this._activateLastUsedWorkspaceReaction,
      this._setWorkspaceBeingEditedReaction,
    ]);
    this._registerReactions(this._allReactions);

    this.isFeatureActive = true;
  }

  @action reset() {
    this._setActiveWorkspace(null);
    this._setNextWorkspace(null);
    this.workspaceBeingEdited = null;
    this._setIsSwitchingWorkspace(false);
    this.isWorkspaceDrawerOpen = false;
  }

  @action stop() {
    super.stop();
    debug('WorkspacesStore::stop');
    this.reset();
    this.isFeatureActive = false;
  }

  filterServicesByActiveWorkspace = services => {
    const { activeWorkspace, isFeatureActive } = this;
    if (isFeatureActive && activeWorkspace) {
      return this.getWorkspaceServices(activeWorkspace);
    }
    return services;
  };

  getWorkspaceServices(workspace) {
    const { services } = this.stores;
    return workspace.services.map(id => services.one(id)).filter(s => !!s);
  }

  // ========== PRIVATE METHODS ========= //

  _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 }) => {
    const workspace = await createWorkspaceRequest.execute(name).promise;
    await getUserWorkspacesRequest.result.push(workspace);
    this._edit({ workspace });
  };

  @action _delete = async ({ workspace }) => {
    await deleteWorkspaceRequest.execute(workspace).promise;
    await getUserWorkspacesRequest.result.remove(workspace);
    this.stores.router.push('/settings/workspaces');
    if (this.activeWorkspace === workspace) {
      this._deactivateActiveWorkspace();
    }
  };

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

  @action _setNextWorkspace(workspace) {
    this.nextWorkspace = workspace;
  }

  @action _setIsSwitchingWorkspace(bool) {
    this.isSwitchingWorkspace = bool;
  }

  @action _setActiveWorkspace(workspace) {
    this.activeWorkspace = workspace;
  }

  @action _setActivateWorkspace = ({ workspace }) => {
    // Indicate that we are switching to another workspace
    this._setIsSwitchingWorkspace(true);
    this._setNextWorkspace(workspace);
    // Delay switching to next workspace so that the services loading does not drag down UI
    setTimeout(() => {
      this._setActiveWorkspace(workspace);
      this._updateSettings({ lastActiveWorkspace: workspace.id });
    }, 100);
    // Indicate that we are done switching to the next workspace
    setTimeout(() => {
      this._setIsSwitchingWorkspace(false);
      this._setNextWorkspace(null);
      if (this.stores.settings.app.splitMode) {
        const serviceNames = new Set(
          this.getWorkspaceServices(workspace).map(service => service.name),
        );
        for (const wrapper of document.querySelectorAll<HTMLDivElement>(
          '.services__webview-wrapper',
        )) {
          wrapper.style.display = serviceNames.has(wrapper.dataset.name)
            ? ''
            : 'none';
        }
      }
    }, 500);
  };

  @action _deactivateActiveWorkspace = () => {
    // Indicate that we are switching to default workspace
    this._setIsSwitchingWorkspace(true);
    this._setNextWorkspace(null);
    this._updateSettings({ lastActiveWorkspace: null });
    // Delay switching to next workspace so that the services loading does not drag down UI
    setTimeout(() => {
      this._setActiveWorkspace(null);
    }, 100);
    // Indicate that we are done switching to the default workspace
    setTimeout(() => {
      this._setIsSwitchingWorkspace(false);
      if (this.stores.settings.app.splitMode) {
        for (const wrapper of document.querySelectorAll<HTMLDivElement>(
          '.services__webview-wrapper',
        )) {
          wrapper.style.display = '';
        }
      }
    }, 500);
  };

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

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

  @action reorderServicesOfActiveWorkspace = async ({ oldIndex, newIndex }) => {
    if (!this.activeWorkspace) {
      return;
    }

    const { services = [] } = this.activeWorkspace;
    // Move services from the old to the new position
    services.splice(newIndex, 0, services.splice(oldIndex, 1)[0]);
    await updateWorkspaceRequest.execute(this.activeWorkspace).promise;
  };

  @action _setOpenDrawerWithSettings() {
    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();
      }
    }
  }

  @action _setWorkspaceBeingEdited(match) {
    this.workspaceBeingEdited = this._getWorkspaceById(match.id);
  }

  _toggleKeepAllWorkspacesLoadedSetting = async () => {
    this._updateSettings({
      keepAllWorkspacesLoaded: !this.settings.keepAllWorkspacesLoaded,
    });
  };

  // Reactions

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

  _setActiveServiceOnWorkspaceSwitchReaction = () => {
    if (!this.isFeatureActive) return;
    if (this.activeWorkspace) {
      const activeService = this.stores.services.active;
      const workspaceServices = this.getWorkspaceServices(this.activeWorkspace);
      if (workspaceServices.length <= 0) return;
      const isActiveServiceInWorkspace =
        workspaceServices.includes(activeService);
      if (!isActiveServiceInWorkspace && this.actions) {
        this.actions.service.setActive({
          serviceId: workspaceServices[0].id,
          keepActiveRoute: true,
        });
      }
    }
  };

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

  _openDrawerWithSettingsReaction = () => {
    this._setOpenDrawerWithSettings();
  };

  _cleanupInvalidServiceReferences = () => {
    const { services } = this.stores;
    const { allServicesRequest } = services;
    const servicesHaveBeenLoaded =
      allServicesRequest.wasExecuted && !allServicesRequest.isError;
    // Loop through all workspaces and remove invalid service ids (locally)
    for (const workspace of this.workspaces) {
      for (const serviceId of workspace.services) {
        if (
          servicesHaveBeenLoaded &&
          !services.one(serviceId) &&
          serviceId !== KEEP_WS_LOADED_USID
        ) {
          workspace.services.remove(serviceId);
        }
      }
    }
  };
}