summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/db/gloda/content/autocomplete-richlistitem.js
blob: 916c6ef5d57274843aba0d2dea80b7d4f32da918 (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
/* 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";

/* global MozXULElement, MozElements */

// Wrap in a block to prevent leaking to window scope.
{
  const gGlodaCompleteStrings = Services.strings.createBundle(
    "chrome://messenger/locale/glodaComplete.properties"
  );

  /**
   * The MozGlodacompleteBaseRichlistitem widget is the
   * abstract base class for all the gloda autocomplete items.
   *
   * @abstract
   * @augments {MozElements.MozRichlistitem}
   */
  class MozGlodacompleteBaseRichlistitem extends MozElements.MozRichlistitem {
    connectedCallback() {
      if (this.delayConnectedCallback()) {
        return;
      }
      this._boundaryCutoff = null;
    }

    get boundaryCutoff() {
      if (!this._boundaryCutoff) {
        this._boundaryCutoff = Services.prefs.getIntPref(
          "toolkit.autocomplete.richBoundaryCutoff"
        );
      }
      return this._boundaryCutoff;
    }

    _getBoundaryIndices(aText, aSearchTokens) {
      // Short circuit for empty search ([""] == "")
      if (aSearchTokens == "") {
        return [0, aText.length];
      }

      // Find which regions of text match the search terms.
      let regions = [];
      for (let search of aSearchTokens) {
        let matchIndex;
        let startIndex = 0;
        let searchLen = search.length;

        // Find all matches of the search terms, but stop early for perf.
        let lowerText = aText.toLowerCase().substr(0, this.boundaryCutoff);
        while ((matchIndex = lowerText.indexOf(search, startIndex)) >= 0) {
          // Start the next search from where this one finished.
          startIndex = matchIndex + searchLen;
          regions.push([matchIndex, startIndex]);
        }
      }

      // Sort the regions by start position then end position.
      regions = regions.sort(function (a, b) {
        let start = a[0] - b[0];
        return start == 0 ? a[1] - b[1] : start;
      });

      // Generate the boundary indices from each region.
      let start = 0;
      let end = 0;
      let boundaries = [];
      for (let i = 0; i < regions.length; i++) {
        // We have a new boundary if the start of the next is past the end.
        let region = regions[i];
        if (region[0] > end) {
          // First index is the beginning of match.
          boundaries.push(start);
          // Second index is the beginning of non-match.
          boundaries.push(end);

          // Track the new region now that we've stored the previous one.
          start = region[0];
        }

        // Push back the end index for the current or new region.
        end = Math.max(end, region[1]);
      }

      // Add the last region.
      boundaries.push(start);
      boundaries.push(end);

      // Put on the end boundary if necessary.
      if (end < aText.length) {
        boundaries.push(aText.length);
      }

      // Skip the first item because it's always 0.
      return boundaries.slice(1);
    }

    _getSearchTokens(aSearch) {
      let search = aSearch.toLowerCase();
      return search.split(/\s+/);
    }

    _needsAlternateEmphasis(aText) {
      for (let i = aText.length - 1; i >= 0; i--) {
        let charCode = aText.charCodeAt(i);
        // Arabic, Syriac, Indic languages are likely to have ligatures
        // that are broken when using the main emphasis styling.
        if (0x0600 <= charCode && charCode <= 0x109f) {
          return true;
        }
      }

      return false;
    }

    _setUpDescription(aDescriptionElement, aText) {
      // Get rid of all previous text.
      while (aDescriptionElement.hasChildNodes()) {
        aDescriptionElement.lastChild.remove();
      }

      // Get the indices that separate match and non-match text.
      let search = this.getAttribute("text");
      let tokens = this._getSearchTokens(search);
      let indices = this._getBoundaryIndices(aText, tokens);

      // If we're searching for something that needs alternate emphasis,
      // we'll need to check the text that we match.
      let checkAlt = this._needsAlternateEmphasis(search);

      let next;
      let start = 0;
      let len = indices.length;
      // Even indexed boundaries are matches, so skip the 0th if it's empty.
      for (let i = indices[0] == 0 ? 1 : 0; i < len; i++) {
        next = indices[i];
        let text = aText.substr(start, next - start);
        start = next;

        if (i % 2 == 0) {
          // Emphasize the text for even indices
          let span = aDescriptionElement.appendChild(
            document.createElementNS("http://www.w3.org/1999/xhtml", "span")
          );
          span.className =
            checkAlt && this._needsAlternateEmphasis(text)
              ? "ac-emphasize-alt"
              : "ac-emphasize-text";
          span.textContent = text;
        } else {
          // Otherwise, it's plain text
          aDescriptionElement.appendChild(document.createTextNode(text));
        }
      }
    }

    _setUpOverflow(aParentBox, aEllipsis) {
      // Hide the ellipsis in case there's just enough to not underflow.
      aEllipsis.hidden = true;

      // Start with the parent's width and subtract off its children.
      let tooltip = [];
      let children = aParentBox.children;
      let widthDiff = aParentBox.getBoundingClientRect().width;

      for (let i = 0; i < children.length; i++) {
        // Only consider a child if it actually takes up space.
        let childWidth = children[i].getBoundingClientRect().width;
        if (childWidth > 0) {
          // Subtract a little less to account for subpixel rounding.
          widthDiff -= childWidth - 0.5;

          // Add to the tooltip if it's not hidden and has text.
          let childText = children[i].textContent;
          if (childText) {
            tooltip.push(childText);
          }
        }
      }

      // If the children take up more space than the parent.. overflow!
      if (widthDiff < 0) {
        // Re-show the ellipsis now that we know it's needed.
        aEllipsis.hidden = false;

        // Separate text components with a ndash --
        aParentBox.tooltipText = tooltip.join(" \u2013 ");
      }
    }

    _doUnderflow(aName) {
      // Hide the ellipsis right when we know we're underflowing instead of
      // waiting for the timeout to trigger the _setUpOverflow calculations.
      this[aName + "Box"].tooltipText = "";
      this[aName + "OverflowEllipsis"].hidden = true;
    }
  }

  MozXULElement.implementCustomInterface(MozGlodacompleteBaseRichlistitem, [
    Ci.nsIDOMXULSelectControlItemElement,
  ]);

  /**
   * The MozGlodaContactChunkRichlistitem widget displays an autocomplete item with
   * contact chunk: e.g. image, name and description of the contact.
   *
   * @augments MozGlodacompleteBaseRichlistitem
   */
  class MozGlodaContactChunkRichlistitem extends MozGlodacompleteBaseRichlistitem {
    static get inheritedAttributes() {
      return {
        "description.ac-comment": "selected",
        "label.ac-comment": "selected",
        "description.ac-url-text": "selected",
        "label.ac-url-text": "selected",
      };
    }

    connectedCallback() {
      super.connectedCallback();
      if (this.delayConnectedCallback() || this.hasChildNodes()) {
        return;
      }
      this.setAttribute("is", "gloda-contact-chunk-richlistitem");
      this.appendChild(
        MozXULElement.parseXULToFragment(`
          <vbox>
            <hbox>
              <hbox class="ac-title"
                    flex="1"
                    onunderflow="_doUnderflow('_name');">
                <description class="ac-normal-text ac-comment"></description>
              </hbox>
              <label class="ac-ellipsis-after ac-comment"
                     hidden="true"></label>
            </hbox>
            <hbox>
              <hbox class="ac-url"
                    flex="1"
                    onunderflow="_doUnderflow('_identity');">
                <description class="ac-normal-text ac-url-text"></description>
              </hbox>
              <label class="ac-ellipsis-after ac-url-text"
                     hidden="true"></label>
            </hbox>
          </vbox>
        `)
      );

      let ellipsis = "\u2026";
      try {
        ellipsis = Services.prefs.getComplexValue(
          "intl.ellipsis",
          Ci.nsIPrefLocalizedString
        ).data;
      } catch (ex) {
        // Do nothing.. we already have a default.
      }

      this._identityOverflowEllipsis = this.querySelector("label.ac-url-text");
      this._nameOverflowEllipsis = this.querySelector("label.ac-comment");

      this._identityOverflowEllipsis.value = ellipsis;
      this._nameOverflowEllipsis.value = ellipsis;

      this._identityBox = this.querySelector(".ac-url");
      this._identity = this.querySelector("description.ac-url-text");

      this._nameBox = this.querySelector(".ac-title");
      this._name = this.querySelector("description.ac-comment");

      this._adjustAcItem();

      this.initializeAttributeInheritance();
    }

    get label() {
      let identity = this.obj;
      return identity.accessibleLabel;
    }

    _adjustAcItem() {
      let contact = this.obj;

      if (contact == null) {
        return;
      }

      let identity = contact.identities[0];

      // Emphasize the matching search terms for the description.
      this._setUpDescription(this._name, contact.name);
      this._setUpDescription(this._identity, identity.value);

      // Set up overflow on a timeout because the contents of the box
      // might not have a width yet even though we just changed them.
      setTimeout(
        this._setUpOverflow,
        0,
        this._nameBox,
        this._nameOverflowEllipsis
      );
      setTimeout(
        this._setUpOverflow,
        0,
        this._identityBox,
        this._identityOverflowEllipsis
      );
    }
  }

  customElements.define(
    "gloda-contact-chunk-richlistitem",
    MozGlodaContactChunkRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  /**
   * The MozGlodaFulltextAllRichlistitem widget displays an autocomplete full text of
   * all the items: e.g. full text explanation of the item.
   *
   * @augments MozGlodacompleteBaseRichlistitem
   */
  class MozGlodaFulltextAllRichlistitem extends MozGlodacompleteBaseRichlistitem {
    connectedCallback() {
      super.connectedCallback();
      if (this.delayConnectedCallback() || this.hasChildNodes()) {
        return;
      }
      this.setAttribute("is", "gloda-fulltext-all-richlistitem");
      this._explanation = document.createXULElement("description");
      this._explanation.classList.add("explanation");
      let label = gGlodaCompleteStrings.GetStringFromName(
        "glodaComplete.messagesMentioningMany.label"
      );
      this._explanation.setAttribute(
        "value",
        label.replace("#1", this.row.words.join(", "))
      );
      this.appendChild(this._explanation);
    }

    get label() {
      return "full text search: " + this.row.item; // what is this for? l10n?
    }
  }

  MozXULElement.implementCustomInterface(MozGlodaFulltextAllRichlistitem, [
    Ci.nsIDOMXULSelectControlItemElement,
  ]);

  customElements.define(
    "gloda-fulltext-all-richlistitem",
    MozGlodaFulltextAllRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  /**
   * The MozGlodaFulltextAllRichlistitem widget displays an autocomplete full text
   * of single item: e.g. full text explanation of the item.
   *
   * @augments MozGlodacompleteBaseRichlistitem
   */
  class MozGlodaFulltextSingleRichlistitem extends MozGlodacompleteBaseRichlistitem {
    connectedCallback() {
      super.connectedCallback();
      if (this.delayConnectedCallback() || this.hasChildNodes()) {
        return;
      }
      this.setAttribute("is", "gloda-fulltext-single-richlistitem");
      this._explanation = document.createXULElement("description");
      this._explanation.classList.add("explanation", "gloda-fulltext-single");
      this._parameters = document.createXULElement("description");

      this.appendChild(this._explanation);
      this.appendChild(this._parameters);

      let label = gGlodaCompleteStrings.GetStringFromName(
        "glodaComplete.messagesMentioning.label"
      );
      this._explanation.setAttribute(
        "value",
        label.replace("#1", this.row.item)
      );
    }

    get label() {
      return "full text search: " + this.row.item;
    }
  }

  MozXULElement.implementCustomInterface(MozGlodaFulltextSingleRichlistitem, [
    Ci.nsIDOMXULSelectControlItemElement,
  ]);

  customElements.define(
    "gloda-fulltext-single-richlistitem",
    MozGlodaFulltextSingleRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  /**
   * The MozGlodaMultiRichlistitem widget displays an autocomplete description of multiple
   * type items: e.g. explanation of the items.
   *
   * @augments MozGlodacompleteBaseRichlistitem
   */
  class MozGlodaMultiRichlistitem extends MozGlodacompleteBaseRichlistitem {
    connectedCallback() {
      super.connectedCallback();
      if (this.delayConnectedCallback() || this.hasChildNodes()) {
        return;
      }
      this.setAttribute("is", "gloda-multi-richlistitem");
      this._explanation = document.createXULElement("description");
      this._identityHolder = document.createXULElement("hbox");
      this._identityHolder.setAttribute("flex", "1");

      this.appendChild(this._explanation);
      this.appendChild(this._identityHolder);
      this._adjustAcItem();
    }

    get label() {
      return this._explanation.value;
    }

    renderItem(aObj) {
      let node = document.createXULElement("richlistitem");

      node.obj = aObj;
      node.setAttribute(
        "type",
        "gloda-" + this.row.nounDef.name + "-chunk-richlistitem"
      );

      this._identityHolder.appendChild(node);
    }

    _adjustAcItem() {
      // clear out any lingering children.
      while (this._identityHolder.hasChildNodes()) {
        this._identityHolder.lastChild.remove();
      }

      let row = this.row;
      if (row == null) {
        return;
      }

      this._explanation.value =
        row.nounDef.name + "s " + row.criteriaType + "ed " + row.criteria;

      // render anyone already in there.
      for (let item of row.collection.items) {
        this.renderItem(item);
      }
      // listen up, yo.
      row.renderer = this;
    }
  }

  MozXULElement.implementCustomInterface(MozGlodaMultiRichlistitem, [
    Ci.nsIDOMXULSelectControlItemElement,
  ]);

  customElements.define("gloda-multi-richlistitem", MozGlodaMultiRichlistitem, {
    extends: "richlistitem",
  });

  /**
   * The MozGlodaSingleIdentityRichlistitem widget displays an autocomplete item with
   * single identity: e.g. image, name and description of the item.
   *
   * @augments MozGlodacompleteBaseRichlistitem
   */
  class MozGlodaSingleIdentityRichlistitem extends MozGlodacompleteBaseRichlistitem {
    static get inheritedAttributes() {
      return {
        "description.ac-comment": "selected",
        "label.ac-comment": "selected",
        "description.ac-url-text": "selected",
        "label.ac-url-text": "selected",
      };
    }

    connectedCallback() {
      super.connectedCallback();
      if (this.delayConnectedCallback() || this.hasChildNodes()) {
        return;
      }

      this.setAttribute("is", "gloda-single-identity-richlistitem");
      this.appendChild(
        MozXULElement.parseXULToFragment(`
          <hbox class="gloda-single-identity">
            <vbox>
              <hbox>
                <hbox class="ac-title"
                      flex="1"
                      onunderflow="_doUnderflow('_name');">
                  <description class="ac-normal-text ac-comment"></description>
                </hbox>
                <label class="ac-ellipsis-after ac-comment"
                       hidden="true"></label>
              </hbox>
              <hbox>
                <hbox class="ac-url"
                      flex="1"
                      onunderflow="_doUnderflow('_identity');">
                  <description class="ac-normal-text ac-url-text"
                               inherits="selected"></description>
                </hbox>
                <label class="ac-ellipsis-after ac-url-text"
                       hidden="true"></label>
              </hbox>
            </vbox>
          </hbox>
        `)
      );

      let ellipsis = "\u2026";
      try {
        ellipsis = Services.prefs.getComplexValue(
          "intl.ellipsis",
          Ci.nsIPrefLocalizedString
        ).data;
      } catch (ex) {
        // Do nothing.. we already have a default.
      }

      this._identityOverflowEllipsis = this.querySelector("label.ac-url-text");
      this._nameOverflowEllipsis = this.querySelector("label.ac-comment");

      this._identityOverflowEllipsis.value = ellipsis;
      this._nameOverflowEllipsis.value = ellipsis;

      this._identityBox = this.querySelector(".ac-url");
      this._identity = this.querySelector("description.ac-url-text");

      this._nameBox = this.querySelector(".ac-title");
      this._name = this.querySelector("description.ac-comment");

      this._adjustAcItem();

      this.initializeAttributeInheritance();
    }

    get label() {
      let identity = this.row.item;
      return identity.accessibleLabel;
    }

    _adjustAcItem() {
      let identity = this.row.item;

      if (identity == null) {
        return;
      }

      // Emphasize the matching search terms for the description.
      this._setUpDescription(this._name, identity.contact.name);
      this._setUpDescription(this._identity, identity.value);

      // Set up overflow on a timeout because the contents of the box
      // might not have a width yet even though we just changed them.
      setTimeout(
        this._setUpOverflow,
        0,
        this._nameBox,
        this._nameOverflowEllipsis
      );
      setTimeout(
        this._setUpOverflow,
        0,
        this._identityBox,
        this._identityOverflowEllipsis
      );
    }
  }

  MozXULElement.implementCustomInterface(MozGlodaSingleIdentityRichlistitem, [
    Ci.nsIDOMXULSelectControlItemElement,
  ]);

  customElements.define(
    "gloda-single-identity-richlistitem",
    MozGlodaSingleIdentityRichlistitem,
    {
      extends: "richlistitem",
    }
  );

  /**
   * The MozGlodaSingleTagRichlistitem widget displays an autocomplete item with
   * single tag: e.g. explanation of the item.
   *
   * @augments MozGlodacompleteBaseRichlistitem
   */
  class MozGlodaSingleTagRichlistitem extends MozGlodacompleteBaseRichlistitem {
    connectedCallback() {
      super.connectedCallback();
      if (this.delayConnectedCallback() || this.hasChildNodes()) {
        return;
      }
      this.setAttribute("is", "gloda-single-tag-richlistitem");
      this._explanation = document.createXULElement("description");
      this._explanation.classList.add("explanation", "gloda-single");
      this.appendChild(this._explanation);
      let label = gGlodaCompleteStrings.GetStringFromName(
        "glodaComplete.messagesTagged.label"
      );
      this._explanation.setAttribute(
        "value",
        label.replace("#1", this.row.item.tag)
      );
    }

    get label() {
      return "tag " + this.row.item.tag;
    }
  }

  MozXULElement.implementCustomInterface(MozGlodaSingleTagRichlistitem, [
    Ci.nsIDOMXULSelectControlItemElement,
  ]);

  customElements.define(
    "gloda-single-tag-richlistitem",
    MozGlodaSingleTagRichlistitem,
    {
      extends: "richlistitem",
    }
  );
}