added advertising
This commit is contained in:
65
src/components/AdSlot.jsx
Normal file
65
src/components/AdSlot.jsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { API_URL } from '../config/authConstants';
|
||||
import { getAccessToken } from '../api/apiClient';
|
||||
import { normalizeMediaUrl } from '../api/adsApi';
|
||||
import AdCard from './AdCard';
|
||||
|
||||
export default function AdSlot() {
|
||||
const slotRef = useRef(null);
|
||||
const [ad, setAd] = useState(null);
|
||||
const [closed, setClosed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (closed) return;
|
||||
const node = slotRef.current;
|
||||
if (!node) return;
|
||||
|
||||
let cancelled = false;
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (!entry.isIntersecting) return;
|
||||
observer.disconnect();
|
||||
|
||||
const token = getAccessToken();
|
||||
fetch(`${API_URL}/api/ads/next`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
||||
})
|
||||
.then((res) => {
|
||||
// 204 No Content — свободных объявлений нет, оставляем пустой слот
|
||||
if (res.status === 204) return null;
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
return res.json();
|
||||
})
|
||||
.then((data) => {
|
||||
if (!cancelled && data) {
|
||||
if (data.mediaUrl) data.mediaUrl = normalizeMediaUrl(data.mediaUrl);
|
||||
setAd(data);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
},
|
||||
{ rootMargin: '200px' }
|
||||
);
|
||||
|
||||
observer.observe(node);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [closed]);
|
||||
|
||||
const handleClose = () => setClosed(true);
|
||||
|
||||
if (closed) return null;
|
||||
|
||||
if (ad) {
|
||||
return (
|
||||
<div ref={slotRef} className="ad-slot">
|
||||
<AdCard ad={ad} onClose={handleClose} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Зарезервированная высота, чтобы место под объявление не «дёргало» ленту
|
||||
return <div ref={slotRef} className="ad-slot-placeholder" />;
|
||||
}
|
||||
Reference in New Issue
Block a user