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

[Labs] new TagInput component! #1232

Merged
merged 14 commits into from
Jun 16, 2017
1 change: 1 addition & 0 deletions packages/core/src/common/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* and https://github.com/palantir/blueprint/blob/master/PATENTS
*/

export const BACKSPACE = 8;
export const TAB = 9;
export const ENTER = 13;
export const SHIFT = 16;
Expand Down
9 changes: 5 additions & 4 deletions packages/core/src/components/tag/tag.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import { isFunction } from "../../common/utils";

import * as Classes from "../../common/classes";

export interface ITagProps extends IProps, IIntentProps, React.HTMLProps<HTMLSpanElement> {
export interface ITagProps extends IProps, IIntentProps, React.HTMLAttributes<Tag> {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

💥 HTMLAttributes does not include ref so it avoids the nasty { ref, ...htmlInputProps } spread we've had to do! i'll go refactor other usages separately.

/**
* Click handler for remove button.
* Button will only be rendered if this prop is defined.
*/
onRemove?: (e: React.MouseEvent<HTMLSpanElement>) => void;
onRemove?: (e: React.MouseEvent<HTMLButtonElement>) => void;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

previous type was incorrect, as the onClick is applied to a <button>

}

@PureRender
Expand All @@ -31,8 +31,9 @@ export class Tag extends React.Component<ITagProps, {}> {
const tagClasses = classNames(Classes.TAG, Classes.intentClass(intent), {
[Classes.TAG_REMOVABLE]: onRemove != null,
}, className);
const button =
isFunction(onRemove) ? <button type="button" className={Classes.TAG_REMOVE} onClick={onRemove} /> : undefined;
const button = isFunction(onRemove)
? <button type="button" className={Classes.TAG_REMOVE} onClick={onRemove} />
: undefined;

return (
<span {...removeNonHTMLProps(this.props)} className={tagClasses}>
Expand Down
1 change: 1 addition & 0 deletions packages/labs/examples/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
*/

export * from "./selectExample";
export * from "./tagInputExample";
2 changes: 1 addition & 1 deletion packages/labs/examples/selectExample.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class SelectExample extends BaseExample<ISelectExampleState> {
/>,
<Switch
key="minimal"
label="Minimal style"
label="Minimal popover style"
checked={this.state.minimal}
onChange={this.handleMinimalChange}
/>,
Expand Down
90 changes: 90 additions & 0 deletions packages/labs/examples/tagInputExample.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2017 Palantir Technologies, Inc. All rights reserved.
* Licensed under the BSD-3 License as modified (the “License”); you may obtain a copy
* of the license at https://github.com/palantir/blueprint/blob/master/LICENSE
* and https://github.com/palantir/blueprint/blob/master/PATENTS
*/

import * as React from "react";

import { Classes, Intent, ITagProps, Switch } from "@blueprintjs/core";
import { BaseExample, handleBooleanChange } from "@blueprintjs/docs";
import { TagInput } from "../src/tagInput/tagInput";

const INTENTS = [Intent.NONE, Intent.PRIMARY, Intent.SUCCESS, Intent.DANGER, Intent.WARNING];

export interface ITagInputExampleState {
intent?: boolean;
large?: boolean;
minimal?: boolean;
values?: string[];
}

export class TagInputExample extends BaseExample<ITagInputExampleState> {
public state: ITagInputExampleState = {
intent: false,
large: false,
minimal: false,
values: ["Albert", "Bartholomew", "Casper"],
};

private handleIntentChange = handleBooleanChange((intent) => this.setState({ intent }));
private handleLargeChange = handleBooleanChange((large) => this.setState({ large }));
private handleMinimalChange = handleBooleanChange((minimal) => this.setState({ minimal }));

protected renderExample() {
const { large, values } = this.state;

// define a new function every time so switch changes will cause it to re-render
// NOTE: avoid this pattern in your app (use this.getTagProps instead); this is only for
// example purposes!!
const getTagProps = (_v: string, index: number): ITagProps => ({
className: this.state.minimal ? Classes.MINIMAL : "",
intent: this.state.intent ? INTENTS[index % INTENTS.length] : Intent.NONE,
});

return (
<TagInput
className={large ? Classes.LARGE : ""}
onAdd={this.handleAdd}
onRemove={this.handleRemove}
tagProps={getTagProps}
values={values}
/>
);
}

protected renderOptions() {
return [
[
<Switch
checked={this.state.large}
label="Large"
key="large"
onChange={this.handleLargeChange}
/>,
], [
<label key="heading" className={Classes.LABEL}>Tag props</label>,
<Switch
checked={this.state.minimal}
label="Use minimal tags"
key="minimal"
onChange={this.handleMinimalChange}
/>,
<Switch
checked={this.state.intent}
label="Cycle through intents"
key="intent"
onChange={this.handleIntentChange}
/>,
],
];
}

private handleAdd = (newValue: string) => {
this.setState({ values: [...this.state.values, newValue] });
}
private handleRemove = (_removedValue: string, removedIndex: number) => {
this.setState({ values: this.state.values.filter((_, i) => i !== removedIndex) });
}
}
2 changes: 2 additions & 0 deletions packages/labs/src/blueprint-labs.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

@import "~@blueprintjs/core/src/common/variables";

@import "./tagInput/tag-input";

$select-popover-max-height: $pt-grid-size * 20 !default;
$select-popover-max-width: $pt-grid-size * 40 !default;

Expand Down
1 change: 1 addition & 0 deletions packages/labs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@

export * from "./inputList";
export * from "./select";
export * from "./tagInput/tagInput";
12 changes: 12 additions & 0 deletions packages/labs/src/labs.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,15 @@ An object with the following properties will be passed to an `InputList` `render
This interface is generic, accepting a type parameter `<T>` for an item in the list.

@interface IInputListRendererProps

@## TagInput

`TagInput` renders [`Tag`](#core/components/tag)s inside an input, followed by an actual text input. The container is merely styled to look like a Blueprint input; the actual editable element appears after the last tag. Clicking anywhere on the container will focus the text input for seamless interaction.

@reactExample TagInputExample

`TagInput` must be controlled, meaning the `values` prop is required and event handlers are strongly suggested. The component controls the text input internally to support the `onAdd` event, but you can wrest control by supplying your own `inputProps`.

`Tag` appearance can be customized with `tagProps`: supply an object to apply the same props to every tag, or supply a callback to apply dynamic props per tag. Tag `values` must be an array of strings so you may need a transformation step between your state and these props.

@interface ITagInputProps
51 changes: 51 additions & 0 deletions packages/labs/src/tagInput/tag-input.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright 2017 Palantir Technologies, Inc. All rights reserved.
* Licensed under the BSD-3 License as modified (the “License”); you may obtain a copy
* of the license at https://github.com/palantir/blueprint/blob/master/LICENSE
* and https://github.com/palantir/blueprint/blob/master/PATENTS
*/

@import "~@blueprintjs/core/src/common/variables";
@import "~@blueprintjs/core/src/components/forms/common";
@import "~@blueprintjs/core/src/components/tag/common";

$input-padding: ($pt-input-height - $tag-height) / 2;

.pt-tag-input {
display: flex;
flex-wrap: wrap;
cursor: text;
height: auto;
padding: $input-padding 0 0 $input-padding;

.pt-tag {
margin: 0 $input-padding $input-padding 0;
}

.pt-input-invisible {
// input fills remaining line
flex: 1 1 auto;
margin-bottom: $input-padding;
// essentially a min-width, cuz flex allows it to grow or shrink:
width: $pt-grid-size * 10;
line-height: $tag-height;
}

&.pt-large {
height: auto;
}

&.pt-active {
box-shadow: input-transition-shadow($input-shadow-color-focus, true), $input-box-shadow-focus;
background-color: $input-background-color;
}
}

// TODO: this is probably a useful modifier that we should pull into core, and use in EditableText
.pt-input-invisible {
// reset browser input styles (we're using an input solely because you can type in it)
border: none;
box-shadow: none;
background: none;
padding: 0;
}
137 changes: 137 additions & 0 deletions packages/labs/src/tagInput/tagInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
* Copyright 2017 Palantir Technologies, Inc. All rights reserved.
* Licensed under the BSD-3 License as modified (the “License”); you may obtain a copy
* of the license at https://github.com/palantir/blueprint/blob/master/LICENSE
* and https://github.com/palantir/blueprint/blob/master/PATENTS
*/

import * as classNames from "classnames";
import * as PureRender from "pure-render-decorator";
import * as React from "react";

import { AbstractComponent, Classes, HTMLInputProps, IProps, ITagProps, Keys, Tag, Utils } from "@blueprintjs/core";

export interface ITagInputProps extends IProps {
/** React props to pass to the `<input>` element */
inputProps?: HTMLInputProps;

/**
* Callback invoked when a new tag is added by the user pressing `enter` on the input.
* Receives the current value of the input field. New tags are expected to be appended to
* the list.
*/
onAdd?: (value: string) => void;

/**
* Callback invoked when the user clicks the X button on a tag.
* Receives value and index of removed tag.
*/
onRemove?: (value: string, index: number) => void;

/**
* React props to pass to each `Tag`. Provide an object to pass the same props to every tag,
* or a function to customize props per tag.
*
* If you define `onRemove` here then you will have to implement your own tag removal
* handling as the `TagInput` `onRemove` prop will never be invoked.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

...TagInput's own handler will never...

*/
tagProps?: ITagProps | ((value: string, index: number) => ITagProps);

/** Controlled tag values. */
values: string[];
}

export interface ITagInputState {
inputValue?: string;
isInputFocused?: boolean;
}

@PureRender
export class TagInput extends AbstractComponent<ITagInputProps, ITagInputState> {
public static displayName = "Blueprint.TagInput";

public static defaultProps: Partial<ITagInputProps> = {
inputProps: {},
tagProps: {},
};

public state: ITagInputState = { inputValue: "", isInputFocused: false };

private inputElement: HTMLInputElement;
private refHandlers = {
input: (ref: HTMLInputElement) => {
this.inputElement = ref;
const refHandler = this.props.inputProps.ref;
if (Utils.isFunction(refHandler)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we use Utils.safeInvoke?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

great Q!

typings problems with safeInvoke: refHandler is typed string | (ref) => void so i must use isFunction for the type guard. (note that this is exactly what safeInvoke does inside, but it expects functions. I think we can relax those types and maybe also make it a type guard?)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

seems there's not much to be done to improve safeInvoke usage. if i make it accept non-functions then it loses all type safety :(. adding code comment instead.

refHandler(ref);
}
},
};

public render() {
const { inputProps, tagProps, values } = this.props;

const classes = classNames(Classes.INPUT, "pt-tag-input", {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

note: no constant

[Classes.ACTIVE]: this.state.isInputFocused,
}, this.props.className);

const tags = values.map((tag, i) => {
const props = Utils.isFunction(tagProps) ? tagProps(tag, i) : tagProps;
return <Tag data-tag-index={i} key={tag + "__" + i} onRemove={this.handleRemoveTag} {...props}>{tag}</Tag>;
});
return (
<div className={classes} onClick={this.handleContainerClick}>
{tags}
<input
value={this.state.inputValue}
{...inputProps}
onBlur={this.handleInputBlur}
onFocus={this.handleInputFocus}
onChange={this.handleInputChange}
onKeyDown={this.handleInputKeyDown}
ref={this.refHandlers.input}
className={classNames("pt-input-invisible", inputProps.className)}
/>
</div>
);
}

private handleContainerClick = () => {
if (this.inputElement != null) {
this.inputElement.focus();
Copy link
Contributor

Choose a reason for hiding this comment

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

If I'm blurred and then click a tag's remove button, is it still expected that the input focus?

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 cuz you've clicked in the .pt-input (the thing that looks like a text input)

}
}

private handleInputBlur = (event: React.FocusEvent<HTMLInputElement>) => {
this.setState({ isInputFocused: false });
Utils.safeInvoke(this.props.inputProps.onBlur, event);
}

private handleInputFocus = (event: React.FocusEvent<HTMLInputElement>) => {
this.setState({ isInputFocused: true });
Utils.safeInvoke(this.props.inputProps.onFocus, event);
}

private handleInputChange = (event: React.KeyboardEvent<HTMLInputElement>) => {
this.setState({ inputValue: event.currentTarget.value });
Utils.safeInvoke(this.props.inputProps.onChange, event);
}

private handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
const { value } = event.currentTarget;
if (event.which === Keys.ENTER && value.length > 0) {
Utils.safeInvoke(this.props.onAdd, value);
Copy link
Contributor

Choose a reason for hiding this comment

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

Elsewhere, we setState before invoking the callback. Is the switch here intentional?

this.setState({ inputValue: "" });
} else if (event.which === Keys.BACKSPACE && value.length === 0) {
const lastIndex = this.props.values.length - 1;
Utils.safeInvoke(this.props.onRemove, this.props.values[lastIndex], lastIndex);
}
Utils.safeInvoke(this.props.inputProps.onKeyDown, event);
}

private handleRemoveTag = (event: React.MouseEvent<HTMLSpanElement>) => {
// using data attribute to simplify callback logic -- one handler for all children
Copy link
Contributor

Choose a reason for hiding this comment

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

🥇

const index = +event.currentTarget.parentElement.getAttribute("data-tag-index");
Utils.safeInvoke(this.props.onRemove, this.props.values[index], index);
}
}
1 change: 1 addition & 0 deletions packages/labs/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@

import "./inputListTests";
import "./selectTests";
import "./tagInputTests";
Loading