[csswg-drafts] [mediaqueries-5] Script control of (prefers-*) queries (#6517)

tabatkins has just created a new issue for https://github.com/w3c/csswg-drafts:

== [mediaqueries-5] Script control of (prefers-*) queries ==
In [this Discourse thread](https://discourse.wicg.io/t/allow-browsers-extensions-and-sites-to-set-user-preference-media-queries/5493/4), jimmyfrasche requests the ability for pages to override the (prefers-*) MQs in script, so they can easily integrate a manual toggle in the page without having to do silly duplication of their styles in both an MQ *and* a selector.

My initial response was that custom MQs would solve this, but they're actually somewhat non-trivial to do.

The trivial solution of "just make a script-based custom MQ that initially defers to (prefers-color-scheme), and can be overridden to true/false if you manually toggle" means that if script doesn't load, you have an unknown `(--dark-mode)` MQ in your page that is just always false, so you apply light-mode styles even if the user normally wants dark mode.

Instead you *must* double-layer them:

```
<style>
@custom-media --dark-mode (prefers-color-scheme: dark);
/* use @media (--dark-mode) {...} for stuff */
</style>
<script>
/* Assuming that a JS registration overrides any existing CSS-based ones */
CSS.customMedias.set("--dark-mode", ...);
</script>
```

And this only works for boolean MQs. If they're multi-state, it's trickier; you have to set up distinct custom MQs for each of the states and override all of them in script.

Would it instead make sense to allow authors to override *at least* the (prefers-*) queries with `CSS.customMedias`, supplying a CSS value that's valid for the MQ in question? That way you could instead write:

```
<style>
@media (prefers-color-scheme: dark) {...}
/* always works */
</style>
<script>
/* override when manual toggle is engaged */
CSS.customMedias.set("prefers-color-scheme", ...);
</script>
```

(I don't see a particular reason to limit it to *only* the (prefers-*) queries, but nor do I see a reason to *allow* it for things like (width). I mildly lean towards allowing override of anything, just so we don't have to think about which ones are allowed and which aren't and keep that list up to date, but I could easily be convinced otherwise.)

Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/6517 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Friday, 13 August 2021 20:36:21 UTC