import { useState, useCallback, useContext, useEffect, createContext } from 'react' import { useQuery } from '@apollo/client' import Comment, { CommentSkeleton } from './comment' import Item from './item' import ItemJob from './item-job' import { NOTIFICATIONS } from '../fragments/notifications' import { useRouter } from 'next/router' import MoreFooter from './more-footer' import Invite from './invite' import { ignoreClick } from '../lib/clicks' import { timeSince } from '../lib/time' import Link from 'next/link' import Check from '../svgs/check-double-line.svg' import HandCoin from '../svgs/hand-coin-fill.svg' import { COMMENT_DEPTH_LIMIT } from '../lib/constants' import CowboyHatIcon from '../svgs/cowboy.svg' import BaldIcon from '../svgs/bald.svg' import { RootProvider } from './root' import { Alert } from 'react-bootstrap' import styles from './notifications.module.css' function Notification ({ n }) { switch (n.__typename) { case 'Earn': return case 'Invitification': return case 'InvoicePaid': return case 'Referral': return case 'Streak': return case 'Votification': return case 'Mention': return case 'JobChanged': return case 'Reply': return } console.error('__typename not supported:', n.__typename) return null } function NotificationLayout ({ children, onClick }) { return (
{ if (ignoreClick(e)) return onClick?.(e) }} > {children}
) } const defaultOnClick = (n, router) => () => { if (!n.item.title) { if (n.item.path.split('.').length > COMMENT_DEPTH_LIMIT + 1) { router.push({ pathname: '/items/[id]', query: { id: n.item.parentId, commentId: n.item.id } }, `/items/${n.item.parentId}`) } else { router.push({ pathname: '/items/[id]', query: { id: n.item.root.id, commentId: n.item.id } }, `/items/${n.item.root.id}`) } } else { router.push({ pathname: '/items/[id]', query: { id: n.item.id } }, `/items/${n.item.id}`) } } function Streak ({ n }) { function blurb (n) { const index = Number(n.id) % 6 const FOUND_BLURBS = [ 'The harsh frontier is no place for the unprepared. This hat will protect you from the sun, dust, and other elements Mother Nature throws your way.', 'A cowboy is nothing without a cowboy hat. Take good care of it, and it will protect you from the sun, dust, and other elements on your journey.', "This is not just a hat, it's a matter of survival. Take care of this essential tool, and it will shield you from the scorching sun and the elements.", "A cowboy hat isn't just a fashion statement. It's your last defense against the unforgiving elements of the Wild West. Hang onto it tight.", "A good cowboy hat is worth its weight in gold, shielding you from the sun, wind, and dust of the western frontier. Don't lose it.", 'Your cowboy hat is the key to your survival in the wild west. Treat it with respect and it will protect you from the elements.' ] const LOST_BLURBS = [ 'your cowboy hat was taken by the wind storm that blew in from the west. No worries, a true cowboy always finds another hat.', "you left your trusty cowboy hat in the saloon before leaving town. You'll need a replacement for the long journey west.", 'you lost your cowboy hat in a wild shoot-out on the outskirts of town. Tough luck, tIme to start searching for another one.', 'you ran out of food and had to trade your hat for supplies. Better start looking for another hat.', "your hat was stolen by a mischievous prairie dog. You won't catch the dog, but you can always find another hat.", 'you lost your hat while crossing the river on your journey west. Maybe you can find a replacement hat in the next town.' ] if (n.days) { return `After ${n.days} days, ` + LOST_BLURBS[index] } return FOUND_BLURBS[index] } return (
{n.days ? : }
you {n.days ? 'lost your' : 'found a'} cowboy hat
{blurb(n)}
) } function EarnNotification ({ n }) { return (
you stacked {n.earnedSats} sats in rewards{timeSince(new Date(n.sortTime))}
{n.sources &&
{n.sources.posts > 0 && {n.sources.posts} sats for top posts} {n.sources.comments > 0 && {n.sources.posts > 0 && ' \\ '}{n.sources.comments} sats for top comments} {n.sources.tips > 0 && {(n.sources.comments > 0 || n.sources.posts > 0) && ' \\ '}{n.sources.tips} sats for tipping top content early}
}
SN distributes the sats it earns back to its best users daily. These sats come from jobs, boosts, posting fees, and donations. You can see the daily rewards pool and make a donation here.
) } function Invitification ({ n }) { const router = useRouter() return ( router.push('/invites')}> your invite has been redeemed by {n.invite.invitees.length} users
= n.invite.limit) } />
) } function InvoicePaid ({ n }) { const router = useRouter() return ( router.push(`/invoices/${n.invoice.id}`)}>
{n.earnedSats} sats were deposited in your account {timeSince(new Date(n.sortTime))}
) } function Referral ({ n }) { return ( someone joined via one of your referral links {timeSince(new Date(n.sortTime))} ) } function Votification ({ n }) { const router = useRouter() return ( your {n.item.title ? 'post' : 'reply'} {n.item.fwdUser ? 'forwarded' : 'stacked'} {n.earnedSats} sats{n.item.fwdUser && ` to @${n.item.fwdUser.name}`}
{n.item.title ? : (
)}
) } function Mention ({ n }) { const router = useRouter() return ( you were mentioned in
{n.item.title ? : (
)}
) } function JobChanged ({ n }) { const router = useRouter() return ( {n.item.status === 'ACTIVE' ? 'your job is active again' : (n.item.status === 'NOSATS' ? 'your job promotion ran out of sats' : 'your job has been stopped')} ) } function Reply ({ n }) { const router = useRouter() return (
{n.item.title ? : (
)}
) } function NotificationAlert () { const [showAlert, setShowAlert] = useState(false) const pushNotify = useNotification() useEffect(() => { // basically, we only want to show the alert if the user hasn't interacted with // either opt-in of the double opt-in setShowAlert(pushNotify.isDefault && !localStorage.getItem('hideNotifyPrompt')) }, [pushNotify]) const close = () => { localStorage.setItem('hideNotifyPrompt', 'yep') setShowAlert(false) } return ( showAlert ? ( Enable push notifications? ) : null ) } export default function Notifications ({ notifications, earn, cursor, lastChecked, variables }) { const { data, fetchMore } = useQuery(NOTIFICATIONS, { variables }) if (data) { ({ notifications: { notifications, earn, cursor } } = data) } const [fresh, old] = notifications.reduce((result, n) => { result[new Date(n.sortTime).getTime() > lastChecked ? 0 : 1].push(n) return result }, [[], []]) return ( <> {/* XXX we shouldn't use the index but we don't have a unique id in this union yet */}
{earn && } {fresh.map((n, i) => ( ))}
{old.map((n, i) => ( ))} ) } function CommentsFlatSkeleton () { const comments = new Array(21).fill(null) return (
{comments.map((_, i) => ( ))}
) } const NotificationContext = createContext({}) export const NotificationProvider = ({ children }) => { const isBrowser = typeof window !== 'undefined' const [isSupported] = useState(isBrowser ? 'Notification' in window : false) const [permission, setPermission_] = useState( isSupported ? window.Notification.permission === 'granted' // if permission was granted, we need to check if user has withdrawn permission using the settings // since requestPermission only works once ? localStorage.getItem('notify-permission') ?? window.Notification.permission : window.Notification.permission : 'unsupported') const isDefault = permission === 'default' const isGranted = permission === 'granted' const isDenied = permission === 'denied' const isWithdrawn = permission === 'withdrawn' const show_ = (title, options) => { const icon = '/android-chrome-24x24.png' return new window.Notification(title, { icon, ...options }) } const show = useCallback((...args) => { if (!isGranted) return show_(...args) }, [isGranted]) const setPermission = useCallback((perm) => { localStorage.setItem('notify-permission', perm) setPermission_(perm) }, []) const requestPermission = useCallback((cb) => { window.Notification.requestPermission().then(result => { setPermission(window.Notification.permission) if (result === 'granted') show_('Stacker News notifications enabled') cb?.(result) }) }, []) const withdrawPermission = useCallback(() => isGranted ? setPermission('withdrawn') : null, [isGranted]) const ctx = { isBrowser, isSupported, isDefault, isGranted, isDenied, isWithdrawn, requestPermission, withdrawPermission, show } return {children} } export function useNotification () { return useContext(NotificationContext) }