All files / src/hooks useDataCheckboxes.ts

91.17% Statements 62/68
75% Branches 33/44
100% Functions 11/11
91.17% Lines 62/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195              9x     9x         7x 1x   6x     6x   6x     6x         2x 2x     4x 4x                     9x       30x 30x     30x 30x 30x         30x 24x 24x 14x   10x   3x     3x       3x 3x 3x 3x   30x 21x     3x     10x   10x 10x         30x 28x 28x 18x     10x 33x 33x                     33x   1x     33x         33x 1x         1x       1x 1x           1x   1x 9x             9x                           33x     33x     10x   10x 10x       30x 10x           30x                
/* eslint-disable no-param-reassign */
import { useRef, useCallback, useState, useEffect } from 'react';
import { debounce } from 'lodash-es';
import { schedule } from 'timing-functions';
 
// Needs to match the style (would be good to come from CSS modules)
// Needs to use this when using custom checkboxes (in cards for example)
export const checkboxCellSelector = '.checkbox-cell';
 
// Use debounce to wait until the next tick (0 and `leading: false`)
export const updateSelectAllCheckbox = debounce(
  (
    checkboxContainer?: HTMLElement | null,
    selectAllCheckbox?: HTMLInputElement | null
  ) => {
    if (!checkboxContainer || !selectAllCheckbox) {
      return;
    }
    const allCheckboxes = checkboxContainer?.querySelectorAll<HTMLInputElement>(
      `${checkboxCellSelector} > input[type="checkbox"]`
    );
    if (allCheckboxes?.length) {
      const checkedCheckboxes =
        checkboxContainer.querySelectorAll<HTMLInputElement>(
          `${checkboxCellSelector} > input[type="checkbox"]:checked`
        );
      if (
        checkedCheckboxes?.length &&
        allCheckboxes.length !== checkedCheckboxes.length
      ) {
        // Mixed state
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = true;
      } else {
        // Or all, or nothing
        selectAllCheckbox.checked = Boolean(checkedCheckboxes?.length);
        selectAllCheckbox.indeterminate = false;
      }
    } else E{
      selectAllCheckbox.checked = false;
      selectAllCheckbox.indeterminate = false;
    }
  },
  0,
  { leading: false }
);
 
const useDataCheckboxes = (
  onSelectionChange?: (event: MouseEvent | KeyboardEvent) => void
) => {
  // HTML elements refs
  const privateSelectAllRef = useRef<HTMLInputElement | null>(null);
  const privateCheckboxContainerRef = useRef<
    HTMLTableSectionElement | HTMLUListElement | null
  >(null);
  const lastTickedRef = useRef<HTMLInputElement | null>(null);
  const [selectAll, selectAllRef] = useState<HTMLInputElement | null>(null);
  const [checkboxContainer, checkboxContainerRef] = useState<
    HTMLTableSectionElement | HTMLUListElement | null
  >(null);
 
  // Bind click event to native event on select-all checkbox
  useEffect(() => {
    privateSelectAllRef.current = selectAll;
    if (!selectAll) {
      return;
    }
    const listener = () => {
      const allCheckboxes =
        privateCheckboxContainerRef.current?.querySelectorAll<HTMLInputElement>(
          `${checkboxCellSelector} > input[type="checkbox"]`
        );
      Iif (!allCheckboxes?.length) {
        return;
      }
      // should check all boxes if is checked
      const shouldBeChecked = selectAll.checked;
      selectAll.disabled = true;
      schedule().then(() => {
        for (const checkbox of allCheckboxes.values()) {
          // If inconsistent state, click to sync
          if (shouldBeChecked !== checkbox.checked) {
            checkbox.click(); // Needs to click to trigger event
          }
        }
        selectAll.disabled = false;
      });
    };
    selectAll.addEventListener('click', listener);
    // eslint-disable-next-line consistent-return
    return () => {
      selectAll.removeEventListener('click', listener);
    };
  }, [selectAll]);
 
  // Bind click event to native event using event delegation on container
  useEffect(() => {
    privateCheckboxContainerRef.current = checkboxContainer;
    if (!(onSelectionChange && checkboxContainer)) {
      return;
    }
 
    const listener = (event: Event) => {
      const { target } = event;
      Iif (
        !(
          (event instanceof MouseEvent || event instanceof KeyboardEvent) &&
          target instanceof HTMLElement &&
          target.parentElement?.matches(checkboxCellSelector)
        )
      ) {
        // Not the target labels or checkboxes, bail
        return;
      }
 
      if (event.shiftKey) {
        // Remove the default text selection that might happen
        window.getSelection()?.removeAllRanges();
      }
 
      Iif (!(target instanceof HTMLInputElement)) {
        // If it's not the checkbox, it's the label, bail, another event will come
        return;
      }
 
      if (event.shiftKey) {
        const checkboxes = Array.from(
          checkboxContainer.querySelectorAll<HTMLInputElement>(
            `${checkboxCellSelector} > input[type="checkbox"]`
          ) || []
        );
        let firstIndex = Math.max(
          0,
          lastTickedRef.current ? checkboxes.indexOf(lastTickedRef.current) : 0
        );
        let lastIndex = checkboxes.indexOf(target);
        Iif (lastIndex < firstIndex) {
          // Switch order if the last is before the first
          [firstIndex, lastIndex] = [lastIndex, firstIndex + 1];
        }
 
        // not immediately, fires native events that are handled synchronously
        schedule().then(() => {
          // loop on all the checkboxes within the range
          for (const checkbox of checkboxes.slice(firstIndex, lastIndex)) {
            Eif (
              // if the target is checked, check all the others
              (target.checked && !checkbox.checked) ||
              // if the target is unchecked, uncheck all the others
              (!target.checked && checkbox.checked)
            ) {
              // Artificially click them all to trigger click events
              checkbox.click();
            }
          }
        });
      }
 
      // No way to test that as we can't generate trusted events in tests
      /* istanbul ignore next */
      if (event.isTrusted) {
        // user-generated event, keep track of target as last toggled checkbox
        lastTickedRef.current = target;
      }
 
      // Toggle select all accordingly
      updateSelectAllCheckbox(checkboxContainer, privateSelectAllRef.current);
 
      // Call user event handler with the native event
      onSelectionChange(event);
    };
 
    checkboxContainer?.addEventListener('click', listener);
    // eslint-disable-next-line consistent-return
    return () => {
      checkboxContainer?.removeEventListener('click', listener);
    };
  }, [checkboxContainer, onSelectionChange]);
 
  const checkSelectAllSync = useCallback(() => {
    updateSelectAllCheckbox(
      privateCheckboxContainerRef.current,
      privateSelectAllRef.current
    );
  }, []);
 
  return {
    selectAllRef,
    checkboxContainerRef,
    checkSelectAllSync,
  };
};
 
export default useDataCheckboxes;