import React, { useEffect, useState, useRef, useCallback } from 'react'; import { useTranslation } from 'react-i18next'; import Typography from '../Typography'; import Item from '../AnnotationItem'; import { watchScroll } from '../../helpers/utility'; import { getAnnotationText } from '../../helpers/annotation'; import { Body } from '../../global/sidebarStyled'; type Props = { isActive?: boolean; annotations: AnnotationType[]; viewport: ViewportType; scale: number; pdf: any; }; const AnnotationList: React.FC = ({ isActive = false, annotations, viewport, scale, pdf, }: Props) => { const { t } = useTranslation('sidebar'); const [renderQueue, setQueue] = useState([]); const containerRef = useRef(null); const innerRef = useRef(null); const getText = async ( page: number, position: PositionType[] ): Promise => { const text = await getAnnotationText({ pdf, viewport, scale, page, coords: position, }); return text; }; const scrollUpdate = useCallback( (state: ScrollStateType): void => { const innerHeight = innerRef.current?.offsetHeight || 0; const wrapperHeight = containerRef.current?.offsetHeight || 0; if ( wrapperHeight + state.lastY >= innerHeight && renderQueue.length !== annotations.length ) { const start = renderQueue.length; const end = renderQueue.length + 10; const newQueue = [...renderQueue, ...annotations.slice(start, end)]; setQueue(newQueue); } }, [renderQueue, annotations] ); useEffect(() => { const state = watchScroll(containerRef.current, scrollUpdate); return (): void => { state.subscriber.unsubscribe(); }; }, [scrollUpdate]); useEffect(() => { if (isActive) { setQueue(annotations.slice(0, 10)); } }, [isActive, annotations]); return (
{`${annotations.length} ${t('annotation')}`} {isActive && renderQueue.map((ele, index) => { const key = `annot_item_${index}`; const { obj_type, obj_attr: { page, bdcolor, position, transparency }, } = ele; const actualPage = page + 1; const prevAnnot = annotations[index - 1]; const prevPage = index > 0 && prevAnnot ? prevAnnot.obj_attr.page + 1 : -1; return ( => getText(actualPage, position as PositionType[]) } showPageNum={actualPage !== prevPage} /> ); })}
); }; export default AnnotationList;