fix: useDetectOverflow support resize

This commit is contained in:
Shusui MOYATANI
2023-12-18 21:34:16 +09:00
parent e3f30b0e30
commit 750fd3c47a
2 changed files with 21 additions and 6 deletions

View File

@@ -21,7 +21,7 @@ const Post: Component<PostProps> = (props) => {
const { overflow, elementRef } = useDetectOverflow();
const formatDate = useFormatDate();
const [showOverflow, setShowOverflow] = createSignal();
const [showOverflow, setShowOverflow] = createSignal(false);
const createdAt = () => formatDate(props.createdAt);
const createdAtFull = () => props.createdAt.toLocaleString();
@@ -88,7 +88,7 @@ const Post: Component<PostProps> = (props) => {
<div
ref={elementRef}
class="overflow-hidden"
classList={{ 'max-h-screen': !showOverflow() }}
classList={{ 'max-h-screen': !showOverflow(), 'max-h-none': showOverflow() }}
>
{props.content}
</div>

View File

@@ -1,8 +1,16 @@
import { createSignal, onMount, onCleanup } from 'solid-js';
import throttle from 'lodash/throttle';
// TODO Find a better way to solve this. Firefox on Windows can cause 2px gap.
const Offset = 2;
const ThrottleWaitMs = 200;
/**
* Detect overflow if the height of the target element content is bigger than
* actual displayed height or window height.
*/
const useDetectOverflow = () => {
let elementRef: HTMLElement | undefined;
const [overflow, setOverflow] = createSignal(false);
@@ -11,11 +19,14 @@ const useDetectOverflow = () => {
elementRef = el;
};
const detectOverflow = () => {
const detectOverflow = throttle(() => {
if (elementRef != null) {
setOverflow(elementRef.scrollHeight > elementRef.clientHeight + Offset);
setOverflow(
elementRef.scrollHeight > elementRef.clientHeight + Offset ||
elementRef.scrollHeight > document.documentElement.clientHeight + Offset,
);
}
};
}, ThrottleWaitMs);
onMount(() => {
if (elementRef != null) {
@@ -30,13 +41,17 @@ const useDetectOverflow = () => {
});
},
{
threshold: [0, 0.5, 1],
threshold: 0,
},
);
observer.observe(elementRef);
const handleResize = () => detectOverflow();
window.addEventListener('resize', handleResize);
onCleanup(() => {
observer.disconnect();
window.removeEventListener('resize', handleResize);
});
}
});