overleaf/services/web/frontend/js/ide/outline/components/OutlineItem.js
Paulo Jorge Reis 4e3a9d4fa8 Merge pull request #3070 from overleaf/ta-outline-scroll-fixes
Outline Scroll Fixes

GitOrigin-RevId: 14bff01ab7678d363884bd8525ad3f7e60acacb4
2020-08-10 15:55:30 +00:00

90 lines
2.4 KiB
JavaScript

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 (
<li className={mainItemClasses}>
<div className="outline-item-row">
{outlineItem.children ? (
<button
className="outline-item-expand-collapse-btn"
onClick={handleExpandCollapseClick}
>
<i className={expandCollapseIconClasses} />
</button>
) : null}
<button
className={itemLinkClasses}
onClick={handleOutlineItemLinkClick}
ref={titleElementRef}
>
{outlineItem.title}
</button>
</div>
{expanded && outlineItem.children ? (
<OutlineList
outline={outlineItem.children}
jumpToLine={jumpToLine}
isRoot={false}
highlightedLine={highlightedLine}
/>
) : null}
</li>
)
}
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