Q:

Vaadin Flow app switch between light and dark modes automatically

Vaadin Flow 14 ships with light and dark versions of its two bundled themes, Lumo and Material. 
And now browsers can ask the host OS for the user’s preference for light or dark modes. 
Is there a way to have a Vaadin app automatically use the light or dark theme variant per the user’s wishes? 
Marcus Hellberg wrote a helpful post on how to switch light/dark mode theme variants programmatically.  I am wondering if Vaadin 14 might be able to switch automatically now that the user preference is detectable from within the browser.  
If not, perhaps Someone could show Java code for inquiring about the user’s preference from server-side Java code.  

A:

You can use window.matchMedia API to listen for changes to the prefers-color-scheme media query standardized in Media Queries Level 5.  See CanIUse.com for browser support. 
That CSS media feature of color scheme preference has 3 possible values: no-preference, light, and dark.  The code below looks for a match on dark.  

Put the JavaScript code shown below into /frontend/prefers-color-scheme.js
On your main view, add the annotation @JsModule("prefers-color-scheme.js")

let mm = window.matchMedia('(prefers-color-scheme: dark)');
function apply() {
    document.documentElement.setAttribute("theme",mm.matches?"dark":"");
}
mm.addListener(apply);
apply();

Source: https://gist.github.com/emarc/690eb2659c8b51cb895716914d65ec19

