OperateAllControl.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import type { ChangeEvent, ForwardRefRenderFunction } from 'react';
  2. import React, { forwardRef, useImperativeHandle, useRef } from 'react';
  3. import { Input } from 'reactstrap';
  4. import type { ISelectableAndIndeterminatable } from '~/client/interfaces/selectable-all';
  5. import type { IndeterminateInputElement } from '~/interfaces/indeterminate-input-elm';
  6. type Props = {
  7. inputId?: string,
  8. inputClassName?: string,
  9. isCheckboxDisabled?: boolean,
  10. onCheckboxChanged?: (isChecked: boolean) => void,
  11. children?: React.ReactNode,
  12. }
  13. const OperateAllControlSubstance: ForwardRefRenderFunction<ISelectableAndIndeterminatable, Props> = (props: Props, ref): JSX.Element => {
  14. const {
  15. inputId,
  16. inputClassName = '',
  17. isCheckboxDisabled,
  18. onCheckboxChanged,
  19. children,
  20. } = props;
  21. const selectAllCheckboxElm = useRef<IndeterminateInputElement>(null);
  22. // publish ISelectable methods
  23. useImperativeHandle(ref, () => ({
  24. select: () => {
  25. const input = selectAllCheckboxElm.current;
  26. if (input != null) {
  27. input.checked = true;
  28. input.indeterminate = false;
  29. }
  30. },
  31. deselect: () => {
  32. const input = selectAllCheckboxElm.current;
  33. if (input != null) {
  34. input.checked = false;
  35. input.indeterminate = false;
  36. }
  37. },
  38. setIndeterminate: () => {
  39. const input = selectAllCheckboxElm.current;
  40. if (input != null) {
  41. input.indeterminate = true;
  42. }
  43. },
  44. }));
  45. const checkboxChangedHandler = (e: ChangeEvent<HTMLInputElement>) => {
  46. if (onCheckboxChanged != null) {
  47. onCheckboxChanged(e.target.checked);
  48. }
  49. };
  50. return (
  51. <div className="d-flex align-items-center">
  52. <Input
  53. id={inputId}
  54. type="checkbox"
  55. data-testid="cb-select-all"
  56. className={inputClassName}
  57. innerRef={selectAllCheckboxElm}
  58. disabled={isCheckboxDisabled}
  59. onChange={checkboxChangedHandler}
  60. />
  61. {children}
  62. </div>
  63. );
  64. };
  65. export const OperateAllControl = React.memo(forwardRef(OperateAllControlSubstance));