Skip to content

Commit

Permalink
[select] feat: new Select2 component uses Popover2 (#5306)
Browse files Browse the repository at this point in the history
  • Loading branch information
adidahiya authored May 17, 2022
1 parent a6453da commit 44c14e5
Show file tree
Hide file tree
Showing 15 changed files with 722 additions and 282 deletions.
6 changes: 3 additions & 3 deletions packages/docs-app/src/common/filmSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import * as React from "react";

import { Button, MenuItem } from "@blueprintjs/core";
import { Select, SelectProps } from "@blueprintjs/select";
import { Select2, Select2Props } from "@blueprintjs/select";

import {
areFilmsEqual,
Expand All @@ -30,10 +30,10 @@ import {
TOP_100_FILMS,
} from "./films";

const FilmSelect = Select.ofType<IFilm>();
const FilmSelect = Select2.ofType<IFilm>();

type Props = Omit<
SelectProps<IFilm>,
Select2Props<IFilm>,
| "createNewItemFromQuery"
| "createNewItemRenderer"
| "items"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export interface ISelectExampleState {
matchTargetWidth: false;
}

/** Technically a Select2 example, since FilmSelect uses Select2. */
export class SelectExample extends React.PureComponent<IExampleProps, ISelectExampleState> {
public state: ISelectExampleState = {
allowCreate: false,
Expand Down
1 change: 0 additions & 1 deletion packages/select/karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const { createKarmaConfig } = require("@blueprintjs/karma-build-scripts");

module.exports = function (config) {
const baseConfig = createKarmaConfig({
coverage: false,
dirname: __dirname,
});
config.set(baseConfig);
Expand Down
1 change: 1 addition & 0 deletions packages/select/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
},
"dependencies": {
"@blueprintjs/core": "^4.3.2",
"@blueprintjs/popover2": "^1.2.2",
"classnames": "^2.2",
"tslib": "~2.3.1"
},
Expand Down
1 change: 1 addition & 0 deletions packages/select/src/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ export * from "./omnibar/omnibar";
export * from "./query-list/queryList";
export * from "./select/multiSelect";
export * from "./select/select";
export * from "./select/select2";
export * from "./select/suggest";
3 changes: 2 additions & 1 deletion packages/select/src/components/select/_select.scss
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ $select-popover-max-width: $pt-grid-size * 40 !default;
}
}

.#{$ns}-popover-content {
.#{$ns}-popover-content,
.#{$ns}-popover2-content {
// use padding on container rather than margin on input group
// because top margin leaves some empty space with no background color.
padding: $pt-grid-size * 0.5;
Expand Down
279 changes: 15 additions & 264 deletions packages/select/src/components/select/select-component.md
Original file line number Diff line number Diff line change
@@ -1,276 +1,27 @@
@# Select

Use `Select<T>` for choosing one item from a list. The component's children will be wrapped in a [`Popover`](#core/components/popover) that contains the list and an optional `InputGroup` to filter it. Provide a predicate to customize the filtering algorithm. The value of a `Select<T>` (the currently chosen item) is uncontrolled: listen to changes with `onItemSelect`.
<div class="@ns-callout @ns-intent-danger @ns-icon-error">
<h4 class="@ns-heading">

<div class="@ns-callout @ns-intent-primary @ns-icon-info-sign">
<h4 class="@ns-heading">Disabling a Select</h4>
Deprecated: use [Select2](#select/select2)

Disabling the component requires setting the `disabled` prop to `true`
and separately disabling the component's children as appropriate (because `Select` accepts arbitrary children).
</h4>

For example, `<Select ... disabled={true}><Button ... disabled={true} /></Select>`
This component is **deprecated since @blueprintjs/select v4.3.0** in favor of the new
Select2 component, which uses Popover2 instead of Popover under the hood.
You should migrate to the new API which will become the standard in Blueprint v5.

</div>

@reactExample SelectExample
The `Select<T>` component renders a UI to choose one item from a list. Its children are wrapped in a
[`Popover`](#core/components/popover) that contains the list and an optional `InputGroup` to filter it.
You may provide a predicate to customize the filtering algorithm. The value of a `Select<T>`
(the currently chosen item) is uncontrolled: listen to changes with `onItemSelect`.

```tsx
import { Button, MenuItem } from "@blueprintjs/core";
import { Select } from "@blueprintjs/select";
import * as Films from "./films";
The API for this component is nearly identical to that of Select2, except for a slight change in
`popoverProps` and the wrapper element(s) rendered around its children.
Refer to the [Select2 documentation](#select/select2) for full API details.

// Select<T> is a generic component to work with your data types.
// In TypeScript, you must first obtain a non-generic reference:
const FilmSelect = Select.ofType<Films.Film>();

ReactDOM.render(
<FilmSelect
items={Films.items}
itemPredicate={Films.itemPredicate}
itemRenderer={Films.itemRenderer}
noResults={<MenuItem disabled={true} text="No results." />}
onItemSelect={...}
>
{/* children become the popover target; render value here */}
<Button text={Films.items[0].title} rightIcon="double-caret-vertical" />
</FilmSelect>,
document.querySelector("#root")
);
```

In TypeScript, `Select<T>` is a _generic component_ so you must define a local type that specifies `<T>`, the type of one item in `items`. The props on this local type will now operate on your data type (speak your language) so you can easily define handlers without transformation steps, but most props are required as a result. The static `Select.ofType<T>()` method is available to streamline this process. (Note that this has no effect on JavaScript usage: the `Select` export is a perfectly valid React component class.)

@## Querying

Supply a predicate to automatically query items based on the `InputGroup` value. Use `itemPredicate` to filter each item individually; this is great for lightweight searches. Use `itemListPredicate` to query the entire array in one go, and even reorder it, such as with [fuzz-aldrin-plus](https://github.com/jeancroy/fuzz-aldrin-plus). The array of filtered items is cached internally by `QueryList` state and only recomputed when `query` or `items`-related props change.

Omitting both `itemPredicate` and `itemListPredicate` props will cause the component to always render all `items`. It will not hide the `InputGroup`; use the `filterable` prop for that. In this case, you can implement your own filtering and simply change the `items` prop.

The **@blueprintjs/select** package exports `ItemPredicate<T>` and `ItemListPredicate<T>` type aliases to simplify the process of implementing these functions.
See the code sample in [Item Renderer API](#select/select-component.item-renderer) below for usage.

@### Non-ideal states

If the query returns no results or `items` is empty, then `noResults` will be rendered in place of the usual list. You also have the option to provide `initialContent`, which will render in place of the item list if the query is empty.

@## Custom menu

By default, `Select` renders the displayed items in a [`Menu`](#core/components/menu). This behavior can be overridden by providing the `itemListRenderer` prop, giving you full control over the layout of the items. For example, you can group items under a common heading, or render large data sets using [react-virtualized](https://github.com/bvaughn/react-virtualized).

Note that the non-ideal states of `noResults` and `initialContent` are specific to the default renderer. If you provide the `itemListRenderer` prop, these props will be ignored.

See the code sample in [Item List Renderer API](#select/select-component.item-list-renderer) below for usage.

@## Controlled usage

The input value can be controlled with the `query` and `onQueryChange` props. _Do not use `inputProps` for this;_ the component ignores `inputProps.value` and `inputProps.onChange` in favor of `query` and `onQueryChange` (as noted in the prop documentation).

The focused item (for keyboard interactions) can be controlled with the `activeItem` and `onActiveItemChange` props.

```tsx
<FilmSelect
items={myFilter(ALL_ITEMS, this.state.myQuery)}
itemRenderer={...}
onItemSelect={...}
// controlled active item
activeItem={this.state.myActiveItem}
onActiveItemChange={this.handleActiveItemChange}
// controlled query
query={this.state.myQuery}
onQueryChange={this.handleQueryChange}
/>
```

This controlled usage allows you to implement all sorts of advanced behavior on
top of the basic `Select` interactions, such as windowed filtering for large
data sets.

<div class="@ns-callout @ns-intent-primary @ns-icon-info-sign">

To control the active item when a "Create Item" option is present, See [Controlling the active item](#select/select-component.controlling-the-active-item) in the "Creating new items" section below.
</div>

@## Creating new items

If you wish, you can allow users to select a brand new item that doesn't appear
in the list, based on the current query string. Use `createNewItemFromQuery` and
`createNewItemRenderer` to enable this:
- `createNewItemFromQuery`: Specifies how to convert a user-entered query string
into an item of type `<T>` that `Select` understands.
- `createNewItemRenderer`: Renders a custom "Create Item" element that will be
shown at the bottom of the list. When selected via click or `Enter`, this element
will invoke `onItemSelect` with the item returned from `createNewItemFromQuery`.

<div class="@ns-callout @ns-intent-warning @ns-icon-info-sign">
<h4 class="@ns-heading">Avoiding type conflicts</h4>

The "Create Item" option is represented by the reserved type `ICreateNewItem`
exported from this package. It is exceedingly unlikely but technically possible
for your custom type `<T>` to conflict with this type. If your type conflicts,
you may see unexpected behavior; to resolve, consider changing the schema for
your items.

</div>

```tsx
function createFilm(title: string): IFilm {
return {
rank: /* ... */,
title,
year: /* ... */,
};
}

function renderCreateFilmOption(
query: string,
active: boolean,
handleClick: React.MouseEventHandler<HTMLElement>,
) {
return (
<MenuItem
icon="add"
text={`Create "${query}"`}
selected={active}
onClick={handleClick}
shouldDismissPopover={false}
/>
)
}

ReactDOM.render(
<FilmSelect
createNewItemFromQuery={createFilm}
createNewItemRenderer={renderCreateFilmOption}
items={Films.items}
itemPredicate={Films.itemPredicate}
itemRenderer={Films.itemRenderer}
noResults={<MenuItem disabled={true} text="No results." />}
onItemSelect={...}
/>,
document.querySelector("#root")
);
```

@### Controlling the active item

Controlling the active item is slightly more involved when the "Create Item"
option is present. At a high level, the process works the same way as before:
control the `activeItem` value and listen for updates via `onActiveItemChange`.
However, some special handling is required.

When the "Create Item" option is present, the callback will emit
`activeItem=null` and `isCreateNewItem=true`:

```tsx
onActiveItemChange(null, true);
```

You can then make the "Create Item" option active by passing the result of
`getCreateNewItem()` to the `activeItem` prop (the `getCreateNewItem` function
is exported from this package):

```tsx
activeItem={isCreateNewItemActive ? getCreateNewItem() : activeItem}
```

Altogether, the code might look something like this:

```tsx
const currentActiveItem: Film | ICreateNewItem | null;
const isCreateNewItemActive: Film | ICreateNewItem | null;

function handleActiveItemChange(
activeItem: Film | ICreateNewItem | null,
isCreateNewItem: boolean,
) {
currentActiveItem = activeItem;
isCreateNewItemActive = isCreateNewItem;
}

function getActiveItem() {
return isCreateNewItemActive ? getCreateNewItem() : currentActiveItem;
}

ReactDOM.render(
<FilmSelect
{...} // Other required props (see previous examples).
activeItem={getActiveItem()}
createNewItemFromQuery={...}
createNewItemRenderer={...}
onActiveItemChange={handleActiveItemChange}
/>,
document.querySelector("#root")
);
```

@## JavaScript API
@## Props interface

@interface ISelectProps

@### Item renderer

`Select`'s `itemRenderer` will be called for each item and receives the item and a props object containing data specific
to rendering this item in this frame. The renderer is called for all items, so don't forget to respect
`modifiers.matchesPredicate` to hide items that don't match the predicate. Also, don't forget to define a `key` for each item, or face React's console wrath!

```tsx
import { Classes, MenuItem } from "@blueprintjs/core";
import { ItemRenderer, ItemPredicate, Select } from "@blueprintjs/select";

const FilmSelect = Select.ofType<Film>();

const filterFilm: ItemPredicate<IFilm> = (query, film) => {
return film.title.toLowerCase().indexOf(query.toLowerCase()) >= 0;
};

const renderFilm: ItemRenderer<Film> = (film, { handleClick, handleFocus, modifiers }) => {
if (!modifiers.matchesPredicate) {
return null;
}
return (
<MenuItem
selected={modifiers.active}
key={film.title}
label={film.year}
onClick={handleClick}
onFocus={handleFocus}
text={film.title}
/>
);
};

<FilmSelect itemPredicate={filterFilm} itemRenderer={renderFilm} items={...} onItemSelect={...} />
```

@interface IItemRendererProps

@### Item list renderer

If provided, the `itemListRenderer` prop will be called to render the contents of the dropdown menu. It has access to the items, the current query, and a `renderItem` callback for rendering a single item. A ref handler (`itemsParentRef`) is given as well; it should be attached to the parent element of the rendered menu items so that the currently selected item can be scrolled into view automatically.

```tsx
import { ItemListRenderer } from "@blueprintjs/select";

const renderMenu: ItemListRenderer<Film> = ({ items, itemsParentRef, query, renderItem }) => {
const renderedItems = items.map(renderItem).filter(item => item != null);
return (
<Menu ulRef={itemsParentRef}>
<MenuItem
disabled={true}
text={`Found ${renderedItems.length} items matching "${query}"`}
/>
{renderedItems}
</Menu>
);
};

<FilmSelect
itemListRenderer={renderMenu}
itemPredicate={filterFilm}
itemRenderer={renderFilm}
items={...}
onItemSelect={...}
/>
```

@interface IItemListRendererProps
1 change: 1 addition & 0 deletions packages/select/src/components/select/select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ export class Select<T> extends AbstractPureComponent2<SelectProps<T>, ISelectSta
private handlePopoverClosing = (node: HTMLElement) => {
// restore focus to saved element.
// timeout allows popover to begin closing and remove focus handlers beforehand.
/* istanbul ignore next */
this.requestAnimationFrame(() => {
if (this.previousFocusedElement !== undefined) {
this.previousFocusedElement.focus();
Expand Down
Loading

1 comment on commit 44c14e5

@blueprint-bot
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[select] feat: new Select2 component uses Popover2 (#5306)

Previews: documentation | landing | table | demo

Please sign in to comment.