Files
nahodka-front/src/components/FullscreenAdOverlay.jsx
SlimusMinus db37befb8d Support new backend contracts: single-flight refresh, ad impression tokens, error handling
- apiFetch: proactive refresh, cross-tab single-flight via Web Locks, no logout on transient errors
- AuthContext: save tokens returned on own login change, revoke refresh on logout, sync tabs
- Ads: X-Session-Id, impressionToken in impression/click, IAB viewability, safe http(s) targetUrl
- STOMP: refresh before CONNECT, stop reconnect loop on dead session, /user/queue/errors behind flag
- Auth form: password 8 chars / 72 bytes; 429/413 messages via describeApiError
- My posts with auth + moderation badges; post form step validation and field limits
- Map: escape user text in Yandex hint/template

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 02:03:42 +03:00

135 lines
5.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { openExternalUrl } from "../utils/safeUrl";
const SKIP_DELAY_SECONDS = 5;
/**
* FullscreenAdOverlay — полноэкранный оверлей поверх всего интерфейса
* (z-index выше всех модалок). Кнопка закрытия появляется через 5 секунд
* (тот же паттерн таймера, что и в AdCard). Клик по видео открывает targetUrl
* в новой вкладке (если задан), не закрывая оверлей.
*
* Звук: мобильные браузеры блокируют autoplay со звуком (и останавливают видео
* при попытке программного unmute), поэтому стартуем строго muted — автоплей
* гарантирован на любом устройстве. Звук включается только вручную кнопкой 🔊.
*/
export default function FullscreenAdOverlay({ ad, onClose }) {
const { t } = useTranslation();
const [remaining, setRemaining] = useState(SKIP_DELAY_SECONDS);
const [soundOn, setSoundOn] = useState(false);
const videoRef = useRef(null);
const closeRef = useRef(null);
const canClose = remaining <= 0;
// Фон под оверлеем не скроллится (на iOS иначе «уезжает» лента)
useEffect(() => {
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => { document.body.style.overflow = prev; };
}, []);
// Esc закрывает, как только появилась кнопка закрытия; фокус — на неё
useEffect(() => {
if (!canClose) return;
closeRef.current?.focus();
const onKey = (e) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [canClose, onClose]);
useEffect(() => {
if (remaining <= 0) return;
const timerId = setTimeout(() => setRemaining((r) => r - 1), 1000);
return () => clearTimeout(timerId);
}, [remaining]);
// Автоплей: снимаем muted как свойство ДО старта (атрибут на iOS не всегда
// применяется вовремя), и дополнительно пробуем play() ещё раз, когда
// браузер загрузил данные/может воспроизвести — это покрывает случаи,
// когда первый play() отклонился «NotReady»/«Abort". Никаких автоматических
// размуток — они останавливают видео на мобильных.
useEffect(() => {
const videoNode = videoRef.current;
if (!videoNode) return;
videoNode.muted = true;
const tryPlay = () => {
videoNode.muted = true;
const promise = videoNode.play();
if (promise) promise.catch(() => {});
};
tryPlay();
videoNode.addEventListener("loadeddata", tryPlay);
videoNode.addEventListener("canplay", tryPlay);
return () => {
videoNode.removeEventListener("loadeddata", tryPlay);
videoNode.removeEventListener("canplay", tryPlay);
};
}, []);
const handleVideoClick = () => {
videoRef.current?.play().catch(() => {});
// Только абсолютный http(s): targetUrl — данные с сервера
openExternalUrl(ad.targetUrl);
};
const handleToggleSound = (e) => {
e.stopPropagation();
const videoNode = videoRef.current;
if (!videoNode) return;
const nextMuted = !videoNode.muted;
videoNode.muted = nextMuted;
videoNode.play().catch(() => {});
setSoundOn(!nextMuted);
};
return (
<div className="fs-ad-overlay" role="dialog" aria-modal="true" aria-label={t('fullscreenAd.label')}>
<span className="fs-ad-label">{t('fullscreenAd.label')}</span>
<video
ref={(node) => {
videoRef.current = node;
if (node) node.muted = true; // свойство сразу при монтировании
}}
className="fs-ad-video"
src={ad.mediaUrl}
autoPlay
muted
controls={false}
playsInline
loop
preload="auto"
onClick={handleVideoClick}
/>
<button
type="button"
className="fs-ad-sound"
onClick={handleToggleSound}
aria-label={soundOn ? t('fullscreenAd.mute') : t('fullscreenAd.unmute')}
>
{soundOn ? "🔊" : "🔇"}
</button>
{!canClose ? (
<span className="fs-ad-skip-timer">
{t('fullscreenAd.closeIn', { seconds: remaining })}
</span>
) : (
<button
ref={closeRef}
type="button"
className="fs-ad-close"
onClick={onClose}
aria-label={t('common.close')}
>
✕
</button>
)}
</div>
);
}