gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

Color pickers for tcomb-form #273

Open gcanti opened 8 years ago

gcanti commented 8 years ago

Hi,

this is a factory I just wrote (for a project of mine) using @casesandberg's react-color. Hope it can be helpful to others.

// there are many styles (check out react-color's README)
// I like the chrome one
import ReactColor from 'react-color/lib/components/ChromePicker'

// statefull picker
class ColorPicker extends React.Component {

  state = {
    isOpen: false
  }

  toggle = () => {
    this.setState({ isOpen: !this.state.isOpen })
  }

  onChange = (color) => {
    this.setState({ isOpen: false })
    this.props.onChange('#' + color.hex)
  }

  render() {
    const color = this.props.value || undefined // react-color doesn't like null
    return (
      <div className="input-group-addon">
        {/* trigger: opens / closes the color picker */}
        <span className="glyphicon glyphicon-tint" onClick={this.toggle} style={{cursor: 'pointer'}}></span>
        <ReactColor
          display={this.state.isOpen}
          onClose={this.close}
          color={color}
          onChangeComplete={this.onChange} />
      </div>
    )
  }

}

function renderTextbox(locals) {
  const onChange = (evt) => locals.onChange(evt.target.value)
  return (
    <div>
      <div className="input-group">
        <input className="form-control" type="text" value={locals.value} onChange={onChange} />
        <ColorPicker value={locals.value} onChange={locals.onChange} />
      </div>
    </div>
  )
}

// override just the renderTextbox partial of the default template
const colorTemplate = t.form.Form.templates.textbox.clone({ renderTextbox })

// here we are: the factory
class ColorPickerFactory extends t.form.Textbox {

  getTemplate() {
    return colorTemplate
  }

}

// example
const Type = t.struct({
  color: t.String
})

const options = {
  fields: {
    color: {
      factory: ColorPickerFactory
    }
  }
}