qiniu / formstate-x

Manage state of form with ease.
https://qiniu.github.io/formstate-x
MIT License
33 stars 10 forks source link

`ProxyState` #56

Closed nighca closed 2 years ago

nighca commented 2 years ago

Overview

  1. Value transform inside of state, fix #49
  2. interface Validatable -> IState with some fields adjustment
  3. Extract common logic among different states, as class StateUtils & class State
  4. Remove src/adapter
  5. Extract src/testUtils
  6. Fix FieldState issue with value: NaN

Value transform inside of state

Check proposal detail here. Examples:

ProxyState for FieldState:

interface Host {
  hostname: string
  port: number
}

type HostInput = string

function parseHost(input: HostInput): Host {
  const [hostname, portStr] = input.split(':')
  const port = parseInt(portStr, 10)
  return { hostname, port }
}

function stringifyHost(host: Host) {
  return [host.hostname, host.port].join(':')
}

function createHostState() {
  const rawState = new FieldState('')
  return new ProxyState(rawState, parseHost, stringifyHost)
}

const hostState = createHostState()
assertType<Host>(hostState.value)
assertType<HostInput>(hostState.$.value)

ProxyState for FormState:

interface HostInput {
  hostname: string
  port: number
}

type Host = string

function parseHost(host: string): HostInput {
  const [hostname, portStr] = host.split(':')
  const port = parseInt(portStr, 10)
  return { hostname, port }
}

function stringifyHost(input: HostInput) {
  const suffix = Number.isNaN(input.port) ? '' : `:${input.port}`
  return input.hostname + suffix
}

function createHostState(host: string = '127.0.0.1:80') {
  const hostInput = parseHost(host)
  const rawState = new FormState({
    hostname: new FieldState(hostInput.hostname),
    port: new FieldState(hostInput.port)
  })
  return new ProxyState(rawState, stringifyHost, parseHost)
}

const hostState = createHostState()
assertType<Host>(hostState.value)
assertType<HostInput>(hostState.$.value)
assertType<string>(hostState.$.$.hostnamae.value)
nighca commented 2 years ago

https://github.com/qiniu/formstate-x/pull/54#issuecomment-972761697 这里先 merge