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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
|
/* 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/. */
/**
* This module exports a provider that offers a search engine when the user is
* typing a search engine domain.
*/
import {
UrlbarProvider,
UrlbarUtils,
} from "resource:///modules/UrlbarUtils.sys.mjs";
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
UrlbarView: "resource:///modules/UrlbarView.sys.mjs",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs",
UrlbarProviderAutofill: "resource:///modules/UrlbarProviderAutofill.sys.mjs",
UrlbarResult: "resource:///modules/UrlbarResult.sys.mjs",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.sys.mjs",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.sys.mjs",
});
const DYNAMIC_RESULT_TYPE = "onboardTabToSearch";
const VIEW_TEMPLATE = {
attributes: {
selectable: true,
},
children: [
{
name: "no-wrap",
tag: "span",
classList: ["urlbarView-no-wrap"],
children: [
{
name: "icon",
tag: "img",
classList: ["urlbarView-favicon"],
},
{
name: "text-container",
tag: "span",
children: [
{
name: "first-row-container",
tag: "span",
children: [
{
name: "title",
tag: "span",
classList: ["urlbarView-title"],
children: [
{
name: "titleStrong",
tag: "strong",
},
],
},
{
name: "title-separator",
tag: "span",
classList: ["urlbarView-title-separator"],
},
{
name: "action",
tag: "span",
classList: ["urlbarView-action"],
attributes: {
"slide-in": true,
},
},
],
},
{
name: "description",
tag: "span",
},
],
},
],
},
],
};
/**
* Initializes this provider's dynamic result. To be called after the creation
* of the provider singleton.
*/
function initializeDynamicResult() {
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
lazy.UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
}
/**
* Class used to create the provider.
*/
class ProviderTabToSearch extends UrlbarProvider {
constructor() {
super();
this.enginesShown = {
onboarding: new Set(),
regular: new Set(),
};
}
/**
* Returns the name of this provider.
*
* @returns {string} the name of this provider.
*/
get name() {
return "TabToSearch";
}
/**
* Returns the type of this provider.
*
* @returns {integer} one of the types from UrlbarUtils.PROVIDER_TYPE.*
*/
get type() {
return UrlbarUtils.PROVIDER_TYPE.PROFILE;
}
/**
* Whether this provider should be invoked for the given context.
* If this method returns false, the providers manager won't start a query
* with this provider, to save on resources.
*
* @param {UrlbarQueryContext} queryContext The query context object
* @returns {boolean} Whether this provider should be invoked for the search.
*/
async isActive(queryContext) {
return (
queryContext.searchString &&
queryContext.tokens.length == 1 &&
!queryContext.searchMode &&
lazy.UrlbarPrefs.get("suggest.engines")
);
}
/**
* Gets the provider's priority.
*
* @returns {number} The provider's priority for the given query.
*/
getPriority() {
return 0;
}
/**
* This is called only for dynamic result types, when the urlbar view updates
* the view of one of the results of the provider. It should return an object
* describing the view update.
*
* @param {UrlbarResult} result The result whose view will be updated.
* @returns {object} An object describing the view update.
*/
getViewUpdate(result) {
return {
icon: {
attributes: {
src: result.payload.icon,
},
},
titleStrong: {
l10n: {
id: "urlbar-result-action-search-w-engine",
args: {
engine: result.payload.engine,
},
},
},
action: {
l10n: {
id: result.payload.isGeneralPurposeEngine
? "urlbar-result-action-tabtosearch-web"
: "urlbar-result-action-tabtosearch-other-engine",
args: {
engine: result.payload.engine,
},
},
},
description: {
l10n: {
id: "urlbar-tabtosearch-onboard",
},
},
};
}
/**
* Called when a result from the provider is selected. "Selected" refers to
* the user highlighing the result with the arrow keys/Tab, before it is
* picked. onSelection is also called when a user clicks a result. In the
* event of a click, onSelection is called just before onLegacyEngagement.
*
* @param {UrlbarResult} result
* The result that was selected.
*/
onSelection(result) {
// We keep track of the number of times the user interacts with
// tab-to-search onboarding results so we stop showing them after
// `tabToSearch.onboard.interactionsLeft` interactions.
// Also do not increment the counter if the result was interacted with less
// than 5 minutes ago. This is a guard against the user running up the
// counter by interacting with the same result repeatedly.
if (
result.payload.dynamicType &&
(!this.onboardingInteractionAtTime ||
this.onboardingInteractionAtTime < Date.now() - 1000 * 60 * 5)
) {
let interactionsLeft = lazy.UrlbarPrefs.get(
"tabToSearch.onboard.interactionsLeft"
);
if (interactionsLeft > 0) {
lazy.UrlbarPrefs.set(
"tabToSearch.onboard.interactionsLeft",
--interactionsLeft
);
}
this.onboardingInteractionAtTime = Date.now();
}
}
onLegacyEngagement(state, queryContext, details) {
let { result, element } = details;
if (
result?.providerName == this.name &&
result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC
) {
// Confirm search mode, but only for the onboarding (dynamic) result. The
// input will handle confirming search mode for the non-onboarding
// `RESULT_TYPE.SEARCH` result since it sets `providesSearchMode`.
element.ownerGlobal.gURLBar.maybeConfirmSearchModeFromResult({
result,
checkValue: false,
});
}
if (!this.enginesShown.regular.size && !this.enginesShown.onboarding.size) {
return;
}
try {
// urlbar.tabtosearch.* is prerelease-only/opt-in for now. See bug 1686330.
for (let engine of this.enginesShown.regular) {
let scalarKey = lazy.UrlbarSearchUtils.getSearchModeScalarKey({
engineName: engine,
});
Services.telemetry.keyedScalarAdd(
"urlbar.tabtosearch.impressions",
scalarKey,
1
);
}
for (let engine of this.enginesShown.onboarding) {
let scalarKey = lazy.UrlbarSearchUtils.getSearchModeScalarKey({
engineName: engine,
});
Services.telemetry.keyedScalarAdd(
"urlbar.tabtosearch.impressions_onboarding",
scalarKey,
1
);
}
// We also record in urlbar.tips because only it has been approved for use
// in release channels.
Services.telemetry.keyedScalarAdd(
"urlbar.tips",
"tabtosearch-shown",
this.enginesShown.regular.size
);
Services.telemetry.keyedScalarAdd(
"urlbar.tips",
"tabtosearch_onboard-shown",
this.enginesShown.onboarding.size
);
} catch (ex) {
// If your test throws this error or causes another test to throw it, it
// is likely because your test showed a tab-to-search result but did not
// start and end the engagement in which it was shown. Be sure to fire an
// input event to start an engagement and blur the Urlbar to end it.
this.logger.error(
`Exception while recording TabToSearch telemetry: ${ex})`
);
} finally {
// Even if there's an exception, we want to clear these Sets. Otherwise,
// we might get into a state where we repeatedly run the same engines
// through the code above and never record telemetry, because there's an
// error every time.
this.enginesShown.regular.clear();
this.enginesShown.onboarding.clear();
}
}
/**
* Defines whether the view should defer user selection events while waiting
* for the first result from this provider.
*
* @returns {boolean} Whether the provider wants to defer user selection
* events.
*/
get deferUserSelection() {
return true;
}
/**
* Starts querying.
*
* @param {object} queryContext The query context object
* @param {Function} addCallback Callback invoked by the provider to add a new
* result.
* @returns {Promise} resolved when the query stops.
*/
async startQuery(queryContext, addCallback) {
// enginesForDomainPrefix only matches against engine domains.
// Remove trailing slashes and www. from the search string and check if the
// resulting string is worth matching.
let [searchStr] = UrlbarUtils.stripPrefixAndTrim(
queryContext.searchString,
{
stripWww: true,
trimSlash: true,
}
);
// Skip any string that cannot be an origin.
if (
!lazy.UrlbarTokenizer.looksLikeOrigin(searchStr, {
ignoreKnownDomains: true,
noIp: true,
})
) {
return;
}
// Also remove the public suffix, if present, to allow for partial matches.
if (searchStr.includes(".")) {
searchStr = UrlbarUtils.stripPublicSuffixFromHost(searchStr);
}
// Add all matching engines.
let engines = await lazy.UrlbarSearchUtils.enginesForDomainPrefix(
searchStr,
{
matchAllDomainLevels: true,
}
);
if (!engines.length) {
return;
}
const onboardingInteractionsLeft = lazy.UrlbarPrefs.get(
"tabToSearch.onboard.interactionsLeft"
);
// If the engine host begins with the search string, autofill may happen
// for it, and the Muxer will retain the result only if there's a matching
// autofill heuristic result.
// Otherwise, we may have a partial match, where the search string is at
// the boundary of a host part, for example "wiki" in "en.wikipedia.org".
// We put those engines apart, and later we check if their host satisfies
// the autofill threshold. If they do, we mark them with the
// "satisfiesAutofillThreshold" payload property, so the muxer can avoid
// filtering them out.
let partialMatchEnginesByHost = new Map();
for (let engine of engines) {
// Trim the engine host. This will also be set as the result url, so the
// Muxer can use it to filter.
let [host] = UrlbarUtils.stripPrefixAndTrim(engine.searchUrlDomain, {
stripWww: true,
});
// Check if the host may be autofilled.
if (host.startsWith(searchStr.toLocaleLowerCase())) {
if (onboardingInteractionsLeft > 0) {
addCallback(this, makeOnboardingResult(engine));
} else {
addCallback(this, makeResult(queryContext, engine));
}
continue;
}
// Otherwise it may be a partial match that would not be autofilled.
if (host.includes("." + searchStr.toLocaleLowerCase())) {
partialMatchEnginesByHost.set(engine.searchUrlDomain, engine);
// Don't continue here, we are looking for more partial matches.
}
// We also try to match the searchForm domain, because otherwise for an
// engine like ebay, we'd check rover.ebay.com, when the user is likely
// to visit ebay.LANG. The searchForm URL often points to the main host.
let searchFormHost;
try {
searchFormHost = new URL(engine.searchForm).host;
} catch (ex) {
// Invalid url or no searchForm.
}
if (searchFormHost?.includes("." + searchStr)) {
partialMatchEnginesByHost.set(searchFormHost, engine);
}
}
if (partialMatchEnginesByHost.size) {
let host = await lazy.UrlbarProviderAutofill.getTopHostOverThreshold(
queryContext,
Array.from(partialMatchEnginesByHost.keys())
);
if (host) {
let engine = partialMatchEnginesByHost.get(host);
if (onboardingInteractionsLeft > 0) {
addCallback(this, makeOnboardingResult(engine, true));
} else {
addCallback(this, makeResult(queryContext, engine, true));
}
}
}
}
}
function makeOnboardingResult(engine, satisfiesAutofillThreshold = false) {
let [url] = UrlbarUtils.stripPrefixAndTrim(engine.searchUrlDomain, {
stripWww: true,
});
url = url.substr(0, url.length - engine.searchUrlPublicSuffix.length);
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.SEARCH,
{
engine: engine.name,
url,
providesSearchMode: true,
icon: UrlbarUtils.ICON.SEARCH_GLASS,
dynamicType: DYNAMIC_RESULT_TYPE,
satisfiesAutofillThreshold,
}
);
result.resultSpan = 2;
result.suggestedIndex = 1;
return result;
}
function makeResult(context, engine, satisfiesAutofillThreshold = false) {
let [url] = UrlbarUtils.stripPrefixAndTrim(engine.searchUrlDomain, {
stripWww: true,
});
url = url.substr(0, url.length - engine.searchUrlPublicSuffix.length);
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...lazy.UrlbarResult.payloadAndSimpleHighlights(context.tokens, {
engine: engine.name,
isGeneralPurposeEngine: engine.isGeneralPurposeEngine,
url,
providesSearchMode: true,
icon: UrlbarUtils.ICON.SEARCH_GLASS,
query: "",
satisfiesAutofillThreshold,
})
);
result.suggestedIndex = 1;
return result;
}
export var UrlbarProviderTabToSearch = new ProviderTabToSearch();
initializeDynamicResult();
|