added definitions for react select (v2) (#27737)

* moved existing "react-select" definitions into "v1" directory

* updated references to V1 of "react-select"

* dts-gen --dt --name react-select --template module

* added placeholders for react-select definitions and tests

* fixed imports of react and react-select

* updated config. files

* drafted definitions for react-select

* updated definitions for react-select

* made Props in stateManager.d.ts and Select.d.ts optional

* handle grouped options in Select.d.ts

* updated definitions for react-select

* resolved merge conflicts

* fixed issues identified by "npm test"

* updated type of "menuPortalTarget"

* remove OptionType type and introduce throughout as a generic parameter

* add an extra type

* re-enable interface-over-type-literal lint rule

* parameterize GroupedOptionsType
after some consideration this should be parameterized, typically with a union type, see Grouped example which is a select of `ColourOption | FlavourOption`
This commit is contained in:
Claas Ahlrichs
2018-08-03 01:41:18 +02:00
committed by Sheetal Nandi
parent 3a9ec5cad2
commit 7c33a95827
90 changed files with 4716 additions and 662 deletions

View File

@@ -1,654 +1,21 @@
// Type definitions for react-select 1.3
// Project: https://github.com/JedWatson/react-select
// Definitions by: ESQUIBET Hugo <https://github.com/Hesquibet>
// Gilad Gray <https://github.com/giladgray>
// Izaak Baker <https://github.com/iebaker>
// Tadas Dailyda <https://github.com/skirsdeda>
// Mark Vujevits <https://github.com/vujevits>
// Mike Deverell <https://github.com/devrelm>
// MartynasZilinskas <https://github.com/MartynasZilinskas>
// Onat Yigit Mercan <https://github.com/onatm>
// Ian Johnson <https://github.com/ninjaferret>
// Anton Novik <https://github.com/tehbi4>
// David Schkalee <https://github.com/misantronic>
// Arthur Udalov <https://github.com/darkartur>
// Sebastian Silbermann <https://github.com/eps1lon>
// Endurance Idehen <https://github.com/endurance>
// Guillaume Chartier <https://github.com/RCGuillaume>
// Type definitions for react-select 2.0
// Project: https://github.com/JedWatson/react-select#readme
// Definitions by: Claas Ahlrichs <https://github.com/claasahl>
// Jon Freedman <https://github.com/jonfreedman>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.9
import * as React from 'react';
import SelectBase from './lib/Select';
import { StateManager } from './lib/stateManager';
export default class ReactSelectClass<TValue = OptionValues> extends React.Component<ReactSelectProps<TValue>> {
focus(): void;
setValue(value: Option<TValue>): void;
}
// Other components
export class Creatable<TValue = OptionValues> extends React.Component<ReactCreatableSelectProps<TValue>> { }
export class Async<TValue = OptionValues> extends React.Component<ReactAsyncSelectProps<TValue>> { }
export class AsyncCreatable<TValue = OptionValues> extends React.Component<ReactAsyncCreatableSelectProps<TValue>> { }
export default SelectBase;
// export default StateManager;
export type OptionComponentType<TValue = OptionValues> = React.ComponentType<OptionComponentProps<TValue>>;
export type ValueComponentType<TValue = OptionValues> = React.ComponentType<ValueComponentProps<TValue>>;
export type HandlerRendererResult = JSX.Element | null | false;
// Handlers
export type FocusOptionHandler<TValue = OptionValues> = (option: Option<TValue>) => void;
export type SelectValueHandler<TValue = OptionValues> = (option: Option<TValue>) => void;
export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult;
export type ClearRendererHandler = () => HandlerRendererResult;
export type FilterOptionHandler<TValue = OptionValues> = (option: Option<TValue>, filter: string) => boolean;
export type FilterOptionsHandler<TValue = OptionValues> = (options: Options<TValue>, filter: string, currentValues: Options<TValue>) => Options<TValue>;
export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult;
export type MenuRendererHandler<TValue = OptionValues> = (props: MenuRendererProps<TValue>) => HandlerRendererResult;
export type OnCloseHandler = () => void;
export type OnInputChangeHandler = (inputValue: string) => string;
export type OnInputKeyDownHandler = React.KeyboardEventHandler<HTMLDivElement | HTMLInputElement>;
export type OnMenuScrollToBottomHandler = () => void;
export type OnOpenHandler = () => void;
export type OnFocusHandler = React.FocusEventHandler<HTMLDivElement | HTMLInputElement>;
export type OnBlurHandler = React.FocusEventHandler<HTMLDivElement | HTMLInputElement>;
export type OptionRendererHandler<TValue = OptionValues> = (option: Option<TValue>) => HandlerRendererResult;
export type ValueRendererHandler<TValue = OptionValues> = (option: Option<TValue>, index?: number) => HandlerRendererResult;
export type OnValueClickHandler<TValue = OptionValues> = (option: Option<TValue>, event: React.MouseEvent<HTMLAnchorElement>) => void;
export type IsOptionUniqueHandler<TValue = OptionValues> = (arg: { option: Option<TValue>, options: Options<TValue>, labelKey: string, valueKey: string }) => boolean;
export type IsValidNewOptionHandler = (arg: { label: string }) => boolean;
export type NewOptionCreatorHandler<TValue = OptionValues> = (arg: { label: string, labelKey: string, valueKey: string }) => Option<TValue>;
export type PromptTextCreatorHandler = (filterText: string) => string;
export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean;
export type OnChangeSingleHandler<TValue = OptionValues> = OnChangeHandler<TValue, Option<TValue>>;
export type OnChangeMultipleHandler<TValue = OptionValues> = OnChangeHandler<TValue, Options<TValue>>;
export type OnChangeHandler<TValue = OptionValues, TOption = Option<TValue> | Options<TValue>> = (newValue: TOption | null) => void;
export type OnNewOptionClickHandler<TValue = OptionValues> = (option: Option<TValue>) => void;
export type LoadOptionsHandler<TValue = OptionValues> = LoadOptionsAsyncHandler<TValue> | LoadOptionsLegacyHandler<TValue>;
export type LoadOptionsAsyncHandler<TValue = OptionValues> = (input: string) => Promise<AutocompleteResult<TValue>>;
export type LoadOptionsLegacyHandler<TValue = OptionValues> = (input: string, callback: (err: any, result: AutocompleteResult<TValue>) => void) => void;
export interface AutocompleteResult<TValue = OptionValues> {
/** The search-results to be displayed */
options: Options<TValue>;
/**
* Should be set to true, if and only if a longer query with the same prefix
* would return a subset of the results
* If set to true, more specific queries will not be sent to the server.
*/
complete: boolean;
}
export type Options<TValue = OptionValues> = Array<Option<TValue>>;
export interface Option<TValue = OptionValues> {
/** Text for rendering */
label?: string;
/** Value for searching */
value?: TValue;
/**
* Allow this option to be cleared
* @default true
*/
clearableValue?: boolean;
/**
* Do not allow this option to be selected
* @default false
*/
disabled?: boolean;
/**
* In the event that a custom menuRenderer is provided, Option should be able
* to accept arbitrary key-value pairs. See react-virtualized-select.
*/
[property: string]: any;
}
export type OptionValues = string | number | boolean;
export interface MenuRendererProps<TValue = OptionValues> {
/**
* The currently focused option; should be visible in the menu by default.
* default {}
*/
focusedOption: Option<TValue>;
/**
* Callback to focus a new option; receives the option as a parameter.
*/
focusOption: FocusOptionHandler<TValue>;
/**
* Option labels are accessible with this string key.
*/
labelKey: string;
/**
* Ordered array of options to render.
*/
options: Options<TValue>;
/**
* Callback to select a new option; receives the option as a parameter.
*/
selectValue: SelectValueHandler<TValue>;
/**
* Array of currently selected options.
*/
valueArray: Options<TValue>;
/**
* Callback to remove selection from option; receives the option as a parameter.
*/
removeValue: SelectValueHandler<TValue>;
/**
* function which returns a custom way to render the options in the menu
*/
optionRenderer: OptionRendererHandler<TValue>;
}
export interface OptionComponentProps<TValue = OptionValues> {
/**
* Classname(s) to apply to the option component.
*/
className?: string;
/**
* Currently focused option.
*/
focusOption?: Option<TValue>;
inputValue?: string;
instancePrefix?: string;
/**
* True if this option is disabled.
*/
isDisabled?: boolean;
/**
* True if this option is focused.
*/
isFocused?: boolean;
/**
* True if this option is selected.
*/
isSelected?: boolean;
/**
* Callback to be invoked when this option is focused.
*/
onFocus?: (option: Option<TValue>, event: any) => void;
/**
* Callback to be invoked when this option is selected.
*/
onSelect?: (option: Option<TValue>, event: any) => void;
/**
* Option to be rendered by this component.
*/
option: Option<TValue>;
/**
* Index of the option being rendered in the list
*/
optionIndex?: number;
/**
* Callback to invoke when removing an option from a multi-selection. (Not necessarily the one
* being rendered)
*/
removeValue?: (value: TValue | TValue[]) => void;
/**
* Callback to invoke to select an option. (Not necessarily the one being rendered)
*/
selectValue?: (value: TValue | TValue[]) => void;
}
export interface ArrowRendererProps {
/**
* Arrow mouse down event handler.
*/
onMouseDown: React.MouseEventHandler<any>;
/**
* whether the Select is open or not.
*/
isOpen: boolean;
}
export interface ValueComponentProps<TValue = OptionValues> {
disabled: ReactSelectProps<TValue>['disabled'];
id: string;
instancePrefix: string;
onClick: OnValueClickHandler<TValue> | null;
onRemove?: SelectValueHandler<TValue>;
placeholder: ReactSelectProps<TValue>['placeholder'];
value: Option<TValue>;
values?: Array<Option<TValue>>;
}
export interface ReactSelectProps<TValue = OptionValues> extends React.Props<ReactSelectClass<TValue>> {
/**
* text to display when `allowCreate` is true.
* @default 'Add "{label}"?'
*/
addLabelText?: string;
/**
* renders a custom drop-down arrow to be shown in the right-hand side of the select.
* @default undefined
*/
arrowRenderer?: ArrowRendererHandler | null;
/**
* blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices.
* @default false
*/
autoBlur?: boolean;
/**
* autofocus the component on mount
* @deprecated. Use autoFocus instead
* @default false
*/
autofocus?: boolean;
/**
* autofocus the component on mount
* @default false
*/
autoFocus?: boolean;
/**
* If enabled, the input will expand as the length of its value increases
*/
autosize?: boolean;
/**
* whether pressing backspace removes the last item when there is no input value
* @default true
*/
backspaceRemoves?: boolean;
/**
* Message to use for screenreaders to press backspace to remove the current item
* {label} is replaced with the item label
* @default "Press backspace to remove..."
*/
backspaceToRemoveMessage?: string;
/**
* CSS className for the outer element
*/
className?: string;
/**
* Prefix prepended to element default className if no className is defined
*/
classNamePrefix?: string;
/**
* title for the "clear" control when `multi` is true
* @default "Clear all"
*/
clearAllText?: string;
/**
* Renders a custom clear to be shown in the right-hand side of the select when clearable true
* @default undefined
*/
clearRenderer?: ClearRendererHandler;
/**
* title for the "clear" control
* @default "Clear value"
*/
clearValueText?: string;
/**
* whether to close the menu when a value is selected
* @default true
*/
closeOnSelect?: boolean;
/**
* whether it is possible to reset value. if enabled, an X button will appear at the right side.
* @default true
*/
clearable?: boolean;
/**
* whether backspace removes an item if there is no text input
* @default true
*/
deleteRemoves?: boolean;
/**
* delimiter to use to join multiple values
* @default ","
*/
delimiter?: string;
/**
* whether the Select is disabled or not
* @default false
*/
disabled?: boolean;
/**
* whether escape clears the value when the menu is closed
* @default true
*/
escapeClearsValue?: boolean;
/**
* method to filter a single option
*/
filterOption?: FilterOptionHandler<TValue>;
/**
* method to filter the options array
*/
filterOptions?: FilterOptionsHandler<TValue>;
/**
* id for the underlying HTML input element
* @default undefined
*/
id?: string;
/**
* whether to strip diacritics when filtering
* @default true
*/
ignoreAccents?: boolean;
/**
* whether to perform case-insensitive filtering
* @default true
*/
ignoreCase?: boolean;
/**
* custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
* @default {}
*/
inputProps?: { [key: string]: any };
/**
* renders a custom input
*/
inputRenderer?: InputRendererHandler;
/**
* allows for synchronization of component id's on server and client.
* @see https://github.com/JedWatson/react-select/pull/1105
*/
instanceId?: string;
/**
* whether the Select is loading externally or not (such as options being loaded).
* if true, a loading spinner will be shown at the right side.
* @default false
*/
isLoading?: boolean;
/**
* (legacy mode) joins multiple values into a single form field with the delimiter
* @default false
*/
joinValues?: boolean;
/**
* the option property to use for the label
* @default "label"
*/
labelKey?: string;
/**
* (any, start) match the start or entire string when filtering
* @default "any"
*/
matchPos?: string;
/**
* (any, label, value) which option property to filter on
* @default "any"
*/
matchProp?: string;
/**
* buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
* @default 0
*/
menuBuffer?: number;
/**
* optional style to apply to the menu container
*/
menuContainerStyle?: React.CSSProperties;
/**
* renders a custom menu with options
*/
menuRenderer?: MenuRendererHandler<TValue>;
/**
* optional style to apply to the menu
*/
menuStyle?: React.CSSProperties;
/**
* multi-value input
* @default false
*/
multi?: boolean;
/**
* field name, for hidden `<input>` tag
*/
name?: string;
/**
* placeholder displayed when there are no matching search results or a falsy value to hide it
* @default "No results found"
*/
noResultsText?: string | JSX.Element;
/**
* onBlur handler: function (event) {}
*/
onBlur?: OnBlurHandler;
/**
* whether to clear input on blur or not
* @default true
*/
onBlurResetsInput?: boolean;
/**
* whether the input value should be reset when options are selected.
* Also input value will be set to empty if 'onSelectResetsInput=true' and
* Select will get new value that not equal previous value.
* @default true
*/
onSelectResetsInput?: boolean;
/**
* whether to clear input when closing the menu through the arrow
* @default true
*/
onCloseResetsInput?: boolean;
/**
* onChange handler: function (newValue) {}
*/
onChange?: OnChangeHandler<TValue>;
/**
* fires when the menu is closed
*/
onClose?: OnCloseHandler;
/**
* onFocus handler: function (event) {}
*/
onFocus?: OnFocusHandler;
/**
* onInputChange handler: function (inputValue) {}
*/
onInputChange?: OnInputChangeHandler;
/**
* onInputKeyDown handler: function (keyboardEvent) {}
*/
onInputKeyDown?: OnInputKeyDownHandler;
/**
* fires when the menu is scrolled to the bottom; can be used to paginate options
*/
onMenuScrollToBottom?: OnMenuScrollToBottomHandler;
/**
* fires when the menu is opened
*/
onOpen?: OnOpenHandler;
/**
* boolean to enable opening dropdown when focused
* @default false
*/
openOnClick?: boolean;
/**
* open the options menu when the input gets focus (requires searchable = true)
* @default true
*/
openOnFocus?: boolean;
/**
* className to add to each option component
*/
optionClassName?: string;
/**
* option component to render in dropdown
*/
optionComponent?: OptionComponentType<TValue>;
/**
* function which returns a custom way to render the options in the menu
*/
optionRenderer?: OptionRendererHandler<TValue>;
/**
* array of Select options
* @default false
*/
options?: Options<TValue>;
/**
* number of options to jump when using page up/down keys
* @default 5
*/
pageSize?: number;
/**
* field placeholder, displayed when there's no value
* @default "Select..."
*/
placeholder?: string | JSX.Element;
/**
* whether the selected option is removed from the dropdown on multi selects
* @default true
*/
removeSelected?: boolean;
/**
* applies HTML5 required attribute when needed
* @default false
*/
required?: boolean;
/**
* value to use when you clear the control
*/
resetValue?: any;
/**
* use react-select in right-to-left direction
* @default false
*/
rtl?: boolean;
/**
* whether the viewport will shift to display the entire menu when engaged
* @default true
*/
scrollMenuIntoView?: boolean;
/**
* whether to enable searching feature or not
* @default true;
*/
searchable?: boolean;
/**
* whether to select the currently focused value when the [tab] key is pressed
*/
tabSelectsValue?: boolean;
/**
* initial field value
*/
value?: Option<TValue> | Options<TValue> | string | string[] | number | number[] | boolean;
/**
* the option property to use for the value
* @default "value"
*/
valueKey?: string;
/**
* function which returns a custom way to render the value selected
* @default false
*/
valueRenderer?: ValueRendererHandler<TValue>;
/**
* optional style to apply to the control
*/
style?: React.CSSProperties;
/**
* optional tab index of the control
*/
tabIndex?: string | number;
/**
* value component to render
*/
valueComponent?: ValueComponentType<TValue>;
/**
* optional style to apply to the component wrapper
*/
wrapperStyle?: React.CSSProperties;
/**
* onClick handler for value labels: function (value, event) {}
*/
onValueClick?: OnValueClickHandler<TValue>;
/**
* pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false
*/
simpleValue?: boolean;
}
export interface ReactCreatableSelectProps<TValue = OptionValues> extends ReactSelectProps<TValue> {
/**
* Searches for any matching option within the set of options. This function prevents
* duplicate options from being created.
*/
isOptionUnique?: IsOptionUniqueHandler<TValue>;
/**
* Determines if the current input text represents a valid option.
*/
isValidNewOption?: IsValidNewOptionHandler;
/**
* factory to create new options
*/
newOptionCreator?: NewOptionCreatorHandler<TValue>;
/**
* Creates prompt/placeholder for option text.
*/
promptTextCreator?: PromptTextCreatorHandler;
/**
* Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option.
*/
shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler;
/**
* new option click handler: function (option) {}
*/
onNewOptionClick?: OnNewOptionClickHandler<TValue>;
/**
* true: Show new option at top of list
* false: Show new option at bottom of list
* @default true
*/
showNewOptionAtTop?: boolean;
}
export interface ReactAsyncSelectProps<TValue = OptionValues> extends ReactSelectProps<TValue> {
/**
* Whether to auto-load the default async options set.
*/
autoload?: boolean;
/**
* object to use to cache results; can be null to disable cache
*/
cache?: { [key: string]: any } | boolean;
/**
* function to call to load options asynchronously
*/
loadOptions: LoadOptionsHandler<TValue>;
/**
* replaces the placeholder while options are loading
*/
loadingPlaceholder?: string | JSX.Element;
/**
* displayed in the drop down list when the user did not type anything yet
*/
searchPromptText?: string;
}
export type ReactAsyncCreatableSelectProps<TValue = OptionValues> = ReactAsyncSelectProps<TValue> & ReactCreatableSelectProps<TValue>;
export { SelectBase };
export { default as Async } from './lib/Async';
export { default as AsyncCreatable } from './lib/AsyncCreatable';
export { default as Creatable } from './lib/Creatable';
export { createFilter } from './lib/filters';
export { default as makeAnimated } from './lib/animated/index';
export { components } from './lib/components/index';
export { mergeStyles } from './lib/styles';

47
types/react-select/lib/Async.d.ts vendored Normal file
View File

@@ -0,0 +1,47 @@
import * as React from 'react';
import Select, { Props as SelectProps } from './Select';
import { handleInputChange } from './utils';
import manageState from './stateManager';
import { OptionsType, InputActionMeta } from './types';
export interface AsyncProps<OptionType> {
/* The default set of options to show before the user starts searching. When
set to `true`, the results for loadOptions('') will be autoloaded. */
defaultOptions: OptionsType<OptionType> | boolean;
/* Function that returns a promise, which is the set of options to be used
once the promise resolves. */
loadOptions: (inputValue: string, callback: ((options: OptionsType<OptionType>) => void)) => Promise<any> | void;
/* If cacheOptions is truthy, then the loaded data will be cached. The cache
will remain until `cacheOptions` changes value. */
cacheOptions: any;
}
export type Props<OptionType> = SelectProps<OptionType> & AsyncProps<OptionType>;
export const defaultProps: Props<any>;
export interface State<OptionType> {
defaultOptions?: OptionsType<OptionType>;
inputValue: string;
isLoading: boolean;
loadedInputValue?: string;
loadedOptions: OptionsType<OptionType>;
passEmptyOptions: boolean;
}
export class Async<OptionType> extends React.Component<Props<OptionType>, State<OptionType>> {
static defaultProps: Props<any>;
select: React.Ref<any>;
lastRequest: {};
mounted: boolean;
optionsCache: { [key: string]: OptionsType<OptionType> };
focus(): void;
blur(): void;
loadOptions(inputValue: string, callback: (options: OptionsType<OptionType>) => void): void;
handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string;
}
export function makeAsyncSelect(SelectComponent: React.ComponentType<any>): Async<any>;
export default Async;

View File

@@ -0,0 +1,25 @@
import { Component, Ref as ElementRef } from 'react';
import { Props as AsyncProps, State as AsyncState } from './Async';
import { Props as CreatableProps, State as CreatableState } from './Creatable';
import { OptionsType, ValueType, ActionMeta, InputActionMeta } from './types';
import { cleanValue } from './utils';
type Props<OptionType> = AsyncProps<OptionType> & CreatableProps<OptionType>;
type State<OptionType> = AsyncState<OptionType> & CreatableState<OptionType>;
export class AsyncCreatable<OptionType> extends Component<Props<OptionType>, State<OptionType>> {
static defaultProps: Props<any>;
select: ElementRef<any>;
lastRequest: {};
mounted: boolean;
optionsCache: { [key: string]: OptionsType<OptionType> };
focus(): void;
blur(): void;
loadOptions(inputValue: string, callback: (options: OptionsType<OptionType>) => void): void;
handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string;
onChange: (newValue: ValueType<OptionType>, actionMeta: ActionMeta) => void;
}
export default AsyncCreatable;

49
types/react-select/lib/Creatable.d.ts vendored Normal file
View File

@@ -0,0 +1,49 @@
import * as React from 'react';
import Select, { Props as SelectProps } from './Select';
import { OptionsType, ValueType, ActionMeta } from './types';
import { cleanValue } from './utils';
import manageState from './stateManager';
export interface CreatableProps<OptionType> {
/* Allow options to be created while the `isLoading` prop is true. Useful to
prevent the "create new ..." option being displayed while async results are
still being loaded. */
allowCreateWhileLoading?: boolean;
/* Gets the label for the "create new ..." option in the menu. Is given the
current input value. */
formatCreateLabel?: (inputValue: string) => Node;
/* Determines whether the "create new ..." option should be displayed based on
the current input value, select value and options array. */
isValidNewOption?: (a: string, b: ValueType<OptionType>, c: OptionsType<OptionType>) => boolean;
/* Returns the data for the new option when it is created. Used to display the
value, and is passed to `onChange`. */
getNewOptionData?: (a: string, b: Node) => OptionType;
/* If provided, this will be called with the input value when a new option is
created, and `onChange` will **not** be called. Use this when you need more
control over what happens when new options are created. */
onCreateOption?: (inputValue: string) => void;
/* Sets the position of the createOption element in your options list. Defaults to 'last' */
createOptionPosition?: 'first' | 'last';
}
export type Props<OptionType> = SelectProps<OptionType> & CreatableProps<OptionType>;
export const defaultProps: Props<any>;
export interface State<OptionType> {
newOption: OptionType | undefined;
options: OptionsType<OptionType>;
}
export class Creatable<OptionType> extends React.Component<Props<OptionType>, State<OptionType>> {
static defaultProps: Props<any>;
select: React.Ref<any>;
onChange: (newValue: ValueType<OptionType>, actionMeta: ActionMeta) => void;
focus(): void;
blur(): void;
}
export function makeCreatableSelect(SelectComponent: React.ComponentType<any>): Creatable<any>;
export default Creatable;

419
types/react-select/lib/Select.d.ts vendored Normal file
View File

@@ -0,0 +1,419 @@
import * as React from 'react';
import { Option } from './filters';
import {
InstructionsContext,
ValueEventContext,
} from './accessibility/index';
import {
classNames,
noop,
scrollIntoView,
} from './utils';
import {
formatGroupLabel,
getOptionLabel,
getOptionValue,
isOptionDisabled,
} from './builtins';
import {
PlaceholderOrValue,
SelectComponents,
SelectComponentsConfig,
} from './components/index';
import { StylesConfig } from './styles';
import {
ActionMeta,
ActionTypes,
FocusDirection,
FocusEventHandler,
GroupType,
InputActionMeta,
KeyboardEventHandler,
MenuPlacement,
MenuPosition,
OptionsType,
ValueType,
GroupedOptionsType,
} from './types';
export type MouseOrTouchEvent =
| React.MouseEvent<HTMLElement>
| React.TouchEvent<HTMLElement>;
export type FormatOptionLabelContext = 'menu' | 'value';
export interface FormatOptionLabelMeta<OptionType> {
context: FormatOptionLabelContext;
inputValue: string;
selectValue: ValueType<OptionType>;
}
export interface Props<OptionType> {
/* Aria label (for assistive tech) */
'aria-label'?: string;
/* HTML ID of an element that should be used as the label (for assistive tech) */
'aria-labelledby'?: string;
/* Focus the control when it is mounted */
autoFocus?: boolean;
/* Remove the currently focused option when the user presses backspace */
backspaceRemovesValue?: boolean;
/* Remove focus from the input when the user selects an option (handy for dismissing the keyboard on touch devices) */
blurInputOnSelect?: boolean;
/* When the user reaches the top/bottom of the menu, prevent scroll on the scroll-parent */
captureMenuScroll?: boolean;
/* className attribute applied to the outer component */
className?: string;
/* classNamePrefix attribute used as a base for inner component classNames */
classNamePrefix?: string | null;
/* Close the select menu when the user selects an option */
closeMenuOnSelect?: boolean;
/*
If `true`, close the select menu when the user scrolls the document/body.
If a function, takes a standard javascript `ScrollEvent` you return a boolean:
`true` => The menu closes
`false` => The menu stays open
This is useful when you have a scrollable modal and want to portal the menu out,
but want to avoid graphical issues.
*/
closeMenuOnScroll?: boolean | EventListener;
/*
This complex object includes all the compositional components that are used
in `react-select`. If you wish to overwrite a component, pass in an object
with the appropriate namespace.
If you only wish to restyle a component, we recommend using the `styles` prop
instead. For a list of the components that can be passed in, and the shape
that will be passed to them, see [the components docs](/api#components)
*/
components?: SelectComponentsConfig<OptionType>;
/* Whether the value of the select, e.g. SingleValue, should be displayed in the control. */
controlShouldRenderValue?: boolean;
/* Delimiter used to join multiple values into a single HTML Input value */
delimiter?: string;
/* Clear all values when the user presses escape AND the menu is closed */
escapeClearsValue?: boolean;
/* Custom method to filter whether an option should be displayed in the menu */
filterOption?: ((
option: Option,
rawInput: string
) => boolean) | null;
/* Formats group labels in the menu as React components */
formatGroupLabel?: typeof formatGroupLabel;
/* Formats option labels in the menu and control as React components */
formatOptionLabel?: (a: OptionType, b: FormatOptionLabelMeta<OptionType>) => Node;
/* Resolves option data to a string to be displayed as the label by components */
getOptionLabel?: typeof getOptionLabel;
/* Resolves option data to a string to compare options and specify value attributes */
getOptionValue?: typeof getOptionValue;
/* Hide the selected option from the menu */
hideSelectedOptions?: boolean;
/* The id to set on the SelectContainer component. */
id?: string;
/* The value of the search input */
inputValue?: string;
/* The id of the search input */
inputId?: string;
/* Define an id prefix for the select components e.g. {your-id}-value */
instanceId?: number | string;
/* Is the select value clearable */
isClearable?: boolean;
/* Is the select disabled */
isDisabled?: boolean;
/* Is the select in a state of loading (async) */
isLoading?: boolean;
/* Override the built-in logic to detect whether an option is disabled */
isOptionDisabled?: (a: OptionType, b: OptionsType<OptionType>) => boolean | false;
/* Override the built-in logic to detect whether an option is selected */
isOptionSelected?: (a: OptionType, b: OptionsType<OptionType>) => boolean;
/* Support multiple selected options */
isMulti?: boolean;
/* Is the select direction right-to-left */
isRtl?: boolean;
/* Whether to enable search functionality */
isSearchable?: boolean;
/* Async: Text to display when loading options */
loadingMessage?: (obj: { inputValue: string }) => string | null;
/* Minimum height of the menu before flipping */
minMenuHeight?: number;
/* Maximum height of the menu before scrolling */
maxMenuHeight?: number;
/* Whether the menu is open */
menuIsOpen?: boolean;
/* Default placement of the menu in relation to the control. 'auto' will flip
when there isn't enough space below the control. */
menuPlacement?: MenuPlacement;
/* The CSS position value of the menu, when "fixed" extra layout management is required */
menuPosition?: MenuPosition;
/* Whether the menu should use a portal, and where it should attach */
menuPortalTarget?: HTMLElement | null;
/* Whether to block scroll events when the menu is open */
menuShouldBlockScroll?: boolean;
/* Whether the menu should be scrolled into view when it opens */
menuShouldScrollIntoView?: boolean;
/* Name of the HTML Input (optional - without this, no input will be rendered) */
name?: string;
/* Text to display when there are no options */
noOptionsMessage?: (obj: { inputValue: string }) => string | null;
/* Handle blur events on the control */
onBlur?: FocusEventHandler;
/* Handle change events on the select */
onChange?: (value: ValueType<OptionType>, action: ActionMeta) => void;
/* Handle focus events on the control */
onFocus?: FocusEventHandler;
/* Handle change events on the input */
onInputChange?: (newValue: string, actionMeta: InputActionMeta) => void;
/* Handle key down events on the select */
onKeyDown?: KeyboardEventHandler;
/* Handle the menu opening */
onMenuOpen?: () => void;
/* Handle the menu closing */
onMenuClose?: () => void;
/* Fired when the user scrolls to the top of the menu */
onMenuScrollToTop?: (event: React.SyntheticEvent<HTMLElement>) => void;
/* Fired when the user scrolls to the bottom of the menu */
onMenuScrollToBottom?: (event: React.SyntheticEvent<HTMLElement>) => void;
/* Allows control of whether the menu is opened when the Select is focused */
openMenuOnFocus?: boolean;
/* Allows control of whether the menu is opened when the Select is clicked */
openMenuOnClick?: boolean;
/* Array of options that populate the select menu */
options?: GroupedOptionsType<OptionType> | OptionsType<OptionType>;
/* Number of options to jump in menu when page{up|down} keys are used */
pageSize?: number;
/* Placeholder text for the select value */
placeholder?: string;
/* Status to relay to screen readers */
screenReaderStatus?: (obj: { count: number }) => string;
/* Style modifier methods */
styles?: StylesConfig;
/* Sets the tabIndex attribute on the input */
tabIndex?: string;
/* Select the currently focused option when the user presses tab */
tabSelectsValue?: boolean;
/* The value of the select; reflected by the selected option */
value?: ValueType<OptionType>;
defaultInputValue?: string;
defaultMenuIsOpen?: boolean;
defaultValue?: ValueType<OptionType>;
}
export const defaultProps: Props<any>;
export interface MenuOptions<OptionType> {
render: OptionType[];
focusable: OptionType[];
}
export interface State<OptionType> {
ariaLiveSelection: string;
ariaLiveContext: string;
inputIsHidden: boolean;
isFocused: boolean;
isComposing: boolean;
focusedOption: OptionType | null;
focusedValue: OptionType | null;
menuOptions: MenuOptions<OptionType>;
selectValue: OptionsType<OptionType>;
}
export type ElRef = React.Ref<any>;
export default class Select<OptionType> extends React.Component<Props<OptionType>, State<OptionType>> {
static defaultProps: Props<any>;
// Misc. Instance Properties
// ------------------------------
blockOptionHover: boolean;
clearFocusValueOnUpdate: boolean;
commonProps: any; // TODO
components: SelectComponents<OptionType>;
hasGroups: boolean;
initialTouchX: number;
initialTouchY: number;
inputIsHiddenAfterUpdate: boolean | null;
instancePrefix: string;
openAfterFocus: boolean;
scrollToFocusedOptionOnUpdate: boolean;
userIsDragging: boolean | null;
// Refs
// ------------------------------
controlRef: ElRef;
getControlRef: (ref: HTMLElement) => void;
focusedOptionRef: ElRef;
getFocusedOptionRef: (ref: HTMLElement) => void;
menuListRef: ElRef;
getMenuListRef: (ref: HTMLElement) => void;
inputRef: ElRef;
getInputRef: (ref: HTMLElement) => void;
// Lifecycle
// ------------------------------
cacheComponents: (components: SelectComponents<OptionType>) => void;
// ==============================
// Consumer Handlers
// ==============================
onMenuOpen(): void;
onMenuClose(): void;
onInputChange(newValue: string, actionMeta: InputActionMeta): void;
// ==============================
// Methods
// ==============================
focusInput(): void;
blurInput(): void;
// aliased for consumers
focus(): void;
blur(): void;
openMenu(focusOption: 'first' | 'last'): void;
focusValue(direction: 'previous' | 'next'): void;
focusOption(direction: FocusDirection): void;
setValue: (
newValue: ValueType<OptionType>,
action: ActionTypes,
option?: OptionType
) => void;
selectOption: (newValue: OptionType) => void;
removeValue: (removedValue: OptionType) => void;
clearValue: () => void;
popValue: () => void;
// ==============================
// Getters
// ==============================
getCommonProps(): {
cx: any;
clearValue: () => void;
getStyles: (key: string, props: {}) => {};
getValue: () => OptionType[];
hasValue: boolean;
isMulti: boolean;
isRtl: boolean;
options: OptionsType<any>;
selectOption: (newValue: OptionType) => void;
setValue: (newValue: ValueType<OptionType>, action: ActionTypes, option?: OptionType) => void;
selectProps: Readonly<{
children?: Node;
}> & Readonly<Props<OptionType>>;
};
getNextFocusedValue(nextSelectValue: OptionsType<OptionType>): OptionType;
getNextFocusedOption(options: OptionsType<OptionType>): OptionType;
getOptionLabel: (data: OptionType) => string;
getOptionValue: (data: OptionType) => string;
getStyles: (key: string, props: {}) => {};
getElementId: (element: 'group' | 'input' | 'listbox' | 'option') => string;
getActiveDescendentId: () => any;
// ==============================
// Helpers
// ==============================
announceAriaLiveSelection: (props: {
event: string,
context: ValueEventContext,
}) => void;
announceAriaLiveContext: (props: {
event: string,
context?: InstructionsContext,
}) => void;
hasValue(): boolean;
hasOptions(): boolean;
countOptions(): number;
isClearable(): boolean;
isOptionDisabled(option: OptionType, selectValue: OptionsType<OptionType>): boolean;
isOptionSelected(option: OptionType, selectValue: OptionsType<OptionType>): boolean;
filterOption(option: {}, inputValue: string): boolean;
formatOptionLabel(data: OptionType, context: FormatOptionLabelContext): Node;
formatGroupLabel(data: GroupType<OptionType>): Node;
// ==============================
// Mouse Handlers
// ==============================
onMenuMouseDown: (event: React.MouseEvent<HTMLElement>) => void;
onMenuMouseMove: (event: React.MouseEvent<HTMLElement>) => void;
onControlMouseDown: (event: MouseOrTouchEvent) => void;
onDropdownIndicatorMouseDown: (event: MouseOrTouchEvent) => void;
onClearIndicatorMouseDown: (event: MouseOrTouchEvent) => void;
onScroll: (event: Event) => void;
// ==============================
// Composition Handlers
// ==============================
startListeningComposition(): void;
stopListeningComposition(): void;
onCompositionStart: () => void;
onCompositionEnd: () => void;
// ==============================
// Touch Handlers
// ==============================
startListeningToTouch(): void;
stopListeningToTouch(): void;
onTouchStart: (event: TouchEvent) => void;
onTouchMove: (event: TouchEvent) => void;
onTouchEnd: (event: TouchEvent) => void;
onControlTouchEnd: (event: React.TouchEvent<HTMLElement>) => void;
onClearIndicatorTouchEnd: (event: React.TouchEvent<HTMLElement>) => void;
onDropdownIndicatorTouchEnd: (event: React.TouchEvent<HTMLElement>) => void;
// ==============================
// Focus Handlers
// ==============================
handleInputChange: (event: React.KeyboardEvent<HTMLInputElement>) => void;
onInputFocus: (event: React.FocusEvent<HTMLInputElement>) => void;
onInputBlur: (event: React.FocusEvent<HTMLInputElement>) => void;
onOptionHover: (focusedOption: OptionType) => void;
shouldHideSelectedOptions: () => boolean;
// ==============================
// Keyboard Handlers
// ==============================
onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;
// ==============================
// Menu Options
// ==============================
buildMenuOptions(props: Props<OptionType>, selectValue: OptionsType<OptionType>): MenuOptions<OptionType>;
// ==============================
// Renderers
// ==============================
constructAriaLiveMessage(): string;
renderInput(): Node;
renderPlaceholderOrValue(): PlaceholderOrValue<OptionType> | null;
renderClearIndicator(): Node;
renderLoadingIndicator(): Node;
renderIndicatorSeparator(): Node;
renderDropdownIndicator(): Node;
renderMenu(): Node;
renderFormField(): Node;
renderLiveRegion(): Node;
}

View File

@@ -0,0 +1,10 @@
export interface InstructionsContext { isSearchable?: boolean; isMulti?: boolean; label?: string; }
export interface ValueEventContext { value: string; }
export function instructionsAriaMessage(event: any, context?: InstructionsContext): string;
export function valueEventAriaMessage(event: any, context: ValueEventContext): string;
export function valueFocusAriaMessage({ focusedValue, getOptionLabel, selectValue }: any): string;
export function optionFocusAriaMessage({ focusedOption, getOptionLabel, options }: any): string;
export function resultsAriaMessage({ inputValue, screenReaderMessage }: any): string;

View File

@@ -0,0 +1,10 @@
import * as React from 'react';
import { InputProps } from '../components/Input';
import { BaseTransition } from './transitions';
import { PropsWithInnerRef } from '../types';
export type AnimatedInputProps = BaseTransition & PropsWithInnerRef & InputProps;
export function AnimatedInput(WrappedComponent: React.ComponentType<InputProps>): React.ComponentType<AnimatedInputProps>;
export default AnimatedInput;

View File

@@ -0,0 +1,12 @@
import { ComponentType } from 'react';
import { MultiValueProps } from '../components/MultiValue';
import { Collapse, fn } from './transitions';
export type AnimatedMultiValueProps<OptionType> = {
in: boolean,
onExited: fn,
} & MultiValueProps<OptionType>;
export function AnimatedMultiValue<OptionType>(WrappedComponent: ComponentType<MultiValueProps<OptionType>>): ComponentType<AnimatedMultiValueProps<OptionType>>;
export default AnimatedMultiValue;

View File

@@ -0,0 +1,9 @@
import { ComponentType } from 'react';
import { PlaceholderProps } from '../components/Placeholder';
import { Fade, collapseDuration } from './transitions';
export type AnimatedPlaceholderProps<OptionType> = PlaceholderProps<OptionType>;
export function AnimatedPlaceholder<OptionType>(WrappedComponent: ComponentType<PlaceholderProps<OptionType>>): ComponentType<AnimatedPlaceholderProps<OptionType>>;
export default AnimatedPlaceholder;

View File

@@ -0,0 +1,9 @@
import { ComponentType } from 'react';
import { SingleValueProps } from '../components/SingleValue';
import { Fade } from './transitions';
export type AnimatedSingleValueProps<OptionType> = SingleValueProps<OptionType>;
export function AnimatedSingleValue<OptionType>(WrappedComponent: ComponentType<SingleValueProps<OptionType>>): ComponentType<AnimatedSingleValueProps<OptionType>>;
export default AnimatedSingleValue;

View File

@@ -0,0 +1,9 @@
import { ComponentType } from 'react';
import { TransitionGroup } from 'react-transition-group';
import { ValueContainerProps } from '../components/containers';
export type AnimatedValueContainerProps<OptionType> = ValueContainerProps<OptionType>;
export function AnimatedValueContainer<OptionType>(WrappedComponent: ComponentType<ValueContainerProps<OptionType>>): ComponentType<AnimatedValueContainerProps<OptionType>>;
export default AnimatedValueContainer;

View File

@@ -0,0 +1,17 @@
import { ComponentType } from 'react';
import { SelectComponents, defaultComponents } from '../components/index';
import { default as AnimatedInput, AnimatedInputProps } from './Input';
import { default as AnimatedMultiValue, AnimatedMultiValueProps } from './MultiValue';
import { default as AnimatedPlaceholder, AnimatedPlaceholderProps } from './Placeholder';
import { default as AnimatedSingleValue, AnimatedSingleValueProps } from './SingleValue';
import { default as AnimatedValueContainer, AnimatedValueContainerProps } from './ValueContainer';
export function makeAnimated<OptionType>(externalComponents?: SelectComponents<OptionType>): SelectComponents<OptionType>;
export const Input: ComponentType<AnimatedInputProps>;
export const MultiValue: ComponentType<AnimatedMultiValueProps<any>>;
export const Placeholder: ComponentType<AnimatedPlaceholderProps<any>>;
export const SingleValue: ComponentType<AnimatedSingleValueProps<any>>;
export const ValueContainer: ComponentType<AnimatedValueContainerProps<any>>;
export default makeAnimated;

View File

@@ -0,0 +1,50 @@
import * as React from 'react';
import { Transition } from 'react-transition-group';
export type fn = () => void;
export interface BaseTransition {
/** Whether we are in a transition. */
in: boolean;
/** Function to be called once transition finishes. */
onExited: fn;
}
// ==============================
// Fade Transition
// ==============================
export type FadeProps = BaseTransition & {
component: React.ComponentType<any>,
duration: number,
};
export const Fade: React.ComponentType<FadeProps>;
// ==============================
// Collapse Transition
// ==============================
export const collapseDuration: number;
export type TransitionState = 'exiting' | 'exited';
export type Width = number | 'auto';
export interface CollapseProps { children: any; in: boolean; }
export interface CollapseState { width: Width; }
// wrap each MultiValue with a collapse transition; decreases width until
// finally removing from DOM
export class Collapse extends React.Component<CollapseProps, CollapseState> {
duration: number;
transition: {
exiting: any,
exited: any,
};
// width must be calculated; cannot transition from `undefined` to `number`
getWidth: (ref: React.Ref<any>) => void;
// get base styles
getStyle: (width: Width) => any;
// get transition styles
getTransition: (state: TransitionState) => any;
}

10
types/react-select/lib/builtins.d.ts vendored Normal file
View File

@@ -0,0 +1,10 @@
import { ReactNode as Node } from 'react';
import { GroupType } from './types';
export function formatGroupLabel(group: GroupType<any>): Node;
export function getOptionLabel(option: any): string;
export function getOptionValue(option: any): string;
export function isOptionDisabled(option: any): boolean;

View File

@@ -0,0 +1,29 @@
import { ComponentType, ReactNode as Node, Ref as ElementRef } from 'react';
import { borderRadius, colors, spacing } from '../theme';
import { CommonProps, PropsWithStyles } from '../types';
interface State {
/** Whether the select is disabled. */
isDisabled: boolean;
/** Whether the select is focused. */
isFocused: boolean;
}
export type ControlProps<OptionType> = CommonProps<OptionType> &
PropsWithStyles &
State & {
/** Children to render. */
children: Node,
innerRef: ElementRef<any>,
/** The mouse down event and the innerRef to pass down to the controller element. */
innerProps: {
onMouseDown: (event: React.MouseEvent<HTMLElement>) => void,
},
};
export function css(state: State): any; // TODO css type
declare const Control: ComponentType<ControlProps<any>>;
export default Control;

View File

@@ -0,0 +1,24 @@
import { ReactNode as Node, ComponentType } from 'react';
import { spacing } from '../theme';
import { CommonProps } from '../types';
interface ComponentProps {
/** The children to be rendered. */
children: Node;
/** Component to wrap the label, recieves headingProps. */
Heading: ComponentType<any>;
/** Label to be displayed in the heading component. */
label: Node;
}
export type GroupProps<OptionType> = CommonProps<OptionType> & ComponentProps;
export function groupCSS(): any; // TODO css type
export const Group: ComponentType<GroupProps<any>>;
export function groupHeadingCSS(): any; // TODO css type
export const GroupHeading: ComponentType<any>;
export default Group;

View File

@@ -0,0 +1,23 @@
import { ComponentType, Ref as ElementRef } from 'react';
import { colors, spacing } from '../theme';
import { PropsWithStyles, ClassNamesState } from '../types';
export type InputProps = PropsWithStyles & {
cx: (a: string | null, b: ClassNamesState, c: string) => string | void,
/** Reference to the internal element */
innerRef: (element: ElementRef<any>) => void,
/** Set whether the input should be visible. Does not affect input size. */
isHidden: boolean,
/** Whether the input is disabled */
isDisabled?: boolean,
className?: string,
};
export function inputCSS(props: InputProps): any; // TODO css type;
export function inputStyle(isHidden: boolean): any; // TODO css type
export const Input: ComponentType<InputProps>;
export default Input;

View File

@@ -0,0 +1,158 @@
import {
Component,
ReactElement,
Ref as ElementRef,
ReactNode as Node,
ComponentType
} from 'react';
import { createPortal } from 'react-dom';
import {
animatedScrollTo,
getBoundingClientObj,
RectType,
getScrollParent,
getScrollTop,
scrollTo,
} from '../utils';
import { borderRadius, colors, spacing } from '../theme';
import {
InnerRef,
MenuPlacement,
MenuPosition,
CommonProps,
} from '../types';
// ==============================
// Menu
// ==============================
// Get Menu Placement
// ------------------------------
interface MenuState { placement: 'bottom' | 'top' | null; maxHeight: number; }
interface PlacementArgs {
maxHeight: number;
menuEl: ElementRef<any>;
minHeight: number;
placement: 'bottom' | 'top' | 'auto';
shouldScroll: boolean;
isFixedPosition: boolean;
}
export function getMenuPlacement(args: PlacementArgs): MenuState;
// Menu Component
// ------------------------------
export type MenuProps<OptionType> = CommonProps<OptionType> & {
/** The children to be rendered. */
children: ReactElement<any>,
/** Callback to update the portal after possible flip. */
getPortalPlacement: (state: MenuState) => void,
/** Props to be passed to the menu wrapper. */
innerProps: object,
/** Set the maximum height of the menu. */
maxMenuHeight: number,
/** Set whether the menu should be at the top, at the bottom. The auto options sets it to bottom. */
menuPlacement: MenuPlacement,
/* The CSS position value of the menu, when "fixed" extra layout management is required */
menuPosition: MenuPosition,
/** Set the minimum height of the menu. */
minMenuHeight: number,
/** Set whether the page should scroll to show the menu. */
menuShouldScrollIntoView: boolean,
};
export function menuCSS(state: MenuState): any; // TODO css type
export class Menu<OptionType> extends Component<MenuProps<OptionType>, MenuState> {
static contextTypes: {
getPortalPlacement: (state: MenuState) => void,
};
getPlacement: (ref: ElementRef<any>) => void;
getState: () => MenuProps<OptionType> & MenuState;
}
export default Menu;
// ==============================
// Menu List
// ==============================
interface MenuListState {
/** Set classname for isMulti */
isMulti: boolean;
/* Set the max height of the Menu component */
maxHeight: number;
}
export interface MenuListProps {
/** The children to be rendered. */
children: Node;
/** Inner ref to DOM Node */
innerRef: InnerRef;
}
export type MenuListComponentProps<OptionType> = CommonProps<OptionType> &
MenuListProps &
MenuListState;
export function menuListCSS(state: MenuState): any; // TODO css type
export const MenuList: ComponentType<MenuListComponentProps<any>>;
// ==============================
// Menu Notices
// ==============================
export function noOptionsMessageCSS(): any; // TODO css type
export function loadingMessageCSS(): any; // TODO css type
export type NoticeProps<OptionType> = CommonProps<OptionType> & {
/** The children to be rendered. */
children: Node,
/** Props to be passed on to the wrapper. */
innerProps: { [key: string]: any },
};
export const NoOptionsMessage: ComponentType<NoticeProps<any>>;
// NoOptionsMessage.defaultProps = {
// children: 'No options',
// };
export const LoadingMessage: ComponentType<NoticeProps<any>>;
// LoadingMessage.defaultProps = {
// children: 'Loading...',
// };
// ==============================
// Menu Portal
// ==============================
export type MenuPortalProps<OptionType> = CommonProps<OptionType> & {
appendTo: HTMLElement,
children: Node, // ideally Menu<MenuProps>
controlElement: HTMLElement,
menuPlacement: MenuPlacement,
menuPosition: MenuPosition,
};
interface MenuPortalState {
placement: 'bottom' | 'top' | null;
}
interface PortalStyleArgs {
offset: number;
position: MenuPosition;
rect: RectType;
}
export function menuPortalCSS(args: PortalStyleArgs): any; // TODO css type
export class MenuPortal<OptionType> extends Component<MenuPortalProps<OptionType>, MenuPortalState> {
static childContextTypes: {
getPortalPlacement: (state: MenuState) => void,
};
getChildContext(): {
getPortalPlacement: (state: MenuState) => void;
};
// callback for occassions where the menu must "flip"
getPortalPlacement: (state: MenuState) => void;
}

View File

@@ -0,0 +1,57 @@
import { ComponentType, Component, ReactNode as Node } from 'react';
import { borderRadius, colors, spacing } from '../theme';
import { CommonProps } from '../types';
export type MultiValueProps<OptionType> = CommonProps<OptionType> &{
children: Node,
components: any,
cropWithEllipsis: boolean,
data: OptionType,
innerProps: any,
isFocused: boolean,
isDisabled: boolean,
removeProps: {
onTouchEnd: (event: any) => void,
onClick: (event: any) => void,
onMouseDown: (event: any) => void,
},
};
export function multiValueCSS(): any; // TODO css type
export function multiValueLabelCSS(props: MultiValueProps<any>): any; // TODO css type
export function multiValueRemoveCSS(props: MultiValueProps<any>): any; // TODO css type
export interface MultiValueGenericProps<OptionType> {
children: Node;
data: OptionType;
innerProps: { className?: string };
selectProps: any;
}
export const MultiValueGeneric: ComponentType<MultiValueGenericProps<any>>;
export const MultiValueContainer: typeof MultiValueGeneric;
export const MultiValueLabel: typeof MultiValueGeneric;
export type MultiValueRemoveProps<OptionType> = CommonProps<OptionType> & {
children: Node,
innerProps: {
className: string,
onTouchEnd: (event: any) => void,
onClick: (event: any) => void,
onMouseDown: (event: any) => void,
},
selectProps: any,
};
export class MultiValueRemove<OptionType> extends Component<MultiValueRemoveProps<OptionType>> {
static defaultProps: {
children: Node,
};
}
export class MultiValue<OptionType> extends Component<MultiValueProps<OptionType>> {
static defaultProps: {
cropWithEllipsis: boolean,
};
}
export default MultiValue;

View File

@@ -0,0 +1,41 @@
import { ComponentType, ReactNode as Node, MouseEventHandler } from 'react';
import { colors, spacing } from '../theme';
import { CommonProps, PropsWithStyles, InnerRef } from '../types';
interface State {
/** Wether the option is disabled. */
isDisabled: boolean;
/** Wether the option is focused. */
isFocused: boolean;
/** Whether the option is selected. */
isSelected: boolean;
}
interface InnerProps {
id: string;
key: string;
onClick: MouseEventHandler;
onMouseOver: MouseEventHandler;
tabIndex: number;
}
export type OptionProps<OptionType> = PropsWithStyles &
CommonProps<OptionType> &
State & {
/** The children to be rendered. */
children: Node,
/** Inner ref to DOM Node */
innerRef: InnerRef,
/** props passed to the wrapping element for the group. */
innerProps: InnerProps,
/* Text to be displayed representing the option. */
label: string,
/* Type is used by the menu to determine whether this is an option or a group.
In the case of option this is always `option`. */
type: 'option',
};
export function optionCSS(state: State): any; // TODO css type
export const Option: ComponentType<OptionProps<any>>;
export default Option;

View File

@@ -0,0 +1,17 @@
import { ComponentType, ReactNode as Node } from 'react';
import { colors, spacing } from '../theme';
import { CommonProps } from '../types';
export type PlaceholderProps<OptionType> = CommonProps<OptionType> & {
/** The children to be rendered. */
children: Node,
/** props passed to the wrapping element for the group. */
innerProps: { [key: string]: any },
};
export function placeholderCSS(): any; // TODO css type
export const Placeholder: ComponentType<PlaceholderProps<any>>;
export default Placeholder;

View File

@@ -0,0 +1,23 @@
import { ComponentType } from 'react';
import { colors, spacing } from '../theme';
import { CommonProps } from '../types';
interface State {
/** Whether this is disabled */
isDisabled: boolean;
}
interface ValueProps<OptionType> {
/** The children to be rendered. */
children: string;
/* The data of the selected option rendered in the Single Value componentn */
data: OptionType;
/** Props passed to the wrapping element for the group. */
innerProps: any;
}
export type SingleValueProps<OptionType> = CommonProps<OptionType> & ValueProps<OptionType> & State;
export function css(props: SingleValueProps<any>): any; // TODO css type
export const SingleValue: ComponentType<SingleValueProps<any>>;
export default SingleValue;

View File

@@ -0,0 +1,57 @@
import { Component, ReactNode as Node, ComponentType } from 'react';
import { spacing } from '../theme';
import { CommonProps, KeyboardEventHandler } from '../types';
// ==============================
// Root Container
// ==============================
export interface ContainerState {
/** Whether the select is disabled. */
isDisabled: boolean;
/** Whether the text in the select is indented from right to left. */
isRtl: boolean;
}
export type ContainerProps<OptionType> = CommonProps<OptionType> &
ContainerState & {
/** The children to be rendered. */
children: Node,
/** Inner props to be passed down to the container. */
innerProps: { onKeyDown: KeyboardEventHandler },
};
export function containerCSS(state: ContainerState): any; // TODO css type;
export const SelectContainer: ComponentType<ContainerProps<any>>;
// ==============================
// Value Container
// ==============================
export type ValueContainerProps<OptionType> = CommonProps<OptionType> & {
/** Set when the value container should hold multiple values */
isMulti: boolean,
/** Whether the value container currently holds a value. */
hasValue: boolean,
/** The children to be rendered. */
children: Node,
};
export function valueContainerCSS(): any; // TODO css type;
export class ValueContainer extends Component<ValueContainerProps<any>> {}
// ==============================
// Indicator Container
// ==============================
export interface IndicatorsState {
/** Whether the text should be rendered right to left. */
isRtl: boolean;
}
export type IndicatorContainerProps<OptionType> = CommonProps<OptionType> &
IndicatorsState & {
/** The children to be rendered. */
children: Node,
};
export function indicatorsContainerCSS(): any; // TODO css type;
export const IndicatorsContainer: ComponentType<IndicatorContainerProps<any>>;

View File

@@ -0,0 +1,142 @@
import {
ComponentType,
ReactElement as Element,
} from 'react';
import {
IndicatorContainerProps,
ContainerProps,
ValueContainerProps,
IndicatorsContainer,
SelectContainer,
ValueContainer,
} from './containers';
import {
IndicatorProps,
LoadingIconProps,
ClearIndicator,
DropdownIndicator,
LoadingIndicator,
IndicatorSeparator,
DownChevron,
CrossIcon,
} from './indicators';
import Control, { ControlProps } from './Control';
import Group, { GroupProps, GroupHeading } from './Group';
import Input, { InputProps } from './Input';
import Menu, {
MenuProps,
MenuList,
MenuListComponentProps,
MenuPortal,
MenuPortalProps,
NoticeProps,
NoOptionsMessage,
LoadingMessage,
} from './Menu';
import MultiValue, {
MultiValueProps,
MultiValueContainer,
MultiValueLabel,
MultiValueRemove,
} from './MultiValue';
import Option, { OptionProps } from './Option';
import Placeholder, { PlaceholderProps } from './Placeholder';
import SingleValue, { SingleValueProps } from './SingleValue';
export type PlaceholderOrValue<OptionType> =
| Element<ComponentType<PlaceholderProps<OptionType>>>
| Element<ComponentType<SingleValueProps<OptionType>>>
| Array<Element<ComponentType<MultiValueProps<OptionType>>>>;
export type IndicatorComponentType<OptionType> = ComponentType<IndicatorProps<OptionType>>;
export interface SelectComponents<OptionType> {
ClearIndicator: IndicatorComponentType<OptionType> | null;
Control: ComponentType<ControlProps<OptionType>>;
DropdownIndicator: IndicatorComponentType<OptionType> | null;
DownChevron: ComponentType<any>;
CrossIcon: ComponentType<any>;
Group: ComponentType<GroupProps<OptionType>>;
GroupHeading: ComponentType<any>;
IndicatorsContainer: ComponentType<IndicatorContainerProps<OptionType>>;
IndicatorSeparator: IndicatorComponentType<OptionType> | null;
Input: ComponentType<InputProps>;
LoadingIndicator: ComponentType<LoadingIconProps<OptionType>> | null;
Menu: ComponentType<MenuProps<OptionType>>;
MenuList: ComponentType<MenuListComponentProps<OptionType>>;
MenuPortal: ComponentType<MenuPortalProps<OptionType>>;
LoadingMessage: ComponentType<NoticeProps<OptionType>>;
NoOptionsMessage: ComponentType<NoticeProps<OptionType>>;
MultiValue: ComponentType<MultiValueProps<OptionType>>;
MultiValueContainer: ComponentType<any>;
MultiValueLabel: ComponentType<any>;
MultiValueRemove: ComponentType<any>;
Option: ComponentType<OptionProps<OptionType>>;
Placeholder: ComponentType<PlaceholderProps<OptionType>>;
SelectContainer: ComponentType<ContainerProps<OptionType>>;
SingleValue: ComponentType<SingleValueProps<OptionType>>;
ValueContainer: ComponentType<ValueContainerProps<OptionType>>;
}
export interface SelectComponentsConfig<OptionType> {
ClearIndicator?: IndicatorComponentType<OptionType> | null;
Control?: ComponentType<ControlProps<OptionType>>;
DropdownIndicator?: IndicatorComponentType<OptionType> | null;
DownChevron?: ComponentType<any>;
CrossIcon?: ComponentType<any>;
Group?: ComponentType<GroupProps<OptionType>>;
GroupHeading?: ComponentType<any>;
IndicatorsContainer?: ComponentType<IndicatorContainerProps<OptionType>>;
IndicatorSeparator?: IndicatorComponentType<OptionType> | null;
Input?: ComponentType<InputProps>;
LoadingIndicator?: ComponentType<LoadingIconProps<OptionType>> | null;
Menu?: ComponentType<MenuProps<OptionType>>;
MenuList?: ComponentType<MenuListComponentProps<any>>;
MenuPortal?: ComponentType<MenuPortalProps<any>>;
LoadingMessage?: ComponentType<NoticeProps<any>>;
NoOptionsMessage?: ComponentType<NoticeProps<any>>;
MultiValue?: ComponentType<MultiValueProps<OptionType>>;
MultiValueContainer?: ComponentType<any>;
MultiValueLabel?: ComponentType<any>;
MultiValueRemove?: ComponentType<any>;
Option?: ComponentType<OptionProps<OptionType>>;
Placeholder?: ComponentType<PlaceholderProps<OptionType>>;
SelectContainer?: ComponentType<ContainerProps<OptionType>>;
SingleValue?: ComponentType<SingleValueProps<OptionType>>;
ValueContainer?: ComponentType<ValueContainerProps<OptionType>>;
}
export namespace components {
const ClearIndicator: IndicatorComponentType<any> | null;
const Control: ComponentType<ControlProps<any>>;
const DropdownIndicator: IndicatorComponentType<any> | null;
const DownChevron: ComponentType<any>;
const CrossIcon: ComponentType<any>;
const Group: ComponentType<GroupProps<any>>;
const GroupHeading: ComponentType<any>;
const IndicatorsContainer: ComponentType<IndicatorContainerProps<any>>;
const IndicatorSeparator: IndicatorComponentType<any> | null;
const Input: ComponentType<InputProps>;
const LoadingIndicator: ComponentType<LoadingIconProps<any>> | null;
const Menu: ComponentType<MenuProps<any>>;
const MenuList: ComponentType<MenuListComponentProps<any>>;
const MenuPortal: ComponentType<MenuPortalProps<any>>;
const LoadingMessage: ComponentType<NoticeProps<any>>;
const NoOptionsMessage: ComponentType<NoticeProps<any>>;
const MultiValue: ComponentType<MultiValueProps<any>>;
const MultiValueContainer: ComponentType<any>;
const MultiValueLabel: ComponentType<any>;
const MultiValueRemove: ComponentType<any>;
const Option: ComponentType<OptionProps<any>>;
const Placeholder: ComponentType<PlaceholderProps<any>>;
const SelectContainer: ComponentType<ContainerProps<any>>;
const SingleValue: ComponentType<SingleValueProps<any>>;
const ValueContainer: ComponentType<ValueContainerProps<any>>;
}
export interface Props {
components: SelectComponentsConfig<any>;
}
export function defaultComponents(props: Props): SelectComponentsConfig<any>;

View File

@@ -0,0 +1,67 @@
import { ComponentType, ReactElement as ElementType } from 'react';
import { colors, spacing } from '../theme';
import { CommonProps } from '../types';
// ==============================
// Dropdown & Clear Icons
// ==============================
export function CrossIcon(props: any): any; // TODO svg type
export function DownChevron(props: any): any; // TODO svg type
// ==============================
// Dropdown & Clear Buttons
// ==============================
export type IndicatorProps<OptionType> = CommonProps<OptionType> & {
/** The children to be rendered inside the indicator. */
children: ElementType<any>,
/** Props that will be passed on to the children. */
innerProps: any,
/** The focused state of the select. */
isFocused: boolean,
/** Whether the text is right to left */
isRtl: boolean,
};
export type baseCSS = (props: IndicatorProps<any>) => any; // TODO css type
export const dropdownIndicatorCSS: baseCSS;
export const DropdownIndicator: ComponentType<IndicatorProps<any>>;
export const clearIndicatorCSS: baseCSS;
export const ClearIndicator: ComponentType<IndicatorProps<any>>;
// ==============================
// Separator
// ==============================
export interface SeparatorState { isDisabled: boolean; }
export function indicatorSeparatorCSS(state: SeparatorState): any; // TODO css type
export const IndicatorSeparator: ComponentType<IndicatorProps<any>>;
// ==============================
// Loading
// ==============================
export function loadingIndicatorCSS(state: {
isFocused: boolean,
size: number,
}): any; // TODO css type
export type LoadingIconProps<OptionType> = {
/** Props that will be passed on to the children. */
innerProps: any,
/** The focused state of the select. */
isFocused: boolean,
/** Whether the text is right to left */
isRtl: boolean,
} & CommonProps<OptionType> & {
/** Set size of the container. */
size: number,
};
export const LoadingIndicator: ComponentType<LoadingIconProps<any>>;
// TODO LoadingIndicator.defaultProps: { size: number };

View File

@@ -0,0 +1 @@
export function stripDiacritics(str: string): string;

16
types/react-select/lib/filters.d.ts vendored Normal file
View File

@@ -0,0 +1,16 @@
export interface Config {
ignoreCase?: boolean;
ignoreAccents?: boolean;
stringify?: (obj: any) => string;
trim?: boolean;
matchFrom?: 'any' | 'start';
}
import { stripDiacritics } from './diacritics';
export interface Option { label: string; value: string; data: any; }
export function createFilter(config: Config | null): (
option: Option,
rawInput: string
) => boolean;

View File

@@ -0,0 +1,36 @@
import { Component, ComponentType, Ref as ElementRef } from 'react';
import { ActionMeta, InputActionMeta, ValueType } from './types';
export interface Props<OptionType> {
defaultInputValue?: string;
defaultMenuIsOpen?: boolean;
defaultValue?: ValueType<OptionType>;
inputValue?: string;
menuIsOpen?: boolean;
value?: ValueType<OptionType>;
}
interface State<OptionType> {
inputValue: string;
menuIsOpen: boolean;
value: ValueType<OptionType>;
}
export class StateManager<OptionType> extends Component<Props<OptionType>, State<OptionType>> {
static defaultProps: Props<any>;
select: ElementRef<any>;
focus(): void;
blur(): void;
getProp(key: string): any;
callProp(name: string, ...args: any[]): any;
onChange: (value: any, actionMeta: ActionMeta) => void;
onInputChange: (value: any, actionMeta: InputActionMeta) => void;
onMenuOpen: () => void;
onMenuClose: () => void;
}
export function manageState(SelectComponent: ComponentType<any>): StateManager<any>;
export default manageState;

99
types/react-select/lib/styles.d.ts vendored Normal file
View File

@@ -0,0 +1,99 @@
import {
containerCSS,
indicatorsContainerCSS,
valueContainerCSS,
} from './components/containers';
import { css as controlCSS } from './components/Control';
import { groupCSS, groupHeadingCSS } from './components/Group';
import {
clearIndicatorCSS,
dropdownIndicatorCSS,
loadingIndicatorCSS,
indicatorSeparatorCSS,
} from './components/indicators';
import { inputCSS } from './components/Input';
import { placeholderCSS } from './components/Placeholder';
import { optionCSS } from './components/Option';
import {
menuCSS,
menuListCSS,
menuPortalCSS,
noOptionsMessageCSS,
loadingMessageCSS,
} from './components/Menu';
import { css as singleValueCSS } from './components/SingleValue';
import {
multiValueCSS,
multiValueLabelCSS,
multiValueRemoveCSS,
} from './components/MultiValue';
export interface Props { [key: string]: any; }
/**
* @param base -- the component's default style
* @param state -- the component's current state e.g. `isFocused`
* @returns
*/
export type styleFn = (base: any, state: any) => any;
export interface Styles {
clearIndicator?: styleFn;
container?: styleFn;
control?: styleFn;
dropdownIndicator?: styleFn;
group?: styleFn;
groupHeading?: styleFn;
indicatorsContainer?: styleFn;
indicatorSeparator?: styleFn;
input?: styleFn;
loadingIndicator?: styleFn;
// TODO loadingMessageCSS?: styleFn;
loadingMessage?: styleFn;
menu?: styleFn;
menuList?: styleFn;
menuPortal?: styleFn;
multiValue?: styleFn;
multiValueLabel?: styleFn;
multiValueRemove?: styleFn;
// TODO noOptionsMessageCSS?: styleFn;
noOptionsMessage?: styleFn;
option?: styleFn;
placeholder?: styleFn;
singleValue?: styleFn;
valueContainer: styleFn;
}
export interface StylesConfig {
clearIndicator?: styleFn;
container?: styleFn;
control?: styleFn;
dropdownIndicator?: styleFn;
group?: styleFn;
groupHeading?: styleFn;
indicatorsContainer?: styleFn;
indicatorSeparator?: styleFn;
input?: styleFn;
loadingIndicator?: styleFn;
// TODO loadingMessageCSS?: styleFn;
loadingMessage?: styleFn;
menu?: styleFn;
menuList?: styleFn;
menuPortal?: styleFn;
multiValue?: styleFn;
multiValueLabel?: styleFn;
multiValueRemove?: styleFn;
// TODO noOptionsMessageCSS?: styleFn;
noOptionsMessage?: styleFn;
option?: styleFn;
placeholder?: styleFn;
singleValue?: styleFn;
valueContainer?: styleFn;
}
export type GetStyles = (a: string, b: Props) => any;
export const defaultStyles: Styles;
// Merge Utility
// Allows consumers to extend a base Select with additional styles
export function mergeStyles(source: any, target: any): any;

53
types/react-select/lib/theme.d.ts vendored Normal file
View File

@@ -0,0 +1,53 @@
export const borderRadius: number;
export const colors: {
text: string;
textLight: string;
primary: string;
primary75: string;
primary50: string;
primary25: string;
danger: string;
dangerLight: string;
neutral0: string;
neutral1: string;
neutral2: string;
neutral3: string;
neutral4: string;
neutral5: string;
neutral10: string;
neutral20: string;
neutral30: string;
neutral40: string;
neutral50: string;
neutral60: string;
neutral70: string;
neutral80: string;
neutral90: string;
neutral100: string;
neutral1a: string;
neutral2a: string;
neutral3a: string;
neutral4a: string;
neutral5a: string;
neutral10a: string;
neutral20a: string;
neutral30a: string;
neutral40a: string;
neutral50a: string;
neutral60a: string;
neutral70a: string;
neutral80a: string;
neutral90a: string;
};
export const spacing: {
/* Used to calculate consistent margin/padding on elements */
baseUnit: number,
/* The minimum height of the control */
controlHeight: number,
/* The amount of space between the control and menu */
menuGutter: number,
};

100
types/react-select/lib/types.d.ts vendored Normal file
View File

@@ -0,0 +1,100 @@
import * as React from 'react';
export type OptionsType<OptionType> = OptionType[];
export interface GroupType<OptionType> {
options: OptionsType<OptionType>;
[key: string]: any;
}
export type GroupedOptionsType<UnionOptionType> = Array<GroupType<UnionOptionType>>;
export type ValueType<OptionType> = OptionType | OptionsType<OptionType> | null | undefined;
export type FocusEventHandler = (event: React.FocusEvent<HTMLElement>) => void;
export type MouseEventHandler = (event: React.MouseEvent<HTMLElement>) => void;
export type KeyboardEventHandler = (event: React.KeyboardEvent<HTMLElement>) => void;
export type InnerRef = React.Ref<any>;
export interface PropsWithInnerRef {
/** The inner reference. */
innerRef: React.Ref<any>;
}
export interface PropsWithStyles {
/*
Get the styles of a particular part of the select. Pass in the name of the
property as the first argument, and the current props as the second argument.
See the `styles` object for the properties available.
*/
getStyles: (name: string, props: any) => {};
}
export type ClassNameList = string[];
export type ClassNamesState = { [key: string]: boolean } | undefined;
export interface CommonProps<OptionType> {
clearValue: () => void;
className?: string;
cx: (a: string | null, b: ClassNamesState | undefined, c: string | undefined) => string | void;
/*
Get the styles of a particular part of the select. Pass in the name of the
property as the first argument, and the current props as the second argument.
See the `styles` object for the properties available.
*/
getStyles: (name: string, props: any) => {};
getValue: () => ValueType<OptionType>;
hasValue: boolean;
isMulti: boolean;
options: OptionsType<OptionType>;
selectOption: (option: OptionType) => void;
selectProps: any;
setValue: (value: ValueType<OptionType>, action: ActionTypes) => void;
}
export type ActionTypes =
| 'select-option'
| 'deselect-option'
| 'remove-value'
| 'pop-value'
| 'set-value'
| 'clear'
| 'create-option';
export interface ActionMeta {
action: ActionTypes;
}
export type InputActionTypes =
| 'set-value'
| 'input-change'
| 'input-blur'
| 'menu-close';
export interface InputActionMeta {
action: InputActionTypes;
}
export type MenuPlacement = 'auto' | 'bottom' | 'top';
export type MenuPosition = 'absolute' | 'fixed';
export type FocusDirection =
| 'up'
| 'down'
| 'pageup'
| 'pagedown'
| 'first'
| 'last';
export type OptionProps = PropsWithInnerRef & {
data: any,
id: number,
index: number,
isDisabled: boolean,
isFocused: boolean,
isSelected: boolean,
label: string,
onClick: MouseEventHandler,
onMouseOver: MouseEventHandler,
value: any,
};

121
types/react-select/lib/utils.d.ts vendored Normal file
View File

@@ -0,0 +1,121 @@
import * as React from 'react';
import {
ClassNamesState,
InputActionMeta,
OptionsType,
ValueType,
} from './types';
// ==============================
// NO OP
// ==============================
export function noop(): void;
export function emptyString(): string;
// ==============================
// Class Name Prefixer
// ==============================
export function classNames(
prefix?: string | null,
cssKey?: string | null,
state?: ClassNamesState,
className?: string,
): string;
// ==============================
// Clean Value
// ==============================
export function cleanValue<OptionType>(value: ValueType<OptionType>): OptionsType<OptionType>;
// ==============================
// Handle Input Change
// ==============================
export function handleInputChange(
inputValue: string,
actionMeta: InputActionMeta,
onInputChange?: (inputValue: string, actionMeta: InputActionMeta) => string | void
): string;
// ==============================
// Scroll Helpers
// ==============================
export function isDocumentElement(el: Element): boolean;
// Normalized Scroll Top
// ------------------------------
export function normalizedHeight(el: Element): number;
// Normalized scrollTo & scrollTop
// ------------------------------
export function getScrollTop(el: Element): number;
export function scrollTo(el: Element, top: number): void;
// Get Scroll Parent
// ------------------------------
export function getScrollParent(element: React.Ref<any>): Element;
// Animated Scroll To
// ------------------------------
export function animatedScrollTo(
element: Element,
to: number,
duration: number,
callback: (element: Element) => void
): void;
// Scroll Into View
// ------------------------------
export function scrollIntoView(
menuEl: HTMLElement,
focusedEl: HTMLElement
): void;
// ==============================
// Get bounding client object
// ==============================
// cannot get keys using array notation with DOMRect
export function getBoundingClientObj(element: HTMLElement): {
bottom: number;
height: number;
left: number;
right: number;
top: number;
width: number;
};
export interface RectType {
left: number;
right: number;
bottom: number;
height: number;
width: number;
}
// ==============================
// String to Key (kebabify)
// ==============================
export function toKey(str: string): string;
// ==============================
// Touch Capability Detector
// ==============================
export function isTouchCapable(): boolean;
// ==============================
// Mobile Device Detector
// ==============================
export function isMobileDevice(): boolean;

View File

@@ -0,0 +1,11 @@
export const Tooltip = (props: any) => null;
export const EmojiIcon = (props: any) => null;
export const EditorPanelIcon = (props: any) => null;
export const Spinner = (props: any) => null;
export const Button = (props: any) => null;
export const Modal = (props: any) => null;

View File

@@ -0,0 +1 @@
export function parseDate(a: any): any {}

View File

@@ -0,0 +1,132 @@
import { GroupedOptionsType, GroupType } from "react-select/lib/types";
export interface ColourOption {
value: string;
label: string;
color: string;
disabled?: boolean;
}
export const colourOptions: ColourOption[] = [
{ value: 'ocean', label: 'Ocean', color: '#00B8D9' },
{ value: 'blue', label: 'Blue', color: '#0052CC', disabled: true },
{ value: 'purple', label: 'Purple', color: '#5243AA' },
{ value: 'red', label: 'Red', color: '#FF5630' },
{ value: 'orange', label: 'Orange', color: '#FF8B00' },
{ value: 'yellow', label: 'Yellow', color: '#FFC400' },
{ value: 'green', label: 'Green', color: '#36B37E' },
{ value: 'forest', label: 'Forest', color: '#00875A' },
{ value: 'slate', label: 'Slate', color: '#253858' },
{ value: 'silver', label: 'Silver', color: '#666666' },
];
export interface FlavourOption {
value: string;
label: string;
rating: 'safe' | 'good' | 'wild' | 'crazy';
}
export const flavourOptions: FlavourOption[] = [
{ value: 'vanilla', label: 'Vanilla', rating: 'safe' },
{ value: 'chocolate', label: 'Chocolate', rating: 'good' },
{ value: 'strawberry', label: 'Strawberry', rating: 'wild' },
{ value: 'salted-caramel', label: 'Salted Caramel', rating: 'crazy' },
];
export interface StateOption {
value: string;
label: string;
}
export const stateOptions: StateOption[] = [
{ value: 'AL', label: 'Alabama' },
{ value: 'AK', label: 'Alaska' },
{ value: 'AS', label: 'American Samoa' },
{ value: 'AZ', label: 'Arizona' },
{ value: 'AR', label: 'Arkansas' },
{ value: 'CA', label: 'California' },
{ value: 'CO', label: 'Colorado' },
{ value: 'CT', label: 'Connecticut' },
{ value: 'DE', label: 'Delaware' },
{ value: 'DC', label: 'District Of Columbia' },
{ value: 'FM', label: 'Federated States Of Micronesia' },
{ value: 'FL', label: 'Florida' },
{ value: 'GA', label: 'Georgia' },
{ value: 'GU', label: 'Guam' },
{ value: 'HI', label: 'Hawaii' },
{ value: 'ID', label: 'Idaho' },
{ value: 'IL', label: 'Illinois' },
{ value: 'IN', label: 'Indiana' },
{ value: 'IA', label: 'Iowa' },
{ value: 'KS', label: 'Kansas' },
{ value: 'KY', label: 'Kentucky' },
{ value: 'LA', label: 'Louisiana' },
{ value: 'ME', label: 'Maine' },
{ value: 'MH', label: 'Marshall Islands' },
{ value: 'MD', label: 'Maryland' },
{ value: 'MA', label: 'Massachusetts' },
{ value: 'MI', label: 'Michigan' },
{ value: 'MN', label: 'Minnesota' },
{ value: 'MS', label: 'Mississippi' },
{ value: 'MO', label: 'Missouri' },
{ value: 'MT', label: 'Montana' },
{ value: 'NE', label: 'Nebraska' },
{ value: 'NV', label: 'Nevada' },
{ value: 'NH', label: 'New Hampshire' },
{ value: 'NJ', label: 'New Jersey' },
{ value: 'NM', label: 'New Mexico' },
{ value: 'NY', label: 'New York' },
{ value: 'NC', label: 'North Carolina' },
{ value: 'ND', label: 'North Dakota' },
{ value: 'MP', label: 'Northern Mariana Islands' },
{ value: 'OH', label: 'Ohio' },
{ value: 'OK', label: 'Oklahoma' },
{ value: 'OR', label: 'Oregon' },
{ value: 'PW', label: 'Palau' },
{ value: 'PA', label: 'Pennsylvania' },
{ value: 'PR', label: 'Puerto Rico' },
{ value: 'RI', label: 'Rhode Island' },
{ value: 'SC', label: 'South Carolina' },
{ value: 'SD', label: 'South Dakota' },
{ value: 'TN', label: 'Tennessee' },
{ value: 'TX', label: 'Texas' },
{ value: 'UT', label: 'Utah' },
{ value: 'VT', label: 'Vermont' },
{ value: 'VI', label: 'Virgin Islands' },
{ value: 'VA', label: 'Virginia' },
{ value: 'WA', label: 'Washington' },
{ value: 'WV', label: 'West Virginia' },
{ value: 'WI', label: 'Wisconsin' },
{ value: 'WY', label: 'Wyoming' },
];
export const optionLength = [
{ value: 1, label: 'general' },
{
value: 2,
label:
'Evil is the moment when I lack the strength to be true to the Good that compels me.',
},
{
value: 3,
label:
// tslint:disable-next-line:max-line-length
"It is now an easy matter to spell out the ethic of a truth: 'Do all that you can to persevere in that which exceeds your perseverance. Persevere in the interruption. Seize in your being that which has seized and broken you.",
},
];
// let bigOptions = [];
// for (let i = 0; i < 10000; i++) {
// bigOptions = bigOptions.concat(colourOptions);
// }
const colourGroup: GroupType<ColourOption> = {
label: 'Colours',
options: colourOptions
};
const flavourGroup: GroupType<FlavourOption> = {
label: 'Flavours',
options: flavourOptions,
};
export const groupedOptions: GroupedOptionsType<ColourOption | FlavourOption> = [ colourGroup, flavourGroup ];

View File

@@ -0,0 +1,114 @@
import * as React from 'react';
import Select from 'react-select';
import AsyncSelect from 'react-select/lib/Async';
import CreatableSelect from 'react-select/lib/Creatable';
import { Note } from '../styled-components';
import { ColourOption, colourOptions } from '../data';
const filterColors = (inputValue: string) =>
colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
const promiseOptions = (inputValue: string) =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class AccessingInterals extends React.Component {
selectRef: Select<ColourOption>;
asyncRef: AsyncSelect<ColourOption>;
creatableRef: CreatableSelect<ColourOption>;
focus = () => {
console.log(this.selectRef);
this.selectRef.focus();
}
focusCreatable = () => {
console.log(this.creatableRef);
this.creatableRef.focus();
}
focusAsync = () => {
console.log(this.asyncRef);
this.asyncRef.focus();
}
blurAsync = () => {
this.asyncRef.blur();
}
blurCreatable = () => {
this.creatableRef.blur();
}
blur = () => this.selectRef.blur();
onSelectRef = (ref: any) => {
console.log(ref);
this.selectRef = ref;
}
render() {
return (
<React.Fragment>
<h4>
Creatable Select
</h4>
<CreatableSelect
ref={ (ref: any) => { this.creatableRef = ref; }}
isClearable
options={colourOptions}
/>
<Note Tag="label">
<button
onClick={this.focusCreatable}
id="cypress-single__clearable-checkbox"
>Focus</button>
</Note>
<Note Tag="label">
<button
onClick={this.blurCreatable}
id="cypress-single__clearable-checkbox"
>Blur</button>
</Note>
<h4>
Async Select
</h4>
<AsyncSelect
ref={ (ref: any) => { this.asyncRef = ref; }}
cacheOptions
defaultOptions
loadOptions={promiseOptions}
/>
<Note Tag="label">
<button
onClick={this.focusAsync}
id="cypress-single__clearable-checkbox"
>Focus</button>
</Note>
<Note Tag="label">
<button
onClick={this.blurAsync}
id="cypress-single__clearable-checkbox"
>Blur</button>
</Note>
<h4>Select</h4>
<Select
ref={(ref: any) => { this.selectRef = ref; }}
defaultValue={colourOptions[2]}
name="colors"
options={colourOptions}
/>
<Note Tag="label">
<button
onClick={this.focus}
id="cypress-single__clearable-checkbox"
>Focus</button>
</Note>
<Note Tag="label">
<button
onClick={this.blur}
id="cypress-single__clearable-checkbox"
>Blur</button>
</Note>
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,17 @@
import * as React from 'react';
import Select from 'react-select';
import makeAnimated from 'react-select/lib/animated';
import { ColourOption, colourOptions } from '../data';
export default function AnimatedMulti() {
return (
<Select<ColourOption>
closeMenuOnSelect={false}
components={makeAnimated()}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);
}

View File

@@ -0,0 +1,42 @@
import * as React from 'react';
import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from '../data';
import { OptionsType } from 'react-select/lib/types';
interface State {
inputValue: string;
}
const filterColors = (inputValue: string) =>
colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
const loadOptions = (inputValue: string, callback: (c: OptionsType<any>) => void) => {
setTimeout(() => {
callback(filterColors(inputValue));
}, 1000);
};
export default class WithCallbacks extends React.Component<any, State> {
state = { inputValue: '' };
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
}
render() {
return (
<div>
<pre>inputValue: "{this.state.inputValue}"</pre>
<AsyncSelect
cacheOptions
loadOptions={loadOptions}
defaultOptions
onInputChange={this.handleInputChange}
/>
</div>
);
}
}

View File

@@ -0,0 +1,28 @@
import * as React from 'react';
import AsyncCreatableSelect from 'react-select/lib/AsyncCreatable';
import { colourOptions } from '../data';
const filterColors = (inputValue: string) =>
colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
const promiseOptions = (inputValue: string) =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class WithPromises extends React.Component {
render() {
return (
<AsyncCreatableSelect
cacheOptions
defaultOptions
loadOptions={promiseOptions}
/>
);
}
}

View File

@@ -0,0 +1,39 @@
import * as React from 'react';
import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from '../data';
interface State {
inputValue: string;
}
const filterColors = (inputValue: string) =>
colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
const promiseOptions = (inputValue: string) =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class AsyncMulti extends React.Component<any, State> {
state = { inputValue: '' };
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
}
render() {
return (
<AsyncSelect
isMulti
cacheOptions
defaultOptions
loadOptions={promiseOptions}
/>
);
}
}

View File

@@ -0,0 +1,34 @@
import * as React from 'react';
import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from '../data';
interface State {
inputValue: string;
}
const filterColors = (inputValue: string) =>
colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
const promiseOptions = (inputValue: string) =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class WithPromises extends React.Component<any, State> {
state = { inputValue: '' };
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
}
render() {
return (
<AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} />
);
}
}

View File

@@ -0,0 +1,37 @@
import * as React from 'react';
import Select from 'react-select';
import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data';
const groupStyles = {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
};
const groupBadgeStyles = {
backgroundColor: '#EBECF0',
borderRadius: '2em',
color: '#172B4D',
display: 'inline-block',
fontSize: 12,
fontWeight: 'normal' as 'normal',
lineHeight: '1',
minWidth: 1,
padding: '0.16666666666667em 0.5em',
textAlign: 'center' as 'center',
};
const formatGroupLabel = (data: any) => (
<div style={groupStyles}>
<span>{data.label}</span>
<span style={groupBadgeStyles}>{data.options.length}</span>
</div>
);
export default () => (
<Select<ColourOption | FlavourOption>
defaultValue={colourOptions[1]}
options={groupedOptions}
formatGroupLabel={formatGroupLabel}
/>
);

View File

@@ -0,0 +1,15 @@
import * as React from 'react';
import Select from 'react-select';
import { colourOptions } from '../data';
export default () => (
<Select
defaultValue={[colourOptions[2], colourOptions[3]]}
isMulti
name="colors"
options={colourOptions}
className="basic-multi-select"
classNamePrefix="select"
/>
);

View File

@@ -0,0 +1,101 @@
import * as React from 'react';
import Select from 'react-select';
import { colourOptions } from '../data';
import { Note } from '../styled-components';
const Checkbox = (props: any) => <input type="checkbox" {...props} />;
interface State {
isClearable: boolean;
isDisabled: boolean;
isLoading: boolean;
isRtl: boolean;
isSearchable: boolean;
}
export default class SingleSelect extends React.Component<any, State> {
state = {
isClearable: true,
isDisabled: false,
isLoading: false,
isRtl: false,
isSearchable: true,
};
toggleClearable = () =>
this.setState(state => ({ isClearable: !state.isClearable }))
toggleDisabled = () =>
this.setState(state => ({ isDisabled: !state.isDisabled }))
toggleLoading = () =>
this.setState(state => ({ isLoading: !state.isLoading }))
toggleRtl = () => this.setState(state => ({ isRtl: !state.isRtl }));
toggleSearchable = () =>
this.setState(state => ({ isSearchable: !state.isSearchable }))
render() {
const {
isClearable,
isSearchable,
isDisabled,
isLoading,
isRtl,
} = this.state;
return (
<React.Fragment>
<Select
className="basic-single"
classNamePrefix="select"
defaultValue={colourOptions[0]}
isDisabled={isDisabled}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
name="color"
options={colourOptions}
/>
<Note Tag="label">
<Checkbox
checked={isClearable}
onChange={this.toggleClearable}
id="cypress-single__clearable-checkbox"
/>
Clearable
</Note>
<Note Tag="label" style={{ marginLeft: '1em' }}>
<Checkbox
checked={isSearchable}
onChange={this.toggleSearchable}
id="cypress-single__searchable-checkbox"
/>
Searchable
</Note>
<Note Tag="label" style={{ marginLeft: '1em' }}>
<Checkbox
checked={isDisabled}
onChange={this.toggleDisabled}
id="cypress-single__disabled-checkbox"
/>
Disabled
</Note>
<Note Tag="label" style={{ marginLeft: '1em' }}>
<Checkbox
checked={isLoading}
onChange={this.toggleLoading}
id="cypress-single__loading-checkbox"
/>
Loading
</Note>
<Note Tag="label" style={{ marginLeft: '1em' }}>
<Checkbox
type="checkbox"
checked={isRtl}
onChange={this.toggleRtl}
id="cypress-single__rtl-checkbox"
/>
RTL
</Note>
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,42 @@
import * as React from 'react';
import Select from 'react-select';
import { colourOptions } from '../data';
import { Note } from '../styled-components';
const Checkbox = (props: any) => <input type="checkbox" {...props} />;
interface State {
menuIsOpen: boolean;
}
export default class controlledMenu extends React.Component<any, State> {
state = {
menuIsOpen: false,
};
toggleMenuIsOpen = () =>
this.setState(state => ({ menuIsOpen: !state.menuIsOpen }))
render() {
const { menuIsOpen } = this.state;
return (
<React.Fragment>
<Select
defaultValue={colourOptions[0]}
isClearable
menuIsOpen={menuIsOpen}
styles={{ menu: (base: any) => ({ ...base, position: 'relative' }) }}
name="color"
options={colourOptions}
/>
<Note Tag="label">
<Checkbox
checked={menuIsOpen}
onChange={this.toggleMenuIsOpen}
id="cypress-single__clearable-checkbox"
/>
menuIsOpen
</Note>
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,70 @@
import * as React from 'react';
import CreatableSelect from 'react-select/lib/Creatable';
interface Option {
label: string;
value: string;
}
interface State {
isLoading: boolean;
options: Option[];
value: string | undefined;
}
const createOption = (label: string): Option => ({
label,
value: label.toLowerCase().replace(/\W/g, ''),
});
const defaultOptions = [
createOption('One'),
createOption('Two'),
createOption('Three'),
];
export default class CreatableAdvanced extends React.Component<any, State> {
state = {
isLoading: false,
options: defaultOptions,
value: undefined,
};
handleChange = (newValue: any, actionMeta: any) => {
console.group('Value Changed');
console.log(newValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
this.setState({ value: newValue });
}
handleCreate = (inputValue: string) => {
this.setState({ isLoading: true });
console.group('Option created');
console.log('Wait a moment...');
setTimeout(() => {
const { options } = this.state;
const newOption = createOption(inputValue);
console.log(newOption);
console.groupEnd();
this.setState({
isLoading: false,
options: [...options, newOption],
value: inputValue,
});
}, 1000);
}
render() {
const { isLoading, options, value } = this.state;
return (
<CreatableSelect
isClearable
isDisabled={isLoading}
isLoading={isLoading}
onChange={this.handleChange}
onCreateOption={this.handleCreate}
options={options}
value={value}
/>
);
}
}

View File

@@ -0,0 +1,72 @@
import * as React from 'react';
import CreatableSelect from 'react-select/lib/Creatable';
const components = {
DropdownIndicator: null,
};
interface Option {
label: string;
value: string;
}
const createOption = (label: string): Option => ({
label,
value: label,
});
interface State {
inputValue: string;
value: Option[];
}
export default class CreatableInputOnly extends React.Component<any, State> {
state: State = {
inputValue: '',
value: [],
};
handleChange = (value: any, actionMeta: any) => {
console.group('Value Changed');
console.log(value);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
this.setState({ value });
}
handleInputChange = (inputValue: string) => {
this.setState({ inputValue });
}
handleKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {
const { inputValue, value } = this.state;
if (!inputValue) return;
switch (event.key) {
case 'Enter':
case 'Tab':
console.group('Value Added');
console.log(value);
console.groupEnd();
this.setState({
inputValue: '',
value: [...value, createOption(inputValue)],
});
event.preventDefault();
}
}
render() {
const { inputValue, value } = this.state;
return (
<CreatableSelect
components={components}
inputValue={inputValue}
isClearable
isMulti
menuIsOpen={false}
onChange={this.handleChange}
onInputChange={this.handleInputChange}
onKeyDown={this.handleKeyDown}
placeholder="Type something and press enter..."
value={value}
/>
);
}
}

View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import CreatableSelect from 'react-select/lib/Creatable';
import { colourOptions } from '../data';
export default class CreatableMulti extends React.Component {
handleChange = (newValue: any, actionMeta: any) => {
console.group('Value Changed');
console.log(newValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
}
render() {
return (
<CreatableSelect
isMulti
onChange={this.handleChange}
options={colourOptions}
/>
);
}
}

View File

@@ -0,0 +1,29 @@
import * as React from 'react';
import CreatableSelect from 'react-select/lib/Creatable';
import { colourOptions } from '../data';
export default class CreatableSingle extends React.Component {
handleChange = (newValue: any, actionMeta: any) => {
console.group('Value Changed');
console.log(newValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
}
handleInputChange = (inputValue: any, actionMeta: any) => {
console.group('Input Changed');
console.log(inputValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
}
render() {
return (
<CreatableSelect
isClearable
onChange={this.handleChange}
onInputChange={this.handleInputChange}
options={colourOptions}
/>
);
}
}

View File

@@ -0,0 +1,85 @@
import * as React from 'react';
import Select, { createFilter } from 'react-select';
import { colourOptions } from '../data';
import { Note } from '../styled-components';
const Checkbox = (props: any) => <input type="checkbox" {...props} />;
interface State {
ignoreCase: boolean;
ignoreAccents: boolean;
trim: boolean;
matchFromStart: boolean;
}
export default class SelectCreateFilter extends React.Component<any, State> {
state: State = {
ignoreCase: false,
ignoreAccents: false,
trim: false,
matchFromStart: false,
};
toggleOption = (key: string) => () => {
this.setState((state: any) => ({ ...state, [key]: !state[key] }));
}
render() {
const {
ignoreCase,
ignoreAccents,
trim,
matchFromStart,
} = this.state;
const filterConfig = {
ignoreCase,
ignoreAccents,
trim,
matchFrom: this.state.matchFromStart ? ('start' as 'start') : ('any' as 'any'),
};
return (
<React.Fragment>
<Select
defaultValue={colourOptions[0]}
isClearable
isSearchable
name="color"
options={colourOptions}
filterOption={createFilter(filterConfig)}
/>
<Note Tag="label">
<Checkbox
checked={ignoreCase}
onChange={this.toggleOption('ignoreCase')}
id="cypress-single__clearable-checkbox"
/>
Ignore Case
</Note>
<Note Tag="label">
<Checkbox
checked={ignoreAccents}
onChange={this.toggleOption('ignoreAccents')}
id="cypress-single__clearable-checkbox"
/>
Ignore Accents
</Note>
<Note Tag="label">
<Checkbox
checked={trim}
onChange={this.toggleOption('trim')}
id="cypress-single__clearable-checkbox"
/>
Trim
</Note>
<Note Tag="label">
<Checkbox
checked={matchFromStart}
onChange={this.toggleOption('matchFromStart')}
id="cypress-single__clearable-checkbox"
/>
Match from the start
</Note>
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,35 @@
import * as React from 'react';
import Select from 'react-select';
import { colourOptions } from '../data';
const CustomClearText = () => <span>clear all</span>;
const ClearIndicator = (props: any) => {
const { children = <CustomClearText/>, getStyles, innerProps: { ref, ...restInnerProps } } = props;
return (
<div {...restInnerProps} ref={ref} style={getStyles('clearIndicator', props)}>
<div style={{ padding: '0px 5px' }}>
{children}
</div>
</div>
);
};
const ClearIndicatorStyles = (base: any, state: any) => ({
...base,
cursor: 'pointer',
color: state.isFocused ? 'blue' : 'black',
});
export default function CustomClearIndicator() {
return (
<Select
closeMenuOnSelect={false}
components={{ ClearIndicator }}
styles={{ clearIndicator: ClearIndicatorStyles }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);
}

View File

@@ -0,0 +1,32 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const controlStyles = {
borderRadius: '1px solid black',
padding: '5px',
background: colourOptions[2].color,
color: 'white'
};
const ControlComponent = (props: any) => (
<div style={controlStyles}>
{<p>Custom Control</p>}
<components.Control {...props} />
</div>
);
export default class CustomControl extends React.Component {
render() {
return (
<Select
defaultValue={colourOptions[0]}
isClearable
components={{ Control: ControlComponent }}
isSearchable
name="color"
options={colourOptions}
/>
);
}
}

View File

@@ -0,0 +1,24 @@
import * as React from 'react';
import { EmojiIcon } from '../AtlaskitDummy';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const DropdownIndicator = (props: any) => {
return components.DropdownIndicator && (
<components.DropdownIndicator {...props}>
<EmojiIcon
primaryColor={colourOptions[2].color}
/>
</components.DropdownIndicator>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ DropdownIndicator }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);

View File

@@ -0,0 +1,34 @@
import * as React from 'react';
import Select from 'react-select';
import { colourOptions } from '../data';
interface State {
ignoreCase: boolean;
ignoreAccents: boolean;
trim: boolean;
matchFrom: boolean;
}
const filterOptions = (candidate: any, input: string) => {
if (input) {
return candidate.value === customOptions[0].value;
}
return true;
};
const customOptions = [{ value: 'custom', label: 'Using a custom filter to always display this option on search' }, ...colourOptions];
export default class SelectCreateFilter extends React.Component<any, State> {
render() {
return (
<Select
defaultValue={customOptions[0]}
isClearable
isSearchable
name="color"
options={customOptions}
filterOption={filterOptions}
/>
);
}
}

View File

@@ -0,0 +1,23 @@
import * as React from 'react';
import Select from 'react-select';
import { FlavourOption, flavourOptions } from '../data';
export default class CustomGetOptionLabel extends React.Component {
private readonly getFlavourOptionLabel = (option: FlavourOption): string => `${option.label}: ${option.rating}`;
render() {
return (
<React.Fragment>
<p>Composing a display label from the label property and rating property in the options object</p>
<Select
defaultValue={flavourOptions[0]}
isClearable
isSearchable
name="color"
options={flavourOptions}
getOptionLabel={this.getFlavourOptionLabel}
/>
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,24 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data';
const groupStyles = {
border: `2px dotted ${colourOptions[2].color}`,
borderRadius: '5px',
background: '#f2fcff'
};
const Group = (props: any) => (
<div style={groupStyles}>
<components.Group {...props}/>
</div>
);
export default () => (
<Select<ColourOption | FlavourOption>
defaultValue={colourOptions[1]}
options={groupedOptions}
components={{ Group }}
/>
);

View File

@@ -0,0 +1,31 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data';
import { EditorPanelIcon, Tooltip } from '../AtlaskitDummy';
const groupStyles = {
border: `2px dotted ${colourOptions[2].color}`,
color: 'white',
background: colourOptions[2].color,
padding: '5px 0px',
display: 'flex',
};
const GroupHeading = (props: any) => (
<div style={groupStyles}>
<components.GroupHeading {...props}/>
<Tooltip content="Custom GroupHeading Component">
<EditorPanelIcon/>
</Tooltip>
</div>
);
export default () => (
<Select<ColourOption | FlavourOption>
defaultValue={colourOptions[1]}
options={groupedOptions}
components={{ GroupHeading }}
styles={{ groupHeading: (base: any) => ({ ...base, flex: '1 1', color: 'white', margin: 0 }) }}
/>
);

View File

@@ -0,0 +1,27 @@
import * as React from 'react';
import Select from 'react-select';
import { colourOptions } from '../data';
const indicatorSeparatorStyle = {
alignSelf: 'stretch',
backgroundColor: colourOptions[2].color,
marginBottom: 8,
marginTop: 8,
width: 1,
};
const IndicatorSeparator = ({ innerProps }: any) => {
return (
<span style={indicatorSeparatorStyle} {...innerProps}/>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ IndicatorSeparator }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);

View File

@@ -0,0 +1,21 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const IndicatorsContainer = (props: any) => {
return (
<div style={{ background: colourOptions[2].color }}>
<components.IndicatorsContainer {...props}/>
</div>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ IndicatorsContainer }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);

View File

@@ -0,0 +1,27 @@
import * as React from 'react';
import { Tooltip } from '../AtlaskitDummy';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const Input = (props: any) => {
if (props.isHidden) {
return <components.Input {...props}/>;
}
return (
<div style={{ border: `1px dotted ${colourOptions[2].color}` }}>
<Tooltip content={'Custom Input'}>
<components.Input {...props}/>
</Tooltip>
</div>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ Input }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);

View File

@@ -0,0 +1,21 @@
import * as React from 'react';
import Select from 'react-select';
import { flavourOptions } from '../data';
export default class CustomIsOptionDisabled extends React.Component {
render() {
return (
<React.Fragment>
<p>Disable all options that do not have a 'safe' rating, via the isOptionsDisabled fn prop</p>
<Select
defaultValue={flavourOptions[0]}
isClearable
isSearchable
name="color"
options={flavourOptions}
isOptionDisabled={(option) => option.rating !== 'safe'}
/>
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,47 @@
import * as React from 'react';
import { Spinner, Tooltip } from '../AtlaskitDummy';
import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from '../data';
const LoadingIndicator = (props: any) => {
return (
<Tooltip content={'Custom Loader'}>
<Spinner {...props} delay={0}/>
</Tooltip>
);
};
interface State {
inputValue: string;
}
const filterColors = (inputValue: string) =>
colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
const promiseOptions = (inputValue: string) =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class CustomLoadingIndicator extends React.Component<any, State> {
state = { inputValue: '' };
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
}
render() {
return (
<AsyncSelect
cacheOptions
defaultOptions
loadOptions={promiseOptions}
components={{ LoadingIndicator }}
/>
);
}
}

View File

@@ -0,0 +1,50 @@
import * as React from 'react';
import { Tooltip } from '../AtlaskitDummy';
import AsyncSelect from 'react-select/lib/Async';
import { colourOptions } from '../data';
const LoadingMessage = (props: any) => {
return (
<Tooltip content={'Custom Loading Message'}>
<div {...props} style={props.getStyles('loadingMessage', props)}>
{props.children}
</div>
</Tooltip>
);
};
interface State {
inputValue: string;
}
const filterColors = (inputValue: string) =>
colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
const promiseOptions = (inputValue: string) =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class CustomLoadingIndicator extends React.Component<any, State> {
state = { inputValue: '' };
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
}
render() {
return (
<AsyncSelect
cacheOptions
defaultOptions
loadOptions={promiseOptions}
styles={{ loadingMessage: (base: any) => ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }}
components={{ LoadingMessage }}
/>
);
}
}

View File

@@ -0,0 +1,37 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data';
function getLength(options: any) {
return options.reduce((acc: any, curr: any) => {
if (curr.options) return acc + getLength(curr.options);
return acc + 1;
}, 0);
}
const menuHeaderStyle = {
padding: '8px 12px',
};
const Menu = (props: any) => {
const optionsLength = getLength(props.options);
return (
<React.Fragment>
<div style={menuHeaderStyle}>
Custom Menu with {optionsLength} options
</div>
<components.Menu {...props}>
{props.children}
</components.Menu>
</React.Fragment>
);
};
export default () => (
<Select<ColourOption | FlavourOption>
defaultValue={colourOptions[1]}
options={groupedOptions}
components={{ Menu }}
/>
);

View File

@@ -0,0 +1,29 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data';
const menuHeaderStyle = {
padding: '8px 12px',
background: colourOptions[2].color,
color: 'white',
};
const MenuList = (props: any) => {
return (
<components.MenuList {...props}>
<div style={menuHeaderStyle}>
Custom Menu List
</div>
{props.children}
</components.MenuList>
);
};
export default () => (
<Select<ColourOption | FlavourOption>
defaultValue={colourOptions[1]}
options={groupedOptions}
components={{ MenuList }}
/>
);

View File

@@ -0,0 +1,23 @@
import * as React from 'react';
import { Tooltip } from '../AtlaskitDummy';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const MultiValueContainer = (props: any) => {
return (
<Tooltip content={'Customise your multi-value container!'}>
<components.MultiValueContainer {...props}/>
</Tooltip>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ MultiValueContainer }}
styles={{ multiValue: (base: any) => ({ ...base, border: `2px dotted ${colourOptions[2].color}` }) }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);

View File

@@ -0,0 +1,23 @@
import * as React from 'react';
import { Tooltip } from '../AtlaskitDummy';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const MultiValueLabel = (props: any) => {
return (
<Tooltip content={'Customise your multi-value label component!'}>
<components.MultiValueLabel {...props}/>
</Tooltip>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ MultiValueLabel }}
styles={{ multiValueLabel: (base: any) => ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);

View File

@@ -0,0 +1,25 @@
import * as React from 'react';
import { EmojiIcon, Tooltip } from '../AtlaskitDummy';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const MultiValueRemove = (props: any) => {
return (
<Tooltip content={'Customise your multi-value remove component!'} truncateText>
<components.MultiValueRemove {...props}>
<EmojiIcon primaryColor={colourOptions[2].color}/>
</components.MultiValueRemove>
</Tooltip>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ MultiValueRemove }}
styles={{ multiValueRemove: (base: any) => ({ ...base, border: `1px dotted ${colourOptions[2].color}`, height: '100%' }) }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);

View File

@@ -0,0 +1,31 @@
import * as React from 'react';
import { Tooltip } from '../AtlaskitDummy';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const msgStyles = {
background: colourOptions[2].color,
color: 'white'
};
const NoOptionsMessage = (props: any) => {
return (
<Tooltip content="Custom NoOptionsMessage Component">
<components.NoOptionsMessage {...props} />
</Tooltip>
);
};
export default class CustomNoOptionsMessage extends React.Component {
render() {
return (
<Select
isClearable
components={{ NoOptionsMessage }}
styles={{ noOptionsMessage: (base: any) => ({ ...base, ...msgStyles }) }}
isSearchable
name="color"
options={[]}
/>
);
}
}

View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import { Tooltip } from '../AtlaskitDummy';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const Option = (props: any) => {
return (
<Tooltip content={'Customise your option component!'} truncateText>
<components.Option {...props}/>
</Tooltip>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ Option }}
styles={{ option: (base: any) => ({ ...base, border: `1px dotted ${colourOptions[2].color}`, height: '100%' }) }}
defaultValue={colourOptions[4]}
options={colourOptions}
/>
);

View File

@@ -0,0 +1,19 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const Placeholder = (props: any) => {
return (
<components.Placeholder {...props}/>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ Placeholder }}
placeholder={'custom placeholder component'}
styles={{ placeholder: (base: any) => ({ ...base, fontSize: '1em', color: colourOptions[2].color, fontWeight: 400 }) }}
options={colourOptions}
/>
);

View File

@@ -0,0 +1,24 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { Tooltip } from '../AtlaskitDummy';
import { colourOptions } from '../data';
const SelectContainer = ({ children, ...props }: any) => {
return (
<Tooltip content={'customise your select container'} delay={0}>
<components.SelectContainer {...props}>
{children}
</components.SelectContainer>
</Tooltip>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ SelectContainer }}
styles={{ container: (base: any) => ({ ...base, backgroundColor: colourOptions[2].color, padding: 5 }) }}
options={colourOptions}
/>
);

View File

@@ -0,0 +1,25 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const SingleValue = ({ children, ...props }: any) => (
<components.SingleValue {...props}>
{children}
</components.SingleValue>
);
export default class CustomControl extends React.Component {
render() {
return (
<Select
defaultValue={colourOptions[0]}
isClearable
styles={{ singleValue: (base: any) => ({ ...base, padding: 5, borderRadius: 5, background: colourOptions[2].color, color: 'white', display: 'flex' }) }}
components={{ SingleValue }}
isSearchable
name="color"
options={colourOptions}
/>
);
}
}

View File

@@ -0,0 +1,28 @@
import * as React from 'react';
import Select, { components } from 'react-select';
import { colourOptions } from '../data';
const ValueContainer = ({ children, ...props }: any) => (
<components.ValueContainer {...props}>
{children}
</components.ValueContainer>
);
export default class CustomControl extends React.Component {
render() {
return (
<Select
defaultValue={colourOptions[0]}
isClearable
styles={{
singleValue: (base: any) => ({ ...base, color: 'white' }),
valueContainer: (base: any) => ({ ...base, background: colourOptions[2].color, color: 'white', width: '100%' }),
}}
components={{ ValueContainer }}
isSearchable
name="color"
options={colourOptions}
/>
);
}
}

View File

@@ -0,0 +1,211 @@
import * as React from 'react';
import * as moment from 'moment';
import * as chrono from '../ChronoNodeDummy';
import Select, { components as SelectComponents } from 'react-select';
const createOptionForDate = (d: any) => {
const date = moment.isMoment(d) ? d : moment(d);
return {
date,
value: date.toDate(),
label: date.calendar(undefined, {
sameDay: '[Today] (Do MMM YYYY)',
nextDay: '[Tomorrow] (Do MMM YYYY)',
nextWeek: '[Next] dddd (Do MMM YYYY)',
lastDay: '[Yesterday] (Do MMM YYYY)',
lastWeek: '[Last] dddd (Do MMM YYYY)',
sameElse: 'Do MMMM YYYY',
}),
};
};
const defaultOptions: any = ['today', 'tomorrow', 'yesterday'].map(i =>
createOptionForDate(chrono.parseDate(i))
);
const createCalendarOptions = (date = new Date()) => {
// $FlowFixMe
const daysInMonth = Array.apply(null, {
length: moment(date).daysInMonth(),
}).map((x: any, i: number) => {
const d = moment(date).date(i + 1);
return { ...createOptionForDate(d), display: 'calendar' };
});
return {
label: moment(date).format('MMMM YYYY'),
options: daysInMonth,
};
};
defaultOptions.push(createCalendarOptions());
const suggestions = [
'sunday',
'saturday',
'friday',
'thursday',
'wednesday',
'tuesday',
'monday',
'december',
'november',
'october',
'september',
'august',
'july',
'june',
'may',
'april',
'march',
'february',
'january',
'yesterday',
'tomorrow',
'today',
].reduce((acc: any, str: string) => {
for (let i = 1; i < str.length; i++) {
acc[str.substr(0, i)] = str;
}
return acc;
}, {});
const suggest = (str: string) =>
str
.split(/\b/)
.map(i => suggestions[i] || i)
.join('');
const days = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
const daysHeaderStyles = {
marginTop: '5px',
paddingTop: '5px',
paddingLeft: '2%',
borderTop: '1px solid #eee',
};
const daysHeaderItemStyles = {
color: '#999',
cursor: 'default',
// display: 'block',
fontSize: '75%',
fontWeight: 500,
display: 'inline-block',
width: '12%',
margin: '0 1%',
textAlign: 'center' as 'center',
};
const daysContainerStyles = {
paddingTop: '5px',
paddingLeft: '2%',
};
const Group = (props: any) => {
const { Heading, getStyles, children, label, innerProps, headingProps, cx } = props;
return (
<div aria-label={label} css={getStyles('group', props)} {...innerProps}>
<Heading
getStyles={getStyles}
cx={cx}
{...headingProps}
>
{label}
</Heading>
<div style={daysHeaderStyles}>// TODO css type
{days.map((day, i) => (
<span key={`${i}-${day}`} style={daysHeaderItemStyles}>// TODO css type
{day}
</span>
))}
</div>
<div style={daysContainerStyles}>{children}</div>// TODO css type
</div>
);
};
const getOptionStyles = (defaultStyles: any) => ({
...defaultStyles,
display: 'inline-block',
width: '12%',
margin: '0 1%',
textAlign: 'center',
borderRadius: '4px',
});
const Option = (props: any) => {
const { data, getStyles, innerRef, innerProps } = props;
if (data.display === 'calendar') {
const defaultStyles = getStyles('option', props);
const styles = getOptionStyles(defaultStyles);
if (data.date.date() === 1) {
const indentBy = data.date.day();
if (indentBy) {
styles.marginLeft = `${indentBy * 14 + 1}%`;
}
}
return (
<span {...innerProps} css={styles} ref={innerRef}>
{data.date.format('D')}
</span>
);
} else return <SelectComponents.Option {...props} />;
};
class DatePicker extends React.Component<any> {
state = {
options: defaultOptions,
};
handleInputChange = (value: string) => {
if (!value) {
this.setState({ options: defaultOptions });
return;
}
const date = chrono.parseDate(suggest(value.toLowerCase()));
if (date) {
this.setState({
options: [createOptionForDate(date), createCalendarOptions(date)],
});
} else {
this.setState({
options: [],
});
}
}
render() {
const { value } = this.props;
const { options } = this.state;
return (
<Select
{...this.props}
components={{ Group, Option }}
filterOption={null}
isMulti={false}
isOptionSelected={(o, v) => v.some(i => i.date.isSame(o.date, 'day'))}
maxMenuHeight={380}
onChange={this.props.onChange}
onInputChange={this.handleInputChange}
options={options}
value={value}
/>
);
}
}
export default class Experimental extends React.Component {
state = {
value: defaultOptions[0],
};
handleChange = (value: any) => {
this.setState({ value });
}
render() {
const { value } = this.state;
const displayValue = value && value.value ? value.value.toString() : 'null';
return (
<div>
<pre>Value: {displayValue}</pre>
<DatePicker value={value} onChange={this.handleChange} />
</div>
);
}
}

View File

@@ -0,0 +1,91 @@
import * as React from 'react';
import { Modal, Button } from '../AtlaskitDummy';
import Select from 'react-select';
import { H1, Note } from '../styled-components';
import { colourOptions } from '../data';
interface State {
isOpen: boolean;
isFixed: boolean;
portalPlacement: 'auto' | 'bottom' | 'top';
}
export default class MenuPortal extends React.Component<any, State> {
state: State = {
isOpen: false,
isFixed: false,
portalPlacement: 'bottom',
};
open = () => {
console.log('menuPortal is Open');
this.setState({ isOpen: true });
}
close = () => { this.setState({ isOpen: false }); };
setPlacement = ({ currentTarget }: any) => {
const portalPlacement = currentTarget && currentTarget.value;
this.setState({ portalPlacement });
}
toggleMode = () => {
this.setState(state => ({ isFixed: !state.isFixed }));
}
render() {
const { close, open } = this;
const { isOpen, isFixed, portalPlacement } = this.state;
return (
<React.Fragment>
<Button onClick={open}>Open Modal</Button>
{
isOpen ?
<Modal onClose={close}>
<H1>Portaled Menu Element</H1>
<Select
defaultValue={colourOptions[0]}
isClearable
styles={{ menuPortal: (base: any) => ({ ...base, zIndex: 9999 }) }}
menuPortalTarget={document.body}
isSearchable
name="color"
menuPosition={isFixed ? 'fixed' : 'absolute'}
menuPlacement={portalPlacement}
options={colourOptions}
/>
<Note Tag="label">
<select
// TODO type="radio"
onChange={this.setPlacement}
value={portalPlacement}
id="cypress-portalled__radio-bottom"
>
<option value="auto">auto</option>
<option value="bottom">bottom</option>
<option value="top">top</option>
</select>
</Note>
<Note Tag="label" style={{ marginLeft: '1em' }}>
<input
type="radio"
onChange={this.toggleMode}
value="fixed"
checked={isFixed}
id="cypress-portalled__fixed"
/>
Fixed
</Note>
<Note Tag="label" style={{ marginLeft: '1em' }}>
<input
type="radio"
onChange={this.toggleMode}
value="portal"
checked={!isFixed}
id="cypress-portalled__portal"
/>
Portal
</Note>
</Modal>
: null
}
</React.Fragment>
);
}
}

View File

@@ -0,0 +1,47 @@
import * as React from 'react';
import Select from 'react-select';
import { colourOptions } from '../data';
import { InputActionMeta } from 'react-select/lib/types';
export default class OnSelectResetsInput extends React.Component {
state = {
inputValue: '',
menuIsOpen: undefined
};
onInputChange = (inputValue: string, { action }: InputActionMeta) => {
console.log(inputValue, action);
switch (action) {
case 'input-change':
this.setState({ inputValue });
return;
case 'menu-close':
console.log(this.state.inputValue);
let menuIsOpen;
if (this.state.inputValue) {
menuIsOpen = true;
}
this.setState({
menuIsOpen
});
return;
default:
return;
}
}
render() {
const { inputValue, menuIsOpen } = this.state;
return (
<Select
isMulti
defaultValue={colourOptions[0]}
isClearable
isSearchable
inputValue={inputValue}
onInputChange={this.onInputChange}
name="color"
options={colourOptions}
menuIsOpen={menuIsOpen}
/>
);
}
}

View File

@@ -0,0 +1,128 @@
import * as React from 'react';
import { Button } from '../AtlaskitDummy';
import Select from 'react-select';
import { colors } from 'react-select/lib/theme';
import { stateOptions } from '../data';
const selectStyles = {
control: (provided: any) => ({ ...provided, minWidth: 240, margin: 8 }),
menu: () => ({ boxShadow: 'inset 0 1px 0 rgba(0, 0, 0, 0.1)' }),
};
interface State { isOpen: boolean; value: any; }
export default class PopoutExample extends React.Component<any, State> {
state: State = { isOpen: false, value: undefined };
toggleOpen = () => {
this.setState(state => ({ isOpen: !state.isOpen }));
}
onSelectChange = (value: any) => {
this.toggleOpen();
this.setState({ value });
}
render() {
const { isOpen, value } = this.state;
return (
<Dropdown
isOpen={isOpen}
onClose={this.toggleOpen}
target={
<Button
iconAfter={<ChevronDown />}
onClick={this.toggleOpen}
isSelected={isOpen}
>
{value ? `State: ${value.label}` : 'Select a State'}
</Button>
}
>
<Select
autoFocus
backspaceRemovesValue={false}
components={{ DropdownIndicator, IndicatorSeparator: null }}
controlShouldRenderValue={false}
hideSelectedOptions={false}
isClearable={false}
menuIsOpen
onChange={this.onSelectChange}
options={stateOptions}
placeholder="Search..."
styles={selectStyles}
tabSelectsValue={false}
value={value}
/>
</Dropdown>
);
}
}
// styled components
const Menu = (props: any) => {
const shadow = colors.neutral10a;
return (
<div
css={{
backgroundColor: 'white',
borderRadius: 4,
boxShadow: `0 0 0 1px ${shadow}, 0 4px 11px ${shadow}`,
marginTop: 8,
position: 'absolute',
zIndex: 2,
}}
{...props}
/>
);
};
const Blanket = (props: any) => (
<div
css={{
bottom: 0,
left: 0,
top: 0,
right: 0,
position: 'fixed',
zIndex: 1,
}}
{...props}
/>
);
const Dropdown = ({ children, isOpen, target, onClose }: any) => (
<div style={{ position: 'relative' }}>// TODO css type
{target}
{isOpen ? <Menu>{children}</Menu> : null}
{isOpen ? <Blanket onClick={onClose} /> : null}
</div>
);
const Svg = (p: any) => (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
focusable="false"
role="presentation"
{...p}
/>
);
const DropdownIndicator = () => (
<div style={{ color: colors.neutral20, height: 24, width: 32 }}>// TODO css type
<Svg>
<path
d="M16.436 15.085l3.94 4.01a1 1 0 0 1-1.425 1.402l-3.938-4.006a7.5 7.5 0 1 1 1.423-1.406zM10.5 16a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11z"
fill="currentColor"
fillRule="evenodd"
/>
</Svg>
</div>
);
const ChevronDown = () => (
<Svg style={{ marginRight: -6 }}>
<path
// tslint:disable-next-line:max-line-length
d="M8.292 10.293a1.009 1.009 0 0 0 0 1.419l2.939 2.965c.218.215.5.322.779.322s.556-.107.769-.322l2.93-2.955a1.01 1.01 0 0 0 0-1.419.987.987 0 0 0-1.406 0l-2.298 2.317-2.307-2.327a.99.99 0 0 0-1.406 0z"
fill="currentColor"
fillRule="evenodd"
/>
</Svg>
);

View File

@@ -0,0 +1,53 @@
import * as React from 'react';
import * as chroma from 'chroma-js';
import { colourOptions } from '../data';
import Select from 'react-select';
const colourStyles = {
control: (styles: any) => ({ ...styles, backgroundColor: 'white' }),
option: (styles: any, { data, isDisabled, isFocused, isSelected }: any) => {
const color = chroma(data.color);
return {
...styles,
backgroundColor: isDisabled
? null
: isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null,
color: isDisabled
? '#ccc'
: isSelected
? chroma.contrast(color, 'white') > 2 ? 'white' : 'black'
: data.color,
cursor: isDisabled ? 'not-allowed' : 'default',
};
},
multiValue: (styles: any, { data }: any) => {
const color = chroma(data.color);
return {
...styles,
backgroundColor: color.alpha(0.1).css(),
};
},
multiValueLabel: (styles: any, { data }: any) => ({
...styles,
color: data.color,
}),
multiValueRemove: (styles: any, { data }: any) => ({
...styles,
color: data.color,
':hover': {
backgroundColor: data.color,
color: 'white',
},
}),
};
export default () => (
<Select
closeMenuOnSelect={false}
defaultValue={[colourOptions[0], colourOptions[1]]}
isMulti
options={colourOptions}
styles={colourStyles}
/>
);

View File

@@ -0,0 +1,51 @@
import * as React from 'react';
import * as chroma from 'chroma-js';
import { colourOptions } from '../data';
import Select from 'react-select';
const dot = (color = '#ccc') => ({
alignItems: 'center',
display: 'flex',
':before': {
backgroundColor: color,
borderRadius: 10,
content: ' ',
display: 'block',
marginRight: 8,
height: 10,
width: 10,
},
});
const colourStyles = {
control: (styles: any) => ({ ...styles, backgroundColor: 'white' }),
option: (styles: any, { data, isDisabled, isFocused, isSelected }: any) => {
const color = chroma(data.color);
return {
...styles,
backgroundColor: isDisabled
? null
: isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null,
color: isDisabled
? '#ccc'
: isSelected
? chroma.contrast(color, 'white') > 2 ? 'white' : 'black'
: data.color,
cursor: isDisabled ? 'not-allowed' : 'default',
};
},
input: (styles: any) => ({ ...styles, ...dot() }),
placeholder: (styles: any) => ({ ...styles, ...dot() }),
singleValue: (styles: any, { data }: any) => ({ ...styles, ...dot(data.color) }),
};
export default () => (
<Select
defaultValue={colourOptions[2]}
// TODO label="Single select"
options={colourOptions}
styles={colourStyles}
/>
);

View File

@@ -0,0 +1,17 @@
import * as React from 'react';
export const Note = ({ Tag = 'div', ...props }: any) => (
<Tag
css={{
color: 'hsl(0, 0%, 40%)',
display: 'inline-block',
fontSize: 12,
fontStyle: 'italic',
marginTop: '1em',
}}
{...props}
/>
);
export const H1 = (props: any) => <h1 css={{ marginTop: 0 }} {...props} />;
export const H2 = (props: any) => <h2 css={{ marginTop: '2em' }} {...props} />;

View File

@@ -1,10 +1,4 @@
{
"files": [
"index.d.ts",
"lib/Option/index.d.ts",
"lib/utils/defaultMenuRenderer/index.d.ts",
"react-select-tests.tsx"
],
"compilerOptions": {
"module": "commonjs",
"lib": [
@@ -12,16 +6,99 @@
"dom"
],
"noImplicitAny": true,
"noImplicitThis": false,
"strictNullChecks": false,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"jsx": "react",
"typeRoots": [
"../"
],
"jsx": "react",
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
},
"files": [
"index.d.ts",
"lib/animated/Input.d.ts",
"lib/animated/MultiValue.d.ts",
"lib/animated/Placeholder.d.ts",
"lib/animated/SingleValue.d.ts",
"lib/animated/ValueContainer.d.ts",
"lib/animated/transitions.d.ts",
"lib/animated/index.d.ts",
"lib/components/containers.d.ts",
"lib/components/Control.d.ts",
"lib/components/Group.d.ts",
"lib/components/Input.d.ts",
"lib/components/Menu.d.ts",
"lib/components/MultiValue.d.ts",
"lib/components/Option.d.ts",
"lib/components/Placeholder.d.ts",
"lib/components/SingleValue.d.ts",
"lib/components/indicators.d.ts",
"lib/components/index.d.ts",
"lib/accessibility/index.d.ts",
"lib/theme.d.ts",
"lib/Creatable.d.ts",
"lib/Async.d.ts",
"lib/AsyncCreatable.d.ts",
"lib/filters.d.ts",
"lib/styles.d.ts",
"lib/stateManager.d.ts",
"lib/builtins.d.ts",
"lib/utils.d.ts",
"lib/diacritics.d.ts",
"lib/types.d.ts",
"lib/Select.d.ts",
"test/data.ts",
"test/styled-components.tsx",
"test/AtlaskitDummy.ts",
"test/ChronoNodeDummy.ts",
"test/examples/AccessingInternals.tsx",
"test/examples/AnimatedMulti.tsx",
"test/examples/AsyncCallbacks.tsx",
"test/examples/AsyncCreatable.tsx",
"test/examples/AsyncMulti.tsx",
"test/examples/AsyncPromises.tsx",
"test/examples/BasicGrouped.tsx",
"test/examples/BasicMulti.tsx",
"test/examples/BasicSingle.tsx",
"test/examples/ControlledMenu.tsx",
"test/examples/CreatableAdvanced.tsx",
"test/examples/CreatableInputOnly.tsx",
"test/examples/CreatableMulti.tsx",
"test/examples/CreatableSingle.tsx",
"test/examples/CreateFilter.tsx",
"test/examples/CustomClearIndicator.tsx",
"test/examples/CustomControl.tsx",
"test/examples/CustomDropdownIndicator.tsx",
"test/examples/CustomFilterOptions.tsx",
"test/examples/CustomGetOptionLabel.tsx",
"test/examples/CustomGroup.tsx",
"test/examples/CustomGroupHeading.tsx",
"test/examples/CustomIndicatorsContainer.tsx",
"test/examples/CustomIndicatorSeparator.tsx",
"test/examples/CustomInput.tsx",
"test/examples/CustomIsOptionDisabled.tsx",
"test/examples/CustomLoadingIndicator.tsx",
"test/examples/CustomLoadingMessage.tsx",
"test/examples/CustomMenu.tsx",
"test/examples/CustomMenuList.tsx",
"test/examples/CustomMultiValueContainer.tsx",
"test/examples/CustomMultiValueLabel.tsx",
"test/examples/CustomMultiValueRemove.tsx",
"test/examples/CustomNoOptionsMessage.tsx",
"test/examples/CustomOption.tsx",
"test/examples/CustomPlaceholder.tsx",
"test/examples/CustomSelectContainer.tsx",
"test/examples/CustomSingleValue.tsx",
"test/examples/CustomValueContainer.tsx",
"test/examples/Experimental.tsx",
"test/examples/MenuPortal.tsx",
"test/examples/OnSelectResetsInput.tsx",
"test/examples/Popout.tsx",
"test/examples/StyledMulti.tsx",
"test/examples/StyledSingle.tsx"
]
}

View File

@@ -1 +1,3 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json"
}

654
types/react-select/v1/index.d.ts vendored Normal file
View File

@@ -0,0 +1,654 @@
// Type definitions for react-select 1.3
// Project: https://github.com/JedWatson/react-select
// Definitions by: ESQUIBET Hugo <https://github.com/Hesquibet>
// Gilad Gray <https://github.com/giladgray>
// Izaak Baker <https://github.com/iebaker>
// Tadas Dailyda <https://github.com/skirsdeda>
// Mark Vujevits <https://github.com/vujevits>
// Mike Deverell <https://github.com/devrelm>
// MartynasZilinskas <https://github.com/MartynasZilinskas>
// Onat Yigit Mercan <https://github.com/onatm>
// Ian Johnson <https://github.com/ninjaferret>
// Anton Novik <https://github.com/tehbi4>
// David Schkalee <https://github.com/misantronic>
// Arthur Udalov <https://github.com/darkartur>
// Sebastian Silbermann <https://github.com/eps1lon>
// Endurance Idehen <https://github.com/endurance>
// Guillaume Chartier <https://github.com/RCGuillaume>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
import * as React from 'react';
export default class ReactSelectClass<TValue = OptionValues> extends React.Component<ReactSelectProps<TValue>> {
focus(): void;
setValue(value: Option<TValue>): void;
}
// Other components
export class Creatable<TValue = OptionValues> extends React.Component<ReactCreatableSelectProps<TValue>> { }
export class Async<TValue = OptionValues> extends React.Component<ReactAsyncSelectProps<TValue>> { }
export class AsyncCreatable<TValue = OptionValues> extends React.Component<ReactAsyncCreatableSelectProps<TValue>> { }
export type OptionComponentType<TValue = OptionValues> = React.ComponentType<OptionComponentProps<TValue>>;
export type ValueComponentType<TValue = OptionValues> = React.ComponentType<ValueComponentProps<TValue>>;
export type HandlerRendererResult = JSX.Element | null | false;
// Handlers
export type FocusOptionHandler<TValue = OptionValues> = (option: Option<TValue>) => void;
export type SelectValueHandler<TValue = OptionValues> = (option: Option<TValue>) => void;
export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult;
export type ClearRendererHandler = () => HandlerRendererResult;
export type FilterOptionHandler<TValue = OptionValues> = (option: Option<TValue>, filter: string) => boolean;
export type FilterOptionsHandler<TValue = OptionValues> = (options: Options<TValue>, filter: string, currentValues: Options<TValue>) => Options<TValue>;
export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult;
export type MenuRendererHandler<TValue = OptionValues> = (props: MenuRendererProps<TValue>) => HandlerRendererResult;
export type OnCloseHandler = () => void;
export type OnInputChangeHandler = (inputValue: string) => string;
export type OnInputKeyDownHandler = React.KeyboardEventHandler<HTMLDivElement | HTMLInputElement>;
export type OnMenuScrollToBottomHandler = () => void;
export type OnOpenHandler = () => void;
export type OnFocusHandler = React.FocusEventHandler<HTMLDivElement | HTMLInputElement>;
export type OnBlurHandler = React.FocusEventHandler<HTMLDivElement | HTMLInputElement>;
export type OptionRendererHandler<TValue = OptionValues> = (option: Option<TValue>) => HandlerRendererResult;
export type ValueRendererHandler<TValue = OptionValues> = (option: Option<TValue>, index?: number) => HandlerRendererResult;
export type OnValueClickHandler<TValue = OptionValues> = (option: Option<TValue>, event: React.MouseEvent<HTMLAnchorElement>) => void;
export type IsOptionUniqueHandler<TValue = OptionValues> = (arg: { option: Option<TValue>, options: Options<TValue>, labelKey: string, valueKey: string }) => boolean;
export type IsValidNewOptionHandler = (arg: { label: string }) => boolean;
export type NewOptionCreatorHandler<TValue = OptionValues> = (arg: { label: string, labelKey: string, valueKey: string }) => Option<TValue>;
export type PromptTextCreatorHandler = (filterText: string) => string;
export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean;
export type OnChangeSingleHandler<TValue = OptionValues> = OnChangeHandler<TValue, Option<TValue>>;
export type OnChangeMultipleHandler<TValue = OptionValues> = OnChangeHandler<TValue, Options<TValue>>;
export type OnChangeHandler<TValue = OptionValues, TOption = Option<TValue> | Options<TValue>> = (newValue: TOption | null) => void;
export type OnNewOptionClickHandler<TValue = OptionValues> = (option: Option<TValue>) => void;
export type LoadOptionsHandler<TValue = OptionValues> = LoadOptionsAsyncHandler<TValue> | LoadOptionsLegacyHandler<TValue>;
export type LoadOptionsAsyncHandler<TValue = OptionValues> = (input: string) => Promise<AutocompleteResult<TValue>>;
export type LoadOptionsLegacyHandler<TValue = OptionValues> = (input: string, callback: (err: any, result: AutocompleteResult<TValue>) => void) => void;
export interface AutocompleteResult<TValue = OptionValues> {
/** The search-results to be displayed */
options: Options<TValue>;
/**
* Should be set to true, if and only if a longer query with the same prefix
* would return a subset of the results
* If set to true, more specific queries will not be sent to the server.
*/
complete: boolean;
}
export type Options<TValue = OptionValues> = Array<Option<TValue>>;
export interface Option<TValue = OptionValues> {
/** Text for rendering */
label?: string;
/** Value for searching */
value?: TValue;
/**
* Allow this option to be cleared
* @default true
*/
clearableValue?: boolean;
/**
* Do not allow this option to be selected
* @default false
*/
disabled?: boolean;
/**
* In the event that a custom menuRenderer is provided, Option should be able
* to accept arbitrary key-value pairs. See react-virtualized-select.
*/
[property: string]: any;
}
export type OptionValues = string | number | boolean;
export interface MenuRendererProps<TValue = OptionValues> {
/**
* The currently focused option; should be visible in the menu by default.
* default {}
*/
focusedOption: Option<TValue>;
/**
* Callback to focus a new option; receives the option as a parameter.
*/
focusOption: FocusOptionHandler<TValue>;
/**
* Option labels are accessible with this string key.
*/
labelKey: string;
/**
* Ordered array of options to render.
*/
options: Options<TValue>;
/**
* Callback to select a new option; receives the option as a parameter.
*/
selectValue: SelectValueHandler<TValue>;
/**
* Array of currently selected options.
*/
valueArray: Options<TValue>;
/**
* Callback to remove selection from option; receives the option as a parameter.
*/
removeValue: SelectValueHandler<TValue>;
/**
* function which returns a custom way to render the options in the menu
*/
optionRenderer: OptionRendererHandler<TValue>;
}
export interface OptionComponentProps<TValue = OptionValues> {
/**
* Classname(s) to apply to the option component.
*/
className?: string;
/**
* Currently focused option.
*/
focusOption?: Option<TValue>;
inputValue?: string;
instancePrefix?: string;
/**
* True if this option is disabled.
*/
isDisabled?: boolean;
/**
* True if this option is focused.
*/
isFocused?: boolean;
/**
* True if this option is selected.
*/
isSelected?: boolean;
/**
* Callback to be invoked when this option is focused.
*/
onFocus?: (option: Option<TValue>, event: any) => void;
/**
* Callback to be invoked when this option is selected.
*/
onSelect?: (option: Option<TValue>, event: any) => void;
/**
* Option to be rendered by this component.
*/
option: Option<TValue>;
/**
* Index of the option being rendered in the list
*/
optionIndex?: number;
/**
* Callback to invoke when removing an option from a multi-selection. (Not necessarily the one
* being rendered)
*/
removeValue?: (value: TValue | TValue[]) => void;
/**
* Callback to invoke to select an option. (Not necessarily the one being rendered)
*/
selectValue?: (value: TValue | TValue[]) => void;
}
export interface ArrowRendererProps {
/**
* Arrow mouse down event handler.
*/
onMouseDown: React.MouseEventHandler<any>;
/**
* whether the Select is open or not.
*/
isOpen: boolean;
}
export interface ValueComponentProps<TValue = OptionValues> {
disabled: ReactSelectProps<TValue>['disabled'];
id: string;
instancePrefix: string;
onClick: OnValueClickHandler<TValue> | null;
onRemove?: SelectValueHandler<TValue>;
placeholder: ReactSelectProps<TValue>['placeholder'];
value: Option<TValue>;
values?: Array<Option<TValue>>;
}
export interface ReactSelectProps<TValue = OptionValues> extends React.Props<ReactSelectClass<TValue>> {
/**
* text to display when `allowCreate` is true.
* @default 'Add "{label}"?'
*/
addLabelText?: string;
/**
* renders a custom drop-down arrow to be shown in the right-hand side of the select.
* @default undefined
*/
arrowRenderer?: ArrowRendererHandler | null;
/**
* blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices.
* @default false
*/
autoBlur?: boolean;
/**
* autofocus the component on mount
* @deprecated. Use autoFocus instead
* @default false
*/
autofocus?: boolean;
/**
* autofocus the component on mount
* @default false
*/
autoFocus?: boolean;
/**
* If enabled, the input will expand as the length of its value increases
*/
autosize?: boolean;
/**
* whether pressing backspace removes the last item when there is no input value
* @default true
*/
backspaceRemoves?: boolean;
/**
* Message to use for screenreaders to press backspace to remove the current item
* {label} is replaced with the item label
* @default "Press backspace to remove..."
*/
backspaceToRemoveMessage?: string;
/**
* CSS className for the outer element
*/
className?: string;
/**
* Prefix prepended to element default className if no className is defined
*/
classNamePrefix?: string;
/**
* title for the "clear" control when `multi` is true
* @default "Clear all"
*/
clearAllText?: string;
/**
* Renders a custom clear to be shown in the right-hand side of the select when clearable true
* @default undefined
*/
clearRenderer?: ClearRendererHandler;
/**
* title for the "clear" control
* @default "Clear value"
*/
clearValueText?: string;
/**
* whether to close the menu when a value is selected
* @default true
*/
closeOnSelect?: boolean;
/**
* whether it is possible to reset value. if enabled, an X button will appear at the right side.
* @default true
*/
clearable?: boolean;
/**
* whether backspace removes an item if there is no text input
* @default true
*/
deleteRemoves?: boolean;
/**
* delimiter to use to join multiple values
* @default ","
*/
delimiter?: string;
/**
* whether the Select is disabled or not
* @default false
*/
disabled?: boolean;
/**
* whether escape clears the value when the menu is closed
* @default true
*/
escapeClearsValue?: boolean;
/**
* method to filter a single option
*/
filterOption?: FilterOptionHandler<TValue>;
/**
* method to filter the options array
*/
filterOptions?: FilterOptionsHandler<TValue>;
/**
* id for the underlying HTML input element
* @default undefined
*/
id?: string;
/**
* whether to strip diacritics when filtering
* @default true
*/
ignoreAccents?: boolean;
/**
* whether to perform case-insensitive filtering
* @default true
*/
ignoreCase?: boolean;
/**
* custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'}
* @default {}
*/
inputProps?: { [key: string]: any };
/**
* renders a custom input
*/
inputRenderer?: InputRendererHandler;
/**
* allows for synchronization of component id's on server and client.
* @see https://github.com/JedWatson/react-select/pull/1105
*/
instanceId?: string;
/**
* whether the Select is loading externally or not (such as options being loaded).
* if true, a loading spinner will be shown at the right side.
* @default false
*/
isLoading?: boolean;
/**
* (legacy mode) joins multiple values into a single form field with the delimiter
* @default false
*/
joinValues?: boolean;
/**
* the option property to use for the label
* @default "label"
*/
labelKey?: string;
/**
* (any, start) match the start or entire string when filtering
* @default "any"
*/
matchPos?: string;
/**
* (any, label, value) which option property to filter on
* @default "any"
*/
matchProp?: string;
/**
* buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport
* @default 0
*/
menuBuffer?: number;
/**
* optional style to apply to the menu container
*/
menuContainerStyle?: React.CSSProperties;
/**
* renders a custom menu with options
*/
menuRenderer?: MenuRendererHandler<TValue>;
/**
* optional style to apply to the menu
*/
menuStyle?: React.CSSProperties;
/**
* multi-value input
* @default false
*/
multi?: boolean;
/**
* field name, for hidden `<input>` tag
*/
name?: string;
/**
* placeholder displayed when there are no matching search results or a falsy value to hide it
* @default "No results found"
*/
noResultsText?: string | JSX.Element;
/**
* onBlur handler: function (event) {}
*/
onBlur?: OnBlurHandler;
/**
* whether to clear input on blur or not
* @default true
*/
onBlurResetsInput?: boolean;
/**
* whether the input value should be reset when options are selected.
* Also input value will be set to empty if 'onSelectResetsInput=true' and
* Select will get new value that not equal previous value.
* @default true
*/
onSelectResetsInput?: boolean;
/**
* whether to clear input when closing the menu through the arrow
* @default true
*/
onCloseResetsInput?: boolean;
/**
* onChange handler: function (newValue) {}
*/
onChange?: OnChangeHandler<TValue>;
/**
* fires when the menu is closed
*/
onClose?: OnCloseHandler;
/**
* onFocus handler: function (event) {}
*/
onFocus?: OnFocusHandler;
/**
* onInputChange handler: function (inputValue) {}
*/
onInputChange?: OnInputChangeHandler;
/**
* onInputKeyDown handler: function (keyboardEvent) {}
*/
onInputKeyDown?: OnInputKeyDownHandler;
/**
* fires when the menu is scrolled to the bottom; can be used to paginate options
*/
onMenuScrollToBottom?: OnMenuScrollToBottomHandler;
/**
* fires when the menu is opened
*/
onOpen?: OnOpenHandler;
/**
* boolean to enable opening dropdown when focused
* @default false
*/
openOnClick?: boolean;
/**
* open the options menu when the input gets focus (requires searchable = true)
* @default true
*/
openOnFocus?: boolean;
/**
* className to add to each option component
*/
optionClassName?: string;
/**
* option component to render in dropdown
*/
optionComponent?: OptionComponentType<TValue>;
/**
* function which returns a custom way to render the options in the menu
*/
optionRenderer?: OptionRendererHandler<TValue>;
/**
* array of Select options
* @default false
*/
options?: Options<TValue>;
/**
* number of options to jump when using page up/down keys
* @default 5
*/
pageSize?: number;
/**
* field placeholder, displayed when there's no value
* @default "Select..."
*/
placeholder?: string | JSX.Element;
/**
* whether the selected option is removed from the dropdown on multi selects
* @default true
*/
removeSelected?: boolean;
/**
* applies HTML5 required attribute when needed
* @default false
*/
required?: boolean;
/**
* value to use when you clear the control
*/
resetValue?: any;
/**
* use react-select in right-to-left direction
* @default false
*/
rtl?: boolean;
/**
* whether the viewport will shift to display the entire menu when engaged
* @default true
*/
scrollMenuIntoView?: boolean;
/**
* whether to enable searching feature or not
* @default true;
*/
searchable?: boolean;
/**
* whether to select the currently focused value when the [tab] key is pressed
*/
tabSelectsValue?: boolean;
/**
* initial field value
*/
value?: Option<TValue> | Options<TValue> | string | string[] | number | number[] | boolean;
/**
* the option property to use for the value
* @default "value"
*/
valueKey?: string;
/**
* function which returns a custom way to render the value selected
* @default false
*/
valueRenderer?: ValueRendererHandler<TValue>;
/**
* optional style to apply to the control
*/
style?: React.CSSProperties;
/**
* optional tab index of the control
*/
tabIndex?: string | number;
/**
* value component to render
*/
valueComponent?: ValueComponentType<TValue>;
/**
* optional style to apply to the component wrapper
*/
wrapperStyle?: React.CSSProperties;
/**
* onClick handler for value labels: function (value, event) {}
*/
onValueClick?: OnValueClickHandler<TValue>;
/**
* pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false
*/
simpleValue?: boolean;
}
export interface ReactCreatableSelectProps<TValue = OptionValues> extends ReactSelectProps<TValue> {
/**
* Searches for any matching option within the set of options. This function prevents
* duplicate options from being created.
*/
isOptionUnique?: IsOptionUniqueHandler<TValue>;
/**
* Determines if the current input text represents a valid option.
*/
isValidNewOption?: IsValidNewOptionHandler;
/**
* factory to create new options
*/
newOptionCreator?: NewOptionCreatorHandler<TValue>;
/**
* Creates prompt/placeholder for option text.
*/
promptTextCreator?: PromptTextCreatorHandler;
/**
* Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option.
*/
shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler;
/**
* new option click handler: function (option) {}
*/
onNewOptionClick?: OnNewOptionClickHandler<TValue>;
/**
* true: Show new option at top of list
* false: Show new option at bottom of list
* @default true
*/
showNewOptionAtTop?: boolean;
}
export interface ReactAsyncSelectProps<TValue = OptionValues> extends ReactSelectProps<TValue> {
/**
* Whether to auto-load the default async options set.
*/
autoload?: boolean;
/**
* object to use to cache results; can be null to disable cache
*/
cache?: { [key: string]: any } | boolean;
/**
* function to call to load options asynchronously
*/
loadOptions: LoadOptionsHandler<TValue>;
/**
* replaces the placeholder while options are loading
*/
loadingPlaceholder?: string | JSX.Element;
/**
* displayed in the drop down list when the user did not type anything yet
*/
searchPromptText?: string;
}
export type ReactAsyncCreatableSelectProps<TValue = OptionValues> = ReactAsyncSelectProps<TValue> & ReactCreatableSelectProps<TValue>;

View File

@@ -0,0 +1,35 @@
{
"files": [
"index.d.ts",
"lib/Option/index.d.ts",
"lib/utils/defaultMenuRenderer/index.d.ts",
"react-select-tests.tsx"
],
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": false,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../../",
"jsx": "react",
"typeRoots": [
"../../"
],
"paths": {
"react-select": [
"react-select/v1"
],
"react-select/*": [
"react-select/v1/*"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -10,11 +10,18 @@
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"paths": {
"react-select": [
"react-select/v1"
],
"react-select/*": [
"react-select/v1/*"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true