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

Handling Dropdown content resize #70

Merged
merged 11 commits into from
May 23, 2019
Merged
Show file tree
Hide file tree
Changes from 8 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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,8 @@
"react-day-picker": "^7.2.4",
"react-material-icon-svg": "1.7.0",
"react-popper": "^1.3.3",
"react-transition-group": "^2.4.0"
"react-transition-group": "^2.4.0",
"resize-observer-polyfill": "^1.5.1"
Copy link
Contributor Author

Choose a reason for hiding this comment

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

},
"postcss": {},
"jest": {
Expand Down
153 changes: 110 additions & 43 deletions src/components/Dropdown/Dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,14 @@ import * as PropTypes from 'prop-types';
import memoizeOne from 'memoize-one';
import cssClassNames from 'classnames/bind';
import { Manager, Reference, Popper } from 'react-popper';
import ResizeObserver from 'resize-observer-polyfill';
import styles from './style.scss';
import getMergedClassNames from '../../utils/getMergedClassNames';
import { KeyCodes } from '../../constants/keyCodes';

const cx = cssClassNames.bind(styles);

class Dropdown extends React.PureComponent {
static defaultProps = {
modifiers: {},
zIndex: 20,
closeOnEscPress: true,
closeOnEnterPress: false
};

static buildPopperModifiers(modifiers) {
const { offset, flip, hide, preventOverflow, arrow, ...rest } = modifiers;
return {
Expand All @@ -40,6 +34,7 @@ class Dropdown extends React.PureComponent {
componentDidMount() {
if (this.props.isVisible) {
this.addEventHandlers();
this.attachResizeObserver();
}
}

Expand All @@ -49,18 +44,21 @@ class Dropdown extends React.PureComponent {

if (isShown) {
this.addEventHandlers();
this.attachResizeObserver();
if (this.popupRef) {
this.popupRef.focus({ preventScroll: true });
}
}

if (isHidden) {
this.removeEventHandlers();
this.detachResizeObserver();
}
}

componentWillUnmount() {
this.removeEventHandlers();
this.detachResizeObserver();
}

getModifiers = memoizeOne(Dropdown.buildPopperModifiers);
Expand Down Expand Up @@ -88,22 +86,51 @@ class Dropdown extends React.PureComponent {
};

handleKeyDown = event => {
if (this.props.onClose) {
const isEscKeyPressed = event.keyCode === KeyCodes.esc;
const isEnterKeyPressed = event.keyCode === KeyCodes.enter;
const { keyCode } = event;
const {
closeKeyCodes,
closeOnEnterPress,
closeOnEscPress,
onClose
} = this.props;

if (onClose) {
const isEscKeyPressed = keyCode === KeyCodes.esc;
const isEnterKeyPressed = keyCode === KeyCodes.enter;
const isCustomCloseKeyPressed =
closeKeyCodes && closeKeyCodes.includes(keyCode);

if (
(this.props.closeOnEscPress && isEscKeyPressed) ||
(this.props.closeOnEnterPress && isEnterKeyPressed)
(closeOnEscPress && isEscKeyPressed) ||
(closeOnEnterPress && isEnterKeyPressed) ||
isCustomCloseKeyPressed
) {
this.props.onClose();
onClose();
if (this.triggerRef) {
this.triggerRef.focus();
}
}
}
};

attachResizeObserver = () => {
// to boost component performance resize observer should be optional
if (this.props.shouldUpdateOnResize && this.popupRef) {
this.observer = new ResizeObserver(() => {
if (this.popperScheduleUpdate) {
this.popperScheduleUpdate();
}
});
this.observer.observe(this.popupRef);
}
};

detachResizeObserver = () => {
if (this.observer) {
this.observer.disconnect();
}
};

addEventHandlers = () => {
document.addEventListener('keydown', this.handleKeyDown, true);
document.addEventListener('click', this.handleDocumentClick);
Expand All @@ -114,9 +141,14 @@ class Dropdown extends React.PureComponent {
document.removeEventListener('click', this.handleDocumentClick);
};

render() {
const { children, className, triggerRenderer, isVisible } = this.props;

renderDropdownContent = ({
ref,
style,
placement,
arrowProps,
scheduleUpdate
}) => {
const { className, isVisible, zIndex, children, modifiers } = this.props;
const mergedClassNames = getMergedClassNames(
cx({
dropdown: true,
Expand All @@ -125,41 +157,59 @@ class Dropdown extends React.PureComponent {
className
);

const modifiers = this.getModifiers(this.props.modifiers);
const computedModifiers = this.getModifiers(modifiers);

// updating `popperScheduleUpdate` reference used in resize observer
this.popperScheduleUpdate = scheduleUpdate;

return (
<div
ref={ref}
tabIndex={0}
style={{ ...style, zIndex }}
data-placement={placement}
className={mergedClassNames}
>
{children}
{computedModifiers.arrow.enabled && (
<div
ref={arrowProps.ref}
className={styles.dropdown__arrow}
data-placement={placement}
style={arrowProps.style}
/>
)}
</div>
);
};

render() {
const {
placement,
triggerRenderer,
eventsEnabled,
positionFixed,
referenceElement,
isVisible
} = this.props;

const computedModifiers = this.getModifiers(this.props.modifiers);

return (
<Manager>
{triggerRenderer && (
<Reference innerRef={this.setTriggerRef}>{triggerRenderer}</Reference>
)}
{this.props.isVisible && (
{isVisible && (
<Popper
innerRef={this.setPopupRef}
placement={this.props.placement || 'bottom-start'}
modifiers={modifiers}
eventsEnabled={this.props.eventsEnabled}
positionFixed={this.props.positionFixed}
referenceElement={this.props.referenceElement}
placement={placement || 'bottom-start'}
kamilmateusiak marked this conversation as resolved.
Show resolved Hide resolved
modifiers={computedModifiers}
eventsEnabled={eventsEnabled}
positionFixed={positionFixed}
referenceElement={referenceElement}
>
{({ ref, style, placement, arrowProps }) => (
<div
ref={ref}
tabIndex={0}
style={{ ...style, zIndex: this.props.zIndex }}
data-placement={placement}
className={mergedClassNames}
>
{children}
{modifiers.arrow.enabled && (
<div
ref={arrowProps.ref}
className={styles.dropdown__arrow}
data-placement={placement}
style={arrowProps.style}
/>
)}
</div>
)}
{this.renderDropdownContent}
</Popper>
)}
</Manager>
Expand All @@ -168,10 +218,14 @@ class Dropdown extends React.PureComponent {
}

Dropdown.propTypes = {
children: PropTypes.node.isRequired,
children: PropTypes.node,
className: PropTypes.string,
closeOnEscPress: PropTypes.bool,
closeOnEnterPress: PropTypes.bool,
/**
* you can specify which key press should trigger Dropdown close
*/
closeKeyCodes: PropTypes.arrayOf(PropTypes.number),
eventsEnabled: PropTypes.bool,
isVisible: PropTypes.bool.isRequired,
modifiers: PropTypes.object,
Expand All @@ -197,9 +251,22 @@ Dropdown.propTypes = {
clientWidth: PropTypes.number.isRequired,
clientHeight: PropTypes.number.isRequired
}),
/**
* Pass `true` when it's possible that content of your dropdown will resize
* (e.g removing list items on select)
*/
shouldUpdateOnResize: PropTypes.bool,
triggerRenderer: PropTypes.func,
zIndex: PropTypes.number,
onClose: PropTypes.func
};

Dropdown.defaultProps = {
modifiers: {},
zIndex: 20,
closeOnEscPress: true,
closeOnEnterPress: false,
shouldUpdateOnResize: false
};

export default Dropdown;
65 changes: 57 additions & 8 deletions src/components/Dropdown/DropdownList.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,27 @@ import findNextFocusableItem from '../../helpers/find-next-focusable-item';
const baseClass = 'dropdown';

class DropdownList extends React.PureComponent {
state = {
focusedElement: null
};
constructor(props) {
super(props);

this.state = {
focusedElement: (props.items[0] && props.items[0].itemId) || null,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

autofocus first item on component create

itemsCount: props.items.length
};
}

static getDerivedStateFromProps(props, state) {
if (
props.autoFocusOnItemsCountChange &&
props.items.length !== state.itemsCount
) {
return {
focusedElement: (props.items[0] && props.items[0].itemId) || null,
itemsCount: props.items.length
};
}
return null;
}

componentDidMount() {
document.addEventListener('keydown', this.onKeydown);
Expand All @@ -31,8 +49,9 @@ class DropdownList extends React.PureComponent {
this.handleArrowKeyUse(event);
}

if (keyCode === KeyCodes.enter) {
this.handleEnterKeyUse();
if (this.isItemSelectKeyCode(keyCode)) {
event.preventDefault();
this.handleSelectKeyUse();
}
};

Expand All @@ -48,7 +67,7 @@ class DropdownList extends React.PureComponent {
return this.hoverCallbacks[itemKey];
};

handleEnterKeyUse = () => {
handleSelectKeyUse = () => {
const { focusedElement } = this.state;

if (focusedElement !== null) {
Expand Down Expand Up @@ -104,6 +123,16 @@ class DropdownList extends React.PureComponent {
);
};

isItemSelectKeyCode = keyCode => {
const { itemSelectKeyCodes } = this.props;

if (itemSelectKeyCodes && itemSelectKeyCodes.includes(keyCode)) {
return true;
}

return false;
};

scrollItems = () => {
if (!this.listRef.current) {
return;
Expand Down Expand Up @@ -142,7 +171,14 @@ class DropdownList extends React.PureComponent {
listRef = React.createRef();

render() {
const { className, items, getItemBody, ...restProps } = this.props;
const {
className,
items,
getItemBody,
itemSelectKeyCodes,
autoFocusOnItemsCountChange,
...restProps
} = this.props;

const mergedClassNames = getMergedClassNames(
styles[`${baseClass}__list`],
Expand Down Expand Up @@ -188,7 +224,12 @@ class DropdownList extends React.PureComponent {
}

DropdownList.propTypes = {
autoFocusOnItemsCountChange: PropTypes.bool,
className: PropTypes.string,
defaultFocusedItemId: PropTypes.oneOfType([
Copy link
Contributor

Choose a reason for hiding this comment

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

Where this prop is used? I can't find it in the code.

Copy link
Contributor Author

@kamilmateusiak kamilmateusiak May 23, 2019

Choose a reason for hiding this comment

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

leftover, good catch :)

PropTypes.string,
PropTypes.number
]),
items: PropTypes.arrayOf(
PropTypes.shape({
className: PropTypes.string,
Expand All @@ -205,7 +246,15 @@ DropdownList.propTypes = {
})
).isRequired,
getItemBody: PropTypes.func,
onScroll: PropTypes.func
onScroll: PropTypes.func,
/**
* you can specify which key press should trigger list item select
*/
itemSelectKeyCodes: PropTypes.arrayOf(PropTypes.number)
};

DropdownList.defaultProps = {
itemSelectKeyCodes: [KeyCodes.enter]
};

export default DropdownList;
1 change: 1 addition & 0 deletions src/components/Dropdown/DropdownListItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const baseClass = 'dropdown__list-item';
class DropdownListItem extends React.PureComponent {
handleClick = e => {
if (!this.props.isDisabled && this.props.onItemSelect) {
e.nativeEvent.stopImmediatePropagation();
this.props.onItemSelect(this.props.itemId);
}
if (this.props.onClick) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ exports[`Archives | Components | FiltersMenu renders correctly 1`] = `
/>
}
isDisabled={true}
isFocused={false}
isFocused={true}
isSelected={false}
itemId={1}
onItemSelect={[MockFunction]}
Expand Down
Loading