checkbox.tsx 9.9 KB

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