summaryrefslogtreecommitdiffstats
path: root/toolkit/content/widgets/autocomplete-input.js
blob: 34da0cc1f414d45451dfff0178892684afd20fda (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
/* 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 { AppConstants } = ChromeUtils.importESModule(
    "resource://gre/modules/AppConstants.sys.mjs"
  );
  const { XPCOMUtils } = ChromeUtils.importESModule(
    "resource://gre/modules/XPCOMUtils.sys.mjs"
  );

  class AutocompleteInput extends HTMLInputElement {
    constructor() {
      super();

      this.popupSelectedIndex = -1;

      ChromeUtils.defineESModuleGetters(this, {
        PrivateBrowsingUtils:
          "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
      });

      XPCOMUtils.defineLazyPreferenceGetter(
        this,
        "disablePopupAutohide",
        "ui.popup.disable_autohide",
        false
      );

      this.addEventListener("input", event => {
        this.onInput(event);
      });

      this.addEventListener("keydown", event => this.handleKeyDown(event));

      this.addEventListener(
        "compositionstart",
        event => {
          if (
            this.mController.input.wrappedJSObject == this.nsIAutocompleteInput
          ) {
            this.mController.handleStartComposition();
          }
        },
        true
      );

      this.addEventListener(
        "compositionend",
        event => {
          if (
            this.mController.input.wrappedJSObject == this.nsIAutocompleteInput
          ) {
            this.mController.handleEndComposition();
          }
        },
        true
      );

      this.addEventListener(
        "focus",
        event => {
          this.attachController();
          if (
            window.gBrowser &&
            window.gBrowser.selectedBrowser.hasAttribute("usercontextid")
          ) {
            this.userContextId = parseInt(
              window.gBrowser.selectedBrowser.getAttribute("usercontextid")
            );
          } else {
            this.userContextId = 0;
          }
        },
        true
      );

      this.addEventListener(
        "blur",
        event => {
          if (!this._dontBlur) {
            if (this.forceComplete && this.mController.matchCount >= 1) {
              // If forceComplete is requested, we need to call the enter processing
              // on blur so the input will be forced to the closest match.
              // Thunderbird is the only consumer of forceComplete and this is used
              // to force an recipient's email to the exact address book entry.
              this.mController.handleEnter(true);
            }
            if (!this.ignoreBlurWhileSearching) {
              this._dontClosePopup = this.disablePopupAutohide;
              this.detachController();
            }
          }
        },
        true
      );
    }

    connectedCallback() {
      this.setAttribute("is", "autocomplete-input");
      this.setAttribute("autocomplete", "off");

      this.mController = Cc[
        "@mozilla.org/autocomplete/controller;1"
      ].getService(Ci.nsIAutoCompleteController);
      this.mSearchNames = null;
      this.mIgnoreInput = false;
      this.noRollupOnEmptySearch = false;

      this._popup = null;

      this.nsIAutocompleteInput = this.getCustomInterfaceCallback(
        Ci.nsIAutoCompleteInput
      );

      this.valueIsTyped = false;
    }

    get popup() {
      // Memoize the result in a field rather than replacing this property,
      // so that it can be reset along with the binding.
      if (this._popup) {
        return this._popup;
      }

      let popup = null;
      let popupId = this.getAttribute("autocompletepopup");
      if (popupId) {
        popup = document.getElementById(popupId);
      }

      /* This path is only used in tests, we have the <popupset> and <panel>
         in document for other usages */
      if (!popup) {
        popup = document.createXULElement("panel", {
          is: "autocomplete-richlistbox-popup",
        });
        popup.setAttribute("type", "autocomplete-richlistbox");
        popup.setAttribute("noautofocus", "true");

        if (!this._popupset) {
          this._popupset = document.createXULElement("popupset");
          document.documentElement.appendChild(this._popupset);
        }

        this._popupset.appendChild(popup);
      }
      popup.mInput = this;

      return (this._popup = popup);
    }

    get popupElement() {
      return this.popup;
    }

    get controller() {
      return this.mController;
    }

    set popupOpen(val) {
      if (val) {
        this.openPopup();
      } else {
        this.closePopup();
      }
    }

    get popupOpen() {
      return this.popup.popupOpen;
    }

    set disableAutoComplete(val) {
      this.setAttribute("disableautocomplete", val);
    }

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

    set completeDefaultIndex(val) {
      this.setAttribute("completedefaultindex", val);
    }

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

    set completeSelectedIndex(val) {
      this.setAttribute("completeselectedindex", val);
    }

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

    set forceComplete(val) {
      this.setAttribute("forcecomplete", val);
    }

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

    set minResultsForPopup(val) {
      this.setAttribute("minresultsforpopup", val);
    }

    get minResultsForPopup() {
      var m = parseInt(this.getAttribute("minresultsforpopup"));
      return isNaN(m) ? 1 : m;
    }

    set timeout(val) {
      this.setAttribute("timeout", val);
    }

    get timeout() {
      var t = parseInt(this.getAttribute("timeout"));
      return isNaN(t) ? 50 : t;
    }

    set searchParam(val) {
      this.setAttribute("autocompletesearchparam", val);
    }

    get searchParam() {
      return this.getAttribute("autocompletesearchparam") || "";
    }

    get searchCount() {
      this.initSearchNames();
      return this.mSearchNames.length;
    }

    get inPrivateContext() {
      return this.PrivateBrowsingUtils.isWindowPrivate(window);
    }

    get noRollupOnCaretMove() {
      return this.popup.getAttribute("norolluponanchor") == "true";
    }

    set textValue(val) {
      // "input" event is automatically dispatched by the editor if
      // necessary.
      this._setValueInternal(val, true);
    }

    get textValue() {
      return this.value;
    }
    /**
     * =================== nsIDOMXULMenuListElement ===================
     */
    get editable() {
      return true;
    }

    set crop(val) {}

    get crop() {
      return false;
    }

    set open(val) {
      if (val) {
        this.showHistoryPopup();
      } else {
        this.closePopup();
      }
    }

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

    set value(val) {
      this._setValueInternal(val, false);
    }

    get value() {
      return super.value;
    }

    get focused() {
      return this === document.activeElement;
    }
    /**
     * maximum number of rows to display at a time when opening the popup normally
     * (e.g., focus element and press the down arrow)
     */
    set maxRows(val) {
      this.setAttribute("maxrows", val);
    }

    get maxRows() {
      return parseInt(this.getAttribute("maxrows")) || 0;
    }
    /**
     * maximum number of rows to display at a time when opening the popup by
     * clicking the dropmarker (for inputs that have one)
     */
    set maxdropmarkerrows(val) {
      this.setAttribute("maxdropmarkerrows", val);
    }

    get maxdropmarkerrows() {
      return parseInt(this.getAttribute("maxdropmarkerrows"), 10) || 14;
    }
    /**
     * option to allow scrolling through the list via the tab key, rather than
     * tab moving focus out of the textbox
     */
    set tabScrolling(val) {
      this.setAttribute("tabscrolling", val);
    }

    get tabScrolling() {
      return this.getAttribute("tabscrolling") == "true";
    }
    /**
     * option to completely ignore any blur events while searches are
     * still going on.
     */
    set ignoreBlurWhileSearching(val) {
      this.setAttribute("ignoreblurwhilesearching", val);
    }

    get ignoreBlurWhileSearching() {
      return this.getAttribute("ignoreblurwhilesearching") == "true";
    }
    /**
     * option to highlight entries that don't have any matches
     */
    set highlightNonMatches(val) {
      this.setAttribute("highlightnonmatches", val);
    }

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

    getSearchAt(aIndex) {
      this.initSearchNames();
      return this.mSearchNames[aIndex];
    }

    selectTextRange(aStartIndex, aEndIndex) {
      super.setSelectionRange(aStartIndex, aEndIndex);
    }

    onSearchBegin() {
      if (this.popup && typeof this.popup.onSearchBegin == "function") {
        this.popup.onSearchBegin();
      }
    }

    onSearchComplete() {
      if (this.mController.matchCount == 0) {
        this.setAttribute("nomatch", "true");
      } else {
        this.removeAttribute("nomatch");
      }

      if (this.ignoreBlurWhileSearching && !this.focused) {
        this.handleEnter();
        this.detachController();
      }
    }

    onTextEntered(event) {
      if (this.getAttribute("notifylegacyevents") === "true") {
        let e = new CustomEvent("textEntered", {
          bubbles: false,
          cancelable: true,
          detail: { rootEvent: event },
        });
        return !this.dispatchEvent(e);
      }
      return false;
    }

    onTextReverted(event) {
      if (this.getAttribute("notifylegacyevents") === "true") {
        let e = new CustomEvent("textReverted", {
          bubbles: false,
          cancelable: true,
          detail: { rootEvent: event },
        });
        return !this.dispatchEvent(e);
      }
      return false;
    }

    /**
     * =================== PRIVATE MEMBERS ===================
     */

    /*
     * ::::::::::::: autocomplete controller :::::::::::::
     */

    attachController() {
      this.mController.input = this.nsIAutocompleteInput;
    }

    detachController() {
      if (
        this.mController.input &&
        this.mController.input.wrappedJSObject == this.nsIAutocompleteInput
      ) {
        this.mController.input = null;
      }
    }

    /**
     * ::::::::::::: popup opening :::::::::::::
     */
    openPopup() {
      if (this.focused) {
        this.popup.openAutocompletePopup(this.nsIAutocompleteInput, this);
      }
    }

    closePopup() {
      if (this._dontClosePopup) {
        delete this._dontClosePopup;
        return;
      }
      this.popup.closePopup();
    }

    showHistoryPopup() {
      // Store our "normal" maxRows on the popup, so that it can reset the
      // value when the popup is hidden.
      this.popup._normalMaxRows = this.maxRows;

      // Temporarily change our maxRows, since we want the dropdown to be a
      // different size in this case. The popup's popupshowing/popuphiding
      // handlers will take care of resetting this.
      this.maxRows = this.maxdropmarkerrows;

      // Ensure that we have focus.
      if (!this.focused) {
        this.focus();
      }
      this.attachController();
      this.mController.startSearch("");
    }

    toggleHistoryPopup() {
      if (!this.popup.popupOpen) {
        this.showHistoryPopup();
      } else {
        this.closePopup();
      }
    }

    handleKeyDown(aEvent) {
      // Re: urlbarDeferred, see the comment in urlbarBindings.xml.
      if (aEvent.defaultPrevented && !aEvent.urlbarDeferred) {
        return false;
      }

      if (
        typeof this.onBeforeHandleKeyDown == "function" &&
        this.onBeforeHandleKeyDown(aEvent)
      ) {
        return true;
      }

      const isMac = AppConstants.platform == "macosx";
      var cancel = false;

      // Catch any keys that could potentially move the caret. Ctrl can be
      // used in combination with these keys on Windows and Linux; and Alt
      // can be used on OS X, so make sure the unused one isn't used.
      let metaKey = isMac ? aEvent.ctrlKey : aEvent.altKey;
      if (!metaKey) {
        switch (aEvent.keyCode) {
          case KeyEvent.DOM_VK_LEFT:
          case KeyEvent.DOM_VK_RIGHT:
          case KeyEvent.DOM_VK_HOME:
            cancel = this.mController.handleKeyNavigation(aEvent.keyCode);
            break;
        }
      }

      // Handle keys that are not part of a keyboard shortcut (no Ctrl or Alt)
      if (!aEvent.ctrlKey && !aEvent.altKey) {
        switch (aEvent.keyCode) {
          case KeyEvent.DOM_VK_TAB:
            if (this.tabScrolling && this.popup.popupOpen) {
              cancel = this.mController.handleKeyNavigation(
                aEvent.shiftKey ? KeyEvent.DOM_VK_UP : KeyEvent.DOM_VK_DOWN
              );
            } else if (this.forceComplete && this.mController.matchCount >= 1) {
              this.mController.handleTab();
            }
            break;
          case KeyEvent.DOM_VK_UP:
          case KeyEvent.DOM_VK_DOWN:
          case KeyEvent.DOM_VK_PAGE_UP:
          case KeyEvent.DOM_VK_PAGE_DOWN:
            cancel = this.mController.handleKeyNavigation(aEvent.keyCode);
            break;
        }
      }

      // Handle readline/emacs-style navigation bindings on Mac.
      if (
        isMac &&
        this.popup.popupOpen &&
        aEvent.ctrlKey &&
        (aEvent.key === "n" || aEvent.key === "p")
      ) {
        const effectiveKey =
          aEvent.key === "p" ? KeyEvent.DOM_VK_UP : KeyEvent.DOM_VK_DOWN;
        cancel = this.mController.handleKeyNavigation(effectiveKey);
      }

      // Handle keys we know aren't part of a shortcut, even with Alt or
      // Ctrl.
      switch (aEvent.keyCode) {
        case KeyEvent.DOM_VK_ESCAPE:
          cancel = this.mController.handleEscape();
          break;
        case KeyEvent.DOM_VK_RETURN:
          if (isMac) {
            // Prevent the default action, since it will beep on Mac
            if (aEvent.metaKey) {
              aEvent.preventDefault();
            }
          }
          if (this.popup.selectedIndex >= 0) {
            this.popupSelectedIndex = this.popup.selectedIndex;
          }
          cancel = this.handleEnter(aEvent);
          break;
        case KeyEvent.DOM_VK_DELETE:
          if (isMac && !aEvent.shiftKey) {
            break;
          }
          cancel = this.handleDelete();
          break;
        case KeyEvent.DOM_VK_BACK_SPACE:
          if (isMac && aEvent.shiftKey) {
            cancel = this.handleDelete();
          }
          break;
        case KeyEvent.DOM_VK_DOWN:
        case KeyEvent.DOM_VK_UP:
          if (aEvent.altKey) {
            this.toggleHistoryPopup();
          }
          break;
        case KeyEvent.DOM_VK_F4:
          if (!isMac) {
            this.toggleHistoryPopup();
          }
          break;
      }

      if (cancel) {
        aEvent.stopPropagation();
        aEvent.preventDefault();
      }

      return true;
    }

    handleEnter(event) {
      return this.mController.handleEnter(false, event || null);
    }

    handleDelete() {
      return this.mController.handleDelete();
    }

    /**
     * ::::::::::::: miscellaneous :::::::::::::
     */
    initSearchNames() {
      if (!this.mSearchNames) {
        var names = this.getAttribute("autocompletesearch");
        if (!names) {
          this.mSearchNames = [];
        } else {
          this.mSearchNames = names.split(" ");
        }
      }
    }

    _focus() {
      this._dontBlur = true;
      this.focus();
      this._dontBlur = false;
    }

    resetActionType() {
      if (this.mIgnoreInput) {
        return;
      }
      this.removeAttribute("actiontype");
    }

    _setValueInternal(value, isUserInput) {
      this.mIgnoreInput = true;

      if (typeof this.onBeforeValueSet == "function") {
        value = this.onBeforeValueSet(value);
      }

      this.valueIsTyped = false;
      if (isUserInput) {
        super.setUserInput(value);
      } else {
        super.value = value;
      }

      this.mIgnoreInput = false;
      var event = document.createEvent("Events");
      event.initEvent("ValueChange", true, true);
      super.dispatchEvent(event);
      return value;
    }

    onInput(aEvent) {
      if (
        !this.mIgnoreInput &&
        this.mController.input.wrappedJSObject == this.nsIAutocompleteInput
      ) {
        this.valueIsTyped = true;
        this.mController.handleText();
      }
      this.resetActionType();
    }
  }

  MozHTMLElement.implementCustomInterface(AutocompleteInput, [
    Ci.nsIAutoCompleteInput,
    Ci.nsIDOMXULMenuListElement,
  ]);
  customElements.define("autocomplete-input", AutocompleteInput, {
    extends: "input",
  });
}