<!DOCTYPE HTML>
<meta charset="UTF-8">
<title>CSS Toggles: CSSToggle and CSSToggleMap API</title>
<link rel="author" title="L. David Baron" href="https://dbaron.org/">
<link rel="author" title="Google" href="http://www.google.com/">
<link rel="help" href="https://tabatkins.github.io/css-toggle/#csstoggleevent">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="support/toggle-helpers.js"></script>

<div id="test"></div>

<script>

let container = document.getElementById("test");

function click_while_waiting_for_togglechange(event_watcher, element) {
  let p = event_watcher.wait_for("togglechange");
  element.click();
  return p;
}

promise_test(async test => {
  container.innerHTML = `
    <div id="element" style="toggle: mytoggle 2 at 1 self sticky"></div>
  `;
  const element = document.getElementById("element");

  await wait_for_toggle_creation(element);
  let toggle = element.toggles.get("mytoggle");

  assert_equals(toggle.value, 1, "initial value of toggle");

  const watcher = new EventWatcher(test, element, [ "togglechange" ]);

  await click_while_waiting_for_togglechange(watcher, element).then(ev => {
    assert_equals(Object.getPrototypeOf(ev), CSSToggleEvent.prototype);
    assert_equals(ev.toggleName, "mytoggle", "event.toggleName after first change");
    assert_equals(ev.toggle, toggle, "event.toggle after first change");
    assert_equals(toggle.value, 2, "value after first change");
  });

  // Test that the event does not fire when the toggle doesn't change due to
  // being "sticky" and stuck.  EventWatcher will assert if there is an event.
  element.click();
  assert_equals(toggle.value, 2, "value after second change");

  toggle.value = 0;
  // there should be no event; EventWatcher will assert if there is one.
}, "basic toggle event firing");

</script>
