summaryrefslogtreecommitdiffstats
path: root/comm/mail/base/content/widgets/gloda-autocomplete-input.js
blob: 59f71ba6aed08107fdd40ebca1b1375166d4ac43 (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
/**
 * 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/. */

/* global MozXULElement */

"use strict";

// The autocomplete CE is defined lazily. Create one now to get
// autocomplete-input defined, allowing us to inherit from it.
if (!customElements.get("autocomplete-input")) {
  delete document.createXULElement("input", { is: "autocomplete-input" });
}

customElements.whenDefined("autocomplete-input").then(() => {
  const { AppConstants } = ChromeUtils.importESModule(
    "resource://gre/modules/AppConstants.sys.mjs"
  );
  const { XPCOMUtils } = ChromeUtils.importESModule(
    "resource://gre/modules/XPCOMUtils.sys.mjs"
  );

  const lazy = {};
  ChromeUtils.defineESModuleGetters(lazy, {
    GlodaIMSearcher: "resource:///modules/GlodaIMSearcher.sys.mjs",
  });
  ChromeUtils.defineModuleGetter(
    lazy,
    "Gloda",
    "resource:///modules/gloda/GlodaPublic.jsm"
  );
  ChromeUtils.defineModuleGetter(
    lazy,
    "GlodaMsgSearcher",
    "resource:///modules/gloda/GlodaMsgSearcher.jsm"
  );
  ChromeUtils.defineModuleGetter(
    lazy,
    "GlodaConstants",
    "resource:///modules/gloda/GlodaConstants.jsm"
  );

  XPCOMUtils.defineLazyGetter(
    lazy,
    "glodaCompleter",
    () =>
      Cc["@mozilla.org/autocomplete/search;1?name=gloda"].getService(
        Ci.nsIAutoCompleteSearch
      ).wrappedJSObject
  );

  /**
   * The MozGlodaAutocompleteInput widget is used to display the autocomplete search bar.
   *
   * @augments {AutocompleteInput}
   */
  class MozGlodaAutocompleteInput extends customElements.get(
    "autocomplete-input"
  ) {
    constructor() {
      super();

      this.addEventListener(
        "drop",
        event => {
          this.searchInputDNDObserver.onDrop(event);
        },
        true
      );

      this.addEventListener("keypress", event => {
        if (event.keyCode == KeyEvent.DOM_VK_RETURN) {
          // Trigger the click event if a popup result is currently selected.
          if (this.popup.richlistbox.selectedIndex != -1) {
            this.popup.onPopupClick(event);
          } else {
            this.doSearch();
          }
          event.preventDefault();
          event.stopPropagation();
        }

        if (event.keyCode == KeyEvent.DOM_VK_ESCAPE) {
          this.clearSearch();
          event.preventDefault();
          event.stopPropagation();
        }
      });
    }

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

      this.hasConnected = true;
      super.connectedCallback();

      this.setAttribute("is", "gloda-autocomplete-input");

      // @implements {nsIObserver}
      this.searchInputDNDObserver = {
        onDrop: event => {
          if (event.dataTransfer.types.includes("text/x-moz-address")) {
            this.focus();
            this.value = event.dataTransfer.getData("text/plain");
            // XXX for some reason the input field is _cleared_ even though
            // the search works.
            this.doSearch();
          }
          event.stopPropagation();
        },
      };

      // @implements {nsIObserver}
      this.textObserver = {
        observe: (subject, topic, data) => {
          try {
            // Some autocomplete controllers throw NS_ERROR_NOT_IMPLEMENTED.
            subject.popupElement;
          } catch (ex) {
            return;
          }
          if (
            topic == "autocomplete-did-enter-text" &&
            document.activeElement == this
          ) {
            let selectedIndex = this.popup.selectedIndex;
            let curResult = lazy.glodaCompleter.curResult;
            if (!curResult) {
              // autocomplete didn't even finish.
              return;
            }
            let row = curResult.getObjectAt(selectedIndex);
            if (row == null) {
              return;
            }
            if (row.fullText) {
              // The autocomplete-did-enter-text notification is synchronously
              // generated by nsAutoCompleteController which will attempt to
              // call ClosePopup after we return and then tell the searchbox
              // about the text entered. Since doSearch may close the current
              // tab (and thus destroy the XUL document that owns the popup and
              // the input field), the search box may no longer have its
              // binding attached when we return and telling it about the
              // entered text could fail.
              // To avoid this, we defer the doSearch call to the next turn of
              // the event loop by using setTimeout.
              setTimeout(this.doSearch.bind(this), 0);
            } else if (row.nounDef) {
              let theQuery = lazy.Gloda.newQuery(
                lazy.GlodaConstants.NOUN_MESSAGE
              );
              if (row.nounDef.name == "tag") {
                theQuery = theQuery.tags(row.item);
              } else if (row.nounDef.name == "identity") {
                theQuery = theQuery.involves(row.item);
              }
              theQuery.orderBy("-date");
              document.getElementById("tabmail").openTab("glodaFacet", {
                query: theQuery,
              });
            }
          }
        },
      };

      let keyLabel =
        AppConstants.platform == "macosx" ? "keyLabelMac" : "keyLabelNonMac";
      let placeholder = this.getAttribute("emptytextbase").replace(
        "#1",
        this.getAttribute(keyLabel)
      );

      this.setAttribute("placeholder", placeholder);

      Services.obs.addObserver(
        this.textObserver,
        "autocomplete-did-enter-text"
      );

      // make sure we set our emptytext here from the get-go
      if (this.hasAttribute("placeholder")) {
        this.placeholder = this.getAttribute("placeholder");
      }
    }

    set state(val) {
      this.value = val.string;
    }

    get state() {
      return { string: this.value };
    }

    doSearch() {
      if (this.value) {
        let tabmail = document.getElementById("tabmail");
        // If the current tab is a gloda search tab, reset the value
        // to the initial search value. Otherwise, clear it. This
        // is the value that is going to be saved with the current
        // tab when we switch back to it next.
        let searchString = this.value;

        if (tabmail.currentTabInfo.mode.name == "glodaFacet") {
          // We'd rather reuse the existing tab (and somehow do something
          // smart with any preexisting facet choices, but that's a
          // bit hard right now, so doing the cheap thing and closing
          // this tab and starting over.
          tabmail.closeTab();
        }
        this.value = ""; // clear our value, to avoid persistence
        let args = {
          searcher: new lazy.GlodaMsgSearcher(null, searchString),
        };
        if (Services.prefs.getBoolPref("mail.chat.enabled")) {
          args.IMSearcher = new lazy.GlodaIMSearcher(null, searchString);
        }
        tabmail.openTab("glodaFacet", args);
      }
    }

    clearSearch() {
      this.value = "";
    }

    disconnectedCallback() {
      Services.obs.removeObserver(
        this.textObserver,
        "autocomplete-did-enter-text"
      );
      this.hasConnected = false;
    }
  }

  MozXULElement.implementCustomInterface(MozGlodaAutocompleteInput, [
    Ci.nsIObserver,
  ]);
  customElements.define("gloda-autocomplete-input", MozGlodaAutocompleteInput, {
    extends: "input",
  });
});