summaryrefslogtreecommitdiffstats
path: root/toolkit/components/satchel/InputListAutoComplete.sys.mjs
blob: 10820a2ebc7174d50961cfeb72f3979cba462fd9 (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
/* 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 { FormAutoCompleteResult } from "resource://gre/modules/nsFormAutoCompleteResult.sys.mjs";

export function InputListAutoComplete() {}

InputListAutoComplete.prototype = {
  classID: Components.ID("{bf1e01d0-953e-11df-981c-0800200c9a66}"),
  QueryInterface: ChromeUtils.generateQI(["nsIInputListAutoComplete"]),

  autoCompleteSearch(aUntrimmedSearchString, aField) {
    let items = this.getListSuggestions(aField);
    let searchResult = items.length
      ? Ci.nsIAutoCompleteResult.RESULT_SUCCESS
      : Ci.nsIAutoCompleteResult.RESULT_NOMATCH;
    let defaultIndex = items.length ? 0 : -1;

    return new FormAutoCompleteResult(
      aUntrimmedSearchString,
      searchResult,
      defaultIndex,
      "",
      items,
      null
    );
  },

  getListSuggestions(aField) {
    let items = [];
    if (!aField || !aField.list) {
      return items;
    }

    let filter = !aField.hasAttribute("mozNoFilter");
    let lowerFieldValue = aField.value.toLowerCase();
    let options = aField.list.options;

    for (let item of options) {
      let label = "";
      if (item.label) {
        label = item.label;
      } else if (item.text) {
        label = item.text;
      } else {
        label = item.value;
      }

      if (filter && !label.toLowerCase().includes(lowerFieldValue)) {
        continue;
      }

      items.push({
        label,
        value: item.value,
        comment: "",
        removable: false,
      });
    }

    return items;
  },
};