checkbox.tsx 10 KB

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