summaryrefslogtreecommitdiffstats
path: root/comm/mail/base/content/multimessageview.js
blob: 9b4c593fde2918e3b0c70ba7caa9885dcb693a4f (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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
/* 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/. */

var { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);
var { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);

XPCOMUtils.defineLazyModuleGetters(this, {
  DisplayNameUtils: "resource:///modules/DisplayNameUtils.jsm",
  Gloda: "resource:///modules/gloda/Gloda.jsm",
  makeFriendlyDateAgo: "resource:///modules/TemplateUtils.jsm",
  MessageArchiver: "resource:///modules/MessageArchiver.jsm",
  mimeMsgToContentSnippetAndMeta: "resource:///modules/gloda/GlodaContent.jsm",
  MsgHdrToMimeMessage: "resource:///modules/gloda/MimeMessage.jsm",
  PluralStringFormatter: "resource:///modules/TemplateUtils.jsm",
  TagUtils: "resource:///modules/TagUtils.jsm",
});

var gMessenger = Cc["@mozilla.org/messenger;1"].createInstance(Ci.nsIMessenger);

// Set up our string formatter for localizing strings.
XPCOMUtils.defineLazyGetter(this, "formatString", function () {
  let formatter = new PluralStringFormatter(
    "chrome://messenger/locale/multimessageview.properties"
  );
  return function (...args) {
    return formatter.get(...args);
  };
});

/**
 * A LimitIterator is a utility class that allows limiting the maximum number
 * of items to iterate over.
 *
 * @param aArray     The array to iterate over (can be anything with a .length
 *                   property and a subscript operator.
 * @param aMaxLength The maximum number of items to iterate over.
 */
function LimitIterator(aArray, aMaxLength) {
  this._array = aArray;
  this._maxLength = aMaxLength;
}

LimitIterator.prototype = {
  /**
   * Returns true if the iterator won't actually iterate over everything in the
   * array.
   */
  get limited() {
    return this._array.length > this._maxLength;
  },

  /**
   * Returns the number of elements that will actually be iterated over.
   */
  get length() {
    return Math.min(this._array.length, this._maxLength);
  },

  /**
   * Returns the real number of elements in the array.
   */
  get trueLength() {
    return this._array.length;
  },
};

var JS_HAS_SYMBOLS = typeof Symbol === "function";
var ITERATOR_SYMBOL = JS_HAS_SYMBOLS ? Symbol.iterator : "@@iterator";

/**
 * Iterate over the array until we hit the end or the maximum length,
 * whichever comes first.
 */
LimitIterator.prototype[ITERATOR_SYMBOL] = function* () {
  let length = this.length;
  for (let i = 0; i < length; i++) {
    yield this._array[i];
  }
};

/**
 * The MultiMessageSummary class is responsible for populating the message pane
 * with a reasonable summary of a set of messages.
 */
function MultiMessageSummary() {
  this._summarizers = {};
}

MultiMessageSummary.prototype = {
  /**
   * The maximum number of messages to examine in any way.
   */
  kMaxMessages: 10000,

  /**
   * Register a summarizer for a particular type of message summary.
   *
   * @param aSummarizer The summarizer object.
   */
  registerSummarizer(aSummarizer) {
    this._summarizers[aSummarizer.name] = aSummarizer;
    aSummarizer.onregistered(this);
  },

  /**
   * Store a mapping from a message header to the summary node in the DOM. We
   * use this to update things when Gloda tells us to.
   *
   * @param aMsgHdr The nsIMsgDBHdr.
   * @param aNode   The related DOM node.
   */
  mapMsgToNode(aMsgHdr, aNode) {
    let key = aMsgHdr.messageKey + aMsgHdr.folder.URI;
    this._msgNodes[key] = aNode;
  },

  /**
   * Clear all the content from the summary.
   */
  clear() {
    this._selectCallback = null;
    this._listener = null;
    this._glodaQuery = null;
    this._msgNodes = {};

    // Clear the messages list.
    let messageList = document.getElementById("message_list");
    while (messageList.hasChildNodes()) {
      messageList.lastChild.remove();
    }

    // Clear the notice.
    document.getElementById("notice").textContent = "";
  },

  /**
   * Fill in the summary pane describing the selected messages.
   *
   * @param aType       The type of summary to perform (e.g. 'multimessage').
   * @param aMessages   The messages to summarize.
   * @param aDBView     The current DB view.
   * @param aSelectCallback  Called with an array of nsIMsgHdrs when one of
   *                    a summarized message is clicked on.
   * @param [aListener] A listener to be notified when the summary starts and
   *                    finishes.
   */
  summarize(aType, aMessages, aDBView, aSelectCallback, aListener) {
    this.clear();

    this._selectCallback = aSelectCallback;
    this._listener = aListener;
    if (this._listener) {
      this._listener.onLoadStarted();
    }

    // Enable/disable the archive button as appropriate.
    let archiveBtn = document.getElementById("hdrArchiveButton");
    archiveBtn.hidden = !MessageArchiver.canArchive(aMessages);

    // Set archive and delete button listeners.
    let topChromeWindow = window.browsingContext.topChromeWindow;
    archiveBtn.onclick = event => {
      if (event.button == 0) {
        topChromeWindow.goDoCommand("cmd_archive");
      }
    };
    document.getElementById("hdrTrashButton").onclick = event => {
      if (event.button == 0) {
        topChromeWindow.goDoCommand("cmd_delete");
      }
    };

    headerToolbarNavigation.init();

    let summarizer = this._summarizers[aType];
    if (!summarizer) {
      throw new Error('Unknown summarizer "' + aType + '"');
    }

    let messages = new LimitIterator(aMessages, this.kMaxMessages);
    let summarizedMessages = summarizer.summarize(messages, aDBView);

    // Stash somewhere so it doesn't get GC'ed.
    this._glodaQuery = Gloda.getMessageCollectionForHeaders(
      summarizedMessages,
      this
    );
    this._computeSize(messages);
  },

  /**
   * Set the heading for the summary.
   *
   * @param title    The title for the heading.
   * @param subtitle A smaller subtitle for the heading.
   */
  setHeading(title, subtitle) {
    let titleNode = document.getElementById("summary_title");
    let subtitleNode = document.getElementById("summary_subtitle");
    titleNode.textContent = title || "";
    subtitleNode.textContent = subtitle || "";
  },

  /**
   * Create a summary item for a message or thread.
   *
   * @param aMsgOrThread An nsIMsgDBHdr or an array thereof
   * @param [aOptions]   An optional object to customize the output:
   *                      showSubject: true if the subject of the message
   *                        should be shown; defaults to false
   *                      snippetLength: the length in bytes of the message
   *                        snippet; defaults to undefined (let Gloda decide)
   * @returns A DOM node for the summary item.
   */
  makeSummaryItem(aMsgOrThread, aOptions) {
    let message, thread, numUnread, isStarred, tags;
    if (aMsgOrThread instanceof Ci.nsIMsgDBHdr) {
      thread = null;
      message = aMsgOrThread;

      numUnread = message.isRead ? 0 : 1;
      isStarred = message.isFlagged;

      tags = this._getTagsForMsg(message);
    } else {
      thread = aMsgOrThread;
      message = thread[0];

      numUnread = thread.reduce(function (x, hdr) {
        return x + (hdr.isRead ? 0 : 1);
      }, 0);
      isStarred = thread.some(function (hdr) {
        return hdr.isFlagged;
      });

      tags = new Set();
      for (let message of thread) {
        for (let tag of this._getTagsForMsg(message)) {
          tags.add(tag);
        }
      }
    }

    let row = document.createElement("li");
    row.dataset.messageId = message.messageId;
    row.classList.toggle("thread", thread && thread.length > 1);
    row.classList.toggle("unread", numUnread > 0);
    row.classList.toggle("starred", isStarred);

    row.appendChild(document.createElement("div")).classList.add("star");

    let summary = document.createElement("div");
    summary.classList.add("item_summary");
    summary
      .appendChild(document.createElement("div"))
      .classList.add("item_header");
    summary.appendChild(document.createElement("div")).classList.add("snippet");
    row.appendChild(summary);

    let itemHeaderNode = row.querySelector(".item_header");

    let authorNode = document.createElement("span");
    authorNode.classList.add("author");
    authorNode.textContent = DisplayNameUtils.formatDisplayNameList(
      message.mime2DecodedAuthor,
      "from"
    );

    if (aOptions && aOptions.showSubject) {
      authorNode.classList.add("right");
      itemHeaderNode.appendChild(authorNode);

      let subjectNode = document.createElement("span");
      subjectNode.classList.add("subject", "primary_header", "link");
      subjectNode.textContent =
        message.mime2DecodedSubject || formatString("noSubject");
      subjectNode.addEventListener("click", () => this._selectCallback(thread));
      itemHeaderNode.appendChild(subjectNode);

      if (thread && thread.length > 1) {
        let numUnreadStr = "";
        if (numUnread) {
          numUnreadStr = formatString(
            "numUnread",
            [numUnread.toLocaleString()],
            numUnread
          );
        }
        let countStr =
          "(" +
          formatString(
            "numMessages",
            [thread.length.toLocaleString()],
            thread.length
          ) +
          numUnreadStr +
          ")";

        let countNode = document.createElement("span");
        countNode.classList.add("count");
        countNode.textContent = countStr;
        itemHeaderNode.appendChild(countNode);
      }
    } else {
      let dateNode = document.createElement("span");
      dateNode.classList.add("date", "right");
      dateNode.textContent = makeFriendlyDateAgo(new Date(message.date / 1000));
      itemHeaderNode.appendChild(dateNode);

      authorNode.classList.add("primary_header", "link");
      authorNode.addEventListener("click", () => {
        this._selectCallback([message]);
      });
      itemHeaderNode.appendChild(authorNode);
    }

    let tagNode = document.createElement("span");
    tagNode.classList.add("tags");
    this._addTagNodes(tags, tagNode);
    itemHeaderNode.appendChild(tagNode);

    let snippetNode = row.querySelector(".snippet");
    try {
      const kSnippetLength = aOptions && aOptions.snippetLength;
      MsgHdrToMimeMessage(
        message,
        null,
        function (aMsgHdr, aMimeMsg) {
          if (aMimeMsg == null) {
            // Shouldn't happen, but sometimes does?
            return;
          }
          let [text, meta] = mimeMsgToContentSnippetAndMeta(
            aMimeMsg,
            aMsgHdr.folder,
            kSnippetLength
          );
          snippetNode.textContent = text;
          if (meta.author) {
            authorNode.textContent = meta.author;
          }
        },
        false,
        { saneBodySize: true }
      );
    } catch (e) {
      if (e.result == Cr.NS_ERROR_FAILURE) {
        // Offline messages generate exceptions, which is unfortunate.  When
        // that's fixed, this code should adapt. XXX
        snippetNode.textContent = "...";
      } else {
        throw e;
      }
    }
    return row;
  },

  /**
   * Show an informative notice about the summarized messages (e.g. if we only
   * summarized some of them).
   *
   * @param aNoticeText The text to show in the notice.
   */
  showNotice(aNoticeText) {
    let notice = document.getElementById("notice");
    notice.textContent = aNoticeText;
  },

  /**
   * Given a msgHdr, return a list of tag objects. This function just does the
   * messy work of understanding how tags are stored in nsIMsgDBHdrs.  It would
   * be a good candidate for a utility library.
   *
   * @param aMsgHdr The msgHdr whose tags we want.
   * @returns An array of nsIMsgTag objects.
   */
  _getTagsForMsg(aMsgHdr) {
    let keywords = new Set(aMsgHdr.getStringProperty("keywords").split(" "));
    let allTags = MailServices.tags.getAllTags();

    return allTags.filter(function (tag) {
      return keywords.has(tag.key);
    });
  },

  /**
   * Add a list of tags to a DOM node.
   *
   * @param aTags An array (or any iterable) of nsIMsgTag objects.
   * @param aTagsNode The DOM node to contain the list of tags.
   */
  _addTagNodes(aTags, aTagsNode) {
    // Make sure the tags are sorted in their natural order.
    let sortedTags = [...aTags];
    sortedTags.sort(function (a, b) {
      return a.key.localeCompare(b.key) || a.ordinal.localeCompare(b.ordinal);
    });

    for (let tag of sortedTags) {
      let tagNode = document.createElement("span");

      tagNode.className = "tag";
      let color = MailServices.tags.getColorForKey(tag.key);
      if (color) {
        let textColor = !TagUtils.isColorContrastEnough(color)
          ? "white"
          : "black";
        tagNode.setAttribute(
          "style",
          "color: " + textColor + "; background-color: " + color + ";"
        );
      }
      tagNode.dataset.tag = tag.tag;
      tagNode.textContent = tag.tag;
      aTagsNode.appendChild(tagNode);
    }
  },

  /**
   * Compute the size of the messages in the selection and display it in the
   * element of id "size".
   *
   * @param aMessages A LimitIterator of the messages to calculate the size of.
   */
  _computeSize(aMessages) {
    let numBytes = 0;
    for (let msgHdr of aMessages) {
      numBytes += msgHdr.messageSize;
      // XXX do something about news?
    }

    let format = aMessages.limited
      ? "messagesTotalSizeMoreThan"
      : "messagesTotalSize";
    document.getElementById("size").textContent = formatString(format, [
      gMessenger.formatFileSize(numBytes),
    ]);
  },

  // These are listeners for the gloda collections.
  onItemsAdded(aItems) {},
  onItemsModified(aItems) {
    this._processItems(aItems);
  },
  onItemsRemoved(aItems) {},

  /**
   * Given a set of items from a gloda collection, process them and update
   * the display accordingly.
   *
   * @param aItems Contents of a gloda collection.
   */
  _processItems(aItems) {
    let knownMessageNodes = new Map();

    for (let glodaMsg of aItems) {
      // Unread and starred will get set if any of the messages in a collapsed
      // thread qualify.  The trick here is that we may get multiple items
      // corresponding to the same thread (and hence DOM node), so we need to
      // detect when we get the first item for a particular DOM node, stash the
      // preexisting status of that DOM node, an only do transitions if the
      // items warrant it.
      let key = glodaMsg.messageKey + glodaMsg.folder.uri;
      let headerNode = this._msgNodes[key];
      if (!headerNode) {
        continue;
      }
      if (!knownMessageNodes.has(headerNode)) {
        knownMessageNodes.set(headerNode, {
          read: true,
          starred: false,
          tags: new Set(),
        });
      }

      let flags = knownMessageNodes.get(headerNode);

      // Count as read if *all* the messages are read.
      flags.read &= glodaMsg.read;
      // Count as starred if *any* of the messages are starred.
      flags.starred |= glodaMsg.starred;
      // Count as tagged with a tag if *any* of the messages have that tag.
      for (let tag of this._getTagsForMsg(glodaMsg.folderMessage)) {
        flags.tags.add(tag);
      }
    }

    for (let [headerNode, flags] of knownMessageNodes) {
      headerNode.classList.toggle("unread", !flags.read);
      headerNode.classList.toggle("starred", flags.starred);

      // Clear out all the tags and start fresh, just to make sure we don't get
      // out of sync.
      let tagsNode = headerNode.querySelector(".tags");
      while (tagsNode.hasChildNodes()) {
        tagsNode.lastChild.remove();
      }
      this._addTagNodes(flags.tags, tagsNode);
    }
  },

  onQueryCompleted(aCollection) {
    // If we need something that's just available from GlodaMessages, this is
    // where we'll get it initially.
    if (this._listener) {
      this._listener.onLoadCompleted();
    }
  },
};

/**
 * A summarizer to use for a single thread.
 */
function ThreadSummarizer() {}

ThreadSummarizer.prototype = {
  /**
   * The maximum number of messages to summarize.
   */
  kMaxSummarizedMessages: 100,

  /**
   * The length of message snippets to fetch from Gloda.
   */
  kSnippetLength: 300,

  /**
   * Returns a canonical name for this summarizer.
   */
  get name() {
    return "thread";
  },

  /**
   * A function to be called once the summarizer has been registered with the
   * main summary object.
   *
   * @param aContext The MultiMessageSummary object holding this summarizer.
   */
  onregistered(aContext) {
    this.context = aContext;
  },

  /**
   * Summarize a list of messages.
   *
   * @param aMessages A LimitIterator of the messages to summarize.
   * @returns An array of the messages actually summarized.
   */
  summarize(aMessages, aDBView) {
    let messageList = document.getElementById("message_list");

    // Remove all ignored messages from summarization.
    let summarizedMessages = [];
    for (let message of aMessages) {
      if (!message.isKilled) {
        summarizedMessages.push(message);
      }
    }
    let ignoredCount = aMessages.trueLength - summarizedMessages.length;

    // Summarize the selected messages.
    let subject = null;
    let maxCountExceeded = false;
    for (let [i, msgHdr] of summarizedMessages.entries()) {
      if (i == this.kMaxSummarizedMessages) {
        summarizedMessages.length = i;
        maxCountExceeded = true;
        break;
      }

      if (subject == null) {
        subject = msgHdr.mime2DecodedSubject;
      }

      let msgNode = this.context.makeSummaryItem(msgHdr, {
        snippetLength: this.kSnippetLength,
      });
      messageList.appendChild(msgNode);

      this.context.mapMsgToNode(msgHdr, msgNode);
    }

    // Set the heading based on the subject and number of messages.
    let countInfo = formatString(
      "numMessages",
      [aMessages.length.toLocaleString()],
      aMessages.length
    );
    if (ignoredCount != 0) {
      let format = aMessages.limited ? "atLeastNumIgnored" : "numIgnored";
      countInfo += formatString(
        format,
        [ignoredCount.toLocaleString()],
        ignoredCount
      );
    }

    this.context.setHeading(subject || formatString("noSubject"), countInfo);

    if (maxCountExceeded) {
      this.context.showNotice(
        formatString("maxCountExceeded", [
          aMessages.trueLength.toLocaleString(),
          this.kMaxSummarizedMessages.toLocaleString(),
        ])
      );
    }
    return summarizedMessages;
  },
};

/**
 * A summarizer to use when multiple threads are selected.
 */
function MultipleSelectionSummarizer() {}

MultipleSelectionSummarizer.prototype = {
  /**
   * The maximum number of threads to summarize.
   */
  kMaxSummarizedThreads: 100,

  /**
   * The length of message snippets to fetch from Gloda.
   */
  kSnippetLength: 300,

  /**
   * Returns a canonical name for this summarizer.
   */
  get name() {
    return "multipleselection";
  },

  /**
   * A function to be called once the summarizer has been registered with the
   * main summary object.
   *
   * @param aContext The MultiMessageSummary object holding this summarizer.
   */
  onregistered(aContext) {
    this.context = aContext;
  },

  /**
   * Summarize a list of messages.
   *
   * @param aMessages The messages to summarize.
   */
  summarize(aMessages, aDBView) {
    let messageList = document.getElementById("message_list");

    let threads = this._buildThreads(aMessages, aDBView);
    let threadsCount = threads.length;

    // Set the heading based on the number of messages & threads.
    let format = aMessages.limited
      ? "atLeastNumConversations"
      : "numConversations";
    this.context.setHeading(
      formatString(format, [threads.length.toLocaleString()], threads.length)
    );

    // Summarize the selected messages by thread.
    let maxCountExceeded = false;
    for (let [i, msgs] of threads.entries()) {
      if (i == this.kMaxSummarizedThreads) {
        threads.length = i;
        maxCountExceeded = true;
        break;
      }

      let msgNode = this.context.makeSummaryItem(msgs, {
        showSubject: true,
        snippetLength: this.kSnippetLength,
      });
      messageList.appendChild(msgNode);

      for (let msgHdr of msgs) {
        this.context.mapMsgToNode(msgHdr, msgNode);
      }
    }

    if (maxCountExceeded) {
      this.context.showNotice(
        formatString("maxThreadCountExceeded", [
          threadsCount.toLocaleString(),
          this.kMaxSummarizedThreads.toLocaleString(),
        ])
      );

      // Return only the messages for the threads we're actually showing. We
      // need to collapse our array-of-arrays into a flat array.
      return threads.reduce(function (accum, curr) {
        accum.push(...curr);
        return accum;
      }, []);
    }

    // Return everything, since we're showing all the threads. Don't forget to
    // turn it into an array, though!
    return [...aMessages];
  },

  /**
   * Group all the messages to be summarized into threads.
   *
   * @param aMessages The messages to group.
   * @returns An array of arrays of messages, grouped by thread.
   */
  _buildThreads(aMessages, aDBView) {
    // First, we group the messages in threads and count the threads.
    let threads = [];
    let threadMap = {};
    for (let msgHdr of aMessages) {
      let viewThreadId = aDBView.getThreadContainingMsgHdr(msgHdr).threadKey;
      if (!(viewThreadId in threadMap)) {
        threadMap[viewThreadId] = threads.length;
        threads.push([msgHdr]);
      } else {
        threads[threadMap[viewThreadId]].push(msgHdr);
      }
    }
    return threads;
  },
};

var gMessageSummary = new MultiMessageSummary();

gMessageSummary.registerSummarizer(new ThreadSummarizer());
gMessageSummary.registerSummarizer(new MultipleSelectionSummarizer());

/**
 * Roving tab navigation for the header buttons.
 */
const headerToolbarNavigation = {
  /**
   * If the roving tab has already been loaded.
   *
   * @type {boolean}
   */
  isLoaded: false,
  /**
   * Get all currently visible buttons of the message header toolbar.
   *
   * @returns {Array} An array of buttons.
   */
  get headerButtons() {
    return this.headerToolbar.querySelectorAll(
      `toolbarbutton:not([hidden="true"])`
    );
  },

  init() {
    // Bail out if we already initialized this.
    if (this.isLoaded) {
      return;
    }
    this.headerToolbar = document.getElementById("header-view-toolbar");
    this.headerToolbar.addEventListener("keypress", event => {
      this.triggerMessageHeaderRovingTab(event);
    });
    this.updateRovingTab();
    this.isLoaded = true;
  },

  /**
   * Update the `tabindex` attribute of the currently visible buttons.
   */
  updateRovingTab() {
    for (const button of this.headerButtons) {
      button.tabIndex = -1;
    }
    // Allow focus on the first available button.
    // We use `setAttribute` to guarantee compatibility with XUL toolbarbuttons.
    this.headerButtons[0].setAttribute("tabindex", "0");
  },

  /**
   * Handles the keypress event on the message header toolbar.
   *
   * @param {Event} event - The keypress DOMEvent.
   */
  triggerMessageHeaderRovingTab(event) {
    // Expected keyboard actions are Left, Right, Home, End, Space, and Enter.
    if (!["ArrowRight", "ArrowLeft", " ", "Enter"].includes(event.key)) {
      return;
    }

    const headerButtons = [...this.headerButtons];
    const focusableButton = headerButtons.find(b => b.tabIndex != -1);
    let elementIndex = headerButtons.indexOf(focusableButton);

    // TODO: Remove once the buttons are updated to not be XUL
    // NOTE: Normally a button click handler would cover Enter and Space key
    // events. However, we need to prevent the default behavior and explicitly
    // trigger the button click because the XUL toolbarbuttons do not work when
    // the Enter key is pressed. They do work when the Space key is pressed.
    // However, if the toolbarbutton is a dropdown menu, the Space key
    // does not open the menu.
    if (
      event.key == "Enter" ||
      (event.key == " " && event.target.hasAttribute("type"))
    ) {
      event.preventDefault();
      event.target.click();
      return;
    }

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

    // Move the focus to a new toolbar button and update the tabindex attribute.
    const newFocusableButton = headerButtons[elementIndex];
    if (newFocusableButton) {
      focusableButton.tabIndex = -1;
      newFocusableButton.setAttribute("tabindex", "0");
      newFocusableButton.focus();
    }
  },
};