Repository: diegohaz/styled-theme
Branch: master
Commit: 4009214b7e9c
Files: 19
Total size: 19.7 KB
Directory structure:
gitextract_tnzi80xu/
├── .babelrc
├── .editorconfig
├── .eslintrc
├── .flowconfig
├── .gitattributes
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── _config.yml
├── composer.js
├── index.js
├── package.json
├── src/
│ ├── composer.js
│ ├── index.js
│ ├── theme.js
│ └── types.js
└── test/
├── composer.js
└── index.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc
================================================
{
"presets": [
["env", {
"targets": {
"browsers": "last 2 versions"
}
}],
"stage-2"
],
"plugins": ["transform-flow-strip-types"]
}
================================================
FILE: .editorconfig
================================================
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# Change these settings to your own preference
indent_style = space
indent_size = 2
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
================================================
FILE: .eslintrc
================================================
{
"parser": "babel-eslint",
"extends": [
"airbnb-base",
"plugin:flowtype/recommended"
],
"plugins": [
"flowtype",
"flowtype-errors"
],
"env": {
"jest": true
},
"rules": {
"semi": [2, never],
"comma-dangle": 0,
"flowtype-errors/show-errors": 2,
"import/prefer-default-export": 0
}
}
================================================
FILE: .flowconfig
================================================
[ignore]
.*/dist
.*/coverage
================================================
FILE: .gitattributes
================================================
* text=auto
*.js text eol=lf
================================================
FILE: .gitignore
================================================
.DS_Store
node_modules
coverage
dist
*.log
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- v6
script:
- npm run lint && npm test -- --coverage
after_success:
- bash <(curl -s https://codecov.io/bash)
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 Diego Haz
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.
================================================
FILE: README.md
================================================
# styled-theme 💅🏿
[](https://github.com/diegohaz/nod)
[](https://npmjs.org/package/styled-theme)
[](https://travis-ci.org/diegohaz/styled-theme) [](https://codecov.io/gh/diegohaz/styled-theme/branch/master)
Theming system for [styled-components 💅](https://github.com/styled-components/styled-components)
## Install
$ npm install --save styled-theme
## Usage
Play with it on [WebpackBin](https://www.webpackbin.com/bins/-KeZfaFl3_761CAGa0CC)
```js
import styled from 'styled-components'
import { font, palette } from 'styled-theme'
const Text = styled.span`
font-family: ${font('primary')};
background-color: ${palette(1)};
color: ${palette('grayscale', 0, true)};
`
Text.defaultProps = {
palette: 'primary'
}
```
```jsx
Hello
```

```jsx
Hello
```

```jsx
Hello
```

### Provide your own theme
```jsx
import { ThemeProvider } from 'styled-components'
const xmasTheme = {
fonts: {
primary: 'Georgia, serif'
},
palette: {
// red gradient
primary: ['#D32F2F', '#F44336', '#F8877F', '#FFCDD2']
}
}
Hello
```

## Default theme structure
This is the content of [`src/theme.js`](src/theme.js):
```js
import coolorsToHex from 'coolors-to-hex'
import { reversePalette } from './composer'
const theme = {}
theme.palette = {
primary: coolorsToHex('https://coolors.co/1976d2-2196f3-71bcf7-97cef9-c2e2fb'),
secondary: coolorsToHex('https://coolors.co/c2185b-e91e63-f06292-f48caf-f8bbd0'),
danger: coolorsToHex('https://coolors.co/d32f2f-f44336-f8877f-f9a7a1-ffcdd2'),
alert: coolorsToHex('https://coolors.co/ffa000-ffc107-ffd761-ffecb3-fff2ce'),
success: coolorsToHex('https://coolors.co/388e3c-4caf50-7cc47f-9fd4a1-c8e6c9'),
grayscale: ['#212121', '#616161', '#9e9e9e', '#bdbdbd', '#e0e0e0', '#ffffff']
}
theme.reversePalette = reversePalette(theme.palette)
theme.fonts = {
primary: 'Helvetica Neue, Helvetica, Roboto, sans-serif',
pre: 'Consolas, Liberation Mono, Menlo, Courier, monospace',
quote: 'Georgia, serif'
}
theme.sizes = {
maxWidth: '1100px'
}
export default theme
```
[`reversePalette`](#reversePalette) is a helper method. Import it from `styled-theme/composer`.
## API
### reversePalette
Revert the palette
**Parameters**
- `palette` **[Palette](#palette)**
**Examples**
```javascript
reversePalette({ primary: ['red', 'yellow', 'green'] })
// { primary: ['green', 'yellow', 'red'] }
```
Returns **[Palette](#palette)**
### key
Returns the value of `props.theme[path]` or `styledTheme[path]`
**Parameters**
- `path` **([string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)>)**
- `defaultValue` **any**
**Examples**
```javascript
const Button = styled.button`
font-family: ${key('fonts.primary')};
color: ${key(['colors', 'primary', 0])};
`
```
Returns **any**
### font
Shorthand to `key(['fonts', path])`
**Parameters**
- `path` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `defaultValue` **any**
**Examples**
```javascript
const Button = styled.button`
font-family: ${font('primary')};
`
```
Returns **[Font](#font)**
### size
Shorthand to `key(['sizes', path])`
**Parameters**
- `path` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `defaultValue` **any**
**Examples**
```javascript
const Button = styled.button`
padding: ${size('padding')};
`
```
Returns **[Size](#size)**
### palette
Returns the value of `props.theme[palette || reversePalette][path][index]` or
`styledTheme[palette || reversePalette][path][index]` (default theme)
The arguments can be passed in any order, as long as types are kept.
**Parameters**
- `index` **[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)** The index of tone in theme palette tones array
- `path` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)?** The key of the tones in theme palette object (optional, default `props.palette`)
- `exceptions` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)?** An object with path as key and index as value
- `reverse` **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** Flag to return tone from `reversePalette` or `palette`
- `defaultValue` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)?** Default value
- `args` **...any**
**Examples**
```javascript
// index = 1
// exception = { grayscale: 0 }
// reverse = true
const Button = styled.button`
background-color: ${palette({ grayscale: 0 }, 1, true)};
`
// renders props.theme.reversePalette.grayscale[0]
// renders props.theme.palette.danger[1] (nullify reverse)
```
Returns **[Tones](#tones)**
### Tone
Type: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
### Tones
Type: [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Tone](#tone)>
### Font
Type: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
### Size
Type: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
### Palette
Type: {}
### Fonts
Type: {}
### Sizes
Type: {}
### Theme
Type: {palette: [Palette](#palette)?, reversePalette: [Palette](#palette)?, fonts: [Fonts](#fonts)?, sizes: [Sizes](#sizes)?}
## Related
- [styled-tools](https://github.com/diegohaz/styled-tools) - Utilities for styled-components (like lodash)
## License
MIT © [Diego Haz](https://github.com/diegohaz)
================================================
FILE: _config.yml
================================================
theme: jekyll-theme-cayman
================================================
FILE: composer.js
================================================
module.exports = require('./dist/composer')
================================================
FILE: index.js
================================================
module.exports = require('./dist')
================================================
FILE: package.json
================================================
{
"name": "styled-theme",
"version": "0.3.3",
"description": "Theming system for styled-components",
"license": "MIT",
"repository": "diegohaz/styled-theme",
"main": "index.js",
"author": {
"name": "Diego Haz",
"email": "hazdiego@gmail.com",
"url": "github.com/diegohaz"
},
"files": [
"dist",
"index.js",
"composer.js"
],
"scripts": {
"test": "jest",
"coverage": "npm test -- --coverage",
"postcoverage": "opn coverage/lcov-report/index.html",
"lint": "eslint src test",
"flow": "flow check",
"docs": "documentation readme src --section=API",
"clean": "del dist",
"prebuild": "npm run docs && npm run clean",
"build": "babel src -d dist",
"watch": "npm-watch",
"patch": "npm version patch && npm publish",
"minor": "npm version minor && npm publish",
"major": "npm version major && npm publish",
"prepublish": "npm run lint && npm test && npm run build",
"postpublish": "git push origin master --follow-tags"
},
"watch": {
"test": "{src,test}/*.js",
"lint": "{src,test}/*.js",
"build": "src"
},
"jest": {
"testRegex": "/test/.*",
"testEnvironment": "node"
},
"keywords": [
"styled-components",
"styled",
"style",
"theme",
"theming"
],
"dependencies": {
"coolors-to-hex": "^1.0.0",
"styled-tools": "^0.1.4"
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-eslint": "^7.1.1",
"babel-jest": "^20.0.2",
"babel-plugin-transform-flow-strip-types": "^6.21.0",
"babel-preset-env": "^1.1.8",
"babel-preset-stage-2": "^6.18.0",
"del-cli": "^1.0.0",
"documentation": "4.0.0-rc.0",
"eslint": "^3.14.0",
"eslint-config-airbnb-base": "^11.0.1",
"eslint-plugin-flowtype": "^2.29.2",
"eslint-plugin-flowtype-errors": "^3.0.0",
"eslint-plugin-import": "^2.2.0",
"flow-bin": "^0.50.0",
"jest-cli": "^20.0.2",
"npm-watch": "^0.2.0",
"opn-cli": "^3.1.0"
}
}
================================================
FILE: src/composer.js
================================================
// @flow
import type { Palette } from './types'
/**
* Revert the palette
* @example
* reversePalette({ primary: ['red', 'yellow', 'green'] })
* // { primary: ['green', 'yellow', 'red'] }
*/
export const reversePalette = (palette: Palette): Palette =>
Object.keys(palette).reduce((newPalette, key) => ({
...newPalette,
[key]: [...palette[key]].reverse()
}), {})
================================================
FILE: src/index.js
================================================
// @flow
import { prop } from 'styled-tools'
import theme from './theme'
import type { Theme, Tones, Font, Size } from './types'
type Props = {
theme?: Theme,
palette?: string,
reverse?: boolean
}
/**
* Returns the value of `props.theme[path]` or `styledTheme[path]`
* @example
* const Button = styled.button`
* font-family: ${key('fonts.primary')};
* color: ${key(['colors', 'primary', 0])};
* `
*/
export const key = (path: string | string[], defaultValue?: any): any =>
(props: Props = {}): any => prop(path, prop(path, defaultValue)(theme))(props.theme)
/**
* Shorthand to `key(['fonts', path])`
* @example
* const Button = styled.button`
* font-family: ${font('primary')};
* `
*/
export const font = (path: string, defaultValue?: any): Font =>
key(['fonts', path], defaultValue)
/**
* Shorthand to `key(['sizes', path])`
* @example
* const Button = styled.button`
* padding: ${size('padding')};
* `
*/
export const size = (path: string, defaultValue?: any): Size =>
key(['sizes', path], defaultValue)
/**
* Returns the value of `props.theme[palette || reversePalette][path][index]` or
* `styledTheme[palette || reversePalette][path][index]` (default theme)
*
* The arguments can be passed in any order, as long as types are kept.
* @param {number} index The index of tone in theme palette tones array
* @param {string} [path=props.palette] The key of the tones in theme palette object
* @param {Object} [exceptions] An object with path as key and index as value
* @param {boolean} [reverse] Flag to return tone from `reversePalette` or `palette`
* @param {string} [defaultValue] Default value
* @example
* // index = 1
* // exception = { grayscale: 0 }
* // reverse = true
* const Button = styled.button`
* background-color: ${palette({ grayscale: 0 }, 1, true)};
* `
*
* // renders props.theme.reversePalette.grayscale[0]
*
*
* // renders props.theme.palette.danger[1] (nullify reverse)
*
* @returns {Tones}
*/
// eslint-disable-next-line flowtype-errors/show-errors
export const palette = (...args) => (props: Props = {}): Tones => {
const exceptions = args.find(arg => typeof arg === 'object') || {}
const path = args.find(arg => typeof arg === 'string') || props.palette
const defaultValue = [...args].reverse().find(arg => typeof arg === 'string')
let index = args.find(arg => typeof arg === 'number')
let reverse = args.find(arg => typeof arg === 'boolean')
reverse = reverse ? !props.reverse : props.reverse
if (typeof index === 'undefined') {
throw new Error('[palette] You must pass index')
}
if (typeof path === 'undefined') {
throw new Error('[palette] You must pass palette path')
}
if (Object.keys(exceptions).indexOf(path) >= 0) {
index = exceptions[path]
}
const palettePath = reverse ? 'reversePalette' : 'palette'
return key([palettePath, path, index], defaultValue !== path && defaultValue)(props)
}
================================================
FILE: src/theme.js
================================================
// @flow
import coolorsToHex from 'coolors-to-hex'
import { reversePalette } from './composer'
import type { Theme } from './types'
const theme: Theme = {}
theme.palette = {
primary: coolorsToHex('https://coolors.co/1976d2-2196f3-71bcf7-97cef9-c2e2fb'),
secondary: coolorsToHex('https://coolors.co/c2185b-e91e63-f06292-f48caf-f8bbd0'),
danger: coolorsToHex('https://coolors.co/d32f2f-f44336-f8877f-f9a7a1-ffcdd2'),
alert: coolorsToHex('https://coolors.co/ffa000-ffc107-ffd761-ffecb3-fff2ce'),
success: coolorsToHex('https://coolors.co/388e3c-4caf50-7cc47f-9fd4a1-c8e6c9'),
grayscale: ['#212121', '#616161', '#9e9e9e', '#bdbdbd', '#e0e0e0', '#ffffff']
}
theme.reversePalette = reversePalette(theme.palette)
theme.fonts = {
primary: 'Helvetica Neue, Helvetica, Roboto, sans-serif',
pre: 'Consolas, Liberation Mono, Menlo, Courier, monospace',
quote: 'Georgia, serif'
}
theme.sizes = {
maxWidth: '1100px'
}
export default theme
================================================
FILE: src/types.js
================================================
// @flow
/** */
export type Tone = string
/** */
export type Tones = Array
/** */
export type Font = string
/** */
export type Size = string
/** */
export type Palette = {[string]: Tones}
/** */
export type Fonts = {[string]: Font}
/** */
export type Sizes = {[string]: Size}
/** */
export type Theme = {
palette?: Palette,
reversePalette?: Palette,
fonts?: Fonts,
sizes?: Sizes
}
================================================
FILE: test/composer.js
================================================
import { reversePalette } from '../src/composer'
test('reversePalette', () => {
const palette = {
key1: [1, 2, 3],
key2: [3, 2, 1]
}
expect(reversePalette(palette)).toEqual({
key1: [3, 2, 1],
key2: [1, 2, 3]
})
})
================================================
FILE: test/index.js
================================================
import theme from '../src/theme'
import { key, font, palette, size } from '../src'
describe('key', () => {
const theme2 = {
foo: 'bar'
}
it('returns value from theme when no anotherTheme was passed in', () => {
expect(key('palette')()).toBe(theme.palette)
})
it('returns value from anotherTheme when passed in', () => {
expect(key('foo')({ theme: theme2 })).toBe(theme2.foo)
})
it('returns defaultValue', () => {
expect(key('foo', 'baz')()).toBe('baz')
})
})
describe('size', () => {
const theme2 = {
sizes: {
foo: 'bar'
}
}
it('returns value from theme when no anotherTheme was passed in', () => {
expect(size('maxWidth')()).toBe(theme.sizes.maxWidth)
})
it('returns value from anotherTheme when passed in', () => {
expect(size('foo')({ theme: theme2 })).toBe(theme2.sizes.foo)
})
it('returns defaultValue', () => {
expect(size('foo', 'baz')()).toBe('baz')
})
})
describe('font', () => {
const theme2 = {
fonts: {
foo: 'bar',
pre: 'test'
}
}
it('returns default font when no anotherTheme was passed in', () => {
expect(font('primary')()).toBe(theme.fonts.primary)
})
it('returns default font when it does not exist on anotherTheme', () => {
expect(font('primary')({ theme: theme2 })).toBe(theme.fonts.primary)
expect(font('quote')({ theme: theme2 })).toBe(theme.fonts.quote)
})
it('returns anotherTheme font when it exists', () => {
expect(font('foo')({ theme: theme2 })).toBe(theme2.fonts.foo)
expect(font('pre')({ theme: theme2 })).toBe(theme2.fonts.pre)
})
it('returns defaultValue', () => {
expect(font('foo', 'baz')()).toBe('baz')
})
})
describe('palette', () => {
const theme2 = {
palette: {
foo: ['bar', 'baz']
},
reversePalette: {
foo: ['baz', 'bar']
}
}
it('throws when no index was passed in', () => {
expect(() => palette()({ theme: theme2, palette: 'primary' })).toThrow()
})
it('throws when no palette was passed in', () => {
expect(() => palette(0)({ theme: theme2 })).toThrow()
})
it('returns palette at index when palette was passed in with props', () => {
expect(palette(0)({ theme: theme2, palette: 'primary' })).toBe(theme.palette.primary[0])
expect(palette(0)({ theme: theme2, palette: 'foo' })).toBe(theme2.palette.foo[0])
expect(palette(0)({ theme: theme2, palette: 'danger', reverse: true }))
.toBe(theme.reversePalette.danger[0])
})
it('returns palette at index when palette was passed in with args ignoring props', () => {
expect(palette('danger', 1)()).toBe(theme.palette.danger[1])
expect(palette('danger', 1)({ theme: theme2 })).toBe(theme.palette.danger[1])
expect(palette('danger', 1)({ theme: theme2, palette: 'foo' })).toBe(theme.palette.danger[1])
expect(palette('danger', 1)({ theme: theme2, reverse: true }))
.toBe(theme.reversePalette.danger[1])
})
it('returns palette at proper index when exception was passed in', () => {
expect(palette(1, { danger: 0 })({ theme: theme2, palette: 'foo' })).toBe(theme2.palette.foo[1])
expect(palette(1, { danger: 0 })({ theme: theme2, palette: 'danger' }))
.toBe(theme.palette.danger[0])
})
it('returns reverse palette when true argument is passed in', () => {
expect(palette(1, true)({ theme: theme2, palette: 'foo' })).toBe(theme2.reversePalette.foo[1])
expect(palette(1, true)({ theme: theme2, palette: 'foo', reverse: true }))
.toBe(theme2.palette.foo[1])
expect(palette(1, true)({ theme: theme2, palette: 'danger' }))
.toBe(theme.reversePalette.danger[1])
})
it('returns defaultValue', () => {
expect(palette('foo', 1, 'red')()).toBe('red')
expect(palette('foo', 1, 'red')({ theme: theme2 })).toBe(theme2.palette.foo[1])
})
})