Skip to content

[typescript] add tests and implementation for FieldArrayProps #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jan 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ lib
es
npm-debug.log
.DS_Store
.idea
yarn.lock
2,250 changes: 749 additions & 1,501 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion package-scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,14 @@ module.exports = {
description: 'flow check the entire project',
script: 'flow check'
},
typescript: {
description: 'typescript check the entire project',
script: 'tsc'
},
validate: {
description:
'This runs several scripts to make sure things look good before committing or on clean install',
default: concurrent.nps('lint', 'flow', 'build.andTest', 'test')
default: concurrent.nps('lint', 'flow', 'typescript', 'build.andTest', 'test')
}
},
options: {
Expand Down
31 changes: 18 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
{
"name": "react-final-form-arrays",
"version": "1.0.2",
"description":
"A component for rendering and editing arrays 🏁 React Final Form",
"description": "A component for rendering and editing arrays 🏁 React Final Form",
"main": "dist/react-final-form-arrays.cjs.js",
"jsnext:main": "dist/react-final-form-arrays.es.js",
"module": "dist/react-final-form-arrays.es.js",
"typings": "dist/index.d.js",
"files": ["dist"],
"typings": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"start": "nps",
"test": "nps test",
"precommit": "lint-staged && npm start validate"
},
"author":
"Erik Rasmussen <[email protected]> (http://github.com/erikras)",
"author": "Erik Rasmussen <[email protected]> (http://github.com/erikras)",
"license": "MIT",
"repository": {
"type": "git",
Expand Down Expand Up @@ -42,9 +42,8 @@
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.4.0",
"final-form": "^2.0.0",
"final-form-arrays": "^1.0.3",
"flow": "^0.2.3",
"final-form": "^4.0.4",
"final-form-arrays": "^1.0.4",
"flow-bin": "^0.61.0",
"husky": "^0.14.3",
"jest": "^21.2.1",
Expand All @@ -57,14 +56,15 @@
"raf": "^3.4.0",
"react": "^16.1.0",
"react-dom": "^16.1.0",
"react-final-form": "^1.1.0",
"react-final-form": "^3.0.5",
"rollup": "^0.52.0",
"rollup-plugin-babel": "^3.0.2",
"rollup-plugin-commonjs": "^8.2.6",
"rollup-plugin-flow": "^1.1.1",
"rollup-plugin-node-resolve": "^3.0.0",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-uglify": "^2.0.1"
"rollup-plugin-uglify": "^2.0.1",
"typescript": "^2.6.2"
},
"peerDependencies": {
"final-form": ">=2.0.0",
Expand All @@ -73,10 +73,15 @@
"react": "^15.3.0 || ^16.0.0-0"
},
"jest": {
"setupFiles": ["raf/polyfill"]
"setupFiles": [
"raf/polyfill"
]
},
"lint-staged": {
"*.{js*,ts,json,md,css}": ["prettier --write", "git add"]
"*.{js*,ts*,json,md,css}": [
"prettier --write",
"git add"
]
},
"bundlesize": [
{
Expand Down
82 changes: 82 additions & 0 deletions src/FieldArray.d.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import * as React from 'react'
import { Form, Field } from 'react-final-form'
import arrayMutators from 'final-form-arrays'
import { FieldArray } from './index'

const onSubmit = async (values: any) => {
console.log(values)
}

const basic = () => (
<Form
onSubmit={onSubmit}
mutators={{
...arrayMutators
}}
>
{({
handleSubmit,
mutators: { push, pop }, // injected from final-form-arrays above
pristine,
reset,
submitting,
values
}) => {
return (
<form onSubmit={handleSubmit}>
<div>
<label>Company</label>
<Field name="company" component="input" />
</div>
<div className="buttons">
<button type="button" onClick={() => push('customers', undefined)}>
Add Customer
</button>
<button type="button" onClick={() => pop('customers')}>
Remove Customer
</button>
</div>
<FieldArray name="customers">
{({ fields }) =>
fields.map((name, index) => (
<div key={name}>
<label>Cust. #{index + 1}</label>
<Field
name={`${name}.firstName`}
component="input"
placeholder="First Name"
/>
<Field
name={`${name}.lastName`}
component="input"
placeholder="Last Name"
/>
<span
onClick={() => fields.remove(index)}
style={{ cursor: 'pointer' }}
>
</span>
</div>
))
}
</FieldArray>

<div className="buttons">
<button type="submit" disabled={submitting || pristine}>
Submit
</button>
<button
type="button"
onClick={reset}
disabled={submitting || pristine}
>
Reset
</button>
</div>
<pre>{JSON.stringify(values)}</pre>
</form>
)
}}
</Form>
)
46 changes: 39 additions & 7 deletions src/FieldArray.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ export default class FieldArray extends React.PureComponent<Props, State> {
name,
listener,
subscription ? { ...subscription, length: true } : all,
{ validate: this.validate }
{
getValidator: () => this.props.validate
}
)
}

Expand All @@ -80,9 +82,6 @@ export default class FieldArray extends React.PureComponent<Props, State> {
}
}

validate = (value: ?any, allValues: Object) =>
this.props.validate && this.props.validate(value, allValues)

notify = (state: FieldState) => {
setTimeout(() => this.setState({ state }))
}
Expand Down Expand Up @@ -132,18 +131,51 @@ export default class FieldArray extends React.PureComponent<Props, State> {

render() {
const { name, ...rest } = this.props
let { value, length, ...meta } = this.state.state
let {
length,
active,
dirty,
error,
initial,
invalid,
pristine,
submitError,
submitFailed,
submitSucceeded,
touched,
valid,
visited,
...fieldStateFunctions
} = this.state.state
const meta = {
active,
dirty,
error,
initial,
invalid,
pristine,
submitError,
submitFailed,
submitSucceeded,
touched,
valid,
visited
}
const fieldState = {
...meta,
...fieldStateFunctions
}
return renderComponent(
{
fields: {
name,
forEach: this.forEach,
length,
map: this.map,
...this.mutators
...this.mutators,
...fieldState
},
meta,
value,
...rest
},
`FieldArray(${name})`
Expand Down
4 changes: 2 additions & 2 deletions src/FieldArray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,14 @@ describe('FieldArray', () => {
const dom = TestUtils.renderIntoDocument(<Container />)
expect(renderArray).toHaveBeenCalled()
expect(renderArray).toHaveBeenCalledTimes(1)
expect(renderArray.mock.calls[0][0].value).toEqual(['Odie'])
expect(renderArray.mock.calls[0][0].fields.value).toEqual(['Odie'])

const button = TestUtils.findRenderedDOMComponentWithTag(dom, 'button')
TestUtils.Simulate.click(button)
await sleep(2)

expect(renderArray).toHaveBeenCalledTimes(4)
expect(renderArray.mock.calls[3][0].value).toEqual(['Garfield'])
expect(renderArray.mock.calls[3][0].fields.value).toEqual(['Garfield'])
})

it('should not resubscribe if name changes when not inside a <Form> (duh)', () => {
Expand Down
50 changes: 47 additions & 3 deletions src/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,49 @@
import * as React from 'react'
import { FieldArrayProps } from 'final-form'
import { FieldSubscription, FieldState } from 'final-form'
export const version: string

export var FieldArray: React.ComponentType<FieldArrayProps>
export var version: string
export const FieldArray: React.ComponentType<FieldArrayProps>

export interface FieldArrayRenderProps {
fields: {
forEach: (iterator: (name: string, index: number) => void) => void
insert: (index: number, value: any) => void
map: (iterator: (name: string, index: number) => any) => any[]
move: (from: number, to: number) => void
name: string
pop: () => any
push: (value: any) => void
remove: (index: number) => any
shift: () => any
swap: (indexA: number, indexB: number) => void
unshift: (value: any) => void
} & FieldState
meta: Partial<{
// TODO: Make a diff of `FieldState` without all the functions
active: boolean
dirty: boolean
error: boolean
initial: boolean
invalid: boolean
pristine: boolean
submitError: boolean
submitFailed: boolean
submitSucceeded: boolean
touched: boolean
valid: boolean
visited: boolean
}>
}

export interface RenderableProps<T> {
children?: ((props: T) => React.ReactNode) | React.ReactNode
component?: React.ComponentType<T> | string
render?: (props: T) => React.ReactNode
}

export interface FieldArrayProps
extends RenderableProps<FieldArrayRenderProps> {
name: string
subscription?: FieldSubscription
validate?: (value: any, allValues: object) => any
}
15 changes: 15 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"lib": [
"es2015",
"dom"
],
"jsx": "react",
"baseUrl": ".",
"noEmit": true,
"strict": true
},
"include": [
"./src/**/*"
]
}