summaryrefslogtreecommitdiffstats
path: root/browser/components/aboutlogins/content/components/login-filter.mjs
blob: e5b89327d6a3cee5b3dd6d09810dcb8e935eadd3 (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
/* 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 { recordTelemetryEvent } from "../aboutLoginsUtils.mjs";

export default class LoginFilter extends HTMLElement {
  get #loginList() {
    return document.querySelector("login-list");
  }

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

    let loginFilterTemplate = document.querySelector("#login-filter-template");
    let shadowRoot = this.attachShadow({ mode: "open" });
    document.l10n.connectRoot(shadowRoot);
    shadowRoot.appendChild(loginFilterTemplate.content.cloneNode(true));

    this._input = this.shadowRoot.querySelector("input");

    this.addEventListener("input", this);
    this._input.addEventListener("keydown", this);
    window.addEventListener("AboutLoginsFilterLogins", this);
  }

  focus() {
    this._input.focus();
  }

  handleEvent(event) {
    switch (event.type) {
      case "AboutLoginsFilterLogins":
        this.#filterLogins(event.detail);
        break;
      case "input":
        this.#input(event.originalTarget.value);
        break;
      case "keydown":
        this.#keyDown(event);
        break;
    }
  }

  #filterLogins(filterText) {
    if (this.value != filterText) {
      this.value = filterText;
    }
  }

  #input(value) {
    this._dispatchFilterEvent(value);
  }

  #keyDown(e) {
    switch (e.code) {
      case "ArrowUp":
        e.preventDefault();
        this.#loginList.selectPrevious();
        break;
      case "ArrowDown":
        e.preventDefault();
        this.#loginList.selectNext();
        break;
      case "Escape":
        e.preventDefault();
        this.value = "";
        break;
      case "Enter":
        e.preventDefault();
        this.#loginList.clickSelected();
        break;
    }
  }

  get value() {
    return this._input.value;
  }

  set value(val) {
    this._input.value = val;
    this._dispatchFilterEvent(val);
  }

  _dispatchFilterEvent(value) {
    this.dispatchEvent(
      new CustomEvent("AboutLoginsFilterLogins", {
        bubbles: true,
        composed: true,
        detail: value,
      })
    );

    recordTelemetryEvent({ object: "list", method: "filter" });
  }
}
customElements.define("login-filter", LoginFilter);