checkbox.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. }
  39. class Checkbox extends BaseComponent<CheckboxProps, CheckboxState> {
  40. static contextType = Context;
  41. static propTypes = {
  42. 'aria-describedby': PropTypes.string,
  43. 'aria-errormessage': PropTypes.string,
  44. 'aria-invalid': PropTypes.bool,
  45. 'aria-labelledby': PropTypes.string,
  46. 'aria-required': PropTypes.bool,
  47. // Specifies whether it is currently selected
  48. checked: PropTypes.bool,
  49. // Initial check
  50. defaultChecked: PropTypes.bool,
  51. // Failure state
  52. disabled: PropTypes.bool,
  53. // Set indeterminate state, only responsible for style control
  54. indeterminate: PropTypes.bool,
  55. // Callback function when changing
  56. onChange: PropTypes.func,
  57. value: PropTypes.any,
  58. style: PropTypes.object,
  59. className: PropTypes.string,
  60. prefixCls: PropTypes.string,
  61. onMouseEnter: PropTypes.func,
  62. onMouseLeave: PropTypes.func,
  63. extra: PropTypes.node,
  64. index: PropTypes.number,
  65. 'aria-label': PropTypes.string,
  66. tabIndex: PropTypes.number,
  67. };
  68. static defaultProps = {
  69. defaultChecked: false,
  70. indeterminate: false,
  71. onChange: noop,
  72. onMouseEnter: noop,
  73. onMouseLeave: noop,
  74. };
  75. checkboxEntity: CheckboxInner;
  76. context: CheckboxContextType;
  77. get adapter(): CheckboxAdapter<CheckboxProps, CheckboxState> {
  78. return {
  79. ...super.adapter,
  80. setNativeControlChecked: checked => {
  81. this.setState({ checked });
  82. },
  83. notifyChange: cbContent => {
  84. const { onChange } = this.props;
  85. onChange && onChange(cbContent);
  86. },
  87. getIsInGroup: () => this.isInGroup(),
  88. getGroupValue: () => (this.context && this.context.checkboxGroup.value) || [],
  89. notifyGroupChange: cbContent => {
  90. this.context.checkboxGroup.onChange(cbContent);
  91. },
  92. getGroupDisabled: () => (this.context && this.context.checkboxGroup.disabled),
  93. setAddonId: () => {
  94. this.setState({ addonId: getUuidShort({ prefix: 'addon' }) });
  95. },
  96. setExtraId: () => {
  97. this.setState({ extraId: getUuidShort({ prefix: 'extra' }) });
  98. }
  99. };
  100. }
  101. foundation: CheckboxFoundation;
  102. addonId: string;
  103. extraId: string;
  104. constructor(props: CheckboxProps) {
  105. super(props);
  106. const checked = false;
  107. this.state = {
  108. checked: props.checked || props.defaultChecked || checked,
  109. addonId: props.addonId,
  110. extraId: props.extraId,
  111. };
  112. this.checkboxEntity = null;
  113. this.foundation = new CheckboxFoundation(this.adapter);
  114. }
  115. componentDidUpdate(prevProps: CheckboxProps) {
  116. if (this.props.checked !== prevProps.checked) {
  117. if (isUndefined(this.props.checked)) {
  118. this.foundation.setChecked(false);
  119. } else if (isBoolean(this.props.checked)) {
  120. this.foundation.setChecked(this.props.checked);
  121. }
  122. }
  123. }
  124. isInGroup() {
  125. return Boolean(this.context && this.context.checkboxGroup);
  126. }
  127. focus() {
  128. this.checkboxEntity && this.checkboxEntity.focus();
  129. }
  130. blur() {
  131. this.checkboxEntity && this.checkboxEntity.blur();
  132. }
  133. handleChange: React.MouseEventHandler<HTMLSpanElement> = e => this.foundation.handleChange(e);
  134. handleEnterPress = (e: React.KeyboardEvent<HTMLSpanElement>) => this.foundation.handleEnterPress(e);
  135. render() {
  136. const {
  137. disabled,
  138. style,
  139. prefixCls,
  140. className,
  141. indeterminate,
  142. children,
  143. onMouseEnter,
  144. onMouseLeave,
  145. extra,
  146. value,
  147. role,
  148. tabIndex,
  149. id
  150. } = this.props;
  151. const { checked, addonId, extraId } = this.state;
  152. const props: Record<string, any> = {
  153. checked,
  154. disabled,
  155. };
  156. const inGroup = this.isInGroup();
  157. if (inGroup) {
  158. if (this.context.checkboxGroup.value) {
  159. const realChecked = (this.context.checkboxGroup.value || []).includes(value);
  160. props.checked = realChecked;
  161. }
  162. if (this.context.checkboxGroup.disabled) {
  163. props.disabled = this.context.checkboxGroup.disabled || this.props.disabled;
  164. }
  165. const { isCardType, isPureCardType } = this.context.checkboxGroup;
  166. props.isCardType = isCardType;
  167. props.isPureCardType = isPureCardType;
  168. }
  169. const prefix = prefixCls || css.PREFIX;
  170. const wrapper = classnames(prefix, {
  171. [`${prefix}-disabled`]: props.disabled,
  172. [`${prefix}-indeterminate`]: indeterminate,
  173. [`${prefix}-checked`]: props.checked,
  174. [`${prefix}-unChecked`]: !props.checked,
  175. [`${prefix}-cardType`]: props.isCardType,
  176. [`${prefix}-cardType_disabled`]: props.disabled && props.isCardType,
  177. [`${prefix}-cardType_unDisabled`]: !(props.disabled && props.isCardType),
  178. [`${prefix}-cardType_checked`]: props.isCardType && props.checked && !props.disabled,
  179. [`${prefix}-cardType_checked_disabled`]: props.isCardType && props.checked && props.disabled,
  180. [className]: Boolean(className),
  181. });
  182. const extraCls = classnames(`${prefix}-extra`, {
  183. [`${prefix}-cardType_extra_noChildren`]: props.isCardType && !children,
  184. });
  185. const name = inGroup && this.context.checkboxGroup.name;
  186. const renderContent = () => (
  187. <>
  188. {children ? <span id={addonId} className={`${prefix}-addon`}>{children}</span> : null}
  189. {extra ? <div id={extraId} className={extraCls}>{extra}</div> : null}
  190. </>
  191. );
  192. return (
  193. // label is better than span, however span is here which is to solve gitlab issue #364
  194. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  195. <span
  196. role={role}
  197. tabIndex={tabIndex}
  198. style={style}
  199. className={wrapper}
  200. id={id}
  201. onMouseEnter={onMouseEnter}
  202. onMouseLeave={onMouseLeave}
  203. onClick={this.handleChange}
  204. onKeyPress={this.handleEnterPress}
  205. aria-labelledby={this.props['aria-labelledby']}
  206. >
  207. <CheckboxInner
  208. {...this.props}
  209. {...props}
  210. addonId={children && addonId}
  211. extraId={extra && extraId}
  212. name={name}
  213. isPureCardType={props.isPureCardType}
  214. ref={ref => {
  215. this.checkboxEntity = ref;
  216. }}
  217. />
  218. {
  219. props.isCardType ?
  220. <div>{renderContent()}</div> :
  221. renderContent()
  222. }
  223. </span>
  224. );
  225. }
  226. }
  227. export default Checkbox;