summaryrefslogtreecommitdiffstats
path: root/comm/mail/base/content/quickFilterBar.js
blob: e254b914161002b20f93d867fcf51077c8dcbe41 (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
/* 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-globals-from about3Pane.js */

var { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);
XPCOMUtils.defineLazyModuleGetters(this, {
  MessageTextFilter: "resource:///modules/QuickFilterManager.jsm",
  SearchSpec: "resource:///modules/SearchSpec.jsm",
  QuickFilterManager: "resource:///modules/QuickFilterManager.jsm",
  QuickFilterSearchListener: "resource:///modules/QuickFilterManager.jsm",
  QuickFilterState: "resource:///modules/QuickFilterManager.jsm",
});

class ToggleButton extends HTMLButtonElement {
  constructor() {
    super();
    this.addEventListener("click", () => {
      this.pressed = !this.pressed;
    });
  }

  connectedCallback() {
    this.setAttribute("is", "toggle-button");
    if (!this.hasAttribute("aria-pressed")) {
      this.pressed = false;
    }
  }

  get pressed() {
    return this.getAttribute("aria-pressed") === "true";
  }

  set pressed(value) {
    this.setAttribute("aria-pressed", value ? "true" : "false");
  }
}
customElements.define("toggle-button", ToggleButton, { extends: "button" });

var quickFilterBar = {
  _filterer: null,
  activeTopLevelFilters: new Set(),
  topLevelFilters: ["unread", "starred", "addrBook", "attachment"],

  /**
   * The UI element that last triggered a search. This can be used to avoid
   * updating the element when a search returns - in particular the text box,
   * which the user may still be typing into.
   *
   * @type {Element}
   */
  activeElement: null,

  init() {
    this._bindUI();
    this.updateRovingTab();

    // Enable any filters set by the user.
    // If keep filters applied/sticky setting is enabled, enable sticky.
    let xulStickyVal = Services.xulStore.getValue(
      XULSTORE_URL,
      "quickFilterBarSticky",
      "enabled"
    );
    if (xulStickyVal) {
      this.filterer.setFilterValue("sticky", xulStickyVal == "true");

      // If sticky is set, show saved filters.
      // Otherwise do not display saved filters on load.
      if (xulStickyVal == "true") {
        // If any filter settings are enabled, retrieve the enabled filters.
        let enabledTopFiltersVal = Services.xulStore.getValue(
          XULSTORE_URL,
          "quickFilter",
          "enabledTopFilters"
        );

        // Set any enabled filters to enabled in the UI.
        if (enabledTopFiltersVal) {
          let enabledTopFilters = JSON.parse(enabledTopFiltersVal);
          for (let filterName of enabledTopFilters) {
            this.activeTopLevelFilters.add(filterName);
            this.filterer.setFilterValue(filterName, true);
          }
        }
      }
    }

    // Hide the toolbar, unless it has been previously shown.
    if (
      Services.xulStore.getValue(
        XULSTORE_URL,
        "quickFilterBar",
        "collapsed"
      ) === "false"
    ) {
      this._showFilterBar(true, true);
    } else {
      this._showFilterBar(false, true);
    }

    commandController.registerCallback("cmd_showQuickFilterBar", () => {
      if (!this.filterer.visible) {
        this._showFilterBar(true);
      }
      document.getElementById(QuickFilterManager.textBoxDomId).select();
    });
    commandController.registerCallback("cmd_toggleQuickFilterBar", () => {
      let show = !this.filterer.visible;
      this._showFilterBar(show);
      if (show) {
        document.getElementById(QuickFilterManager.textBoxDomId).select();
      }
    });
    window.addEventListener("keypress", event => {
      if (event.keyCode != KeyEvent.DOM_VK_ESCAPE || !this.filterer.visible) {
        // The filter bar isn't visible, do nothing.
        return;
      }
      if (this.filterer.userHitEscape()) {
        // User hit the escape key; do our undo-ish thing.
        this.updateSearch();
        this.reflectFiltererState();
      } else {
        // Close the filter since there was nothing left to relax.
        this._showFilterBar(false);
      }
    });

    document.getElementById("qfd-dropdown").addEventListener("click", event => {
      document
        .getElementById("quickFilterButtonsContext")
        .openPopup(event.target, { triggerEvent: event });
    });

    for (let buttonGroup of this.rovingGroups) {
      buttonGroup.addEventListener("keypress", event => {
        this.triggerQFTRovingTab(event);
      });
    }

    document.getElementById("qfb-sticky").addEventListener("click", event => {
      let stickyValue = event.target.pressed ? "true" : "false";
      Services.xulStore.setValue(
        XULSTORE_URL,
        "quickFilterBarSticky",
        "enabled",
        stickyValue
      );
    });
  },

  /**
   * Get all button groups with the roving-group class.
   *
   * @returns {Array} An array of buttons.
   */
  get rovingGroups() {
    return document.querySelectorAll("#quick-filter-bar .roving-group");
  },

  /**
   * Update the `tabindex` attribute of the buttons.
   */
  updateRovingTab() {
    for (let buttonGroup of this.rovingGroups) {
      for (let button of buttonGroup.querySelectorAll("button")) {
        button.tabIndex = -1;
      }
      // Allow focus on the first available button.
      buttonGroup.querySelector("button").tabIndex = 0;
    }
  },

  /**
   * Handles the keypress event on the button group.
   *
   * @param {Event} event - The keypress DOMEvent.
   */
  triggerQFTRovingTab(event) {
    if (!["ArrowRight", "ArrowLeft"].includes(event.key)) {
      return;
    }

    let buttonGroup = [
      ...event.target
        .closest(".roving-group")
        .querySelectorAll(`[is="toggle-button"]`),
    ];
    let focusableButton = buttonGroup.find(b => b.tabIndex != -1);
    let elementIndex = buttonGroup.indexOf(focusableButton);

    // Find the adjacent focusable element based on the pressed key.
    let isRTL = document.dir == "rtl";
    if (
      (isRTL && event.key == "ArrowLeft") ||
      (!isRTL && event.key == "ArrowRight")
    ) {
      elementIndex++;
      if (elementIndex > buttonGroup.length - 1) {
        elementIndex = 0;
      }
    } else if (
      (!isRTL && event.key == "ArrowLeft") ||
      (isRTL && event.key == "ArrowRight")
    ) {
      elementIndex--;
      if (elementIndex == -1) {
        elementIndex = buttonGroup.length - 1;
      }
    }

    // Move the focus to a button and update the tabindex attribute.
    let newFocusableButton = buttonGroup[elementIndex];
    if (newFocusableButton) {
      focusableButton.tabIndex = -1;
      newFocusableButton.tabIndex = 0;
      newFocusableButton.focus();
    }
  },

  get filterer() {
    if (!this._filterer) {
      this._filterer = new QuickFilterState();
      this._filterer.visible = false;
    }
    return this._filterer;
  },

  set filterer(value) {
    this._filterer = value;
  },

  // ---------------------
  // UI State Manipulation

  /**
   * Add appropriate event handlers to the DOM elements.  We do this rather
   *  than requiring lots of boilerplate "oncommand" junk on the nodes.
   *
   * We hook up the following:
   * - "command" event listener.
   * - reflect filter state
   */
  _bindUI() {
    for (let filterDef of QuickFilterManager.filterDefs) {
      let domNode = document.getElementById(filterDef.domId);
      let menuItemNode = document.getElementById(filterDef.menuItemID);

      let handlerDomId, handlerMenuItems;

      if (!("onCommand" in filterDef)) {
        handlerDomId = event => {
          try {
            let postValue = domNode.pressed ? true : null;
            this.filterer.setFilterValue(filterDef.name, postValue);
            this.updateFiltersSettings(filterDef.name, postValue);
            this.deferredUpdateSearch(domNode);
          } catch (ex) {
            console.error(ex);
          }
        };
        handlerMenuItems = event => {
          try {
            let postValue = menuItemNode.hasAttribute("checked") ? true : null;
            this.filterer.setFilterValue(filterDef.name, postValue);
            this.updateFiltersSettings(filterDef.name, postValue);
            this.deferredUpdateSearch();
          } catch (ex) {
            console.error(ex);
          }
        };
      } else {
        handlerDomId = event => {
          if (filterDef.name == "tags") {
            filterDef.callID = "button";
          }
          let filterValues = this.filterer.filterValues;
          let preValue =
            filterDef.name in filterValues
              ? filterValues[filterDef.name]
              : null;
          let [postValue, update] = filterDef.onCommand(
            preValue,
            domNode,
            event,
            document
          );
          this.filterer.setFilterValue(filterDef.name, postValue, !update);
          this.updateFiltersSettings(filterDef.name, postValue);
          if (update) {
            this.deferredUpdateSearch(domNode);
          }
        };
        handlerMenuItems = event => {
          if (filterDef.name == "tags") {
            filterDef.callID = "menuItem";
          }
          let filterValues = this.filterer.filterValues;
          let preValue =
            filterDef.name in filterValues
              ? filterValues[filterDef.name]
              : null;
          let [postValue, update] = filterDef.onCommand(
            preValue,
            menuItemNode,
            event,
            document
          );
          this.filterer.setFilterValue(filterDef.name, postValue, !update);
          this.updateFiltersSettings(filterDef.name, postValue);
          if (update) {
            this.deferredUpdateSearch();
          }
        };
      }

      if (domNode.namespaceURI == document.documentElement.namespaceURI) {
        domNode.addEventListener("click", handlerDomId);
      } else {
        domNode.addEventListener("command", handlerDomId);
      }
      if (menuItemNode !== null) {
        menuItemNode.addEventListener("command", handlerMenuItems);
      }

      if ("domBindExtra" in filterDef) {
        filterDef.domBindExtra(document, this, domNode);
      }
    }
  },

  /**
   * Update enabled filters in XULStore.
   */
  updateFiltersSettings(filterName, filterValue) {
    if (this.topLevelFilters.includes(filterName)) {
      this.updateTopLevelFilters(filterName, filterValue);
    }
  },

  /**
   * Update enabled top level filters in XULStore.
   */
  updateTopLevelFilters(filterName, filterValue) {
    if (filterValue) {
      this.activeTopLevelFilters.add(filterName);
    } else {
      this.activeTopLevelFilters.delete(filterName);
    }

    // Save enabled filter settings to XULStore.
    Services.xulStore.setValue(
      XULSTORE_URL,
      "quickFilter",
      "enabledTopFilters",
      JSON.stringify(Array.from(this.activeTopLevelFilters))
    );
  },

  /**
   * Ensure all the quick filter menuitems in the quick filter dropdown menu are
   * checked to reflect their current state.
   */
  updateCheckedStateQuickFilterButtons() {
    for (let item of document.querySelectorAll(".quick-filter-menuitem")) {
      if (Object.hasOwn(this.filterer.filterValues, `${item.value}`)) {
        item.setAttribute("checked", true);
        continue;
      }
      item.removeAttribute("checked");
    }
  },

  /**
   * Update the UI to reflect the state of the filterer constraints.
   *
   * @param [aFilterName] If only a single filter needs to be updated, name it.
   */
  reflectFiltererState(aFilterName) {
    // If we aren't visible then there is no need to update the widgets.
    if (this.filterer.visible) {
      let filterValues = this.filterer.filterValues;
      for (let filterDef of QuickFilterManager.filterDefs) {
        // If we only need to update one state, check and skip as appropriate.
        if (aFilterName && filterDef.name != aFilterName) {
          continue;
        }

        let domNode = document.getElementById(filterDef.domId);

        let value =
          filterDef.name in filterValues ? filterValues[filterDef.name] : null;
        if (!("reflectInDOM" in filterDef)) {
          domNode.pressed = value;
        } else {
          filterDef.reflectInDOM(domNode, value, document, this);
        }
      }
    }

    this.reflectFiltererResults();

    this.domNode.hidden = !this.filterer.visible;
  },

  /**
   * Update the UI to reflect the state of the folderDisplay in terms of
   *  filtering.  This is expected to be called by |reflectFiltererState| and
   *  when something happens event-wise in terms of search.
   *
   * We can have one of two states:
   * - No filter is active; no attributes exposed for CSS to do anything.
   * - A filter is active and we are still searching; filterActive=searching.
   */
  reflectFiltererResults() {
    let threadPane = document.getElementById("threadTree");

    // bail early if the view is in the process of being created
    if (!gDBView) {
      return;
    }

    // no filter active
    if (!gViewWrapper.search || !gViewWrapper.search.userTerms) {
      threadPane.removeAttribute("filterActive");
      this.domNode.removeAttribute("filterActive");
    } else if (gViewWrapper.searching) {
      // filter active, still searching
      // Do not set this immediately; wait a bit and then only set this if we
      //  still are in this same state (and we are still the active tab...)
      setTimeout(() => {
        threadPane.setAttribute("filterActive", "searching");
        this.domNode.setAttribute("filterActive", "searching");
      }, 500);
    }
  },

  // ----------------------
  // Event Handling Support

  /**
   * Retrieve the current filter state value (presumably an object) for mutation
   *  purposes.  This causes the filter to be the last touched filter for escape
   *  undo-ish purposes.
   */
  getFilterValueForMutation(aName) {
    return this.filterer.getFilterValue(aName);
  },

  /**
   * Set the filter state for the given named filter to the given value.  This
   *  causes the filter to be the last touched filter for escape undo-ish
   *  purposes.
   *
   * @param aName Filter name.
   * @param aValue The new filter state.
   */
  setFilterValue(aName, aValue) {
    this.filterer.setFilterValue(aName, aValue);
  },

  /**
   * For UI responsiveness purposes, defer the actual initiation of the search
   * until after the button click handling has completed and had the ability
   * to paint such.
   *
   * @param {Element} activeElement - The element that triggered a call to
   *   this function, if any.
   */
  deferredUpdateSearch(activeElement) {
    setTimeout(() => this.updateSearch(activeElement), 10);
  },

  /**
   * Update the user terms part of the search definition to reflect the active
   * filterer's current state.
   *
   * @param {Element?} activeElement - The element that triggered a call to
   *   this function, if any.
   */
  updateSearch(activeElement) {
    if (!this._filterer || !gViewWrapper?.search) {
      return;
    }

    this.activeElement = activeElement;
    this.filterer.displayedFolder = gFolder;

    let [terms, listeners] = this.filterer.createSearchTerms(
      gViewWrapper.search.session
    );

    for (let [listener, filterDef] of listeners) {
      // it registers itself with the search session.
      new QuickFilterSearchListener(
        gViewWrapper,
        this.filterer,
        filterDef,
        listener,
        quickFilterBar
      );
    }

    gViewWrapper.search.userTerms = terms;
    // Uncomment to know what the search state is when we (try and) update it.
    // dump(tab.folderDisplay.view.search.prettyString());
  },

  /**
   * Shows and hides quick filter bar, and sets the XUL Store value for the
   * quick filter bar status.
   *
   * @param {boolean} show - Filter Status.
   * @param {boolean} [init=false] - Initial Function Call.
   */
  _showFilterBar(show, init = false) {
    this.filterer.visible = show;
    if (!show) {
      this.filterer.clear();
      this.updateSearch();
      // Cannot call the below function when threadTree hasn't been initialized yet.
      if (!init) {
        threadTree.table.body.focus();
      }
    }
    this.reflectFiltererState();
    Services.xulStore.setValue(
      XULSTORE_URL,
      "quickFilterBar",
      "collapsed",
      !show
    );

    window.dispatchEvent(new Event("qfbtoggle"));
  },

  /**
   * Called by the view wrapper so we can update the results count.
   */
  onMessagesChanged() {
    let filtering = gViewWrapper.search?.userTerms != null;
    let newCount = filtering ? gDBView.numMsgsInView : null;
    this.filterer.setFilterValue("results", newCount, true);

    // - postFilterProcess everyone who cares
    // This may need to be converted into an asynchronous process at some point.
    for (let filterDef of QuickFilterManager.filterDefs) {
      if ("postFilterProcess" in filterDef) {
        let preState =
          filterDef.name in this.filterer.filterValues
            ? this.filterer.filterValues[filterDef.name]
            : null;
        let [newState, update, treatAsUserAction] = filterDef.postFilterProcess(
          preState,
          gViewWrapper,
          filtering
        );
        this.filterer.setFilterValue(
          filterDef.name,
          newState,
          !treatAsUserAction
        );
        if (update) {
          let domNode = document.getElementById(filterDef.domId);
          // We are passing update as a super-secret data propagation channel
          //  exclusively for one-off cases like the text filter gloda upsell.
          filterDef.reflectInDOM(domNode, newState, document, this, update);
        }
      }
    }

    // - Update match status.
    this.reflectFiltererState();
  },

  /**
   * The displayed folder changed. Reset or reapply the filter, depending on
   * the sticky state.
   */
  onFolderChanged() {
    this.filterer = new QuickFilterState(this.filterer);
    this.reflectFiltererState();
    if (this._filterer?.filterValues.sticky) {
      this.updateSearch();
    }
  },

  _testHelperResetFilterState() {
    if (!this._filterer) {
      return;
    }
    this._filterer = new QuickFilterState();
    this.updateSearch();
    this.reflectFiltererState();
  },
};
XPCOMUtils.defineLazyGetter(quickFilterBar, "domNode", () =>
  document.getElementById("quick-filter-bar")
);