├── .eslintrc ├── .vscode └── settings.json ├── .gitignore ├── docs ├── favicon.ico ├── static │ ├── preview.87ecc1030fac931c5992.bundle.js.map │ └── manager.958779b5fb60b2065863.bundle.js.map ├── iframe.html └── index.html ├── assets └── example.gif ├── src ├── index.js ├── main.js ├── CallLimiter.js ├── Chip.js ├── theme.js └── Chips.js ├── .npmignore ├── .babelrc ├── .storybook ├── config.js └── webpack.config.js ├── site ├── bundle.js.map └── src │ ├── Root.js │ ├── index.js │ ├── basic.js │ ├── customChipTheme.js │ ├── async.js │ ├── CustomChip.js │ └── custom.js ├── circle.yml ├── index.html ├── tools ├── build.sh └── devServer.js ├── stories ├── Chips.js ├── CustomChip.js └── index.js ├── __tests__ └── Chips.test.js ├── webpack.config.js ├── webpack.config.prod.js ├── LICENSE ├── package.json └── README.md /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint" 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "vsicons.presets.angular": false 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /dist 3 | npm-debug.log 4 | lib 5 | coverage -------------------------------------------------------------------------------- /docs/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gregchamberlain/react-chips/HEAD/docs/favicon.ico -------------------------------------------------------------------------------- /assets/example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gregchamberlain/react-chips/HEAD/assets/example.gif -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import Chips from './Chips'; 2 | export default Chips; 3 | export Chip from './Chip'; 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | /src 2 | /example 3 | /node_modules 4 | .babelrc 5 | webpack.config.js 6 | .gitignore 7 | .eslintrc 8 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["es2015", "stage-0", "react"], 3 | "env": { 4 | "development": { 5 | "plugins": ["react-hot-loader/babel"] 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.storybook/config.js: -------------------------------------------------------------------------------- 1 | import { configure } from '@kadira/storybook'; 2 | 3 | function loadStories() { 4 | require('../stories'); 5 | } 6 | 7 | configure(loadStories, module); 8 | -------------------------------------------------------------------------------- /site/bundle.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"bundle.js","sources":["webpack:///bundle.js"],"mappings":"AAAA;;;;;AA0QA;AAw5IA;;;;;;;;;;;;;;AAwjCA;AAgjHA;;;;;AAq1DA;;;;;AA2kBA;AAwkEA;AA60EA;AAujGA;AA8hIA","sourceRoot":""} -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from 'react-dom' 3 | import Chips from 'react-chips' 4 | 5 | let items = ["Java", "Ruby", "Javascript", "C", "C++"] 6 | 7 | render(, document.getElementById("root")); 8 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | machine: 2 | environment: 3 | PATH: "${PATH}:${HOME}/${CIRCLE_PROJECT_REPONAME}/node_modules/.bin" 4 | 5 | dependencies: 6 | override: 7 | - yarn 8 | cache_directories: 9 | - ~/.cache/yarn 10 | 11 | test: 12 | override: 13 | - yarn test -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | React Component Skeleton 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /tools/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # build minified standalone version in dist 4 | # rm -rf dist 5 | # ./node_modules/.bin/webpack --output-filename=dist/ReactDnD.js 6 | # ./node_modules/.bin/webpack --output-filename=dist/ReactDnD.min.js --optimize-minimize 7 | 8 | # build ES5 modules to lib 9 | rm -rf lib 10 | ./node_modules/.bin/babel src --out-dir lib 11 | -------------------------------------------------------------------------------- /docs/static/preview.87ecc1030fac931c5992.bundle.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"static/preview.87ecc1030fac931c5992.bundle.js","sources":["webpack:///static/preview.87ecc1030fac931c5992.bundle.js"],"mappings":"AAAA;AAkuDA;AAq1DA;AAqkEA;AAgtDA;AAs9CA;AA6jEA;AAirDA;AA+iDA;AAw7DA;AAooDA;AA67CA;AAiqDA;AA+kEA;AAo1DA;AA46CA;AAg2CA;AAyhDA;AA8jEA;AA4/DA;AAwmDA;AAq3DA;AAi6CA;AAkuDA;AA29CA;AA+7CA;AAuoCA;AA+uCA;AA2nCA","sourceRoot":""} -------------------------------------------------------------------------------- /docs/static/manager.958779b5fb60b2065863.bundle.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"static/manager.958779b5fb60b2065863.bundle.js","sources":["webpack:///static/manager.958779b5fb60b2065863.bundle.js"],"mappings":"AAAA;AAkuDA;AA+3DA;AAsgEA;AAgwDA;AA6uEA;AAqyDA;AAs+CA;AA0kDA;AAu3DA;AAqrDA;AAi+CA;AAwnDA;AAijEA;AA83DA;AA+7CA;AAizCA;AAynDA;AAgkEA;AA68DA;AAupDA;AA04DA;AA+1DA;AA4mDA;AAo4DA;AA8zEA;AA40FA;AAjHA;AAioGA;AAgoEA;AAupEA;AA7bA;AA+8DA","sourceRoot":""} -------------------------------------------------------------------------------- /site/src/Root.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import BasicExample from './basic'; 4 | import CustomExample from './custom'; 5 | import AsyncExample from './async'; 6 | import CustomChipThemeExample from './customChipTheme'; 7 | 8 | const Root = () => ( 9 |
10 |

Basic

11 | 12 |

Custom

13 | 14 |

Custom Chip Theme

15 | 16 |

Async

17 | 18 |
19 | ); 20 | 21 | export default Root; 22 | -------------------------------------------------------------------------------- /.storybook/webpack.config.js: -------------------------------------------------------------------------------- 1 | // you can use this file to add your custom webpack plugins, loaders and anything you like. 2 | // This is just the basic way to add addional webpack configurations. 3 | // For more information refer the docs: https://goo.gl/qPbSyX 4 | 5 | // IMPORTANT 6 | // When you add this file, we won't add the default configurations which is similar 7 | // to "React Create App". This only has babel loader to load JavaScript. 8 | 9 | module.exports = { 10 | plugins: [ 11 | // your custom plugins 12 | ], 13 | module: { 14 | loaders: [ 15 | // add your custom loaders. 16 | ], 17 | }, 18 | }; 19 | -------------------------------------------------------------------------------- /stories/Chips.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Chips from '../src'; 3 | 4 | class ChipsExample extends Component { 5 | 6 | constructor(props) { 7 | super(props); 8 | this.state = { 9 | chips: [] 10 | }; 11 | } 12 | 13 | updateChips = chips => { 14 | if (this.props.onChange) { 15 | this.props.onChange(); 16 | } 17 | this.setState({ chips }); 18 | } 19 | 20 | render() { 21 | const { chips } = this.state; 22 | return ( 23 | 24 | ); 25 | } 26 | } 27 | 28 | export default ChipsExample; 29 | -------------------------------------------------------------------------------- /__tests__/Chips.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | 4 | import Chips from '../src/Chips'; 5 | 6 | const minProps = { 7 | value: [], 8 | onChange: () => {} 9 | }; 10 | 11 | const withChipTheme = { 12 | ...minProps, 13 | chipTheme: { chip: { padding: 100 } } 14 | } 15 | 16 | test('Renders without exploding', () => { 17 | 18 | const chips = shallow( 19 | 20 | ); 21 | 22 | expect(chips); 23 | 24 | }); 25 | 26 | test('Renders with chipTheme without exploiding', () => { 27 | 28 | const chips = shallow( 29 | 30 | ); 31 | 32 | expect(chips); 33 | 34 | }); -------------------------------------------------------------------------------- /docs/iframe.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | React Storybook 13 | 14 | 15 | 16 | 17 |
18 |
19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /site/src/index.js: -------------------------------------------------------------------------------- 1 | import { AppContainer } from 'react-hot-loader'; 2 | import React from 'react'; 3 | import { render } from 'react-dom'; 4 | 5 | import Root from './Root'; 6 | 7 | const rootEl = document.getElementById('root'); 8 | render( 9 | 10 | 11 | , 12 | rootEl 13 | ); 14 | 15 | if (module.hot) { 16 | module.hot.accept('./Root', () => { 17 | // If you use Webpack 2 in ES modules mode, you can 18 | // use here rather than require() a . 19 | const NextRoot = require('./Root').default; 20 | render( 21 | 22 | 23 | , 24 | rootEl 25 | ); 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | var webpack = require('webpack'); 3 | 4 | module.exports = { 5 | devtool: 'eval', 6 | entry: [ 7 | 'react-hot-loader/patch', 8 | 'webpack-hot-middleware/client', 9 | './site/src/index.js' 10 | ], 11 | output: { 12 | path: path.join(__dirname, 'site'), 13 | filename: 'bundle.js', 14 | publicPath: '/site/' 15 | }, 16 | plugins: [ 17 | new webpack.optimize.OccurenceOrderPlugin(), 18 | new webpack.HotModuleReplacementPlugin(), 19 | new webpack.NoErrorsPlugin(), 20 | ], 21 | module: { 22 | loaders: [{ 23 | test: /\.js?$/, 24 | loaders: ['babel'], 25 | exclude: /node_modules/ 26 | }] 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/CallLimiter.js: -------------------------------------------------------------------------------- 1 | 2 | class CallLimitier { 3 | 4 | constructor(fn, interval){ 5 | this.fn = fn; 6 | this.interval = interval || 20; 7 | } 8 | 9 | register(fn, ctx) { 10 | this.fn = fn; 11 | } 12 | 13 | get tm() { 14 | return this._tm 15 | } 16 | 17 | set tm(value) { 18 | this._tm = value; 19 | } 20 | 21 | invoke() { 22 | let args = arguments; 23 | if(this.tm){ 24 | clearTimeout(this.tm); 25 | } 26 | let currentTm = this.tm = setTimeout(() => { 27 | let canceled = { 28 | isCancaled: () => this.tm !== currentTm 29 | }; 30 | this.fn.call(null, ...args, canceled); 31 | }, this.interval); 32 | } 33 | } 34 | 35 | export default CallLimitier; -------------------------------------------------------------------------------- /tools/devServer.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | var webpack = require('webpack'); 3 | var express = require('express'); 4 | var devMiddleware = require('webpack-dev-middleware'); 5 | var hotMiddleware = require('webpack-hot-middleware'); 6 | var config = require('../webpack.config'); 7 | 8 | var app = express(); 9 | var compiler = webpack(config); 10 | 11 | app.use(devMiddleware(compiler, { 12 | publicPath: config.output.publicPath, 13 | historyApiFallback: true, 14 | })); 15 | 16 | app.use(hotMiddleware(compiler)); 17 | 18 | app.get('*', function (req, res) { 19 | res.sendFile(path.join(__dirname, '../index.html')); 20 | }); 21 | 22 | app.listen(3000, function (err) { 23 | if (err) { 24 | return console.error(err); 25 | } 26 | 27 | console.log('Listening at http://localhost:3000/'); 28 | }); 29 | -------------------------------------------------------------------------------- /webpack.config.prod.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | var webpack = require('webpack'); 3 | 4 | module.exports = { 5 | devtool: 'cheap-module-source-map', 6 | entry: './site/src/index.js', 7 | output: { 8 | path: path.join(__dirname, 'site'), 9 | filename: 'bundle.js', 10 | }, 11 | plugins: [ 12 | new webpack.optimize.OccurenceOrderPlugin(), 13 | new webpack.NoErrorsPlugin(), 14 | new webpack.DefinePlugin({ 15 | 'process.env':{ 16 | 'NODE_ENV': JSON.stringify('production') 17 | } 18 | }), 19 | new webpack.optimize.UglifyJsPlugin({ 20 | compress:{ 21 | warnings: false 22 | } 23 | }) 24 | ], 25 | module: { 26 | loaders: [{ 27 | test: /\.js?$/, 28 | loaders: ['babel'], 29 | exclude: /node_modules/ 30 | }] 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /site/src/basic.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Chips, { Chip } from '../../src' 3 | 4 | const data = [ 5 | 'JavaScript', 6 | 'Ruby', 7 | 'Python', 8 | 'Java', 9 | 'Swift', 10 | 'C++', 11 | 'C', 12 | 'Objective C', 13 | 'Go' 14 | ]; 15 | 16 | class BasicExample extends Component { 17 | 18 | constructor(props) { 19 | super(props); 20 | this.state = { 21 | value: [] 22 | } 23 | } 24 | 25 | onChange = value => { 26 | this.setState({ value }); 27 | } 28 | 29 | render() { 30 | return ( 31 | value.length >= 0} 38 | fromSuggestionsOnly={false} /> 39 | ); 40 | } 41 | } 42 | 43 | export default BasicExample; 44 | -------------------------------------------------------------------------------- /site/src/customChipTheme.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Chips, { Chip } from '../../src' 3 | 4 | const data = [ 5 | 'JavaScript', 6 | 'Ruby', 7 | 'Python', 8 | 'Java', 9 | 'Swift', 10 | 'C++', 11 | 'C', 12 | 'Objective C', 13 | 'Go' 14 | ]; 15 | 16 | class CustomChipThemeExample extends Component { 17 | 18 | constructor(props) { 19 | super(props); 20 | this.state = { 21 | value: [] 22 | } 23 | } 24 | 25 | onChange = value => { 26 | this.setState({ value }); 27 | } 28 | 29 | render() { 30 | return ( 31 | value.length >= 0} 39 | fromSuggestionsOnly={false} /> 40 | ); 41 | } 42 | } 43 | 44 | export default CustomChipThemeExample; 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2016 Gregory Chamberlain 3 | 4 | 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: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | 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. 9 | -------------------------------------------------------------------------------- /site/src/async.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Chips, { Chip } from '../../src' 3 | 4 | const data = [ 5 | 'JavaScript', 6 | 'Ruby', 7 | 'Python', 8 | 'Java', 9 | 'Swift', 10 | 'C++', 11 | 'C', 12 | 'Objective C', 13 | 'Go' 14 | ]; 15 | 16 | class AsyncExample extends Component { 17 | 18 | constructor(props) { 19 | super(props); 20 | this.state = { 21 | value: [] 22 | } 23 | } 24 | 25 | fetchData(value) { 26 | return new Promise((resolve, reject) => { 27 | 28 | if(value.length >= 1){ 29 | 30 | setTimeout(() => { 31 | let filtered = data.filter(opt => opt.toLowerCase().indexOf(value.toLowerCase()) !== -1); 32 | resolve(filtered); 33 | }, 1000); 34 | 35 | } else { 36 | resolve([]); 37 | } 38 | 39 | }); 40 | } 41 | 42 | onChange = value => { 43 | this.setState({ value }); 44 | } 45 | 46 | render() { 47 | return ( 48 | value.length >= 0} 55 | fromSuggestionsOnly={false} /> 56 | ); 57 | } 58 | } 59 | 60 | export default AsyncExample; 61 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | React Storybook 9 | 38 | 39 | 40 |
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /site/src/CustomChip.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Radium from 'radium'; 3 | 4 | class CustomChip extends Component { 5 | render() { 6 | return ( 7 |
8 | 9 |
{this.props.children}
10 |
this.props.onRemove(this.props.index)}>×
11 |
12 | ); 13 | } 14 | } 15 | 16 | let styles = { 17 | selected: { 18 | background: "#ccc", 19 | }, 20 | container: { 21 | display: "flex", 22 | alignItems: "center", 23 | height: 32, 24 | boxSizing: 'border-box', 25 | color: "#444", 26 | background: "#e0e0e0", 27 | margin: "2.5px", 28 | borderRadius: 16, 29 | cursor: 'default', 30 | }, 31 | image: { 32 | width: 32, 33 | height: 32, 34 | overflow: 'hidden', 35 | borderRadius: 16, 36 | background: "#888", 37 | }, 38 | text: { 39 | fontSize: 13, 40 | boxSizing: 'border-box', 41 | padding: '0px 4px 0px 8px', 42 | }, 43 | remove: { 44 | textAlign: "center", 45 | cursor: "pointer", 46 | fontSize: 18, 47 | width: 20, 48 | height: 20, 49 | color: "#e0e0e0", 50 | borderRadius: 12, 51 | background: "#aaa", 52 | margin: "0 6px" 53 | } 54 | } 55 | 56 | export default Radium(CustomChip) 57 | -------------------------------------------------------------------------------- /stories/CustomChip.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Radium from 'radium'; 3 | 4 | class CustomChip extends Component { 5 | render() { 6 | return ( 7 |
8 | 9 |
{this.props.children}
10 |
this.props.onRemove(this.props.index)}>×
11 |
12 | ); 13 | } 14 | } 15 | 16 | let styles = { 17 | selected: { 18 | background: "#666", 19 | }, 20 | container: { 21 | display: "flex", 22 | alignItems: "center", 23 | height: 32, 24 | boxSizing: 'border-box', 25 | color: "#eee", 26 | fontWeight: 'bold', 27 | background: "#333", 28 | margin: "2.5px", 29 | borderRadius: 16, 30 | cursor: 'default', 31 | }, 32 | image: { 33 | width: 24, 34 | height: 24, 35 | margin: 4, 36 | overflow: 'hidden', 37 | borderRadius: 12, 38 | background: "#888", 39 | }, 40 | text: { 41 | fontSize: 13, 42 | boxSizing: 'border-box', 43 | padding: '0px 4px 0px 8px', 44 | }, 45 | remove: { 46 | textAlign: "center", 47 | cursor: "pointer", 48 | fontSize: 18, 49 | width: 20, 50 | height: 20, 51 | color: "#e0e0e0", 52 | borderRadius: 12, 53 | background: "#666", 54 | margin: "0 6px" 55 | } 56 | } 57 | 58 | export default Radium(CustomChip) 59 | -------------------------------------------------------------------------------- /src/Chip.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import PropTypes from 'prop-types'; 3 | import Radium from 'radium'; 4 | import themeable from 'react-themeable'; 5 | import { chipTheme } from './theme'; 6 | 7 | const Chip = ({ selected, theme, onRemove, children }) => { 8 | // if someone provided a theme, try and merge between the original and provided 9 | const mergedTheme = deepMerge(chipTheme, theme); 10 | const themr = themeable(mergedTheme); 11 | return ( 12 |
13 | {children} 14 | × 17 |
18 | ); 19 | } 20 | 21 | Chip.propTypes = { 22 | theme: PropTypes.object, 23 | selected: PropTypes.bool, 24 | onRemove: PropTypes.func, 25 | } 26 | 27 | Chip.defaultProps = { 28 | theme: chipTheme, 29 | selected: false, 30 | } 31 | 32 | // from https://stackoverflow.com/a/49798508/1824521 33 | const deepMerge = (...sources) => { 34 | let acc = {} 35 | for (const source of sources) { 36 | if (source instanceof Array) { 37 | if (!(acc instanceof Array)) { 38 | acc = [] 39 | } 40 | acc = [...acc, ...source] 41 | } else if (source instanceof Object) { 42 | for (let [key, value] of Object.entries(source)) { 43 | if (value instanceof Object && key in acc) { 44 | value = deepMerge(acc[key], value) 45 | } 46 | acc = { ...acc, [key]: value } 47 | } 48 | } 49 | } 50 | return acc 51 | } 52 | 53 | export default Radium(Chip); 54 | -------------------------------------------------------------------------------- /src/theme.js: -------------------------------------------------------------------------------- 1 | const theme = { 2 | chipsContainer: { 3 | display: "flex", 4 | position: "relative", 5 | border: "1px solid #ccc", 6 | backgroundColor: '#fff', 7 | font: "13.33333px Arial", 8 | minHeight: 24, 9 | alignItems: "center", 10 | flexWrap: "wrap", 11 | padding: "2.5px", 12 | borderRadius: 5, 13 | ':focus': { 14 | border: "1px solid #aaa", 15 | } 16 | }, 17 | container:{ 18 | flex: 1, 19 | }, 20 | containerOpen: { 21 | 22 | }, 23 | input: { 24 | border: 'none', 25 | outline: 'none', 26 | boxSizing: 'border-box', 27 | width: '100%', 28 | padding: 5, 29 | margin: 2.5 30 | }, 31 | suggestionsContainer: { 32 | 33 | }, 34 | suggestionsList: { 35 | position: 'absolute', 36 | border: '1px solid #ccc', 37 | zIndex: 10, 38 | left: 0, 39 | top: '100%', 40 | width: '100%', 41 | backgroundColor: '#fff', 42 | listStyle: 'none', 43 | padding: 0, 44 | margin: 0, 45 | }, 46 | suggestion: { 47 | padding: '5px 15px' 48 | }, 49 | suggestionHighlighted: { 50 | background: '#ddd' 51 | }, 52 | sectionContainer: { 53 | 54 | }, 55 | sectionTitle: { 56 | 57 | }, 58 | } 59 | 60 | export default theme; 61 | 62 | export const chipTheme = { 63 | chip: { 64 | padding: 5, 65 | background: "#ccc", 66 | margin: "2.5px", 67 | borderRadius: 3, 68 | cursor: 'default', 69 | }, 70 | chipSelected: { 71 | background: '#888', 72 | }, 73 | chipRemove: { 74 | fontWeight: "bold", 75 | cursor: "pointer", 76 | ':hover': { 77 | color: 'red', 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-chips", 3 | "version": "0.8.0", 4 | "description": "A flexible and easy to use Chips component for React", 5 | "keywords": [ 6 | "react", 7 | "react-component" 8 | ], 9 | "main": "lib/index.js", 10 | "scripts": { 11 | "start": "node tools/devServer.js", 12 | "test": "jest", 13 | "test:watch": "npm run test -- --watch", 14 | "test:coverage": "npm run test -- --coverage", 15 | "build": "NODE_ENV=production ./tools/build.sh", 16 | "buildSite": "NODE_ENV=production webpack --config webpack.config.prod.js --progress", 17 | "prepublish": "npm run build", 18 | "storybook": "start-storybook -p 6006", 19 | "build-storybook": "build-storybook -c .storybook -o docs" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/gregchamberlain/react-chips.git" 24 | }, 25 | "author": "Greg Chamberlain (https://gregchamberlain.github.io)", 26 | "license": "ISC", 27 | "bugs": { 28 | "url": "https://github.com/gregchamberlain/react-chips/issues" 29 | }, 30 | "homepage": "https://github.com/gregchamberlain/react-chips#readme", 31 | "devDependencies": { 32 | "@kadira/storybook": "^2.35.3", 33 | "babel-cli": "^6.16.0", 34 | "babel-core": "^6.5.2", 35 | "babel-eslint": "^6.1.2", 36 | "babel-jest": "^19.0.0", 37 | "babel-loader": "^6.2.3", 38 | "babel-preset-es2015": "^6.5.0", 39 | "babel-preset-react": "^6.5.0", 40 | "babel-preset-stage-0": "^6.5.0", 41 | "enzyme": "^3.7.0", 42 | "eslint": "^3.3.0", 43 | "express": "^4.14.0", 44 | "jest": "^19.0.1", 45 | "prop-types": "^15.6.2", 46 | "react": "^16.5.2", 47 | "react-dom": "^16.5.2", 48 | "react-hot-loader": "^4.3.11", 49 | "react-test-renderer": "^16.5.2", 50 | "webpack": "^1.14.0", 51 | "webpack-dev-middleware": "^1.8.4", 52 | "webpack-hot-middleware": "^2.13.2" 53 | }, 54 | "peerDependencies": { 55 | "prop-types": "^15.6.2", 56 | "react": "^0.14.0 || ^16.4.1" 57 | }, 58 | "dependencies": { 59 | "radium": "^0.25.0", 60 | "react-autosuggest": "^9.0.1", 61 | "react-themeable": "^1.1.0" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /site/src/custom.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import Chips, { Chip } from '../../src' 3 | import CustomChip from './CustomChip' 4 | 5 | const data = [ 6 | {name: 'JavaScript', image: 'http://i.stack.imgur.com/Mmww2.png'}, 7 | {name: 'Ruby', image: 'https://www.codementor.io/assets/tutorial_icon/ruby-on-rails.png' }, 8 | {name: 'Python', image: 'http://www.iconarchive.com/download/i73027/cornmanthe3rd/plex/Other-python.ico' }, 9 | {name: 'Java', image: 'https://cdn2.iconfinder.com/data/icons/metro-ui-dock/128/Java.png' }, 10 | {name: 'Swift', image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTcNaPStsM3XwWDAgvjFfT5RFcDxuynJUJmY4lH5PSMyhphA9hA' }, 11 | {name: 'C++', image: 'http://www.freeiconspng.com/uploads/c--logo-icon-0.png' }, 12 | {name: 'C', image: 'http://www.compindiatechnologies.com/images/icon/c.gif' }, 13 | {name: 'Objective C', image: 'http://2.bp.blogspot.com/-BuR1DpqQprU/U5CQ_0w2L7I/AAAAAAAABZY/H9wbfbO-kew/s1600/iOS_Objective_C.png' }, 14 | {name: 'Go', image: 'https://www.codemate.com/wp-content/uploads/2015/11/go-lang-icon-180x180.png' }, 15 | ]; 16 | 17 | class CustomExample extends Component { 18 | 19 | constructor(props) { 20 | super(props); 21 | this.state = { 22 | value: [] 23 | } 24 | } 25 | 26 | onChange = value => { 27 | this.setState({ value }); 28 | } 29 | 30 | render() { 31 | return ( 32 | ( 38 | {item.name} 39 | )} 40 | fromSuggestionsOnly={true} 41 | renderSuggestion={(item, { query }) => ( 42 |
45 | {item.name} 46 |
47 | )} 48 | suggestionsFilter={(opt, val) => ( 49 | opt.name.toLowerCase().indexOf(val.toLowerCase()) !== -1 50 | )} 51 | getSuggestionValue={suggestion => suggestion.name} 52 | /> 53 | ); 54 | } 55 | } 56 | 57 | const style = { 58 | display: "flex", 59 | alignItems: "center", 60 | padding: '2px 6px', 61 | cursor: 'default' 62 | } 63 | 64 | export default CustomExample; 65 | -------------------------------------------------------------------------------- /stories/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { storiesOf, action, linkTo } from '@kadira/storybook'; 3 | import Chips from './Chips'; 4 | import CustomChip from './CustomChip'; 5 | 6 | const suggestions = [ 7 | 'JavaScript', 8 | 'Ruby', 9 | 'Python', 10 | 'Java', 11 | 'Swift', 12 | 'C++', 13 | 'C', 14 | 'Objective C', 15 | 'Go' 16 | ]; 17 | 18 | const data = [ 19 | {name: 'JavaScript', image: 'http://i.stack.imgur.com/Mmww2.png'}, 20 | {name: 'Ruby', image: 'https://www.sitepoint.com/wp-content/themes/sitepoint/assets/images/icon.ruby.png' }, 21 | {name: 'Python', image: 'http://www.iconarchive.com/download/i73027/cornmanthe3rd/plex/Other-python.ico' }, 22 | {name: 'Java', image: 'https://cdn2.iconfinder.com/data/icons/metro-ui-dock/128/Java.png' }, 23 | {name: 'Swift', image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTcNaPStsM3XwWDAgvjFfT5RFcDxuynJUJmY4lH5PSMyhphA9hA' }, 24 | {name: 'C++', image: 'http://www.freeiconspng.com/uploads/c--logo-icon-0.png' }, 25 | {name: 'C', image: 'http://www.compindiatechnologies.com/images/icon/c.gif' }, 26 | {name: 'Objective C', image: 'http://2.bp.blogspot.com/-BuR1DpqQprU/U5CQ_0w2L7I/AAAAAAAABZY/H9wbfbO-kew/s1600/iOS_Objective_C.png' }, 27 | {name: 'Go', image: 'https://www.codemate.com/wp-content/uploads/2015/11/go-lang-icon-180x180.png' }, 28 | ]; 29 | 30 | const fetchSuggestions = (value) => { 31 | return new Promise((resolve, reject) => { 32 | if(value.length >= 1){ 33 | setTimeout(() => { 34 | let filtered = suggestions 35 | .filter(opt => opt.toLowerCase().indexOf(value.toLowerCase()) !== -1) 36 | resolve(filtered); 37 | }, 1000); 38 | } else { 39 | resolve([]); 40 | } 41 | }); 42 | }; 43 | 44 | storiesOf('Chips', module) 45 | .add('Basic', () => ( 46 | 52 | )) 53 | .add('Custom Chip Theme', () => ( 54 | value.length >= 0} 58 | fromSuggestionsOnly={false} /> 59 | )) 60 | .add('Custom Chip', () => ( 61 | ( 65 | {item.name} 66 | )} 67 | fromSuggestionsOnly={true} 68 | renderSuggestion={(item, { query }) => ( 69 |
72 | {item.name} 73 |
74 | )} 75 | suggestionsFilter={(opt, val) => ( 76 | opt.name.toLowerCase().indexOf(val.toLowerCase()) !== -1 77 | )} 78 | getSuggestionValue={suggestion => suggestion.name} 79 | /> 80 | )) 81 | .add('Async', () => ( 82 | 86 | )); 87 | 88 | 89 | const style = { 90 | display: "flex", 91 | alignItems: "center", 92 | padding: '2px 6px', 93 | cursor: 'default' 94 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Chips [![npm package](https://img.shields.io/npm/v/react-chips.svg?style=flat-square)](https://www.npmjs.org/package/react-chips) [![Build Status](https://img.shields.io/circleci/project/github/gregchamberlain/react-chips/master.svg?style=flat-square)](https://circleci.com/gh/gregchamberlain/react-chips) 2 | 3 | A controlled React input for arrays of data. 4 | ![Example](assets/example.gif) 5 | 6 | **Chip** 7 | 8 | A chip is a component used to represent an arbitrary data object. 9 | 10 | 11 | ## Getting Started 12 | 13 | ``` 14 | npm install --save react-chips 15 | ``` 16 | 17 | ```js 18 | import React, { Component } from 'react'; 19 | import Chips, { Chip } from '../src' 20 | 21 | class YourComponent extends Component { 22 | 23 | constructor(props) { 24 | super(props); 25 | this.state = { 26 | chips: [] 27 | } 28 | } 29 | 30 | onChange = chips => { 31 | this.setState({ chips }); 32 | } 33 | 34 | render() { 35 | return ( 36 |
37 | 43 |
44 | ); 45 | } 46 | } 47 | ``` 48 | 49 | ## Chips 50 | 51 | |Property|Type|Required|Description| 52 | |--------|----|:-----:|-----------| 53 | |`value`|Array|✓|An array of data that represents the value of the chips| 54 | |`onChange`|Function|✓|A function called when the value of chips changes, passes the chips value as an argument.| 55 | |`placeholder`|String||The placeholder to populate the input with| 56 | |`theme`|Object||A [react-themeable](https://github.com/markdalgleish/react-themeable) theme| 57 | |`chipTheme`|Object|| A [react-themeable](https://github.com/markdalgleish/react-themeable) theme that will override the default chip theme, 58 | |`suggestions`|Array||Data to fill the autocomplete list with| 59 | |`fetchSuggestions`|Function|| Delegate expecting to recive autocomplete suggestions (callback or promise)| 60 | |`fetchSuggestionsThrushold`|Number|| Maximum calls to fetchSuggestions per-second | 61 | |`fromSuggestionsOnly`|Boolean||Only allow chips to be added from the suggestions list| 62 | |`uniqueChips`|Boolean||Only allow one chip for each object| 63 | |`renderChip`|Function||For custom chip usage. A function that passes the value of the chip as an argument, must return an element that will be rendered as each chip.| 64 | |`suggestionsFilter`|Function||A function that is passed an autoCompleteData item, and the current input value as arguments. Must return a boolean for if the item should be shown.| 65 | |`getChipValue`|Function||A function used to change the value that is passed into each chip.| 66 | |`createChipKeys`|Array||An array of keys/keyCodes that will create a chip with the current input value when pressed. (Will not work of `fromSuggestionsOnly` is true).| 67 | |`getSuggestionValue`|Function||The value to show in the input when a suggestion is selected| 68 | |`renderSuggestion`|Function||For custom autocomplete list item usage. A function that passes the value as an argument, must return an element to render for each list item.| 69 | |`shouldRenderSuggestions`|Function||See [AutoSuggest](https://github.com/moroshko/react-autosuggest#shouldRenderSuggestionsProp)| 70 | |`alwaysRenderSuggestions`|Boolean||See [AutoSuggest](https://github.com/moroshko/react-autosuggest#alwaysRenderSuggestionsProp)| 71 | |`highlightFirstSuggestion`|Boolean||See [AutoSuggest](https://github.com/moroshko/react-autosuggest#focusFirstSuggestionProp)| 72 | |`focusInputOnSuggestionClick`|Boolean||See [AutoSuggest](https://github.com/moroshko/react-autosuggest#focusInputOnSuggestionClickProp)| 73 | |`multiSection`|Boolean||See [AutoSuggest](https://github.com/moroshko/react-autosuggest#multiSectionProp)| 74 | |`renderSectionTitle`|Function|✓ when multiSection={true}|See [AutoSuggest](https://github.com/moroshko/react-autosuggest#renderSectionTitleProp)| 75 | |`getSectionSuggestions`|Function|✓ when multiSection={true}|See [AutoSuggest](https://github.com/moroshko/react-autosuggest#getSectionSuggestionsProp)| 76 | 77 | ## Styles 78 | 79 | This project uses [react-themeable](https://github.com/markdalgleish/react-themeable) and [Radium](http://stack.formidable.com/radium/) for styling. The `Chips`, and default `Chip` components both accept a theme prop. The theme structure, and default theme can be found [here](src/theme.js) 80 | 81 | ## Custom Chip Component 82 | You may use a custom chip component, simply return the custom component to the renderChip prop function. This component will receive the following additional props from the Chips component. 83 | 84 | ```js 85 | {value}} 88 | /> 89 | ``` 90 | 91 | |Property|Type|Description| 92 | |--------|----|-----------| 93 | |selected|bool|A boolean that tells the chip if it is currently selected.| 94 | |onRemove|func|A function to be invoked when the chip should be removed| 95 | 96 | ## Async Suggestions 97 | To fetch asynchronous suggestions use `fetchSuggestions`. 98 | 99 | ```js 100 | { 103 | someAsynCall(callback) 104 | }} 105 | /> 106 | 107 | // or with a Promise 108 | 109 | someAsyncCallThatReturnsPromise} 112 | /> 113 | ``` -------------------------------------------------------------------------------- /src/Chips.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import Autosuggest from 'react-autosuggest'; 4 | import Radium from 'radium'; 5 | import themeable from 'react-themeable'; 6 | 7 | import theme from './theme'; 8 | import Chip from './Chip'; 9 | import CallLimiter from './CallLimiter'; 10 | import { chipTheme } from './theme' 11 | 12 | class Chips extends Component { 13 | 14 | constructor(props) { 15 | super(props) 16 | this.state = { 17 | loading: false, 18 | value: "", 19 | chipSelected: false, 20 | suggestions: [] 21 | }; 22 | 23 | this.asyncSuggestLimiter = 24 | new CallLimiter(this.callFetchSuggestions.bind(this), 1000 / props.fetchSuggestionsThrushold); 25 | } 26 | 27 | componentWillReceiveProps = (nextProps) => { 28 | this.asyncSuggestLimiter.interval = (1000 / nextProps.fetchSuggestionsThrushold); 29 | } 30 | 31 | onBlur = e => { 32 | this.refs.wrapper.focus(); 33 | } 34 | 35 | onFocus = e => { 36 | this.refs.wrapper.blur(); 37 | } 38 | 39 | handleKeyDown = e => { 40 | if (e.keyCode === 13 && this.lastEvent === e) { 41 | this.lastEvent = null; 42 | return; 43 | } 44 | if (!this.props.fromSuggestionsOnly && (this.props.createChipKeys.includes(e.keyCode) || this.props.createChipKeys.includes(e.key))) { 45 | e.preventDefault(); 46 | if (this.state.value.trim()) this.addChip(this.state.value); 47 | } 48 | if (e.keyCode === 8) { 49 | this.onBackspace(); 50 | } else if (this.state.chipSelected) { 51 | this.setState({chipSelected: false}); 52 | } 53 | } 54 | 55 | onBackspace = (code) => { 56 | if (this.state.value === "" && this.props.value.length > 0) { 57 | if (this.state.chipSelected) { 58 | const nextChips = this.props.value.slice(0, -1); 59 | this.setState({ 60 | chipSelected: false, 61 | chips: nextChips, 62 | }); 63 | this.props.onChange(nextChips); 64 | } else { 65 | this.setState({chipSelected: true}) 66 | } 67 | } 68 | } 69 | 70 | addChip = (value) => { 71 | if (this.props.uniqueChips && this.props.value.indexOf(value) !== -1) { 72 | this.setState({value: ""}); 73 | return; 74 | } 75 | let chips = [...this.props.value, value] 76 | this.props.onChange(chips); 77 | this.setState({ value: "" }) 78 | } 79 | 80 | removeChip = idx => () => { 81 | let left = this.props.value.slice(0, idx); 82 | let right = this.props.value.slice(idx + 1); 83 | const nextChips = [...left, ...right]; 84 | this.props.onChange(nextChips); 85 | } 86 | 87 | renderChips = () => { 88 | return this.props.value.map((chip, idx) => { 89 | return ( 90 | React.cloneElement(this.props.renderChip(chip, this.props.chipTheme), { 91 | selected: this.state.chipSelected && idx === this.props.value.length - 1, 92 | onRemove: this.removeChip(idx), 93 | index: idx, 94 | key: `chip${idx}`, 95 | }) 96 | ); 97 | }); 98 | } 99 | 100 | filterUniqueChips = suggestions => { 101 | let { value, getChipValue, getSuggestionValue } = this.props; 102 | 103 | return suggestions 104 | .filter(suggestion => !value.some(chip => getChipValue(chip) == getSuggestionValue(suggestion))); 105 | } 106 | 107 | callFetchSuggestions = (fetchSuggestions, value, canceled) => { 108 | let { uniqueChips } = this.props; 109 | 110 | let callback = suggestions => { 111 | if(!canceled.isCancaled()){ 112 | this.setState({ 113 | loading: false, 114 | suggestions: (uniqueChips ? this.filterUniqueChips(suggestions) : suggestions) 115 | }); 116 | } 117 | } 118 | 119 | let suggestionResult = 120 | fetchSuggestions.call(this, value, callback); 121 | 122 | if(suggestionResult && 'then' in suggestionResult){ // To Support Promises 123 | suggestionResult.then(callback); 124 | } 125 | } 126 | 127 | onSuggestionsFetchRequested = ({ value }) => { 128 | let { uniqueChips, suggestions, fetchSuggestions, suggestionsFilter } = this.props; 129 | 130 | if( fetchSuggestions ){ 131 | this.setState({loading: true}); 132 | 133 | this.asyncSuggestLimiter.invoke(fetchSuggestions, value); 134 | } else { 135 | this.setState({ 136 | suggestions: (uniqueChips ? this.filterUniqueChips(suggestions) : suggestions).filter(opts => suggestionsFilter(opts, value)) 137 | }); 138 | } 139 | } 140 | 141 | onSuggestionsClearRequested = () => { 142 | this.setState({suggestions: []}) 143 | } 144 | 145 | onSuggestionSelected = (e, { suggestion }) => { 146 | this.lastEvent = e; 147 | this.addChip(suggestion); 148 | this.setState({ value: '' }); 149 | } 150 | 151 | onChange = (e, { newValue }) => { 152 | if (!this.props.fromSuggestionsOnly && newValue.indexOf(',') !== -1 && this.props.createChipKeys.includes(9)) { 153 | let chips = newValue.split(",").map((val) => val.trim()).filter((val) => val !== ""); 154 | chips.forEach(chip => { 155 | this.addChip(chip) 156 | }); 157 | } else { 158 | this.setState({value: newValue}); 159 | } 160 | } 161 | 162 | render() { 163 | 164 | const { loading, value, suggestions } = this.state; 165 | const { placeholder, renderLoading } = this.props; 166 | const themr = themeable(this.props.theme); 167 | 168 | const inputProps = { 169 | placeholder, 170 | value, 171 | onChange: this.onChange, 172 | onKeyDown: this.handleKeyDown, 173 | onBlur: this.onBlur, 174 | onFocus: this.onFocus 175 | }; 176 | 177 | return ( 178 |
179 | {this.renderChips()} 180 | this.state.value} 187 | inputProps={inputProps} 188 | onSuggestionSelected={this.onSuggestionSelected} 189 | /> 190 | { loading ? renderLoading() : null } 191 |
192 | ); 193 | } 194 | } 195 | 196 | Chips.propTypes = { 197 | value: PropTypes.array.isRequired, 198 | onChange: PropTypes.func, 199 | placeholder: PropTypes.string, 200 | theme: PropTypes.object, 201 | chipTheme: PropTypes.object, 202 | suggestions: PropTypes.array, 203 | fetchSuggestions: PropTypes.func, 204 | fetchSuggestionsThrushold: PropTypes.number, 205 | fromSuggestionsOnly: PropTypes.bool, 206 | uniqueChips: PropTypes.bool, 207 | renderChip: PropTypes.func, 208 | suggestionsFilter: PropTypes.func, 209 | getChipValue: PropTypes.func, 210 | createChipKeys: PropTypes.array, 211 | getSuggestionValue: PropTypes.func, 212 | renderSuggestion: PropTypes.func, 213 | shouldRenderSuggestions: PropTypes.func, 214 | alwaysRenderSuggestions: PropTypes.bool, 215 | highlightFirstSuggestion: PropTypes.bool, 216 | focusInputOnSuggestionClick: PropTypes.bool, 217 | multiSection: PropTypes.bool, 218 | renderSectionTitle: PropTypes.func, 219 | getSectionSuggestions: PropTypes.func, 220 | }; 221 | 222 | Chips.defaultProps = { 223 | placeholder: '', 224 | theme: theme, 225 | chipTheme: chipTheme, 226 | suggestions: [], 227 | fetchSuggestions: null, 228 | fetchSuggestionsThrushold: 10, 229 | createChipKeys: [9], 230 | fromSuggestionsOnly: false, 231 | uniqueChips: true, 232 | getSuggestionValue: s => s, 233 | value: [], 234 | onChange: () => {}, 235 | renderChip: (value, customTheme) => ({value}), 236 | renderLoading: () => (Loading...), 237 | renderSuggestion: (suggestion, { query }) => {suggestion}, 238 | suggestionsFilter: (opt, val) => opt.toLowerCase().indexOf(val.toLowerCase()) !== -1, 239 | getChipValue: (item) => item, 240 | }; 241 | 242 | export default Radium(Chips); 243 | --------------------------------------------------------------------------------