From f9b2ab3b940f209c3d1f6c5e10d964e2c2cf1b75 Mon Sep 17 00:00:00 2001 From: Lim Chee Aun Date: Tue, 19 Sep 2023 16:27:22 +0800 Subject: [PATCH] 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. --- src/components/status.jsx | 37 +++---------------------------------- src/utils/useTruncated.js | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 34 deletions(-) create mode 100644 src/utils/useTruncated.js diff --git a/src/components/status.jsx b/src/components/status.jsx index dc24b308..c72b4d1f 100644 --- a/src/components/status.jsx +++ b/src/components/status.jsx @@ -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); diff --git a/src/utils/useTruncated.js b/src/utils/useTruncated.js new file mode 100644 index 00000000..7d71842d --- /dev/null +++ b/src/utils/useTruncated.js @@ -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; +}