import { useCallback } from 'react';

/**
 * Hook to provide accessible props to attach a click listener to what is
 * usually a non-interactive element. In general it's best practice to attach
 * click listeners to conventionally interactive elements like buttons, but for
 * cases when that is not possible this hook makes it easy to also add an
 * `onKeyPress` event handler that responds to a keyboard return, a `role` of
 * "button", and a `tabIndex` of 0. The typical usage is
 *
 * ```jsx
 * const clickProps = useA11yOnClick(() => {
 *   doSomethingWith(myValue);
 * }, [myValue]);
 *
 * return (
 *   <div {...clickProps}>Click Me</div>
 * );
 * ```
 *
 * The first argument to the hook is the callback to handle the click event;
 * the second argument is a dependency array which gets forwarded to
 * `useCallback` to memoize the callback.
 *
 * ```js
 *
 * import { useA11yOnClick } from '@politico/interactive-style';
 * ```
 *
 * @param {function} callback
 *   The event handler that will get called when the user clicks or presses
 *   enter while the node is focused.
 * @param {any[]} [dependencies]
 *   An optional array of dependencies that gets forwarded to `useCallback` to
 *   memoize the event handler callback.
 *
 * @returns {Object}
 */
const useA11yOnClick = function useA11yOnClick(callback, dependencies) {
  const cb = useCallback(callback, dependencies);
  const onKeyPress = useCallback(e => {
    /* If pressing enter */
    if (e.charCode === 13) {
      cb(e);
    }
  }, [cb]);
  return {
    onClick: cb,
    onKeyPress,
    role: 'button',
    tabIndex: '0'
  };
};
export default useA11yOnClick;