Skip to content

Commit

Permalink
Merge pull request #64 from orbita-center/v1.3.7
Browse files Browse the repository at this point in the history
V1.3.7
  • Loading branch information
RUVATA authored Aug 28, 2022
2 parents 39a98fa + 35f62e7 commit 13fdabe
Show file tree
Hide file tree
Showing 9 changed files with 329 additions and 384 deletions.
49 changes: 39 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,19 @@ function that returns node (or nodes array) to place that as 'custom action'
at v1.3.4 variant 'React.ReactNode' deprecated at types definition
since v1.3.5 variant 'React.ReactNode' will be deprecated from functionality
```typescript
// {ResponseType<T>} where 'T' is one of FetchType (value placed at 'type' prop):
// {AddressQueryMode} 'address' | {PartyQueryMode} 'party' | {BankQueryMode} |
// {EmailQueryMode} 'email' | {FioQueryMode} 'fio' | {FmsUnitQueryMode} 'fms_unit';
// it determines DaData response object type
customActions?: ((suggestions: SpecificQueryModeResponse<T>[]) => React.ReactNode);
import { SpecificQueryModeResponse, FetchType } from 'react-dadata-box';

// {SpecificQueryModeResponse<T>} where 'T' is one of FetchType (value placed at 'type' prop):
// {AddressQueryMode} 'address' | {CountryQueryMode} 'country' | {PartyQueryMode} 'party' |
// {BankQueryMode} 'bank' | {EmailQueryMode} 'email' | {FioQueryMode} 'fio' |
// {FmsUnitQueryMode} 'fms_unit';

// SpecificQueryModeResponse<FetchType> is generic that returned one of corresponding AbstractResponseType
// AbstractResponseType and any of response types is built-in and may be impoted from library
type AbstractResponseType = CountryResponseType | PartyResponseType | BankResponseType | EmailResponseType | FioResponseType | FmsUnitResponseType

// type of 'suggestions' wiil be infered automaticaliy from fetch type and it will be SpecificQueryModeResponse<T>[]
customActions?: ((suggestions: SpecificQueryModeResponse<FetchType>[]) => React.ReactNode);
```
at versions < v1.3.4
```typescript
Expand Down Expand Up @@ -129,8 +137,22 @@ debounce?: number;
___
#### onChange ![](https://img.shields.io/badge/optional-green)
change/select event handler, called when user select suggestion by mouse click or Enter key from keyboard. Handler gets suggestion object as argument

```typescript
onChange?: (suggestion: DadataSuggestion) => void;
import { SpecificQueryModeResponse, FetchType } from 'react-dadata-box';

// {SpecificQueryModeResponse<T>} where 'T' is one of FetchType (value placed at 'type' prop):
// {AddressQueryMode} 'address' | {CountryQueryMode} 'country' | {PartyQueryMode} 'party' |
// {BankQueryMode} 'bank' | {EmailQueryMode} 'email' | {FioQueryMode} 'fio' |
// {FmsUnitQueryMode} 'fms_unit';

// SpecificQueryModeResponse<FetchType> is generic that returned one of corresponding AbstractResponseType
// AbstractResponseType and any of response types is built-in and may be impoted from library

type AbstractResponseType = CountryResponseType | PartyResponseType | BankResponseType | EmailResponseType | FioResponseType | FmsUnitResponseType

// type of 'suggestion' wiil be infered automaticaliy from fetch type and it will be SpecificQueryModeResponse<T>[]
onChange ? : (suggestion: SpecificQueryModeResponse<FetchType>) => void;
```
___
#### onIdleOut ![](https://img.shields.io/badge/optional-green)
Expand Down Expand Up @@ -189,24 +211,30 @@ ___
#### type ![](https://img.shields.io/badge/optional-green) ![](https://img.shields.io/badge/default-"address"-lightgrey)
fetched suggestions type (declarative in DaData service terms).

It may be 'address', 'bank', 'email', 'fio' (last/first/middle names + gender detection), 'fms_unit' (branch/unit that issued Russian pasport)
It may be 'address', 'country', 'bank', 'email', 'fio' (last/first/middle names + gender detection), 'fms_unit' (branch/unit that issued Russian pasport)

```typescript
type?: 'address' | 'party' | 'bank' | 'email' | 'fio' | 'fms_unit';
type FetchType = AddressQueryMode | CountryQueryMode | PartyQueryMode | BankQueryMode | EmailQueryMode | FioQueryMode | FmsUnitQueryMode;
// => 'address' (default) | 'country' | 'party' | 'bank' | 'email' | 'fio' | 'fms_unit'
type?: FetchType;
```
![](https://img.shields.io/badge/ATTENTION-red) [![](https://img.shields.io/badge/TypeScript-types-blue?logo=typescript)](https://www.typescriptlang.org/)
For correct infer types results of fetching, you need to manually setup type string to component generic parameter:
*'address'* is default typing it not need to be placed patently

[![](https://img.shields.io/badge/CodeSandbox-playground-black?logo=codesandbox)](https://codesandbox.io/s/react-dadata-box-example-customactions-ox2li)
```typescript
// for example if we need to fetch 'party'
import { PartyResponseType } from 'react-dadata-box';
import { SpecificQueryModeResponse } from 'react-dadata-box';
...
// if you setup 'party' as generic param - handlers as 'onChange' will be typed accordingly
// (suggestion: PartyResponseType) => void in this sample
<ReactDadataBox<'party'>
token={testToken}
type='party'
onChange={(suggestion: PartyResponseType) => setSample2(suggestion)}
// 'suggestion' type will be automatically infered as : SpecificQueryModeResponse<'party'>
onChange={(suggestion) => setSample2(suggestion)}
// 'suggestion' type will be automatically infered as : SpecificQueryModeResponse<'party'>
customActions={(suggestions) =>
!suggestions.length && (
<a href=" " onClick={idleAction}>
Expand All @@ -221,6 +249,7 @@ exported bulit-in types accordingly to type parameter
| **type param** | **built-in type** |
| ------------- | ------------- |
| 'address' | AddressResponseType (default) |
| 'country' | CountryResponseType |
| 'party' | PartyResponseType |
| 'bank' | BankResponseType |
| 'email' | EmailResponseType |
Expand Down
59 changes: 45 additions & 14 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,21 @@ ___
в версии v1.3.4 вариант определения как 'React.ReactNode' упразднен в определении типов
насиная с версии v1.3.5 вариант определения как 'React.ReactNode' будет упразднен технически
```typescript
// {ResponseType<T>} где 'T' это один из FetchType (значение передаваемое в пропс 'type'):
// {AddressQueryMode} 'address' | {PartyQueryMode} 'party' | {BankQueryMode} |
// {EmailQueryMode} 'email' | {FioQueryMode} 'fio' | {FmsUnitQueryMode} 'fms_unit';
import { SpecificQueryModeResponse, FetchType } from 'react-dadata-box';

// {SpecificQueryModeResponse<T>} где 'T' это один из FetchType (значение передаваемое в пропс 'type'):
// {AddressQueryMode} 'address' | {CountryQueryMode} 'country' | {PartyQueryMode} 'party' |
// {BankQueryMode} | {EmailQueryMode} 'email' | {FioQueryMode} 'fio' |
// {FmsUnitQueryMode} 'fms_unit';
// это определяет типизацию структуры соотв. ответа от DaData по специфическому type
customActions?: ((suggestions: SpecificQueryModeResponse<T>[]) => React.ReactNode);

// SpecificQueryModeResponse<FetchType> дженерик который выводит один из AbstractResponseType
// AbstractResponseType и любой их отдельных типов этого Union являются встроенными типами и могут быть импортированы под нужды описания типов из библиотеки
type AbstractResponseType = CountryResponseType | PartyResponseType | BankResponseType | EmailResponseType | FioResponseType | FmsUnitResponseType

// тип 'suggestions' будет выведен автоматически на основе установленного типа запроса (type property)
// и он будет являться SpecificQueryModeResponse<T>[] где 'T' соотв. (type property: FetchType)
customActions?: ((suggestions: SpecificQueryModeResponse<FetchType>[]) => React.ReactNode);
```
at versions < v1.3.4
```typescript
Expand Down Expand Up @@ -131,7 +141,21 @@ ___
#### onChange ![](https://img.shields.io/badge/optional-green)
обработчик события выбора подсказки пользователем (клик по элементу в списке или Enter для элемента который в данный момент выделен), принимает объект отражающий выбранную 'подсказку' в качестве аргумента
```typescript
onChange?: (suggestion: DadataSuggestion) => void;
import { SpecificQueryModeResponse, FetchType } from 'react-dadata-box';

// {SpecificQueryModeResponse<T>} где 'T' это один из FetchType (значение передаваемое в пропс 'type'):
// {AddressQueryMode} 'address' | {CountryQueryMode} 'country' | {PartyQueryMode} 'party' |
// {BankQueryMode} | {EmailQueryMode} 'email' | {FioQueryMode} 'fio' |
// {FmsUnitQueryMode} 'fms_unit';
// это определяет типизацию структуры соотв. ответа от DaData по специфическому type

// SpecificQueryModeResponse<FetchType> дженерик который выводит один из AbstractResponseType
// AbstractResponseType и любой их отдельных типов этого Union являются встроенными типами и могут быть импортированы под нужды описания типов из библиотеки
type AbstractResponseType = CountryResponseType | PartyResponseType | BankResponseType | EmailResponseType | FioResponseType | FmsUnitResponseType

// тип 'suggestion' будет выведен автоматически на основе установленного типа запроса (type property)
// и он будет являться SpecificQueryModeResponse<T>[] где 'T' соотв. (type property: FetchType)
onChange?: (suggestion: SpecificQueryModeResponse<FetchType>) => void;
```
___
#### onIdleOut ![](https://img.shields.io/badge/optional-green)
Expand Down Expand Up @@ -190,32 +214,38 @@ token: string;
```
___
#### type ![](https://img.shields.io/badge/optional-green) ![](https://img.shields.io/badge/default-"address"-lightgrey)
тип запрашиваемых "подсказок" (в терминологии сервиса DaData): 'address' (адреса), 'bank' (банки), 'email' (электронная почта), 'fio' (ФИО + определение пола), 'fms_unit' (отделение выдавшее паспорт РФ)
тип запрашиваемых "подсказок" (в терминологии сервиса DaData): 'address' (адреса), 'country' (страны), 'bank' (банки), 'email' (электронная почта), 'fio' (ФИО + определение пола), 'fms_unit' (отделение выдавшее паспорт РФ)

```typescript
type?: 'address' | 'party' | 'bank' | 'email' | 'fio' | 'fms_unit';
type FetchType = AddressQueryMode | CountryQueryMode | PartyQueryMode | BankQueryMode | EmailQueryMode | FioQueryMode | FmsUnitQueryMode;
// => 'address' (default) | 'country' | 'party' | 'bank' | 'email' | 'fio' | 'fms_unit'
type?: FetchType;
```
![](https://img.shields.io/badge/ATTENTION-red) [![](https://img.shields.io/badge/TypeScript-types-blue?logo=typescript)](https://www.typescriptlang.org/)
Для корректного вывода типов описывающих структуры которыми отвечает сервер DaData в соответствии с указанным типом сервиса (параметр **type**) -
необходимо передать этот тип (соотв. строку) как параметр дженерика.

*'address'* является значение по умолчанию - и не требует явной установки

[![](https://img.shields.io/badge/CodeSandbox-playground-black?logo=codesandbox)](https://codesandbox.io/s/react-dadata-box-example-customactions-ox2li)
```typescript
// н/п если мы используем сервис 'party'
import { PartyResponseType } from 'react-dadata-box';
import { SpecificQueryModeResponse } from 'react-dadata-box';
...
// после установки 'party' как дженерик параметра компонента - обработчики такие как 'onChange' начинают типизироваться соотв.
// выводится тип (suggestion: PartyResponseType) => void в данном примере
<ReactDadataBox<'party'>
token={testToken}
type='party'
onChange={(suggestion: PartyResponseType) => setSample2(suggestion)}
// тип 'suggestion' будет выведен автоматически как SpecificQueryModeResponse<'party'>
onChange={(suggestion) => setSample2(suggestion)}
// тип 'suggestion' будет выведен автоматически как SpecificQueryModeResponse<'party'>
customActions={(suggestions) =>
!suggestions.length && (
<a href=" " onClick={idleAction}>
произвольное действие
</a>
)
!suggestions.length && (
<a href=" " onClick={idleAction}>
произвольное действие
</a>
)
}
/>
```
Expand All @@ -224,6 +254,7 @@ import { PartyResponseType } from 'react-dadata-box';
| **type param** | **built-in type** |
| ------------- | ------------- |
| 'address' | AddressResponseType (default) |
| 'country' | CountryResponseType |
| 'party' | PartyResponseType |
| 'bank' | BankResponseType |
| 'email' | EmailResponseType |
Expand Down
Empty file modified dist/index.css
100755 → 100644
Empty file.
Loading

0 comments on commit 13fdabe

Please sign in to comment.