checkbox.tsx 8.5 KB

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