1
mirror of https://github.com/jakejarvis/dark-mode.git synced 2025-06-30 21:56:38 -04:00

Compare commits

...

43 Commits
0.3.0 ... main

Author SHA1 Message Date
0328cdb280 v0.10.0 2021-11-11 10:45:09 -05:00
57989cf25f switch to microbundle 2021-11-11 10:44:56 -05:00
c62cde5e91 fixes for eslint 8.0.0 2021-10-12 20:22:57 -04:00
ce472773c9 bring bundle config up-to-date with rollup template
https://github.com/jakejarvis/rollup-module-template
2021-10-09 16:49:25 -04:00
07ce4cab10 Release 0.9.1 2021-10-04 09:27:23 -04:00
9c9351398d remove toggle || null (already checked for) 2021-10-04 09:26:15 -04:00
1c1ff4e186 Release 0.9.0 2021-10-04 09:25:46 -04:00
45d856cab3 add onUserToggle callback, move onInit and onChange up 2021-10-04 09:25:10 -04:00
fba5494cfe Release 0.8.1 2021-09-09 17:56:35 -04:00
8670de8a30 types: HTMLElement -> Element | null 2021-09-09 17:55:23 -04:00
e5a76a03b3 Release 0.8.0 2021-09-09 17:49:07 -04:00
02f772dd46 Rename package from @jakejarvis/dark-mode to dark-mode-switcheroo 2021-09-09 17:48:20 -04:00
5fc1bd80b3 📦 npm: Bump @babel/core from 7.15.0 to 7.15.5
Bumps [@babel/core](https://github.com/babel/babel/tree/HEAD/packages/babel-core) from 7.15.0 to 7.15.5.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.15.5/packages/babel-core)

---
updated-dependencies:
- dependency-name: "@babel/core"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-09-09 17:45:58 -04:00
ba8cd84d66 📦 npm: Bump @babel/preset-env from 7.15.0 to 7.15.4
Bumps [@babel/preset-env](https://github.com/babel/babel/tree/HEAD/packages/babel-preset-env) from 7.15.0 to 7.15.4.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.15.4/packages/babel-preset-env)

---
updated-dependencies:
- dependency-name: "@babel/preset-env"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-09-09 17:43:21 -04:00
9d599b4675 Release 0.7.2 2021-08-31 10:44:39 -04:00
8f96d0bb83 use rollup-plugin-delete to clean dist folder on build 2021-08-31 10:30:56 -04:00
2fcad1a9e7 update eslint config to use @jakejarvis/eslint-config 2021-08-30 19:41:32 -04:00
20aaf287b2 Release 0.7.1 2021-08-23 09:15:31 -04:00
a84de1b0e5 📦 npm: Bump rollup from 2.56.2 to 2.56.3
Bumps [rollup](https://github.com/rollup/rollup) from 2.56.2 to 2.56.3.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v2.56.2...v2.56.3)

---
updated-dependencies:
- dependency-name: rollup
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-23 09:14:48 -04:00
d00e3d54b2 add version number to banner comment 2021-08-23 09:11:27 -04:00
80153bce73 Release 0.7.0 2021-08-22 10:41:07 -04:00
fa128cb222 remove super-duper edge case testing of localStorage support
use the following methods externally to test on older browsers if needed:
- https://www.npmjs.com/package/storage-available
- https://www.npmjs.com/package/local-storage-fallback
- https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#testing_for_availability
2021-08-22 10:38:26 -04:00
582e64ae13 📦 npm: Bump eslint-plugin-compat from 3.12.0 to 3.13.0
Bumps [eslint-plugin-compat](https://github.com/amilajack/eslint-plugin-compat) from 3.12.0 to 3.13.0.
- [Release notes](https://github.com/amilajack/eslint-plugin-compat/releases)
- [Changelog](https://github.com/amilajack/eslint-plugin-compat/blob/master/CHANGELOG.md)
- [Commits](https://github.com/amilajack/eslint-plugin-compat/compare/v3.12.0...v3.13.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-compat
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-22 10:37:54 -04:00
eb6d058b5b set "sideEffects": false 2021-08-16 23:06:22 -04:00
46ade562c4 Release 0.6.3 2021-08-11 09:48:05 -04:00
6ef857154b publish via CI to NPM and GH packages 2021-08-11 09:47:30 -04:00
df981e17b3 add dependabot.yml 2021-08-11 09:39:52 -04:00
710e94d7dc Release 0.6.2 2021-08-07 10:04:01 -04:00
1ad8cf373e add exports field to package.json to comply with skypack.dev 2021-08-07 10:03:16 -04:00
01ff103e08 Update README 2021-08-05 12:02:56 -04:00
29728eb5cf Release 0.6.1 2021-08-05 08:47:05 -04:00
755ac19dba small cleanup 2021-08-05 08:41:45 -04:00
7e2e8948ec Release 0.6.0 2021-08-05 08:17:30 -04:00
6bf29bca6f Update README 2021-08-05 08:12:49 -04:00
cfa1f575e3 add onInit and onChange callback function options 2021-08-05 07:54:47 -04:00
8b40221791 Release 0.5.1 2021-08-04 21:00:06 -04:00
f87f43c5c5 clean up type defs, update example HTML 2021-08-04 20:59:02 -04:00
c7a304caa4 Release 0.5.0 2021-08-04 19:18:58 -04:00
eedd0a96e0 much simpler bundling with rollup, also generate separate ESM and CJS files 2021-08-04 19:16:33 -04:00
1c2b15d70f Release 0.4.0 2021-08-04 15:37:02 -04:00
a91d67cfeb a bit more cleanup 2021-08-04 15:34:22 -04:00
e4d7e4f61b remove unnecessary deps (now zero 😎) 2021-08-04 15:19:54 -04:00
4881b908e9 expose an init function instead of exporting as module default 2021-08-04 15:00:26 -04:00
14 changed files with 2876 additions and 1151 deletions

17
.editorconfig Normal file
View File

@ -0,0 +1,17 @@
# http://editorconfig.org
# this file is the top-most editorconfig file
root = true
# all files
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true
# site content
[*.md]
trim_trailing_whitespace = false

View File

@ -1,19 +1,16 @@
{
"extends": [
"eslint:recommended",
"plugin:compat/recommended",
"plugin:prettier/recommended"
"@jakejarvis/eslint-config",
"plugin:@typescript-eslint/recommended"
],
"plugins": [
"prettier"
"@typescript-eslint"
],
"parser": "@typescript-eslint/parser",
"env": {
"browser": true,
"node": true
"browser": true
},
"parserOptions": {
"ecmaVersion": 2015,
"sourceType": "module"
},
"rules": {}
"ignorePatterns": [
"dist/**"
]
}

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Set default behavior to automatically normalize line endings.
* text=auto eol=lf

10
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,10 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
versioning-strategy: increase
schedule:
interval: "daily"
commit-message:
prefix: "📦 npm:"

View File

@ -3,16 +3,17 @@ name: CI
on:
push:
branches:
- main
- main
pull_request:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14.x'
- run: yarn install --frozen-lockfile
- run: yarn lint
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16.x
- run: yarn install --frozen-lockfile
- run: yarn lint
- run: yarn build

20
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: Release
on:
push:
tags:
- 'v*'
jobs:
npm:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16.x
registry-url: https://registry.npmjs.org/
- run: yarn install --frozen-lockfile
- run: yarn publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@ -1,6 +0,0 @@
{
"printWidth": 70,
"tabWidth": 2,
"semi": true,
"singleQuote": false
}

View File

@ -1,12 +1,11 @@
# 🌓 Dark mode switcheroo
# 🌓 Dark Mode Switcheroo
[![CI](https://github.com/jakejarvis/dark-mode.js/actions/workflows/ci.yml/badge.svg)](https://github.com/jakejarvis/dark-mode.js/actions/workflows/ci.yml)
[![npm (scoped)](https://img.shields.io/npm/v/@jakejarvis/dark-mode)](https://www.npmjs.com/package/@jakejarvis/dark-mode)
[![GitHub](https://img.shields.io/github/license/jakejarvis/dark-mode?color=violet)](LICENSE)
[![CI](https://github.com/jakejarvis/dark-mode/actions/workflows/ci.yml/badge.svg)](https://github.com/jakejarvis/dark-mode/actions/workflows/ci.yml)
[![npm](https://img.shields.io/npm/v/dark-mode-switcheroo)](https://www.npmjs.com/package/dark-mode-switcheroo)
Very simple CSS dark/light mode toggler with saved preference via local storage & dynamic OS setting detection. Only ~700 bytes gzipped!
Very simple CSS dark/light mode toggler with saved preference via local storage & dynamic OS setting detection. Zero dependencies and [only ~500 bytes gzipped!](https://bundlephobia.com/package/dark-mode-switcheroo)
- [View the example.](https://jakejarvis.github.io/dark-mode-example/)
- [View the example.](https://jakejarvis.github.io/dark-mode/)
- [Read the blog post.](https://jarv.is/notes/dark-mode/)
- [See it in action.](https://jarv.is/)
@ -14,21 +13,24 @@ Very simple CSS dark/light mode toggler with saved preference via local storage
### Options
`darkMode([...options])`
`darkMode.init([...options])`
- **toggle:** The clickable HTML element used to toggle between the two themes. (optional, default: `null`)
- **classes:** An object containing the `<body>` class names for the light and dark themes. (optional, default: `{ light: "light", dark: "dark" }`)
- **default:** The initial `<body>` class hard-coded into the HTML template. (optional, default: `"light"`)
- **storageKey:** Name of the `localStorage` key holding the user's preference. (optional, default: `"dark_mode_pref"`)
- **`toggle`**: The clickable [HTMLElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) used to toggle between the two themes. (optional, default: `null`)
- **`classes`**: An object containing the `<body>` class names for the light and dark themes. (optional, default: `{ light: "light", dark: "dark" }`)
- **`default`**: The initial `<body>` class hard-coded into the HTML template. (optional, default: `"light"`)
- **`storageKey`**: Name of the `localStorage` key holding the user's preference. (optional, default: `"dark_mode_pref"`)
- **`onInit([toggle])`**: Callback function executed at the end of initialization. The toggle above is passed in if set. (optional, default: `null`)
- **`onUserToggle([toggle])`**: Callback function executed when a user manually interacts with the toggle button. The toggle above (if set) is passed in. (optional, default: `null`)
- **`onChange([theme, toggle])`**: Callback function executed when theme is switched. The new theme and the toggle above (if set) are passed in. (optional, default: `null`)
### Browser
```html
<button class="dark-mode-toggle">💡 Click to see the light... or not.</button>
<button class="dark-mode-toggle" style="visibility: hidden;">💡 Click to see the light... or not.</button>
<script src="https://unpkg.com/@jakejarvis/dark-mode/dist/index.js"></script>
<script src="https://unpkg.com/dark-mode-switcheroo/dist/dark-mode.min.js"></script>
<script>
window.darkMode({
window.darkMode.init({
toggle: document.querySelector(".dark-mode-toggle"),
classes: {
light: "light",
@ -36,6 +38,12 @@ Very simple CSS dark/light mode toggler with saved preference via local storage
},
default: "light",
storageKey: "dark_mode_pref",
onInit: function (toggle) {
toggle.style.visibility = "visible"; // toggle appears now that we know JS is enabled
},
onChange: function (theme, toggle) {
console.log("Theme is now " + theme);
},
});
</script>
```
@ -43,27 +51,37 @@ Very simple CSS dark/light mode toggler with saved preference via local storage
### Node
```bash
npm install @jakejarvis/dark-mode
npm install dark-mode-switcheroo
# or...
yarn add @jakejarvis/dark-mode
yarn add dark-mode-switcheroo
```
#### Module via `import`
```js
import darkMode from "@jakejarvis/dark-mode";
// or:
// const darkMode = require("@jakejarvis/dark-mode");
import { init } from "dark-mode-switcheroo";
darkMode({
toggle: document.querySelector(".dark-mode-toggle"),
classes: {
light: "light",
dark: "dark",
},
default: "light",
storageKey: "dark_mode_pref",
init({
// ...same as browser.
});
```
#### CommonJS via `require()`
```js
const darkMode = require("dark-mode-switcheroo");
darkMode.init({
// ...same as browser.
});
```
## To-Do
- [ ] Support more than two themes
- [ ] Better readme docs
- [x] Add callback function `onChange` (or `onToggle` etc.) passed in as an option
## License
MIT

View File

@ -4,19 +4,60 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome to the dark side 🌓</title>
<style>/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}body{font-family:system-ui,-apple-system,sans-serif;text-align:center}a{text-decoration:none}h1{font-size:1.8em}.dark-mode-toggle{cursor:pointer;padding:1em;visibility:hidden}body.light{background-color:#fff;color:#222}body.light a{color:#06f}body.dark{background-color:#222;color:#fff}body.dark a{color:#fe0}</style>
<style>/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}</style>
<style>
/* Global styles */
body {
font-family: system-ui, -apple-system, sans-serif;
text-align: center;
}
/* Light theme */
body.light {
background-color: #fff;
color: #222;
}
body.light a {
color: #06f;
}
/* Dark theme */
body.dark {
background-color: #222;
color: #fff;
}
body.dark a {
color: #fe0;
}
/* The Toggle (TM) */
.dark-mode-toggle {
padding: 1em;
cursor: pointer;
/* Hide the toggle initially if the user's JS is disabled: */
visibility: hidden;
}
</style>
</head>
<body class="light">
<body class="light"> <!-- default to light theme -->
<h1>Welcome to the dark side 🌓</h1>
<button class="dark-mode-toggle">💡 Click to see the light... or not.</button>
<p><a href="https://github.com/jakejarvis/dark-mode-example" target="_blank" rel="noopener">View the source code</a> or <a href="https://jarv.is/notes/dark-mode/" target="_blank" rel="noopener">read the post</a>.</p>
<p><a href="https://github.com/jakejarvis/dark-mode" target="_blank" rel="noopener">View the source code</a> or <a href="https://jarv.is/notes/dark-mode/" target="_blank" rel="noopener">read the post</a>.</p>
<script src="../dist/index.js"></script>
<script src="../dist/dark-mode.min.js"></script> <!-- or use CDN: https://unpkg.com/dark-mode-switcheroo/dist/dark-mode.min.js -->
<script>
window.darkMode({
window.darkMode.init({
toggle: document.querySelector(".dark-mode-toggle"),
onInit: function (e) {
e.style.visibility = "visible";
console.log("Toggle is visible now that we know user has JS enabled.");
},
onChange: function (t) {
console.log("Set theme to " + t);
}
});
</script>
</body>

View File

@ -1,8 +1,9 @@
{
"name": "@jakejarvis/dark-mode",
"version": "0.3.0",
"description": "Super simple CSS theme switching with saved preferences and automatic OS setting detection",
"name": "dark-mode-switcheroo",
"version": "0.10.0",
"description": "🌓 Simple CSS theme switching with saved preferences and automatic OS setting detection",
"license": "MIT",
"homepage": "https://jrvs.io/darkmode",
"author": {
"name": "Jake Jarvis",
"email": "jake@jarv.is",
@ -12,35 +13,40 @@
"type": "git",
"url": "https://github.com/jakejarvis/dark-mode.git"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "webpack --mode production",
"lint": "eslint src/**/*.js",
"prepublishOnly": "run-s lint build"
},
"dependencies": {
"storage-available": "^1.1.0"
},
"devDependencies": {
"copy-webpack-plugin": "^9.0.1",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-compat": "^3.11.1",
"eslint-plugin-prettier": "^3.4.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.3.2",
"terser-webpack-plugin": "^5.1.4",
"webpack": "^5.48.0",
"webpack-cli": "^4.7.2"
},
"type": "module",
"files": [
"dist/index.js",
"dist/index.d.ts"
"dist"
],
"source": "./src/dark-mode.ts",
"main": "./dist/dark-mode.cjs",
"module": "./dist/dark-mode.esm.js",
"unpkg": "./dist/dark-mode.min.js",
"exports": {
"require": "./dist/dark-mode.cjs",
"import": "./dist/dark-mode.esm.js",
"browser": "./dist/dark-mode.min.js"
},
"types": "./dist/dark-mode.d.ts",
"scripts": {
"build": "microbundle --format cjs,esm,umd --name 'darkMode'",
"lint": "eslint .",
"prepublishOnly": "yarn build"
},
"dependencies": {},
"devDependencies": {
"@jakejarvis/eslint-config": "*",
"@typescript-eslint/eslint-plugin": "^5.3.1",
"@typescript-eslint/parser": "^5.3.1",
"eslint": "^8.2.0",
"microbundle": "^0.14.1",
"typescript": "^4.4.4"
},
"keywords": [
"frontend",
"front-end",
"dark mode",
"theme",
"appearance",
"design",
"css"
]
}

View File

@ -1,7 +1,12 @@
const storageAvailable = require("storage-available");
module.exports = function (options) {
// { toggle, classes: { light, dark }, default, storageKey }
export function init(options: {
toggle?: Element | null;
classes?: { dark: string, light: string };
default?: string;
storageKey?: string;
onInit?: (toggle?: Element | null) => unknown;
onUserToggle?: (toggle?: Element | null) => unknown;
onChange?: (theme: string, toggle?: Element | null) => unknown;
}): void {
options = options || {};
// use a specified element(s) to trigger swap when clicked
@ -9,9 +14,7 @@ module.exports = function (options) {
// check for preset `dark_mode_pref` preference in local storage
const storageKey = options.storageKey || "dark_mode_pref";
const storageEnabled = storageAvailable("localStorage");
// eslint-disable-next-line prettier/prettier
const pref = storageEnabled ? localStorage.getItem(storageKey) : null;
const pref = localStorage.getItem(storageKey);
// change CSS via these <body> classes:
const dark = options.classes ? options.classes.dark : "dark";
@ -24,20 +27,30 @@ module.exports = function (options) {
let active = defaultTheme === dark;
// receives a class name and switches <body> to it
const activateTheme = function (theme, save = false) {
const activateTheme = function (theme: string, remember?: boolean) {
// optional onChange callback function passed as option
if (typeof options.onChange === "function") {
options.onChange(theme, toggle);
}
document.body.classList.remove(dark, light);
document.body.classList.add(theme);
active = theme === dark;
if (storageEnabled && save) {
if (remember) {
localStorage.setItem(storageKey, theme);
}
};
// optional onInit callback function passed as option
if (typeof options.onInit === "function") {
options.onInit(toggle);
}
// user has never clicked the button, so go by their OS preference until/if they do so
if (!pref) {
// returns media query selector syntax
const prefers = function (colorScheme) {
const prefers = function (colorScheme: "dark" | "light") {
// https://drafts.csswg.org/mediaqueries-5/#prefers-color-scheme
return `(prefers-color-scheme: ${colorScheme})`;
};
@ -53,20 +66,16 @@ module.exports = function (options) {
}
// real-time switching if supported by OS/browser
window
.matchMedia(prefers("dark"))
.addEventListener("change", function (e) {
if (e.matches) {
activateTheme(dark);
}
});
window
.matchMedia(prefers("light"))
.addEventListener("change", function (e) {
if (e.matches) {
activateTheme(light);
}
});
window.matchMedia(prefers("dark")).addEventListener("change", function (e) {
if (e.matches) {
activateTheme(dark);
}
});
window.matchMedia(prefers("light")).addEventListener("change", function (e) {
if (e.matches) {
activateTheme(light);
}
});
} else if (pref === dark || pref === light) {
// if user already explicitly toggled in the past, restore their preference
activateTheme(pref);
@ -77,11 +86,13 @@ module.exports = function (options) {
// don't freak out if page happens not to have a toggle
if (toggle !== null) {
// toggle re-appears now that we know user has JS enabled
toggle.style.visibility = "visible";
// handle toggle click
toggle.addEventListener("click", function () {
// optional onUserToggle callback function passed as option
if (typeof options.onUserToggle === "function") {
options.onUserToggle(toggle);
}
// switch to the opposite theme & save preference in local storage
if (active) {
activateTheme(light, true);
@ -90,4 +101,4 @@ module.exports = function (options) {
}
});
}
};
}

8
src/index.d.ts vendored
View File

@ -1,8 +0,0 @@
interface DarkModeOptions {
toggle?: HTMLElement;
classes?: { dark: string, light: string };
default?: string;
storageKey?: string;
}
export default function (options?: Partial<DarkModeOptions>): void;

View File

@ -1,38 +0,0 @@
const webpack = require("webpack");
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
library: {
name: "darkMode",
type: "umd",
},
globalObject: "this",
},
plugins: [
new webpack.BannerPlugin({
banner: "Dark mode switcheroo | MIT License | jrvs.io/darkmode",
}),
new CopyPlugin({
patterns: [
{
from: path.join(__dirname, "src/index.d.ts"),
to: path.join(__dirname, "dist", "index.d.ts"),
},
],
}),
],
optimization: {
minimizer: [
new TerserPlugin({
extractComments: false,
}),
],
},
};

3640
yarn.lock

File diff suppressed because it is too large Load Diff