All files / src/components/ui/lists FlatList.tsx

0% Statements 0/95
0% Branches 0/71
0% Functions 0/20
0% Lines 0/91

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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import throttle from "lodash/throttle";
import React, {
  CSSProperties,
  ReactNode,
  useEffect,
  useRef,
  useState,
} from "react";
import { FixedSizeList as List } from "react-window";
import styled from "styled-components";
import { ThemeInterface } from "ui/theme/ThemeInterface";
import { ListItem } from "./ListItem";
import { getEventNodeName } from "renderer/lib/helpers/dom";
 
export interface FlatListItem {
  id: string;
  name: string;
}
 
interface RowProps<T extends FlatListItem> {
  readonly index: number;
  readonly style: CSSProperties;
  readonly data: {
    readonly items: T[];
    readonly selectedId: string;
    readonly highlightIds?: string[];
    readonly setSelectedId?: (value: string, item: T) => void;
    readonly renderItem: (props: {
      selected: boolean;
      item: T;
      index: number;
    }) => React.ReactNode;
  };
}
 
export interface FlatListProps<T extends FlatListItem> {
  readonly height: number;
  readonly items: T[];
  readonly selectedId?: string;
  readonly highlightIds?: string[];
  readonly setSelectedId?: (id: string, item: T) => void;
  readonly onKeyDown?: (e: KeyboardEvent, item?: T) => void;
  readonly children: (props: {
    selected: boolean;
    item: T;
    index: number;
  }) => React.ReactNode;
  readonly theme?: ThemeInterface;
}
 
const Wrapper = styled.div`
  padding: 0;
  width: 100%;
  box-sizing: border-box;
`;
 
const Row = <T extends FlatListItem>({ index, style, data }: RowProps<T>) => {
  const item = data.items[index];
  Iif (!item) {
    return <div style={style} />;
  }
  return (
    <div
      key={item.id}
      style={style}
      onClick={() => data.setSelectedId?.(item.id, item)}
      data-id={item.id}
    >
      <ListItem
        data-selected={data.selectedId === item.id}
        data-highlighted={data.highlightIds?.includes(item.id)}
      >
        {data.renderItem
          ? data.renderItem({
              item,
              selected: data.selectedId === item.id,
              index,
            })
          : item.name}
      </ListItem>
    </div>
  );
};
 
export const FlatList = <T extends FlatListItem>({
  items,
  selectedId,
  highlightIds,
  setSelectedId,
  height,
  onKeyDown,
  children,
}: FlatListProps<T>) => {
  const typedSetSelectedId = setSelectedId as <T extends FlatListItem>(
    id: string,
    item: T
  ) => void | undefined;
  const typedItems = items as T[];
 
  const ref = useRef<HTMLDivElement>(null);
  const [hasFocus, setHasFocus] = useState(false);
  const list = useRef<List>(null);
 
  const selectedIndex = items.findIndex((item) => item.id === selectedId);
 
  const handleKeys = (e: KeyboardEvent) => {
    Iif (!hasFocus || getEventNodeName(e) === "INPUT") {
      return;
    }
    Iif (e.metaKey || e.ctrlKey) {
      return;
    }
    if (e.key === "ArrowDown") {
      e.preventDefault();
      throttledNext.current(items, selectedId || "");
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      throttledPrev.current(items, selectedId || "");
    } else if (e.key === "Home") {
      const nextItem = items[0];
      setSelectedId?.(nextItem.id, nextItem);
      setFocus(nextItem.id);
    } else if (e.key === "End") {
      const nextItem = items[items.length - 1];
      setSelectedId?.(nextItem.id, nextItem);
      setFocus(nextItem.id);
    } else {
      handleSearch(e.key);
    }
    onKeyDown?.(e, items[selectedIndex]);
  };
 
  const throttledNext = useRef(
    throttle((items: T[], selectedId: string) => {
      const currentIndex = items.findIndex((item) => item.id === selectedId);
      const nextIndex = currentIndex + 1;
      const nextItem = items[nextIndex];
      Iif (nextItem) {
        setSelectedId?.(nextItem.id, nextItem);
        setFocus(nextItem.id);
      }
    }, 150)
  );
 
  const throttledPrev = useRef(
    throttle((items: T[], selectedId: string) => {
      const currentIndex = items.findIndex((item) => item.id === selectedId);
      const nextIndex = currentIndex - 1;
      const nextItem = items[nextIndex];
      Iif (nextItem) {
        setSelectedId?.(nextItem.id, nextItem);
        setFocus(nextItem.id);
      }
    }, 150)
  );
 
  const handleSearch = (key: string) => {
    const search = key.toLowerCase();
    const index = selectedIndex + 1;
    let next = items.slice(index).find((node) => {
      const name = String(node.name).toLowerCase();
      return name.startsWith(search);
    });
    Iif (!next) {
      next = items.slice(0, index).find((node) => {
        const name = String(node.name).toLowerCase();
        return name.startsWith(search);
      });
    }
    Iif (next) {
      setSelectedId?.(next.id, next);
      setFocus(next.id);
    }
  };
 
  const handleClickOutside = (e: MouseEvent) => {
    Iif (ref.current && hasFocus && !ref.current.contains(e.target as Node)) {
      setHasFocus(false);
    }
  };
 
  const setFocus = (id: string) => {
    Iif (ref.current) {
      const el = ref.current.querySelector('[data-id="' + id + '"]');
      Iif (el) {
        (el as HTMLDivElement).focus();
      }
    }
  };
 
  useEffect(() => {
    window.addEventListener("keydown", handleKeys);
    window.addEventListener("mousedown", handleClickOutside);
    return () => {
      window.removeEventListener("keydown", handleKeys);
      window.removeEventListener("mousedown", handleClickOutside);
    };
  });
 
  useEffect(() => {
    /**
     * enables scrolling on key down arrow
     */
    Iif (selectedIndex >= 0 && list.current !== null) {
      list.current.scrollToItem(selectedIndex);
    }
  }, [selectedIndex, items, list]);
 
  Iif (height <= 0) {
    return <Wrapper ref={ref} style={{ height }}></Wrapper>;
  }
 
  return (
    <Wrapper
      ref={ref}
      role="listbox"
      onFocus={() => setHasFocus(true)}
      onBlur={() => setHasFocus(false)}
      tabIndex={0}
      style={{ height }}
    >
      <List
        ref={list}
        width="100%"
        height={Math.max(0, height)}
        itemCount={items.length}
        itemSize={25}
        itemData={{
          items: typedItems,
          selectedId: selectedId ?? "",
          highlightIds,
          setSelectedId: typedSetSelectedId,
          renderItem: ((props: { selected: boolean; item: T; index: number }) =>
            children(props)) as (props: {
            selected: boolean;
            item: FlatListItem;
            index: number;
          }) => ReactNode,
        }}
      >
        {Row}
      </List>
    </Wrapper>
  );
};