'use client'; import { useFetch } from '@gitroom/helpers/utils/custom.fetch'; import useSWR from 'swr'; import { FC, useCallback, useState } from 'react'; import clsx from 'clsx'; import dayjs from 'dayjs'; import { useClickAway } from '@uidotdev/usehooks'; import ReactLoading from '@gitroom/frontend/components/layout/loading'; import { useT } from '@gitroom/react/translation/get.transation.service.client'; function replaceLinks(text: string) { const urlRegex = /(\bhttps?:\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gi; return text.replace( urlRegex, '$1' ); } export const ShowNotification: FC<{ notification: { createdAt: string; content: string; }; lastReadNotification: string; }> = (props) => { const { notification } = props; const [newNotification] = useState( new Date(notification.createdAt) > new Date(props.lastReadNotification) ); const createdAt = dayjs(notification.createdAt); const isWithin24h = dayjs().diff(createdAt, 'hour') < 24; const fullDate = createdAt.format('MMM D, YYYY h:mm A'); return (
{isWithin24h ? createdAt.fromNow() : fullDate}
); }; export const NotificationOpenComponent = () => { const fetch = useFetch(); const loadNotifications = useCallback(async () => { return await (await fetch('/notifications/list')).json(); }, []); const t = useT(); const { data, isLoading } = useSWR('notifications', loadNotifications); return (
{t('notifications', 'Notifications')}
{isLoading && (
)} {!isLoading && !data.notifications.length && (
{t('no_notifications', 'No notifications')}
)} {!isLoading && data.notifications.map( ( notification: { createdAt: string; content: string; }, index: number ) => ( ) )}
); }; const NotificationComponent = () => { const fetch = useFetch(); const [show, setShow] = useState(false); const loadNotifications = useCallback(async () => { return await (await fetch('/notifications')).json(); }, []); const { data, mutate } = useSWR('notifications-list', loadNotifications); const changeShow = useCallback(() => { mutate( { ...data, total: 0, }, { revalidate: false, } ); setShow(!show); }, [show, data]); const ref = useClickAway(() => setShow(false)); return (
{data && data.total > 0 && ( )}
{show && }
); }; export default NotificationComponent;