summaryrefslogtreecommitdiffstats
path: root/devtools/shared/commands/resource/tests/browser_resources_stylesheets.js
blob: 6c4f2e867a469094fa9d66e0d9cc07eec4d8cb16 (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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

// Test the ResourceCommand API around STYLESHEET.

const ResourceCommand = require("resource://devtools/shared/commands/resource/resource-command.js");

const STYLE_TEST_URL = URL_ROOT_SSL + "style_document.html";

const EXISTING_RESOURCES = [
  {
    styleText: "body { color: lime; }",
    href: null,
    nodeHref:
      "https://example.com/browser/devtools/shared/commands/resource/tests/style_document.html",
    isNew: false,
    disabled: false,
    constructed: false,
    ruleCount: 1,
    atRules: [],
  },
  {
    styleText: "body { margin: 1px; }",
    href: "https://example.com/browser/devtools/shared/commands/resource/tests/style_document.css",
    nodeHref:
      "https://example.com/browser/devtools/shared/commands/resource/tests/style_document.html",
    isNew: false,
    disabled: false,
    constructed: false,
    ruleCount: 1,
    atRules: [],
  },
  {
    styleText: "",
    href: null,
    nodeHref: null,
    isNew: false,
    disabled: false,
    constructed: true,
    ruleCount: 1,
    atRules: [],
  },
  {
    styleText: "body { background-color: pink; }",
    href: null,
    nodeHref:
      "https://example.org/browser/devtools/shared/commands/resource/tests/style_iframe.html",
    isNew: false,
    disabled: false,
    constructed: false,
    ruleCount: 1,
    atRules: [],
  },
  {
    styleText: "body { padding: 1px; }",
    href: "https://example.org/browser/devtools/shared/commands/resource/tests/style_iframe.css",
    nodeHref:
      "https://example.org/browser/devtools/shared/commands/resource/tests/style_iframe.html",
    isNew: false,
    disabled: false,
    constructed: false,
    ruleCount: 1,
    atRules: [],
  },
];

const ADDITIONAL_INLINE_RESOURCE = {
  styleText:
    "@media all { body { color: red; } } @media print { body { color: cyan; } } body { font-size: 10px; }",
  href: null,
  nodeHref:
    "https://example.com/browser/devtools/shared/commands/resource/tests/style_document.html",
  isNew: false,
  disabled: false,
  constructed: false,
  ruleCount: 5,
  atRules: [
    {
      type: "media",
      conditionText: "all",
      matches: true,
      line: 1,
      column: 1,
    },
    {
      type: "media",
      conditionText: "print",
      matches: false,
      line: 1,
      column: 37,
    },
  ],
};

const ADDITIONAL_CONSTRUCTED_RESOURCE = {
  styleText: "",
  href: null,
  nodeHref: null,
  isNew: false,
  disabled: false,
  constructed: true,
  ruleCount: 2,
  atRules: [],
};

const ADDITIONAL_FROM_ACTOR_RESOURCE = {
  styleText: "body { font-size: 10px; }",
  href: null,
  nodeHref:
    "https://example.com/browser/devtools/shared/commands/resource/tests/style_document.html",
  isNew: true,
  disabled: false,
  constructed: false,
  ruleCount: 1,
  atRules: [],
};

add_task(async function () {
  // Enable @property
  await pushPref("layout.css.properties-and-values.enabled", true);
  await testResourceAvailableDestroyedFeature();
  await testResourceUpdateFeature();
  await testNestedResourceUpdateFeature();
});

function pushAvailableResource(availableResources) {
  // TODO(bug 1826538): Find a better way of dealing with these.
  return function (resources) {
    for (const resource of resources) {
      if (resource.href?.startsWith("resource://")) {
        continue;
      }
      availableResources.push(resource);
    }
  };
}

async function testResourceAvailableDestroyedFeature() {
  info("Check resource available feature of the ResourceCommand");

  const tab = await addTab(STYLE_TEST_URL);
  let resourceTimingEntryCounts = await getResourceTimingCount(tab);
  is(
    resourceTimingEntryCounts,
    2,
    "Should have two entires for resource timing"
  );

  const { client, resourceCommand, targetCommand } = await initResourceCommand(
    tab
  );

  info("Check whether ResourceCommand gets existing stylesheet");
  const availableResources = [];
  const destroyedResources = [];
  await resourceCommand.watchResources([resourceCommand.TYPES.STYLESHEET], {
    onAvailable: pushAvailableResource(availableResources),
    onDestroyed: resources => destroyedResources.push(...resources),
  });

  is(
    availableResources.length,
    EXISTING_RESOURCES.length,
    "Length of existing resources is correct"
  );
  for (let i = 0; i < availableResources.length; i++) {
    const availableResource = availableResources[i];
    // We can not expect the resources to always be forwarded in the same order.
    // See intermittent Bug 1655016.
    const expectedResource = findMatchingExpectedResource(availableResource);
    ok(expectedResource, "Found a matching expected resource for the resource");
    await assertResource(availableResource, expectedResource);
  }

  resourceTimingEntryCounts = await getResourceTimingCount(tab);
  is(
    resourceTimingEntryCounts,
    2,
    "Should still have two entires for resource timing after devtools APIs have been triggered"
  );

  info("Check whether ResourceCommand gets additonal stylesheet");
  await ContentTask.spawn(
    tab.linkedBrowser,
    ADDITIONAL_INLINE_RESOURCE.styleText,
    text => {
      const document = content.document;
      const stylesheet = document.createElement("style");
      stylesheet.id = "inline-from-test";
      stylesheet.textContent = text;
      document.body.appendChild(stylesheet);
    }
  );
  await waitUntil(
    () => availableResources.length === EXISTING_RESOURCES.length + 1
  );
  await assertResource(
    availableResources[availableResources.length - 1],
    ADDITIONAL_INLINE_RESOURCE
  );

  info("Check whether ResourceCommand gets additonal constructed stylesheet");
  await ContentTask.spawn(tab.linkedBrowser, null, () => {
    const document = content.document;
    const s = new content.CSSStyleSheet();
    // We use the different number of rules to meaningfully differentiate
    // between constructed stylesheets.
    s.replaceSync("foo { color: red } bar { color: blue }");
    // TODO(bug 1751346): wrappedJSObject should be unnecessary.
    document.wrappedJSObject.adoptedStyleSheets.push(s);
  });
  await waitUntil(
    () => availableResources.length === EXISTING_RESOURCES.length + 2
  );
  await assertResource(
    availableResources[availableResources.length - 1],
    ADDITIONAL_CONSTRUCTED_RESOURCE
  );

  info(
    "Check whether ResourceCommand gets additonal stylesheet which is added by DevTools"
  );
  const styleSheetsFront = await targetCommand.targetFront.getFront(
    "stylesheets"
  );
  await styleSheetsFront.addStyleSheet(
    ADDITIONAL_FROM_ACTOR_RESOURCE.styleText
  );
  await waitUntil(
    () => availableResources.length === EXISTING_RESOURCES.length + 3
  );
  await assertResource(
    availableResources[availableResources.length - 1],
    ADDITIONAL_FROM_ACTOR_RESOURCE
  );

  info("Check resource destroyed feature of the ResourceCommand");
  is(destroyedResources.length, 0, "There was no removed stylesheets yet");

  info("Remove inline stylesheet added in the test");
  await ContentTask.spawn(tab.linkedBrowser, null, () => {
    content.document.querySelector("#inline-from-test").remove();
  });
  await waitUntil(() => destroyedResources.length === 1);
  assertDestroyed(destroyedResources[0], {
    resourceId: availableResources.at(-3).resourceId,
  });

  info("Remove existing top-level inline stylesheet");
  await ContentTask.spawn(tab.linkedBrowser, null, () => {
    content.document.querySelector("style").remove();
  });
  await waitUntil(() => destroyedResources.length === 2);
  assertDestroyed(destroyedResources[1], {
    resourceId: availableResources.find(
      resource =>
        findMatchingExpectedResource(resource) === EXISTING_RESOURCES[0]
    ).resourceId,
  });

  info("Remove existing top-level <link> stylesheet");
  await ContentTask.spawn(tab.linkedBrowser, null, () => {
    content.document.querySelector("link").remove();
  });
  await waitUntil(() => destroyedResources.length === 3);
  assertDestroyed(destroyedResources[2], {
    resourceId: availableResources.find(
      resource =>
        findMatchingExpectedResource(resource) === EXISTING_RESOURCES[1]
    ).resourceId,
  });

  info("Remove existing iframe inline stylesheet");
  const iframeBrowsingContext = await SpecialPowers.spawn(
    tab.linkedBrowser,
    [],
    () => content.document.querySelector("iframe").browsingContext
  );

  await SpecialPowers.spawn(iframeBrowsingContext, [], () => {
    content.document.querySelector("style").remove();
  });
  await waitUntil(() => destroyedResources.length === 4);
  assertDestroyed(destroyedResources[3], {
    resourceId: availableResources.find(
      resource =>
        findMatchingExpectedResource(resource) === EXISTING_RESOURCES[3]
    ).resourceId,
  });

  info("Remove existing iframe <link> stylesheet");
  await SpecialPowers.spawn(iframeBrowsingContext, [], () => {
    content.document.querySelector("link").remove();
  });
  await waitUntil(() => destroyedResources.length === 5);
  assertDestroyed(destroyedResources[4], {
    resourceId: availableResources.find(
      resource =>
        findMatchingExpectedResource(resource) === EXISTING_RESOURCES[4]
    ).resourceId,
  });

  targetCommand.destroy();
  await client.close();
}

async function testResourceUpdateFeature() {
  info("Check resource update feature of the ResourceCommand");

  const tab = await addTab(STYLE_TEST_URL);

  const { client, resourceCommand, targetCommand } = await initResourceCommand(
    tab
  );

  info("Setup the watcher");
  const availableResources = [];
  const updates = [];
  await resourceCommand.watchResources([resourceCommand.TYPES.STYLESHEET], {
    onAvailable: pushAvailableResource(availableResources),
    onUpdated: newUpdates => updates.push(...newUpdates),
  });
  is(
    availableResources.length,
    EXISTING_RESOURCES.length,
    "Length of existing resources is correct"
  );
  is(updates.length, 0, "there's no update yet");

  info("Check toggleDisabled function");
  // Retrieve the stylesheet of the top-level target
  const resource = availableResources.find(
    innerResource => innerResource.targetFront.isTopLevel
  );
  const styleSheetsFront = await resource.targetFront.getFront("stylesheets");
  await styleSheetsFront.toggleDisabled(resource.resourceId);
  await waitUntil(() => updates.length === 1);

  // Check the content of the update object.
  assertUpdate(updates[0].update, {
    resourceId: resource.resourceId,
    updateType: "property-change",
  });
  is(
    updates[0].update.resourceUpdates.disabled,
    true,
    "resourceUpdates is correct"
  );

  // Check whether the cached resource is updated correctly.
  is(
    updates[0].resource.disabled,
    true,
    "cached resource is updated correctly"
  );

  // Check whether the actual stylesheet is updated correctly.
  const styleSheetDisabled = await ContentTask.spawn(
    tab.linkedBrowser,
    null,
    () => {
      const document = content.document;
      const stylesheet = document.styleSheets[0];
      return stylesheet.disabled;
    }
  );
  is(styleSheetDisabled, true, "actual stylesheet was updated correctly");

  info("Check update function");
  const expectedAtRules = [
    {
      type: "media",
      conditionText: "screen",
      matches: true,
    },
    {
      type: "media",
      conditionText: "print",
      matches: false,
    },
  ];

  const updateCause = "updated-by-test";
  await styleSheetsFront.update(
    resource.resourceId,
    "@media screen { color: red; } @media print { color: green; } body { color: cyan; }",
    false,
    updateCause
  );
  await waitUntil(() => updates.length === 4);

  assertUpdate(updates[1].update, {
    resourceId: resource.resourceId,
    updateType: "property-change",
  });
  is(
    updates[1].update.resourceUpdates.ruleCount,
    3,
    "resourceUpdates is correct"
  );
  is(updates[1].resource.ruleCount, 3, "cached resource is updated correctly");

  assertUpdate(updates[2].update, {
    resourceId: resource.resourceId,
    updateType: "style-applied",
    event: {
      cause: updateCause,
    },
  });
  is(
    updates[2].update.resourceUpdates,
    undefined,
    "resourceUpdates is correct"
  );

  assertUpdate(updates[3].update, {
    resourceId: resource.resourceId,
    updateType: "at-rules-changed",
  });
  assertAtRules(updates[3].update.resourceUpdates.atRules, expectedAtRules);

  // Check the actual page.
  const styleSheetResult = await getStyleSheetResult(tab);

  is(
    styleSheetResult.ruleCount,
    3,
    "ruleCount of actual stylesheet is updated correctly"
  );
  assertAtRules(styleSheetResult.atRules, expectedAtRules);

  targetCommand.destroy();
  await client.close();
}

async function testNestedResourceUpdateFeature() {
  info("Check nested resource update feature of the ResourceCommand");

  const tab = await addTab(STYLE_TEST_URL);

  const { outerWidth: originalWindowWidth, outerHeight: originalWindowHeight } =
    tab.ownerGlobal;

  registerCleanupFunction(() => {
    tab.ownerGlobal.resizeTo(originalWindowWidth, originalWindowHeight);
  });

  const { client, resourceCommand, targetCommand } = await initResourceCommand(
    tab
  );

  info("Setup the watcher");
  const availableResources = [];
  const updates = [];
  await resourceCommand.watchResources([resourceCommand.TYPES.STYLESHEET], {
    onAvailable: pushAvailableResource(availableResources),
    onUpdated: newUpdates => updates.push(...newUpdates),
  });
  is(
    availableResources.length,
    EXISTING_RESOURCES.length,
    "Length of existing resources is correct"
  );

  info("Apply new media query");
  // In order to avoid applying the media query (min-height: 400px).
  if (originalWindowHeight !== 300) {
    await new Promise(resolve => {
      tab.ownerGlobal.addEventListener("resize", resolve, { once: true });
      tab.ownerGlobal.resizeTo(originalWindowWidth, 300);
    });
  }

  // Retrieve the stylesheet of the top-level target
  const resource = availableResources.find(
    innerResource => innerResource.targetFront.isTopLevel
  );
  const styleSheetsFront = await resource.targetFront.getFront("stylesheets");
  await styleSheetsFront.update(
    resource.resourceId,
    `@media (min-height: 400px) {
      html {
        color: red;
      }
      @layer myLayer {
        @supports (container-type) {
          :root {
            color: gold;
            container: root inline-size;
          }

          @container root (width > 10px) {
            body {
              color: gold;
            }
          }
        }
      }
    }
    @property --my-property {
      syntax: "<color>";
      inherits: true;
      initial-value: #f06;
    }`,
    false
  );
  await waitUntil(() => updates.length === 3);
  is(
    updates.at(-1).resource.ruleCount,
    8,
    "Resource in update has expected ruleCount"
  );

  is(resource.atRules[0].matches, false, "Media query is not matched yet");

  info("Change window size to fire matches-change event");
  tab.ownerGlobal.resizeTo(originalWindowWidth, 500);
  await waitUntil(() => updates.length === 4);

  // Check the update content.
  const targetUpdate = updates[3];
  assertUpdate(targetUpdate.update, {
    resourceId: resource.resourceId,
    updateType: "matches-change",
  });
  Assert.strictEqual(
    resource,
    targetUpdate.resource,
    "Update object has the same resource"
  );

  is(
    JSON.stringify(targetUpdate.update.nestedResourceUpdates[0].path),
    JSON.stringify(["atRules", 0, "matches"]),
    "path of nestedResourceUpdates is correct"
  );
  is(
    targetUpdate.update.nestedResourceUpdates[0].value,
    true,
    "value of nestedResourceUpdates is correct"
  );

  // Check the resource.
  const expectedAtRules = [
    {
      type: "media",
      conditionText: "(min-height: 400px)",
      matches: true,
    },
    {
      type: "layer",
      layerName: "myLayer",
    },
    {
      type: "support",
      conditionText: "(container-type)",
    },
    {
      type: "container",
      conditionText: "root (width > 10px)",
    },
    {
      type: "property",
      propertyName: "--my-property",
    },
  ];

  assertAtRules(targetUpdate.resource.atRules, expectedAtRules);

  // Check the actual page.
  const styleSheetResult = await getStyleSheetResult(tab);
  is(
    styleSheetResult.ruleCount,
    8,
    "ruleCount of actual stylesheet is updated correctly"
  );
  assertAtRules(styleSheetResult.atRules, expectedAtRules);

  tab.ownerGlobal.resizeTo(originalWindowWidth, originalWindowHeight);

  targetCommand.destroy();
  await client.close();
}

function findMatchingExpectedResource(resource) {
  return EXISTING_RESOURCES.find(
    expected =>
      resource.href === expected.href &&
      resource.nodeHref === expected.nodeHref &&
      resource.ruleCount === expected.ruleCount &&
      resource.constructed == expected.constructed
  );
}

async function getStyleSheetResult(tab) {
  const result = await ContentTask.spawn(tab.linkedBrowser, null, () => {
    const document = content.document;
    const stylesheet = document.styleSheets[0];
    let ruleCount = 0;
    const atRules = [];

    const traverseRules = ruleList => {
      for (const rule of ruleList) {
        ruleCount++;

        if (rule.media) {
          let matches = false;
          try {
            const mql = content.matchMedia(rule.media.mediaText);
            matches = mql.matches;
          } catch (e) {
            // Ignored
          }

          atRules.push({
            type: "media",
            conditionText: rule.conditionText,
            matches,
          });
        } else if (rule instanceof content.CSSContainerRule) {
          atRules.push({
            type: "container",
            conditionText: rule.conditionText,
          });
        } else if (rule instanceof content.CSSLayerBlockRule) {
          atRules.push({ type: "layer", layerName: rule.name });
        } else if (rule instanceof content.CSSSupportsRule) {
          atRules.push({
            type: "support",
            conditionText: rule.conditionText,
          });
        } else if (rule instanceof content.CSSPropertyRule) {
          atRules.push({
            type: "property",
            propertyName: rule.name,
          });
        }

        if (rule.cssRules) {
          traverseRules(rule.cssRules);
        }
      }
    };
    traverseRules(stylesheet.cssRules);

    return { ruleCount, atRules };
  });

  return result;
}

function assertAtRules(atRules, expectedAtRules) {
  is(
    atRules.length,
    expectedAtRules.length,
    "Length of the atRules is correct"
  );

  for (let i = 0; i < atRules.length; i++) {
    const atRule = atRules[i];
    const expected = expectedAtRules[i];
    is(atRule.type, expected.type, "at-rule is of expected type");
    is(
      atRules[i].conditionText,
      expected.conditionText,
      "conditionText is correct"
    );
    if (expected.type === "media") {
      is(atRule.matches, expected.matches, "matches is correct");
    } else if (expected.type === "layer") {
      is(atRule.layerName, expected.layerName, "layerName is correct");
    } else if (expected.type === "property") {
      is(atRule.propertyName, expected.propertyName, "propertyName is correct");
    }

    if (expected.line !== undefined) {
      is(atRule.line, expected.line, "line is correct");
    }

    if (expected.column !== undefined) {
      is(atRule.column, expected.column, "column is correct");
    }
  }
}

async function assertResource(resource, expected) {
  is(
    resource.resourceType,
    ResourceCommand.TYPES.STYLESHEET,
    "Resource type is correct"
  );
  const styleText = (await getStyleSheetResourceText(resource)).trim();
  is(styleText, expected.styleText, "Style text is correct");
  is(resource.href, expected.href, "href is correct");
  is(resource.nodeHref, expected.nodeHref, "nodeHref is correct");
  is(resource.isNew, expected.isNew, "isNew is correct");
  is(resource.disabled, expected.disabled, "disabled is correct");
  is(resource.constructed, expected.constructed, "constructed is correct");
  is(resource.ruleCount, expected.ruleCount, "ruleCount is correct");
  assertAtRules(resource.atRules, expected.atRules);
}

function assertUpdate(update, expected) {
  is(
    update.resourceType,
    ResourceCommand.TYPES.STYLESHEET,
    "Resource type is correct"
  );
  is(update.resourceId, expected.resourceId, "resourceId is correct");
  is(update.updateType, expected.updateType, "updateType is correct");
  if (expected.event?.cause) {
    is(update.event?.cause, expected.event.cause, "cause is correct");
  }
}

function assertDestroyed(resource, expected) {
  is(
    resource.resourceType,
    ResourceCommand.TYPES.STYLESHEET,
    "Resource type is correct"
  );
  is(resource.resourceId, expected.resourceId, "resourceId is correct");
}

function getResourceTimingCount(tab) {
  return ContentTask.spawn(tab.linkedBrowser, [], () => {
    return content.performance.getEntriesByType("resource").length;
  });
}