Created
June 27, 2016 07:21
-
-
Save LeiZeng/659897730a81d7a7050c9847947c13c3 to your computer and use it in GitHub Desktop.
TagPicker.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import _ from 'lodash'; | |
import { | |
withReducer, | |
withState, | |
} from 'recompose'; | |
class Tag { | |
constructor(tag) { | |
this.id = tag.id || new Date().getSeconds(); | |
this.name = tag.name; | |
} | |
} | |
const mergeTag = (tags, newTag) => { | |
const nextTag = new Tag(newTag); | |
return ({ | |
...tags, | |
[tags.id]: nextTag, | |
}); | |
}; | |
const tagReducer = (tags, action) => { | |
switch (action.type) { | |
case 'DELETE': | |
return _.omit(tags, action.payload.id); | |
case 'ADD': | |
case 'EDIT': | |
return mergeTag(tags, action.payload); | |
default: | |
return tags; | |
} | |
}; | |
const InputForm = withState('value', 'updateValue', ({ value }) => value)(({ | |
value, updateValue, | |
onSubmit, | |
onCancel, | |
}) => ( | |
<form | |
onSubmit={(evt) => { | |
evt.preventDefault(); | |
return onSubmit(value); | |
}} | |
> | |
<input | |
type='text' | |
value={value} | |
onChange={evt => updateValue(evt.target.value)} | |
/> | |
<input | |
type='submit' | |
value='SUBMIT' | |
/> | |
<input | |
type='button' | |
value='CANCEL' | |
onClick={onCancel} | |
/> | |
</form> | |
)); | |
const InlineEdit = withState('editing', 'updateEditing', false)(({ | |
editing, updateEditing, | |
value, | |
onSubmit, | |
}) => ( | |
<span > | |
{editing ? <InputForm | |
value={value} | |
onSubmit={onSubmit} | |
onCancel={() => updateEditing(false)} | |
/> : <span onClick={() => updateEditing(true)}> | |
{value} | |
</span>} | |
</span> | |
)); | |
const TagPicker = withReducer('tags', 'dispatch', tagReducer, {})(({ | |
tags, dispatch, | |
}) => ( | |
<section> | |
<div> | |
{_.isEmpty(tags) | |
? 'No Tag yet.' | |
: _.map(tags, tag => (<span> | |
<InlineEdit | |
value={tag.name} | |
onSubmit={(value) => dispatch({ | |
type: 'EDIT', | |
payload: { | |
name: value, | |
}, | |
})} | |
/> | |
<input | |
type='button' | |
value='DELETE' | |
onClick={evt => dispatch({ | |
type: 'DELETE', | |
payload: { | |
id: tag.id | |
}, | |
})} | |
/> | |
)) | |
</span>) | |
)} | |
</div> | |
<InputForm | |
onSubmit={(value) => dispatch({ | |
type: 'ADD', | |
payload: { | |
name: value, | |
}, | |
})} | |
/> | |
</section> | |
)); | |
export default TagPicker; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment