aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/reactions/loadServices.ts
blob: 1325a363867a09efc898bd37e0549c7940893298 (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
/*
 * Copyright (C)  2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { reaction } from 'mobx';
import { addDisposer } from 'mobx-state-tree';

import type {
  MainWindow,
  Partition,
  ServiceView,
  ViewFactory,
} from '../infrastructure/electron/types.js';
import type MainStore from '../stores/MainStore.js';
import type Service from '../stores/Service.js';
import getLogger from '../utils/getLogger.js';

const log = getLogger('loadServices');

export default function loadServices(
  store: MainStore,
  viewFactory: ViewFactory,
): void {
  const profilesToPartitions = new Map<string, Partition>();
  const servicesToViews = new Map<string, ServiceView>();

  type ReactionArgs = [
    Map<string, Service>,
    MainWindow | undefined,
    Service | undefined,
    unknown,
  ];

  const disposer = reaction(
    (): ReactionArgs => [
      new Map(store.shared.servicesById),
      store.mainWindow,
      store.visibleService,
      [...store.shared.servicesById.values()].map((service) => [
        service.settings.profile,
        service.shouldBeLoaded,
      ]),
    ],
    ([servicesById, mainWindow, visibleService]: ReactionArgs) => {
      log.debug('Loading service partitions and views');

      const partitionsToDispose = new Map(profilesToPartitions);
      servicesById.forEach((service) => {
        const {
          settings: { profile },
        } = service;
        const { id: profileId } = profile;
        partitionsToDispose.delete(profileId);
        if (!profilesToPartitions.has(profileId)) {
          log.debug('Creating partition for profile', profileId);
          profilesToPartitions.set(
            profileId,
            viewFactory.createPartition(profile),
          );
        }
      });

      const viewsToDispose = new Map(servicesToViews);
      servicesById.forEach((service, serviceId) => {
        if (!service.shouldBeLoaded) {
          return;
        }
        let view = servicesToViews.get(serviceId);
        const {
          settings: {
            profile: { id: profileId },
          },
        } = service;
        if (view === undefined || view.partitionId !== profileId) {
          log.debug('Creating view for service', serviceId);
          const partition = profilesToPartitions.get(profileId);
          if (partition === undefined) {
            throw new Error(`Missing Partition ${profileId}`);
          }
          view = viewFactory.createServiceView(service, partition);
          servicesToViews.set(serviceId, view);
          service.setServiceView(view);
          const { urlToLoad } = service;
          view.loadURL(urlToLoad);
        } else {
          viewsToDispose.delete(serviceId);
        }
      });

      mainWindow?.setServiceView(visibleService?.serviceView);
      log.debug('Visible service is', visibleService?.serviceView?.id);

      viewsToDispose.forEach((view, serviceId) => {
        const currentView = servicesToViews.get(serviceId);
        if (currentView === view) {
          servicesToViews.delete(serviceId);
          const service = store.shared.servicesById.get(serviceId);
          if (service !== undefined) {
            service.setServiceView(undefined);
          }
          log.debug('Disposing view for service', serviceId);
        } else {
          log.debug('Changed partition for service', serviceId);
        }
        view.dispose();
      });

      partitionsToDispose.forEach((partition, profileId) => {
        log.debug('Disposing partition for profile', profileId);
        profilesToPartitions.delete(profileId);
        partition.dispose();
      });
    },
    {
      fireImmediately: true,
    },
  );

  addDisposer(store, () => {
    disposer();
    store.mainWindow?.setServiceView(undefined);
    servicesToViews.forEach((serviceView, serviceId) => {
      store.shared.servicesById.get(serviceId)?.setServiceView(undefined);
      serviceView.dispose();
    });
    profilesToPartitions.forEach((partition) => partition.dispose());
  });
}