checkbox.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /* eslint-disable max-len */
  2. import React from 'react';
  3. import PropTypes from 'prop-types';
  4. import classnames from 'classnames';
  5. import { checkboxClasses as css } from '@douyinfe/semi-foundation/checkbox/constants';
  6. import CheckboxFoundation, { CheckboxAdapter, BasicCheckboxEvent, BasicTargetObject, BaseCheckboxProps } from '@douyinfe/semi-foundation/checkbox/checkboxFoundation';
  7. import CheckboxInner from './checkboxInner';
  8. import BaseComponent from '../_base/baseComponent';
  9. import '@douyinfe/semi-foundation/checkbox/checkbox.scss';
  10. import { Context, CheckboxContextType } from './context';
  11. import { isUndefined, isBoolean, noop } from 'lodash';
  12. import { getUuidShort } from '@douyinfe/semi-foundation/utils/uuid';
  13. export type CheckboxEvent = BasicCheckboxEvent;
  14. export type TargetObject = BasicTargetObject;
  15. export interface CheckboxProps extends BaseCheckboxProps {
  16. 'aria-describedby'?: React.AriaAttributes['aria-describedby'];
  17. 'aria-errormessage'?: React.AriaAttributes['aria-errormessage'];
  18. 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
  19. 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
  20. 'aria-required'?: React.AriaAttributes['aria-required'];
  21. children?: React.ReactNode | undefined;
  22. onChange?: (e: CheckboxEvent) => any;
  23. // TODO, docs
  24. style?: React.CSSProperties;
  25. onMouseEnter?: React.MouseEventHandler<HTMLSpanElement>;
  26. onMouseLeave?: React.MouseEventHandler<HTMLSpanElement>;
  27. extra?: React.ReactNode;
  28. 'aria-label'?: React.AriaAttributes['aria-label'];
  29. role?: React.HTMLAttributes<HTMLSpanElement>['role']; // a11y: wrapper role
  30. tabIndex?: number; // a11y: wrapper tabIndex
  31. addonId?: string;
  32. extraId?: string;
  33. }
  34. interface CheckboxState {
  35. checked: boolean;
  36. addonId?: string;
  37. extraId?: string;
  38. focusVisible?: boolean;
  39. }
  40. class Checkbox extends BaseComponent<CheckboxProps, CheckboxState> {
  41. static contextType = Context;
  42. static propTypes = {
  43. 'aria-describedby': PropTypes.string,
  44. 'aria-errormessage': PropTypes.string,
  45. 'aria-invalid': PropTypes.bool,
  46. 'aria-labelledby': PropTypes.string,
  47. 'aria-required': PropTypes.bool,
  48. // Specifies whether it is currently selected
  49. checked: PropTypes.bool,
  50. // Initial check
  51. defaultChecked: PropTypes.bool,
  52. // Failure state
  53. disabled: PropTypes.bool,
  54. // Set indeterminate state, only responsible for style control
  55. indeterminate: PropTypes.bool,
  56. // Callback function when changing
  57. onChange: PropTypes.func,
  58. value: PropTypes.any,
  59. style: PropTypes.object,
  60. className: PropTypes.string,
  61. prefixCls: PropTypes.string,
  62. onMouseEnter: PropTypes.func,
  63. onMouseLeave: PropTypes.func,
  64. extra: PropTypes.node,
  65. index: PropTypes.number,
  66. 'aria-label': PropTypes.string,
  67. tabIndex: PropTypes.number,
  68. };
  69. static defaultProps = {
  70. defaultChecked: false,
  71. indeterminate: false,
  72. onChange: noop,
  73. onMouseEnter: noop,
  74. onMouseLeave: noop,
  75. };
  76. checkboxEntity: CheckboxInner;
  77. context: CheckboxContextType;
  78. get adapter(): CheckboxAdapter<CheckboxProps, CheckboxState> {
  79. return {
  80. ...super.adapter,
  81. setNativeControlChecked: checked => {
  82. this.setState({ checked });
  83. },
  84. notifyChange: cbContent => {
  85. const { onChange } = this.props;
  86. onChange && onChange(cbContent);
  87. },
  88. getIsInGroup: () => this.isInGroup(),
  89. getGroupValue: () => (this.context && this.context.checkboxGroup.value) || [],
  90. notifyGroupChange: cbContent => {
  91. this.context.checkboxGroup.onChange(cbContent);
  92. },
  93. getGroupDisabled: () => (this.context && this.context.checkboxGroup.disabled),
  94. setAddonId: () => {
  95. this.setState({ addonId: getUuidShort({ prefix: 'addon' }) });
  96. },
  97. setExtraId: () => {
  98. this.setState({ extraId: getUuidShort({ prefix: 'extra' }) });
  99. },
  100. setFocusVisible: (focusVisible: boolean): void => {
  101. this.setState({ focusVisible });
  102. },
  103. focusCheckboxEntity: () => {
  104. this.focus();
  105. },
  106. };
  107. }
  108. foundation: CheckboxFoundation;
  109. addonId: string;
  110. extraId: string;
  111. constructor(props: CheckboxProps) {
  112. super(props);
  113. const checked = false;
  114. this.state = {
  115. checked: props.checked || props.defaultChecked || checked,
  116. addonId: props.addonId,
  117. extraId: props.extraId,
  118. focusVisible: false
  119. };
  120. this.checkboxEntity = null;
  121. this.foundation = new CheckboxFoundation(this.adapter);
  122. }
  123. componentDidUpdate(prevProps: CheckboxProps) {
  124. if (this.props.checked !== prevProps.checked) {
  125. if (isUndefined(this.props.checked)) {
  126. this.foundation.setChecked(false);
  127. } else if (isBoolean(this.props.checked)) {
  128. this.foundation.setChecked(this.props.checked);
  129. }
  130. }
  131. }
  132. isInGroup() {
  133. return Boolean(this.context && this.context.checkboxGroup);
  134. }
  135. focus() {
  136. this.checkboxEntity && this.checkboxEntity.focus();
  137. }
  138. blur() {
  139. this.checkboxEntity && this.checkboxEntity.blur();
  140. }
  141. handleChange: React.MouseEventHandler<HTMLSpanElement> = e => this.foundation.handleChange(e);
  142. handleEnterPress = (e: React.KeyboardEvent<HTMLSpanElement>) => this.foundation.handleEnterPress(e);
  143. handleFocusVisible = (event: React.FocusEvent) => {
  144. this.foundation.handleFocusVisible(event);
  145. }
  146. handleBlur = (event: React.FocusEvent) => {
  147. this.foundation.handleBlur();
  148. }
  149. render() {
  150. const {
  151. disabled,
  152. style,
  153. prefixCls,
  154. className,
  155. indeterminate,
  156. children,
  157. onMouseEnter,
  158. onMouseLeave,
  159. extra,
  160. value,
  161. role,
  162. tabIndex,
  163. id
  164. } = this.props;
  165. const { checked, addonId, extraId, focusVisible } = this.state;
  166. const props: Record<string, any> = {
  167. checked,
  168. disabled,
  169. };
  170. const inGroup = this.isInGroup();
  171. if (inGroup) {
  172. if (this.context.checkboxGroup.value) {
  173. const realChecked = (this.context.checkboxGroup.value || []).includes(value);
  174. props.checked = realChecked;
  175. }
  176. if (this.context.checkboxGroup.disabled) {
  177. props.disabled = this.context.checkboxGroup.disabled || this.props.disabled;
  178. }
  179. const { isCardType, isPureCardType } = this.context.checkboxGroup;
  180. props.isCardType = isCardType;
  181. props.isPureCardType = isPureCardType;
  182. props['name'] = this.context.checkboxGroup.name;
  183. }
  184. const prefix = prefixCls || css.PREFIX;
  185. const focusOuter = props.isCardType || props.isPureCardType;
  186. const wrapper = classnames(prefix, {
  187. [`${prefix}-disabled`]: props.disabled,
  188. [`${prefix}-indeterminate`]: indeterminate,
  189. [`${prefix}-checked`]: props.checked,
  190. [`${prefix}-unChecked`]: !props.checked,
  191. [`${prefix}-cardType`]: props.isCardType,
  192. [`${prefix}-cardType_disabled`]: props.disabled && props.isCardType,
  193. [`${prefix}-cardType_unDisabled`]: !(props.disabled && props.isCardType),
  194. [`${prefix}-cardType_checked`]: props.isCardType && props.checked && !props.disabled,
  195. [`${prefix}-cardType_checked_disabled`]: props.isCardType && props.checked && props.disabled,
  196. [className]: Boolean(className),
  197. [`${prefix}-focus`]: focusVisible && focusOuter,
  198. });
  199. const extraCls = classnames(`${prefix}-extra`, {
  200. [`${prefix}-cardType_extra_noChildren`]: props.isCardType && !children,
  201. });
  202. const renderContent = () => (
  203. <>
  204. {children ? <span id={addonId} className={`${prefix}-addon`}>{children}</span> : null}
  205. {extra ? <div id={extraId} className={extraCls}>{extra}</div> : null}
  206. </>
  207. );
  208. return (
  209. // label is better than span, however span is here which is to solve gitlab issue #364
  210. <span
  211. role={role}
  212. tabIndex={tabIndex}
  213. style={style}
  214. className={wrapper}
  215. id={id}
  216. onMouseEnter={onMouseEnter}
  217. onMouseLeave={onMouseLeave}
  218. onClick={this.handleChange}
  219. onKeyPress={this.handleEnterPress}
  220. aria-labelledby={this.props['aria-labelledby']}
  221. >
  222. <CheckboxInner
  223. {...this.props}
  224. {...props}
  225. addonId={children && addonId}
  226. extraId={extra && extraId}
  227. isPureCardType={props.isPureCardType}
  228. ref={ref => {
  229. this.checkboxEntity = ref;
  230. }}
  231. focusInner={focusVisible && !focusOuter}
  232. onInputFocus={e => {
  233. this.handleFocusVisible(e);
  234. }}
  235. onInputBlur={e => {
  236. this.handleBlur(e);
  237. }}
  238. />
  239. {
  240. props.isCardType ?
  241. <div>{renderContent()}</div> :
  242. renderContent()
  243. }
  244. </span>
  245. );
  246. }
  247. }
  248. export default Checkbox;