├── example ├── .npmignore ├── .htmlnanorc ├── static │ ├── light.css │ └── dark.css ├── tsconfig.json ├── index.html ├── package.json └── index.tsx ├── .gitignore ├── .eslintrc.js ├── .github └── workflows │ └── main.yml ├── tsconfig.json ├── LICENSE ├── src ├── utils.ts └── index.tsx ├── package.json ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md ├── README.md └── test └── index.test.tsx /example/.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .cache 3 | dist -------------------------------------------------------------------------------- /example/.htmlnanorc: -------------------------------------------------------------------------------- 1 | { 2 | "removeComments": false 3 | } -------------------------------------------------------------------------------- /example/static/light.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: aliceblue; 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | node_modules 4 | .cache 5 | dist 6 | coverage 7 | -------------------------------------------------------------------------------- /example/static/dark.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #303030; 3 | color: white; 4 | } 5 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "extends": [ 3 | "react-app", 4 | "prettier/@typescript-eslint", 5 | "plugin:prettier/recommended" 6 | ], 7 | "settings": { 8 | "react": { 9 | "version": "detect" 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Install, test and upload to CodeCov 2 | on: [push, pull_request] 3 | jobs: 4 | run: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@master 8 | - name: Install Modules 9 | run: yarn 10 | - name: Run tests 11 | run: yarn test 12 | - name: Upload coverage to Codecov 13 | uses: codecov/codecov-action@v1 14 | with: 15 | flags: unittest 16 | name: codecov-1 17 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": false, 4 | "target": "es5", 5 | "module": "commonjs", 6 | "jsx": "react", 7 | "moduleResolution": "node", 8 | "noImplicitAny": false, 9 | "noUnusedLocals": false, 10 | "noUnusedParameters": false, 11 | "removeComments": true, 12 | "strictNullChecks": true, 13 | "preserveConstEnums": true, 14 | "sourceMap": true, 15 | "lib": ["es2015", "es2016", "dom"], 16 | "baseUrl": ".", 17 | "types": ["node"] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src", "types"], 3 | "compilerOptions": { 4 | "module": "esnext", 5 | "lib": ["dom", "esnext"], 6 | "importHelpers": true, 7 | "declaration": true, 8 | "sourceMap": true, 9 | "rootDir": "./src", 10 | "strict": true, 11 | "noUnusedLocals": true, 12 | "noUnusedParameters": true, 13 | "noImplicitReturns": true, 14 | "noFallthroughCasesInSwitch": true, 15 | "moduleResolution": "node", 16 | "baseUrl": "./", 17 | "paths": { 18 | "*": ["src/*", "node_modules/*"] 19 | }, 20 | "jsx": "react", 21 | "esModuleInterop": true 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 18 | 19 | 20 | Playground 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "license": "MIT", 6 | "scripts": { 7 | "start": "parcel index.html", 8 | "build": "parcel build index.html" 9 | }, 10 | "dependencies": { 11 | "react-app-polyfill": "^1.0.0", 12 | "react-switch": "^5.0.1" 13 | }, 14 | "alias": { 15 | "react": "../node_modules/react", 16 | "react-dom": "../node_modules/react-dom/profiling", 17 | "scheduler/tracing": "../node_modules/scheduler/tracing-profiling" 18 | }, 19 | "devDependencies": { 20 | "@types/react": "^16.9.56", 21 | "@types/react-dom": "^16.9.9", 22 | "parcel": "^1.12.4", 23 | "parcel-plugin-static-files-copy": "^2.5.0", 24 | "typescript": "^4.0.5" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Jfelix61 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 all 13 | 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 THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | export function findCommentNode(comment: string) { 2 | const head = document.head; 3 | for (let i = 0; i < head.childNodes.length; i++) { 4 | const node = head.childNodes[i]; 5 | if (node.nodeType === 8 && node?.nodeValue?.trim() === comment) { 6 | return node; 7 | } 8 | } 9 | return null; 10 | } 11 | 12 | export function isElement(o: any): Boolean { 13 | return typeof HTMLElement === 'object' 14 | ? o instanceof HTMLElement //DOM2 15 | : o && 16 | typeof o === 'object' && 17 | o !== null && 18 | o.nodeType === 1 && 19 | typeof o.nodeName === 'string'; 20 | } 21 | 22 | export function arrayToObject(array: string[]): Record { 23 | const obj: Record = {}; 24 | array.forEach(el => (obj[el] = el)); 25 | return obj; 26 | } 27 | 28 | export function createLinkElement(attributes: Record) { 29 | const linkElement = document.createElement('link'); 30 | 31 | for (const [attribute, value] of Object.entries(attributes)) { 32 | if (attribute === 'onload') { 33 | linkElement.onload = attributes.onload; 34 | continue; 35 | } 36 | 37 | // @ts-ignore 38 | linkElement[attribute] = value; 39 | } 40 | 41 | return linkElement; 42 | } 43 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-css-theme-switcher", 3 | "description": "Switch between CSS themes using React", 4 | "version": "0.3.0", 5 | "license": "MIT", 6 | "main": "dist/index.js", 7 | "typings": "dist/index.d.ts", 8 | "files": [ 9 | "dist", 10 | "src" 11 | ], 12 | "engines": { 13 | "node": ">=10" 14 | }, 15 | "scripts": { 16 | "start": "tsdx watch", 17 | "build": "tsdx build", 18 | "test": "is-ci test:coverage test:watch", 19 | "test:watch": "tsdx test --watch", 20 | "test:coverage": "tsdx test --coverage", 21 | "lint": "tsdx lint", 22 | "prepare": "tsdx build" 23 | }, 24 | "keywords": [ 25 | "react", 26 | "ui", 27 | "themes", 28 | "switcher", 29 | "css" 30 | ], 31 | "husky": { 32 | "hooks": { 33 | "pre-commit": "tsdx lint" 34 | } 35 | }, 36 | "prettier": { 37 | "printWidth": 80, 38 | "semi": true, 39 | "singleQuote": true, 40 | "trailingComma": "es5" 41 | }, 42 | "author": "Jose R. Felix (https://jfelix.info)", 43 | "module": "dist/react-css-theme-switcher.esm.js", 44 | "repository": { 45 | "type": "git", 46 | "url": "https://github.com/JoseRFelix/react-css-theme-switcher" 47 | }, 48 | "bugs": { 49 | "url": "https://github.com/JoseRFelix/react-css-theme-switcher/issues" 50 | }, 51 | "homepage": "https://github.com/JoseRFelix/react-css-theme-switcher#readme", 52 | "peerDependencies": { 53 | "react": ">=16" 54 | }, 55 | "devDependencies": { 56 | "@testing-library/react-hooks": "^6.0.0", 57 | "@types/react": "^17.0.6", 58 | "@types/react-dom": "^17.0.5", 59 | "husky": "^4.3.6", 60 | "is-ci-cli": "^2.2.0", 61 | "react": "^17.0.2", 62 | "react-dom": "^17.0.2", 63 | "react-test-renderer": "^17.0.2", 64 | "tsdx": "^0.14.1", 65 | "tslib": "^2.2.0", 66 | "typescript": "^4.2.4" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thanks for being willing to contribute! 4 | 5 | **Working on your first Pull Request?** You can learn how from this _free_ series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github) 6 | 7 | ## Project setup 8 | 9 | 1. Fork and clone the repo 10 | 2. Run `npm install` to install dependencies and run validation 11 | 3. Create a branch for your PR with `git checkout -b pr/your-branch-name` 12 | 13 | > Tip: Keep your `master` branch pointing at the original repository and make 14 | > pull requests from branches on your fork. To do this, run: 15 | > 16 | > ``` 17 | > git remote add upstream https://github.com/testing-library/react-testing-library.git 18 | > git fetch upstream 19 | > git branch --set-upstream-to=upstream/master master 20 | > ``` 21 | > 22 | > This will add the original repository as a "remote" called "upstream," Then 23 | > fetch the git information from that remote, then set your local `master` 24 | > branch to use the upstream master branch whenever you run `git pull`. Then you 25 | > can make all of your pull request branches based on this `master` branch. 26 | > Whenever you want to update your version of `master`, do a regular `git pull`. 27 | 28 | ## Committing and Pushing changes 29 | 30 | Please make sure to run the tests before you commit your changes with `npm run test`. Make sure to include snapshot changes (if they exist) in your commit. 31 | 32 | ### Update Typings 33 | 34 | If your PR introduced some changes in the API, you are more than welcome to 35 | modify the Typescript type definition to reflect those changes. If you have never seen Typescript 36 | definitions before, you can read more about it in its 37 | [documentation pages](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). 38 | 39 | ## Help needed 40 | 41 | Please checkout the [the open issues][issues] 42 | 43 | Also, please watch the repo and respond to questions/bug reports/feature 44 | requests! Thanks! 45 | -------------------------------------------------------------------------------- /example/index.tsx: -------------------------------------------------------------------------------- 1 | import 'react-app-polyfill/ie11'; 2 | import * as React from 'react'; 3 | import * as ReactDOM from 'react-dom'; 4 | import Switch from 'react-switch'; 5 | 6 | import { ThemeSwitcherProvider, useThemeSwitcher } from '../.'; 7 | 8 | const Component = () => { 9 | const { switcher, themes, currentTheme, status } = useThemeSwitcher(); 10 | const [isDarkMode, setIsDarkMode] = React.useState(true); 11 | 12 | if (status === 'loading') { 13 | return
Loading styles...
; 14 | } 15 | 16 | const toggleDarkMode = checked => { 17 | switcher({ theme: checked ? themes.dark : themes.light }); 18 | setIsDarkMode(checked); 19 | }; 20 | 21 | return ( 22 |
31 |

36 | Toggle dark mode 37 |

38 |

Current theme: {currentTheme}

39 | 40 | 52 | 🌞 53 |
54 | } 55 | checkedIcon={ 56 |
66 | 🌑 67 |
68 | } 69 | onColor="#4d4d4d" 70 | onChange={toggleDarkMode} 71 | checked={isDarkMode} 72 | /> 73 | 74 | ); 75 | }; 76 | 77 | const themes = { 78 | light: './light.css', 79 | dark: './dark.css', 80 | }; 81 | 82 | const App = () => { 83 | return ( 84 | 89 | 90 | 91 | ); 92 | }; 93 | 94 | ReactDOM.render(, document.getElementById('root')); 95 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at jfelx@outlook.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { 3 | findCommentNode, 4 | arrayToObject, 5 | createLinkElement, 6 | isElement, 7 | } from './utils'; 8 | 9 | enum Status { 10 | idle = 'idle', 11 | loading = 'loading', 12 | loaded = 'loaded', 13 | } 14 | 15 | interface IThemeSwitcherContext { 16 | currentTheme: string | undefined; 17 | themes: Record; 18 | switcher: ({ theme }: { theme: string }) => void; 19 | status: Status; 20 | } 21 | 22 | const ThemeSwitcherContext = React.createContext< 23 | IThemeSwitcherContext | undefined 24 | >(undefined); 25 | 26 | interface Props { 27 | themeMap: Record; 28 | children?: React.ReactNode; 29 | insertionPoint?: string | HTMLElement | null; 30 | id?: string; 31 | defaultTheme?: string; 32 | attr?: string; 33 | } 34 | 35 | export function ThemeSwitcherProvider({ 36 | themeMap, 37 | insertionPoint, 38 | defaultTheme, 39 | id = 'current-theme-style', 40 | attr = 'data-theme', 41 | ...rest 42 | }: Props) { 43 | const [status, setStatus] = React.useState(Status.idle); 44 | const [currentTheme, setCurrentTheme] = React.useState(); 45 | 46 | const insertStyle = React.useCallback( 47 | (linkElement: HTMLElement): HTMLElement | void => { 48 | if (insertionPoint || insertionPoint === null) { 49 | const insertionPointElement = isElement(insertionPoint) 50 | ? (insertionPoint as HTMLElement) 51 | : findCommentNode(insertionPoint as string); 52 | 53 | if (!insertionPointElement) { 54 | console.warn( 55 | `Insertion point '${insertionPoint}' does not exist. Be sure to add comment on head and that it matches the insertionPoint` 56 | ); 57 | return document.head.appendChild(linkElement); 58 | } 59 | 60 | const { parentNode } = insertionPointElement; 61 | if (parentNode) { 62 | return parentNode.insertBefore( 63 | linkElement, 64 | insertionPointElement.nextSibling 65 | ); 66 | } 67 | } else { 68 | return document.head.appendChild(linkElement); 69 | } 70 | }, 71 | [insertionPoint] 72 | ); 73 | 74 | const switcher = React.useCallback( 75 | ({ theme }: { theme: string }) => { 76 | if (theme === currentTheme) return; 77 | 78 | if (themeMap[theme]) { 79 | setStatus(Status.loading); 80 | 81 | const linkElement = createLinkElement({ 82 | type: 'text/css', 83 | rel: 'stylesheet', 84 | id: id + '_temp', 85 | href: themeMap[theme], 86 | onload: () => { 87 | const previousStyle = document.getElementById(id); 88 | if (previousStyle) { 89 | previousStyle.remove(); 90 | } 91 | 92 | const nextStyle = document.getElementById(id + '_temp'); 93 | if (nextStyle) { 94 | nextStyle.setAttribute('id', id); 95 | } 96 | setStatus(Status.loaded); 97 | }, 98 | }); 99 | 100 | insertStyle(linkElement); 101 | setCurrentTheme(theme); 102 | } else { 103 | return console.warn('Could not find specified theme'); 104 | } 105 | 106 | document.body.setAttribute(attr, theme); 107 | }, 108 | [themeMap, insertStyle, attr, id, currentTheme] 109 | ); 110 | 111 | React.useEffect(() => { 112 | if (defaultTheme) { 113 | switcher({ theme: defaultTheme }); 114 | } 115 | // eslint-disable-next-line react-hooks/exhaustive-deps 116 | }, [defaultTheme]); 117 | 118 | React.useEffect(() => { 119 | const themes = Object.keys(themeMap); 120 | 121 | themes.map(theme => { 122 | const themeAssetId = `theme-prefetch-${theme}`; 123 | if (!document.getElementById(themeAssetId)) { 124 | const stylePrefetch = document.createElement('link'); 125 | stylePrefetch.rel = 'prefetch'; 126 | stylePrefetch.type = 'text/css'; 127 | stylePrefetch.id = themeAssetId; 128 | stylePrefetch.href = themeMap[theme]; 129 | 130 | insertStyle(stylePrefetch); 131 | } 132 | return ''; 133 | }); 134 | }, [themeMap, insertStyle]); 135 | 136 | const value = React.useMemo( 137 | () => ({ 138 | switcher, 139 | status, 140 | currentTheme, 141 | themes: arrayToObject(Object.keys(themeMap)), 142 | }), 143 | [switcher, status, currentTheme, themeMap] 144 | ); 145 | 146 | return ; 147 | } 148 | 149 | export function useThemeSwitcher() { 150 | const context = React.useContext(ThemeSwitcherContext); 151 | if (!context) { 152 | throw new Error( 153 | 'To use `useThemeSwitcher`, component must be within a ThemeSwitcherProvider' 154 | ); 155 | } 156 | return context; 157 | } 158 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

React CSS Theme Switcher

3 |
4 |

5 | 6 | Version 7 | 8 | 9 | 10 | License: MIT 11 | 12 | 13 | codecov 14 | 15 | 16 | PRs Welcome 17 | 18 | Bundle size 19 | 20 |

21 | 22 | > 💫 Switch between CSS themes using React 23 | 24 | ## Prerequisites 25 | 26 | - node >=10 27 | 28 | ## Installation 29 | 30 | ```shell 31 | npm i react-css-theme-switcher 32 | ``` 33 | 34 | or with Yarn: 35 | 36 | ```shell 37 | yarn add react-css-theme-switcher 38 | ``` 39 | 40 | ## Usage 41 | 42 | Import ThemeSwitcherProvider and pass a theme object with the names of the themes and their respective paths to the CSS stylesheet (normally, public folder). 43 | 44 | ```jsx 45 | import React from 'react'; 46 | import ReactDOM from 'react-dom'; 47 | 48 | import { ThemeSwitcherProvider } from 'react-css-theme-switcher'; 49 | 50 | const themes = { 51 | light: 'public/light.css', 52 | dark: 'public/dark.css', 53 | }; 54 | 55 | const App = () => { 56 | return ( 57 | 58 | 59 | 60 | ); 61 | }; 62 | ``` 63 | 64 | Use `useThemeSwitcher` Hook: 65 | 66 | ```jsx 67 | import { useThemeSwitcher } from 'react-css-theme-switcher'; 68 | 69 | const Component = () => { 70 | const { switcher, themes, currentTheme, status } = useThemeSwitcher(); 71 | const [isDarkMode, setIsDarkMode] = React.useState(false); 72 | 73 | if (status === 'loading') { 74 | return
Loading styles...
; 75 | } 76 | 77 | const toggleDarkMode = () => { 78 | setIsDarkMode(previous => { 79 | switcher({ theme: previous ? themes.light : themes.dark }); 80 | return !previous; 81 | }); 82 | }; 83 | 84 | return ( 85 |
86 |

Current theme: {currentTheme}

87 |
89 | ); 90 | }; 91 | ``` 92 | 93 | ### CSS Injection Order 94 | 95 | react-css-theme-switcher provides a way to avoid collision with other stylesheets or appended styles by providing where to inject the styles. To achieve this, add an HTML comment like `` somewhere on the head and then provide `'inject-styles-here'` or your custom name in the insertionPoint prop in `ThemeSwitcherProvider`. 96 | 97 | ```html 98 | 99 | 100 | 101 | 112 | 113 | Playground 114 | 115 | 116 | 117 |
118 | 119 | 120 | ``` 121 | 122 | ```jsx 123 | const App = () => { 124 | return ( 125 | 130 | 131 | 132 | ); 133 | }; 134 | ``` 135 | 136 | ### HTML Element Insertion Point 137 | 138 | Some libraries and frameworks make it hard to use comments in head for handling injection order. To solve this issue, you can provide a DOM element as the insertion point. Take for example a `` element: 139 | 140 | ```html 141 | 142 | 143 | 144 | 155 | 156 | 157 | Playground 158 | 159 | 160 | 161 |
162 | 163 | 164 | ``` 165 | 166 | ```jsx 167 | const App = () => { 168 | return ( 169 | 174 | 175 | 176 | ); 177 | }; 178 | ``` 179 | 180 | ## API 181 | 182 | ### ThemeSwitcherProvider 183 | 184 | #### Props 185 | 186 | | Name | Type | Default value | Description | 187 | |----------------|--------|---------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 188 | | attr | String | data-theme | Attribute name for that will be appended to the body tag. Its value will be the current theme name. | 189 | | defaultTheme | String | | Default theme to load on mount. Must be in themeMap | 190 | | id | String | current-theme-style | Id of the current selected CSS. | 191 | | insertionPoint | String or HTMLElement | | Comment string or element where pre-fetch styles and current themes will be injected. The library will look for the comment string inside head element. If missing will append styles at the end of the head. This is useful for CSS override. | 192 | | themeMap | Object | | Object with all themes available. Key is the theme name and the value is the path for the CSS file. | 193 | 194 | ### useThemeSwitcher 195 | 196 | #### Returns 197 | 198 | | Name | Type | Default value | Description | 199 | |--------------|-----------------------------------------|---------------|-------------------------------------------------------------------------------------------------| 200 | | currentTheme | String or Undefined | undefined | Current selected theme | 201 | | themes | Object | themeMap keys | All themes supplied in the themeMap. | 202 | | switcher | ({ theme }: { theme: string }) => void; | Function | Function to change themes. | 203 | | status | enum('idle', 'loading', 'loaded') | idle | Current load status of the selected stylesheet. Useful to prevent flicker when changing themes. | 204 | 205 | ## Contributors 206 | 207 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 |

Jose Felix

💻 📖 ⚠️
217 | 218 | 219 | 220 | 221 | 222 | 223 | This project follows the [all-contributors](https://allcontributors.org) specification. 224 | Contributions of any kind are welcome! 225 | 226 | ## Show your support 227 | 228 | Give a ⭐️ if this project helped you! 229 | -------------------------------------------------------------------------------- /test/index.test.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { renderHook, act } from '@testing-library/react-hooks'; 3 | 4 | import { ThemeSwitcherProvider, useThemeSwitcher } from '../src'; 5 | 6 | // Mock utils 7 | const utils = require('../src/utils'); 8 | const mockedCreateLinkElement = jest.fn(utils.createLinkElement); 9 | utils.createLinkElement = mockedCreateLinkElement; 10 | 11 | beforeAll(() => { 12 | jest.spyOn(console, 'warn').mockImplementation(); 13 | }); 14 | 15 | afterEach(() => { 16 | jest.clearAllMocks(); 17 | document.documentElement.innerHTML = ''; 18 | }); 19 | 20 | afterAll(() => { 21 | jest.restoreAllMocks(); 22 | }); 23 | 24 | const themes = { 25 | dark: './dark.css', 26 | light: './light.css', 27 | }; 28 | 29 | const Wrapper = ( 30 | themeOptions: React.ComponentProps = { 31 | themeMap: themes, 32 | } 33 | ) => ({ children }: any) => { 34 | return ( 35 | {children} 36 | ); 37 | }; 38 | 39 | describe('Theme switcher', () => { 40 | it('should add pre-rendered css themes, and be able to switch between them', async () => { 41 | expect(document.querySelectorAll('link[rel="prefetch"]').length).toBe(0); 42 | 43 | const { result, waitFor } = renderHook(() => useThemeSwitcher(), { 44 | wrapper: Wrapper(), 45 | }); 46 | 47 | expect(document.querySelector('body[data-theme]')).toBeFalsy(); 48 | expect(document.querySelectorAll('link[rel="prefetch"]').length).toBe(2); 49 | expect(result.current).toEqual({ 50 | currentTheme: undefined, 51 | status: 'idle', 52 | switcher: expect.any(Function), 53 | themes: { 54 | dark: 'dark', 55 | light: 'light', 56 | }, 57 | }); 58 | 59 | act(() => { 60 | result.current.switcher({ theme: result.current.themes.dark }); 61 | }); 62 | 63 | expect(result.current.status).toBe('loading'); 64 | 65 | act(() => { 66 | mockedCreateLinkElement.mock.calls[0][0].onload(); 67 | }); 68 | 69 | await waitFor( 70 | () => 71 | !!document.querySelector( 72 | 'link[href="./dark.css"][id="current-theme-style"]' 73 | ) 74 | ); 75 | 76 | expect(document.querySelector('body[data-theme="dark"]')).toBeTruthy(); 77 | expect(result.current.status).toBe('loaded'); 78 | expect(result.current).toEqual({ 79 | currentTheme: 'dark', 80 | status: 'loaded', 81 | switcher: expect.any(Function), 82 | themes: { 83 | dark: 'dark', 84 | light: 'light', 85 | }, 86 | }); 87 | 88 | act(() => { 89 | result.current.switcher({ theme: result.current.themes.light }); 90 | }); 91 | 92 | expect(result.current.status).toBe('loading'); 93 | 94 | act(() => { 95 | mockedCreateLinkElement.mock.calls[1][0].onload(); 96 | }); 97 | 98 | await waitFor( 99 | () => 100 | !!document.querySelector( 101 | 'link[href="./light.css"][id="current-theme-style"]' 102 | ) 103 | ); 104 | 105 | expect(document.querySelector('body[data-theme="light"]')).toBeTruthy(); 106 | expect(result.current.status).toBe('loaded'); 107 | expect(result.current).toEqual({ 108 | currentTheme: 'light', 109 | status: 'loaded', 110 | switcher: expect.any(Function), 111 | themes: { 112 | dark: 'dark', 113 | light: 'light', 114 | }, 115 | }); 116 | }); 117 | 118 | it('should be able to add default theme', async () => { 119 | const { result, waitFor } = renderHook(() => useThemeSwitcher(), { 120 | wrapper: Wrapper({ themeMap: themes, defaultTheme: 'dark' }), 121 | }); 122 | 123 | act(() => { 124 | mockedCreateLinkElement.mock.calls[0][0].onload(); 125 | }); 126 | 127 | await waitFor( 128 | () => 129 | !!document.querySelector( 130 | 'link[href="./dark.css"][id="current-theme-style"]' 131 | ) 132 | ); 133 | 134 | expect(result.current).toEqual({ 135 | currentTheme: 'dark', 136 | status: 'loaded', 137 | switcher: expect.any(Function), 138 | themes: { 139 | dark: 'dark', 140 | light: 'light', 141 | }, 142 | }); 143 | }); 144 | 145 | it('should be able to change custom id and custom attribute', async () => { 146 | const customId = 'custom-id'; 147 | const customAttr = 'custom-attr'; 148 | 149 | const { waitFor } = renderHook(() => useThemeSwitcher(), { 150 | wrapper: Wrapper({ 151 | themeMap: themes, 152 | defaultTheme: 'dark', 153 | id: customId, 154 | attr: customAttr, 155 | }), 156 | }); 157 | 158 | act(() => { 159 | mockedCreateLinkElement.mock.calls[0][0].onload(); 160 | }); 161 | 162 | await waitFor( 163 | () => !!document.querySelector(`link[href="./dark.css"][id=${customId}]`) 164 | ); 165 | 166 | expect(document.querySelector(`body[${customAttr}="dark"]`)).toBeTruthy(); 167 | }); 168 | 169 | it('should error if there is no provider', () => { 170 | const { result } = renderHook(() => useThemeSwitcher()); 171 | 172 | expect(result.error).toMatchInlineSnapshot( 173 | `[Error: To use \`useThemeSwitcher\`, component must be within a ThemeSwitcherProvider]` 174 | ); 175 | }); 176 | 177 | it('should insert styles on comment insertionPoint', () => { 178 | const insertionPoint = 'insert-style-here'; 179 | 180 | document.head.insertBefore( 181 | document.createComment(insertionPoint), 182 | document.head.firstElementChild 183 | ); 184 | 185 | const otherElement = document.createElement('meta'); 186 | document.head.append(otherElement); 187 | 188 | renderHook(() => useThemeSwitcher(), { 189 | wrapper: Wrapper({ 190 | themeMap: themes, 191 | defaultTheme: 'dark', 192 | insertionPoint, 193 | }), 194 | }); 195 | 196 | act(() => { 197 | mockedCreateLinkElement.mock.calls[0][0].onload(); 198 | }); 199 | 200 | function allPreviousElements(element: Element | null) { 201 | const previousElements: HTMLLinkElement[] = []; 202 | while ((element = element!.previousElementSibling)) 203 | previousElements.push(element as HTMLLinkElement); 204 | 205 | return previousElements; 206 | } 207 | 208 | const element = document.head.lastElementChild; 209 | const previousElements = allPreviousElements(element); 210 | 211 | previousElements.forEach(elem => { 212 | const conditions = [ 213 | 'current-theme-style', 214 | 'theme-prefetch-dark', 215 | 'theme-prefetch-light', 216 | ]; 217 | const found = conditions.some(condition => elem.id === condition); 218 | expect(found).toBeTruthy(); 219 | }); 220 | }); 221 | 222 | it('should insert styles on DOM insertionPoint', () => { 223 | const insertionPoint = document.createElement('noscript'); 224 | insertionPoint.id = 'style-insertion-point'; 225 | 226 | document.head.insertBefore(insertionPoint, document.head.firstElementChild); 227 | 228 | const otherElement = document.createElement('meta'); 229 | document.head.append(otherElement); 230 | renderHook(() => useThemeSwitcher(), { 231 | wrapper: Wrapper({ 232 | themeMap: themes, 233 | defaultTheme: 'dark', 234 | insertionPoint: document.getElementById(insertionPoint.id) ?? undefined, 235 | }), 236 | }); 237 | 238 | act(() => { 239 | mockedCreateLinkElement.mock.calls[0][0].onload(); 240 | }); 241 | 242 | function allPreviousElements(element: Element | null) { 243 | const previousElements: HTMLLinkElement[] = []; 244 | while ((element = element!.previousElementSibling)) 245 | previousElements.push(element as HTMLLinkElement); 246 | 247 | return previousElements; 248 | } 249 | 250 | document.getElementById(insertionPoint.id)?.remove(); 251 | const element = document.head.lastElementChild; 252 | const previousElements = allPreviousElements(element); 253 | 254 | previousElements.forEach(elem => { 255 | const conditions = [ 256 | 'current-theme-style', 257 | 'theme-prefetch-dark', 258 | 'theme-prefetch-light', 259 | ]; 260 | const found = conditions.some(condition => elem.id === condition); 261 | expect(found).toBeTruthy(); 262 | }); 263 | }); 264 | 265 | it('should warn when comment insertionPoint does not exist', () => { 266 | renderHook(() => useThemeSwitcher(), { 267 | wrapper: Wrapper({ 268 | themeMap: themes, 269 | defaultTheme: 'dark', 270 | insertionPoint: 'not-in-dom-insertion-point', 271 | }), 272 | }); 273 | 274 | expect(console.warn).toHaveBeenCalledTimes(3); 275 | // @ts-ignore 276 | expect(console.warn.mock.calls[0][0]).toMatchInlineSnapshot( 277 | `"Insertion point 'not-in-dom-insertion-point' does not exist. Be sure to add comment on head and that it matches the insertionPoint"` 278 | ); 279 | }); 280 | 281 | it('should warn when DOM insertionPoint does not exist', () => { 282 | renderHook(() => useThemeSwitcher(), { 283 | wrapper: Wrapper({ 284 | themeMap: themes, 285 | defaultTheme: 'dark', 286 | insertionPoint: document.getElementById('not-in-dom-insertion-point'), 287 | }), 288 | }); 289 | 290 | expect(console.warn).toHaveBeenCalledTimes(3); 291 | // @ts-ignore 292 | expect(console.warn.mock.calls[0][0]).toMatchInlineSnapshot( 293 | `"Insertion point 'null' does not exist. Be sure to add comment on head and that it matches the insertionPoint"` 294 | ); 295 | }); 296 | 297 | it('should append to head even when insertionPoint does not exist', async () => { 298 | const { waitFor } = renderHook(() => useThemeSwitcher(), { 299 | wrapper: Wrapper({ 300 | themeMap: themes, 301 | defaultTheme: 'dark', 302 | insertionPoint: 'not-in-dom-insertion-point', 303 | }), 304 | }); 305 | 306 | act(() => { 307 | mockedCreateLinkElement.mock.calls[0][0].onload(); 308 | }); 309 | 310 | await waitFor( 311 | () => 312 | !!document.querySelector( 313 | 'link[href="./dark.css"][id="current-theme-style"]' 314 | ) 315 | ); 316 | expect(document.querySelectorAll('link[rel="prefetch"]').length).toBe(2); 317 | }); 318 | 319 | it('should display error when theme is not found', () => { 320 | const { result } = renderHook(() => useThemeSwitcher(), { 321 | wrapper: Wrapper(), 322 | }); 323 | 324 | act(() => { 325 | result.current.switcher({ theme: 'this-theme-does-not-exist' }); 326 | }); 327 | 328 | expect(console.warn).toHaveBeenCalledTimes(1); 329 | // @ts-ignore 330 | expect(console.warn.mock.calls[0][0]).toMatchInlineSnapshot( 331 | `"Could not find specified theme"` 332 | ); 333 | }); 334 | 335 | it('should not change theme when selecting the same theme', () => { 336 | const { result } = renderHook(() => useThemeSwitcher(), { 337 | wrapper: Wrapper({ 338 | themeMap: themes, 339 | defaultTheme: 'dark', 340 | }), 341 | }); 342 | 343 | act(() => { 344 | mockedCreateLinkElement.mock.calls[0][0].onload(); 345 | }); 346 | 347 | const expectedResult = result.current; 348 | 349 | act(() => { 350 | result.current.switcher({ theme: result.current.themes.dark }); 351 | }); 352 | 353 | expect(result.current).toEqual(expectedResult); 354 | }); 355 | }); 356 | --------------------------------------------------------------------------------