Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[select] itemListRenderer #2252

Merged
merged 15 commits into from
Mar 20, 2018
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions packages/select/src/common/itemListRenderer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright 2017 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the terms of the LICENSE file distributed with this project.
*/

/**
* An object describing how to render the list of items.
* An `itemListRenderer` receives this object as its sole argument.
*/
export interface IItemListRendererProps<T> {
/**
* Array of items filtered by `itemListPredicate` or `itemPredicate`.
* See `items` for the full list of items.
*/
filteredItems: T[];

/**
* Array of all items in the list.
* See `filteredItems` for a filtered array based on `query` and predicate props.
*/
items: T[];

/**
* The current query string.
*/
query: string;

/**
* A ref handler that should be attached to the parent HTML element of the menu items.
* This is required for the active item to scroll into view automatically.
*/
itemsParentRef: (ref: HTMLElement | null) => void;

/**
* Call this function to render an item.
* This retrieves the modifiers for the item and delegates actual rendering
* to the owner component's `itemRenderer` prop.
*/
renderItem: (item: T, index?: number) => JSX.Element | null;
}

/** Type alias for a function that renders the list of items. */
export type ItemListRenderer<T> = (itemListProps: IItemListRendererProps<T>) => JSX.Element;
35 changes: 0 additions & 35 deletions packages/select/src/common/menuRenderer.ts

This file was deleted.

36 changes: 3 additions & 33 deletions packages/select/src/components/omnibar/omnibar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
InputGroup,
IOverlayableProps,
IOverlayProps,
Menu,
Overlay,
Utils,
} from "@blueprintjs/core";
Expand All @@ -24,14 +23,6 @@ import * as Classes from "../../common/classes";
import { IListItemsProps, IQueryListRendererProps, QueryList } from "../query-list/queryList";

export interface IOmnibarProps<T> extends IListItemsProps<T> {
/**
* React child to render when query is empty.
*/
initialContent?: React.ReactChild;

/** React child to render when filtering items returns zero results. */
noResults?: React.ReactChild;

/**
* Props to spread to `InputGroup`. All props are supported except `ref` (use `inputRef` instead).
* If you want to control the filter input, you can pass `value` and `onChange` here
Expand Down Expand Up @@ -90,11 +81,12 @@ export class Omnibar<T> extends React.PureComponent<IOmnibarProps<T>, IOmnibarSt

public render() {
// omit props specific to this component, spread the rest.
const { initialContent, isOpen, inputProps, noResults, overlayProps, ...restProps } = this.props;
const { initialContent = null, isOpen, inputProps, overlayProps, ...restProps } = this.props;

return (
<this.TypedQueryList
{...restProps}
initialContent={initialContent}
activeItem={this.state.activeItem}
onActiveItemChange={this.handleActiveItemChange}
onItemSelect={this.handleItemSelect}
Expand Down Expand Up @@ -138,34 +130,12 @@ export class Omnibar<T> extends React.PureComponent<IOmnibarProps<T>, IOmnibarSt
{...inputProps}
onChange={this.handleQueryChange}
/>
{this.maybeRenderMenu(listProps)}
{listProps.itemList}
</div>
</Overlay>
);
};

private renderItems({ items, renderItem }: IQueryListRendererProps<T>) {
const renderedItems = items.map(renderItem).filter(item => item != null);
return renderedItems.length > 0 ? renderedItems : this.props.noResults;
}

private maybeRenderMenu(listProps: IQueryListRendererProps<T>) {
const { initialContent } = this.props;
let menuChildren: any;

if (!this.isQueryEmpty()) {
menuChildren = this.renderItems(listProps);
} else if (initialContent != null) {
menuChildren = initialContent;
}

if (menuChildren != null) {
return <Menu ulRef={listProps.itemsParentRef}>{menuChildren}</Menu>;
}

return undefined;
}

private isQueryEmpty = () => this.state.query.length === 0;

private handleActiveItemChange = (activeItem?: T) => this.setState({ activeItem });
Expand Down
138 changes: 90 additions & 48 deletions packages/select/src/components/query-list/queryList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

import * as React from "react";

import { IProps, Keys, Utils } from "@blueprintjs/core";
import { IProps, Keys, Menu, Utils } from "@blueprintjs/core";
import { IItemListRendererProps, ItemListRenderer } from "../../common/itemListRenderer";
import { IItemModifiers, ItemRenderer } from "../../common/itemRenderer";
import { ItemListPredicate, ItemPredicate } from "../../common/predicate";

Expand All @@ -20,7 +21,7 @@ export interface IListItemsProps<T> extends IProps {
* This method can reorder, add, or remove items at will.
* (Supports filter algorithms that operate on the entire set, rather than individual items.)
*
* If defined with `itemPredicate`, this prop takes priority and the other will be ignored.
* If `itemPredicate` is also defined, this prop takes priority and the other will be ignored.
*/
itemListPredicate?: ItemListPredicate<T>;

Expand All @@ -29,7 +30,7 @@ export interface IListItemsProps<T> extends IProps {
* This method will be invoked once for each item, so it should be performant. For more complex
* queries, use `itemListPredicate` to operate once on the entire array.
*
* If defined with `itemListPredicate`, this prop will be ignored.
* This prop is ignored if `itemListPredicate` is also defined.
*/
itemPredicate?: ItemPredicate<T>;

Expand All @@ -40,6 +41,32 @@ export interface IListItemsProps<T> extends IProps {
*/
itemRenderer: ItemRenderer<T>;

/**
* Custom renderer for the contents of the dropdown.
*
* The default implementation invokes `itemRenderer` for each item that passes the predicate
* and wraps them all in a `Menu` element. If the query is empty then `initialContent` is returned,
* and if all items are filtered away then `noResults` is returned.
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: "if there are no items that match the predicate" (items could be empty, for all we know.)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

nice

*/
itemListRenderer?: ItemListRenderer<T>;

/**
* React content to render when query is empty.
* If omitted, all items will be rendered (or result of `itemListPredicate` with empty query).
* If explicit `null`, nothing will be rendered when query is empty.
*
* This prop is ignored if a custom `menuRenderer` is supplied.
*/
initialContent?: React.ReactNode | null;

/**
* React content to render when filtering items returns zero results.
* If omitted, nothing will be rendered in this case.
*
* This prop is ignored if a custom `menuRenderer` is supplied.
*/
noResults?: React.ReactNode;

/**
* Callback invoked when an item from the list is selected,
* typically by clicking or pressing `enter` key.
Expand Down Expand Up @@ -89,8 +116,16 @@ export interface IQueryListProps<T> extends IListItemsProps<T> {
query: string;
}

/** Interface for object passed to `QueryList` `renderer` function. */
/**
* An object describing how to render a `QueryList`.
* A `QueryList` `renderer` receives this object as its sole argument.
*/
export interface IQueryListRendererProps<T> extends IProps {
/**
* Array of items filtered by `itemListPredicate` or `itemPredicate`.
*/
filteredItems: T[];

/**
* Selection handler that should be invoked when a new item has been chosen,
* perhaps because the user clicked it.
Expand All @@ -109,29 +144,10 @@ export interface IQueryListRendererProps<T> extends IProps {
*/
handleKeyUp: React.KeyboardEventHandler<HTMLElement>;

/**
* Call this function to render an `item`.
* `QueryList` will retrieve modifiers for the item and delegate to `itemRenderer` prop for the actual rendering.
* The second parameter `index` is optional here; if provided, it will be passed through `itemRenderer` props.
*/
renderItem: (item: T, index?: number) => JSX.Element | null;

/**
* Array of all (unfiltered) items in the list.
* See `filteredItems` for a filtered array based on `query`.
*/
items: T[];

/**
* A ref handler that should be applied to the HTML element that contains the rendererd items.
* This is required for the `QueryList` to scroll the active item into view automatically.
*/
itemsParentRef: (ref: HTMLElement | null) => void;
/** Rendered elements returned from `menuRenderer` prop. */
Copy link
Contributor

Choose a reason for hiding this comment

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

menuRenderer -> itemListRenderer

itemList: React.ReactNode;

/**
* Controlled query string. Attach an `onChange` handler to the relevant
* element to control this prop from your application's state.
*/
/** The current query string. */
query: string;
}

Expand All @@ -146,6 +162,22 @@ export class QueryList<T> extends React.Component<IQueryListProps<T>, IQueryList
return QueryList as new (props: IQueryListProps<T>) => QueryList<T>;
}

/**
* Helper method for rendering `props.filteredItems`, with optional support for `noResults`
* (when filtered items is empty) and `initialContent` (when query is empty).
*/
public static renderFilteredItems(
Copy link
Contributor

@reiv reiv Mar 16, 2018

Choose a reason for hiding this comment

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

Can we broaden the scope of this helper? How about instead of taking IItemListRendererProps, we take items: T[]; then an itemListRenderer can call it with either filteredItems or items, depending on which is more appropriate. Also, since this is meant to be called first and foremost by an itemListRenderer, it's a bit awkward that it's defined on QueryList, which we usually don't import directly when consuming Select and friends. Can we maybe make it a top-level export of the select package?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

cool yes def down for the root export.

taking the props as a first argument was a quick way to get off the ground, cuz it receives both items and renderItem in one go. the name indicates which set of items it'll use. my goal here was to streamline the 99% case; if you want to render items then you're on your own.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yep, fair enough on the streamlining part.

props: IItemListRendererProps<any>,
noResults?: React.ReactNode,
initialContent?: React.ReactNode | null,
): React.ReactNode {
if (props.query.length === 0 && initialContent !== undefined) {
return initialContent;
}
const items = props.filteredItems.map(props.renderItem).filter(item => item != null);
return items.length > 0 ? items : noResults;
}

private itemsParentRef?: HTMLElement | null;
private refHandlers = {
itemsParent: (ref: HTMLElement | null) => (this.itemsParentRef = ref),
Expand All @@ -158,16 +190,22 @@ export class QueryList<T> extends React.Component<IQueryListProps<T>, IQueryList
private shouldCheckActiveItemInViewport: boolean = false;

public render() {
const { className, items, renderer, query } = this.props;
const { className, items, renderer, query, itemListRenderer = this.defaultMenuRenderer } = this.props;
const { filteredItems } = this.state;
return renderer({
className,
filteredItems,
handleItemSelect: this.handleItemSelect,
handleKeyDown: this.handleKeyDown,
handleKeyUp: this.handleKeyUp,
items,
itemsParentRef: this.refHandlers.itemsParent,
itemList: itemListRenderer({
filteredItems,
items,
itemsParentRef: this.refHandlers.itemsParent,
query,
renderItem: this.renderItem,
}),
query,
renderItem: this.renderItem,
});
}

Expand Down Expand Up @@ -231,6 +269,28 @@ export class QueryList<T> extends React.Component<IQueryListProps<T>, IQueryList
}
}

private defaultMenuRenderer = (listProps: IItemListRendererProps<T>) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Would have suggested defaultItemListRenderer just for consistency, but that's a mouthful isn't it?

const { initialContent, noResults } = this.props;
const menuContent = QueryList.renderFilteredItems(listProps, noResults, initialContent);
return <Menu ulRef={listProps.itemsParentRef}>{menuContent}</Menu>;
};

private renderItem = (item: T, index?: number) => {
const { activeItem, query } = this.props;
const matchesPredicate = this.state.filteredItems.indexOf(item) >= 0;
Copy link
Contributor

@reiv reiv Mar 16, 2018

Choose a reason for hiding this comment

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

I know this isn't new, but wouldn't it have been better in hindsight to cache the filtered items as an ES6 Set (or anything that's not O(N), really) to speed up this lookup?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, definitely a pain point in my head. we should do such a refactor.

const modifiers: IItemModifiers = {
active: activeItem === item,
disabled: false,
matchesPredicate,
};
return this.props.itemRenderer(item, {
handleClick: e => this.handleItemSelect(item, e),
index,
modifiers,
query,
});
};

private getActiveElement() {
if (this.itemsParentRef != null) {
return this.itemsParentRef.children.item(this.getActiveIndex()) as HTMLElement;
Expand Down Expand Up @@ -295,24 +355,6 @@ export class QueryList<T> extends React.Component<IQueryListProps<T>, IQueryList
const nextActiveIndex = Utils.clamp(this.getActiveIndex() + direction, 0, maxIndex);
Utils.safeInvoke(this.props.onActiveItemChange, filteredItems[nextActiveIndex]);
}

private renderItem = (item: T, index?: number) => {
const { activeItem, itemListPredicate, itemPredicate = () => true, query } = this.props;
const matchesPredicate = Utils.isFunction(itemListPredicate)
? this.state.filteredItems.indexOf(item) >= 0
: itemPredicate(query, item, index);
const modifiers: IItemModifiers = {
active: activeItem === item,
disabled: false,
matchesPredicate,
};
return this.props.itemRenderer(item, {
handleClick: e => this.handleItemSelect(item, e),
index,
modifiers,
query,
});
};
}

function pxToNumber(value: string | null) {
Expand Down
Loading