summaryrefslogtreecommitdiffstats
path: root/browser/components/urlbar/private/PocketSuggestions.sys.mjs
blob: f15b2106069e736c4493e5f430a445f4fe3421e1 (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
/* 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/. */

import { BaseFeature } from "resource:///modules/urlbar/private/BaseFeature.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  QuickSuggest: "resource:///modules/QuickSuggest.sys.mjs",
  SuggestionsMap: "resource:///modules/urlbar/private/SuggestBackendJs.sys.mjs",
  UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs",
  UrlbarResult: "resource:///modules/UrlbarResult.sys.mjs",
  UrlbarUtils: "resource:///modules/UrlbarUtils.sys.mjs",
});

const RESULT_MENU_COMMAND = {
  HELP: "help",
  NOT_INTERESTED: "not_interested",
  NOT_RELEVANT: "not_relevant",
  SHOW_LESS_FREQUENTLY: "show_less_frequently",
};

/**
 * A feature that manages Pocket suggestions in remote settings.
 */
export class PocketSuggestions extends BaseFeature {
  constructor() {
    super();
    this.#lowConfidenceSuggestionsMap = new lazy.SuggestionsMap();
    this.#highConfidenceSuggestionsMap = new lazy.SuggestionsMap();
  }

  get shouldEnable() {
    return (
      lazy.UrlbarPrefs.get("pocketFeatureGate") &&
      lazy.UrlbarPrefs.get("suggest.pocket") &&
      lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored")
    );
  }

  get enablingPreferences() {
    return ["suggest.pocket", "suggest.quicksuggest.nonsponsored"];
  }

  get merinoProvider() {
    return "pocket";
  }

  get rustSuggestionTypes() {
    return ["Pocket"];
  }

  get showLessFrequentlyCount() {
    let count = lazy.UrlbarPrefs.get("pocket.showLessFrequentlyCount") || 0;
    return Math.max(count, 0);
  }

  get canShowLessFrequently() {
    let cap =
      lazy.UrlbarPrefs.get("pocketShowLessFrequentlyCap") ||
      lazy.QuickSuggest.backend.config?.showLessFrequentlyCap ||
      0;
    return !cap || this.showLessFrequentlyCount < cap;
  }

  enable(enabled) {
    if (enabled) {
      lazy.QuickSuggest.jsBackend.register(this);
    } else {
      lazy.QuickSuggest.jsBackend.unregister(this);
      this.#lowConfidenceSuggestionsMap.clear();
      this.#highConfidenceSuggestionsMap.clear();
    }
  }

  async queryRemoteSettings(searchString) {
    // If the search string matches high confidence suggestions, they should be
    // treated as top picks. Otherwise try to match low confidence suggestions.
    let is_top_pick = false;
    let suggestions = this.#highConfidenceSuggestionsMap.get(searchString);
    if (suggestions.length) {
      is_top_pick = true;
    } else {
      suggestions = this.#lowConfidenceSuggestionsMap.get(searchString);
    }

    let lowerSearchString = searchString.toLocaleLowerCase();
    return suggestions.map(suggestion => {
      // Add `full_keyword` to each matched suggestion. It should be the longest
      // keyword that starts with the user's search string.
      let full_keyword = lowerSearchString;
      let keywords = is_top_pick
        ? suggestion.highConfidenceKeywords
        : suggestion.lowConfidenceKeywords;
      for (let keyword of keywords) {
        if (
          keyword.startsWith(lowerSearchString) &&
          full_keyword.length < keyword.length
        ) {
          full_keyword = keyword;
        }
      }
      return { ...suggestion, is_top_pick, full_keyword };
    });
  }

  async onRemoteSettingsSync(rs) {
    let records = await rs.get({ filters: { type: "pocket-suggestions" } });
    if (!this.isEnabled) {
      return;
    }

    let lowMap = new lazy.SuggestionsMap();
    let highMap = new lazy.SuggestionsMap();

    this.logger.debug(`Got ${records.length} records`);
    for (let record of records) {
      let { buffer } = await rs.attachments.download(record);
      if (!this.isEnabled) {
        return;
      }

      let suggestions = JSON.parse(new TextDecoder("utf-8").decode(buffer));
      this.logger.debug(`Adding ${suggestions.length} suggestions`);

      await lowMap.add(suggestions, {
        keywordsProperty: "lowConfidenceKeywords",
        mapKeyword:
          lazy.SuggestionsMap.MAP_KEYWORD_PREFIXES_STARTING_AT_FIRST_WORD,
      });
      if (!this.isEnabled) {
        return;
      }

      await highMap.add(suggestions, {
        keywordsProperty: "highConfidenceKeywords",
      });
      if (!this.isEnabled) {
        return;
      }
    }

    this.#lowConfidenceSuggestionsMap = lowMap;
    this.#highConfidenceSuggestionsMap = highMap;
  }

  makeResult(queryContext, suggestion, searchString) {
    if (!this.isEnabled) {
      // The feature is disabled on the client, but Merino may still return
      // suggestions anyway, and we filter them out here.
      return null;
    }

    // If the user hasn't clicked the "Show less frequently" command, the
    // suggestion can be shown. Otherwise, the suggestion can be shown if the
    // user typed more than one word with at least `showLessFrequentlyCount`
    // characters after the first word, including spaces.
    if (this.showLessFrequentlyCount) {
      let spaceIndex = searchString.search(/\s/);
      if (
        spaceIndex < 0 ||
        searchString.length - spaceIndex < this.showLessFrequentlyCount
      ) {
        return null;
      }
    }

    if (suggestion.source == "rust") {
      suggestion.is_top_pick = suggestion.isTopPick;
      delete suggestion.isTopPick;

      // The Rust component doesn't implement these properties. For now we use
      // dummy values. See issue #5878 in application-services.
      suggestion.description = suggestion.title;
      suggestion.full_keyword = searchString;
    }

    let url = new URL(suggestion.url);
    url.searchParams.set("utm_medium", "firefox-desktop");
    url.searchParams.set("utm_source", "firefox-suggest");
    url.searchParams.set(
      "utm_campaign",
      "pocket-collections-in-the-address-bar"
    );
    url.searchParams.set("utm_content", "treatment");

    return Object.assign(
      new lazy.UrlbarResult(
        lazy.UrlbarUtils.RESULT_TYPE.URL,
        lazy.UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK,
        ...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
          url: url.href,
          originalUrl: suggestion.url,
          title: [suggestion.title, lazy.UrlbarUtils.HIGHLIGHT.TYPED],
          description: suggestion.is_top_pick ? suggestion.description : "",
          // Use the favicon for non-best matches so the icon exactly matches
          // the Pocket favicon in the user's history and tabs.
          icon: suggestion.is_top_pick
            ? "chrome://global/skin/icons/pocket.svg"
            : "chrome://global/skin/icons/pocket-favicon.ico",
          shouldShowUrl: true,
          bottomTextL10n: {
            id: "firefox-suggest-pocket-bottom-text",
            args: {
              keywordSubstringTyped: searchString,
              keywordSubstringNotTyped: suggestion.full_keyword.substring(
                searchString.length
              ),
            },
          },
          helpUrl: lazy.QuickSuggest.HELP_URL,
        })
      ),
      {
        isRichSuggestion: true,
        richSuggestionIconSize: suggestion.is_top_pick ? 24 : 16,
        showFeedbackMenu: true,
      }
    );
  }

  handleCommand(view, result, selType) {
    switch (selType) {
      case RESULT_MENU_COMMAND.HELP:
        // "help" is handled by UrlbarInput, no need to do anything here.
        break;
      // selType == "dismiss" when the user presses the dismiss key shortcut.
      case "dismiss":
      case RESULT_MENU_COMMAND.NOT_RELEVANT:
        // PocketSuggestions adds the UTM parameters to the original URL and
        // returns it as payload.url in the result. However, as
        // UrlbarProviderQuickSuggest filters suggestions with original URL of
        // provided suggestions, need to use the original URL when adding to the
        // block list.
        lazy.QuickSuggest.blockedSuggestions.add(result.payload.originalUrl);
        result.acknowledgeDismissalL10n = {
          id: "firefox-suggest-dismissal-acknowledgment-one",
        };
        view.controller.removeResult(result);
        break;
      case RESULT_MENU_COMMAND.NOT_INTERESTED:
        lazy.UrlbarPrefs.set("suggest.pocket", false);
        result.acknowledgeDismissalL10n = {
          id: "firefox-suggest-dismissal-acknowledgment-all",
        };
        view.controller.removeResult(result);
        break;
      case RESULT_MENU_COMMAND.SHOW_LESS_FREQUENTLY:
        view.acknowledgeFeedback(result);
        this.incrementShowLessFrequentlyCount();
        if (!this.canShowLessFrequently) {
          view.invalidateResultMenuCommands();
        }
        break;
    }
  }

  getResultCommands(result) {
    let commands = [];

    if (!result.isBestMatch && this.canShowLessFrequently) {
      commands.push({
        name: RESULT_MENU_COMMAND.SHOW_LESS_FREQUENTLY,
        l10n: {
          id: "firefox-suggest-command-show-less-frequently",
        },
      });
    }

    commands.push(
      {
        l10n: {
          id: "firefox-suggest-command-dont-show-this",
        },
        children: [
          {
            name: RESULT_MENU_COMMAND.NOT_RELEVANT,
            l10n: {
              id: "firefox-suggest-command-not-relevant",
            },
          },
          {
            name: RESULT_MENU_COMMAND.NOT_INTERESTED,
            l10n: {
              id: "firefox-suggest-command-not-interested",
            },
          },
        ],
      },
      { name: "separator" },
      {
        name: RESULT_MENU_COMMAND.HELP,
        l10n: {
          id: "urlbar-result-menu-learn-more-about-firefox-suggest",
        },
      }
    );

    return commands;
  }

  incrementShowLessFrequentlyCount() {
    if (this.canShowLessFrequently) {
      lazy.UrlbarPrefs.set(
        "pocket.showLessFrequentlyCount",
        this.showLessFrequentlyCount + 1
      );
    }
  }

  #lowConfidenceSuggestionsMap;
  #highConfidenceSuggestionsMap;
}