Skip to content
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

Custom focus implementation #25

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 8 additions & 3 deletions src/decorator.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/focusInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// @flow
import type { FocusableInput, FocusInput } from './types'

/**
* Focuses an input
*/
const focusInput: FocusInput = (input: FocusableInput) =>
input.focus()

export default focusInput
2 changes: 2 additions & 0 deletions src/types.js.flow
Original file line number Diff line number Diff line change
Expand Up @@ -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