All files / src/_util use-list-scroll.ts

14.29% Statements 3/21
0% Branches 0/10
25% Functions 1/4
15% Lines 3/20

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 5015x 15x                                                                                           39x    
const SCROLL_OFFSET = 0;
const SCROLL_DURATION = 100;
 
/**
 * 滚动到指定元素
 */
function scrollToElement(
  element: HTMLElement,
  to: number,
  duration: number
): void {
  if (duration <= 0) {
    element.scrollTop = to;
    return;
  }
  const difference = to - element.scrollTop;
  const perTick = (difference / duration) * 10;
 
  requestAnimationFrame(() => {
    element.scrollTop += perTick;
    if (element.scrollTop === to) return;
    scrollToElement(element, to, duration - 10);
  });
}
 
export function useListScroll(selectRef) {
  /**
   * 滚动到当前选择元素
   */
  function scrollTo(
    index: number,
    offset: number = SCROLL_OFFSET,
    duration: number = SCROLL_DURATION
  ): void {
    const element = selectRef.current;
    if (!element) {
      return;
    }
    const topOption = element.children[index] as HTMLElement;
    if (!topOption) {
      return;
    }
    const to = topOption.offsetTop - element.offsetTop - offset;
 
    scrollToElement(element, to, duration);
  }
 
  return scrollTo;
}