import React, { useEffect, useState, useRef, useCallback, } from 'react'; import { WithTranslation } from 'next-i18next'; import { withTranslation } from '../../i18n'; import Typography from '../Typography'; import Item from '../AnnotationItem'; import { AnnotationType, ViewportType, ScrollStateType, PositionType, } from '../../constants/type'; import { watchScroll } from '../../helpers/utility'; import { getAnnotationText } from '../../helpers/annotation'; import { Body } from '../../global/sidebarStyled'; type i18nProps = { t: (key: string) => string; }; type OwnerProps = { isActive?: boolean; annotations: AnnotationType[]; viewport: ViewportType; scale: number; pdf: any; }; type Props = i18nProps & OwnerProps; const AnnotationList: React.FC = ({ t, isActive = false, annotations, viewport, scale, pdf, }: Props) => { 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]); 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} /> ); })}
); }; const translator = withTranslation('sidebar'); type TransProps = WithTranslation & OwnerProps; export default translator(AnnotationList);