improve floating-ui placement of reply quote preview

This commit is contained in:
Tom (plebeius.eth)
2024-06-06 10:06:31 +02:00
parent b44fb15078
commit a6e0ea6f80
@@ -4,7 +4,7 @@ import { Trans, useTranslation } from 'react-i18next';
import { Link, useLocation, useParams } from 'react-router-dom'; import { Link, useLocation, useParams } from 'react-router-dom';
import { Comment, useAccount, useBlock } from '@plebbit/plebbit-react-hooks'; import { Comment, useAccount, useBlock } from '@plebbit/plebbit-react-hooks';
import Plebbit from '@plebbit/plebbit-js/dist/browser/index.js'; import Plebbit from '@plebbit/plebbit-js/dist/browser/index.js';
import { useFloating, shift, size, autoUpdate, Placement } from '@floating-ui/react'; import { useFloating, offset, shift, size, autoUpdate, Placement } from '@floating-ui/react';
import styles from '../post.module.css'; import styles from '../post.module.css';
import { getCommentMediaInfo, getDisplayMediaInfoType, getHasThumbnail } from '../../../lib/utils/media-utils'; import { getCommentMediaInfo, getDisplayMediaInfoType, getHasThumbnail } from '../../../lib/utils/media-utils';
import { getFormattedDate } from '../../../lib/utils/time-utils'; import { getFormattedDate } from '../../../lib/utils/time-utils';
@@ -34,18 +34,21 @@ const ReplyLink = ({
hoveredCid: string | null; hoveredCid: string | null;
setHoveredCid: (cid: string | null) => void; setHoveredCid: (cid: string | null) => void;
}) => { }) => {
const [placement, setPlacement] = useState<Placement>('right'); const placementRef = useRef<Placement>('right');
const availableWidthRef = useRef<number>(0);
const { refs, floatingStyles, update } = useFloating({ const { refs, floatingStyles, update } = useFloating({
placement, placement: placementRef.current,
middleware: [ middleware: [
shift({ padding: 10 }), shift({ padding: 10 }),
offset({ mainAxis: placementRef.current === 'right' ? 8 : 4 }),
size({ size({
apply({ availableWidth, elements }) { apply({ availableWidth, elements }) {
availableWidthRef.current = availableWidth;
if (availableWidth >= 250) { if (availableWidth >= 250) {
elements.floating.style.maxWidth = `${availableWidth - 5}px`; elements.floating.style.maxWidth = `${availableWidth - 12}px`;
} else { } else if (placementRef.current === 'right') {
setPlacement('left'); placementRef.current = 'left';
} }
}, },
}), }),
@@ -54,8 +57,21 @@ const ReplyLink = ({
}); });
useEffect(() => { useEffect(() => {
update(); const handleResize = () => {
}, [placement, update]); const availableWidth = availableWidthRef.current;
if (availableWidth >= 250) {
placementRef.current = 'right';
} else {
placementRef.current = 'left';
}
update();
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [update]);
return ( return (
<span className={styles.backlink}> <span className={styles.backlink}>