Skip to content

Commit

Permalink
React on prefers-color-scheme changes
Browse files Browse the repository at this point in the history
  • Loading branch information
tomayac committed Aug 6, 2019
1 parent cbf4883 commit acfc612
Show file tree
Hide file tree
Showing 3 changed files with 199 additions and 8 deletions.
190 changes: 186 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dark-mode-toggle",
"version": "0.2.0",
"version": "0.2.1",
"description": "Web Component that toggles dark mode 🌒",
"main": "./src/dark-mode-toggle.mjs",
"browser": "src/dark-mode-toggle.mjs",
Expand All @@ -11,6 +11,7 @@
"dist"
],
"scripts": {
"start": "npx http-server && echo \"Server running on http://localhost:8080/demo/\"",
"clean": "rm -rf ./dist && mkdir dist",
"lint:js": "npx eslint './src/*.mjs' --fix && npx eslint './demo/*.mjs' --fix",
"lint:css": "cp ./src/dark-mode-toggle.mjs ./src/dark-mode-toggle.html && npx stylelint './src/*.html' --fix && cp ./src/dark-mode-toggle.html ./src/dark-mode-toggle.mjs && rm ./src/dark-mode-toggle.html && npx stylelint './demo/*.css' --fix",
Expand All @@ -35,9 +36,10 @@
"devDependencies": {
"eslint": "^6.1.0",
"eslint-config-google": "^0.13.0",
"http-server": "^0.11.1",
"stylelint": "^10.1.0",
"stylelint-config-standard": "^18.3.0",
"terser": "^4.1.2"
"terser": "^4.1.3"
},
"eslintConfig": {
"parserOptions": {
Expand Down Expand Up @@ -75,6 +77,5 @@
}
]
}
},
"dependencies": {}
}
}
8 changes: 8 additions & 0 deletions src/dark-mode-toggle.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,14 @@ export class DarkModeToogle extends HTMLElement {
// Does the browser support native `prefers-color-scheme`?
const hasNativePrefersColorScheme =
win.matchMedia('(prefers-color-scheme)').media !== 'not all';
// Listen to `prefers-color-scheme` changes, unless `permanent` is true.
if (hasNativePrefersColorScheme) {
win.matchMedia(MQ_DARK).addListener(({matches}) => {
if (!this.permanent) {
this.mode = matches ? DARK : LIGHT;
}
});
}
// Set initial state, giving preference to a remembered value, then the
// native value (if supported), and eventually defaulting to a light
// experience.
Expand Down

0 comments on commit acfc612

Please sign in to comment.