<!doctype html>
<title>@container: style queries parsing</title>
<link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-rule">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="support/cq-testcommon.js"></script>
<div style="container-name:name">
  <main id="main"></main>
</div>
<script>
  setup(() => assert_implements_container_queries());

  function cleanup_main() {
    while (main.firstChild)
      main.firstChild.remove();
  }

  function set_style(text) {
    let style = document.createElement('style');
    style.innerText = text;
    main.append(style);
    return style;
  }

  function test_rule_valid(query) {
    test(t => {
      t.add_cleanup(cleanup_main);
      let style = set_style(`@container ${query} {}`);
      assert_equals(style.sheet.rules.length, 1);
    }, query);
  }

  function test_condition_invalid(condition) {
    test(t => {
      t.add_cleanup(cleanup_main);
      let style = set_style(`@container name ${condition} {}`);
      assert_equals(style.sheet.rules.length, 0);
    }, condition);
  }

  // Tests that 1) the condition parses, and 2) is either "unknown" or not, as
  // specified.
  function test_condition_valid(condition, unknown) {
    test(t => {
      t.add_cleanup(cleanup_main);
      let style = set_style(`
        @container name ${condition} {}
        @container name (${condition}) or (not (${condition})) { main { --match:true; } }
      `);
      assert_equals(style.sheet.rules.length, 2);
      const expected = unknown ? '' : 'true';
      assert_equals(getComputedStyle(main).getPropertyValue('--match'), expected);
    }, condition);
  }

  function test_condition_known(condition) {
    test_condition_valid(condition, false /* unknown */);
  }

  function test_condition_unknown(condition) {
    test_condition_valid(condition, true /* unknown */);
  }

  test_condition_known('style(--my-prop: foo)');
  test_condition_known('style(--my-prop: foo - bar ())');
  test_condition_known('style(not ((--foo: calc(10px + 2em)) and ((--foo: url(x)))))');
  test_condition_known('style((--foo: bar) or (--bar: 10px))');
  test_condition_known('style(--my-prop:)');
  test_condition_known('style(--my-prop: )');
  test_condition_known('style(--foo: bar !important)');
  test_condition_known('style(--foo)');

  test_condition_unknown('style(--foo: bar;)');
  test_condition_unknown('style(style(--foo: bar))');
</script>
