Refactor truncated class

Also removed the hack fix, not sure why/how it's even fixed.
Don't even know how to explain the logic.
Will revisit and investigate more if the bug happens.

This `useTruncated` can now be reusable.
This commit is contained in:
Lim Chee Aun 2023-09-19 16:27:22 +08:00
parent 42f9483491
commit f9b2ab3b94
2 changed files with 20 additions and 34 deletions

View file

@ -48,6 +48,7 @@ import showToast from '../utils/show-toast';
import states, { getStatus, saveStatus, statusKey } from '../utils/states';
import statusPeek from '../utils/status-peek';
import store from '../utils/store';
import useTruncated from '../utils/useTruncated';
import visibilityIconsMap from '../utils/visibility-icons-map';
import Avatar from './avatar';
@ -318,40 +319,8 @@ function Status({
const [showEdited, setShowEdited] = useState(false);
const [showReactions, setShowReactions] = useState(false);
const spoilerContentRef = useRef(null);
useResizeObserver({
ref: spoilerContentRef,
onResize: () => {
if (spoilerContentRef.current) {
const { scrollHeight, clientHeight } = spoilerContentRef.current;
if (scrollHeight < window.innerHeight * 0.4) {
spoilerContentRef.current.classList.remove('truncated');
} else {
spoilerContentRef.current.classList.toggle(
'truncated',
scrollHeight > clientHeight,
);
}
}
},
});
const contentRef = useRef(null);
useResizeObserver({
ref: contentRef,
onResize: () => {
if (contentRef.current) {
const { scrollHeight, clientHeight } = contentRef.current;
if (scrollHeight < window.innerHeight * 0.4) {
contentRef.current.classList.remove('truncated');
} else {
contentRef.current.classList.toggle(
'truncated',
scrollHeight > clientHeight,
);
}
}
},
});
const spoilerContentRef = useTruncated();
const contentRef = useTruncated();
const readMoreText = 'Read more →';
const statusRef = useRef(null);

17
src/utils/useTruncated.js Normal file
View file

@ -0,0 +1,17 @@
import { useRef } from 'preact/hooks';
import useResizeObserver from 'use-resize-observer';
export default function useTruncated({ className = 'truncated' } = {}) {
const ref = useRef();
useResizeObserver({
ref,
box: 'border-box',
onResize: ({ height }) => {
if (ref.current) {
const { scrollHeight } = ref.current;
ref.current.classList.toggle(className, scrollHeight > height);
}
},
});
return ref;
}