diff --git a/src/decorator.js b/src/decorator.js index e6e1887..eb50edb 100644 --- a/src/decorator.js +++ b/src/decorator.js @@ -1,14 +1,16 @@ // @flow import type { Decorator, FormApi } from 'final-form' -import type { GetInputs, FindInput } from './types' +import type { GetInputs, FindInput, FocusInput } from './types' import getAllInputs from './getAllInputs' import defaultFindInput from './findInput' +import defaultFocus from './focusInput' const noop = () => {} const createDecorator = ( getInputs?: GetInputs, - findInput?: FindInput + findInput?: FindInput, + focus?: FocusInput ): Decorator => (form: FormApi) => { const focusOnFirstError = (errors: Object) => { if (!getInputs) { @@ -17,9 +19,12 @@ const createDecorator = ( if (!findInput) { findInput = defaultFindInput } + if (!focus) { + focus = defaultFocus + } const firstInput = findInput(getInputs(), errors) if (firstInput) { - firstInput.focus() + focus(firstInput) } } // Save original submit function diff --git a/src/focusInput.js b/src/focusInput.js new file mode 100644 index 0000000..85769de --- /dev/null +++ b/src/focusInput.js @@ -0,0 +1,10 @@ +// @flow +import type { FocusableInput, FocusInput } from './types' + +/** + * Focuses an input + */ +const focusInput: FocusInput = (input: FocusableInput) => + input.focus() + +export default focusInput diff --git a/src/types.js.flow b/src/types.js.flow index 2548162..a0d2d7b 100644 --- a/src/types.js.flow +++ b/src/types.js.flow @@ -3,4 +3,6 @@ export type FocusableInput = { name: string, focus: () => void } export type GetInputs = () => FocusableInput[] +export type FocusInput = (FocusableInput) => void + export type FindInput = (FocusableInput[], {}) => ?FocusableInput