radio.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /* eslint-disable prefer-destructuring */
  2. import React from 'react';
  3. import PropTypes from 'prop-types';
  4. import cls from 'classnames';
  5. import { noop, isUndefined, isBoolean } from 'lodash';
  6. import RadioFoundation, { RadioAdapter } from '@douyinfe/semi-foundation/radio/radioFoundation';
  7. import { RadioChangeEvent } from '@douyinfe/semi-foundation/radio/radioInnerFoundation';
  8. import { strings, radioClasses as css } from '@douyinfe/semi-foundation/radio/constants';
  9. import { getUuidShort } from '@douyinfe/semi-foundation/utils/uuid';
  10. import '@douyinfe/semi-foundation/radio/radio.scss';
  11. import BaseComponent from '../_base/baseComponent';
  12. import RadioInner from './radioInner';
  13. import Context, { RadioContextValue, RadioMode } from './context';
  14. export type RadioDisplayMode = 'vertical' | '';
  15. export type RadioType =
  16. typeof strings.TYPE_DEFAULT |
  17. typeof strings.TYPE_BUTTON |
  18. typeof strings.TYPE_CARD |
  19. typeof strings.TYPE_PURECARD;
  20. export type RadioProps = {
  21. autoFocus?: boolean;
  22. checked?: boolean;
  23. children?: React.ReactNode | undefined;
  24. defaultChecked?: boolean;
  25. value?: string | number;
  26. disabled?: boolean;
  27. prefixCls?: string;
  28. displayMode?: RadioDisplayMode;
  29. onChange?: (e: RadioChangeEvent) => void;
  30. onMouseEnter?: (e: React.MouseEvent<HTMLLabelElement>) => void;
  31. onMouseLeave?: (e: React.MouseEvent<HTMLLabelElement>) => void;
  32. mode?: RadioMode;
  33. extra?: React.ReactNode;
  34. style?: React.CSSProperties;
  35. className?: string;
  36. addonStyle?: React.CSSProperties;
  37. addonClassName?: string;
  38. type?: RadioType;
  39. 'aria-label'?: React.AriaAttributes['aria-label'];
  40. addonId?: string;
  41. extraId?: string;
  42. name?: string;
  43. preventScroll?: boolean;
  44. };
  45. export interface RadioState {
  46. hover?: boolean;
  47. addonId?: string;
  48. extraId?: string;
  49. focusVisible?: boolean;
  50. checked?: boolean;
  51. }
  52. export { RadioChangeEvent };
  53. class Radio extends BaseComponent<RadioProps, RadioState> {
  54. static contextType = Context;
  55. static propTypes = {
  56. autoFocus: PropTypes.bool,
  57. checked: PropTypes.bool,
  58. defaultChecked: PropTypes.bool,
  59. value: PropTypes.any, // Compare according to value to determine whether to select
  60. style: PropTypes.object,
  61. className: PropTypes.string,
  62. disabled: PropTypes.bool,
  63. prefixCls: PropTypes.string,
  64. displayMode: PropTypes.oneOf<RadioDisplayMode>(['vertical', '']),
  65. onChange: PropTypes.func,
  66. onMouseEnter: PropTypes.func,
  67. onMouseLeave: PropTypes.func,
  68. mode: PropTypes.oneOf(strings.MODE),
  69. extra: PropTypes.node, // extra info
  70. addonStyle: PropTypes.object,
  71. addonClassName: PropTypes.string,
  72. type: PropTypes.oneOf([strings.TYPE_DEFAULT, strings.TYPE_BUTTON, strings.TYPE_CARD, strings.TYPE_PURECARD]), // Button style type
  73. 'aria-label': PropTypes.string,
  74. preventScroll: PropTypes.bool,
  75. };
  76. static defaultProps: Partial<RadioProps> = {
  77. autoFocus: false,
  78. defaultChecked: false,
  79. value: undefined as undefined,
  80. style: undefined as undefined,
  81. onMouseEnter: noop,
  82. onMouseLeave: noop,
  83. mode: '',
  84. type: 'default'
  85. };
  86. radioEntity: RadioInner;
  87. context!: RadioContextValue;
  88. foundation: RadioFoundation;
  89. addonId: string;
  90. extraId: string;
  91. constructor(props: RadioProps) {
  92. super(props);
  93. this.state = {
  94. hover: false,
  95. addonId: props.addonId,
  96. extraId: props.extraId,
  97. checked: props.checked || props.defaultChecked || false,
  98. };
  99. this.foundation = new RadioFoundation(this.adapter);
  100. this.radioEntity = null;
  101. }
  102. componentDidUpdate(prevProps: RadioProps) {
  103. if (this.props.checked !== prevProps.checked) {
  104. if (isUndefined(this.props.checked)) {
  105. this.foundation.setChecked(false);
  106. } else if (isBoolean(this.props.checked)) {
  107. this.foundation.setChecked(this.props.checked);
  108. }
  109. }
  110. }
  111. get adapter(): RadioAdapter {
  112. return {
  113. ...super.adapter,
  114. setHover: (hover: boolean) => {
  115. this.setState({ hover });
  116. },
  117. setAddonId: () => {
  118. this.setState({ addonId: getUuidShort({ prefix: 'addon' }) });
  119. },
  120. setChecked: (checked: boolean) => {
  121. this.setState({ checked });
  122. },
  123. setExtraId: () => {
  124. this.setState({ extraId: getUuidShort({ prefix: 'extra' }) });
  125. },
  126. setFocusVisible: (focusVisible: boolean): void => {
  127. this.setState({ focusVisible });
  128. },
  129. };
  130. }
  131. isInGroup() {
  132. // eslint-disable-next-line react/destructuring-assignment
  133. return this.context && this.context.radioGroup;
  134. }
  135. focus() {
  136. this.radioEntity.focus();
  137. }
  138. blur() {
  139. this.radioEntity.blur();
  140. }
  141. onChange = (e: RadioChangeEvent) => {
  142. const { onChange } = this.props;
  143. if (this.isInGroup()) {
  144. const { radioGroup } = this.context;
  145. radioGroup.onChange && radioGroup.onChange(e);
  146. }
  147. !('checked' in this.props) && this.foundation.setChecked(e.target.checked);
  148. onChange && onChange(e);
  149. };
  150. handleMouseEnter = (e: React.MouseEvent<HTMLLabelElement>) => {
  151. this.props.onMouseEnter(e);
  152. this.foundation.setHover(true);
  153. };
  154. handleMouseLeave = (e: React.MouseEvent<HTMLLabelElement>) => {
  155. this.props.onMouseLeave(e);
  156. this.foundation.setHover(false);
  157. };
  158. handleFocusVisible = (event: React.FocusEvent) => {
  159. this.foundation.handleFocusVisible(event);
  160. }
  161. handleBlur = (event: React.FocusEvent) => {
  162. this.foundation.handleBlur();
  163. }
  164. render() {
  165. const {
  166. addonClassName,
  167. addonStyle,
  168. disabled,
  169. style,
  170. className,
  171. prefixCls,
  172. displayMode,
  173. children,
  174. extra,
  175. mode,
  176. type,
  177. value: propValue,
  178. name
  179. } = this.props;
  180. let realChecked,
  181. isDisabled,
  182. realMode,
  183. isButtonRadioGroup,
  184. isCardRadioGroup,
  185. isPureCardRadioGroup,
  186. isButtonRadioComponent,
  187. buttonSize,
  188. realPrefixCls;
  189. const { hover: isHover, addonId, extraId, focusVisible, checked, } = this.state;
  190. const props: Record<string, any> = {
  191. checked,
  192. disabled,
  193. };
  194. if (this.isInGroup()) {
  195. realChecked = this.context.radioGroup.value === propValue;
  196. isDisabled = disabled || this.context.radioGroup.disabled;
  197. realMode = this.context.mode;
  198. isButtonRadioGroup = this.context.radioGroup.isButtonRadio;
  199. isCardRadioGroup = this.context.radioGroup.isCardRadio;
  200. isPureCardRadioGroup = this.context.radioGroup.isPureCardRadio;
  201. buttonSize = this.context.radioGroup.buttonSize;
  202. realPrefixCls = prefixCls || this.context.radioGroup.prefixCls;
  203. props.checked = realChecked;
  204. props.disabled = isDisabled;
  205. } else {
  206. realChecked = checked;
  207. isDisabled = disabled;
  208. realMode = mode;
  209. isButtonRadioComponent = type === 'button';
  210. realPrefixCls = prefixCls;
  211. isButtonRadioGroup = type === strings.TYPE_BUTTON;
  212. isPureCardRadioGroup = type === strings.TYPE_PURECARD;
  213. isCardRadioGroup = type === strings.TYPE_CARD || isPureCardRadioGroup;
  214. }
  215. const isButtonRadio = typeof isButtonRadioGroup === 'undefined' ? isButtonRadioComponent : isButtonRadioGroup;
  216. const prefix = realPrefixCls || css.PREFIX;
  217. const focusOuter = isCardRadioGroup || isPureCardRadioGroup || isButtonRadio;
  218. const wrapper = cls(prefix, {
  219. [`${prefix}-disabled`]: isDisabled,
  220. [`${prefix}-checked`]: realChecked,
  221. [`${prefix}-${displayMode}`]: Boolean(displayMode),
  222. [`${prefix}-buttonRadioComponent`]: isButtonRadioComponent,
  223. [`${prefix}-buttonRadioGroup`]: isButtonRadioGroup,
  224. [`${prefix}-buttonRadioGroup-${buttonSize}`]: isButtonRadioGroup && buttonSize,
  225. [`${prefix}-cardRadioGroup`]: isCardRadioGroup,
  226. [`${prefix}-cardRadioGroup_disabled`]: isDisabled && isCardRadioGroup,
  227. [`${prefix}-cardRadioGroup_checked`]: isCardRadioGroup && realChecked && !isDisabled,
  228. [`${prefix}-cardRadioGroup_checked_disabled`]: isCardRadioGroup && realChecked && isDisabled,
  229. [`${prefix}-cardRadioGroup_hover`]: isCardRadioGroup && !realChecked && isHover && !isDisabled,
  230. [className]: Boolean(className),
  231. [`${prefix}-focus`]: focusVisible && (isCardRadioGroup || isPureCardRadioGroup),
  232. });
  233. const groupName = this.isInGroup() && this.context.radioGroup.name;
  234. const addonCls = cls({
  235. [`${prefix}-addon`]: !isButtonRadio,
  236. [`${prefix}-addon-buttonRadio`]: isButtonRadio,
  237. [`${prefix}-addon-buttonRadio-checked`]: isButtonRadio && realChecked,
  238. [`${prefix}-addon-buttonRadio-disabled`]: isButtonRadio && isDisabled,
  239. [`${prefix}-addon-buttonRadio-hover`]: isButtonRadio && !realChecked && !isDisabled && isHover,
  240. [`${prefix}-addon-buttonRadio-${buttonSize}`]: isButtonRadio && buttonSize,
  241. [`${prefix}-focus`]: focusVisible && isButtonRadio,
  242. }, addonClassName);
  243. const renderContent = () => (
  244. <>
  245. {children ? (
  246. <span className={addonCls} style={addonStyle} id={addonId} x-semi-prop="children">
  247. {children}
  248. </span>
  249. ) : null}
  250. {extra && !isButtonRadio ? (
  251. <div className={`${prefix}-extra`} id={extraId} x-semi-prop="extra">
  252. {extra}
  253. </div>
  254. ) : null}
  255. </>
  256. );
  257. return (
  258. <label
  259. style={style}
  260. className={wrapper}
  261. onMouseEnter={this.handleMouseEnter}
  262. onMouseLeave={this.handleMouseLeave}
  263. >
  264. <RadioInner
  265. {...this.props}
  266. {...props}
  267. mode={realMode}
  268. name={name ?? groupName}
  269. isButtonRadio={isButtonRadio}
  270. isPureCardRadioGroup={isPureCardRadioGroup}
  271. onChange={this.onChange}
  272. ref={(ref: RadioInner) => {
  273. this.radioEntity = ref;
  274. }}
  275. addonId={children && addonId}
  276. extraId={extra && extraId}
  277. focusInner={focusVisible && !focusOuter}
  278. onInputFocus={this.handleFocusVisible}
  279. onInputBlur={this.handleBlur}
  280. />
  281. {
  282. isCardRadioGroup ?
  283. <div className={`${prefix}-isCardRadioGroup_content`}>{renderContent()}</div> :
  284. renderContent()
  285. }
  286. </label>
  287. );
  288. }
  289. }
  290. export default Radio;