| 1 |
import { track } from '@shared/lib/track'; |
| 2 |
import { useEffect, useState } from '@wordpress/element'; |
| 3 |
import { resolveNotificationLink, siteHost } from './notification-link'; |
| 4 |
import { notificationFor } from './selection'; |
| 5 |
import { fillsSlot, ignoresDismissal, templateFor } from './slots'; |
| 6 |
import { useNotificationsStore } from './state'; |
| 7 |
|
| 8 |
export const Notification = ({ slot }) => { |
| 9 |
const { |
| 10 |
dismissBanner, |
| 11 |
isDismissedBanner, |
| 12 |
recordNotificationView, |
| 13 |
recordNotificationClick, |
| 14 |
} = useNotificationsStore(); |
| 15 |
const Template = templateFor(slot); |
| 16 |
|
| 17 |
// Frozen at mount so dismissing doesn't reveal the next notification until reload. |
| 18 |
const [notification] = useState(() => notificationFor(slot)); |
| 19 |
|
| 20 |
const slug = notification?.slug; |
| 21 |
const source = notification?.source; |
| 22 |
// Only wp-admin defines pagenow; frontend slots never mount there. |
| 23 |
const page = |
| 24 |
window.pagenow ?? (slot.startsWith('frontend-') ? 'frontend' : ''); |
| 25 |
const { href, external } = resolveNotificationLink(notification, siteHost()); |
| 26 |
const renders = |
| 27 |
Boolean(Template && notification) && |
| 28 |
fillsSlot(slot, notification, href) && |
| 29 |
(ignoresDismissal(slot) || !isDismissedBanner(slug)); |
| 30 |
|
| 31 |
useEffect(() => { |
| 32 |
if (!renders || !slug) return; |
| 33 |
track('notification_view', { slug, slot, page, source }); |
| 34 |
recordNotificationView(slug); |
| 35 |
}, [renders, slug, slot, page, source, recordNotificationView]); |
| 36 |
|
| 37 |
if (!renders) return null; |
| 38 |
|
| 39 |
const dismiss = () => { |
| 40 |
track('notification_dismiss', { slug, slot, page, source }); |
| 41 |
dismissBanner(slug); |
| 42 |
}; |
| 43 |
|
| 44 |
const click = () => { |
| 45 |
track('notification_click', { slug, slot, page, source }); |
| 46 |
recordNotificationClick(slug); |
| 47 |
}; |
| 48 |
|
| 49 |
return ( |
| 50 |
<div className="extendify-shared"> |
| 51 |
<Template |
| 52 |
notification={notification} |
| 53 |
href={href} |
| 54 |
external={external} |
| 55 |
onDismiss={dismiss} |
| 56 |
onClick={click} |
| 57 |
/> |
| 58 |
</div> |
| 59 |
); |
| 60 |
}; |
| 61 |
|