summaryrefslogtreecommitdiffstats
path: root/toolkit/content/widgets/autocomplete-richlistitem.js
blob: ccbd37e132b776923adcf6e49af78939ae0618f6 (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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
/* 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/. */

"use strict";

// This is loaded into all XUL windows. Wrap in a block to prevent
// leaking to window scope.
{
  const { LoginHelper } = ChromeUtils.importESModule(
    "resource://gre/modules/LoginHelper.sys.mjs"
  );

  MozElements.MozAutocompleteRichlistitem = class MozAutocompleteRichlistitem extends (
    MozElements.MozRichlistitem
  ) {
    constructor() {
      super();

      /**
       * This overrides listitem's mousedown handler because we want to set the
       * selected item even when the shift or accel keys are pressed.
       */
      this.addEventListener("mousedown", event => {
        // Call this.control only once since it's not a simple getter.
        let control = this.control;
        if (!control || control.disabled) {
          return;
        }
        if (!this.selected) {
          control.selectItem(this);
        }
        control.currentItem = this;
      });

      this.addEventListener("mouseover", event => {
        // The point of implementing this handler is to allow drags to change
        // the selected item.  If the user mouses down on an item, it becomes
        // selected.  If they then drag the mouse to another item, select it.
        // Handle all three primary mouse buttons: right, left, and wheel, since
        // all three change the selection on mousedown.
        let mouseDown = event.buttons & 0b111;
        if (!mouseDown) {
          return;
        }
        // Call this.control only once since it's not a simple getter.
        let control = this.control;
        if (!control || control.disabled) {
          return;
        }
        if (!this.selected) {
          control.selectItem(this);
        }
        control.currentItem = this;
      });

      this.addEventListener("overflow", () => this._onOverflow());
      this.addEventListener("underflow", () => this._onUnderflow());
    }

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

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

      this._boundaryCutoff = null;
      this._inOverflow = false;

      this._adjustAcItem();
    }

    static get inheritedAttributes() {
      return {
        ".ac-type-icon": "selected,current,type",
        ".ac-site-icon": "src=image,selected,type",
        ".ac-title": "selected",
        ".ac-title-text": "selected",
        ".ac-separator": "selected,type",
        ".ac-url": "selected",
        ".ac-url-text": "selected",
      };
    }

    static get markup() {
      return `
      <image class="ac-type-icon"/>
      <image class="ac-site-icon"/>
      <hbox class="ac-title" align="center">
        <description class="ac-text-overflow-container">
          <description class="ac-title-text"/>
        </description>
      </hbox>
      <hbox class="ac-separator" align="center">
        <description class="ac-separator-text" value="—"/>
      </hbox>
      <hbox class="ac-url" align="center" aria-hidden="true">
        <description class="ac-text-overflow-container">
          <description class="ac-url-text"/>
        </description>
      </hbox>
    `;
    }

    get _typeIcon() {
      return this.querySelector(".ac-type-icon");
    }

    get _titleText() {
      return this.querySelector(".ac-title-text");
    }

    get _separator() {
      return this.querySelector(".ac-separator");
    }

    get _urlText() {
      return this.querySelector(".ac-url-text");
    }

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

    get boundaryCutoff() {
      if (!this._boundaryCutoff) {
        this._boundaryCutoff = Services.prefs.getIntPref(
          "toolkit.autocomplete.richBoundaryCutoff"
        );
      }
      return this._boundaryCutoff;
    }

    _cleanup() {
      this.removeAttribute("url");
      this.removeAttribute("image");
      this.removeAttribute("title");
      this.removeAttribute("text");
    }

    _onOverflow() {
      this._inOverflow = true;
      this._handleOverflow();
    }

    _onUnderflow() {
      this._inOverflow = false;
      this._handleOverflow();
    }

    _getBoundaryIndices(aText, aSearchTokens) {
      // Short circuit for empty search ([""] == "")
      if (aSearchTokens == "") {
        return [0, aText.length];
      }

      // Find which regions of text match the search terms
      let regions = [];
      for (let search of Array.prototype.slice.call(aSearchTokens)) {
        let matchIndex = -1;
        let searchLen = search.length;

        // Find all matches of the search terms, but stop early for perf
        let lowerText = aText.substr(0, this.boundaryCutoff).toLowerCase();
        while ((matchIndex = lowerText.indexOf(search, matchIndex + 1)) >= 0) {
          regions.push([matchIndex, matchIndex + searchLen]);
        }
      }

      // Sort the regions by start position then end position
      regions = regions.sort((a, b) => {
        let start = a[0] - b[0];
        return start == 0 ? a[1] - b[1] : start;
      });

      // Generate the boundary indices from each region
      let start = 0;
      let end = 0;
      let boundaries = [];
      let len = regions.length;
      for (let i = 0; i < len; i++) {
        // We have a new boundary if the start of the next is past the end
        let region = regions[i];
        if (region[0] > end) {
          // First index is the beginning of match
          boundaries.push(start);
          // Second index is the beginning of non-match
          boundaries.push(end);

          // Track the new region now that we've stored the previous one
          start = region[0];
        }

        // Push back the end index for the current or new region
        end = Math.max(end, region[1]);
      }

      // Add the last region
      boundaries.push(start);
      boundaries.push(end);

      // Put on the end boundary if necessary
      if (end < aText.length) {
        boundaries.push(aText.length);
      }

      // Skip the first item because it's always 0
      return boundaries.slice(1);
    }

    _getSearchTokens(aSearch) {
      let search = aSearch.toLowerCase();
      return search.split(/\s+/);
    }

    _setUpDescription(aDescriptionElement, aText) {
      // Get rid of all previous text
      if (!aDescriptionElement) {
        return;
      }
      while (aDescriptionElement.hasChildNodes()) {
        aDescriptionElement.firstChild.remove();
      }

      // Get the indices that separate match and non-match text
      let search = this.getAttribute("text");
      let tokens = this._getSearchTokens(search);
      let indices = this._getBoundaryIndices(aText, tokens);

      this._appendDescriptionSpans(
        indices,
        aText,
        aDescriptionElement,
        aDescriptionElement
      );
    }

    _appendDescriptionSpans(
      indices,
      text,
      spansParentElement,
      descriptionElement
    ) {
      let next;
      let start = 0;
      let len = indices.length;
      // Even indexed boundaries are matches, so skip the 0th if it's empty
      for (let i = indices[0] == 0 ? 1 : 0; i < len; i++) {
        next = indices[i];
        let spanText = text.substr(start, next - start);
        start = next;

        if (i % 2 == 0) {
          // Emphasize the text for even indices
          let span = spansParentElement.appendChild(
            document.createElementNS("http://www.w3.org/1999/xhtml", "span")
          );
          this._setUpEmphasisSpan(span, descriptionElement);
          span.textContent = spanText;
        } else {
          // Otherwise, it's plain text
          spansParentElement.appendChild(document.createTextNode(spanText));
        }
      }
    }

    _setUpEmphasisSpan(aSpan, aDescriptionElement) {
      aSpan.classList.add("ac-emphasize-text");
      switch (aDescriptionElement) {
        case this._titleText:
          aSpan.classList.add("ac-emphasize-text-title");
          break;
        case this._urlText:
          aSpan.classList.add("ac-emphasize-text-url");
          break;
      }
    }

    /**
     * This will generate an array of emphasis pairs for use with
     * _setUpEmphasisedSections(). Each pair is a tuple (array) that
     * represents a block of text - containing the text of that block, and a
     * boolean for whether that block should have an emphasis styling applied
     * to it.
     *
     * These pairs are generated by parsing a localised string (aSourceString)
     * with parameters, in the format that is used by
     * nsIStringBundle.formatStringFromName():
     *
     * "textA %1$S textB textC %2$S"
     *
     * Or:
     *
     * "textA %S"
     *
     * Where "%1$S", "%2$S", and "%S" are intended to be replaced by provided
     * replacement strings. These are specified an array of tuples
     * (aReplacements), each containing the replacement text and a boolean for
     * whether that text should have an emphasis styling applied. This is used
     * as a 1-based array - ie, "%1$S" is replaced by the item in the first
     * index of aReplacements, "%2$S" by the second, etc. "%S" will always
     * match the first index.
     */
    _generateEmphasisPairs(aSourceString, aReplacements) {
      let pairs = [];

      // Split on %S, %1$S, %2$S, etc. ie:
      //   "textA %S"
      //     becomes ["textA ", "%S"]
      //   "textA %1$S textB textC %2$S"
      //     becomes ["textA ", "%1$S", " textB textC ", "%2$S"]
      let parts = aSourceString.split(/(%(?:[0-9]+\$)?S)/);

      for (let part of parts) {
        // The above regex will actually give us an empty string at the
        // end - we don't want that, as we don't want to later generate an
        // empty text node for it.
        if (part.length === 0) {
          continue;
        }

        // Determine if this token is a replacement token or a normal text
        // token. If it is a replacement token, we want to extract the
        // numerical number. However, we still want to match on "$S".
        let match = part.match(/^%(?:([0-9]+)\$)?S$/);

        if (match) {
          // "%S" doesn't have a numerical number in it, but will always
          // be assumed to be 1. Furthermore, the input string specifies
          // these with a 1-based index, but we want a 0-based index.
          let index = (match[1] || 1) - 1;

          if (index >= 0 && index < aReplacements.length) {
            pairs.push([...aReplacements[index]]);
          }
        } else {
          pairs.push([part]);
        }
      }

      return pairs;
    }

    /**
     * _setUpEmphasisedSections() has the same use as _setUpDescription,
     * except instead of taking a string and highlighting given tokens, it takes
     * an array of pairs generated by _generateEmphasisPairs(). This allows
     * control over emphasising based on specific blocks of text, rather than
     * search for substrings.
     */
    _setUpEmphasisedSections(aDescriptionElement, aTextPairs) {
      // Get rid of all previous text
      while (aDescriptionElement.hasChildNodes()) {
        aDescriptionElement.firstChild.remove();
      }

      for (let [text, emphasise] of aTextPairs) {
        if (emphasise) {
          let span = aDescriptionElement.appendChild(
            document.createElementNS("http://www.w3.org/1999/xhtml", "span")
          );
          span.textContent = text;
          switch (emphasise) {
            case "match":
              this._setUpEmphasisSpan(span, aDescriptionElement);
              break;
          }
        } else {
          aDescriptionElement.appendChild(document.createTextNode(text));
        }
      }
    }

    _unescapeUrl(url) {
      return Services.textToSubURI.unEscapeURIForUI(url);
    }

    _reuseAcItem() {
      this.collapsed = false;

      // The popup may have changed size between now and the last
      // time the item was shown, so always handle over/underflow.
      let dwu = window.windowUtils;
      let popupWidth = dwu.getBoundsWithoutFlushing(this.parentNode).width;
      if (!this._previousPopupWidth || this._previousPopupWidth != popupWidth) {
        this._previousPopupWidth = popupWidth;
        this.handleOverUnderflow();
      }
    }

    _adjustAcItem() {
      let originalUrl = this.getAttribute("ac-value");
      let title = this.getAttribute("ac-comment");
      this.setAttribute("url", originalUrl);
      this.setAttribute("image", this.getAttribute("ac-image"));
      this.setAttribute("title", title);
      this.setAttribute("text", this.getAttribute("ac-text"));

      let type = this.getAttribute("originaltype");
      let types = new Set(type.split(/\s+/));
      // Remove types that should ultimately not be in the `type` string.
      types.delete("autofill");
      type = [...types][0] || "";
      this.setAttribute("type", type);

      let displayUrl = this._unescapeUrl(originalUrl);

      // Show the domain as the title if we don't have a title.
      if (!title) {
        try {
          let uri = Services.io.newURI(originalUrl);
          // Not all valid URLs have a domain.
          if (uri.host) {
            title = uri.host;
          }
        } catch (e) {}
        if (!title) {
          title = displayUrl;
        }
      }

      if (Array.isArray(title)) {
        this._setUpEmphasisedSections(this._titleText, title);
      } else {
        this._setUpDescription(this._titleText, title);
      }
      this._setUpDescription(this._urlText, displayUrl);

      // Removing the max-width may be jarring when the item is visible, but
      // we have no other choice to properly crop the text.
      // Removing max-widths may cause overflow or underflow events, that
      // will set the _inOverflow property. In case both the old and the new
      // text are overflowing, the overflow event won't happen, and we must
      // enforce an _handleOverflow() call to update the max-widths.
      let wasInOverflow = this._inOverflow;
      this._removeMaxWidths();
      if (wasInOverflow && this._inOverflow) {
        this._handleOverflow();
      }
    }

    _removeMaxWidths() {
      if (this._hasMaxWidths) {
        this._titleText.style.removeProperty("max-width");
        this._urlText.style.removeProperty("max-width");
        this._hasMaxWidths = false;
      }
    }

    /**
     * This method truncates the displayed strings as necessary.
     */
    _handleOverflow() {
      let itemRect = this.parentNode.getBoundingClientRect();
      let titleRect = this._titleText.getBoundingClientRect();
      let separatorRect = this._separator.getBoundingClientRect();
      let urlRect = this._urlText.getBoundingClientRect();
      let separatorURLWidth = separatorRect.width + urlRect.width;

      // Total width for the title and URL is the width of the item
      // minus the start of the title text minus a little optional extra padding.
      // This extra padding amount is basically arbitrary but keeps the text
      // from getting too close to the popup's edge.
      let dir = this.getAttribute("dir");
      let titleStart =
        dir == "rtl"
          ? itemRect.right - titleRect.right
          : titleRect.left - itemRect.left;

      let popup = this.parentNode.parentNode;
      let itemWidth =
        itemRect.width -
        titleStart -
        popup.overflowPadding -
        (popup.margins ? popup.margins.end : 0);

      let titleWidth = titleRect.width;
      if (titleWidth + separatorURLWidth > itemWidth) {
        // The percentage of the item width allocated to the title.
        let titlePct = 0.66;

        let titleAvailable = itemWidth - separatorURLWidth;
        let titleMaxWidth = Math.max(titleAvailable, itemWidth * titlePct);
        if (titleWidth > titleMaxWidth) {
          this._titleText.style.maxWidth = titleMaxWidth + "px";
        }
        let urlMaxWidth = Math.max(
          itemWidth - titleWidth,
          itemWidth * (1 - titlePct)
        );
        urlMaxWidth -= separatorRect.width;
        this._urlText.style.maxWidth = urlMaxWidth + "px";
        this._hasMaxWidths = true;
      }
    }

    handleOverUnderflow() {
      this._removeMaxWidths();
      this._handleOverflow();
    }
  };

  MozXULElement.implementCustomInterface(
    MozElements.MozAutocompleteRichlistitem,
    [Ci.nsIDOMXULSelectControlItemElement]
  );

  class MozAutocompleteRichlistitemInsecureWarning extends MozElements.MozAutocompleteRichlistitem {
    constructor() {
      super();

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

        let baseURL = Services.urlFormatter.formatURLPref(
          "app.support.baseURL"
        );
        window.openTrustedLinkIn(baseURL + "insecure-password", "tab", {
          relatedToCurrent: true,
        });
      });
    }

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

      super.connectedCallback();

      // Unlike other autocomplete items, the height of the insecure warning
      // increases by wrapping. So "forceHandleUnderflow" is for container to
      // recalculate an item's height and width.
      this.classList.add("forceHandleUnderflow");
    }

    static get inheritedAttributes() {
      return {
        ".ac-type-icon": "selected,current,type",
        ".ac-site-icon": "src=image,selected,type",
        ".ac-title-text": "selected",
        ".ac-separator": "selected,type",
        ".ac-url": "selected",
        ".ac-url-text": "selected",
      };
    }

    static get markup() {
      return `
      <image class="ac-type-icon"/>
      <image class="ac-site-icon"/>
      <vbox class="ac-title" align="left">
        <description class="ac-text-overflow-container">
          <description class="ac-title-text"/>
        </description>
      </vbox>
      <hbox class="ac-separator" align="center">
        <description class="ac-separator-text" value="—"/>
      </hbox>
      <hbox class="ac-url" align="center">
        <description class="ac-text-overflow-container">
          <description class="ac-url-text"/>
        </description>
      </hbox>
    `;
    }

    get _learnMoreString() {
      if (!this.__learnMoreString) {
        this.__learnMoreString = Services.strings
          .createBundle("chrome://passwordmgr/locale/passwordmgr.properties")
          .GetStringFromName("insecureFieldWarningLearnMore");
      }
      return this.__learnMoreString;
    }

    /**
     * Override _getSearchTokens to have the Learn More text emphasized
     */
    _getSearchTokens(aSearch) {
      return [this._learnMoreString.toLowerCase()];
    }
  }

  class MozAutocompleteRichlistitemLoginsFooter extends MozElements.MozAutocompleteRichlistitem {}

  class MozAutocompleteImportableLearnMoreRichlistitem extends MozElements.MozAutocompleteRichlistitem {
    constructor() {
      super();
      MozXULElement.insertFTLIfNeeded("toolkit/main-window/autocomplete.ftl");
    }

    static get markup() {
      return `
      <image class="ac-type-icon"/>
      <image class="ac-site-icon"/>
      <vbox class="ac-title" align="left">
        <description class="ac-text-overflow-container">
          <description class="ac-title-text"
                       data-l10n-id="autocomplete-import-learn-more"/>
        </description>
      </vbox>
      <hbox class="ac-separator" align="center">
        <description class="ac-separator-text" value="—"/>
      </hbox>
      <hbox class="ac-url" align="center">
        <description class="ac-text-overflow-container">
          <description class="ac-url-text"/>
        </description>
      </hbox>
    `;
    }

    // Override to avoid clearing out fluent description.
    _setUpDescription() {}
  }

  class MozAutocompleteTwoLineRichlistitem extends MozElements.MozRichlistitem {
    connectedCallback() {
      if (this.delayConnectedCallback()) {
        return;
      }

      this.textContent = "";
      this.appendChild(this.constructor.fragment);
      this.initializeAttributeInheritance();
      this.initializeSecondaryAction();
      this._adjustAcItem();
    }

    initializeSecondaryAction() {
      const button = this.querySelector(".ac-secondary-action");

      if (this.onSecondaryAction) {
        button.addEventListener("mousedown", event => {
          event.stopPropagation();
          this.onSecondaryAction();
        });
      } else {
        button?.remove();
      }
    }

    static get inheritedAttributes() {
      return {
        // getLabelAt:
        ".line1-label": "text=ac-value",
        // getCommentAt:
        ".line2-label": "text=ac-label",
        ".ac-site-icon": "src=ac-image",
      };
    }

    static get markup() {
      return `
      <div xmlns="http://www.w3.org/1999/xhtml"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           class="two-line-wrapper">
        <xul:image class="ac-site-icon"></xul:image>
        <div class="labels-wrapper">
          <div class="label-row line1-label"></div>
          <div class="label-row line2-label"></div>
        </div>
        <button class="ac-secondary-action"></button>
      </div>
    `;
    }

    _adjustAcItem() {}

    _onOverflow() {}

    _onUnderflow() {}

    handleOverUnderflow() {}
  }

  class MozAutocompleteLoginRichlistitem extends MozAutocompleteTwoLineRichlistitem {
    connectedCallback() {
      super.connectedCallback();
      this.firstChild.classList.add("ac-login-item");
    }

    onSecondaryAction() {
      const details = JSON.parse(this.getAttribute("ac-label"));
      LoginHelper.openPasswordManager(window, {
        loginGuid: details?.guid,
      });
    }

    static get inheritedAttributes() {
      return {
        // getLabelAt:
        ".line1-label": "text=ac-value",
        // Don't inherit ac-label with getCommentAt since the label is JSON.
        ".ac-site-icon": "src=ac-image",
      };
    }

    _adjustAcItem() {
      super._adjustAcItem();

      let details = JSON.parse(this.getAttribute("ac-label"));
      this.querySelector(".line2-label").textContent = details.comment;
    }
  }

  class MozAutocompleteGeneratedPasswordRichlistitem extends MozAutocompleteTwoLineRichlistitem {
    constructor() {
      super();

      // Line 2 and line 3 both display text with a different line-height than
      // line 1 but we want the line-height to be the same so we wrap the text
      // in <span> and only adjust the line-height via font CSS properties on them.
      this.generatedPasswordText = document.createElement("span");

      this.line3Text = document.createElement("span");
      this.line3 = document.createElement("div");
      this.line3.className = "label-row generated-password-autosave";
      this.line3.append(this.line3Text);
    }

    get _autoSaveString() {
      if (!this.__autoSaveString) {
        let brandShorterName = Services.strings
          .createBundle("chrome://branding/locale/brand.properties")
          .GetStringFromName("brandShorterName");
        this.__autoSaveString = Services.strings
          .createBundle("chrome://passwordmgr/locale/passwordmgr.properties")
          .formatStringFromName("generatedPasswordWillBeSaved", [
            brandShorterName,
          ]);
      }
      return this.__autoSaveString;
    }

    _adjustAcItem() {
      let { generatedPassword, willAutoSaveGeneratedPassword } = JSON.parse(
        this.getAttribute("ac-label")
      );
      let line2Label = this.querySelector(".line2-label");
      line2Label.textContent = "";
      this.generatedPasswordText.textContent = generatedPassword;
      line2Label.append(this.generatedPasswordText);

      if (willAutoSaveGeneratedPassword) {
        this.line3Text.textContent = this._autoSaveString;
        this.querySelector(".labels-wrapper").append(this.line3);
      } else {
        this.line3.remove();
      }

      super._adjustAcItem();
    }
  }

  class MozAutocompleteImportableLoginsRichlistitem extends MozAutocompleteTwoLineRichlistitem {
    constructor() {
      super();
      MozXULElement.insertFTLIfNeeded("toolkit/main-window/autocomplete.ftl");
    }

    static get inheritedAttributes() {
      return {
        // getLabelAt:
        ".line1-label": "text=ac-value",
        // Don't inherit ac-label with getCommentAt since the label is JSON.
      };
    }

    static get markup() {
      return `
      <div xmlns="http://www.w3.org/1999/xhtml"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           class="two-line-wrapper">
        <xul:image class="ac-site-icon" />
        <div class="labels-wrapper">
          <div class="label-row line1-label" data-l10n-name="line1" />
          <div class="label-row line2-label" data-l10n-name="line2" />
        </div>
      </div>
    `;
    }

    _adjustAcItem() {
      super._adjustAcItem();
      document.l10n.setAttributes(
        this.querySelector(".labels-wrapper"),
        `autocomplete-import-logins-${this.getAttribute("ac-value")}`,
        {
          host: JSON.parse(this.getAttribute("ac-label")).hostname.replace(
            /^www\./,
            ""
          ),
        }
      );
    }
  }

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

  customElements.define(
    "autocomplete-richlistitem-insecure-warning",
    MozAutocompleteRichlistitemInsecureWarning,
    {
      extends: "richlistitem",
    }
  );

  customElements.define(
    "autocomplete-richlistitem-logins-footer",
    MozAutocompleteRichlistitemLoginsFooter,
    {
      extends: "richlistitem",
    }
  );

  customElements.define(
    "autocomplete-two-line-richlistitem",
    MozAutocompleteTwoLineRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  customElements.define(
    "autocomplete-login-richlistitem",
    MozAutocompleteLoginRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  customElements.define(
    "autocomplete-generated-password-richlistitem",
    MozAutocompleteGeneratedPasswordRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  customElements.define(
    "autocomplete-importable-learn-more-richlistitem",
    MozAutocompleteImportableLearnMoreRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  customElements.define(
    "autocomplete-importable-logins-richlistitem",
    MozAutocompleteImportableLoginsRichlistitem,
    {
      extends: "richlistitem",
    }
  );
}