summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/soft-navigation-heuristics/resources/soft-navigation-helper.js
blob: d405adb4e7eb7690fe73f31db523d357a38734ee (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
var counter = 0;
var interacted;
var timestamps = []
const MAX_CLICKS = 50;
// Entries for one hard navigation + 50 soft navigations.
const MAX_PAINT_ENTRIES = 51;
const URL = "foobar.html";
const readValue = (value, defaultValue) => {
  return value !== undefined ? value : defaultValue;
}
const testSoftNavigation =
    options => {
      const addContent = options.addContent;
      const link = options.link;
      const pushState = readValue(options.pushState,
        url=>{history.pushState({}, '', url)});
      const clicks = readValue(options.clicks, 1);
      const extraValidations = readValue(options.extraValidations,
                                                   () => {});
      const testName = options.testName;
      const pushUrl = readValue(options.pushUrl, true);
      const eventType = readValue(options.eventType, "click");
      const interactionFunc = options.interactionFunc;
      const eventPrepWork = options.eventPrepWork;
      promise_test(async t => {
        await waitInitialLCP();
        const preClickLcp = await getLcpEntries();
        setEvent(t, link, pushState, addContent, pushUrl, eventType,
                 eventPrepWork);
        let first_navigation_id;
        for (let i = 0; i < clicks; ++i) {
          const firstClick = (i === 0);
          let paint_entries_promise =
              waitOnPaintEntriesPromise(firstClick);
          interacted = false;
          interact(link, interactionFunc);

          const navigation_id = await waitOnSoftNav();
          if (!first_navigation_id) {
            first_navigation_id = navigation_id;
          }
          // Ensure paint timing entries are fired before moving on to the next
          // click.
          await paint_entries_promise;
        }
        assert_equals(
            document.softNavigations, clicks,
            'Soft Navigations detected are the same as the number of clicks');
        await validateSoftNavigationEntry(
            clicks, extraValidations, pushUrl);

        await runEntryValidations(preClickLcp, first_navigation_id, clicks + 1, options.validate);
      }, testName);
    };

const testNavigationApi = (testName, navigateEventHandler, link) => {
  promise_test(async t => {
    navigation.addEventListener('navigate', navigateEventHandler);
    const navigated = new Promise(resolve => {
      navigation.addEventListener('navigatesuccess', resolve);
      navigation.addEventListener('navigateerror', resolve);
    });
    await waitInitialLCP();
    const preClickLcp = await getLcpEntries();
    let paint_entries_promise = waitOnPaintEntriesPromise();
    interact(link);
    const first_navigation_id = await waitOnSoftNav();
    await navigated;
    await paint_entries_promise;
    assert_equals(document.softNavigations, 1, 'Soft Navigation detected');
    await validateSoftNavigationEntry(1, () => {}, 'foobar.html');

    await runEntryValidations(preClickLcp, first_navigation_id);
  }, testName);
};

const testSoftNavigationNotDetected = options => {
    promise_test(async t => {
      const preClickLcp = await getLcpEntries();
      options.eventTarget.addEventListener(options.eventName, options.eventHandler);
      interact(options.link);
      await new Promise((resolve, reject) => {
        (new PerformanceObserver(() =>
            reject("Soft navigation should not be triggered"))).observe({
          type: 'soft-navigation',
          buffered: true
        });
        t.step_timeout(resolve, 1000);
      });
      if (document.softNavigations) {
        assert_equals(
          document.softNavigations, 0, 'Soft Navigation not detected');
      }
      const postClickLcp = await getLcpEntries();
      assert_equals(
          preClickLcp.length, postClickLcp.length, 'No LCP entries accumulated');
    }, options.testName);
  };

const runEntryValidations =
    async (preClickLcp, first_navigation_id, entries_expected_number = 2,
           validate = null) => {
  await validatePaintEntries('first-contentful-paint', entries_expected_number,
                             first_navigation_id);
  await validatePaintEntries('first-paint', entries_expected_number,
                             first_navigation_id);
  const postClickLcp = await getLcpEntries();
  const postClickLcpWithoutSoftNavs = await getLcpEntriesWithoutSoftNavs();
  assert_greater_than(
      postClickLcp.length, preClickLcp.length,
      'Soft navigation should have triggered at least an LCP entry');

  if (validate) {
    await validate();
  }
  assert_equals(
      postClickLcpWithoutSoftNavs.length, preClickLcp.length,
      'Soft navigation should not have triggered an LCP entry when the ' +
      'observer did not opt in');
  assert_not_equals(
      postClickLcp[postClickLcp.length - 1].size,
      preClickLcp[preClickLcp.length - 1].size,
      'Soft navigation LCP element should not have identical size to the hard ' +
          'navigation LCP element');
  assert_equals(
      postClickLcp[preClickLcp.length].navigationId,
      first_navigation_id, 'Soft navigation LCP should have the same navigation ' +
      'ID as the last soft nav entry')
};

const interact =
    (link, interactionFunc = undefined) => {
      if (test_driver) {
        if (interactionFunc) {
          interactionFunc();
        } else {
          test_driver.click(link);
        }
        timestamps[counter] = {"syncPostInteraction": performance.now()};
      }
    }

const setEvent = (t, button, pushState, addContent, pushUrl, eventType, prepWork) => {
  const eventObject =
      (eventType == 'click' || eventType.startsWith("key")) ? button : window;
  eventObject.addEventListener(eventType, async e => {
    let prepWorkFailed = false;
    if (prepWork &&!prepWork(t)) {
      prepWorkFailed = true;
    }
    // This is the end of the event's sync processing.
    if (!timestamps[counter]["eventEnd"]) {
      timestamps[counter]["eventEnd"] = performance.now();
    }
    if (prepWorkFailed) {
      return;
    }
    // Jump through a task, to ensure task tracking is working properly.
    await new Promise(r => t.step_timeout(r, 0));

    const url = URL + "?" + counter;
    if (pushState) {
      // Change the URL
      if (pushUrl) {
        pushState(url);
      } else {
        pushState();
      }
    }

    // Wait 10 ms to make sure the timestamps are correct.
    await new Promise(r => t.step_timeout(r, 10));

    await addContent(url);

    interacted = true;
    ++counter;
  });
};

const validateSoftNavigationEntry = async (clicks, extraValidations,
                                              pushUrl) => {
  const [entries, options] = await new Promise(resolve => {
    (new PerformanceObserver((list, obs, options) => resolve(
      [list.getEntries(), options]))).observe(
      {type: 'soft-navigation', buffered: true});
    });
  const expectedClicks = Math.min(clicks, MAX_CLICKS);

  assert_equals(entries.length, expectedClicks,
                "Performance observer got an entry");
  for (let i = 0; i < entries.length; ++i) {
    const entry = entries[i];
    assert_true(entry.name.includes(pushUrl ? URL : document.location.href),
                "The soft navigation name is properly set");
    const entryTimestamp = entry.startTime;
    assert_less_than_equal(timestamps[i]["syncPostInteraction"], entryTimestamp,
                "Entry timestamp is lower than the post interaction one");
    assert_greater_than_equal(
        entryTimestamp, timestamps[i]['eventEnd'],
        'Event start timestamp matches');
    assert_not_equals(entry.navigationId,
                      performance.getEntriesByType("navigation")[0].navigationId,
      "The navigation ID was re-generated and different from the initial one.");
    if (i > 0) {
      assert_not_equals(entry.navigationId,
                        entries[i-1].navigationId,
        "The navigation ID was re-generated between clicks");
    }
  }
  assert_equals(performance.getEntriesByType("soft-navigation").length,
                expectedClicks, "Performance timeline got an entry");
  await extraValidations(entries, options);

};

const validatePaintEntries = async (type, entries_number, first_navigation_id) => {
  if (!performance.softNavPaintMetricsSupported) {
    return;
  }
  const expected_entries_number = Math.min(entries_number, MAX_PAINT_ENTRIES);
  const entries = await new Promise(resolve => {
    const entries = [];
    (new PerformanceObserver(list => {
      entries.push(...list.getEntriesByName(type));
      if (entries.length >= expected_entries_number) {
        resolve(entries);
      }
    })).observe(
      {type: 'paint', buffered: true, includeSoftNavigationObservations: true});
    });
  const entries_without_softnavs = await new Promise(resolve => {
    (new PerformanceObserver(list => resolve(
      list.getEntriesByName(type)))).observe(
      {type: 'paint', buffered: true});
    });
  assert_equals(entries.length, expected_entries_number,
    `There are ${entries_number} entries for ${type}`);
  assert_equals(entries_without_softnavs.length, 1,
    `There is one non-softnav entry for ${type}`);
  if (entries_number > 1) {
    assert_not_equals(entries[0].startTime, entries[1].startTime,
      "Entries have different timestamps for " + type);
  }
  if (expected_entries_number > entries_without_softnavs.length) {
    assert_equals(entries[entries_without_softnavs.length].navigationId,
      first_navigation_id,
      "First paint entry should have the same navigation ID as the last soft " +
      "navigation entry");
  }
};

const waitInitialLCP = () => {
  return new Promise(resolve => {
      new PerformanceObserver(list => resolve()).observe({
        type: 'largest-contentful-paint',
        buffered: true
      });
  });
}

const waitOnSoftNav = () => {
  return new Promise(resolve => {
    (new PerformanceObserver(list => {
       const entries = list.getEntries();
       assert_equals(entries.length, 1,
                     "Only one soft navigation entry");
       resolve(entries[0].navigationId);
    })).observe({
      type: 'soft-navigation'
    });
  });
};

const getLcpEntries = async () => {
  const entries = await new Promise(resolve => {
    (new PerformanceObserver(list => resolve(
      list.getEntries()))).observe(
      {type: 'largest-contentful-paint', buffered: true,
       includeSoftNavigationObservations: true});
    });
  return entries;
};

const getLcpEntriesWithoutSoftNavs = async () => {
  const entries = await new Promise(resolve => {
    (new PerformanceObserver(list => resolve(
      list.getEntries()))).observe(
      {type: 'largest-contentful-paint', buffered: true});
    });
  return entries;
};

const addImage = async (element, url="blue.png", id = "imagelcp") => {
  const img = new Image();
  img.src = '/images/'+ url + "?" + Math.random();
  img.id=id
  img.setAttribute("elementtiming", id);
  await img.decode();
  element.appendChild(img);
};
const addImageToMain = async (url="blue.png", id = "imagelcp") => {
  await addImage(document.getElementById('main'), url, id);
};

const addTextParagraphToMain = (text, element_timing = "") => {
  const main = document.getElementById("main");
  const p = document.createElement("p");
  const textNode = document.createTextNode(text);
  p.appendChild(textNode);
  if (element_timing) {
    p.setAttribute("elementtiming", element_timing);
  }
  p.style = "font-size: 3em";
  main.appendChild(p);
  return p;
};
const addTextToDivOnMain = () => {
  const main = document.getElementById("main");
  const prevDiv = document.getElementsByTagName("div")[0];
  if (prevDiv) {
    main.removeChild(prevDiv);
  }
  const div = document.createElement("div");
  const text = document.createTextNode("Lorem Ipsum");
  div.appendChild(text);
  div.style = "font-size: 3em";
  main.appendChild(div);
}

const waitOnPaintEntriesPromise = (expectLCP = true) => {
  return new Promise((resolve, reject) => {
    if (performance.softNavPaintMetricsSupported) {
      const paint_entries = []
      new PerformanceObserver(list => {
        paint_entries.push(...list.getEntries());
        if (paint_entries.length == 2) {
          resolve();
        } else if (paint_entries.length > 2) {
          reject();
        }
      }).observe({type: 'paint', includeSoftNavigationObservations: true});
    } else if (expectLCP) {
        new PerformanceObserver(list => {
          resolve();
        }).observe({
          type: 'largest-contentful-paint',
          includeSoftNavigationObservations: true
        });
    } else {
        step_timeout(
            () => requestAnimationFrame(() => requestAnimationFrame(resolve)),
            100);
    }
  });
};