All files / libs/lti/components/src/lib/enrollment/simulation-widget/pagination use-simulation-widget-pagination.ts

8.33% Statements 1/12
100% Branches 0/0
0% Functions 0/2
8.33% Lines 1/12

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          51x                                                            
import { useEffect, useState } from 'react';
 
import { getPageCount } from '@allshares/studio-design-system';
import { useResizeObserver } from '@amalia/ext/react/hooks';
 
export const useSimulationWidgetPagination = (totalItems: number, widgetBlockSizePx: number) => {
  const minContainerWidth = widgetBlockSizePx * 2;
  const [{ width: containerWidth }, setContainerWidth] = useState({ width: minContainerWidth });
  const containerRef = useResizeObserver({ onResize: setContainerWidth });
 
  // -1 because of the configuration block.
  // Make sure that pageSize is at least 1.
  const kpisPageSize = Math.max(Math.min(totalItems, Math.floor(containerWidth / widgetBlockSizePx) - 1), 1);
  const kpisPageCount = getPageCount(totalItems, kpisPageSize);
  const [kpisPage, setKpisPage] = useState(0);
 
  // Reset page when page size changes (container was resized because of the window).
  useEffect(() => {
    setKpisPage(0);
  }, [kpisPageSize]);
 
  const kpisInCurrentPage = Math.min(kpisPageSize, totalItems - kpisPage * kpisPageSize);
 
  const startIndex = kpisPage * kpisPageSize - (kpisPageSize - kpisInCurrentPage);
 
  return {
    minContainerWidth,
    containerRef,
    kpisPageSize,
    kpisPageCount,
    kpisPage,
    setKpisPage,
    startIndex,
  };
};