import React, { useState, useEffect, createRef, useRef } from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import OutlineList from './OutlineList' function OutlineItem({ outlineItem, jumpToLine, highlightedLine }) { const [expanded, setExpanded] = useState(true) const titleElementRef = createRef() const isHighlightedRef = useRef(false) const mainItemClasses = classNames('outline-item', { 'outline-item-no-children': !outlineItem.children }) const expandCollapseIconClasses = classNames('fa', 'outline-caret-icon', { 'fa-angle-down': expanded, 'fa-angle-right': !expanded }) const itemLinkClasses = classNames('outline-item-link', { 'outline-item-link-highlight': highlightedLine === outlineItem.line }) function handleExpandCollapseClick() { setExpanded(!expanded) } function handleOutlineItemLinkClick() { jumpToLine(outlineItem.line) } useEffect( () => { const wasHighlighted = isHighlightedRef.current const isNowHighlighted = highlightedLine === outlineItem.line isHighlightedRef.current = isNowHighlighted if (!wasHighlighted && isNowHighlighted) { titleElementRef.current.scrollIntoView({ block: 'center' }) } }, [highlightedLine, titleElementRef, isHighlightedRef] ) return (
  • {outlineItem.children ? ( ) : null}
    {expanded && outlineItem.children ? ( ) : null}
  • ) } OutlineItem.propTypes = { outlineItem: PropTypes.exact({ line: PropTypes.number.isRequired, title: PropTypes.string.isRequired, level: PropTypes.number.isRequired, children: PropTypes.array }).isRequired, jumpToLine: PropTypes.func.isRequired, highlightedLine: PropTypes.number } export default OutlineItem