1
0

checkbox.tsx 8.6 KB

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