Giter VIP home page Giter VIP logo

Comments (5)

tgoorden avatar tgoorden commented on April 28, 2024

OK, since this was making me itch, I've figured out a way that is potentially more elegant.

Essentially, setModel, setProperty and the binding are all hooked into the state somehow. This implies that intercepting one would basically force you to intercept all. Otherwise, there is no way of keeping the (model) state predictable, without terribly complex code.

So, the solution seems to abstract out the model state handling instead. In fact, in all likelihood this is what any middleware is interested in anyway. The rest is solvable on a (form) component level.

I've reworded reformed.js to reflect this approach. The middleware can (in this system) intercept setModel, getModel and/or setModelValue and getModelValue. For instance a validator would be able to work with setModelValue to mark dirty fields, etc.

Incidentally, it seems to me that it would make sense to do all this in the constructor instead of the render function, no?

import React from 'react'
import PropTypes from 'prop-types'
import assign from 'object-assign'
import hoistNonReactStatics from 'hoist-non-react-statics'

const makeWrapper = (middleware) => (WrappedComponent) => {
  class FormWrapper extends React.Component {
    static propTypes = {
      initialModel: PropTypes.object,
    }

    constructor (props, ctx) {
      super(props, ctx)
      this.state = {
        model: props.initialModel || {},
      }
      class ModelHandlerWrapper {
        constructor({getState,setState}) {
          this.getState = getState
          this.setState = setState
        }
        setModel = (model) => { 
          this.setState({model})
          return model
        }
        getModel = ()=> getState("model")
        getModelValue = (name)=> this.getModel()[name]
        setModelValue = (name,value)=> {
          return this.setModel(assign({}, this.getModel(), {
            [name]: value,
          }))
        }
      }
      const getState = (name) => this.state[name]
      this.modelHandler = new ModelHandlerWrapper({getState: getState, setState: this.setState.bind(this)})
      if (typeof middleware === 'function') {
        this.modelHandler = middleware(this.modelHandler)
      }
    }

    setModel = (model) => {
      return this.modelHandler.setModel(model)
    }

    setProperty = (prop, value) => {
      return this.modelHandler.setModelValue(prop,value)
    }

    // This, of course, does not handle all possible inputs. In such cases,
    // you should just use `setProperty` or `setModel`. Or, better yet,
    // extend `reformed` to supply the bindings that match your needs.
    bindToChangeEvent = (e) => {
      const { name, type, value } = e.target

      if (type === 'checkbox') {
        const oldCheckboxValue = this.modelHandler.getModelValue(name) || []
        const newCheckboxValue = e.target.checked
          ? oldCheckboxValue.concat(value)
          : oldCheckboxValue.filter(v => v !== value)

        this.setProperty(name, newCheckboxValue)
      } else {
        this.setProperty(name, value)
      }
    }

    bindInput = (name) => {
      return {
        name,
        value: this.modelHandler.getModelValue(name) || '',
        onChange: this.bindToChangeEvent,
      }
    }

    render () {
      let nextProps = assign({}, this.props, {
        model: this.modelHandler.getModel(),
        setProperty: this.setProperty,
        setModel: this.setModel,
        bindInput: this.bindInput,
        bindToChangeEvent: this.bindToChangeEvent
      })

      return React.createElement(WrappedComponent, nextProps)
    }
  }

  FormWrapper.displayName = `Reformed(${getComponentName(WrappedComponent)})`
  return hoistNonReactStatics(FormWrapper, WrappedComponent)
}

const getComponentName = (component) => (
  component.displayName ||
  component.name
)

export default makeWrapper

from react-reformed.

dvdzkwsk avatar dvdzkwsk commented on April 28, 2024

Yeah, I'd realized the patch wouldn't affect setModel, but didn't think it should be necessary because it's an implementation detail of setProperty; that is, the consumer shouldn't rely on setProperty dispatching to setModel.

I will read through your proposals when I get some time today, but wanted to get a quick response out. Thank you for the detailed post. If it's a clean enough solution we can consider it :).

from react-reformed.

dvdzkwsk avatar dvdzkwsk commented on April 28, 2024

I took a look at your proposal, and it seems pretty solid for your use case. I do have some reservations, though, mainly that the middleware function would only run once, at component instantiation time, which would break the expected function signature of Props -> Props and restrict its overall utility.

At this point I'm wondering if this is something that middleware shouldn't even be responsible for, since the only reliable way to update function references after applying middleware is to have them rely on this, but that presents its own set of problems. For what it's worth, middleware at the top-level wasn't something I'd ever really intended to be a core part of the API, but was added mainly as an easy escape hatch.

I would really like to solve for this though, so I'm continuing to play around with a few ideas on my end. If this is blocking you, though, please feel free to fork this project in the meantime :).

from react-reformed.

tgoorden avatar tgoorden commented on April 28, 2024

Yes, I agree that it's an interesting (architectural) challenge. To be honest I'm not familiar enough with the React lifecycle and it's architectural consequences to make a good estimate here. However, it seems to me that it wouldn't be too hard to use this approach inside of the "render" cycle. I guess you would end up with some kind of generator functionality like you wrote before for the bindInput function, but this time with a "model handler" as its argument instead of setProperty.

The current code is quite tied into this to be able to do this without a significant rewrite so I ended up taking the easy way out, which meant doing it at constructor time.

from react-reformed.

tgoorden avatar tgoorden commented on April 28, 2024

OK, this seems to work fine and it allows the middleware to jump in during the render cycle:

You might note that I'm using set and get from lodash to allow "dotted" property names to be used, with a correct translation into an object structure. This adds a lot of extra functionality IMO.

import React from 'react'
import PropTypes from 'prop-types'
import assign from 'object-assign'
import hoistNonReactStatics from 'hoist-non-react-statics'
import { set, get } from 'lodash'

class ModelHandlerWrapper {
  constructor({getState,setState}) {
    this.getState = getState
    this.setState = setState
  }
  setModel = (model) => { 
    this.setState({model})
    return model
  }
  getModel = ()=> this.getState("model")
  getModelValue = (name)=> get(this.getModel(),name)
  setModelValue = (name,value)=> {
    return this.setModel(set(this.getModel(),name,value))
  }
}

const makeWrapper = (middleware) => (WrappedComponent) => {
  class FormWrapper extends React.Component {
    static propTypes = {
      initialModel: PropTypes.object,
    }

    constructor (props, ctx) {
      super(props, ctx)
      this.state = {
        model: props.initialModel || {},
      }
    }

    makeHelpers = (modelHandler) => {
      bindToChangeEvent = (e) => {
        const { name, type, value } = e.target
        if (type === 'checkbox') {
          const oldCheckboxValue = modelHandler.getModelValue(name) || []
          const newCheckboxValue = e.target.checked
            ? oldCheckboxValue.concat(value)
            : oldCheckboxValue.filter(v => v !== value)

          modelHandler.setModelValue(name, newCheckboxValue)
        } else {
          modelHandler.setModelValue(name, value)
        }
      }
      helpers = {
        setModel: (model) => modelHandler.setModel(model)
        ,
        setProperty: (prop, value) => modelHandler.setModelValue(prop,value)
        ,
        bindToChangeEvent: (e) => {
          const { name, type, value } = e.target

          if (type === 'checkbox') {
            const oldCheckboxValue = modelHandler.getModelValue(name) || []
            const newCheckboxValue = e.target.checked
              ? oldCheckboxValue.concat(value)
              : oldCheckboxValue.filter(v => v !== value)

            modelHandler.setModelValue(name, newCheckboxValue)
          } else {
            modelHandler.setModelValue(name, value)
          }
        }
        ,
        bindInput: (name) => {
          return {
            name,
            value: modelHandler.getModelValue(name) || '',
            onChange: bindToChangeEvent,
          }
        }
      }
      return helpers
    }

    render () {
      const getState = (name) => this.state[name]
      let modelHandler = new ModelHandlerWrapper({getState: getState, setState: this.setState.bind(this)})
      if (typeof middleware === 'function') {
        modelHandler = middleware(modelHandler)
      }
      let nextProps = assign({}, this.props, {
        model: modelHandler.getModel()
      },
        this.makeHelpers(modelHandler)
      )
      return React.createElement(WrappedComponent, nextProps)
    }
  }

  FormWrapper.displayName = `Reformed(${getComponentName(WrappedComponent)})`
  return hoistNonReactStatics(FormWrapper, WrappedComponent)
}

const getComponentName = (component) => (
  component.displayName ||
  component.name
)

export default makeWrapper

from react-reformed.

Related Issues (12)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.