summaryrefslogtreecommitdiffstats
path: root/browser/components/asrouter/tests/browser/browser_feature_callout_in_chrome.js
blob: b7169d6be7d34b658a43fa34b15b17a4ea197f39 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

const { CustomizableUITestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/CustomizableUITestUtils.sys.mjs"
);
const { DefaultBrowserCheck } = ChromeUtils.importESModule(
  "resource:///modules/BrowserGlue.sys.mjs"
);

const PDF_TEST_URL =
  "https://example.com/browser/browser/components/newtab/test/browser/file_pdf.PDF";

async function openURLInWindow(window, url) {
  const { selectedBrowser } = window.gBrowser;
  BrowserTestUtils.startLoadingURIString(selectedBrowser, url);
  await BrowserTestUtils.browserLoaded(selectedBrowser, false, url);
  return selectedBrowser;
}

async function openURLInNewTab(window, ...args) {
  return BrowserTestUtils.openNewForegroundTab(window.gBrowser, ...args);
}

const pdfMatch = sinon.match(val => {
  return (
    val?.id === "pdfJsFeatureCalloutCheck" && val?.context?.source === "open"
  );
});

const validateCalloutCustomPosition = (element, absolutePosition, doc) => {
  const browserBox = doc.querySelector("hbox#browser");
  for (let position in absolutePosition) {
    if (Object.prototype.hasOwnProperty.call(absolutePosition, position)) {
      // remove the `px` at the end of our absolute position strings
      const relativePos = parseFloat(absolutePosition[position]);
      const elPos = element.getBoundingClientRect()[position];
      const browserPos = browserBox.getBoundingClientRect()[position];

      if (position in ["top", "left"]) {
        if (elPos !== browserPos + relativePos) {
          return false;
        }
      } else if (position in ["right", "bottom"]) {
        if (elPos !== browserPos - relativePos) {
          return false;
        }
      }
    }
  }
  return true;
};

const validateCalloutRTLPosition = (element, absolutePosition) => {
  for (let position in absolutePosition) {
    if (Object.prototype.hasOwnProperty.call(absolutePosition, position)) {
      const pixels = parseFloat(absolutePosition[position]);
      if (position === "left") {
        if (element.getBoundingClientRect().right !== pixels) {
          return false;
        }
      } else if (position === "right") {
        if (element.getBoundingClientRect().left !== pixels) {
          return false;
        }
      }
    }
  }
  return true;
};

const testMessage = {
  message: {
    id: "TEST_MESSAGE",
    template: "feature_callout",
    content: {
      id: "TEST_MESSAGE",
      template: "multistage",
      backdrop: "transparent",
      transitions: false,
      screens: [
        {
          id: "TEST_MESSAGE_1",
          anchors: [
            { selector: "#PanelUI-menu-button", arrow_position: "top-end" },
          ],
          content: {
            position: "callout",
            title: {
              raw: "Test title",
            },
            subtitle: {
              raw: "Test subtitle",
            },
            primary_button: {
              label: {
                raw: "Done",
              },
              action: {
                navigate: true,
              },
            },
          },
        },
      ],
    },
    priority: 1,
    targeting: "true",
    trigger: { id: "pdfJsFeatureCalloutCheck" },
  },
};

const newtabTestMessage = {
  id: "TEST_MESSAGE",
  template: "feature_callout",
  content: {
    id: "TEST_MESSAGE",
    template: "multistage",
    backdrop: "transparent",
    transitions: false,
    disableHistoryUpdates: true,
    tour_pref_name: "browser.newtab.feature-tour",
    tour_pref_default_value: JSON.stringify({
      screen: "TEST_MESSAGE_1",
      complete: false,
    }),
    screens: [
      {
        id: "TEST_MESSAGE_1",
        anchors: [
          {
            selector: "hbox#browser",
            arrow_position: "top-end",
            absolute_position: { top: "45px", right: "55px" },
          },
        ],
        content: {
          position: "callout",
          title: "Test callout title",
          subtitle: "Test callout subtitle",
          primary_button: {
            label: "Test callout button",
          },
        },
      },
    ],
  },
  priority: 1,
  targeting: "true",
  trigger: { id: "newtabFeatureCalloutCheck" },
};

const testMessageScreenId = testMessage.message.content.screens[0].id;
const newtabTestMessageScreenId = newtabTestMessage.content.screens[0].id;

const inChaosMode = !!parseInt(Services.env.get("MOZ_CHAOSMODE"), 16);

add_setup(async function () {
  let timeoutFactor = 3;
  // Runtime increases in chaos mode on Mac.
  if (inChaosMode && AppConstants.platform === "macosx") {
    timeoutFactor = 5;
  }
  requestLongerTimeout(timeoutFactor);
});

// Test that a feature callout message can be loaded into ASRouter and displayed
// via a standard trigger. Also test that the callout can be a feature tour,
// even if its tour pref doesn't exist in Firefox. The tour pref will be created
// and cleaned up automatically. This allows a feature callout to be implemented
// entirely off-train in an experiment, without landing anything in tree.
add_task(async function triggered_feature_tour_with_custom_pref() {
  let sandbox = sinon.createSandbox();
  const TEST_MESSAGES = [
    {
      id: "TEST_FEATURE_TOUR",
      template: "feature_callout",
      content: {
        id: "TEST_FEATURE_TOUR",
        template: "multistage",
        backdrop: "transparent",
        transitions: false,
        disableHistoryUpdates: true,
        tour_pref_name: "messaging-system-action.browser.test.feature-tour",
        tour_pref_default_value: JSON.stringify({
          screen: "FEATURE_CALLOUT_1",
          complete: false,
        }),
        screens: [
          {
            id: "FEATURE_CALLOUT_1",
            anchors: [
              {
                selector: "#PanelUI-menu-button",
                arrow_position: "top-center-arrow-end",
              },
            ],
            content: {
              position: "callout",
              title: { string_id: "callout-pdfjs-edit-title" },
              subtitle: { string_id: "callout-pdfjs-edit-body-b" },
              primary_button: {
                label: { string_id: "callout-pdfjs-edit-button" },
                action: {
                  type: "SET_PREF",
                  data: {
                    pref: {
                      name: "messaging-system-action.browser.test.feature-tour",
                      value: JSON.stringify({
                        screen: "FEATURE_CALLOUT_2",
                        complete: false,
                      }),
                    },
                  },
                },
              },
              dismiss_button: {
                action: {
                  type: "MULTI_ACTION",
                  data: {
                    actions: [
                      {
                        type: "BLOCK_MESSAGE",
                        data: { id: "TEST_FEATURE_TOUR" },
                      },
                      {
                        type: "SET_PREF",
                        data: {
                          pref: {
                            name: "messaging-system-action.browser.test.feature-tour",
                          },
                        },
                      },
                    ],
                  },
                },
              },
            },
          },
          {
            id: "FEATURE_CALLOUT_2",
            anchors: [
              {
                selector: "#back-button",
                arrow_position: "top-center-arrow-start",
              },
            ],
            content: {
              position: "callout",
              title: { string_id: "callout-pdfjs-draw-title" },
              subtitle: { string_id: "callout-pdfjs-draw-body-b" },
              primary_button: {
                label: { string_id: "callout-pdfjs-draw-button" },
                action: {
                  type: "MULTI_ACTION",
                  data: {
                    actions: [
                      {
                        type: "BLOCK_MESSAGE",
                        data: { id: "TEST_FEATURE_TOUR" },
                      },
                      {
                        type: "SET_PREF",
                        data: {
                          pref: {
                            name: "messaging-system-action.browser.test.feature-tour",
                          },
                        },
                      },
                    ],
                  },
                },
              },
              dismiss_button: {
                action: {
                  type: "MULTI_ACTION",
                  data: {
                    actions: [
                      {
                        type: "BLOCK_MESSAGE",
                        data: { id: "TEST_FEATURE_TOUR" },
                      },
                      {
                        type: "SET_PREF",
                        data: {
                          pref: {
                            name: "messaging-system-action.browser.test.feature-tour",
                          },
                        },
                      },
                    ],
                  },
                },
              },
            },
          },
        ],
      },
      priority: 2,
      targeting: `(('messaging-system-action.browser.test.feature-tour' | preferenceValue) ? (('messaging-system-action.browser.test.feature-tour' | preferenceValue | regExpMatch('(?<=complete":)(.*)(?=})')) ? ('messaging-system-action.browser.test.feature-tour' | preferenceValue | regExpMatch('(?<=complete":)(.*)(?=})')[1] != "true") : true) : true)`,
      trigger: { id: "nthTabClosed" },
    },
    {
      id: "TEST_FEATURE_TOUR_2",
      template: "feature_callout",
      content: {
        id: "TEST_FEATURE_TOUR_2",
        template: "multistage",
        backdrop: "transparent",
        transitions: false,
        disableHistoryUpdates: true,
        screens: [
          {
            id: "FEATURE_CALLOUT_TEST",
            anchors: [
              {
                selector: "#PanelUI-menu-button",
                arrow_position: "top-center-arrow-end",
              },
            ],
            content: {
              position: "callout",
              title: { string_id: "callout-pdfjs-edit-title" },
              subtitle: { string_id: "callout-pdfjs-edit-body-b" },
              primary_button: {
                label: { string_id: "callout-pdfjs-edit-button" },
                action: { dismiss: true },
              },
            },
          },
        ],
      },
      priority: 1,
      targeting: "true",
      trigger: { id: "nthTabClosed" },
    },
  ];
  const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
  getMessagesStub.returns(TEST_MESSAGES);
  await ASRouter._updateMessageProviders();
  await ASRouter.loadMessagesFromAllProviders(
    ASRouter.state.providers.filter(p => p.id === "onboarding")
  );

  // Test that callout is triggered and shown in browser chrome
  const win1 = await BrowserTestUtils.openNewBrowserWindow();
  win1.focus();
  const tab1 = await BrowserTestUtils.openNewForegroundTab(win1.gBrowser);
  await TestUtils.waitForTick();
  win1.gBrowser.removeTab(tab1);
  await waitForCalloutScreen(
    win1.document,
    TEST_MESSAGES[0].content.screens[0].id
  );
  ok(
    win1.document.querySelector(calloutSelector),
    "Feature Callout is rendered in the browser chrome when a message is available"
  );

  // Test that a callout does NOT appear if another is already shown in any window.
  const showFeatureCalloutSpy = sandbox.spy(
    FeatureCalloutBroker,
    "showFeatureCallout"
  );
  const win2 = await BrowserTestUtils.openNewBrowserWindow();
  win2.focus();
  const tab2 = await BrowserTestUtils.openNewForegroundTab(win2.gBrowser);
  await TestUtils.waitForTick();
  win2.gBrowser.removeTab(tab2);
  await BrowserTestUtils.waitForCondition(async () => {
    const rvs = await Promise.all(showFeatureCalloutSpy.returnValues);
    return (
      showFeatureCalloutSpy.calledWith(
        win2.gBrowser.selectedBrowser,
        sinon.match(TEST_MESSAGES[0])
      ) && rvs.every(rv => !rv)
    );
  }, "Waiting for showFeatureCallout to be called");
  ok(
    !win2.document.querySelector(calloutSelector),
    "Feature Callout is not rendered when a callout is already shown in any window"
  );
  await BrowserTestUtils.closeWindow(win2);
  win1.focus();
  await BrowserTestUtils.waitForCondition(
    async () => Services.focus.activeWindow === win1,
    "Waiting for window 1 to be active"
  );

  // Test that the tour pref doesn't exist yet
  ok(
    !Services.prefs.prefHasUserValue(TEST_MESSAGES[0].content.tour_pref_name),
    "Tour pref does not exist yet"
  );

  // Test that the callout advances screen and sets the tour pref
  win1.document.querySelector(calloutCTASelector).click();
  await BrowserTestUtils.waitForCondition(
    () =>
      Services.prefs.prefHasUserValue(TEST_MESSAGES[0].content.tour_pref_name),
    "Waiting for tour pref to be set"
  );
  SimpleTest.isDeeply(
    JSON.parse(
      Services.prefs.getStringPref(
        TEST_MESSAGES[0].content.tour_pref_name,
        "{}"
      )
    ),
    { screen: "FEATURE_CALLOUT_2", complete: false },
    "Tour pref is set correctly"
  );
  await waitForCalloutScreen(
    win1.document,
    TEST_MESSAGES[0].content.screens[1].id
  );
  ok(
    win1.document.querySelector(calloutSelector),
    "Feature Callout screen 2 is rendered"
  );

  // Test that the callout is dismissed and cleans up the tour pref
  win1.document.querySelector(calloutCTASelector).click();
  await waitForCalloutRemoved(win1.document);
  ok(
    !win1.document.querySelector(calloutSelector),
    "Feature Callout is not rendered after being dismissed"
  );
  ok(
    !Services.prefs.prefHasUserValue(TEST_MESSAGES[0].content.tour_pref_name),
    "Tour pref is cleaned up correctly"
  );
  await BrowserTestUtils.waitForCondition(
    () => !FeatureCalloutBroker.isCalloutShowing,
    "Waiting for all callouts to empty from the callout broker"
  );

  // Test that the message was blocked so a different callout is shown
  const tab3 = await BrowserTestUtils.openNewForegroundTab(win1.gBrowser);
  await TestUtils.waitForTick();
  win1.gBrowser.removeTab(tab3);
  await waitForCalloutScreen(
    win1.document,
    TEST_MESSAGES[1].content.screens[0].id
  );
  ok(
    win1.document.querySelector(calloutSelector),
    "A different Feature Callout is rendered"
  );
  win1.document.querySelector(calloutCTASelector).click();
  await waitForCalloutRemoved(win1.document);
  ok(!FeatureCalloutBroker.isCalloutShowing, "No Feature Callout is shown");

  BrowserTestUtils.closeWindow(win1);

  sandbox.restore();
  await ASRouter.unblockMessageById(TEST_MESSAGES[0].id);
  await ASRouter.resetMessageState();
  await ASRouter._updateMessageProviders();
  await ASRouter.loadMessagesFromAllProviders(
    ASRouter.state.providers.filter(p => p.id === "onboarding")
  );
});

add_task(async function callout_not_shown_if_dialog_open() {
  const win = await BrowserTestUtils.openNewBrowserWindow();
  let dialogPromise = BrowserTestUtils.promiseAlertDialog(null, undefined, {
    callback: async dialogWin => {
      let rv = await FeatureCalloutBroker.showFeatureCallout(
        win.gBrowser.selectedBrowser,
        testMessage.message
      );
      ok(
        !rv,
        "Feature callout not shown when a dialog is open in the same window"
      );
      dialogWin.document.querySelector("dialog").getButton("cancel").click();
    },
    isSubDialog: true,
  });
  DefaultBrowserCheck.prompt(win);
  await dialogPromise;

  await BrowserTestUtils.closeWindow(win);
  await SpecialPowers.popPrefEnv();
});

add_task(async function callout_not_shown_if_panel_open() {
  const win = await BrowserTestUtils.openNewBrowserWindow();
  const gCUITestUtils = new CustomizableUITestUtils(win);
  await gCUITestUtils.openMainMenu();

  let rv = await FeatureCalloutBroker.showFeatureCallout(
    win.gBrowser.selectedBrowser,
    testMessage.message
  );
  ok(!rv, "Feature callout not shown when a panel is open in the same window");

  await gCUITestUtils.hideMainMenu();
  await BrowserTestUtils.closeWindow(win);
});

add_task(async function feature_callout_renders_in_browser_chrome_for_pdf() {
  const sandbox = sinon.createSandbox();
  const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
  sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
  sendTriggerStub.callThrough();

  const win = await BrowserTestUtils.openNewBrowserWindow();
  await openURLInWindow(win, PDF_TEST_URL);
  const doc = win.document;
  await waitForCalloutScreen(doc, testMessageScreenId);
  const container = doc.querySelector(calloutSelector);
  ok(
    container,
    "Feature Callout is rendered in the browser chrome with a new window when a message is available"
  );

  // click CTA to close
  doc.querySelector(calloutCTASelector).click();
  await waitForCalloutRemoved(doc);
  ok(
    true,
    "Feature callout removed from browser chrome after clicking button configured to navigate"
  );

  await BrowserTestUtils.closeWindow(win);
  sandbox.restore();
});

add_task(
  async function feature_callout_renders_and_hides_in_chrome_when_switching_tabs() {
    const sandbox = sinon.createSandbox();
    const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
    sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
    sendTriggerStub.callThrough();

    const win = await BrowserTestUtils.openNewBrowserWindow();

    const doc = win.document;
    const tab1 = await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      PDF_TEST_URL
    );
    tab1.focus();
    await waitForCalloutScreen(doc, testMessageScreenId);
    ok(
      doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout rendered when opening a new tab with PDF url"
    );

    const tab2 = await openURLInNewTab(win, "about:preferences");
    tab2.focus();
    await BrowserTestUtils.waitForCondition(() => {
      return !doc.body.querySelector(
        "#multi-stage-message-root.featureCallout"
      );
    });

    ok(
      !doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout removed when tab without PDF URL is navigated to"
    );

    const tab3 = await openURLInNewTab(win, PDF_TEST_URL);
    tab3.focus();
    await waitForCalloutScreen(doc, testMessageScreenId);
    ok(
      doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout still renders when opening a new tab with PDF url after being initially rendered on another tab"
    );

    tab1.focus();
    await waitForCalloutScreen(doc, testMessageScreenId);
    ok(
      doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout rendered on original tab after switching tabs multiple times"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
  }
);

add_task(
  async function feature_callout_disappears_when_navigating_to_non_pdf_url_in_same_tab() {
    const sandbox = sinon.createSandbox();
    const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
    sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
    sendTriggerStub.callThrough();

    const win = await BrowserTestUtils.openNewBrowserWindow();

    const doc = win.document;
    const tab1 = await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      PDF_TEST_URL
    );
    tab1.focus();
    await waitForCalloutScreen(doc, testMessageScreenId);
    ok(
      doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout rendered when opening a new tab with PDF url"
    );

    BrowserTestUtils.startLoadingURIString(win.gBrowser, "about:preferences");
    await BrowserTestUtils.waitForLocationChange(
      win.gBrowser,
      "about:preferences"
    );
    await waitForCalloutRemoved(doc);

    ok(
      !doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout not rendered on original tab after navigating to non pdf URL"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
  }
);

add_task(
  async function feature_callout_disappears_when_closing_foreground_pdf_tab() {
    const sandbox = sinon.createSandbox();
    const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
    sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
    sendTriggerStub.callThrough();

    const win = await BrowserTestUtils.openNewBrowserWindow();

    const doc = win.document;
    const tab1 = await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      PDF_TEST_URL
    );
    tab1.focus();
    await waitForCalloutScreen(doc, testMessageScreenId);
    ok(
      doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout rendered when opening a new tab with PDF url"
    );

    BrowserTestUtils.removeTab(tab1);
    await waitForCalloutRemoved(doc);

    ok(
      !doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout disappears after closing foreground tab"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
  }
);

add_task(
  async function feature_callout_does_not_appear_when_opening_background_pdf_tab() {
    const sandbox = sinon.createSandbox();
    const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
    const TEST_MESSAGES = [newtabTestMessage];
    getMessagesStub.returns(TEST_MESSAGES);
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders(
      ASRouter.state.providers.filter(p => p.id === "onboarding")
    );

    const win = await BrowserTestUtils.openNewBrowserWindow();
    const doc = win.document;

    const tab1 = await BrowserTestUtils.addTab(win.gBrowser, PDF_TEST_URL);
    ok(
      !doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout not rendered when opening a background tab with PDF url"
    );

    BrowserTestUtils.removeTab(tab1);

    ok(
      !doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout still not rendered after closing background tab with PDF url"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();
  }
);

add_task(
  async function newtab_feature_callout_appears_in_browser_chrome_on_newtab() {
    const sandbox = sinon.createSandbox();
    const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
    const TEST_MESSAGES = [newtabTestMessage];
    getMessagesStub.returns(TEST_MESSAGES);
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();

    const win = await BrowserTestUtils.openNewBrowserWindow();
    const doc = win.document;
    const tab1 = await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      "about:newtab"
    );
    tab1.focus();
    await waitForCalloutScreen(doc, newtabTestMessageScreenId);
    ok(
      doc.querySelector(`.${newtabTestMessageScreenId}`),
      "Newtab feature callout rendered when opening a focused newtab"
    );

    BrowserTestUtils.removeTab(tab1);
    await waitForCalloutRemoved(doc);
    ok(
      !doc.querySelector(`.${newtabTestMessageScreenId}`),
      "Feature callout disappears after closing new tab"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();
  }
);

add_task(
  async function newtab_feature_callout_does_not_appear_when_opening_background_newtab_tab() {
    const sandbox = sinon.createSandbox();
    const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
    const TEST_MESSAGES = [newtabTestMessage];
    getMessagesStub.returns(TEST_MESSAGES);
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();

    const win = await BrowserTestUtils.openNewBrowserWindow();
    const doc = win.document;

    await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      "about:preferences"
    );
    const tab2 = await BrowserTestUtils.addTab(win.gBrowser, "about:newtab");
    ok(
      !doc.querySelector(`.${newtabTestMessageScreenId}`),
      "Newtab feature callout not rendered when opening a background newtab"
    );

    BrowserTestUtils.removeTab(tab2);
    await waitForCalloutRemoved(doc);
    ok(
      !doc.querySelector(`.${newtabTestMessageScreenId}`),
      "Feature callout still not rendered after closing background tab"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();
  }
);

add_task(
  async function newtab_feature_callout_does_not_appear_in_browser_chrome_on_new_window() {
    const sandbox = sinon.createSandbox();
    const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
    const TEST_MESSAGES = [newtabTestMessage];
    getMessagesStub.returns(TEST_MESSAGES);
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();

    const win = await BrowserTestUtils.openNewBrowserWindow();
    await openURLInWindow(win, "about:newtab");
    const doc = win.document;

    await waitForCalloutScreen(doc, newtabTestMessageScreenId);
    ok(
      doc.querySelector(`.${newtabTestMessageScreenId}`),
      "Newtab Feature Callout is in the browser chrome of first window when a message is available"
    );

    const win2 = await BrowserTestUtils.openNewBrowserWindow();
    await openURLInWindow(win2, "about:newtab");
    const doc2 = win2.document;
    ok(
      !doc2.querySelector(`.${newtabTestMessageScreenId}`),
      "Newtab Feature Callout is not in the browser chrome new window when a message is available"
    );

    await BrowserTestUtils.closeWindow(win);
    await BrowserTestUtils.closeWindow(win2);
    sandbox.restore();
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();
  }
);

add_task(
  async function feature_callout_disappears_when_navigating_from_newtab_to_pdf_url_in_same_tab() {
    const sandbox = sinon.createSandbox();
    const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
    const TEST_MESSAGES = [newtabTestMessage];
    getMessagesStub.returns(TEST_MESSAGES);
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();

    const win = await BrowserTestUtils.openNewBrowserWindow();

    const doc = win.document;
    const tab1 = await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      "about:newtab"
    );
    tab1.focus();
    await waitForCalloutScreen(doc, newtabTestMessageScreenId);
    ok(
      doc.querySelector(`.${newtabTestMessageScreenId}`),
      "Feature callout rendered when opening a newtab"
    );

    BrowserTestUtils.startLoadingURIString(win.gBrowser, PDF_TEST_URL);
    await BrowserTestUtils.waitForLocationChange(win.gBrowser, PDF_TEST_URL);
    await waitForCalloutRemoved(doc);

    ok(
      !doc.querySelector(`.${testMessageScreenId}`),
      "Feature callout not rendered on original tab after navigating to PDF"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();
  }
);

add_task(
  async function feature_callout_disappears_when_navigating_from_newtab_to_pdf_url_in_different_tab() {
    const sandbox = sinon.createSandbox();
    const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
    const TEST_MESSAGES = [newtabTestMessage];
    getMessagesStub.returns(TEST_MESSAGES);
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();

    const win = await BrowserTestUtils.openNewBrowserWindow();

    const doc = win.document;
    const tab1 = await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      "about:newtab"
    );
    tab1.focus();
    await waitForCalloutScreen(doc, newtabTestMessageScreenId);
    ok(
      doc.querySelector(`.${newtabTestMessageScreenId}`),
      "Feature callout rendered when opening a newtab"
    );

    const tab2 = await BrowserTestUtils.openNewForegroundTab(
      win.gBrowser,
      PDF_TEST_URL
    );
    tab2.focus();
    await waitForCalloutRemoved(doc);

    ok(
      !doc.querySelector(`.${testMessageScreenId}`),
      "Newtab feature callout not rendered after navigating to PDF"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();
  }
);

add_task(
  async function feature_callout_is_positioned_relative_to_browser_window() {
    // Deep copying our test message so we can alter it without disrupting future tests
    const pdfTestMessage = JSON.parse(JSON.stringify(testMessage));
    const pdfTestMessageCalloutSelector =
      pdfTestMessage.message.content.screens[0].id;

    pdfTestMessage.message.content.screens[0].anchors[0] = {
      selector: "hbox#browser",
      absolute_position: { top: "45px", right: "25px" },
    };

    const sandbox = sinon.createSandbox();
    const getMessagesStub = sandbox.stub(FeatureCalloutMessages, "getMessages");
    const TEST_MESSAGES = [pdfTestMessage.message];
    getMessagesStub.returns(TEST_MESSAGES);
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();

    const win = await BrowserTestUtils.openNewBrowserWindow();
    await openURLInWindow(win, PDF_TEST_URL);
    const doc = win.document;
    await waitForCalloutScreen(doc, pdfTestMessageCalloutSelector);

    // Verify that callout renders in appropriate position (without infobar element)
    const callout = doc.querySelector(`.${pdfTestMessageCalloutSelector}`);
    ok(callout, "Callout is rendered when navigating to PDF file");
    ok(
      validateCalloutCustomPosition(
        callout,
        pdfTestMessage.message.content.screens[0].anchors[0].absolute_position,
        doc
      ),
      "Callout custom position is as expected"
    );

    // Add height to the top of the browser to simulate an infobar or other element
    const navigatorToolBox = doc.querySelector("#navigator-toolbox");
    navigatorToolBox.style.height = "150px";
    // We test in a new tab because the callout does not adjust itself
    // when size of the navigator-toolbox-background box changes.
    const tab = await openURLInNewTab(win, "https://example.com/some2.pdf");
    // Verify that callout renders in appropriate position (with infobar element displayed)
    ok(
      validateCalloutCustomPosition(
        callout,
        pdfTestMessage.message.content.screens[0].anchors[0].absolute_position,
        doc
      ),
      "Callout custom position is as expected while navigator toolbox height is extended"
    );
    BrowserTestUtils.removeTab(tab);
    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
    await ASRouter._updateMessageProviders();
    await ASRouter.loadMessagesFromAllProviders();
  }
);

add_task(
  async function custom_position_callout_is_horizontally_reversed_in_rtl_layouts() {
    // Deep copying our test message so we can alter it without disrupting future tests
    const pdfTestMessage = JSON.parse(JSON.stringify(testMessage));
    const pdfTestMessageCalloutSelector =
      pdfTestMessage.message.content.screens[0].id;

    pdfTestMessage.message.content.screens[0].anchors[0] = {
      selector: "hbox#browser",
      absolute_position: { top: "45px", right: "25px" },
    };

    const sandbox = sinon.createSandbox();
    const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
    sendTriggerStub.withArgs(pdfMatch).resolves(pdfTestMessage);
    sendTriggerStub.callThrough();

    const win = await BrowserTestUtils.openNewBrowserWindow();
    win.document.dir = "rtl";
    Assert.strictEqual(
      win.document.documentElement.getAttribute("dir"),
      "rtl",
      "browser window is in RTL"
    );

    await openURLInWindow(win, PDF_TEST_URL);
    const doc = win.document;
    await waitForCalloutScreen(doc, pdfTestMessageCalloutSelector);

    const callout = doc.querySelector(`.${pdfTestMessageCalloutSelector}`);
    ok(callout, "Callout is rendered when navigating to PDF file");
    ok(
      validateCalloutRTLPosition(
        callout,
        pdfTestMessage.message.content.screens[0].anchors[0].absolute_position
      ),
      "Callout custom position is rendered appropriately in RTL mode"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
  }
);

add_task(async function feature_callout_dismissed_on_escape() {
  const sandbox = sinon.createSandbox();
  const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
  sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
  sendTriggerStub.callThrough();

  const win = await BrowserTestUtils.openNewBrowserWindow();
  await openURLInWindow(win, PDF_TEST_URL);
  const doc = win.document;
  await waitForCalloutScreen(doc, testMessageScreenId);
  const container = doc.querySelector(calloutSelector);
  ok(
    container,
    "Feature Callout is rendered in the browser chrome with a new window when a message is available"
  );

  // Ensure the browser is focused
  win.gBrowser.selectedBrowser.focus();

  // Press Escape to close
  EventUtils.synthesizeKey("KEY_Escape", {}, win);
  await waitForCalloutRemoved(doc);
  ok(true, "Feature callout dismissed after pressing Escape");

  await BrowserTestUtils.closeWindow(win);
  sandbox.restore();
});

add_task(
  async function feature_callout_not_dismissed_on_escape_with_interactive_elm_focused() {
    const sandbox = sinon.createSandbox();
    const sendTriggerStub = sandbox.stub(ASRouter, "sendTriggerMessage");
    sendTriggerStub.withArgs(pdfMatch).resolves(testMessage);
    sendTriggerStub.callThrough();

    const win = await BrowserTestUtils.openNewBrowserWindow();
    await openURLInWindow(win, PDF_TEST_URL);
    const doc = win.document;
    await waitForCalloutScreen(doc, testMessageScreenId);
    const container = doc.querySelector(calloutSelector);
    ok(
      container,
      "Feature Callout is rendered in the browser chrome with a new window when a message is available"
    );

    // Ensure an interactive element is focused
    win.gURLBar.focus();

    // Press Escape to close
    EventUtils.synthesizeKey("KEY_Escape", {}, win);
    await TestUtils.waitForTick();
    // Wait 500ms for transition to complete
    // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
    await new Promise(resolve => setTimeout(resolve, 500));
    ok(
      doc.querySelector(calloutSelector),
      "Feature callout is not dismissed after pressing Escape because an interactive element is focused"
    );

    await BrowserTestUtils.closeWindow(win);
    sandbox.restore();
  }
);

add_task(async function first_anchor_selected_is_valid() {
  const win = await BrowserTestUtils.openNewBrowserWindow();
  const config = {
    win,
    location: "chrome",
    context: "chrome",
    browser: win.gBrowser.selectedBrowser,
    theme: { preset: "chrome" },
  };

  const message = JSON.parse(JSON.stringify(testMessage.message));
  const sandbox = sinon.createSandbox();

  const doc = win.document;
  const featureCallout = new FeatureCallout(config);
  const getAnchorSpy = sandbox.spy(featureCallout, "_getAnchor");
  featureCallout.showFeatureCallout(message);
  await waitForCalloutScreen(doc, message.content.screens[0].id);
  ok(
    getAnchorSpy.alwaysReturned(
      sandbox.match(message.content.screens[0].anchors[0])
    ),
    "The first anchor is selected"
  );

  win.document.querySelector(calloutCTASelector).click();
  await waitForCalloutRemoved(win.document);
  await BrowserTestUtils.closeWindow(win);
  sandbox.restore();
});

add_task(async function first_anchor_selected_is_invalid() {
  const win = await BrowserTestUtils.openNewBrowserWindow();
  const doc = win.document;
  const config = {
    win,
    location: "chrome",
    context: "chrome",
    browser: win.gBrowser.selectedBrowser,
    theme: { preset: "chrome" },
  };

  let stopReloadButton = doc.getElementById("stop-reload-button");

  await gCustomizeMode.addToPanel(stopReloadButton);

  const message = JSON.parse(JSON.stringify(testMessage.message));
  message.content.screens[0].anchors = [
    // element that does not exist
    { selector: "#some-fake-id.some-fake-class", arrow_position: "top" },
    // element that exists but has no height/width
    { selector: "#a11y-announcement", arrow_position: "top" },
    // element that exists but is hidden by CSS
    { selector: "#window-modal-dialog", arrow_position: "top" },
    // customizable widget that's in the overflow panel
    { selector: "#stop-reload-button", arrow_position: "top" },
    // element that is fully visible
    { selector: "#PanelUI-menu-button", arrow_position: "top" },
  ];
  const sandbox = sinon.createSandbox();

  const featureCallout = new FeatureCallout(config);
  const getAnchorSpy = sandbox.spy(featureCallout, "_getAnchor");
  featureCallout.showFeatureCallout(message);
  await waitForCalloutScreen(doc, message.content.screens[0].id);
  is(
    getAnchorSpy.lastCall.returnValue.selector,
    message.content.screens[0].anchors[4].selector,
    "The first valid anchor (anchor 5) is selected"
  );

  win.document.querySelector(calloutCTASelector).click();
  await waitForCalloutRemoved(win.document);
  CustomizableUI.reset();
  await BrowserTestUtils.closeWindow(win);
  sandbox.restore();
});