forked from mul-ink/mulink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useTextFolding.js
36 lines (32 loc) · 1.11 KB
/
useTextFolding.js
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
34
35
36
import { useState, useEffect, useRef } from "./deps.js";
export function useTextFolding(hooks){
const useInstance = (instance) => {
const { text, collapsed: isCollapsed = true, isFetching } = instance;
const [collapsed, setCollapsed] = useState(isCollapsed);
const [needToGrow, setNeedToGrow] = useState(false);
const textWrapperRef = useRef();
useEffect(() => {
const { current } = textWrapperRef;
const handleResize = () => {
if (current && (current.clientWidth < current.scrollWidth || current.clientHeight < current.scrollHeight)) {
setNeedToGrow(true);
} else if (collapsed) {
setNeedToGrow(false);
}
};
if (current) {
window.addEventListener('resize', handleResize);
handleResize();
}
return () => {
if (current) {
window.removeEventListener('resize', handleResize);
}
};
}, [textWrapperRef, text, isFetching, collapsed]);
Object.assign(instance, {
collapsed, setCollapsed, text, needToGrow, textWrapperRef,
});
};
hooks.useInstance.push(useInstance);
};