summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/addrbook/test/browser/browser_directory_tree.js
blob: ee4b31ab7cac88a5203604438a61c681b92018cc (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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
/* 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/. */

function rightClickOnIndex(index) {
  let abWindow = getAddressBookWindow();
  let booksList = abWindow.booksList;
  let menu = abWindow.document.getElementById("bookContext");

  let shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown");
  EventUtils.synthesizeMouseAtCenter(
    booksList
      .getRowAtIndex(index)
      .querySelector(".bookRow-name, .listRow-name"),
    { type: "contextmenu" },
    abWindow
  );
  return shownPromise;
}

/**
 * Tests that additions and removals are accurately displayed.
 */
add_task(async function test_additions_and_removals() {
  function checkBooksOrder(...expected) {
    function checkRow(index, { level, open, isList, text, uid }) {
      info(`Row ${index}`);
      let row = rows[index];

      let containingList = row.closest("ul");
      if (level == 1) {
        Assert.equal(containingList.getAttribute("is"), "ab-tree-listbox");
      } else if (level == 2) {
        Assert.equal(containingList.parentNode.localName, "li");
        containingList = containingList.parentNode.closest("ul");
        Assert.equal(containingList.getAttribute("is"), "ab-tree-listbox");
      }

      let childList = row.querySelector("ul");
      // NOTE: We're not explicitly handling open === false because no test
      // needed it.
      if (open) {
        // Ancestor shouldn't have the collapsed class and the UL child list
        // should be expanded and visible.
        Assert.ok(!row.classList.contains("collapsed"));
        Assert.greater(childList.clientHeight, 0);
      } else if (childList) {
        if (row.classList.contains("collapsed")) {
          // If we have a UL child list and the ancestor element has a collapsed
          // class, the child list shouldn't be visible.
          Assert.equal(childList.clientHeight, 0);
        } else if (childList.childNodes.length) {
          // If the ancestor doesn't have the collapsed class, and the UL child
          // list has at least one child node, the child list should be visible.
          Assert.greater(childList.clientHeight, 0);
        }
      }

      Assert.equal(row.classList.contains("listRow"), isList);
      Assert.equal(row.querySelector("span").textContent, text);
      Assert.equal(row.getAttribute("aria-label"), text);
      Assert.equal(row.dataset.uid, uid);
    }

    let rows = abWindow.booksList.rows;
    Assert.equal(rows.length, expected.length + 1);
    for (let i = 0; i < expected.length; i++) {
      let dir = expected[i].directory;
      checkRow(i + 1, {
        ...expected[i],
        isList: dir.isMailList,
        text: dir.dirName,
        uid: dir.UID,
      });
    }
  }

  let abWindow = await openAddressBookWindow();

  // Check the initial order.

  checkDirectoryDisplayed(null);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: historyBook }
  );

  // Add one book, *not* using the UI, and check that we don't move to it.

  let newBook1 = createAddressBook("New Book 1");
  checkDirectoryDisplayed(null);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1 },
    { level: 1, directory: historyBook }
  );

  // Add another book, using the UI, and check that we move to the new book.

  let newBook2 = await createAddressBookWithUI("New Book 2");
  checkDirectoryDisplayed(newBook2);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1 },
    { level: 1, directory: newBook2 },
    { level: 1, directory: historyBook }
  );

  // Add some lists, *not* using the UI, and check that we don't move to them.

  let list1 = newBook1.addMailList(createMailingList("New Book 1 - List 1"));
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(newBook2);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list1 },
    { level: 1, directory: newBook2 },
    { level: 1, directory: historyBook }
  );

  let list3 = newBook1.addMailList(createMailingList("New Book 1 - List 3"));
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(newBook2);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list1 },
    { level: 2, directory: list3 },
    { level: 1, directory: newBook2 },
    { level: 1, directory: historyBook }
  );

  let list0 = newBook1.addMailList(createMailingList("New Book 1 - List 0"));
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(newBook2);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list3 },
    { level: 1, directory: newBook2 },
    { level: 1, directory: historyBook }
  );

  let list2 = newBook1.addMailList(createMailingList("New Book 1 - List 2"));
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(newBook2);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 2, directory: list3 },
    { level: 1, directory: newBook2 },
    { level: 1, directory: historyBook }
  );

  // Close the window and open it again. The tree should be as it was before.

  await closeAddressBookWindow();
  abWindow = await openAddressBookWindow();

  checkDirectoryDisplayed(null);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 2, directory: list3 },
    { level: 1, directory: newBook2 },
    { level: 1, directory: historyBook }
  );

  openDirectory(newBook2);

  let list4 = newBook2.addMailList(createMailingList("New Book 2 - List 4"));
  checkDirectoryDisplayed(newBook2);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 2, directory: list3 },
    { level: 1, directory: newBook2, open: true },
    { level: 2, directory: list4 },
    { level: 1, directory: historyBook }
  );

  // Add a new list, using the UI, and check that we move to it.

  let list5 = await createMailingListWithUI(newBook2, "New Book 2 - List 5");
  checkDirectoryDisplayed(list5);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 2, directory: list3 },
    { level: 1, directory: newBook2, open: true },
    { level: 2, directory: list4 },
    { level: 2, directory: list5 },
    { level: 1, directory: historyBook }
  );

  let list6 = await createMailingListWithUI(newBook2, "New Book 2 - List 6");
  checkDirectoryDisplayed(list6);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 2, directory: list3 },
    { level: 1, directory: newBook2, open: true },
    { level: 2, directory: list4 },
    { level: 2, directory: list5 },
    { level: 2, directory: list6 },
    { level: 1, directory: historyBook }
  );
  // Delete a list that isn't displayed, and check that we don't move.

  newBook1.deleteDirectory(list3);
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(list6);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 1, directory: newBook2, open: true },
    { level: 2, directory: list4 },
    { level: 2, directory: list5 },
    { level: 2, directory: list6 },
    { level: 1, directory: historyBook }
  );

  // Select list5
  let list5Row = abWindow.booksList.getRowForUID(list5.UID);
  EventUtils.synthesizeMouseAtCenter(
    list5Row.querySelector("span"),
    {},
    abWindow
  );
  checkDirectoryDisplayed(list5);

  // Delete the displayed list, and check that we move to the next list under
  // the same book.

  newBook2.deleteDirectory(list5);
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(list6);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 1, directory: newBook2, open: true },
    { level: 2, directory: list4 },
    { level: 2, directory: list6 },
    { level: 1, directory: historyBook }
  );

  // Delete the last list, and check we move to the previous list under the same
  // book.
  newBook2.deleteDirectory(list6);
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(list4);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 1, directory: newBook2, open: true },
    { level: 2, directory: list4 },
    { level: 1, directory: historyBook }
  );

  // Delete the displayed book, and check that we move to the next book.

  await promiseDirectoryRemoved(newBook2.URI);
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(historyBook);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: newBook1, open: true },
    { level: 2, directory: list0 },
    { level: 2, directory: list1 },
    { level: 2, directory: list2 },
    { level: 1, directory: historyBook }
  );

  // Select a list in the first book, then delete the book. Check that we
  // move to the next book.

  openDirectory(list1);
  await promiseDirectoryRemoved(newBook1.URI);
  await new Promise(r => abWindow.setTimeout(r));
  checkDirectoryDisplayed(historyBook);
  checkBooksOrder(
    { level: 1, directory: personalBook },
    { level: 1, directory: historyBook }
  );

  await closeAddressBookWindow();
});

/**
 * Tests that renaming or deleting books or lists is reflected in the UI.
 */
add_task(async function test_rename_and_delete() {
  let abWindow = await openAddressBookWindow();

  let abDocument = abWindow.document;
  let booksList = abWindow.booksList;
  let searchInput = abWindow.searchInput;
  Assert.equal(booksList.rowCount, 3);

  // Create a book.

  EventUtils.synthesizeMouseAtCenter(booksList, {}, abWindow);
  let newBook = await createAddressBookWithUI("New Book");
  Assert.equal(booksList.rowCount, 4);
  Assert.equal(booksList.getIndexForUID(newBook.UID), 2);
  Assert.equal(booksList.selectedIndex, 2);
  Assert.equal(abDocument.activeElement, booksList);

  let bookRow = booksList.getRowAtIndex(2);
  Assert.equal(bookRow.querySelector(".bookRow-name").textContent, "New Book");
  Assert.equal(bookRow.getAttribute("aria-label"), "New Book");

  await TestUtils.waitForCondition(
    () => searchInput.placeholder == "Search New Book",
    "search placeholder updated"
  );

  // Rename the book.

  let menu = abDocument.getElementById("bookContext");
  let propertiesMenuItem = abDocument.getElementById("bookContextProperties");

  await rightClickOnIndex(2);

  Assert.ok(BrowserTestUtils.is_visible(propertiesMenuItem));
  Assert.ok(!propertiesMenuItem.disabled);
  Assert.deepEqual(document.l10n.getAttributes(propertiesMenuItem), {
    id: "about-addressbook-books-context-properties",
    args: null,
  });

  let dialogPromise = promiseLoadSubDialog(
    "chrome://messenger/content/addressbook/abAddressBookNameDialog.xhtml"
  ).then(async function (dialogWindow) {
    let dialogDocument = dialogWindow.document;

    let nameInput = dialogDocument.getElementById("name");
    Assert.equal(nameInput.value, "New Book");
    nameInput.value = "Old Book";

    dialogDocument.querySelector("dialog").getButton("accept").click();
  });
  menu.activateItem(propertiesMenuItem);
  await dialogPromise;

  Assert.equal(booksList.rowCount, 4);
  Assert.equal(booksList.getIndexForUID(newBook.UID), 2);
  Assert.equal(booksList.selectedIndex, 2);
  Assert.equal(abDocument.activeElement, booksList);

  bookRow = booksList.getRowAtIndex(2);
  Assert.equal(bookRow.querySelector(".bookRow-name").textContent, "Old Book");
  Assert.equal(bookRow.getAttribute("aria-label"), "Old Book");

  await TestUtils.waitForCondition(
    () => searchInput.placeholder == "Search Old Book",
    "search placeholder updated"
  );

  // Create a list.

  let newList = await createMailingListWithUI(newBook, "New List");
  Assert.equal(booksList.rowCount, 5);
  Assert.equal(booksList.getIndexForUID(newList.UID), 3);
  Assert.equal(booksList.selectedIndex, 3);
  Assert.equal(abDocument.activeElement, booksList);

  let listRow = booksList.getRowAtIndex(3);
  Assert.equal(
    listRow.compareDocumentPosition(bookRow),
    Node.DOCUMENT_POSITION_CONTAINS | Node.DOCUMENT_POSITION_PRECEDING
  );
  Assert.equal(listRow.querySelector(".listRow-name").textContent, "New List");
  Assert.equal(listRow.getAttribute("aria-label"), "New List");

  await TestUtils.waitForCondition(
    () => searchInput.placeholder == "Search New List",
    "search placeholder updated"
  );

  // Rename the list.

  await rightClickOnIndex(3);

  Assert.ok(BrowserTestUtils.is_visible(propertiesMenuItem));
  Assert.deepEqual(document.l10n.getAttributes(propertiesMenuItem), {
    id: "about-addressbook-books-context-edit-list",
    args: null,
  });

  dialogPromise = promiseLoadSubDialog(
    "chrome://messenger/content/addressbook/abEditListDialog.xhtml"
  ).then(async function (dialogWindow) {
    let dialogDocument = dialogWindow.document;

    let nameInput = dialogDocument.getElementById("ListName");
    Assert.equal(nameInput.value, "New List");
    nameInput.value = "Old List";

    dialogDocument.querySelector("dialog").getButton("accept").click();
  });
  menu.activateItem(propertiesMenuItem);
  await dialogPromise;

  Assert.equal(booksList.rowCount, 5);
  Assert.equal(booksList.getIndexForUID(newList.UID), 3);
  Assert.equal(booksList.selectedIndex, 3);
  Assert.equal(abDocument.activeElement, booksList);

  listRow = booksList.getRowAtIndex(3);
  Assert.equal(listRow.querySelector(".listRow-name").textContent, "Old List");
  Assert.equal(listRow.getAttribute("aria-label"), "Old List");

  await TestUtils.waitForCondition(
    () => searchInput.placeholder == "Search Old List",
    "search placeholder updated"
  );

  // Delete the list.

  let promptPromise = BrowserTestUtils.promiseAlertDialog("accept");
  let selectPromise = BrowserTestUtils.waitForEvent(booksList, "select");
  EventUtils.synthesizeKey("KEY_Delete", {}, abWindow);
  await promptPromise;
  await selectPromise;
  Assert.equal(newBook.childNodes.length, 0, "list was actually deleted");
  await new Promise(r => abWindow.setTimeout(r));

  Assert.equal(booksList.rowCount, 4);
  Assert.equal(booksList.getIndexForUID(newBook.UID), 2);
  Assert.equal(booksList.getIndexForUID(newList.UID), -1);
  // Moves to parent when last list is deleted.
  Assert.equal(booksList.selectedIndex, 2);
  Assert.equal(abDocument.activeElement, booksList);

  bookRow = booksList.getRowAtIndex(2);
  Assert.ok(!bookRow.classList.contains("children"));
  Assert.ok(!bookRow.querySelector("ul, li"));

  // Delete the book.

  promptPromise = BrowserTestUtils.promiseAlertDialog("accept");
  selectPromise = BrowserTestUtils.waitForEvent(booksList, "select");
  EventUtils.synthesizeKey("KEY_Delete", {}, abWindow);
  await promptPromise;
  await selectPromise;
  Assert.equal(
    MailServices.ab.directories.length,
    2,
    "book was actually deleted"
  );

  Assert.equal(booksList.rowCount, 3);
  Assert.equal(booksList.getIndexForUID(newBook.UID), -1);
  Assert.equal(booksList.selectedIndex, 2);
  Assert.equal(abDocument.activeElement, booksList);

  // Attempt to delete the All Address Books entry.
  // Synthesizing the delete key here does not throw immediately.

  booksList.selectedIndex = 0;
  await Assert.rejects(
    booksList.deleteSelected(),
    /Cannot delete the All Address Books item/,
    "Attempting to delete All Address Books should fail."
  );

  // Attempt to delete Personal Address Book.
  // Synthesizing the delete key here does not throw immediately.

  booksList.selectedIndex = 1;
  await Assert.rejects(
    booksList.deleteSelected(),
    /Refusing to delete a built-in address book/,
    "Attempting to delete Personal Address Book should fail."
  );

  // Attempt to delete Collected Addresses.
  // Synthesizing the delete key here does not throw immediately.

  booksList.selectedIndex = 2;
  await Assert.rejects(
    booksList.deleteSelected(),
    /Refusing to delete a built-in address book/,
    "Attempting to delete Collected Addresses should fail."
  );

  await closeAddressBookWindow();
});

/**
 * Tests the context menu of the list.
 */
add_task(async function test_context_menu() {
  let book = createAddressBook("Ordinary Book");
  book.addMailList(createMailingList("Ordinary List"));
  createAddressBook("CardDAV Book", Ci.nsIAbManager.CARDDAV_DIRECTORY_TYPE);

  let abWindow = await openAddressBookWindow();
  let abDocument = abWindow.document;
  let booksList = abWindow.booksList;

  let menu = abWindow.document.getElementById("bookContext");
  let propertiesMenuItem = abDocument.getElementById("bookContextProperties");
  let synchronizeMenuItem = abDocument.getElementById("bookContextSynchronize");
  let printMenuItem = abDocument.getElementById("bookContextPrint");
  let deleteMenuItem = abDocument.getElementById("bookContextDelete");
  let removeMenuItem = abDocument.getElementById("bookContextRemove");
  let startupDefaultItem = abDocument.getElementById(
    "bookContextStartupDefault"
  );

  Assert.equal(booksList.rowCount, 6);

  // Test that the menu does not show for All Address Books.

  await rightClickOnIndex(0);
  Assert.equal(booksList.selectedIndex, 0);
  Assert.equal(abDocument.activeElement, booksList);

  let visibleItems = [...menu.children].filter(BrowserTestUtils.is_visible);
  Assert.equal(visibleItems.length, 1);
  Assert.equal(
    visibleItems[0],
    startupDefaultItem,
    "only the startup default item should be visible"
  );
  let hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden");
  menu.hidePopup();

  // Test directories that can't be deleted.

  for (let index of [1, booksList.rowCount - 1]) {
    await rightClickOnIndex(index);
    Assert.equal(booksList.selectedIndex, index);
    Assert.ok(BrowserTestUtils.is_visible(propertiesMenuItem));
    Assert.ok(!propertiesMenuItem.disabled);
    Assert.ok(!BrowserTestUtils.is_visible(synchronizeMenuItem));
    Assert.ok(BrowserTestUtils.is_visible(printMenuItem));
    Assert.ok(!printMenuItem.disabled);
    Assert.ok(BrowserTestUtils.is_visible(deleteMenuItem));
    Assert.ok(deleteMenuItem.disabled);
    Assert.ok(!BrowserTestUtils.is_visible(removeMenuItem));
    hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden");
    menu.hidePopup();
    await hiddenPromise;
    Assert.equal(abDocument.activeElement, booksList);
  }

  // Test and delete CardDAV directory at index 4.

  await rightClickOnIndex(4);
  Assert.equal(booksList.selectedIndex, 4);
  Assert.ok(BrowserTestUtils.is_visible(propertiesMenuItem));
  Assert.ok(!propertiesMenuItem.disabled);
  Assert.ok(BrowserTestUtils.is_visible(synchronizeMenuItem));
  Assert.ok(!synchronizeMenuItem.disabled);
  Assert.ok(BrowserTestUtils.is_visible(printMenuItem));
  Assert.ok(!printMenuItem.disabled);
  Assert.ok(!BrowserTestUtils.is_visible(deleteMenuItem));
  Assert.ok(BrowserTestUtils.is_visible(removeMenuItem));
  Assert.ok(!removeMenuItem.disabled);
  let promptPromise = BrowserTestUtils.promiseAlertDialog("accept");
  let selectPromise = BrowserTestUtils.waitForEvent(booksList, "select");
  hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden");
  menu.activateItem(removeMenuItem);
  await promptPromise;
  await selectPromise;
  await hiddenPromise;
  Assert.equal(abDocument.activeElement, booksList);

  Assert.equal(booksList.rowCount, 5);
  Assert.equal(booksList.selectedIndex, 4);
  Assert.equal(menu.state, "closed");

  // Test and delete list at index 3, then directory at index 2.

  for (let index of [3, 2]) {
    await new Promise(r => abWindow.setTimeout(r, 250));
    await rightClickOnIndex(index);
    Assert.equal(booksList.selectedIndex, index);
    Assert.ok(BrowserTestUtils.is_visible(propertiesMenuItem));
    Assert.ok(!propertiesMenuItem.disabled);
    Assert.ok(!BrowserTestUtils.is_visible(synchronizeMenuItem));
    Assert.ok(BrowserTestUtils.is_visible(printMenuItem));
    Assert.ok(!printMenuItem.disabled);
    Assert.ok(BrowserTestUtils.is_visible(deleteMenuItem));
    Assert.ok(!deleteMenuItem.disabled);
    Assert.ok(!BrowserTestUtils.is_visible(removeMenuItem));
    promptPromise = BrowserTestUtils.promiseAlertDialog("accept");
    selectPromise = BrowserTestUtils.waitForEvent(booksList, "select");
    hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden");
    menu.activateItem(deleteMenuItem);
    await promptPromise;
    await selectPromise;
    await hiddenPromise;
    Assert.equal(abDocument.activeElement, booksList);

    if (index == 3) {
      Assert.equal(booksList.rowCount, 4);
      // Moves to parent when last list is deleted.
      Assert.equal(booksList.selectedIndex, 2);
    } else {
      Assert.equal(booksList.rowCount, 3);
      Assert.equal(booksList.selectedIndex, 2);
    }
    Assert.equal(menu.state, "closed");
  }

  // Test that the menu does not show beyond the last book.

  EventUtils.synthesizeMouseAtCenter(
    booksList,
    100,
    booksList.clientHeight - 10,
    { type: "contextmenu" },
    abWindow
  );
  Assert.equal(booksList.selectedIndex, 2);
  await new Promise(r => abWindow.setTimeout(r, 500));
  Assert.equal(menu.state, "closed", "menu stayed closed as expected");
  Assert.equal(abDocument.activeElement, booksList);

  await closeAddressBookWindow();
});

/**
 * Tests the menu button on each item.
 */
add_task(async function test_context_menu_button() {
  let book = createAddressBook("Ordinary Book");
  book.addMailList(createMailingList("Ordinary List"));

  let abWindow = await openAddressBookWindow();
  let booksList = abWindow.booksList;
  let menu = abWindow.document.getElementById("bookContext");

  for (let row of booksList.rows) {
    info(row.querySelector(".bookRow-name, .listRow-name").textContent);
    let button = row.querySelector(".bookRow-menu, .listRow-menu");
    Assert.ok(BrowserTestUtils.is_hidden(button), "menu button is hidden");

    EventUtils.synthesizeMouse(row, 100, 5, { type: "mousemove" }, abWindow);
    Assert.ok(BrowserTestUtils.is_visible(button), "menu button is visible");

    let shownPromise = BrowserTestUtils.waitForEvent(menu, "popupshown");
    EventUtils.synthesizeMouseAtCenter(button, {}, abWindow);
    await shownPromise;

    let buttonRect = button.getBoundingClientRect();
    let menuRect = menu.getBoundingClientRect();
    Assert.less(
      Math.abs(menuRect.top - buttonRect.bottom),
      13,
      "menu appeared near the button vertically"
    );
    Assert.less(
      Math.abs(menuRect.left - buttonRect.left),
      20,
      "menu appeared near the button horizontally"
    );

    let hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden");
    menu.hidePopup();
    await hiddenPromise;
  }

  await closeAddressBookWindow();

  await promiseDirectoryRemoved(book.URI);
});

/**
 * Tests that the collapsed state of books survives a reload of the page.
 */
add_task(async function test_collapse_expand() {
  Services.xulStore.removeDocument("about:addressbook");

  personalBook.addMailList(createMailingList("Personal List 1"));
  personalBook.addMailList(createMailingList("Personal List 2"));

  historyBook.addMailList(createMailingList("History List 1"));

  let book1 = createAddressBook("Book 1");
  book1.addMailList(createMailingList("Book 1 List 1"));
  book1.addMailList(createMailingList("Book 1 List 2"));

  let book2 = createAddressBook("Book 2");
  book2.addMailList(createMailingList("Book 2 List 1"));
  book2.addMailList(createMailingList("Book 2 List 2"));
  book2.addMailList(createMailingList("Book 2 List 3"));

  function getRowForBook(book) {
    return abDocument.getElementById(`book-${book.UID}`);
  }

  function checkCollapsedState(book, expectedCollapsed) {
    Assert.equal(
      getRowForBook(book).classList.contains("collapsed"),
      expectedCollapsed,
      `${book.dirName} is ${expectedCollapsed ? "collapsed" : "expanded"}`
    );
  }

  function toggleCollapsedState(book) {
    let twisty = getRowForBook(book).querySelector(".twisty");
    Assert.ok(
      BrowserTestUtils.is_visible(twisty),
      `twisty for ${book.dirName} is visible`
    );
    EventUtils.synthesizeMouseAtCenter(twisty, {}, abWindow);
  }

  let abWindow = await openAddressBookWindow();
  let abDocument = abWindow.document;

  checkCollapsedState(personalBook, false);
  checkCollapsedState(book1, false);
  checkCollapsedState(book2, false);
  checkCollapsedState(historyBook, false);

  toggleCollapsedState(personalBook);
  toggleCollapsedState(book1);

  info("Closing and re-opening");
  await closeAddressBookWindow();
  abWindow = await openAddressBookWindow();
  abDocument = abWindow.document;

  checkCollapsedState(personalBook, true);
  checkCollapsedState(book1, true);
  checkCollapsedState(book2, false);
  checkCollapsedState(historyBook, false);

  toggleCollapsedState(book1);
  toggleCollapsedState(book2);
  toggleCollapsedState(historyBook);

  info("Closing and re-opening");
  await closeAddressBookWindow();
  abWindow = await openAddressBookWindow();
  abDocument = abWindow.document;

  checkCollapsedState(personalBook, true);
  checkCollapsedState(book1, false);
  checkCollapsedState(book2, true);
  checkCollapsedState(historyBook, true);

  toggleCollapsedState(personalBook);

  info("Closing and re-opening");
  await closeAddressBookWindow();
  await promiseDirectoryRemoved(book2.URI);
  abWindow = await openAddressBookWindow();
  abDocument = abWindow.document;

  checkCollapsedState(personalBook, false);
  checkCollapsedState(book1, false);
  checkCollapsedState(historyBook, true);

  await closeAddressBookWindow();

  personalBook.childNodes.forEach(list => personalBook.deleteDirectory(list));
  historyBook.childNodes.forEach(list => historyBook.deleteDirectory(list));
  await promiseDirectoryRemoved(book1.URI);
  Services.xulStore.removeDocument("about:addressbook");
});

/**
 * Tests that the chosen default directory (or lack thereof) is opened when
 * the page opens.
 */
add_task(async function test_startup_directory() {
  const URI_PREF = "mail.addr_book.view.startupURI";
  const DEFAULT_PREF = "mail.addr_book.view.startupURIisDefault";

  Services.prefs.clearUserPref(URI_PREF);
  Services.prefs.clearUserPref(DEFAULT_PREF);

  async function checkMenuItem(index, expectChecked, toggle = false) {
    await rightClickOnIndex(index);

    let menu = abWindow.document.getElementById("bookContext");
    let item = abWindow.document.getElementById("bookContextStartupDefault");
    Assert.equal(
      item.hasAttribute("checked"),
      expectChecked,
      `directory at index ${index} is the default?`
    );

    let hiddenPromise = BrowserTestUtils.waitForEvent(menu, "popuphidden");
    if (toggle) {
      menu.activateItem(item);
    } else {
      menu.hidePopup();
    }
    await hiddenPromise;
  }

  // With the defaults, All Address Books should open.
  // No changes should be made to the prefs.

  let abWindow = await openAddressBookWindow();
  checkDirectoryDisplayed();
  await checkMenuItem(0, true);
  await checkMenuItem(1, false);
  await checkMenuItem(2, false);
  openDirectory(personalBook);
  await closeAddressBookWindow();
  Assert.ok(!Services.prefs.prefHasUserValue(URI_PREF));

  // Now we'll set the default to "last-used".
  // The last-used book should be saved.

  abWindow = await openAddressBookWindow();
  checkDirectoryDisplayed();
  await checkMenuItem(0, true);
  await checkMenuItem(1, false);
  await checkMenuItem(2, false);
  Services.prefs.setBoolPref(DEFAULT_PREF, false);
  openDirectory(personalBook);
  await closeAddressBookWindow();
  Assert.equal(Services.prefs.getStringPref(URI_PREF), personalBook.URI);

  // The last-used book should open.

  abWindow = await openAddressBookWindow();
  checkDirectoryDisplayed(personalBook);
  await checkMenuItem(0, false);
  await checkMenuItem(1, false);
  await checkMenuItem(2, false);
  openDirectory(historyBook);
  await closeAddressBookWindow();
  Assert.equal(Services.prefs.getStringPref(URI_PREF), historyBook.URI);

  // The last-used book should open.
  // We'll set a default directory again.

  abWindow = await openAddressBookWindow();
  checkDirectoryDisplayed(historyBook);
  await checkMenuItem(0, false);
  await checkMenuItem(1, false);
  await checkMenuItem(2, false, true);
  openDirectory(personalBook);
  await closeAddressBookWindow();
  Assert.ok(Services.prefs.getBoolPref(DEFAULT_PREF));
  Assert.equal(Services.prefs.getStringPref(URI_PREF), historyBook.URI);

  // Check that the saved default opens. Change the default.

  abWindow = await openAddressBookWindow();
  checkDirectoryDisplayed(historyBook);
  await checkMenuItem(0, false);
  await checkMenuItem(2, true);
  await checkMenuItem(1, false, true);
  await closeAddressBookWindow();
  Assert.ok(Services.prefs.getBoolPref(DEFAULT_PREF));
  Assert.equal(Services.prefs.getStringPref(URI_PREF), personalBook.URI);

  // Check that the saved default opens. Change the default to All Address Books.

  abWindow = await openAddressBookWindow();
  checkDirectoryDisplayed(personalBook);
  await checkMenuItem(1, true);
  await checkMenuItem(2, false);
  await checkMenuItem(0, false, true);
  await closeAddressBookWindow();
  Assert.ok(Services.prefs.getBoolPref(DEFAULT_PREF));
  Assert.ok(!Services.prefs.prefHasUserValue(URI_PREF));

  // Check that the saved default opens. Clear the default.

  abWindow = await openAddressBookWindow();
  checkDirectoryDisplayed();
  await checkMenuItem(1, false);
  await checkMenuItem(2, false);
  await checkMenuItem(0, true, true);
  await closeAddressBookWindow();
  Assert.ok(!Services.prefs.getBoolPref(DEFAULT_PREF));
  Assert.ok(!Services.prefs.prefHasUserValue(URI_PREF));
});

add_task(async function test_total_address_book_count() {
  let book1 = createAddressBook("First Book");
  let book2 = createAddressBook("Second Book");
  book1.addMailList(createMailingList("Ordinary List"));

  book1.addCard(createContact("contact1", "book 1"));
  book1.addCard(createContact("contact2", "book 1"));
  book1.addCard(createContact("contact3", "book 1"));

  book2.addCard(createContact("contact1", "book 2"));

  let abWindow = await openAddressBookWindow();
  let abDocument = abWindow.document;
  let booksList = abWindow.booksList;
  let cardCount = abDocument.getElementById("cardCount");

  await openAllAddressBooks();
  Assert.deepEqual(abDocument.l10n.getAttributes(cardCount), {
    id: "about-addressbook-card-count-all",
    args: {
      count: 5,
    },
  });

  for (let [index, [name, count]] of [
    ["Personal Address Book", 0],
    ["First Book", 4],
    ["Ordinary List", 0],
    ["Second Book", 1],
  ].entries()) {
    booksList.getRowAtIndex(index + 1).click();
    Assert.deepEqual(abDocument.l10n.getAttributes(cardCount), {
      id: "about-addressbook-card-count",
      args: { name, count },
    });
  }

  // Create a contact and check that the count updates.
  // Select second book.
  booksList.getRowAtIndex(4).click();
  let createdPromise = TestUtils.topicObserved("addrbook-contact-created");
  book2.addCard(createContact("contact2", "book 2"));
  await createdPromise;
  Assert.deepEqual(
    abDocument.l10n.getAttributes(cardCount),
    {
      id: "about-addressbook-card-count",
      args: { name: "Second Book", count: 2 },
    },
    "Address Book count is updated on contact creation."
  );

  // Delete a contact an check that the count updates.
  let promptPromise = BrowserTestUtils.promiseAlertDialog("accept");
  let deletedPromise = TestUtils.topicObserved("addrbook-contact-deleted");
  let cards = abWindow.cardsPane.cardsList;
  EventUtils.synthesizeMouseAtCenter(cards.getRowAtIndex(0), {}, abWindow);
  EventUtils.synthesizeKey("VK_DELETE", {}, abWindow);
  await promptPromise;
  await deletedPromise;
  Assert.deepEqual(
    abDocument.l10n.getAttributes(cardCount),
    {
      id: "about-addressbook-card-count",
      args: { name: "Second Book", count: 1 },
    },
    "Address Book count is updated on contact deletion."
  );

  await closeAddressBookWindow();
  await promiseDirectoryRemoved(book1.URI);
  await promiseDirectoryRemoved(book2.URI);
});