summaryrefslogtreecommitdiffstats
path: root/browser/components/asrouter/modules/FeatureCalloutBroker.sys.mjs
blob: 3f5ed713f17670c6b44337580a04af8075e4edfb (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
/* 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, {
  FeatureCallout: "resource:///modules/asrouter/FeatureCallout.sys.mjs",
});

/**
 * @typedef {Object} FeatureCalloutOptions
 * @property {Window} win window in which messages will be rendered.
 * @property {{name: String, defaultValue?: String}} [pref] optional pref used
 *   to track progress through a given feature tour. for example:
 *   {
 *     name: "browser.pdfjs.feature-tour",
 *     defaultValue: '{ screen: "FEATURE_CALLOUT_1", complete: false }',
 *   }
 *   or { name: "browser.pdfjs.feature-tour" } (defaultValue is optional)
 * @property {String} [location] string to pass as the page when requesting
 *   messages from ASRouter and sending telemetry.
 * @property {MozBrowser} [browser] <browser> element responsible for the
 *   feature callout. for content pages, this is the browser element that the
 *   callout is being shown in. for chrome, this is the active browser.
 * @property {Function} [cleanup] callback to be invoked when the callout is
 *   removed or the window is unloaded.
 * @property {FeatureCalloutTheme} [theme] optional dynamic color theme.
 */

/** @typedef {import("resource:///modules/asrouter/FeatureCallout.sys.mjs").FeatureCalloutTheme} FeatureCalloutTheme */

/**
 * @typedef {Object} FeatureCalloutItem
 * @property {lazy.FeatureCallout} callout instance of FeatureCallout.
 * @property {Function} [cleanup] cleanup callback.
 * @property {Boolean} showing whether the callout is currently showing.
 */

export class _FeatureCalloutBroker {
  /**
   * Make a new FeatureCallout instance and store it in the callout map. Also
   * add an unload listener to the window to clean up the callout when the
   * window is unloaded.
   * @param {FeatureCalloutOptions} config
   */
  makeFeatureCallout(config) {
    const { win, pref, location, browser, theme } = config;
    // Use an AbortController to clean up the unload listener in case the
    // callout is cleaned up before the window is unloaded.
    const controller = new AbortController();
    const cleanup = () => {
      this.#calloutMap.delete(win);
      controller.abort();
      config.cleanup?.();
    };
    this.#calloutMap.set(win, {
      callout: new lazy.FeatureCallout({
        win,
        pref,
        location,
        context: "chrome",
        browser,
        listener: this.handleFeatureCalloutCallback.bind(this),
        theme,
      }),
      cleanup,
      showing: false,
    });
    win.addEventListener("unload", cleanup, { signal: controller.signal });
  }

  /**
   * Show a feature callout message. For use by ASRouter, to be invoked when a
   * trigger has matched to a feature_callout message.
   * @param {MozBrowser} browser <browser> element associated with the trigger.
   * @param {Object} message feature_callout message from ASRouter.
   *   @see {@link FeatureCalloutMessages.sys.mjs}
   * @returns {Promise<Boolean>} whether the callout was shown.
   */
  async showFeatureCallout(browser, message) {
    // Only show one callout at a time, across all windows.
    if (this.isCalloutShowing) {
      return false;
    }
    const win = browser.ownerGlobal;
    // Avoid showing feature callouts if a dialog or panel is showing.
    if (
      win.gDialogBox?.dialog ||
      [...win.document.querySelectorAll("panel")].some(p => p.state === "open")
    ) {
      return false;
    }
    const currentCallout = this.#calloutMap.get(win);
    // If a custom callout was previously showing, but is no longer showing,
    // tear down the FeatureCallout instance. We avoid tearing them down when
    // they stop showing because they may be shown again, and we want to avoid
    // the overhead of creating a new FeatureCallout instance. But the custom
    // callout instance may be incompatible with the new ASRouter message, so
    // we tear it down and create a new one.
    if (currentCallout && currentCallout.callout.location !== "chrome") {
      currentCallout.cleanup();
    }
    let item = this.#calloutMap.get(win);
    let callout = item?.callout;
    if (item) {
      // If a callout previously showed in this instance, but the new message's
      // tour_pref_name is different, update the old instance's tour properties.
      callout.teardownFeatureTourProgress();
      if (message.content.tour_pref_name) {
        callout.pref = {
          name: message.content.tour_pref_name,
          defaultValue: message.content.tour_pref_default_value,
        };
        callout.setupFeatureTourProgress();
      } else {
        callout.pref = null;
      }
    } else {
      const options = {
        win,
        location: "chrome",
        browser,
        theme: { preset: "chrome" },
      };
      if (message.content.tour_pref_name) {
        options.pref = {
          name: message.content.tour_pref_name,
          defaultValue: message.content.tour_pref_default_value,
        };
      }
      this.makeFeatureCallout(options);
      item = this.#calloutMap.get(win);
      callout = item.callout;
    }
    // Set this to true for now so that we can't be interrupted by another
    // invocation. We'll set it to false below if it ended up not showing.
    item.showing = true;
    item.showing = await callout.showFeatureCallout(message).catch(() => {
      item.cleanup();
      return false;
    });
    return item.showing;
  }

  /**
   * Make a new FeatureCallout instance specific to a special location, tearing
   * down the existing generic FeatureCallout if it exists, and (if no message
   * is passed) requesting a feature callout message to show. Does nothing if a
   * callout is already in progress. This allows the PDF.js feature tour, which
   * simulates content, to be shown in the chrome window without interfering
   * with chrome feature callouts.
   * @param {FeatureCalloutOptions} config
   * @param {Object} message feature_callout message from ASRouter.
   *   @see {@link FeatureCalloutMessages.sys.mjs}
   * @returns {FeatureCalloutItem|null} the callout item, if one was created.
   */
  showCustomFeatureCallout(config, message) {
    if (this.isCalloutShowing) {
      return null;
    }
    const { win, pref, location } = config;
    const currentCallout = this.#calloutMap.get(win);
    if (currentCallout && currentCallout.location !== location) {
      currentCallout.cleanup();
    }
    let item = this.#calloutMap.get(win);
    let callout = item?.callout;
    if (item) {
      callout.teardownFeatureTourProgress();
      callout.pref = pref;
      if (pref) {
        callout.setupFeatureTourProgress();
      }
    } else {
      this.makeFeatureCallout(config);
      item = this.#calloutMap.get(win);
      callout = item.callout;
    }
    item.showing = true;
    // In this case, callers are not necessarily async, so we don't await.
    callout
      .showFeatureCallout(message)
      .then(showing => {
        item.showing = showing;
      })
      .catch(() => {
        item.cleanup();
        item.showing = false;
      });
    /** @type {FeatureCalloutItem} */
    return item;
  }

  handleFeatureCalloutCallback(win, event) {
    switch (event) {
      case "end":
        const item = this.#calloutMap.get(win);
        if (item) {
          item.showing = false;
        }
        break;
    }
  }

  /** @returns {Boolean} whether a callout is currently showing. */
  get isCalloutShowing() {
    return [...this.#calloutMap.values()].some(({ showing }) => showing);
  }

  /** @type {Map<Window, FeatureCalloutItem>} */
  #calloutMap = new Map();
}

export const FeatureCalloutBroker = new _FeatureCalloutBroker();