FriendsOfFlarum / nightmode

🌙 Turn off the lights!
https://discuss.flarum.org/d/21492-friendsofflarum-night-mode
MIT License
33 stars 22 forks source link

feat: dispatch event when setting the style #70

Closed n-peugnet closed 1 year ago

n-peugnet commented 1 year ago

Fixes #69

Changes proposed in this pull request:

This allows other extension to simply listen to 'fofnightmodechange' event on document to adapt to a theme change.

if (flarum.extensions['fof-nightmode']) {
  document.addEventListener('fofnightmodechange', (event) => {
    if (event.detail == 'day') {
      console.log('theme is light');
    } else {
      console.log('theme is dark');
    }
  });
}

From what I saw in the code, setStyle(type) is the function that gets call in the end by every theme switching function, so I choose to dispatch the event in this function. It is also convenient as the type variable already contains the style that will be applied so all we have to do is add it as the detail of the event.

Ideally I would have dispatched the event at the end of the function but due to the early return it was simpler to just dispatch it sooner. I can change this if you want. EDIT: done using a break statement with a labeled block.

Confirmed

P.S.

I didn't commit the changes of /js/dist to keep the patch simple.

P.S. 2

I can add a small example in the README once you are OK with the changes. EDIT: Done.

n-peugnet commented 1 year ago

By the way, by registering to the change of the prefers-color-scheme property in JS, this fixes en edge case with the "automatic" mode.

Demo of the bug

Notes:

We can see that before, when setting the mode to auto after it was set to something else, the theme does not automatically change when the prefers-color-scheme property change until the page is reloaded. Whereas after, it does instantly react to this change.

Before

Peek 2023-05-28 22-55

After

Peek 2023-05-28 22-52

n-peugnet commented 1 year ago

@FriendsOfFlarum I just pushed a new commit that adds an example in the README, some comments to clarify the choices I made and moved the event dispatching to the end of setStyle(). This pull request is now fully ready in my opinion.

Here is an example of what this allows me to do in my code highlight extension: https://github.com/club-1/flarum-ext-server-side-highlight/pull/8

n-peugnet commented 1 year ago

@imorland:

PS, Please can you run prettier and push the changes?

Done, I also fixed a comment and made the example in the README a little bit clearer by the way.