checkbox.tsx 9.9 KB

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