summaryrefslogtreecommitdiffstats
path: root/browser/base/content/test/pageActions/browser_page_action_menu.js
blob: deb5dacee8855bcca5578f0b7af71dab02a8401f (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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
"use strict";

const { sinon } = ChromeUtils.import("resource://testing-common/Sinon.jsm");
/* global UIState */

const lastModifiedFixture = 1507655615.87; // Approx Oct 10th 2017
const mockTargets = [
  {
    id: "0",
    name: "foo",
    type: "phone",
    clientRecord: {
      id: "cli0",
      serverLastModified: lastModifiedFixture,
      type: "phone",
    },
  },
  {
    id: "1",
    name: "bar",
    type: "desktop",
    clientRecord: {
      id: "cli1",
      serverLastModified: lastModifiedFixture,
      type: "desktop",
    },
  },
  {
    id: "2",
    name: "baz",
    type: "phone",
    clientRecord: {
      id: "cli2",
      serverLastModified: lastModifiedFixture,
      type: "phone",
    },
  },
  { id: "3", name: "no client record device", type: "phone" },
];

add_task(async function openPanel() {
  if (AppConstants.platform == "macosx") {
    // Ignore this test on Mac.
    return;
  }

  let url = "http://example.com/";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Should still open the panel when Ctrl key is pressed.
    await promisePageActionPanelOpen({ ctrlKey: true });

    // Done.
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;
  });
});

add_task(async function starButtonCtrlClick() {
  // On macOS, ctrl-click shouldn't open the panel because this normally opens
  // the context menu. This happens via the `contextmenu` event which is created
  // by widget code, so our simulated clicks do not do so, so we can't test
  // anything on macOS.
  if (AppConstants.platform == "macosx") {
    return;
  }

  // Open a unique page.
  let url = "http://example.com/browser_page_action_star_button";
  await BrowserTestUtils.withNewTab(url, async () => {
    StarUI._createPanelIfNeeded();
    // The button ignores activation while the bookmarked status is being
    // updated. So, wait for it to finish updating.
    await TestUtils.waitForCondition(
      () => BookmarkingUI.status != BookmarkingUI.STATUS_UPDATING
    );

    const popup = document.getElementById("editBookmarkPanel");
    const starButtonBox = document.getElementById("star-button-box");

    let shownPromise = promisePanelShown(popup);
    EventUtils.synthesizeMouseAtCenter(starButtonBox, { ctrlKey: true });
    await shownPromise;
    ok(true, "Panel shown after button pressed");

    let hiddenPromise = promisePanelHidden(popup);
    document.getElementById("editBookmarkPanelRemoveButton").click();
    await hiddenPromise;
  });
});

add_task(async function bookmark() {
  // Open a unique page.
  let url = "http://example.com/browser_page_action_menu";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Open the panel.
    await promisePageActionPanelOpen();

    // The bookmark button should read "Bookmark This Page" and not be starred.
    let bookmarkButton = document.getElementById("pageAction-panel-bookmark");
    Assert.equal(bookmarkButton.label, "Bookmark This Page");
    Assert.ok(!bookmarkButton.hasAttribute("starred"));

    // Click the button.
    let hiddenPromise = promisePageActionPanelHidden();
    EventUtils.synthesizeMouseAtCenter(bookmarkButton, {});
    await hiddenPromise;

    // Make sure the edit-bookmark panel opens, then hide it.
    await new Promise(resolve => {
      if (StarUI.panel.state == "open") {
        resolve();
        return;
      }
      StarUI.panel.addEventListener("popupshown", resolve, { once: true });
    });
    Assert.equal(
      BookmarkingUI.starBox.getAttribute("open"),
      "true",
      "Star has open attribute"
    );
    StarUI.panel.hidePopup();
    Assert.ok(
      !BookmarkingUI.starBox.hasAttribute("open"),
      "Star no longer has open attribute"
    );

    // Open the panel again.
    await promisePageActionPanelOpen();

    // The bookmark button should now read "Edit This Bookmark" and be starred.
    Assert.equal(bookmarkButton.label, "Edit This Bookmark");
    Assert.ok(bookmarkButton.hasAttribute("starred"));
    Assert.equal(bookmarkButton.getAttribute("starred"), "true");

    // Click it again.
    hiddenPromise = promisePageActionPanelHidden();
    EventUtils.synthesizeMouseAtCenter(bookmarkButton, {});
    await hiddenPromise;

    // The edit-bookmark panel should open again.
    await new Promise(resolve => {
      if (StarUI.panel.state == "open") {
        resolve();
        return;
      }
      StarUI.panel.addEventListener("popupshown", resolve, { once: true });
    });

    let onItemRemovedPromise = PlacesTestUtils.waitForNotification(
      "bookmark-removed",
      events => events.some(event => event.url == url),
      "places"
    );

    // Click the remove-bookmark button in the panel.
    StarUI._element("editBookmarkPanelRemoveButton").click();

    // Wait for the bookmark to be removed before continuing.
    await onItemRemovedPromise;

    // Open the panel again.
    await promisePageActionPanelOpen();

    // The bookmark button should read "Bookmark This Page" and not be starred.
    Assert.equal(bookmarkButton.label, "Bookmark This Page");
    Assert.ok(!bookmarkButton.hasAttribute("starred"));

    // Done.
    hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;
  });
});

add_task(async function pinTabFromPanel() {
  // Open an actionable page so that the main page action button appears.  (It
  // does not appear on about:blank for example.)
  let url = "http://example.com/";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Open the panel and click Pin Tab.
    await promisePageActionPanelOpen();

    let pinTabButton = document.getElementById("pageAction-panel-pinTab");
    Assert.equal(pinTabButton.label, "Pin Tab");
    let hiddenPromise = promisePageActionPanelHidden();
    EventUtils.synthesizeMouseAtCenter(pinTabButton, {});
    await hiddenPromise;

    Assert.ok(gBrowser.selectedTab.pinned, "Tab was pinned");

    // Open the panel and click Unpin Tab.
    await promisePageActionPanelOpen();
    Assert.equal(pinTabButton.label, "Unpin Tab");

    hiddenPromise = promisePageActionPanelHidden();
    EventUtils.synthesizeMouseAtCenter(pinTabButton, {});
    await hiddenPromise;

    Assert.ok(!gBrowser.selectedTab.pinned, "Tab was unpinned");
  });
});

add_task(async function pinTabFromURLBar() {
  // Open an actionable page so that the main page action button appears.  (It
  // does not appear on about:blank for example.)
  let url = "http://example.com/";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Add action to URL bar.
    let action = PageActions._builtInActions.find(a => a.id == "pinTab");
    action.pinnedToUrlbar = true;
    registerCleanupFunction(() => (action.pinnedToUrlbar = false));

    // Click the Pin Tab button.
    let pinTabButton = document.getElementById("pageAction-urlbar-pinTab");
    EventUtils.synthesizeMouseAtCenter(pinTabButton, {});
    await TestUtils.waitForCondition(
      () => gBrowser.selectedTab.pinned,
      "Tab was pinned"
    );

    // Click the Unpin Tab button
    EventUtils.synthesizeMouseAtCenter(pinTabButton, {});
    await TestUtils.waitForCondition(
      () => !gBrowser.selectedTab.pinned,
      "Tab was unpinned"
    );
  });
});

add_task(async function emailLink() {
  // Open an actionable page so that the main page action button appears.  (It
  // does not appear on about:blank for example.)
  let url = "http://example.com/";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Replace the email-link entry point to check whether it's called.
    let originalFn = MailIntegration.sendLinkForBrowser;
    let fnCalled = false;
    MailIntegration.sendLinkForBrowser = () => {
      fnCalled = true;
    };
    registerCleanupFunction(() => {
      MailIntegration.sendLinkForBrowser = originalFn;
    });

    // Open the panel and click Email Link.
    await promisePageActionPanelOpen();
    let emailLinkButton = document.getElementById("pageAction-panel-emailLink");
    let hiddenPromise = promisePageActionPanelHidden();
    EventUtils.synthesizeMouseAtCenter(emailLinkButton, {});
    await hiddenPromise;

    Assert.ok(fnCalled);
  });
});

add_task(async function copyURLFromPanel() {
  // Open an actionable page so that the main page action button appears.  (It
  // does not appear on about:blank for example.)
  let url = "http://example.com/";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Add action to URL bar.
    let action = PageActions._builtInActions.find(a => a.id == "copyURL");
    action.pinnedToUrlbar = true;
    registerCleanupFunction(() => (action.pinnedToUrlbar = false));

    // Open the panel and click Copy URL.
    await promisePageActionPanelOpen();
    Assert.ok(true, "page action panel opened");

    let copyURLButton = document.getElementById("pageAction-panel-copyURL");
    let hiddenPromise = promisePageActionPanelHidden();
    EventUtils.synthesizeMouseAtCenter(copyURLButton, {});
    await hiddenPromise;

    let feedbackPanel = ConfirmationHint._panel;
    let feedbackShownPromise = BrowserTestUtils.waitForEvent(
      feedbackPanel,
      "popupshown"
    );
    await feedbackShownPromise;
    Assert.equal(
      feedbackPanel.anchorNode.id,
      "pageActionButton",
      "Feedback menu should be anchored on the main Page Action button"
    );
    let feedbackHiddenPromise = promisePanelHidden(feedbackPanel);
    await feedbackHiddenPromise;

    action.pinnedToUrlbar = false;
  });
});

add_task(async function copyURLFromURLBar() {
  // Open an actionable page so that the main page action button appears.  (It
  // does not appear on about:blank for example.)
  let url = "http://example.com/";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Add action to URL bar.
    let action = PageActions._builtInActions.find(a => a.id == "copyURL");
    action.pinnedToUrlbar = true;
    registerCleanupFunction(() => (action.pinnedToUrlbar = false));

    let copyURLButton = document.getElementById("pageAction-urlbar-copyURL");
    let panel = ConfirmationHint._panel;
    let feedbackShownPromise = promisePanelShown(panel);
    EventUtils.synthesizeMouseAtCenter(copyURLButton, {});

    await feedbackShownPromise;
    Assert.equal(
      panel.anchorNode.id,
      "pageAction-urlbar-copyURL",
      "Feedback menu should be anchored on the main URL bar button"
    );
    let feedbackHiddenPromise = promisePanelHidden(panel);
    await feedbackHiddenPromise;

    action.pinnedToUrlbar = false;
  });
});

add_task(async function sendToDevice_nonSendable() {
  // Open a tab that's not sendable but where the page action buttons still
  // appear.  about:about is convenient.
  await BrowserTestUtils.withNewTab("about:about", async () => {
    await promiseSyncReady();
    // Open the panel.  Send to Device should be disabled.
    await promisePageActionPanelOpen();
    Assert.equal(
      BrowserPageActions.mainButtonNode.getAttribute("open"),
      "true",
      "Main button has 'open' attribute"
    );
    let panelButton = BrowserPageActions.panelButtonNodeForActionID(
      "sendToDevice"
    );
    Assert.equal(
      panelButton.disabled,
      true,
      "The panel button should be disabled"
    );
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;
    Assert.ok(
      !BrowserPageActions.mainButtonNode.hasAttribute("open"),
      "Main button no longer has 'open' attribute"
    );
    // The urlbar button shouldn't exist.
    let urlbarButton = BrowserPageActions.urlbarButtonNodeForActionID(
      "sendToDevice"
    );
    Assert.equal(urlbarButton, null, "The urlbar button shouldn't exist");
  });
});

add_task(async function sendToDevice_syncNotReady_other_states() {
  // Open a tab that's sendable.
  await BrowserTestUtils.withNewTab("http://example.com/", async () => {
    await promiseSyncReady();
    const sandbox = sinon.createSandbox();
    sandbox.stub(fxAccounts.device, "recentDeviceList").get(() => null);
    sandbox
      .stub(UIState, "get")
      .returns({ status: UIState.STATUS_NOT_VERIFIED });
    sandbox.stub(gSync, "isSendableURI").returns(true);

    let cleanUp = () => {
      sandbox.restore();
    };
    registerCleanupFunction(cleanUp);

    // Open the panel.
    await promisePageActionPanelOpen();
    let sendToDeviceButton = document.getElementById(
      "pageAction-panel-sendToDevice"
    );
    Assert.ok(!sendToDeviceButton.disabled);

    // Click Send to Device.
    let viewPromise = promisePageActionViewShown();
    EventUtils.synthesizeMouseAtCenter(sendToDeviceButton, {});
    let view = await viewPromise;
    Assert.equal(view.id, "pageAction-panel-sendToDevice-subview");

    let expectedItems = [
      {
        className: "pageAction-sendToDevice-notReady",
        display: "none",
        disabled: true,
      },
      {
        attrs: {
          label: "Account Not Verified",
        },
        disabled: true,
      },
      null,
      {
        attrs: {
          label: "Verify Your Account...",
        },
      },
    ];
    checkSendToDeviceItems(expectedItems);

    // Done, hide the panel.
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;

    cleanUp();
  });
});

add_task(async function sendToDevice_syncNotReady_configured() {
  // Open a tab that's sendable.
  await BrowserTestUtils.withNewTab("http://example.com/", async () => {
    await promiseSyncReady();
    const sandbox = sinon.createSandbox();
    const recentDeviceList = sandbox
      .stub(fxAccounts.device, "recentDeviceList")
      .get(() => null);
    sandbox.stub(UIState, "get").returns({ status: UIState.STATUS_SIGNED_IN });
    sandbox.stub(gSync, "isSendableURI").returns(true);

    sandbox.stub(fxAccounts.device, "refreshDeviceList").callsFake(() => {
      recentDeviceList.get(() =>
        mockTargets.map(({ id, name, type }) => ({ id, name, type }))
      );
      sandbox
        .stub(Weave.Service.clientsEngine, "getClientByFxaDeviceId")
        .callsFake(fxaDeviceId => {
          let target = mockTargets.find(c => c.id == fxaDeviceId);
          return target ? target.clientRecord : null;
        });
      sandbox
        .stub(Weave.Service.clientsEngine, "getClientType")
        .callsFake(
          id =>
            mockTargets.find(c => c.clientRecord && c.clientRecord.id == id)
              .clientRecord.type
        );
    });

    let onShowingSubview = BrowserPageActions.sendToDevice.onShowingSubview;
    sandbox
      .stub(BrowserPageActions.sendToDevice, "onShowingSubview")
      .callsFake((...args) => {
        this.numCall++ || (this.numCall = 1);
        onShowingSubview.call(BrowserPageActions.sendToDevice, ...args);
        testSendTabToDeviceMenu(this.numCall);
      });

    let cleanUp = () => {
      sandbox.restore();
    };
    registerCleanupFunction(cleanUp);

    // Open the panel.
    await promisePageActionPanelOpen();
    let sendToDeviceButton = document.getElementById(
      "pageAction-panel-sendToDevice"
    );
    Assert.ok(!sendToDeviceButton.disabled);

    // Click Send to Device.
    let viewPromise = promisePageActionViewShown();
    EventUtils.synthesizeMouseAtCenter(sendToDeviceButton, {});
    let view = await viewPromise;
    Assert.equal(view.id, "pageAction-panel-sendToDevice-subview");

    function testSendTabToDeviceMenu(numCall) {
      if (numCall == 1) {
        // "Syncing devices" should be shown.
        checkSendToDeviceItems([
          {
            className: "pageAction-sendToDevice-notReady",
            disabled: true,
          },
        ]);
      } else if (numCall == 2) {
        // The devices should be shown in the subview.
        let expectedItems = [
          {
            className: "pageAction-sendToDevice-notReady",
            display: "none",
            disabled: true,
          },
        ];
        for (let target of mockTargets) {
          const attrs = {
            clientId: target.id,
            label: target.name,
            clientType: target.type,
          };
          if (target.clientRecord && target.clientRecord.serverLastModified) {
            attrs.tooltiptext = gSync.formatLastSyncDate(
              new Date(target.clientRecord.serverLastModified * 1000)
            );
          }
          expectedItems.push({
            attrs,
          });
        }
        expectedItems.push(null, {
          attrs: {
            label: "Send to All Devices",
          },
        });
        expectedItems.push(null, {
          attrs: {
            label: "Manage Devices...",
          },
        });
        checkSendToDeviceItems(expectedItems);
      } else {
        ok(false, "This should never happen");
      }
    }

    // Done, hide the panel.
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;
    cleanUp();
  });
});

add_task(async function sendToDevice_notSignedIn() {
  // Open a tab that's sendable.
  await BrowserTestUtils.withNewTab("http://example.com/", async () => {
    await promiseSyncReady();

    // Open the panel.
    await promisePageActionPanelOpen();
    let sendToDeviceButton = document.getElementById(
      "pageAction-panel-sendToDevice"
    );
    Assert.ok(!sendToDeviceButton.disabled);

    // Click Send to Device.
    let viewPromise = promisePageActionViewShown();
    EventUtils.synthesizeMouseAtCenter(sendToDeviceButton, {});
    let view = await viewPromise;
    Assert.equal(view.id, "pageAction-panel-sendToDevice-subview");

    let expectedItems = [
      {
        className: "pageAction-sendToDevice-notReady",
        display: "none",
        disabled: true,
      },
      {
        attrs: {
          label: "Not Signed In",
        },
        disabled: true,
      },
      null,
      {
        attrs: {
          label: "Sign in to Firefox...",
        },
      },
      {
        attrs: {
          label: "Learn About Sending Tabs...",
        },
      },
    ];
    checkSendToDeviceItems(expectedItems);

    // Done, hide the panel.
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;
  });
});

add_task(async function sendToDevice_noDevices() {
  // Open a tab that's sendable.
  await BrowserTestUtils.withNewTab("http://example.com/", async () => {
    await promiseSyncReady();
    const sandbox = sinon.createSandbox();
    sandbox.stub(fxAccounts.device, "recentDeviceList").get(() => []);
    sandbox.stub(UIState, "get").returns({ status: UIState.STATUS_SIGNED_IN });
    sandbox.stub(gSync, "isSendableURI").returns(true);
    sandbox.stub(fxAccounts.device, "refreshDeviceList").resolves(true);
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientByFxaDeviceId")
      .callsFake(fxaDeviceId => {
        let target = mockTargets.find(c => c.id == fxaDeviceId);
        return target ? target.clientRecord : null;
      });
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientType")
      .callsFake(
        id =>
          mockTargets.find(c => c.clientRecord && c.clientRecord.id == id)
            .clientRecord.type
      );

    let cleanUp = () => {
      sandbox.restore();
    };
    registerCleanupFunction(cleanUp);

    // Open the panel.
    await promisePageActionPanelOpen();
    let sendToDeviceButton = document.getElementById(
      "pageAction-panel-sendToDevice"
    );
    Assert.ok(!sendToDeviceButton.disabled);

    // Click Send to Device.
    let viewPromise = promisePageActionViewShown();
    EventUtils.synthesizeMouseAtCenter(sendToDeviceButton, {});
    let view = await viewPromise;
    Assert.equal(view.id, "pageAction-panel-sendToDevice-subview");

    let expectedItems = [
      {
        className: "pageAction-sendToDevice-notReady",
        display: "none",
        disabled: true,
      },
      {
        attrs: {
          label: "No Devices Connected",
        },
        disabled: true,
      },
      null,
      {
        attrs: {
          label: "Connect Another Device...",
        },
      },
      {
        attrs: {
          label: "Learn About Sending Tabs...",
        },
      },
    ];
    checkSendToDeviceItems(expectedItems);

    // Done, hide the panel.
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;

    cleanUp();

    await UIState.reset();
  });
});

add_task(async function sendToDevice_devices() {
  // Open a tab that's sendable.
  await BrowserTestUtils.withNewTab("http://example.com/", async () => {
    await promiseSyncReady();
    const sandbox = sinon.createSandbox();
    sandbox
      .stub(fxAccounts.device, "recentDeviceList")
      .get(() => mockTargets.map(({ id, name, type }) => ({ id, name, type })));
    sandbox.stub(UIState, "get").returns({ status: UIState.STATUS_SIGNED_IN });
    sandbox.stub(gSync, "isSendableURI").returns(true);
    sandbox
      .stub(fxAccounts.commands.sendTab, "isDeviceCompatible")
      .returns(true);
    sandbox.stub(fxAccounts.device, "refreshDeviceList").resolves(true);
    sandbox.spy(Weave.Service, "sync");
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientByFxaDeviceId")
      .callsFake(fxaDeviceId => {
        let target = mockTargets.find(c => c.id == fxaDeviceId);
        return target ? target.clientRecord : null;
      });
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientType")
      .callsFake(
        id =>
          mockTargets.find(c => c.clientRecord && c.clientRecord.id == id)
            .clientRecord.type
      );

    let cleanUp = () => {
      sandbox.restore();
    };
    registerCleanupFunction(cleanUp);

    // Open the panel.
    await promisePageActionPanelOpen();
    let sendToDeviceButton = document.getElementById(
      "pageAction-panel-sendToDevice"
    );
    Assert.ok(!sendToDeviceButton.disabled);

    // Click Send to Device.
    let viewPromise = promisePageActionViewShown();
    EventUtils.synthesizeMouseAtCenter(sendToDeviceButton, {});
    let view = await viewPromise;
    Assert.equal(view.id, "pageAction-panel-sendToDevice-subview");

    // The devices should be shown in the subview.
    let expectedItems = [
      {
        className: "pageAction-sendToDevice-notReady",
        display: "none",
        disabled: true,
      },
      {
        attrs: {
          clientId: "1",
          label: "bar",
          clientType: "desktop",
        },
      },
      {
        attrs: {
          clientId: "2",
          label: "baz",
          clientType: "phone",
        },
      },
      {
        attrs: {
          clientId: "0",
          label: "foo",
          clientType: "phone",
        },
      },
      {
        attrs: {
          clientId: "3",
          label: "no client record device",
          clientType: "phone",
        },
      },
      null,
      {
        attrs: {
          label: "Send to All Devices",
        },
      },
      {
        attrs: {
          label: "Manage Devices...",
        },
      },
    ];
    checkSendToDeviceItems(expectedItems);

    Assert.ok(Weave.Service.sync.notCalled);

    // Done, hide the panel.
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;

    cleanUp();
  });
});

add_task(async function sendTabToDevice_syncEnabled() {
  // Open a tab that's sendable.
  await BrowserTestUtils.withNewTab("http://example.com/", async () => {
    await promiseSyncReady();
    const sandbox = sinon.createSandbox();
    sandbox.stub(fxAccounts.device, "recentDeviceList").get(() => []);
    sandbox
      .stub(UIState, "get")
      .returns({ status: UIState.STATUS_SIGNED_IN, syncEnabled: true });
    sandbox.stub(gSync, "isSendableURI").returns(true);
    sandbox.spy(fxAccounts.device, "refreshDeviceList");
    sandbox.spy(Weave.Service, "sync");
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientByFxaDeviceId")
      .callsFake(fxaDeviceId => {
        let target = mockTargets.find(c => c.id == fxaDeviceId);
        return target ? target.clientRecord : null;
      });
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientType")
      .callsFake(
        id =>
          mockTargets.find(c => c.clientRecord && c.clientRecord.id == id)
            .clientRecord.type
      );

    let cleanUp = () => {
      sandbox.restore();
    };
    registerCleanupFunction(cleanUp);

    // Open the panel.
    await promisePageActionPanelOpen();
    let sendToDeviceButton = document.getElementById(
      "pageAction-panel-sendToDevice"
    );
    Assert.ok(!sendToDeviceButton.disabled);

    // Click Send to Device.
    let viewPromise = promisePageActionViewShown();
    EventUtils.synthesizeMouseAtCenter(sendToDeviceButton, {});
    let view = await viewPromise;
    Assert.equal(view.id, "pageAction-panel-sendToDevice-subview");

    let expectedItems = [
      {
        className: "pageAction-sendToDevice-notReady",
        display: "none",
        disabled: true,
      },
      {
        attrs: {
          label: "No Devices Connected",
        },
        disabled: true,
      },
      null,
      {
        attrs: {
          label: "Connect Another Device...",
        },
      },
      {
        attrs: {
          label: "Learn About Sending Tabs...",
        },
      },
    ];
    checkSendToDeviceItems(expectedItems);

    Assert.ok(Weave.Service.sync.notCalled);
    Assert.equal(fxAccounts.device.refreshDeviceList.callCount, 1);

    // Done, hide the panel.
    let hiddenPromise = promisePageActionPanelHidden();
    BrowserPageActions.panelNode.hidePopup();
    await hiddenPromise;

    cleanUp();
  });
});

add_task(async function sendToDevice_title() {
  // Open two tabs that are sendable.
  await BrowserTestUtils.withNewTab(
    "http://example.com/a",
    async otherBrowser => {
      await BrowserTestUtils.withNewTab("http://example.com/b", async () => {
        await promiseSyncReady();
        const sandbox = sinon.createSandbox();
        sandbox.stub(fxAccounts.device, "recentDeviceList").get(() => []);
        sandbox
          .stub(UIState, "get")
          .returns({ status: UIState.STATUS_SIGNED_IN });
        sandbox.stub(gSync, "isSendableURI").returns(true);
        sandbox.stub(fxAccounts.device, "refreshDeviceList").resolves(true);
        sandbox
          .stub(Weave.Service.clientsEngine, "getClientByFxaDeviceId")
          .callsFake(fxaDeviceId => {
            let target = mockTargets.find(c => c.id == fxaDeviceId);
            return target ? target.clientRecord : null;
          });
        sandbox
          .stub(Weave.Service.clientsEngine, "getClientType")
          .callsFake(
            id =>
              mockTargets.find(c => c.clientRecord && c.clientRecord.id == id)
                .clientRecord.type
          );

        let cleanUp = () => {
          sandbox.restore();
        };
        registerCleanupFunction(cleanUp);

        // Open the panel.  Only one tab is selected, so the action's title should
        // be "Send Tab to Device".
        await promisePageActionPanelOpen();
        let sendToDeviceButton = document.getElementById(
          "pageAction-panel-sendToDevice"
        );
        Assert.ok(!sendToDeviceButton.disabled);

        Assert.equal(sendToDeviceButton.label, "Send Tab to Device");

        // Hide the panel.
        let hiddenPromise = promisePageActionPanelHidden();
        BrowserPageActions.panelNode.hidePopup();
        await hiddenPromise;

        // Add the other tab to the selection.
        gBrowser.addToMultiSelectedTabs(
          gBrowser.getTabForBrowser(otherBrowser),
          { isLastMultiSelectChange: true }
        );

        // Open the panel again.  Now the action's title should be "Send 2 Tabs to
        // Device".
        await promisePageActionPanelOpen();
        Assert.ok(!sendToDeviceButton.disabled);
        Assert.equal(sendToDeviceButton.label, "Send 2 Tabs to Device");

        // Hide the panel.
        hiddenPromise = promisePageActionPanelHidden();
        BrowserPageActions.panelNode.hidePopup();
        await hiddenPromise;

        cleanUp();

        await UIState.reset();
      });
    }
  );
});

add_task(async function sendToDevice_inUrlbar() {
  // Open a tab that's sendable.
  await BrowserTestUtils.withNewTab("http://example.com/", async () => {
    await promiseSyncReady();
    const sandbox = sinon.createSandbox();
    sandbox
      .stub(fxAccounts.device, "recentDeviceList")
      .get(() => mockTargets.map(({ id, name, type }) => ({ id, name, type })));
    sandbox.stub(UIState, "get").returns({ status: UIState.STATUS_SIGNED_IN });
    sandbox.stub(gSync, "isSendableURI").returns(true);
    sandbox
      .stub(fxAccounts.commands.sendTab, "isDeviceCompatible")
      .returns(true);
    sandbox.stub(fxAccounts.device, "refreshDeviceList").resolves(true);
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientByFxaDeviceId")
      .callsFake(fxaDeviceId => {
        let target = mockTargets.find(c => c.id == fxaDeviceId);
        return target ? target.clientRecord : null;
      });
    sandbox
      .stub(Weave.Service.clientsEngine, "getClientType")
      .callsFake(
        id =>
          mockTargets.find(c => c.clientRecord && c.clientRecord.id == id)
            .clientRecord.type
      );
    sandbox.stub(gSync, "sendTabToDevice").resolves(true);

    let cleanUp = () => {
      sandbox.restore();
    };
    registerCleanupFunction(cleanUp);

    // Add Send to Device to the urlbar.
    let action = PageActions.actionForID("sendToDevice");
    action.pinnedToUrlbar = true;

    // Click it to open its panel.
    let urlbarButton = document.getElementById(
      BrowserPageActions.urlbarButtonNodeIDForActionID(action.id)
    );
    Assert.notEqual(urlbarButton, null, "The urlbar button should exist");
    Assert.ok(
      !urlbarButton.disabled,
      "The urlbar button should not be disabled"
    );
    EventUtils.synthesizeMouseAtCenter(urlbarButton, {});
    // The panel element for _activatedActionPanelID is created synchronously
    // only after the associated button has been clicked.
    await promisePanelShown(BrowserPageActions._activatedActionPanelID);
    Assert.equal(
      urlbarButton.getAttribute("open"),
      "true",
      "Button has open attribute"
    );

    // The devices should be shown in the subview.
    let expectedItems = [
      {
        className: "pageAction-sendToDevice-notReady",
        display: "none",
        disabled: true,
      },
      {
        attrs: {
          clientId: "1",
          label: "bar",
          clientType: "desktop",
        },
      },
      {
        attrs: {
          clientId: "2",
          label: "baz",
          clientType: "phone",
        },
      },
      {
        attrs: {
          clientId: "0",
          label: "foo",
          clientType: "phone",
        },
      },
      {
        attrs: {
          clientId: "3",
          label: "no client record device",
          clientType: "phone",
        },
      },
      null,
      {
        attrs: {
          label: "Send to All Devices",
        },
      },
      {
        attrs: {
          label: "Manage Devices...",
        },
      },
    ];
    checkSendToDeviceItems(expectedItems, true);

    // Get the first device menu item in the panel.
    let bodyID =
      BrowserPageActions._panelViewNodeIDForActionID("sendToDevice", true) +
      "-body";
    let body = document.getElementById(bodyID);
    let deviceMenuItem = body.querySelector(".sendtab-target");
    Assert.notEqual(deviceMenuItem, null);

    // For good measure, wait until it's visible.
    let dwu = window.windowUtils;
    await TestUtils.waitForCondition(() => {
      let bounds = dwu.getBoundsWithoutFlushing(deviceMenuItem);
      return bounds.height > 0 && bounds.width > 0;
    }, "Waiting for first device menu item to appear");

    // Click it, which should cause the panel to close.
    let hiddenPromise = promisePanelHidden(
      BrowserPageActions._activatedActionPanelID
    );
    EventUtils.synthesizeMouseAtCenter(deviceMenuItem, {});
    info("Waiting for Send to Device panel to close after clicking a device");
    await hiddenPromise;
    Assert.ok(
      !urlbarButton.hasAttribute("open"),
      "URL bar button no longer has open attribute"
    );

    // And then the "Sent!" notification panel should open and close by itself
    // after a moment.
    info("Waiting for the Sent! notification panel to open");
    await promisePanelShown(ConfirmationHint._panel.id);
    Assert.equal(ConfirmationHint._panel.anchorNode.id, urlbarButton.id);
    info("Waiting for the Sent! notification panel to close");
    await promisePanelHidden(ConfirmationHint._panel.id);

    // Remove Send to Device from the urlbar.
    action.pinnedToUrlbar = false;

    cleanUp();
  });
});

add_task(async function contextMenu() {
  // Open an actionable page so that the main page action button appears.
  let url = "http://example.com/";
  await BrowserTestUtils.withNewTab(url, async () => {
    // Open the panel and then open the context menu on the bookmark button.
    await promisePageActionPanelOpen();
    let bookmarkButton = document.getElementById("pageAction-panel-bookmark");
    let contextMenuPromise = promisePanelShown("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(bookmarkButton, {
      type: "contextmenu",
      button: 2,
    });
    await contextMenuPromise;

    // The context menu should show the "remove" item.  Click it.
    let menuItems = collectContextMenuItems();
    Assert.equal(menuItems.length, 1, "Context menu has one child");
    Assert.equal(
      menuItems[0].label,
      "Remove from Address Bar",
      "Context menu is in the 'remove' state"
    );
    contextMenuPromise = promisePanelHidden("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(menuItems[0], {});
    await contextMenuPromise;

    // The action should be removed from the urlbar.  In this case, the bookmark
    // star, the node in the urlbar should be hidden.
    let starButtonBox = document.getElementById("star-button-box");
    await TestUtils.waitForCondition(() => {
      return starButtonBox.hidden;
    }, "Waiting for star button to become hidden");

    // Open the context menu again on the bookmark button.  (The page action
    // panel remains open.)
    contextMenuPromise = promisePanelShown("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(bookmarkButton, {
      type: "contextmenu",
      button: 2,
    });
    await contextMenuPromise;

    // The context menu should show the "add" item.  Click it.
    menuItems = collectContextMenuItems();
    Assert.equal(menuItems.length, 1, "Context menu has one child");
    Assert.equal(
      menuItems[0].label,
      "Add to Address Bar",
      "Context menu is in the 'add' state"
    );
    contextMenuPromise = promisePanelHidden("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(menuItems[0], {});
    await contextMenuPromise;

    // The action should be added to the urlbar.
    await TestUtils.waitForCondition(() => {
      return !starButtonBox.hidden;
    }, "Waiting for star button to become unhidden");

    // Open the context menu on the bookmark star in the urlbar.
    contextMenuPromise = promisePanelShown("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(starButtonBox, {
      type: "contextmenu",
      button: 2,
    });
    await contextMenuPromise;

    // The context menu should show the "remove" item.  Click it.
    menuItems = collectContextMenuItems();
    Assert.equal(menuItems.length, 1, "Context menu has one child");
    Assert.equal(
      menuItems[0].label,
      "Remove from Address Bar",
      "Context menu is in the 'remove' state"
    );
    contextMenuPromise = promisePanelHidden("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(menuItems[0], {});
    await contextMenuPromise;

    // The action should be removed from the urlbar.
    await TestUtils.waitForCondition(() => {
      return starButtonBox.hidden;
    }, "Waiting for star button to become hidden");

    // Finally, add the bookmark star back to the urlbar so that other tests
    // that rely on it are OK.
    await promisePageActionPanelOpen();
    contextMenuPromise = promisePanelShown("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(bookmarkButton, {
      type: "contextmenu",
      button: 2,
    });
    await contextMenuPromise;

    menuItems = collectContextMenuItems();
    Assert.equal(menuItems.length, 1, "Context menu has one child");
    Assert.equal(
      menuItems[0].label,
      "Add to Address Bar",
      "Context menu is in the 'add' state"
    );
    contextMenuPromise = promisePanelHidden("pageActionContextMenu");
    EventUtils.synthesizeMouseAtCenter(menuItems[0], {});
    await contextMenuPromise;
    await TestUtils.waitForCondition(() => {
      return !starButtonBox.hidden;
    }, "Waiting for star button to become unhidden");
  });

  // urlbar tests that run after this one can break if the mouse is left over
  // the area where the urlbar popup appears, which seems to happen due to the
  // above synthesized mouse events.  Move it over the urlbar.
  EventUtils.synthesizeMouseAtCenter(gURLBar.textbox, { type: "mousemove" });
  gURLBar.focus();
});

function promiseSyncReady() {
  let service = Cc["@mozilla.org/weave/service;1"].getService(Ci.nsISupports)
    .wrappedJSObject;
  return service.whenLoaded().then(() => {
    UIState.isReady();
    return UIState.refresh();
  });
}

function checkSendToDeviceItems(expectedItems, forUrlbar = false) {
  let bodyID =
    BrowserPageActions._panelViewNodeIDForActionID("sendToDevice", forUrlbar) +
    "-body";
  let body = document.getElementById(bodyID);
  Assert.equal(body.children.length, expectedItems.length);
  for (let i = 0; i < expectedItems.length; i++) {
    let expected = expectedItems[i];
    let actual = body.children[i];
    if (!expected) {
      Assert.equal(actual.localName, "toolbarseparator");
      continue;
    }
    if ("id" in expected) {
      Assert.equal(actual.id, expected.id);
    }
    if ("className" in expected) {
      let expectedNames = expected.className.split(/\s+/);
      for (let name of expectedNames) {
        Assert.ok(
          actual.classList.contains(name),
          `classList contains: ${name}`
        );
      }
    }
    let display = "display" in expected ? expected.display : "-moz-box";
    Assert.equal(getComputedStyle(actual).display, display);
    let disabled = "disabled" in expected ? expected.disabled : false;
    Assert.equal(actual.disabled, disabled);
    if ("attrs" in expected) {
      for (let name in expected.attrs) {
        Assert.ok(actual.hasAttribute(name));
        let attrVal = actual.getAttribute(name);
        if (name == "label") {
          attrVal = attrVal.normalize("NFKC"); // There's a bug with …
        }
        Assert.equal(attrVal, expected.attrs[name]);
      }
    }
  }
}

function collectContextMenuItems() {
  let contextMenu = document.getElementById("pageActionContextMenu");
  return Array.prototype.filter.call(contextMenu.children, node => {
    return window.getComputedStyle(node).visibility == "visible";
  });
}