@workday/canvas-kit-react
Version:
The parent module that contains all Workday Canvas Kit React components
72 lines (71 loc) • 2.69 kB
JavaScript
import * as React from 'react';
import { Radio } from './Radio';
import { borderRadius, space } from '@workday/canvas-kit-react/tokens';
import { ErrorType, getErrorColors, styled, } from '@workday/canvas-kit-react/common';
const Container = styled('div')({
display: 'inline-block',
boxSizing: 'border-box',
borderRadius: borderRadius.m,
padding: `${space.xxxs} ${space.xs}`,
margin: `0 -${space.xs}`,
'& > div': {
margin: `${space.xxs} ${space.zero}`,
alignItems: 'flex-start',
'> div': {
flex: '0 0 auto',
},
'&:first-of-type': {
marginTop: '6px',
},
'&:last-child': {
marginBottom: space.xxxs,
},
},
}, ({ grow }) => grow && { width: '100%' }, ({ error, theme }) => {
const errorColors = getErrorColors(error, theme);
return {
transition: '100ms box-shadow',
boxShadow: errorColors.outer !== errorColors.inner
? `inset 0 0 0 1px ${errorColors.outer}, inset 0 0 0 3px ${errorColors.inner}`
: `inset 0 0 0 2px ${errorColors.inner}`,
};
});
class RadioGroup extends React.Component {
constructor() {
super(...arguments);
this.renderChild = (child, index, value) => {
if (typeof child.type === typeof Radio) {
const childProps = child.props;
const checked = typeof value === 'number' ? index === value : childProps.value === value;
const name = this.props.name ? this.props.name : childProps.name;
return React.cloneElement(child, {
checked,
name,
onChange: this.onRadioChange.bind(this, childProps.onChange, index),
});
}
return child;
};
this.onRadioChange = (existingOnChange, index, event) => {
if (existingOnChange) {
existingOnChange(event);
}
const target = event.currentTarget;
if (target && this.props.onChange) {
if (target.value) {
this.props.onChange(target.value);
}
else {
this.props.onChange(index);
}
}
};
}
render() {
const { value = 0, children, error, onChange, grow, ...elemProps } = this.props;
return (React.createElement(Container, { error: error, grow: grow, ...elemProps }, React.Children.map(children, (child, index) => this.renderChild(child, index, value))));
}
}
RadioGroup.ErrorType = ErrorType;
export { RadioGroup };
RadioGroup.ErrorType = ErrorType;