Whalebird-desktop-client-ma.../renderer/components/timelines/Notifications.tsx

244 lines
8.9 KiB
TypeScript
Raw Normal View History

2023-11-04 10:14:00 +01:00
import { Account } from '@/db'
2023-11-05 17:09:32 +01:00
import generator, { Entity, MegalodonInterface, WebSocketInterface } from 'megalodon'
2023-12-02 11:26:45 +01:00
import { useEffect, useState, useCallback, useRef, Dispatch, SetStateAction } from 'react'
2023-11-04 10:14:00 +01:00
import { FormattedMessage, useIntl } from 'react-intl'
import { Virtuoso } from 'react-virtuoso'
import Notification from './notification/Notification'
import { Spinner } from '@material-tailwind/react'
import { useRouter } from 'next/router'
import Detail from '../detail/Detail'
2024-01-31 15:03:07 +01:00
import { Marker } from '@/entities/marker'
import { FaCheck } from 'react-icons/fa6'
import { useToast } from '@/provider/toast'
import { useUnreads } from '@/provider/unreads'
2023-11-04 10:14:00 +01:00
2023-11-05 17:09:32 +01:00
const TIMELINE_STATUSES_COUNT = 30
const TIMELINE_MAX_STATUSES = 2147483647
2023-11-04 10:14:00 +01:00
type Props = {
account: Account
client: MegalodonInterface
2023-12-02 11:26:45 +01:00
setAttachment: Dispatch<SetStateAction<Entity.Attachment | null>>
2023-11-04 10:14:00 +01:00
}
export default function Notifications(props: Props) {
const [notifications, setNotifications] = useState<Array<Entity.Notification>>([])
2024-01-28 14:17:47 +01:00
const [unreadNotifications, setUnreadNotifications] = useState<Array<Entity.Notification>>([])
2023-11-05 17:09:32 +01:00
const [firstItemIndex, setFirstItemIndex] = useState(TIMELINE_MAX_STATUSES)
const [marker, setMarker] = useState<Marker | null>(null)
const [pleromaUnreads, setPleromaUnreads] = useState<Array<string>>([])
2024-02-27 12:49:27 +01:00
const [filters, setFilters] = useState<Array<Entity.Filter>>([])
2023-11-05 17:09:32 +01:00
const scrollerRef = useRef<HTMLElement | null>(null)
const streaming = useRef<WebSocketInterface | null>(null)
const router = useRouter()
const showToast = useToast()
2024-01-28 14:17:47 +01:00
const { setUnreads } = useUnreads()
const { formatMessage } = useIntl()
2023-11-04 10:14:00 +01:00
useEffect(() => {
const f = async () => {
2024-02-27 12:49:27 +01:00
const f = await loadFilter(props.client)
setFilters(f)
2023-11-04 10:14:00 +01:00
const res = await loadNotifications(props.client)
setNotifications(res)
2023-11-05 17:09:32 +01:00
const instance = await props.client.getInstance()
const c = generator(props.account.sns, instance.data.urls.streaming_api, props.account.access_token, 'Whalebird')
updateMarker(props.client)
2023-11-05 17:09:32 +01:00
streaming.current = c.userSocket()
streaming.current.on('connect', () => {
console.log('connected to notifications')
})
streaming.current.on('notification', (notification: Entity.Notification) => {
if (scrollerRef.current && scrollerRef.current.scrollTop > 10) {
2024-01-28 14:17:47 +01:00
setUnreadNotifications(current => [notification, ...current])
2023-11-05 17:09:32 +01:00
} else {
setNotifications(current => [notification, ...current])
}
updateMarker(props.client)
2023-11-05 17:09:32 +01:00
})
2023-11-04 10:14:00 +01:00
}
f()
2023-11-05 17:09:32 +01:00
return () => {
2024-01-28 14:17:47 +01:00
setUnreadNotifications([])
setFirstItemIndex(TIMELINE_MAX_STATUSES)
setNotifications([])
2023-11-05 17:09:32 +01:00
if (streaming.current) {
streaming.current.removeAllListeners()
streaming.current.stop()
2023-11-09 15:29:10 +01:00
streaming.current = null
2023-11-05 17:09:32 +01:00
console.log('closed notifications')
}
}
2023-11-04 10:14:00 +01:00
}, [props.client])
useEffect(() => {
// In pleroma, last_read_id is incorrect.
// Items that have not been marked may also be read. So, if marker has unread_count, we should use it for unreads.
if (marker && marker.unread_count) {
2024-01-28 14:17:47 +01:00
const allNotifications = unreadNotifications.concat(notifications)
const u = allNotifications.slice(0, marker.unread_count).map(n => n.id)
setPleromaUnreads(u)
}
2024-01-28 14:17:47 +01:00
}, [marker, unreadNotifications, notifications])
2024-02-27 12:49:27 +01:00
const loadFilter = async (client: MegalodonInterface): Promise<Array<Entity.Filter>> => {
const res = await client.getFilters()
return res.data.filter(f => f.context.includes('notifications'))
}
2023-11-04 10:14:00 +01:00
const loadNotifications = async (client: MegalodonInterface, maxId?: string): Promise<Array<Entity.Notification>> => {
let options = { limit: 30 }
if (maxId) {
options = Object.assign({}, options, { max_id: maxId })
}
const res = await client.getNotifications(options)
return res.data
}
const updateMarker = async (client: MegalodonInterface) => {
try {
const res = await client.getMarkers(['notifications'])
const marker = res.data as Entity.Marker
if (marker.notifications) {
setMarker(marker.notifications)
}
} catch (err) {
console.error(err)
}
}
2023-11-04 10:14:00 +01:00
const updateStatus = (status: Entity.Status) => {
const renew = notifications.map(n => {
if (n.status === undefined || n.status === null) {
return n
}
if (n.status.id === status.id) {
return Object.assign({}, n, { status })
} else if (n.status.reblog && n.status.reblog.id === status.id) {
const s = Object.assign({}, n.status, { reblog: status })
return Object.assign({}, n, { status: s })
}
return n
})
setNotifications(renew)
}
const read = async () => {
try {
await props.client.saveMarkers({ notifications: { last_read_id: notifications[0].id } })
if (props.account.sns === 'pleroma') {
await props.client.readNotifications({ max_id: notifications[0].id })
}
const res = await props.client.getMarkers(['notifications'])
const marker = res.data as Entity.Marker
if (marker.notifications) {
setMarker(marker.notifications)
2024-01-28 14:17:47 +01:00
setUnreads(current =>
Object.assign({}, current, {
[props.account.id?.toString()]: 0
})
)
}
} catch {
showToast({ text: formatMessage({ id: 'alert.failed_mark' }), type: 'failure' })
}
}
2023-11-04 15:03:47 +01:00
const loadMore = useCallback(async () => {
console.debug('appending')
try {
const append = await loadNotifications(props.client, notifications[notifications.length - 1].id)
setNotifications(last => [...last, ...append])
} catch (err) {
console.error(err)
}
}, [props.client, notifications, setNotifications])
2023-11-05 17:09:32 +01:00
const prependUnreads = useCallback(() => {
console.debug('prepending')
2024-01-28 14:17:47 +01:00
const u = unreadNotifications.slice().reverse().slice(0, TIMELINE_STATUSES_COUNT).reverse()
2023-11-05 17:09:32 +01:00
const remains = u.slice(0, -1 * TIMELINE_STATUSES_COUNT)
2024-01-28 14:17:47 +01:00
setUnreadNotifications(() => remains)
2023-11-05 17:09:32 +01:00
setFirstItemIndex(() => firstItemIndex - u.length)
setNotifications(() => [...u, ...notifications])
return false
2024-01-28 14:17:47 +01:00
}, [firstItemIndex, notifications, setNotifications, unreadNotifications])
2023-11-05 17:09:32 +01:00
const timelineClass = () => {
if (router.query.detail) {
return 'timeline-with-drawer'
}
return 'timeline'
}
const backToTop = () => {
scrollerRef.current.scrollTo({
top: 0,
behavior: 'smooth'
})
}
2023-11-04 10:14:00 +01:00
return (
<div className="flex timeline-wrapper">
<section className={`h-full ${timelineClass()}`}>
<div className="w-full bg-blue-950 text-blue-100 p-2 flex justify-between">
<div className="text-lg font-bold cursor-pointer" onClick={() => backToTop()}>
<FormattedMessage id="timeline.notifications" />
</div>
<div className="w-64 text-xs text-right">
<button className="text-gray-400 text-base py-1" title={formatMessage({ id: 'timeline.mark_as_read' })} onClick={read}>
<FaCheck />
</button>
</div>
2023-11-04 10:14:00 +01:00
</div>
<div className="timeline overflow-y-auto w-full overflow-x-hidden" style={{ height: 'calc(100% - 44px)' }}>
{notifications.length > 0 ? (
<Virtuoso
style={{ height: '100%' }}
scrollerRef={ref => {
scrollerRef.current = ref as HTMLElement
}}
firstItemIndex={firstItemIndex}
atTopStateChange={prependUnreads}
className="timeline-scrollable"
data={notifications}
endReached={loadMore}
itemContent={(_, notification) => {
let shadow = {}
if (marker) {
if (marker.unread_count && pleromaUnreads.includes(notification.id)) {
shadow = { boxShadow: '4px 0 2px var(--tw-shadow-color) inset' }
} else if (parseInt(marker.last_read_id) < parseInt(notification.id)) {
shadow = { boxShadow: '4px 0 2px var(--tw-shadow-color) inset' }
}
}
return (
<div className="box-border shadow-teal-500/80" style={shadow}>
<Notification
client={props.client}
account={props.account}
notification={notification}
onRefresh={updateStatus}
key={notification.id}
openMedia={media => props.setAttachment(media)}
2024-02-27 12:49:27 +01:00
filters={filters}
/>
</div>
)
}}
/>
) : (
<div className="w-full pt-6" style={{ height: '100%' }}>
<Spinner className="m-auto" />
</div>
)}
2023-11-04 10:14:00 +01:00
</div>
</section>
<Detail client={props.client} account={props.account} className="detail" openMedia={media => props.setAttachment(media)} />
</div>
2023-11-04 10:14:00 +01:00
)
}