Vaadin Flow app switch between light and dark modes automatically

ⅰ亾dé卋堺 提交于 2020-01-01 06:52:10

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/59462273/vaadin-flow-app-switch-between-light-and-dark-modes-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!