mirror of
https://github.com/hedgedoc/hedgedoc.git
synced 2025-05-15 15:44:45 -04:00
extract scroll code from renderer into hook
Signed-off-by: Tilman Vatteroth <tilman.vatteroth@tu-dortmund.de>
This commit is contained in:
parent
4603e3988a
commit
0750695e2f
3 changed files with 91 additions and 75 deletions
41
src/components/editor/scroll/hooks/use-user-scroll.ts
Normal file
41
src/components/editor/scroll/hooks/use-user-scroll.ts
Normal file
|
@ -0,0 +1,41 @@
|
|||
import { RefObject, useCallback } from 'react'
|
||||
import { LineMarkerPosition } from '../../../markdown-renderer/types'
|
||||
import { ScrollState } from '../scroll-props'
|
||||
|
||||
export const useUserScroll = (lineMarks: LineMarkerPosition[] | undefined, renderer: RefObject<HTMLElement>, onScroll: ((newScrollState: ScrollState) => void)|undefined): () => void =>
|
||||
useCallback(() => {
|
||||
if (!renderer.current || !lineMarks || lineMarks.length === 0 || !onScroll) {
|
||||
return
|
||||
}
|
||||
|
||||
const scrollTop = renderer.current.scrollTop
|
||||
|
||||
const lineMarksBeforeScrollTop = lineMarks.filter(lineMark => lineMark.position <= scrollTop)
|
||||
if (lineMarksBeforeScrollTop.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const lineMarksAfterScrollTop = lineMarks.filter(lineMark => lineMark.position > scrollTop)
|
||||
if (lineMarksAfterScrollTop.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const beforeLineMark = lineMarksBeforeScrollTop
|
||||
.reduce((prevLineMark, currentLineMark) =>
|
||||
prevLineMark.line >= currentLineMark.line ? prevLineMark : currentLineMark)
|
||||
|
||||
const afterLineMark = lineMarksAfterScrollTop
|
||||
.reduce((prevLineMark, currentLineMark) =>
|
||||
prevLineMark.line < currentLineMark.line ? prevLineMark : currentLineMark)
|
||||
|
||||
const componentHeight = afterLineMark.position - beforeLineMark.position
|
||||
const distanceToBefore = scrollTop - beforeLineMark.position
|
||||
const percentageRaw = (distanceToBefore / componentHeight)
|
||||
const lineCount = afterLineMark.line - beforeLineMark.line
|
||||
const line = Math.floor(lineCount * percentageRaw + beforeLineMark.line)
|
||||
const lineHeight = componentHeight / lineCount
|
||||
const innerScrolling = Math.floor((distanceToBefore % lineHeight) / lineHeight * 100)
|
||||
|
||||
const newScrollState: ScrollState = { firstLineInView: line, scrolledPercentage: innerScrolling }
|
||||
onScroll(newScrollState)
|
||||
}, [lineMarks, onScroll, renderer])
|
Loading…
Add table
Add a link
Reference in a new issue