22 Jan 2020

Dark & Light mode on Viewer

The dark mode is available since Windows 10 (May/19 update) and macOS Mojave 10.14. Many desktop & web apps are now adjusting the interface to it, like Outlook (for Mac) and Slack. I'm now using the macOS "Auto" appearance, which changes from light to dark according to the hour of the day (quite a nice reminder that is getting dark outside)

Then I was particularly surprised whenTwitter.com adjusted to it dynamically, so I decided to investigate how to detect it using JavaScript. After a couple of searches, it turned out to be very simple: window.matchMedia() function, supported by all modern browsers (see the list here).

But what about the Forge Viewer? In fact the viewer.setTheme() feature is available since version 4 (Feb 2018). Cool! Now we just need to connect the dots.

As usual, there are many ways to implement it, depending on how your code was designed. Just make sure to read the color scheme, adjust the viewer theme, and listen to the event to adjust it again (macOS allow "Auto" option).

// add this somewhere at your code
const media = window.matchMedia('(prefers-color-scheme: dark)');

// at some point where the viewer is already available, like onDocumentLoadSuccess callback, add this:
media.addListener(() => {
  viewer.setTheme((media.matches ? 'dark' : 'light') + '-theme'); // if it changes after load
viewer.setTheme((media.matches ? 'dark' : 'light') + '-theme'); // first time

For full support, your app needs to adjust the CSS styling accordingly. Luckily there are tons of articles for each framework, just do a quick search! 

Related Article