In this post, we will introduce Headspin UI Dark Theme API. Dark Theme API is a convenient set of functions that allow users to switch between dark and light modes.
Before diving into all the options that we could use, we should understand how dark/light mode logic operates. The hierarchy shown below is in cascade fashion, so each step later will take priority and override the step before.
Logic is following:
To recap two steps are logic to set the theme if the user didn’t set up the theme by clicking on toggle/dropdown. The third step will check if the user has some data stored in local storage and set the theme according to that data.
In the table below we have examples of events that we could use to make more modifications. Init event hooks run only once (initial theme setup after the page is loaded), while Update event hooks are client-side hooks to run before/after each change.
Event | Description | Runs |
theme:hook:beforeInit | Event that runs before the theme is established | Once |
theme:hook:afterInit | Event that runs after the theme is established | Once |
theme:hook:beforeUpdate | Event that runs before the theme setting occurs | Multiple |
theme:hook:afterUpdate | Event that runs before the theme setting occurs | Multiple |
Some usage examples are given below to use as boilerplate for custom logic:
window.addEventListener("theme:hook:beforeInit", function(e){
e = e || window.event;
console.log(e.datil);
})
window.addEventListener("theme:hook:afterInit", function(e){
e = e || window.event;
console.log(e.datil);
})
window.addEventListener("theme:hook:beforeUpdate", function(e){
e = e || window.event;
console.log(e.datil);
})
window.addEventListener("theme:hook:afterUpdate", function(e){
e = e || window.event;
console.log(e.datil);
})
There is also a real-time sync mechanism for multiple opened tabs in the same browser via Broadcast Channel API. In the example below you could use code to hook after the theme was changed, this method we are using for theme change across multiple tabs, if you need to extend further use the sample code below as a boilerplate.
const realtime = new BroadcastChannel("headspin_theme_channel");
realtime.onmessage = (event) => {
console.log(event.data);
};