import { RefObject } from 'react'; import React, { FC, memo, useEffect, useRef, } from '../../../lib/teact/teact'; import { getDispatch, withGlobal } from '../../../lib/teact/teactn'; import { ApiChat, ApiSponsoredMessage, ApiUser } from '../../../api/types'; import { renderTextWithEntities } from '../../common/helpers/renderMessageText'; import { selectChat, selectSponsoredMessage, selectUser } from '../../../modules/selectors'; import { getChatTitle, getUserFullName } from '../../../modules/helpers'; import renderText from '../../common/helpers/renderText'; import useLang from '../../../hooks/useLang'; import { useIntersectionObserver } from '../../../hooks/useIntersectionObserver'; import Button from '../../ui/Button'; import './SponsoredMessage.scss'; type OwnProps = { chatId: string; containerRef: RefObject; }; type StateProps = { message?: ApiSponsoredMessage; bot?: ApiUser; channel?: ApiChat; }; const INTERSECTION_DEBOUNCE_MS = 200; const SponsoredMessage: FC = ({ chatId, message, containerRef, bot, channel, }) => { const { viewSponsoredMessage, openChat, openChatByInvite, startBot, focusMessage, } = getDispatch(); const lang = useLang(); // eslint-disable-next-line no-null/no-null const contentRef = useRef(null); const shouldObserve = Boolean(message); const { observe: observeIntersection, } = useIntersectionObserver({ rootRef: containerRef, debounceMs: INTERSECTION_DEBOUNCE_MS, threshold: 1, }); useEffect(() => { return shouldObserve ? observeIntersection(contentRef.current!, (target) => { if (target.isIntersecting) { viewSponsoredMessage({ chatId }); } }) : undefined; }, [chatId, shouldObserve, observeIntersection, viewSponsoredMessage]); if (!message) { return undefined; } const handleClick = () => { if (message.chatInviteHash) { openChatByInvite({ hash: message.chatInviteHash }); } else if (message.channelPostId) { focusMessage({ chatId: message.chatId, messageId: message.channelPostId }); } else { openChat({ id: message.chatId }); if (message.startParam) { startBot({ botId: message.chatId, param: message.startParam, }); } } }; return (
{bot && renderText(getUserFullName(bot) || '')} {channel && renderText(message.chatInviteTitle || getChatTitle(lang, channel, bot) || '')}

{renderTextWithEntities(message.text.text, message.text.entities)} {lang('SponsoredMessage')}

); }; export default memo(withGlobal( (global, { chatId }): StateProps => { const message = selectSponsoredMessage(global, chatId); const { chatId: fromChatId, isBot } = message || {}; return { message, bot: fromChatId && isBot ? selectUser(global, fromChatId) : undefined, channel: !isBot && fromChatId ? selectChat(global, fromChatId) : undefined, }; }, )(SponsoredMessage));