Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
donavon committed Jan 14, 2019
0 parents commit df82951
Show file tree
Hide file tree
Showing 13 changed files with 12,592 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_size = 2

[*.md]
trim_trailing_whitespace = false
3 changes: 3 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "amex"
}
66 changes: 66 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock
.DS_Store

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# next.js build output
.next

# lib
lib/
dist/
8 changes: 8 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
node_modules
src
.editorconfig
.eslintrc
.babelrc
__tests__
coverage
.prettierrc
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "es5"
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018-present Donavon West

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
114 changes: 114 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# use-dark-mode

A custom [React Hook](https://reactjs.org/docs/hooks-overview.html) to help you implement a "dark mode" component for your application.

[![npm version](https://badge.fury.io/js/use-dark-mode.svg)](https://badge.fury.io/js/use-dark-mode)

![usedarkmode-small](https://user-images.githubusercontent.com/887639/51113468-079ee100-17d0-11e9-8a35-e29b12b74740.gif)

`useDarkMode` works in one of two ways:

1. By toggling a CSS class on whatever element you specify (defaults to `document.body`).
You then setup your CSS to display different views based on the presence of the selector. For example, the following CSS is used in the demo app to ease the background color in/out of dark mode.

```css
body {
background-color: #fff;
color: #333;
transition: background-color 0.3s ease;
}
body.dark-mode {
background-color: #1a1919;
color: #999;
}
```

2. If you don't use global classes, you can specify a callback and take care of the implementation of switching to dark mode yourself.

## Requirement ⚠️

To use `use-dark-mode`, you must use `[email protected]`. React Hooks is currently at
**[RFC](https://github.com/reactjs/rfcs/pull/68)** stage.

## Installation

```sh
$ npm i use-dark-mode
```

## Usage

```js
const [isDarkMode, setDarkMode, clearDarkMode, toggleDarkMode] = useDarkMode(
false,
optionalConfigObject
);
```

### Config

You pass `useDarkMode` an `initialState` (whether it should be in dark mode by by default) and an optional configuration object.
The configuration object contains the following.

| Key | Description |
| :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `className` | The class to apply. Default = `dark-mode`. |
| `element` | The element to apply the class name. Default = `document.body`. |
| `callback` | A callback function that will be called when the state changes and it is safe to access the DOM (i.e. it is called from within a `useEffect`). If you specify `callback` then `className` and `element` are ignored (i.e. no classes are automatically placed on the DOM). You have full control! |

### Return object

isDarkMode, setDarkMode, clearDarkMode, toggleDarkMode
| Key | Description |
| :-------------------- | :--------------------------------------------------------- |
| `isDarkMode` | A boolean containing the current state of dark mode. |
| `setDarkMode` | A function that allows you to set dark mode to `true`. |
| `clearDarkMode` | A function that allows you to set dark mode to `false`. |
| `toggleDarkMode` | A function that allows you to toggle dark mode. |

## Example

Here is a simple component that uses `useDarkMode` to provide a dark mode toggle control.
If dark mode is selected, the CSS class `dark-mode` is applied to `document.body` and is removed
when de-selected.

```jsx
import React from 'react';

import Toggle from './Toggle';
import useDarkMode from 'use-dark-mode';

const DarkModeToggle = () => {
const [isDarkMode, setDarkMode, clearDarkMode, toggleDarkMode] = useDarkMode(
false
);

return (
<div>
<button type="button" onClick={clearDarkMode}>
</button>
<Toggle checked={isDarkMode} onChange={toggleDarkMode} />
<button type="button" onClick={setDarkMode}>
</button>
</div>
);
};

export default DarkModeToggle;
```

## Live demo

You can view/edit the dark mode demo app on CodeSandbox.

[![Edit demo app on CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/github/donavon/use-step-multi-step-form-demo/tree/master/?module=%2Fsrc%2FDarkModeToggle.jsx)

## License

**[MIT](LICENSE)** Licensed

---

A special thanks to [@revelcw](https://twitter.com/revelcw) for his help and inspiration on this package.
8 changes: 8 additions & 0 deletions __tests__/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "amex/test",
"rules": {
"react/prop-types": 0,
"react/button-has-type": 0,
"react/jsx-filename-extension": 0
}
}
98 changes: 98 additions & 0 deletions __tests__/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import React, { Fragment } from 'react';
import { render, cleanup } from 'react-testing-library';
import 'jest-dom/extend-expect';

import useDarkMode from '../src';

afterEach(cleanup);

const createTestElement = obj => ({
classList: {
add: (className) => {
obj.method = 'add';
obj.className = className;
},
remove: (className) => {
obj.method = 'remove';
obj.className = className;
},
},
});

const Component = ({ initialDarkMode, config }) => {
const [isDarkMode, setDarkMode, clearDarkMode, toggleDarkMode] = useDarkMode(
initialDarkMode, config
);
return (
<Fragment>
<span data-testid="isDarkMode">{JSON.stringify(isDarkMode)}</span>
<button data-testid="setDarkMode" type="button" onClick={setDarkMode} />
<button data-testid="clearDarkMode" type="button" onClick={clearDarkMode} />
<button data-testid="toggleDarkMode" type="button" onClick={toggleDarkMode} />
</Fragment>
);
};

describe('useDarkMode', () => {
test('import { useDarkMode } from "use-dark-mode"', () => {
expect(typeof useDarkMode).toBe('function');
});
test('`initialDarkMode` defaults to `false`', () => {
const { getByTestId } = render(<Component config={{ element: createTestElement({}) }} />);
const isDarkModeElement = getByTestId('isDarkMode');
expect(isDarkModeElement.textContent).toBe('false');
});
test('you can pass an `initialDarkMode`', () => {
const {
getByTestId,
} = render(<Component initialDarkMode={true} config={{ element: createTestElement({}) }} />);
const isDarkModeElement = getByTestId('isDarkMode');
expect(isDarkModeElement.textContent).toBe('true');
});
test('the class `className` is applied to the element `element`', (done) => {
const test = {};
const {
getByTestId,
} = render(<Component initialDarkMode={true} config={{ className: 'foo', element: createTestElement(test) }} />);
setTimeout(() => {
expect(test).toEqual({ className: 'foo', method: 'add' });
done();
}, 1);
});
test('you can pass an `callback` that is called with the current state of dark mode', (done) => {
const callback = (isDarkMode) => {
expect(isDarkMode).toBe(true);
done();
};
const { getByTestId } = render(<Component initialDarkMode={true} config={{ callback }} />);
});
// test('supports a custom initial index of 0, 1, or 2', () => {
// [0, 1, 2].forEach((i) => {
// const { container } = render(<Component initialColorIndex={i} />);
// const child = container.firstChild;
// expect(child.textContent).toBe(`${i}`);
// });
// });
// test('has a default duration array of [5000, 4000, 1000] msecs', () => {
// const { container } = render(<Component />);
// const child = container.firstChild;
// expect(child.textContent).toBe('0');
// jest.advanceTimersByTime(5000);
// expect(child.textContent).toBe('1');
// jest.advanceTimersByTime(4000);
// expect(child.textContent).toBe('2');
// jest.advanceTimersByTime(1000);
// expect(child.textContent).toBe('0');
// });
// test('supports a custom duration array', () => {
// const { container } = render(<Component durations={[500, 400, 100]} />);
// const child = container.firstChild;
// expect(child.textContent).toBe('0');
// jest.advanceTimersByTime(500);
// expect(child.textContent).toBe('1');
// jest.advanceTimersByTime(400);
// expect(child.textContent).toBe('2');
// jest.advanceTimersByTime(100);
// expect(child.textContent).toBe('0');
// });
});
Loading

0 comments on commit df82951

Please sign in to comment.