import PropTypes from 'prop-types'
import React from 'react'
import { injectState, provideState } from 'reaclette'

import decorate from '../apply-decorators'

// it provide `data-*` to add params to the `onChange`
const Number_ = decorate([
  provideState({
    effects: {
      onChange: (_, { target: { value } }) => (state, props) => {
        value = value.trim()
        if (value === '') {
          value = undefined
        } else {
          value = +value
          if (Number.isNaN(value)) {
            return
          }
        }

        const params = {}
        let empty = true
        Object.keys(props).forEach(key => {
          if (key.startsWith('data-')) {
            empty = false
            params[key.slice(5)] = props[key]
          }
        })

        props.onChange(value, empty ? undefined : params)
      },
    },
  }),
  injectState,
  ({ state, effects, value, className = 'form-control', ...props }) => (
    <input
      {...props}
      className={className}
      onChange={effects.onChange}
      type='number'
      value={value === undefined ? '' : String(value)}
    />
  ),
])

Number_.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.number.isRequired,
}

export default Number_

@@ -252,16 +252,77 @@
 State(%7B%0A
+    initialState: () =%3E (%7B%0A      displayedValue: '',%0A    %7D),%0A
     effe
@@ -342,18 +342,16 @@
 onChange
-: 
 (_, %7B ta
@@ -373,38 +373,78 @@
  %7D) 
-=%3E (state, props) =%3E %7B%0A       
+%7B%0A        const %7B state, props %7D = this%0A        state.displayedValue =
  val
@@ -461,16 +461,17 @@
 .trim()%0A
+%0A
         
@@ -945,16 +945,367 @@
 %0A    %7D,%0A
+    computed: %7B%0A      value: (%7B displayedValue %7D, %7B value %7D) =%3E %7B%0A        const numericValue = +displayedValue%0A        if (%0A          displayedValue === '' %7C%7C%0A          (!Number.isNaN(numericValue) && numericValue !== value)%0A        ) %7B%0A          return value === undefined ? '' : String(value)%0A        %7D%0A        return displayedValue%0A      %7D,%0A    %7D,%0A
   %7D),%0A  
@@ -1517,48 +1517,19 @@
 ue=%7B
-value === undefined ? '' : String(
+state.
 value
-)
 %7D%0A  
@@ -1603,16 +1603,16 @@
 quired,%0A
+
   value:
@@ -1628,27 +1628,16 @@
 s.number
-.isRequired
 ,%0A%7D%0A%0Aexp

fix inability to set advanced expressions (#4690)