All files / src/UI/Tree TreeFocusProvider.tsx

29.79% Statements 28/94
6.59% Branches 6/91
15.38% Functions 2/13
26.14% Lines 23/88

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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212                              3x                               3x   18x 18x 18x                             3x 59x 59x 59x 59x 59x   59x 59x     118x 59x                       59x           59x                 59x                           59x           59x           59x                                                                                                                                     59x                       59x                                  
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
import React, {
  FocusEvent,
  FunctionComponent,
  KeyboardEvent,
  MouseEvent as ReactMouseEvent,
  RefObject,
  createContext,
  useContext,
  useState,
} from 'react';
 
interface ITreeFocusContext {
  focusedItem: HTMLElement | null;
  setFocusedItem: (item: HTMLElement | null) => void;
}
 
const TreeFocusContext = createContext<ITreeFocusContext | null>(null);
 
export const TreeFocusProvider: FunctionComponent = ({ children }) => {
  const [focusedItem, setFocusedItem] = useState<HTMLElement | null>(null);
  return (
    <TreeFocusContext.Provider value={{ focusedItem, setFocusedItem }}>
      {children}
    </TreeFocusContext.Provider>
  );
};
 
export interface IUseTreeFocusProps {
  ref: RefObject<HTMLDivElement | null>;
  isExpandable?: boolean;
  isExpanded?: boolean;
  collapseTreeitem?: () => void;
  expandTreeitem?: () => void;
}
 
export const useTreeFocus = ({
  ref,
  isExpandable = false,
  isExpanded = false,
  collapseTreeitem,
  expandTreeitem,
}: IUseTreeFocusProps) => {
  const context = useContext(TreeFocusContext);
  Iif (!context) {
    throw new Error(`useTreeFocus can be used only inside a Tree component`);
  }
  const { focusedItem, setFocusedItem } = context;
  const getFocusableItems = (el: HTMLElement) => {
    return Array.from<HTMLElement>(
      el.closest('[role=tree]')?.querySelectorAll('[role=treeitem]') || [],
    ).filter((el) => {
      const group = el.parentElement?.closest('[aria-expanded]');
      if (group) {
        return group.getAttribute('aria-expanded') === 'true';
      }
      return true;
    });
  };
 
  const setFocus = (index: number, nodes: HTMLElement[]) => {
    nodes.forEach((n) => n.setAttribute('tabindex', '-1'));
    nodes[index].setAttribute('tabindex', '0');
    nodes[index].focus();
  };
 
  const setFocusToPreviousItem = () => {
    if (ref.current) {
      const nodes = getFocusableItems(ref.current);
      const idx = nodes?.indexOf(ref.current);
      if (idx > 0) {
        setFocus(idx - 1, nodes);
      }
    }
  };
  const setFocusToNextItem = () => {
    if (ref.current) {
      const nodes = getFocusableItems(ref.current);
      const idx = nodes?.indexOf(ref.current);
      if (idx < nodes.length - 1) {
        setFocus(idx + 1, nodes);
      }
    }
  };
  // const setFocusToParentItem = () => {
  //   if (level > 1 && parentItem) {
  //     setFocus({ level: level - 1, position: parentItem.position });
  //   }
  // };
  const setFocusToFirstItem = () => {
    if (ref.current) {
      const nodes = getFocusableItems(ref.current);
      setFocus(0, nodes);
    }
  };
  const setFocusToLastItem = () => {
    if (ref.current) {
      const nodes = getFocusableItems(ref.current);
      setFocus(nodes.length - 1, nodes);
    }
  };
  const onKeyDown = (event: KeyboardEvent) => {
    // don't handle keyboard events performed on child elements
    if (event.target !== ref.current) {
      return;
    }
    // ignore special keys
    if (event.altKey || event.ctrlKey || event.metaKey) {
      return;
    }
    switch (event.key) {
      case ' ':
      case 'Enter':
        if (event.target === ref.current) {
          // Create simulated mouse event to mimic the behavior of ATs
          // and let the event handler handleClick do the housekeeping.
          event.target.dispatchEvent(
            new MouseEvent('click', {
              view: window,
              bubbles: true,
              cancelable: true,
            }),
          );
          setFocusedItem(ref.current);
        }
        break;
      case 'Escape':
        setFocusedItem(null);
        event.preventDefault();
        break;
      case 'ArrowUp':
        setFocusToPreviousItem();
        break;
      case 'ArrowDown':
        setFocusToNextItem();
        break;
      case 'ArrowRight':
        if (isExpandable) {
          if (isExpanded) {
            setFocusToNextItem();
          } else {
            if (expandTreeitem) {
              expandTreeitem();
            }
          }
        }
        break;
      case 'ArrowLeft':
        if (isExpandable && isExpanded) {
          if (collapseTreeitem) {
            collapseTreeitem();
          }
        } else {
          // if (itemLevel === level) {
          //   setFocusToParentItem();
          // }
        }
        break;
      case 'Home':
        setFocusToFirstItem();
        break;
      case 'End':
        setFocusToLastItem();
        break;
      default:
        break;
    }
  };
  const onClick = (event: ReactMouseEvent<HTMLElement>) => {
    if (ref.current) {
      if (isExpandable && isExpanded) {
        event.stopPropagation();
      } else {
        const nodes = getFocusableItems(ref.current);
        const idx = nodes?.indexOf(ref.current);
        setFocus(idx, nodes);
        setFocusedItem(ref.current);
      }
    }
  };
  return {
    focused: focusedItem && focusedItem === ref.current,
    handlers: {
      onKeyDown,
      onClick,
      onBlur: (event: FocusEvent<HTMLElement>) => {
        if (
          (event.relatedTarget as HTMLElement | null)?.closest(
            '[role=tree]',
          ) !== ref.current?.closest('[role=tree]')
        ) {
          setFocusedItem(null);
        }
      },
    },
  };
};