├── .babelrc
├── .editorconfig
├── .eslintrc.json
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── README.md
├── package-lock.json
├── package.json
├── src
├── index.js
└── use-isomorphic-layout-effect.js
└── test
├── index.test.js
├── mocks
├── index.js
└── window-match-media.js
└── util
└── hide-global-errors.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["@moxy/babel-preset/lib", { "react": true }]
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 | root = true
3 |
4 | [*]
5 | indent_style = space
6 | indent_size = 4
7 | end_of_line = lf
8 | charset = utf-8
9 | trim_trailing_whitespace = true
10 | insert_final_newline = true
11 |
12 | [package.json]
13 | indent_size = 2
14 |
15 | [{*.md,*.snap}]
16 | trim_trailing_whitespace = false
17 |
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "extends": [
4 | "@moxy/eslint-config/es9",
5 | "@moxy/eslint-config/addons/react",
6 | "@moxy/eslint-config/addons/jest",
7 | "@moxy/eslint-config/addons/babel-parser",
8 | "@moxy/eslint-config/addons/es-modules",
9 | "@moxy/eslint-config/addons/browser",
10 | "@moxy/eslint-config/addons/node"
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log*
3 | coverage
4 | lib/
5 | es/
6 | demo/build/
7 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "node"
4 | - "lts/*"
5 | # Report coverage
6 | after_success:
7 | - "npm i codecov"
8 | - "node_modules/.bin/codecov"
9 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ### [1.1.1](https://github.com/zebateira/react-use-system-theme/compare/v1.1.0...v1.1.1) (2020-02-04)
6 |
7 |
8 | ### Bug Fixes
9 |
10 | * suppress react warning "useLayoutEffect does nothing on the server" ([299b2dd](https://github.com/zebateira/react-use-system-theme/commit/299b2dd6f9dfd46d9bc8fbeadd9b91848ea4a98d))
11 |
12 | ## [1.1.0](https://github.com/zebateira/react-use-system-theme/compare/v1.0.4...v1.1.0) (2020-02-04)
13 |
14 |
15 | ### Features
16 |
17 | * support initialTheme value ([386fdcc](https://github.com/zebateira/react-use-system-theme/commit/386fdcce991558d0937a38670b8082910692dad6))
18 |
19 |
20 | ### Bug Fixes
21 |
22 | * use useLayoutEffect on setup to avoid re-render on ssr apps ([6196355](https://github.com/zebateira/react-use-system-theme/commit/6196355e7216ea7e0bb0e0be8f9d91f821c9e612))
23 |
24 | ### [1.0.4](https://github.com/zebateira/react-use-system-theme/compare/v1.0.3...v1.0.4) (2020-02-03)
25 |
26 |
27 | ### Bug Fixes
28 |
29 | * correct arguments on addListener and removeListener ([507f4a7](https://github.com/zebateira/react-use-system-theme/commit/507f4a741ee90665b5e2abc081a303c7447120a0))
30 |
31 | ### [1.0.3](https://github.com/zebateira/react-use-system-theme/compare/v1.0.2...v1.0.3) (2020-02-03)
32 |
33 |
34 | ### Bug Fixes
35 |
36 | * change MediaQueryList listener ([c277610](https://github.com/zebateira/react-use-system-theme/commit/c27761096e9059092a2632584f7ec1ebb82ef387))
37 |
38 |
39 | # 1.0.0 (2019-12-02)
40 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2019 Jose Bateira
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-use-system-theme
2 |
3 | [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url]
4 |
5 | [npm-url]:https://npmjs.org/package/react-use-system-theme
6 | [downloads-image]:https://img.shields.io/npm/dm/react-use-system-theme.svg
7 | [npm-image]:https://img.shields.io/npm/v/react-use-system-theme.svg
8 | [travis-url]:https://travis-ci.org/zebateira/react-use-system-theme
9 | [travis-image]:https://img.shields.io/travis/zebateira/react-use-system-theme/master.svg
10 | [codecov-url]:https://codecov.io/gh/zebateira/react-use-system-theme
11 | [codecov-image]:https://img.shields.io/codecov/c/github/zebateira/react-use-system-theme/master.svg
12 | [david-dm-url]:https://david-dm.org/zebateira/react-use-system-theme
13 | [david-dm-image]:https://img.shields.io/david/zebateira/react-use-system-theme.svg
14 | [david-dm-dev-url]:https://david-dm.org/zebateira/react-use-system-theme?type=dev
15 | [david-dm-dev-image]:https://img.shields.io/david/dev/zebateira/react-use-system-theme.svg
16 |
17 | A React Hook to get the system theme (OS theme: light or dark) based on `prefers-color-scheme`. Subscribes to changes as well.
18 |
19 | ```js
20 | import useSystemTheme from 'react-use-system-theme';
21 |
22 | function App() {
23 | const systemTheme = useSystemTheme('dark');
24 |
25 | return
26 | }
27 | ```
28 |
29 |
30 | 
31 |
32 |
33 | ## Install
34 |
35 | ```sh
36 | $ npm install react-use-system-theme
37 | ```
38 |
39 | This library is written in modern JavaScript and is published in both CommonJS and ES module transpiled variants. If you target older browsers please make sure to transpile accordingly.
40 |
41 | ## Usage
42 |
43 | **`useSystemTheme(initialTheme : Optional)` hook**:
44 |
45 | ```js
46 | import React from 'react';
47 | import { ThemeProvider } from 'styled-components';
48 | import useSystemTheme from 'react-use-system-theme';
49 |
50 | const theme = {
51 | light: {
52 | colors: {
53 | primary: '#fff'
54 | }
55 | },
56 | dark: {
57 | colors: {
58 | primary: '#000'
59 | }
60 | }
61 | }
62 |
63 | function App() {
64 | const systemTheme = useSystemTheme('dark');
65 |
66 | return (
67 |
68 | ...
69 |
70 | );
71 | }
72 | ```
73 |
74 | ### Values
75 |
76 | The values can be either `dark`, `light` or `null` if the system has no preference for the theme (or if `matchMedia` is not supported).
77 |
78 | ### SSR
79 |
80 | Value will be `null` or `initialTheme` if provided, so you can choose which default theme you want to use before we are able to detect the theme.
81 |
82 | ## Why do you need this?
83 |
84 | Initially, support for dark mode apps have been implemented by adding a simple toggle in some settings.
85 | Additionally, some apps have started to support another option "System Default": this is great because the user does not have to change all the apps theme constantly, instead, just change the system theme (mac/windows/linux/android/ios) in one place, and all the apps should change it's theme.
86 |
87 | This react hook allows get the currently active system theme and to also subscribe to the theme changes in order to allow the ui to update to the new theme.
88 |
89 | Usually, the CSS support for this using the media query `(prefers-color-scheme: light)` would be enough, but for `CSS-in-JS` solutions, you probably are getting the theme settings from a js object, so if we can simply use one theme object (`theme.light`/`theme.dark`) given the users system defined theme, we can make our styles simpler.
90 |
91 | **Disclaimer**: Browser support for [`prefers-color-scheme` is coming along really well](https://caniuse.com/#feat=prefers-color-scheme), but still, this is an experimental feature: use it wisely!
92 |
93 |
94 | ## Tests
95 |
96 | ```sh
97 | $ npm test
98 | $ npm test -- --watch # during development
99 | ```
100 |
101 |
102 | ## License
103 |
104 | Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php).
105 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-use-system-theme",
3 | "version": "1.1.1",
4 | "description": "React Hook to get the system theme (OS theme: light or dark) based on prefers-colors-scheme. Subscribes to changes as well.",
5 | "main": "lib/index.js",
6 | "module": "es/index.js",
7 | "homepage": "https://github.com/zebateira/react-use-system-theme#readme",
8 | "author": "Ze Bateira ",
9 | "license": "MIT",
10 | "repository": {
11 | "type": "git",
12 | "url": "git+https://github.com/zebateira/react-use-system-theme.git"
13 | },
14 | "keywords": [
15 | "react",
16 | "hook",
17 | "hooks",
18 | "theme",
19 | "theming",
20 | "prefers-colors-scheme",
21 | "dark-mode",
22 | "system",
23 | "auto-theme"
24 | ],
25 | "bugs": {
26 | "url": "https://github.com/zebateira/react-use-system-theme/issues"
27 | },
28 | "files": [
29 | "lib",
30 | "es"
31 | ],
32 | "scripts": {
33 | "build:commonjs": "BABEL_ENV=commonjs babel src -d lib --delete-dir-on-start",
34 | "build:es": "BABEL_ENV=es babel src -d es --delete-dir-on-start",
35 | "build": "npm run build:commonjs && npm run build:es",
36 | "test": "jest --coverage",
37 | "lint": "eslint --ignore-path .gitignore .",
38 | "prerelease": "npm t && npm run lint && npm run build",
39 | "release": "standard-version",
40 | "predeploy": "npm run build && cd demo && npm i && npm run build",
41 | "deploy": "gh-pages -d demo/build",
42 | "postrelease": "git push --follow-tags origin master && npm publish"
43 | },
44 | "jest": {
45 | "collectCoverageFrom": [
46 | "src/**/*"
47 | ]
48 | },
49 | "husky": {
50 | "hooks": {
51 | "pre-commit": "lint-staged",
52 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
53 | }
54 | },
55 | "lint-staged": {
56 | "*.js": [
57 | "eslint --fix",
58 | "git add"
59 | ]
60 | },
61 | "commitlint": {
62 | "extends": [
63 | "@commitlint/config-conventional"
64 | ]
65 | },
66 | "peerDependencies": {
67 | "react": "^16.12.0"
68 | },
69 | "devDependencies": {
70 | "@babel/cli": "^7.7.5",
71 | "@babel/core": "^7.7.5",
72 | "@commitlint/config-conventional": "^8.2.0",
73 | "@moxy/babel-preset": "^3.2.1",
74 | "@moxy/eslint-config": "^9.1.2",
75 | "@testing-library/react": "^9.3.3",
76 | "@testing-library/react-hooks": "^3.2.1",
77 | "babel-jest": "^24.9.0",
78 | "commitlint": "^8.2.0",
79 | "eslint": "^6.7.2",
80 | "gh-pages": "^2.1.1",
81 | "husky": "^3.1.0",
82 | "jest": "^24.9.0",
83 | "lint-staged": "^9.5.0",
84 | "react": "^16.12.0",
85 | "react-dom": "^16.12.0",
86 | "react-test-renderer": "^16.12.0",
87 | "standard-version": "^8.0.1"
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import { useState, useEffect } from 'react';
2 |
3 | import useLayoutEffect from './use-isomorphic-layout-effect';
4 |
5 | export const colorSchemes = {
6 | light: '(prefers-color-scheme: light)',
7 | dark: '(prefers-color-scheme: dark)',
8 | };
9 |
10 | function onThemeChange(callback) {
11 | return (event) => {
12 | if (!event || !event.matches) {
13 | return;
14 | }
15 |
16 | callback();
17 | };
18 | }
19 |
20 | export default function useSystemTheme(initialTheme) {
21 | const [theme, setTheme] = useState(initialTheme || null);
22 |
23 | useEffect(() => {
24 | // SSR or matchMedia not supported
25 | if (typeof window === 'undefined' || !window.matchMedia) {
26 | return;
27 | }
28 |
29 | const lightMatch = window.matchMedia(colorSchemes.light);
30 | const onLightMatches = onThemeChange(() => setTheme('light'));
31 |
32 | lightMatch.addListener(onLightMatches);
33 |
34 | const darkMatch = window.matchMedia(colorSchemes.dark);
35 | const onDarkMatches = onThemeChange(() => setTheme('dark'));
36 |
37 | darkMatch.addListener(onDarkMatches);
38 |
39 | return () => {
40 | lightMatch.removeListener(onLightMatches);
41 | darkMatch.removeListener(onDarkMatches);
42 | };
43 | }, []);
44 |
45 | useLayoutEffect(() => {
46 | // SSR or matchMedia not supported
47 | if (typeof window === 'undefined' || !window.matchMedia) {
48 | return;
49 | }
50 |
51 | if (window.matchMedia(colorSchemes.dark).matches && theme !== 'dark') {
52 | setTheme('dark');
53 | } else if (window.matchMedia(colorSchemes.light).matches && theme !== 'light') {
54 | setTheme('light');
55 | }
56 | }, [theme]);
57 |
58 | return theme;
59 | }
60 |
--------------------------------------------------------------------------------
/src/use-isomorphic-layout-effect.js:
--------------------------------------------------------------------------------
1 | import { useEffect, useLayoutEffect } from 'react';
2 |
3 | export default typeof window !== 'undefined' ? useLayoutEffect : useEffect;
4 |
--------------------------------------------------------------------------------
/test/index.test.js:
--------------------------------------------------------------------------------
1 | import { renderHook } from '@testing-library/react-hooks';
2 |
3 | import useSystemTheme from '../src';
4 | import mocks from './mocks';
5 | import hideGlobalErrors from './util/hide-global-errors';
6 |
7 | beforeEach(() => {
8 | // Hide "An update to null inside a test was not wrapped in act(...)" error
9 | // This won't be needed in react-dom@^16.9.0 because `act()` will support promises
10 | // See: https://github.com/facebook/react/issues/14769#issuecomment-479592338
11 | hideGlobalErrors();
12 | });
13 |
14 | it('should not initialize if window.matchMedia is not available', () => {
15 | window.matchMedia = null;
16 |
17 | const { result } = renderHook(() => useSystemTheme());
18 |
19 | expect(result.current).toBe(null);
20 | });
21 |
22 | it('should not initialize if it\'s SSR', () => {
23 | global.window = null;
24 |
25 | const { result } = renderHook(() => useSystemTheme());
26 |
27 | expect(result.current).toBe(null);
28 | });
29 |
30 | it('should initialize with the provided initial value if it\'s SSR', () => {
31 | global.window = null;
32 |
33 | const { result } = renderHook(() => useSystemTheme('light'));
34 |
35 | expect(result.current).toBe('light');
36 | });
37 |
38 | it('should initialize with the provided initial value if window.matchMedia is not supported', () => {
39 | window.matchMedia = null;
40 |
41 | const { result } = renderHook(() => useSystemTheme('dark'));
42 |
43 | expect(result.current).toBe('dark');
44 | });
45 |
46 | it('should initialize with the current system theme', () => {
47 | const windowMatchMediaMock = mocks.windowMatchMedia();
48 |
49 | window.matchMedia = windowMatchMediaMock.mock('light');
50 |
51 | const { result } = renderHook(() => useSystemTheme());
52 |
53 | expect(result.current).toBe('light');
54 |
55 | window.matchMedia = windowMatchMediaMock.mock('dark');
56 |
57 | const { result: result2 } = renderHook(() => useSystemTheme());
58 |
59 | expect(result2.current).toBe('dark');
60 | });
61 |
62 | it('should return the new system theme if it changes', () => {
63 | const windowMatchMediaMock = mocks.windowMatchMedia();
64 |
65 | window.matchMedia = windowMatchMediaMock.mock('no-preferance');
66 |
67 | const { result } = renderHook(() => useSystemTheme());
68 |
69 | expect(result.current).toBe(null);
70 |
71 | window.matchMedia = windowMatchMediaMock.mock('dark');
72 | windowMatchMediaMock.triggerOnChangeEvent('dark');
73 |
74 | expect(result.current).toBe('dark');
75 |
76 | window.matchMedia = windowMatchMediaMock.mock('light');
77 | windowMatchMediaMock.triggerOnChangeEvent('light');
78 |
79 | expect(result.current).toBe('light');
80 | });
81 |
--------------------------------------------------------------------------------
/test/mocks/index.js:
--------------------------------------------------------------------------------
1 | import windowMatchMedia from './window-match-media.js';
2 |
3 | export default {
4 | windowMatchMedia,
5 | };
6 |
--------------------------------------------------------------------------------
/test/mocks/window-match-media.js:
--------------------------------------------------------------------------------
1 | export default function windowMatchMedia() {
2 | const listeners = [];
3 |
4 | return {
5 | listeners,
6 | mock: (theme) => (query) => ({
7 | matches: query === `(prefers-color-scheme: ${theme})`,
8 | addListener: (listener) => listeners.push({ listener, query }),
9 | removeListener: (listenerToRemove) => listeners.filter(({ listener }) => listener !== listenerToRemove),
10 | }),
11 | triggerOnChangeEvent: (newTheme) => {
12 | listeners.forEach(({ listener, query }) => listener({ matches: query === `(prefers-color-scheme: ${newTheme})` }));
13 | },
14 | };
15 | }
16 |
--------------------------------------------------------------------------------
/test/util/hide-global-errors.js:
--------------------------------------------------------------------------------
1 | let cleanup;
2 |
3 | afterEach(() => {
4 | if (cleanup) {
5 | cleanup();
6 | cleanup = undefined;
7 | }
8 | });
9 |
10 | const hideGlobalErrors = () => {
11 | if (cleanup) {
12 | return;
13 | }
14 |
15 | const originalConsoleError = console.error;
16 | const globalWindowErrorHandler = (event) => event.preventDefault();
17 |
18 | console.error = jest.fn();
19 | window.addEventListener('error', globalWindowErrorHandler);
20 |
21 | cleanup = () => {
22 | console.error = originalConsoleError;
23 | window.removeEventListener('error', globalWindowErrorHandler);
24 | };
25 | };
26 |
27 | export default hideGlobalErrors;
28 |
--------------------------------------------------------------------------------