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

refactor(react): update ContentSwitcher and Switch to hooks #3302

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
chore: check-in work
  • Loading branch information
joshblack committed Jun 28, 2019
commit 839b141d9429955919cbccd4acd0c45e9e690051
192 changes: 88 additions & 104 deletions packages/react/src/components/ContentSwitcher/ContentSwitcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,125 +6,109 @@
*/

import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import React, {
Children,
cloneElement,
useEffect,
useRef,
useState,
} from 'react';
import cx from 'classnames';
import { settings } from 'carbon-components';
import { composeEventHandlers } from '../../tools/events';
import { getNextIndex } from '../../tools/keyboard-navigation';
import { matches, keyCodes } from '../../tools/key';

const { prefix } = settings;

export default class ContentSwitcher extends React.Component {
/**
* The DOM references of child `<Switch>`.
* @type {Array<Element>}
* @private
*/
_switchRefs = [];

state = {};

static propTypes = {
/**
* Pass in Switch components to be rendered in the ContentSwitcher
*/
children: PropTypes.node,

/**
* Specify an optional className to be added to the container node
*/
className: PropTypes.string,

/**
* Specify an `onChange` handler that is called whenever the ContentSwitcher
* changes which item is selected
*/
onChange: PropTypes.func.isRequired,

/**
* Specify a selected index for the initially selected content
*/
selectedIndex: PropTypes.number,
};

static defaultProps = {
selectedIndex: 0,
};
function ContentSwitcher({
children,
lovemecomputer marked this conversation as resolved.
Show resolved Hide resolved
className: customClassName,
onChange,
selectedIndex: controlledSelectedIndex = 0,
...rest
}) {
const switchRefs = [];
const className = cx(`${prefix}--content-switcher`, customClassName);
const [selectedIndex, setSelectedIndex] = useState(controlledSelectedIndex);

useEffect(() => {
setSelectedIndex(selectedIndex => {
if (selectedIndex !== controlledSelectedIndex) {
return controlledSelectedIndex;
}
return selectedIndex;
});
}, [controlledSelectedIndex]);

useEffect(() => {
const ref = switchRefs[selectedIndex];
if (ref && document.activeElement !== ref.current) {
ref.focus && ref.focus();
joshblack marked this conversation as resolved.
Show resolved Hide resolved
onChange(selectedIndex);
}
}, [selectedIndex]);

static getDerivedStateFromProps({ selectedIndex }, state) {
const { prevSelectedIndex } = state;
return prevSelectedIndex === selectedIndex
? null
: {
selectedIndex,
prevSelectedIndex: selectedIndex,
};
function handleItemRef(index) {
return ref => {
switchRefs[index] = ref;
};
}

handleItemRef = index => ref => {
this._switchRefs[index] = ref;
};

handleChildChange = data => {
// the currently selected child index
const { selectedIndex } = this.state;
// the newly selected child index
const { index } = data;
const { key } = data;
function onClick(index) {
if (selectedIndex !== index) {
setSelectedIndex(index);
}
}

if (matches(data, [keyCodes.RIGHT, keyCodes.LEFT])) {
function onKeyDown(event, index) {
if (matches(event, [keyCodes.RIGHT, keyCodes.LEFT])) {
const nextIndex = getNextIndex(
key,
event.key || event.which,
selectedIndex,
this.props.children.length
);
this.setState(
{
selectedIndex: nextIndex,
},
() => {
const switchRef = this._switchRefs[nextIndex];
switchRef && switchRef.focus();
this.props.onChange(data);
}
children.length
);
} else {
if (selectedIndex !== index) {
this.setState({ selectedIndex: index }, () => {
const switchRef = this._switchRefs[index];
switchRef && switchRef.focus();
this.props.onChange(data);
});
}
console.log(nextIndex);
setSelectedIndex(nextIndex);
}
};
}

render() {
const {
children,
className,
selectedIndex, // eslint-disable-line no-unused-vars
...other
} = this.props;
return (
<div className={className} {...rest}>
{Children.map(children, (child, index) =>
cloneElement(child, {
index,
onClick: composeEventHandlers([onClick, child.props.onClick]),
onKeyDown: onKeyDown,
selected: index === selectedIndex,
ref: handleItemRef(index),
})
)}
</div>
);
}

const classes = classNames(`${prefix}--content-switcher`, className);
ContentSwitcher.propTypes = {
/**
* Pass in Switch components to be rendered in the ContentSwitcher
*/
children: PropTypes.node,

return (
<div {...other} className={classes}>
{React.Children.map(children, (child, index) =>
React.cloneElement(child, {
index,
onClick: composeEventHandlers([
this.handleChildChange,
child.props.onClick,
]),
onKeyDown: this.handleChildChange,
selected: index === this.state.selectedIndex,
ref: this.handleItemRef(index),
})
)}
</div>
);
}
}
/**
* Specify an optional className to be added to the container node
*/
className: PropTypes.string,

/**
* Specify an `onChange` handler that is called whenever the ContentSwitcher
* changes which item is selected
*/
onChange: PropTypes.func.isRequired,

/**
* Specify a selected index for the initially selected content
*/
selectedIndex: PropTypes.number,
};

export default ContentSwitcher;
108 changes: 108 additions & 0 deletions packages/react/src/components/ContentSwitcher/Switch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/

import { settings } from 'carbon-components';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';

const { prefix } = settings;

const Switch = React.forwardRef(function Switch(props, tabRef) {
const {
className: customClassName,
index,
onClick,
onKeyDown,
name,
selected,
text,
...rest
} = props;

const className = cx({
[`${prefix}--content-switcher-btn`]: true,
[`${prefix}--content-switcher--selected`]: selected,
[customClassName]: !!customClassName,
});

function handleOnClick(event) {
// TODO: do we still need this with `type="button"`?
event.preventDefault();
onClick(index);
}

function handleOnKeyDown(event) {
onKeyDown(event, index);
}

return (
<button
aria-selected={selected}
className={className}
ref={tabRef}
role="tab"
onClick={handleOnClick}
onKeyDown={handleOnKeyDown}
tabIndex={selected ? '0' : '-1'}
type="button"
{...rest}>
<span className={`${prefix}--content-switcher__label`}>{text}</span>
</button>
);
});

Switch.displayName = 'Switch';

Switch.propTypes = {
/**
* Specify an optional className to be added to your Switch
*/
className: PropTypes.string,

/**
* The index of your Switch in your ContentSwitcher that is used for event handlers.
* Reserved for usage in ContentSwitcher
*/
index: PropTypes.number,

/**
* Provide the name of your Switch that is used for event handlers
*/
name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

/**
* A handler that is invoked when a user clicks on the control.
* Reserved for usage in ContentSwitcher
*/
onClick: PropTypes.func,

/**
* A handler that is invoked on the key down event for the control.
* Reserved for usage in ContentSwitcher
*/
onKeyDown: PropTypes.func,

/**
* Whether your Switch is selected. Reserved for usage in ContentSwitcher
*/
selected: PropTypes.bool,

/**
* Provide the contents of your Switch
*/
text: PropTypes.string.isRequired,
};

Switch.defaultProps = {
selected: false,
text: 'Provide text',
onClick: () => {},
onKeyDown: () => {},
};

export default Switch;
Loading