predikt/oracle/web/components/notifications/notification-helpers.tsx
caelum0x 2b68bde5d5 Predikt: full Polymarket-style prediction market — web + mobile + on-chain + bots
Working tree is now the canonical repo. Off-chain play-money + trustless on-chain
(FPMM AMM + CLOB via UMA settlement), AI market factory, creator/social/distribution,
mobile shell + push, one-command demo + deploy-kit. Secrets excluded (see ENV-AND-KEYS.md).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 23:29:50 +03:00

369 lines
11 KiB
TypeScript

import clsx from 'clsx'
import { getSourceUrl, Notification } from 'common/notification'
import Link from 'next/link'
import { KeyboardEvent, MouseEvent, ReactNode } from 'react'
import { RelativeTimestamp } from 'web/components/relative-timestamp'
import { Col } from 'web/components/layout/col'
import { Avatar } from 'web/components/widgets/avatar'
import { Linkify } from 'web/components/widgets/linkify'
import { useIsMobile } from 'web/hooks/use-is-mobile'
import { track } from 'web/lib/service/analytics'
import { Row } from '../layout/row'
import { truncateText } from '../widgets/truncate'
import NotificationDropdown from './notification-dropdown'
import { SparklesIcon, XCircleIcon } from '@heroicons/react/solid'
import { UserLink } from '../widgets/user-link'
import { UserHovercard } from '../user/user-hovercard'
import { Button } from '../buttons/button'
function getHighlightClass(highlight: boolean) {
return highlight ? 'text-ink-1000 bg-primary-50' : 'text-ink-700'
}
export const NUM_SUMMARY_LINES = 3
export const NOTIFICATION_ICON_SIZE = 'md'
const INTERACTIVE_NOTIFICATION_CHILD_SELECTOR =
'a, button, input, textarea, select, summary, [role="button"], [role="link"], [data-stop-notification-click]'
const getInteractiveChild = (event: MouseEvent | KeyboardEvent) => {
const target = event.target
if (!(target instanceof Element)) return null
const interactive = target.closest(INTERACTIVE_NOTIFICATION_CHILD_SELECTOR)
// If the notification row itself is the closest interactive element (e.g.
// role="button" for modal-style notifications), that is the row action, not
// a nested control that should suppress the row action.
if (!interactive || interactive === event.currentTarget) return null
return event.currentTarget.contains(interactive) ? interactive : null
}
const isFromInteractiveChild = (event: MouseEvent | KeyboardEvent) =>
!!getInteractiveChild(event)
const isFromNestedLink = (event: MouseEvent) => {
const interactive = getInteractiveChild(event)
return !!interactive?.closest('a[href]')
}
// TODO: fix badges (id based)
export function NotificationUserLink(props: {
userId?: string
name?: string
username?: string
className?: string
hideBadge?: boolean
}) {
const { userId, name, username, className, hideBadge } = props
return (
<UserHovercard userId={userId ?? ''}>
<UserLink
user={{ id: userId || '', name: name || '', username: username || '' }}
className={clsx(
className ?? 'hover:text-primary-500 relative flex-shrink-0'
)}
hideBadge={hideBadge}
displayContext="notifications"
/>
</UserHovercard>
)
}
export function PrimaryNotificationLink(props: {
text: string | undefined
truncatedLength?: 'sm' | 'md' | 'lg' | 'xl' | 'none'
}) {
const { text, truncatedLength } = props
if (!text) {
return <></>
}
// Defensive: ensure text is a string (handles cases where an object was incorrectly stored)
let textString: string
if (typeof text === 'string') {
textString = text
} else if (typeof text === 'object' && text !== null) {
// Try to extract a meaningful string from common object shapes
const obj = text as Record<string, unknown>
textString =
typeof obj.question === 'string'
? obj.question
: typeof obj.title === 'string'
? obj.title
: typeof obj.text === 'string'
? obj.text
: JSON.stringify(text)
} else {
textString = String(text)
}
return (
<span className="hover:text-primary-500 font-semibold transition-colors">
{truncatedLength
? truncateText(textString, truncatedLength ?? 'xl')
: textString}
</span>
)
}
export function QuestionOrGroupLink(props: {
notification: Notification
truncatedLength?: 'sm' | 'md' | 'lg' | 'xl' | 'none'
ignoreClick?: boolean
}) {
const { notification, ignoreClick, truncatedLength } = props
const {
sourceType,
sourceContractTitle,
sourceContractCreatorUsername,
sourceContractSlug,
sourceSlug,
sourceTitle,
} = notification
let title = sourceContractTitle || sourceTitle
if (truncatedLength) {
title = truncateText(title, truncatedLength)
}
if (ignoreClick) return <span className={'font-bold '}>{title}</span>
return (
<Link
className={'hover:text-primary-500 relative font-semibold'}
href={getSourceUrl(notification).split('#')[0]}
onClick={(e) => {
e.stopPropagation()
track('Notification Clicked', {
type: 'question title',
sourceType,
sourceContractTitle,
sourceContractCreatorUsername,
sourceContractSlug,
sourceSlug,
sourceTitle,
})
}}
>
{title}
</Link>
)
}
export function NotificationTextLabel(props: {
notification: Notification
className?: string
}) {
const { className, notification } = props
const { sourceText, reasonText } = notification
const defaultText = sourceText ?? reasonText ?? ''
return (
<div className={className ? className : 'line-clamp-4 whitespace-pre-line'}>
<Linkify text={defaultText} />
</div>
)
}
export function AvatarNotificationIcon(props: {
notification: Notification
symbol: string | ReactNode
}) {
const { notification, symbol } = props
const { sourceUserName, sourceUserAvatarUrl, sourceUserUsername } =
notification
const href = `/${sourceUserUsername}`
return (
<div className="relative">
<Link
href={href}
target={href.startsWith('http') ? '_blank' : undefined}
onClick={(e) => e.stopPropagation()}
>
<Avatar
username={sourceUserName}
avatarUrl={sourceUserAvatarUrl}
size={NOTIFICATION_ICON_SIZE}
noLink={true}
displayContext="notifications"
/>
<div className="absolute -bottom-2 -right-1 text-lg">{symbol}</div>
</Link>
</div>
)
}
export function NotificationIcon(props: {
symbol: string | ReactNode
symbolBackgroundClass: string
}) {
const { symbol, symbolBackgroundClass } = props
return (
<Col
className={clsx(
'h-10 w-10 justify-center rounded-full',
symbolBackgroundClass
)}
>
<div className="mx-auto text-2xl">{symbol}</div>
</Col>
)
}
// the primary skeleton for notifications
export function NotificationFrame(props: {
notification: Notification
highlighted: boolean
setHighlighted: (highlighted: boolean) => void
children: React.ReactNode
icon: ReactNode
link?: string
onClick?: () => void
subtitle?: string | ReactNode
isChildOfGroup?: boolean
customBackground?: ReactNode
isPinned?: boolean
onDismiss?: () => void
}) {
const {
notification,
highlighted,
setHighlighted,
children,
icon,
subtitle,
onClick,
link,
customBackground,
isPinned,
onDismiss,
} = props
const isMobile = useIsMobile()
const markAsSeen = () => {
if (highlighted) {
setHighlighted(false)
}
}
const handleFrameClickCapture = (event: MouseEvent<HTMLDivElement>) => {
// If the user follows a nested notification link, count the notification as
// seen, but still let that link own navigation. Buttons/dropdowns are not
// marked seen here because they may just open a menu or dismiss a pin.
if (isFromNestedLink(event)) markAsSeen()
}
const handleActionClick = (event: MouseEvent<HTMLDivElement>) => {
// Nested links/buttons inside notification copy should win over modal-style
// notification actions.
if (isFromInteractiveChild(event)) return
markAsSeen()
onClick?.()
}
const handleActionKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key !== 'Enter' && event.key !== ' ') return
if (isFromInteractiveChild(event)) return
event.preventDefault()
markAsSeen()
onClick?.()
}
const handleOverlayLinkClick = () => {
markAsSeen()
onClick?.()
}
const frameObject = (
<Row className="cursor-pointer text-sm md:text-base">
<Row className="w-full items-start gap-3">
<Col className="relative h-full w-10 items-center">{icon}</Col>
<Col className="font w-full">
<span>{children}</span>
<div className="mt-1 line-clamp-3 text-xs md:text-sm">{subtitle}</div>
</Col>
<Col className="h-full items-end justify-between gap-1">
<Row className="mt-1 justify-end gap-1 sm:w-36">
{highlighted && !isMobile && (
<SparklesIcon className="text-primary-600 h-4 w-4" />
)}
<RelativeTimestamp
time={notification.createdTime}
shortened={isMobile}
className={clsx(
'text-xs',
highlighted ? 'text-primary-600' : 'text-ink-700'
)}
/>
<NotificationDropdown notification={notification} />
</Row>
{isPinned && onDismiss && (
<Button
color="gray-white"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onDismiss()
}}
className="text-ink-500 hover:text-ink-700 "
>
<XCircleIcon className="h-5 w-5" />
</Button>
)}
</Col>
</Row>
</Row>
)
return (
<Row
className={clsx(
'group relative p-2 transition-colors',
isPinned && 'bg-primary-50',
'hover:bg-primary-100',
getHighlightClass(highlighted)
)}
onClickCapture={handleFrameClickCapture}
onAuxClickCapture={handleFrameClickCapture}
onClick={!link && onClick ? handleActionClick : undefined}
onKeyDown={!link && onClick ? handleActionKeyDown : undefined}
role={!link && onClick ? 'button' : undefined}
tabIndex={!link && onClick ? 0 : undefined}
>
{customBackground}
{link && (
<Link
href={link}
aria-label="Open notification"
className="focus-visible:outline-primary-500 absolute inset-0 z-0 cursor-pointer focus-visible:outline focus-visible:outline-2"
onClick={handleOverlayLinkClick}
/>
)}
<Col
className={clsx(
'relative z-10 w-full',
// For link-backed notifications, let non-interactive content clicks
// pass through to the sibling overlay <Link>, while real nested
// controls keep their own pointer handling.
link &&
'pointer-events-none [&_[data-stop-notification-click]]:pointer-events-auto [&_[role=button]]:pointer-events-auto [&_[role=link]]:pointer-events-auto [&_a]:pointer-events-auto [&_button]:pointer-events-auto [&_input]:pointer-events-auto [&_select]:pointer-events-auto [&_summary]:pointer-events-auto [&_textarea]:pointer-events-auto'
)}
>
{frameObject}
</Col>
</Row>
)
}
export function ParentNotificationHeader(props: {
children: ReactNode
highlighted: boolean
}) {
const { children, highlighted } = props
const highlightedClass = getHighlightClass(highlighted)
return (
<div className={clsx('line-clamp-3 px-2 pt-3 text-base', highlightedClass)}>
{children}
</div>
)
}