-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathuseSyncTotalWidth.ts
More file actions
33 lines (28 loc) · 1.08 KB
/
useSyncTotalWidth.ts
File metadata and controls
33 lines (28 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { useLayoutEffect } from 'react'
interface UseSyncTotalWidthArgs {
textAreaRef: React.RefObject<HTMLTextAreaElement>
widthDivRef: React.RefObject<HTMLDivElement>
}
export const useSyncTotalWidth = ({
textAreaRef,
widthDivRef,
}: UseSyncTotalWidthArgs) => {
// this effect sets an empty div to the width of the text area so the code highlight div can scroll horizontally
useLayoutEffect(() => {
// if the text area or width div ref is not available, return
if (!textAreaRef.current || !widthDivRef.current) return
// create a resize observer to watch the text area for changes in width so once the text area is resized, the width div can be updated
const resize = new ResizeObserver((entries) => {
const entry = entries?.[0]
if (widthDivRef.current && entry) {
widthDivRef.current.style.width = `${entry.target.scrollWidth}px`
}
})
// observe the text area for changes
resize.observe(textAreaRef.current)
return () => {
// disconnect the resize observer
resize.disconnect()
}
}, [textAreaRef, widthDivRef])
}