summaryrefslogtreecommitdiffstats
path: root/browser/components/firefoxview/SyncedTabsController.sys.mjs
blob: 6ab8249bfea59790f17838445a28fab30dcd5fc5 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  ObjectUtils: "resource://gre/modules/ObjectUtils.sys.mjs",
  SyncedTabs: "resource://services-sync/SyncedTabs.sys.mjs",
});

import { SyncedTabsErrorHandler } from "resource:///modules/firefox-view-synced-tabs-error-handler.sys.mjs";
import { TabsSetupFlowManager } from "resource:///modules/firefox-view-tabs-setup-manager.sys.mjs";
import { searchTabList } from "chrome://browser/content/firefoxview/helpers.mjs";

const SYNCED_TABS_CHANGED = "services.sync.tabs.changed";
const TOPIC_SETUPSTATE_CHANGED = "firefox-view.setupstate.changed";

/**
 * The controller for synced tabs components.
 *
 * @implements {ReactiveController}
 */
export class SyncedTabsController {
  /**
   * @type {boolean}
   */
  contextMenu;
  currentSetupStateIndex = -1;
  currentSyncedTabs = [];
  devices = [];
  /**
   * The current error state as determined by `SyncedTabsErrorHandler`.
   *
   * @type {number}
   */
  errorState = null;
  /**
   * Component associated with this controller.
   *
   * @type {ReactiveControllerHost}
   */
  host;
  /**
   * @type {Function}
   */
  pairDeviceCallback;
  searchQuery = "";
  /**
   * @type {Function}
   */
  signupCallback;

  /**
   * Construct a new SyncedTabsController.
   *
   * @param {ReactiveControllerHost} host
   * @param {object} options
   * @param {boolean} [options.contextMenu]
   *   Whether synced tab items have a secondary context menu.
   * @param {Function} [options.pairDeviceCallback]
   *   The function to call when the pair device window is opened.
   * @param {Function} [options.signupCallback]
   *   The function to call when the signup window is opened.
   */
  constructor(host, { contextMenu, pairDeviceCallback, signupCallback } = {}) {
    this.contextMenu = contextMenu;
    this.pairDeviceCallback = pairDeviceCallback;
    this.signupCallback = signupCallback;
    this.observe = this.observe.bind(this);
    this.host = host;
    this.host.addController(this);
  }

  hostConnected() {
    this.host.addEventListener("click", this);
  }

  hostDisconnected() {
    this.host.removeEventListener("click", this);
  }

  addSyncObservers() {
    Services.obs.addObserver(this.observe, SYNCED_TABS_CHANGED);
    Services.obs.addObserver(this.observe, TOPIC_SETUPSTATE_CHANGED);
  }

  removeSyncObservers() {
    Services.obs.removeObserver(this.observe, SYNCED_TABS_CHANGED);
    Services.obs.removeObserver(this.observe, TOPIC_SETUPSTATE_CHANGED);
  }

  handleEvent(event) {
    if (event.type == "click" && event.target.dataset.action) {
      const { ErrorType } = SyncedTabsErrorHandler;
      switch (event.target.dataset.action) {
        case `${ErrorType.SYNC_ERROR}`:
        case `${ErrorType.NETWORK_OFFLINE}`:
        case `${ErrorType.PASSWORD_LOCKED}`: {
          TabsSetupFlowManager.tryToClearError();
          break;
        }
        case `${ErrorType.SIGNED_OUT}`:
        case "sign-in": {
          TabsSetupFlowManager.openFxASignup(event.target.ownerGlobal);
          this.signupCallback?.();
          break;
        }
        case "add-device": {
          TabsSetupFlowManager.openFxAPairDevice(event.target.ownerGlobal);
          this.pairDeviceCallback?.();
          break;
        }
        case "sync-tabs-disabled": {
          TabsSetupFlowManager.syncOpenTabs(event.target);
          break;
        }
        case `${ErrorType.SYNC_DISCONNECTED}`: {
          const win = event.target.ownerGlobal;
          const { switchToTabHavingURI } =
            win.docShell.chromeEventHandler.ownerGlobal;
          switchToTabHavingURI(
            "about:preferences?action=choose-what-to-sync#sync",
            true,
            {}
          );
          break;
        }
      }
    }
  }

  async observe(_, topic, errorState) {
    if (topic == TOPIC_SETUPSTATE_CHANGED) {
      await this.updateStates(errorState);
    }
    if (topic == SYNCED_TABS_CHANGED) {
      await this.getSyncedTabData();
    }
  }

  async updateStates(errorState) {
    let stateIndex = TabsSetupFlowManager.uiStateIndex;
    errorState = errorState || SyncedTabsErrorHandler.getErrorType();

    if (stateIndex == 4 && this.currentSetupStateIndex !== stateIndex) {
      // trigger an initial request for the synced tabs list
      await this.getSyncedTabData();
    }

    this.currentSetupStateIndex = stateIndex;
    this.errorState = errorState;
    this.host.requestUpdate();
  }

  actionMappings = {
    "sign-in": {
      header: "firefoxview-syncedtabs-signin-header",
      description: "firefoxview-syncedtabs-signin-description",
      buttonLabel: "firefoxview-syncedtabs-signin-primarybutton",
    },
    "add-device": {
      header: "firefoxview-syncedtabs-adddevice-header",
      description: "firefoxview-syncedtabs-adddevice-description",
      buttonLabel: "firefoxview-syncedtabs-adddevice-primarybutton",
      descriptionLink: {
        name: "url",
        url: "https://support.mozilla.org/kb/how-do-i-set-sync-my-computer#w_connect-additional-devices-to-sync",
      },
    },
    "sync-tabs-disabled": {
      header: "firefoxview-syncedtabs-synctabs-header",
      description: "firefoxview-syncedtabs-synctabs-description",
      buttonLabel: "firefoxview-tabpickup-synctabs-primarybutton",
    },
    loading: {
      header: "firefoxview-syncedtabs-loading-header",
      description: "firefoxview-syncedtabs-loading-description",
    },
  };

  #getMessageCardForState({ error = false, action, errorState }) {
    errorState = errorState || this.errorState;
    let header,
      description,
      descriptionLink,
      buttonLabel,
      headerIconUrl,
      mainImageUrl;
    let descriptionArray;
    if (error) {
      let link;
      ({ header, description, link, buttonLabel } =
        SyncedTabsErrorHandler.getFluentStringsForErrorType(errorState));
      action = `${errorState}`;
      headerIconUrl = "chrome://global/skin/icons/info-filled.svg";
      mainImageUrl =
        "chrome://browser/content/firefoxview/synced-tabs-error.svg";
      descriptionArray = [description];
      if (errorState == "password-locked") {
        descriptionLink = {};
        // This is ugly, but we need to special case this link so we can
        // coexist with the old view.
        descriptionArray.push("firefoxview-syncedtab-password-locked-link");
        descriptionLink.name = "syncedtab-password-locked-link";
        descriptionLink.url = link.href;
      }
    } else {
      header = this.actionMappings[action].header;
      description = this.actionMappings[action].description;
      buttonLabel = this.actionMappings[action].buttonLabel;
      descriptionLink = this.actionMappings[action].descriptionLink;
      mainImageUrl =
        "chrome://browser/content/firefoxview/synced-tabs-error.svg";
      descriptionArray = [description];
    }
    return {
      action,
      buttonLabel,
      descriptionArray,
      descriptionLink,
      error,
      header,
      headerIconUrl,
      mainImageUrl,
    };
  }

  getRenderInfo() {
    let renderInfo = {};
    for (let tab of this.currentSyncedTabs) {
      if (!(tab.client in renderInfo)) {
        renderInfo[tab.client] = {
          name: tab.device,
          deviceType: tab.deviceType,
          tabs: [],
        };
      }
      renderInfo[tab.client].tabs.push(tab);
    }

    // Add devices without tabs
    for (let device of this.devices) {
      if (!(device.id in renderInfo)) {
        renderInfo[device.id] = {
          name: device.name,
          deviceType: device.clientType,
          tabs: [],
        };
      }
    }

    for (let id in renderInfo) {
      renderInfo[id].tabItems = this.searchQuery
        ? searchTabList(this.searchQuery, this.getTabItems(renderInfo[id].tabs))
        : this.getTabItems(renderInfo[id].tabs);
    }
    return renderInfo;
  }

  getMessageCard() {
    switch (this.currentSetupStateIndex) {
      case 0 /* error-state */:
        if (this.errorState) {
          return this.#getMessageCardForState({ error: true });
        }
        return this.#getMessageCardForState({ action: "loading" });
      case 1 /* not-signed-in */:
        if (Services.prefs.prefHasUserValue("services.sync.lastversion")) {
          // If this pref is set, the user has signed out of sync.
          // This path is also taken if we are disconnected from sync. See bug 1784055
          return this.#getMessageCardForState({
            error: true,
            errorState: "signed-out",
          });
        }
        return this.#getMessageCardForState({ action: "sign-in" });
      case 2 /* connect-secondary-device*/:
        return this.#getMessageCardForState({ action: "add-device" });
      case 3 /* disabled-tab-sync */:
        return this.#getMessageCardForState({ action: "sync-tabs-disabled" });
      case 4 /* synced-tabs-loaded*/:
        // There seems to be an edge case where sync says everything worked
        // fine but we have no devices.
        if (!this.devices.length) {
          return this.#getMessageCardForState({ action: "add-device" });
        }
    }
    return null;
  }

  getTabItems(tabs) {
    return tabs?.map(tab => ({
      icon: tab.icon,
      title: tab.title,
      time: tab.lastUsed * 1000,
      url: tab.url,
      primaryL10nId: "firefoxview-tabs-list-tab-button",
      primaryL10nArgs: JSON.stringify({ targetURI: tab.url }),
      secondaryL10nId: this.contextMenu
        ? "fxviewtabrow-options-menu-button"
        : undefined,
      secondaryL10nArgs: this.contextMenu
        ? JSON.stringify({ tabTitle: tab.title })
        : undefined,
    }));
  }

  updateTabsList(syncedTabs) {
    if (!syncedTabs.length) {
      this.currentSyncedTabs = syncedTabs;
    }

    const tabsToRender = syncedTabs;

    // Return early if new tabs are the same as previous ones
    if (lazy.ObjectUtils.deepEqual(tabsToRender, this.currentSyncedTabs)) {
      return;
    }

    this.currentSyncedTabs = tabsToRender;
    this.host.requestUpdate();
  }

  async getSyncedTabData() {
    this.devices = await lazy.SyncedTabs.getTabClients();
    let tabs = await lazy.SyncedTabs.createRecentTabsList(this.devices, 50, {
      removeAllDupes: false,
      removeDeviceDupes: true,
    });

    this.updateTabsList(tabs);
  }
}