Re: [csswg-drafts] [cssom] Implement CSSStyleRule.p.matches (#3670)

I think that makes sense, but some questions:

 * What should happen when the element given lives in another document? Should media queries be evaluated in the element's document? Or in the stylesheet's document? Or the current global's document? All three may be different and have different viewports, etc.
 * Should it account for the StyleSheet's `media` attribute? `disabled` too, maybe? What about if it's an alternate sheet? Or an `@import`-ed sheet?

So if I understand correctly the way to do it right now would be something like:

```js
function singleRuleMatches(rule: CSSRule, element: Element) {
  if (rule instanceof CSSStyleRule)
    return element.matches(rule.selectorText);
  if (!rule instanceof CSSConditionRule)
    return true;
  if (rule instanceof CSSMediaRule)
    return window.matchMedia(rule.conditionText).matches;
  if (rule instanceof CSSSupportsRule)
    return CSS.supports(rule.conditionText);
  throw "Unknown condition rule?";
}

function singleSheetMatches(sheet: StyleSheet, element: Element) {
  if (sheet.disabled)
    return false;
  if (!window.matchMedia(Array.from(sheet.media).join(",")).matches)
    return false;
  return true;
}

function ruleMatchesElement(rule: CSSRule, element: Element) {
  for (let r = rule; r; r = r.parentRule)
    if (!singleRuleMatches(r, element))
      return false;
  for (let s = rule.parentSyleSheet; s; s = s.parentStyleSheet)
    if (!singleSheetMatches(s, element))
      return false;
  return true;
}
```

Is that right? A bit of a simpler approach would be to add something like `CSSConditionRule.prototype.matches(document)` or something, that'd avoid the questions at least. Though you'd need to still check for stylesheets and such manually...

-- 
GitHub Notification of comment by emilio
Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/3670#issuecomment-466807389 using your GitHub account

Received on Sunday, 24 February 2019 19:19:01 UTC