Skip to content

Commit

Permalink
feat: #70 select first option on blur (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
vitalybaev authored Sep 13, 2021
1 parent 29e3269 commit 93239ad
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const [value, setValue] = useState();
| hintClassName | Нет | string | CSS класс блока текста-пояснения над подсказками, если не передан, используется класс для стилей из коробки. |
| highlightClassName | Нет | string | CSS класс элемента, подсвечивающего совпадения при наборе, если не передан, используется класс для стилей из коробки. |
| customInput | Нет | Element or string | Кастомный компонент поля ввода, например от Styled Components |
| selectOnBlur | Нет | boolean | Если `true`, то при потере фокуса будет выбрана первая подсказка из списка

## Методы

Expand Down
16 changes: 12 additions & 4 deletions src/BaseSuggestions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,19 @@ export abstract class BaseSuggestions<SuggestionType, OwnProps> extends React.Pu

private handleInputBlur = (event: FocusEvent<HTMLInputElement>) => {
const { suggestions } = this.state;
const { selectOnBlur, inputProps } = this.props;

this.setState({ isFocused: false });
if (suggestions.length === 0) {
this.fetchSuggestions();
}

const { inputProps } = this.props;
if (selectOnBlur) {
if (suggestions.length > 0) {
this.selectSuggestion(0, true);
}
}

if (inputProps && inputProps.onBlur) {
inputProps.onBlur(event);
}
Expand Down Expand Up @@ -223,15 +229,17 @@ export abstract class BaseSuggestions<SuggestionType, OwnProps> extends React.Pu
this.selectSuggestion(index);
};

private selectSuggestion = (index: number) => {
private selectSuggestion = (index: number, isSilent = false) => {
const { suggestions } = this.state;
const { onChange } = this.props;

if (suggestions.length >= index - 1) {
const suggestion = suggestions[index];
this.setState({ query: suggestion.value, inputQuery: suggestion.value, displaySuggestions: false }, () => {
this.fetchSuggestions();
setTimeout(() => this.setCursorToEnd(this.textInput));
if (!isSilent) {
this.fetchSuggestions();
setTimeout(() => this.setCursorToEnd(this.textInput));
}
});

if (onChange) {
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface CommonProps<SuggestionType> {
highlightClassName?: string;
minChars?: number;
customInput?: ElementType;
selectOnBlur?: boolean;
}

export interface DaDataAddressMetro {
Expand Down

0 comments on commit 93239ad

Please sign in to comment.