4

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154

1 Answers1

7

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.

  1. Put the JavaScript code shown below into /frontend/prefers-color-scheme.js
  2. 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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Marcus Hellberg
  • 1,853
  • 10
  • 16
  • IntelliJ 2019.1 gives a warning on that `addListener` call, saying “Deprecated symbol used”. – Basil Bourque Dec 24 '19 at 03:56
  • 2
    Wow! That does work dynamically. On my first reading of your code, I did not understand that the listener is ongoing. So I gave it a try. I switched my Mac in macOS Mojave `System Preferences` > `General` > `Appearance`, and sure enough my Vaadin web app page switches to Light Mode or Dark Mode immediately alongside the native running apps. – Basil Bourque Dec 24 '19 at 04:43
  • See [this video screen clip](https://vimeo.com/381286135) demo of user switching Mac from Light to Dark Mode and back again, and the Vaadin web app changing automatically. – Basil Bourque Dec 24 '19 at 07:36