import { Link } from 'preact-router/match'; import { useEffect, useRef, useState } from 'preact/hooks'; import { InView } from 'react-intersection-observer'; import { useSnapshot } from 'valtio'; import Icon from '../components/icon'; import Loader from '../components/loader'; import Status from '../components/status'; import states from '../utils/states'; import store from '../utils/store'; const LIMIT = 20; export default ({ hidden }) => { const snapStates = useSnapshot(states); const [uiState, setUIState] = useState('default'); const [showMore, setShowMore] = useState(false); const statusIterator = useRef( masto.timelines.getHomeIterable({ limit: LIMIT, }), ).current; async function fetchStatuses(firstLoad) { const allStatuses = await statusIterator.next( firstLoad ? { limit: LIMIT, } : undefined, ); if (allStatuses.value <= 0) { return { done: true }; } const homeValues = allStatuses.value.map((status) => { states.statuses.set(status.id, status); if (status.reblog) { states.statuses.set(status.reblog.id, status.reblog); } return { id: status.id, reblog: status.reblog?.id, reply: !!status.inReplyToAccountId, }; }); if (firstLoad) { states.home = homeValues; } else { states.home.push(...homeValues); } states.homeLastFetchTime = Date.now(); console.log(allStatuses); return allStatuses; } const loadStatuses = (firstLoad) => { setUIState('loading'); (async () => { try { const { done } = await fetchStatuses(firstLoad); setShowMore(!done); setUIState('default'); } catch (e) { console.warn(e); setUIState('error'); } })(); }; useEffect(() => { loadStatuses(true); }, []); useEffect(() => { const handleVisibilityChange = () => { if (document.hidden) { const timestamp = Date.now(); store.session.set('lastHidden', timestamp); } else { const timestamp = Date.now(); const lastHidden = store.session.get('lastHidden'); const diff = timestamp - lastHidden; const diffMins = Math.round(diff / 1000 / 60); if (diffMins > 1) { console.log('visible', { lastHidden, diffMins }); setTimeout(() => { loadStatuses(true); states.homeNew = []; }, 100); } } }; document.addEventListener('visibilitychange', handleVisibilityChange); return () => { document.removeEventListener('visibilitychange', handleVisibilityChange); }; }, []); const scrollableRef = useRef(); return ( ); };