1
0

checkbox.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. static elementType: string;
  82. checkboxEntity: CheckboxInner;
  83. context: CheckboxContextType;
  84. get adapter(): CheckboxAdapter<CheckboxProps, CheckboxState> {
  85. return {
  86. ...super.adapter,
  87. setNativeControlChecked: checked => {
  88. this.setState({ checked });
  89. },
  90. notifyChange: cbContent => {
  91. const { onChange } = this.props;
  92. onChange && onChange(cbContent);
  93. },
  94. getIsInGroup: () => this.isInGroup(),
  95. getGroupValue: () => (this.context && this.context.checkboxGroup.value) || [],
  96. notifyGroupChange: cbContent => {
  97. this.context.checkboxGroup.onChange(cbContent);
  98. },
  99. getGroupDisabled: () => (this.context && this.context.checkboxGroup.disabled),
  100. setAddonId: () => {
  101. this.setState({ addonId: getUuidShort({ prefix: 'addon' }) });
  102. },
  103. setExtraId: () => {
  104. this.setState({ extraId: getUuidShort({ prefix: 'extra' }) });
  105. },
  106. setFocusVisible: (focusVisible: boolean): void => {
  107. this.setState({ focusVisible });
  108. },
  109. focusCheckboxEntity: () => {
  110. this.focus();
  111. },
  112. };
  113. }
  114. foundation: CheckboxFoundation;
  115. constructor(props: CheckboxProps) {
  116. super(props);
  117. const checked = false;
  118. this.state = {
  119. checked: props.checked || props.defaultChecked || checked,
  120. addonId: props.addonId,
  121. extraId: props.extraId,
  122. focusVisible: false
  123. };
  124. this.checkboxEntity = null;
  125. this.foundation = new CheckboxFoundation(this.adapter);
  126. }
  127. componentDidUpdate(prevProps: CheckboxProps) {
  128. if (this.props.checked !== prevProps.checked) {
  129. if (isUndefined(this.props.checked)) {
  130. this.foundation.setChecked(false);
  131. } else if (isBoolean(this.props.checked)) {
  132. this.foundation.setChecked(this.props.checked);
  133. }
  134. }
  135. }
  136. isInGroup() {
  137. // Why do we need to determine whether there is a value in props?
  138. // If there is no value in the props of the checkbox in the context of the checkboxGroup,
  139. // it will be considered not to belong to the checkboxGroup。
  140. return Boolean(this.context && this.context.checkboxGroup && ('value' in this.props));
  141. }
  142. focus() {
  143. this.checkboxEntity && this.checkboxEntity.focus();
  144. }
  145. blur() {
  146. this.checkboxEntity && this.checkboxEntity.blur();
  147. }
  148. handleChange: React.MouseEventHandler<HTMLSpanElement> = e => this.foundation.handleChange(e);
  149. handleEnterPress = (e: React.KeyboardEvent<HTMLSpanElement>) => this.foundation.handleEnterPress(e);
  150. handleFocusVisible = (event: React.FocusEvent) => {
  151. this.foundation.handleFocusVisible(event);
  152. }
  153. handleBlur = (event: React.FocusEvent) => {
  154. this.foundation.handleBlur();
  155. }
  156. render() {
  157. const {
  158. disabled,
  159. style,
  160. prefixCls,
  161. className,
  162. indeterminate,
  163. children,
  164. onMouseEnter,
  165. onMouseLeave,
  166. extra,
  167. value,
  168. role,
  169. tabIndex,
  170. id,
  171. type,
  172. } = this.props;
  173. const { checked, addonId, extraId, focusVisible } = this.state;
  174. const props: Record<string, any> = {
  175. checked,
  176. disabled,
  177. };
  178. const inGroup = this.isInGroup();
  179. if (inGroup) {
  180. if (this.context.checkboxGroup.value) {
  181. const realChecked = (this.context.checkboxGroup.value || []).includes(value);
  182. props.checked = realChecked;
  183. }
  184. if (this.context.checkboxGroup.disabled) {
  185. props.disabled = this.context.checkboxGroup.disabled || this.props.disabled;
  186. }
  187. const { isCardType, isPureCardType } = this.context.checkboxGroup;
  188. props.isCardType = isCardType;
  189. props.isPureCardType = isPureCardType;
  190. props['name'] = this.context.checkboxGroup.name;
  191. } else {
  192. props.isPureCardType = type === strings.TYPE_PURECARD;
  193. props.isCardType = type === strings.TYPE_CARD || props.isPureCardType;
  194. }
  195. const prefix = prefixCls || css.PREFIX;
  196. const focusOuter = props.isCardType || props.isPureCardType;
  197. const wrapper = classnames(prefix, {
  198. [`${prefix}-disabled`]: props.disabled,
  199. [`${prefix}-indeterminate`]: indeterminate,
  200. [`${prefix}-checked`]: props.checked,
  201. [`${prefix}-unChecked`]: !props.checked,
  202. [`${prefix}-cardType`]: props.isCardType,
  203. [`${prefix}-cardType_disabled`]: props.disabled && props.isCardType,
  204. [`${prefix}-cardType_unDisabled`]: !(props.disabled && props.isCardType),
  205. [`${prefix}-cardType_checked`]: props.isCardType && props.checked && !props.disabled,
  206. [`${prefix}-cardType_checked_disabled`]: props.isCardType && props.checked && props.disabled,
  207. [className]: Boolean(className),
  208. [`${prefix}-focus`]: focusVisible && focusOuter,
  209. });
  210. const extraCls = classnames(`${prefix}-extra`, {
  211. [`${prefix}-cardType_extra_noChildren`]: props.isCardType && !children,
  212. });
  213. const name = inGroup && this.context.checkboxGroup.name;
  214. const xSemiPropChildren = this.props['x-semi-children-alias'] || 'children';
  215. const renderContent = () => {
  216. if (!children && !extra) {
  217. return null;
  218. }
  219. return (
  220. <div className={`${prefix}-content`}>
  221. {children ? (
  222. <span id={addonId} className={`${prefix}-addon`} x-semi-prop={xSemiPropChildren}>
  223. {children}
  224. </span>
  225. ) : null}
  226. {extra ? (
  227. <div id={extraId} className={extraCls} x-semi-prop="extra">
  228. {extra}
  229. </div>
  230. ) : null}
  231. </div>
  232. );
  233. };
  234. return (
  235. // label is better than span, however span is here which is to solve gitlab issue #364
  236. <span
  237. role={role}
  238. tabIndex={tabIndex}
  239. style={style}
  240. className={wrapper}
  241. id={id}
  242. onMouseEnter={onMouseEnter}
  243. onMouseLeave={onMouseLeave}
  244. onClick={this.handleChange}
  245. onKeyPress={this.handleEnterPress}
  246. aria-labelledby={this.props['aria-labelledby']}
  247. >
  248. <CheckboxInner
  249. {...this.props}
  250. {...props}
  251. addonId={children && addonId}
  252. extraId={extra && extraId}
  253. isPureCardType={props.isPureCardType}
  254. ref={ref => {
  255. this.checkboxEntity = ref;
  256. }}
  257. focusInner={focusVisible && !focusOuter}
  258. onInputFocus={this.handleFocusVisible}
  259. onInputBlur={this.handleBlur}
  260. />
  261. {renderContent()}
  262. </span>
  263. );
  264. }
  265. }
  266. Checkbox.elementType = 'Checkbox';
  267. export default Checkbox;