Skip to content

Commit ee2e8c4

Browse files
committed
Enhance init to allow a similar style to overreacted.io
1 parent 7ace6fa commit ee2e8c4

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,29 @@ var nightwind = {
295295

296296
</details>
297297

298+
<details>
299+
<summary>Gastby (similar to <a href="https://overreacted.io/">overreacted.io</a>)</summary>
300+
301+
* The library adds a `window.__theme` which keeps track of current theme (i.e., `light` or `dark`).
302+
* You can override the `window.__onThemeChange` function to be notified when the theme changes
303+
304+
#### Layout.js
305+
306+
```js
307+
class Layout extends React.Component {
308+
state = {
309+
theme: null,
310+
};
311+
componentDidMount() {
312+
this.setState({ theme: window.__theme });
313+
window.__onThemeChange = () => {
314+
this.setState({ theme: window.__theme });
315+
};
316+
}
317+
}
318+
```
319+
</details>
320+
298321

299322
## Getting started
300323

helper.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ module.exports = {
22
init: () => {
33
const codeToRunOnClient = `
44
(function() {
5+
window.__onThemeChange = function() {};
56
function getInitialColorMode() {
67
const persistedColorPreference = window.localStorage.getItem('nightwind-mode');
78
const hasPersistedPreference = typeof persistedColorPreference === 'string';
@@ -15,12 +16,13 @@ module.exports = {
1516
}
1617
return 'light';
1718
}
19+
window.__theme = getInitialColorMode();
1820
getInitialColorMode() == 'light' ? document.documentElement.classList.remove('dark') : document.documentElement.classList.add('dark');
1921
})()
2022
`;
2123
return codeToRunOnClient;
2224
},
23-
25+
2426
beforeTransition: () => {
2527
const doc = document.documentElement;
2628
const onTransitionDone = () => {
@@ -38,12 +40,16 @@ module.exports = {
3840
if (!document.documentElement.classList.contains('dark')) {
3941
document.documentElement.classList.add('dark');
4042
window.localStorage.setItem('nightwind-mode', 'dark');
43+
window.__theme = 'dark';
44+
window.__onThemeChange();
4145
} else {
4246
document.documentElement.classList.remove('dark');
4347
window.localStorage.setItem('nightwind-mode', 'light');
48+
window.__theme = 'light';
49+
window.__onThemeChange();
4450
}
4551
},
46-
52+
4753
enable: (dark) => {
4854
const mode = dark ? "dark" : "light";
4955
const opposite = dark ? "light" : "dark";
@@ -55,6 +61,8 @@ module.exports = {
5561
}
5662
document.documentElement.classList.add(mode);
5763
window.localStorage.setItem('nightwind-mode', mode);
64+
window.__theme = mode;
65+
window.__onThemeChange();
5866
},
5967

6068
// Old

0 commit comments

Comments
 (0)