Skip to content

Instantly share code, notes, and snippets.

@ohadlevy
Created August 28, 2018 11:28
Show Gist options
  • Save ohadlevy/9b3d78de56f6544c4669c54ad38ceb84 to your computer and use it in GitHub Desktop.
Save ohadlevy/9b3d78de56f6544c4669c54ad38ceb84 to your computer and use it in GitHub Desktop.
import React from 'react';
import PropTypes from 'prop-types';
import {
Grid,
Row,
Col,
Form,
FormGroup,
Dropdown,
MenuItem,
findChild,
} from 'patternfly-react';
import { NONE_TYPE, SERIALCONSOLE_TYPE, VNCCONSOLE_TYPE } from './constants';
class ConsoleSelector extends React.Component {
state = { type: NONE_TYPE };
onTypeChange(type) {
this.setState({ type });
}
getSelectedConsole() {
return this.getConsoleForType(this.state.type);
}
getConsoleForType(type) {
return (
findChild(
this.props.children,
child =>
(child.type && child.type.name === type) || child.props.type === type,
) || null
);
}
render() {
const items = {
[NONE_TYPE]: this.props.textSelectConsoleType,
[SERIALCONSOLE_TYPE]: this.props.textSerialConsole,
[VNCCONSOLE_TYPE]: this.props.textVncConsole,
};
return (
<Grid fluid>
<Form horizontal>
<FormGroup controlId="console-type" className="console-selector">
<Col>
<Dropdown id="console-type-selector">
<Dropdown.Toggle>{items[this.state.type]}</Dropdown.Toggle>
<Dropdown.Menu>
{this.getConsoleForType(SERIALCONSOLE_TYPE) && (
<MenuItem
eventKey="1"
onClick={() => this.onTypeChange(SERIALCONSOLE_TYPE)}
>
{items[SERIALCONSOLE_TYPE]}
</MenuItem>
)}
{this.getConsoleForType(VNCCONSOLE_TYPE) && (
<MenuItem
eventKey="2"
onClick={() => this.onTypeChange(VNCCONSOLE_TYPE)}
>
{items[VNCCONSOLE_TYPE]}
</MenuItem>
)}
</Dropdown.Menu>
</Dropdown>
</Col>
</FormGroup>
</Form>
<Row>
<Col>{this.getSelectedConsole()}</Col>
</Row>
</Grid>
);
}
}
const validChildrenTypes = [SERIALCONSOLE_TYPE, VNCCONSOLE_TYPE];
const childElementValidator = (propValue) => {
const children = Array.isArray(propValue) ? propValue : [propValue];
if (
!children.every(child =>
(child.type && validChildrenTypes.indexOf(child.type.name) >= 0) ||
(child.props && validChildrenTypes.indexOf(child.props.type) >= 0))
) {
return new Error('ConsoleSelector child validation failed');
}
return true;
};
ConsoleSelector.propTypes = {
/**
* Child element can be either
* - <SerialConsole> or <VncConsole>
* - or has a property "type" of value either SERIALCONSOLE_TYPE or VNCCONSOLE_TYPE
* - (useful when wrapping (composing) basic console components)
*/
children: PropTypes.oneOfType([
PropTypes.objectOf(childElementValidator),
PropTypes.arrayOf(childElementValidator),
]).isRequired,
textSelectConsoleType: PropTypes.string,
textSerialConsole: PropTypes.string,
textVncConsole: PropTypes.string,
};
ConsoleSelector.defaultProps = {
textSelectConsoleType: 'Select Console Type',
textSerialConsole: 'Serial Console',
textVncConsole: 'VNC Console',
};
export default ConsoleSelector;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment