summaryrefslogtreecommitdiffstats
path: root/browser/extensions/formautofill/content/customElements.js
blob: 0b3d761817b9cc7084fac940624bae7b5c916a73 (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
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
/* 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 file is loaded into the browser window scope.
/* eslint-env mozilla/browser-window */
/* eslint-disable mozilla/balanced-listeners */ // Not relevant since the document gets unloaded.

"use strict";

// Wrap in a block to prevent leaking to window scope.
(() => {
  function sendMessageToBrowser(msgName, data) {
    let { AutoCompleteParent } = ChromeUtils.importESModule(
      "resource://gre/actors/AutoCompleteParent.sys.mjs"
    );

    let actor = AutoCompleteParent.getCurrentActor();
    if (!actor) {
      return;
    }

    actor.manager.getActor("FormAutofill").sendAsyncMessage(msgName, data);
  }

  class MozAutocompleteProfileListitemBase extends MozElements.MozRichlistitem {
    constructor() {
      super();

      /**
       * For form autofill, we want to unify the selection no matter by
       * keyboard navigation or mouseover in order not to confuse user which
       * profile preview is being shown. This field is set to true to indicate
       * that selectedIndex of popup should be changed while mouseover item
       */
      this.selectedByMouseOver = true;
    }

    get _stringBundle() {
      if (!this.__stringBundle) {
        this.__stringBundle = Services.strings.createBundle(
          "chrome://formautofill/locale/formautofill.properties"
        );
      }
      return this.__stringBundle;
    }

    _cleanup() {
      this.removeAttribute("formautofillattached");
      if (this._itemBox) {
        this._itemBox.removeAttribute("size");
      }
    }

    _onOverflow() {}

    _onUnderflow() {}

    handleOverUnderflow() {}

    _adjustAutofillItemLayout() {
      let outerBoxRect = this.parentNode.getBoundingClientRect();

      // Make item fit in popup as XUL box could not constrain
      // item's width
      this._itemBox.style.width = outerBoxRect.width + "px";
      // Use two-lines layout when width is smaller than 150px or
      // 185px if an image precedes the label.
      let oneLineMinRequiredWidth = this.getAttribute("ac-image") ? 185 : 150;

      if (outerBoxRect.width <= oneLineMinRequiredWidth) {
        this._itemBox.setAttribute("size", "small");
      } else {
        this._itemBox.removeAttribute("size");
      }
    }
  }

  MozElements.MozAutocompleteProfileListitem = class MozAutocompleteProfileListitem extends (
    MozAutocompleteProfileListitemBase
  ) {
    static get markup() {
      return `
        <div xmlns="http://www.w3.org/1999/xhtml" class="autofill-item-box">
          <div class="profile-label-col profile-item-col">
            <span class="profile-label-affix"></span>
            <span class="profile-label"></span>
          </div>
          <div class="profile-comment-col profile-item-col">
            <span class="profile-comment"></span>
          </div>
        </div>
        `;
    }

    connectedCallback() {
      if (this.delayConnectedCallback()) {
        return;
      }

      this.textContent = "";

      this.appendChild(this.constructor.fragment);

      this._itemBox = this.querySelector(".autofill-item-box");
      this._labelAffix = this.querySelector(".profile-label-affix");
      this._label = this.querySelector(".profile-label");
      this._comment = this.querySelector(".profile-comment");

      this.initializeAttributeInheritance();
      this._adjustAcItem();
    }

    static get inheritedAttributes() {
      return {
        ".autofill-item-box": "ac-image",
      };
    }

    set selected(val) {
      if (val) {
        this.setAttribute("selected", "true");
      } else {
        this.removeAttribute("selected");
      }

      sendMessageToBrowser("FormAutofill:PreviewProfile");
    }

    get selected() {
      return this.getAttribute("selected") == "true";
    }

    _adjustAcItem() {
      this._adjustAutofillItemLayout();
      this.setAttribute("formautofillattached", "true");
      this._itemBox.style.setProperty(
        "--primary-icon",
        `url(${this.getAttribute("ac-image")})`
      );

      let { primaryAffix, primary, secondary, ariaLabel } = JSON.parse(
        this.getAttribute("ac-value")
      );

      this._labelAffix.textContent = primaryAffix;
      this._label.textContent = primary;
      this._comment.textContent = secondary;
      if (ariaLabel) {
        this.setAttribute("aria-label", ariaLabel);
      }
    }
  };

  customElements.define(
    "autocomplete-profile-listitem",
    MozElements.MozAutocompleteProfileListitem,
    { extends: "richlistitem" }
  );

  class MozAutocompleteProfileListitemFooter extends MozAutocompleteProfileListitemBase {
    static get markup() {
      return `
        <div xmlns="http://www.w3.org/1999/xhtml" class="autofill-item-box autofill-footer">
          <div class="autofill-footer-row autofill-warning"></div>
          <div class="autofill-footer-row autofill-button"></div>
        </div>
      `;
    }

    constructor() {
      super();

      this.addEventListener("click", event => {
        if (event.button != 0) {
          return;
        }

        if (this._warningTextBox.contains(event.originalTarget)) {
          return;
        }

        window.openPreferences("privacy-form-autofill");
      });
    }

    connectedCallback() {
      if (this.delayConnectedCallback()) {
        return;
      }

      this.textContent = "";
      this.appendChild(this.constructor.fragment);

      this._itemBox = this.querySelector(".autofill-footer");
      this._optionButton = this.querySelector(".autofill-button");
      this._warningTextBox = this.querySelector(".autofill-warning");

      /**
       * A handler for updating warning message once selectedIndex has been changed.
       *
       * There're three different states of warning message:
       * 1. None of addresses were selected: We show all the categories intersection of fields in the
       *    form and fields in the results.
       * 2. An address was selested: Show the additional categories that will also be filled.
       * 3. An address was selected, but the focused category is the same as the only one category: Only show
       * the exact category that we're going to fill in.
       *
       * @private
       * @param {object} data
       *        Message data
       * @param {string[]} data.categories
       *        The categories of all the fields contained in the selected address.
       */
      this.updateWarningNote = data => {
        let categories =
          data && data.categories ? data.categories : this._allFieldCategories;
        // 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 = [
          { id: "address", l10nId: "category.address" },
          { id: "name", l10nId: "category.name" },
          { id: "organization", l10nId: "category.organization2" },
          { id: "tel", l10nId: "category.tel" },
          { id: "email", l10nId: "category.email" },
        ];
        let showCategories = hasExtraCategories
          ? orderedCategoryList.filter(
              category =>
                categories.includes(category.id) &&
                category.id != this._focusedCategory
            )
          : [
              orderedCategoryList.find(
                category => category.id == this._focusedCategory
              ),
            ];

        let separator =
          this._stringBundle.GetStringFromName("fieldNameSeparator");
        let warningTextTmplKey = hasExtraCategories
          ? "phishingWarningMessage"
          : "phishingWarningMessage2";
        let categoriesText = showCategories
          .map(category =>
            this._stringBundle.GetStringFromName(category.l10nId)
          )
          .join(separator);

        this._warningTextBox.textContent =
          this._stringBundle.formatStringFromName(warningTextTmplKey, [
            categoriesText,
          ]);
        this.parentNode.parentNode.adjustHeight();
      };

      this._adjustAcItem();
    }

    _onCollapse() {
      if (this.showWarningText) {
        let { FormAutofillParent } = ChromeUtils.importESModule(
          "resource://autofill/FormAutofillParent.sys.mjs"
        );
        FormAutofillParent.removeMessageObserver(this);
      }
      this._itemBox.removeAttribute("no-warning");
    }

    _adjustAcItem() {
      this._adjustAutofillItemLayout();
      this.setAttribute("formautofillattached", "true");

      let buttonTextBundleKey;
      if (this._itemBox.getAttribute("size") == "small") {
        buttonTextBundleKey =
          AppConstants.platform == "macosx"
            ? "autocompleteFooterOptionOSXShort2"
            : "autocompleteFooterOptionShort2";
      } else {
        buttonTextBundleKey =
          AppConstants.platform == "macosx"
            ? "autocompleteFooterOptionOSX2"
            : "autocompleteFooterOption2";
      }

      let buttonText =
        this._stringBundle.GetStringFromName(buttonTextBundleKey);
      this._optionButton.textContent = buttonText;

      let value = JSON.parse(this.getAttribute("ac-value"));

      this._allFieldCategories = value.categories;
      this._focusedCategory = value.focusedCategory;
      this.showWarningText = this._allFieldCategories && this._focusedCategory;

      if (this.showWarningText) {
        let { FormAutofillParent } = ChromeUtils.importESModule(
          "resource://autofill/FormAutofillParent.sys.mjs"
        );
        FormAutofillParent.addMessageObserver(this);
        this.updateWarningNote();
      } else {
        this._itemBox.setAttribute("no-warning", "true");
      }
    }
  }

  customElements.define(
    "autocomplete-profile-listitem-footer",
    MozAutocompleteProfileListitemFooter,
    { extends: "richlistitem" }
  );

  class MozAutocompleteCreditcardInsecureField extends MozAutocompleteProfileListitemBase {
    static get markup() {
      return `
      <div xmlns="http://www.w3.org/1999/xhtml" class="autofill-insecure-item"></div>
      `;
    }

    connectedCallback() {
      if (this.delayConnectedCallback()) {
        return;
      }
      this.textContent = "";
      this.appendChild(this.constructor.fragment);

      this._itemBox = this.querySelector(".autofill-insecure-item");

      this._adjustAcItem();
    }

    set selected(val) {
      // This item is unselectable since we see this item as a pure message.
    }

    get selected() {
      return this.getAttribute("selected") == "true";
    }

    _adjustAcItem() {
      this._adjustAutofillItemLayout();
      this.setAttribute("formautofillattached", "true");

      let value = this.getAttribute("ac-value");
      this._itemBox.textContent = value;
    }
  }

  customElements.define(
    "autocomplete-creditcard-insecure-field",
    MozAutocompleteCreditcardInsecureField,
    { extends: "richlistitem" }
  );

  class MozAutocompleteProfileListitemClearButton extends MozAutocompleteProfileListitemBase {
    static get markup() {
      return `
        <div xmlns="http://www.w3.org/1999/xhtml" class="autofill-item-box autofill-footer">
          <div class="autofill-footer-row autofill-button"></div>
        </div>
      `;
    }

    constructor() {
      super();

      this.addEventListener("click", event => {
        if (event.button != 0) {
          return;
        }

        sendMessageToBrowser("FormAutofill:ClearForm");
      });
    }

    connectedCallback() {
      if (this.delayConnectedCallback()) {
        return;
      }

      this.textContent = "";
      this.appendChild(this.constructor.fragment);

      this._itemBox = this.querySelector(".autofill-item-box");
      this._clearBtn = this.querySelector(".autofill-button");

      this._adjustAcItem();
    }

    _adjustAcItem() {
      this._adjustAutofillItemLayout();
      this.setAttribute("formautofillattached", "true");

      let clearFormBtnLabel =
        this._stringBundle.GetStringFromName("clearFormBtnLabel2");
      this._clearBtn.textContent = clearFormBtnLabel;
    }
  }

  customElements.define(
    "autocomplete-profile-listitem-clear-button",
    MozAutocompleteProfileListitemClearButton,
    { extends: "richlistitem" }
  );
})();