Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/forms / src / new-forms / plugins / FieldSetPlugin.tsx
Size: Mime:
import * as React from 'react'
import { action } from 'xmobx/mobx'
import { observer } from 'xmobx/mobx-react'
import { Value, SerializerFunction } from '../typings'
import { serializeListIntoMergedObj } from '../deps'
import { FieldSet, FieldSetProps, FieldSetInputState } from '../FieldSet'
import { InputState, InputProps, InputConfig } from '../inputs'
import { DefaultStateReturn } from './PluginsContext'

const fieldSetSerializer = (inputState: FieldSetInputState) => {
  return serializeListIntoMergedObj(inputState.attributes.elementList!)
}

export type FieldSetRenderPropProps = InputProps &
  FieldSetProps & {
    ref?: any
    inputsList: InputState[]
  }
export type FieldSetPluginProps = FieldSetRenderPropProps & {
  renderFieldSet?: (
    props?: FieldSetRenderPropProps
  ) => React.ReactElement<HTMLFieldSetElement | React.ReactFragment>
}
export type FieldSetDefaultStateReturn = DefaultStateReturn & {
  serializer: SerializerFunction<any>
}

@observer
class FieldSetPlugin extends React.Component<FieldSetPluginProps> {
  static isSatisfiedByProps(props: { type: string }): boolean {
    return ['fieldset', 'groupElements'].includes(props.type)
  }

  static defaultState = action(
    (inputState: InputState): FieldSetDefaultStateReturn => {
      // @todo need to improve
      const inputConfigList: InputConfig[] = inputState.attributes.elementList
      const fieldSetInputsList = inputConfigList.map(InputState.from)
      inputState.attributes.elementList = fieldSetInputsList

      return {
        serializer: fieldSetSerializer,
        validator: (value: Value) => {
          return fieldSetInputsList.every(
            subInputState => subInputState.isValid
          )
        },
      }
    }
  )

  static defaultProps = {
    // just pass through right now, could do children & className...
    renderFieldSet: (props: FieldSetRenderPropProps) => <FieldSet {...props} />,
  }

  render() {
    const { ref, renderFieldSet, state, ...remainingProps } = this.props
    const elementList = state.attributes.elementList!
    const props = { ...remainingProps, state, elementList }
    return renderFieldSet!(props)
  }
}

export { FieldSetPlugin }
export default FieldSetPlugin