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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
|
/* 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, {
CreditCard: "resource://gre/modules/CreditCard.sys.mjs",
FormAutofillUtils: "resource://gre/modules/shared/FormAutofillUtils.sys.mjs",
});
ChromeUtils.defineLazyGetter(
lazy,
"l10n",
() => new Localization(["toolkit/formautofill/formAutofill.ftl"], true)
);
class ProfileAutoCompleteResult {
externalEntries = [];
constructor(
searchString,
focusedFieldName,
allFieldNames,
matchingProfiles,
{ resultCode = null, isSecure = true, isInputAutofilled = false }
) {
// nsISupports
this.QueryInterface = ChromeUtils.generateQI(["nsIAutoCompleteResult"]);
// The user's query string
this.searchString = searchString;
// The field name of the focused input.
this._focusedFieldName = focusedFieldName;
// The matching profiles contains the information for filling forms.
this._matchingProfiles = matchingProfiles;
// The default item that should be entered if none is selected
this.defaultIndex = 0;
// The reason the search failed
this.errorDescription = "";
// The value used to determine whether the form is secure or not.
this._isSecure = isSecure;
// The value to indicate whether the focused input has been autofilled or not.
this._isInputAutofilled = isInputAutofilled;
// All fillable field names in the form including the field name of the currently-focused input.
this._allFieldNames = [
...this._matchingProfiles.reduce((fieldSet, curProfile) => {
for (let field of Object.keys(curProfile)) {
fieldSet.add(field);
}
return fieldSet;
}, new Set()),
].filter(field => allFieldNames.includes(field));
// Force return success code if the focused field is auto-filled in order
// to show clear form button popup.
if (isInputAutofilled) {
resultCode = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
}
// The result code of this result object.
if (resultCode) {
this.searchResult = resultCode;
} else {
this.searchResult = matchingProfiles.length
? Ci.nsIAutoCompleteResult.RESULT_SUCCESS
: Ci.nsIAutoCompleteResult.RESULT_NOMATCH;
}
// An array of primary and secondary labels for each profile.
this._popupLabels = this._generateLabels(
this._focusedFieldName,
this._allFieldNames,
this._matchingProfiles
);
}
getAt(index) {
for (const group of [this._popupLabels, this.externalEntries]) {
if (index < group.length) {
return group[index];
}
index -= group.length;
}
throw Components.Exception(
"Index out of range.",
Cr.NS_ERROR_ILLEGAL_VALUE
);
}
/**
* @returns {number} The number of results
*/
get matchCount() {
return this._popupLabels.length + this.externalEntries.length;
}
/**
* Get the secondary label based on the focused field name and related field names
* in the same form.
*
* @param {string} _focusedFieldName The field name of the focused input
* @param {Array<object>} _allFieldNames The field names in the same section
* @param {object} _profile The profile providing the labels to show.
* @returns {string} The secondary label
*/
_getSecondaryLabel(_focusedFieldName, _allFieldNames, _profile) {
return "";
}
_generateLabels(_focusedFieldName, _allFieldNames, _profiles) {}
/**
* Get the value of the result at the given index.
*
* Always return empty string for form autofill feature to suppress
* AutoCompleteController from autofilling, as we'll populate the
* fields on our own.
*
* @param {number} index The index of the result requested
* @returns {string} The result at the specified index
*/
getValueAt(index) {
this.getAt(index);
return "";
}
getLabelAt(index) {
const label = this.getAt(index);
if (typeof label == "string") {
return label;
}
let type = this.getTypeOfIndex(index);
if (type == "clear" || type == "manage") {
return label.primary;
}
return JSON.stringify(label);
}
/**
* Retrieves a comment (metadata instance)
*
* @param {number} index The index of the comment requested
* @returns {string} The comment at the specified index
*/
getCommentAt(index) {
let type = this.getTypeOfIndex(index);
switch (type) {
case "clear":
return '{"fillMessageName": "FormAutofill:ClearForm"}';
case "manage":
return '{"fillMessageName": "FormAutofill:OpenPreferences"}';
case "insecure":
return '{"noLearnMore": true }';
}
const item = this.getAt(index);
return item.comment ?? JSON.stringify(this._matchingProfiles[index]);
}
/**
* Retrieves a style hint specific to a particular index.
*
* @param {number} index The index of the style hint requested
* @returns {string} The style hint at the specified index
*/
getStyleAt(index) {
const itemStyle = this.getAt(index).style;
if (itemStyle) {
return itemStyle;
}
switch (this.getTypeOfIndex(index)) {
case "manage":
return "action";
case "clear":
return "action";
case "insecure":
return "insecureWarning";
default:
return "autofill";
}
}
/**
* Retrieves an image url.
*
* @param {number} index The index of the image url requested
* @returns {string} The image url at the specified index
*/
getImageAt(index) {
return this.getAt(index).image ?? "";
}
/**
* Retrieves a result
*
* @param {number} index The index of the result requested
* @returns {string} The result at the specified index
*/
getFinalCompleteValueAt(index) {
return this.getValueAt(index);
}
/**
* Returns true if the value at the given index is removable
*
* @param {number} _index The index of the result to remove
* @returns {boolean} True if the value is removable
*/
isRemovableAt(_index) {
return false;
}
/**
* Removes a result from the resultset
*
* @param {number} _index The index of the result to remove
*/
removeValueAt(_index) {
// There is no plan to support removing profiles via autocomplete.
}
/**
* Returns a type string that identifies te type of row at the given index.
*
* @param {number} index The index of the result requested
* @returns {string} The type at the specified index
*/
getTypeOfIndex(index) {
if (this._isInputAutofilled && index == 0) {
return "clear";
}
if (index == this._popupLabels.length - 1) {
return "manage";
}
return "item";
}
}
export class AddressResult extends ProfileAutoCompleteResult {
_getSecondaryLabel(focusedFieldName, allFieldNames, profile) {
// We group similar fields into the same field name so we won't pick another
// field in the same group as the secondary label.
const GROUP_FIELDS = {
name: ["name", "given-name", "additional-name", "family-name"],
"street-address": [
"street-address",
"address-line1",
"address-line2",
"address-line3",
],
"country-name": ["country", "country-name"],
tel: [
"tel",
"tel-country-code",
"tel-national",
"tel-area-code",
"tel-local",
"tel-local-prefix",
"tel-local-suffix",
],
};
const secondaryLabelOrder = [
"street-address", // Street address
"name", // Full name
"address-level3", // Townland / Neighborhood / Village
"address-level2", // City/Town
"organization", // Company or organization name
"address-level1", // Province/State (Standardized code if possible)
"country-name", // Country name
"postal-code", // Postal code
"tel", // Phone number
"email", // Email address
];
for (let field in GROUP_FIELDS) {
if (GROUP_FIELDS[field].includes(focusedFieldName)) {
focusedFieldName = field;
break;
}
}
for (const currentFieldName of secondaryLabelOrder) {
if (focusedFieldName == currentFieldName || !profile[currentFieldName]) {
continue;
}
let matching = GROUP_FIELDS[currentFieldName]
? allFieldNames.some(fieldName =>
GROUP_FIELDS[currentFieldName].includes(fieldName)
)
: allFieldNames.includes(currentFieldName);
if (matching) {
if (
currentFieldName == "street-address" &&
profile["-moz-street-address-one-line"]
) {
return profile["-moz-street-address-one-line"];
}
return profile[currentFieldName];
}
}
return ""; // Nothing matched.
}
_generateLabels(focusedFieldName, allFieldNames, profiles) {
const manageLabel = lazy.l10n.formatValueSync(
"autofill-manage-addresses-label"
);
let footerItem = {
primary: manageLabel,
secondary: "",
};
if (this._isInputAutofilled) {
const clearLabel = lazy.l10n.formatValueSync("autofill-clear-form-label");
let labels = [
{
primary: clearLabel,
},
];
labels.push(footerItem);
return labels;
}
let focusedCategory =
lazy.FormAutofillUtils.getCategoryFromFieldName(focusedFieldName);
// Skip results without a primary label.
let labels = profiles
.filter(profile => {
return !!profile[focusedFieldName];
})
.map(profile => {
let primaryLabel = profile[focusedFieldName];
if (
focusedFieldName == "street-address" &&
profile["-moz-street-address-one-line"]
) {
primaryLabel = profile["-moz-street-address-one-line"];
}
let profileFields = allFieldNames.filter(
fieldName => !!profile[fieldName]
);
let categories =
lazy.FormAutofillUtils.getCategoriesFromFieldNames(profileFields);
let status = this.getStatusNote(categories, focusedCategory);
let secondary = this._getSecondaryLabel(
focusedFieldName,
allFieldNames,
profile
);
const ariaLabel = [primaryLabel, secondary, status]
.filter(chunk => !!chunk) // Exclude empty chunks.
.join(" ");
return {
primary: primaryLabel,
secondary,
status,
ariaLabel,
};
});
let allCategories =
lazy.FormAutofillUtils.getCategoriesFromFieldNames(allFieldNames);
if (allCategories && allCategories.length) {
let statusItem = {
primary: "",
secondary: "",
status: this.getStatusNote(allCategories, focusedCategory),
style: "status",
};
labels.push(statusItem);
}
labels.push(footerItem);
return labels;
}
getStatusNote(categories, focusedCategory) {
if (!categories || !categories.length) {
return "";
}
// If the length of categories is 1, that means all the fillable fields are in the same
// category. We will change the way to inform user according to this flag. When the value
// is true, we show "Also autofills ...", otherwise, show "Autofills ..." only.
let hasExtraCategories = categories.length > 1;
// Show the categories in certain order to conform with the spec.
let orderedCategoryList = [
"address",
"name",
"organization",
"tel",
"email",
];
let showCategories = hasExtraCategories
? orderedCategoryList.filter(
category =>
categories.includes(category) && category != focusedCategory
)
: [orderedCategoryList.find(category => category == focusedCategory)];
let formatter = new Intl.ListFormat(undefined, {
style: "narrow",
});
let categoriesText = showCategories.map(category =>
lazy.l10n.formatValueSync("autofill-category-" + category)
);
categoriesText = formatter.format(categoriesText);
let statusTextTmplKey = hasExtraCategories
? "autofill-phishing-warningmessage-extracategory"
: "autofill-phishing-warningmessage";
return lazy.l10n.formatValueSync(statusTextTmplKey, {
categories: categoriesText,
});
}
}
export class CreditCardResult extends ProfileAutoCompleteResult {
_getSecondaryLabel(focusedFieldName, allFieldNames, profile) {
const GROUP_FIELDS = {
"cc-name": [
"cc-name",
"cc-given-name",
"cc-additional-name",
"cc-family-name",
],
"cc-exp": ["cc-exp", "cc-exp-month", "cc-exp-year"],
};
const secondaryLabelOrder = [
"cc-number", // Credit card number
"cc-name", // Full name
"cc-exp", // Expiration date
];
for (let field in GROUP_FIELDS) {
if (GROUP_FIELDS[field].includes(focusedFieldName)) {
focusedFieldName = field;
break;
}
}
for (const currentFieldName of secondaryLabelOrder) {
if (focusedFieldName == currentFieldName || !profile[currentFieldName]) {
continue;
}
let matching = GROUP_FIELDS[currentFieldName]
? allFieldNames.some(fieldName =>
GROUP_FIELDS[currentFieldName].includes(fieldName)
)
: allFieldNames.includes(currentFieldName);
if (matching) {
if (currentFieldName == "cc-number") {
return lazy.CreditCard.formatMaskedNumber(profile[currentFieldName]);
}
return profile[currentFieldName];
}
}
return ""; // Nothing matched.
}
_generateLabels(focusedFieldName, allFieldNames, profiles) {
if (!this._isSecure) {
let brandName =
lazy.FormAutofillUtils.brandBundle.GetStringFromName("brandShortName");
return [
lazy.FormAutofillUtils.stringBundle.formatStringFromName(
"insecureFieldWarningDescription",
[brandName]
),
];
}
const manageLabel = lazy.l10n.formatValueSync(
"autofill-manage-payment-methods-label"
);
let footerItem = {
primary: manageLabel,
};
if (this._isInputAutofilled) {
const clearLabel = lazy.l10n.formatValueSync("autofill-clear-form-label");
let labels = [
{
primary: clearLabel,
},
];
labels.push(footerItem);
return labels;
}
// Skip results without a primary label.
let labels = profiles
.filter(profile => {
return !!profile[focusedFieldName];
})
.map(profile => {
let primary = profile[focusedFieldName];
if (focusedFieldName == "cc-number") {
primary = lazy.CreditCard.formatMaskedNumber(primary);
}
const secondary = this._getSecondaryLabel(
focusedFieldName,
allFieldNames,
profile
);
// The card type is displayed visually using an image. For a11y, we need
// to expose it as text. We do this using aria-label. However,
// aria-label overrides the text content, so we must include that also.
const ccType = profile["cc-type"];
const image = lazy.CreditCard.getCreditCardLogo(ccType);
const ccTypeL10nId = lazy.CreditCard.getNetworkL10nId(ccType);
const ccTypeName = ccTypeL10nId
? lazy.l10n.formatValueSync(ccTypeL10nId)
: ccType ?? ""; // Unknown card type
const ariaLabel = [
ccTypeName,
primary.toString().replaceAll("*", ""),
secondary,
]
.filter(chunk => !!chunk) // Exclude empty chunks.
.join(" ");
return {
primary: primary.toString().replaceAll("*", "•"),
secondary: secondary.toString().replaceAll("*", "•"),
ariaLabel,
image,
};
});
labels.push(footerItem);
return labels;
}
getTypeOfIndex(index) {
if (!this._isSecure) {
return "insecure";
}
return super.getTypeOfIndex(index);
}
}
|