phanpy/src/pages/home.jsx

488 lines
14 KiB
React
Raw Normal View History

2022-12-10 12:14:48 +03:00
import { Link } from 'preact-router/match';
2023-01-07 09:45:04 +03:00
import { memo } from 'preact/compat';
2022-12-10 12:14:48 +03:00
import { useEffect, useRef, useState } from 'preact/hooks';
import { useHotkeys } from 'react-hotkeys-hook';
2022-12-10 12:14:48 +03:00
import { useSnapshot } from 'valtio';
import Icon from '../components/icon';
import Loader from '../components/loader';
import Status from '../components/status';
import db from '../utils/db';
2023-01-09 14:11:34 +03:00
import states, { saveStatus } from '../utils/states';
import { getCurrentAccountNS } from '../utils/store-utils';
import useDebouncedCallback from '../utils/useDebouncedCallback';
import useScroll from '../utils/useScroll';
2022-12-10 12:14:48 +03:00
const LIMIT = 20;
2022-12-16 08:27:04 +03:00
function Home({ hidden }) {
2022-12-10 12:14:48 +03:00
const snapStates = useSnapshot(states);
const [uiState, setUIState] = useState('default');
const [showMore, setShowMore] = useState(false);
console.debug('RENDER Home');
2022-12-18 06:52:53 +03:00
const homeIterator = useRef(
masto.v1.timelines.listHome({
2022-12-10 12:14:48 +03:00
limit: LIMIT,
}),
);
2022-12-10 12:14:48 +03:00
async function fetchStatuses(firstLoad) {
if (firstLoad) {
// Reset iterator
homeIterator.current = masto.v1.timelines.listHome({
limit: LIMIT,
});
2023-01-02 19:27:47 +03:00
states.homeNew = [];
}
const allStatuses = await homeIterator.current.next();
2022-12-10 12:14:48 +03:00
if (allStatuses.value <= 0) {
return { done: true };
}
const homeValues = allStatuses.value.map((status) => {
2023-01-09 14:11:34 +03:00
saveStatus(status);
2022-12-10 12:14:48 +03:00
return {
id: status.id,
reblog: status.reblog?.id,
reply: !!status.inReplyToAccountId,
};
});
2023-01-14 14:42:04 +03:00
{
// BOOSTS CAROUSEL
let specialHome = [];
let boostStash = [];
for (let i = 0; i < homeValues.length; i++) {
const status = homeValues[i];
if (status.reblog) {
boostStash.push(status);
} else {
specialHome.push(status);
}
}
// if boostStash is more than quarter of homeValues
if (boostStash.length > homeValues.length / 4) {
// if boostStash is more than 3 quarter of homeValues
const boostStashID = boostStash.map((status) => status.id);
if (boostStash.length > (homeValues.length * 3) / 4) {
// insert boost array at the end of specialHome list
specialHome = [
...specialHome,
{ id: boostStashID, boosts: boostStash },
];
} else {
// insert boosts array in the middle of specialHome list
const half = Math.floor(specialHome.length / 2);
specialHome = [
...specialHome.slice(0, half),
{
id: boostStashID,
boosts: boostStash,
},
...specialHome.slice(half),
];
}
} else {
// Untouched, this is fine
specialHome = homeValues;
}
console.log({
specialHome,
});
if (firstLoad) {
states.specialHome = specialHome;
} else {
states.specialHome.push(...specialHome);
}
}
2022-12-10 12:14:48 +03:00
if (firstLoad) {
states.home = homeValues;
} else {
states.home.push(...homeValues);
}
states.homeLastFetchTime = Date.now();
return allStatuses;
}
const loadingStatuses = useRef(false);
const loadStatuses = useDebouncedCallback((firstLoad) => {
if (loadingStatuses.current) return;
loadingStatuses.current = true;
2022-12-10 12:14:48 +03:00
setUIState('loading');
(async () => {
try {
const { done } = await fetchStatuses(firstLoad);
setShowMore(!done);
setUIState('default');
} catch (e) {
console.warn(e);
setUIState('error');
} finally {
loadingStatuses.current = false;
2022-12-10 12:14:48 +03:00
}
})();
}, 1000);
2022-12-10 12:14:48 +03:00
useEffect(() => {
loadStatuses(true);
}, []);
const scrollableRef = useRef();
useHotkeys('j', () => {
// focus on next status after active status
// Traverses .timeline li .status-link, focus on .status-link
2023-01-14 14:42:04 +03:00
const activeStatus = document.activeElement.closest(
'.status-link, .status-boost-link',
);
const activeStatusRect = activeStatus?.getBoundingClientRect();
2023-01-14 14:42:04 +03:00
const allStatusLinks = Array.from(
scrollableRef.current.querySelectorAll(
'.status-link, .status-boost-link',
),
);
if (
activeStatus &&
activeStatusRect.top < scrollableRef.current.clientHeight &&
activeStatusRect.bottom > 0
) {
2023-01-14 14:42:04 +03:00
const activeStatusIndex = allStatusLinks.indexOf(activeStatus);
const nextStatus = allStatusLinks[activeStatusIndex + 1];
if (nextStatus) {
2023-01-14 14:42:04 +03:00
nextStatus.focus();
nextStatus.scrollIntoViewIfNeeded?.();
}
} else {
// If active status is not in viewport, get the topmost status-link in viewport
2023-01-14 14:42:04 +03:00
const topmostStatusLink = allStatusLinks.find((statusLink) => {
const statusLinkRect = statusLink.getBoundingClientRect();
2023-01-14 14:42:04 +03:00
return statusLinkRect.top >= 44 && statusLinkRect.left >= 0; // 44 is the magic number for header height, not real
});
if (topmostStatusLink) {
topmostStatusLink.focus();
2023-01-14 14:42:04 +03:00
topmostStatusLink.scrollIntoViewIfNeeded?.();
}
}
});
useHotkeys('k', () => {
// focus on previous status after active status
// Traverses .timeline li .status-link, focus on .status-link
2023-01-14 14:42:04 +03:00
const activeStatus = document.activeElement.closest(
'.status-link, .status-boost-link',
);
const activeStatusRect = activeStatus?.getBoundingClientRect();
2023-01-14 14:42:04 +03:00
const allStatusLinks = Array.from(
scrollableRef.current.querySelectorAll(
'.status-link, .status-boost-link',
),
);
if (
activeStatus &&
activeStatusRect.top < scrollableRef.current.clientHeight &&
activeStatusRect.bottom > 0
) {
2023-01-14 14:42:04 +03:00
const activeStatusIndex = allStatusLinks.indexOf(activeStatus);
const prevStatus = allStatusLinks[activeStatusIndex - 1];
if (prevStatus) {
2023-01-14 14:42:04 +03:00
prevStatus.focus();
prevStatus.scrollIntoViewIfNeeded?.();
}
} else {
// If active status is not in viewport, get the topmost status-link in viewport
2023-01-14 14:42:04 +03:00
const topmostStatusLink = allStatusLinks.find((statusLink) => {
const statusLinkRect = statusLink.getBoundingClientRect();
2023-01-14 14:42:04 +03:00
return statusLinkRect.top >= 44 && statusLinkRect.left >= 0; // 44 is the magic number for header height, not real
});
if (topmostStatusLink) {
topmostStatusLink.focus();
2023-01-14 14:42:04 +03:00
topmostStatusLink.scrollIntoViewIfNeeded?.();
}
}
});
useHotkeys(['enter', 'o'], () => {
// open active status
2023-01-14 14:42:04 +03:00
const activeStatus = document.activeElement.closest(
'.status-link, .status-boost-link',
);
if (activeStatus) {
activeStatus.click();
}
});
2023-01-14 14:42:04 +03:00
const { scrollDirection, reachStart, nearReachStart, nearReachEnd } =
useScroll({
scrollableElement: scrollableRef.current,
2023-01-14 14:42:04 +03:00
distanceFromStart: 0.1,
distanceFromEnd: 0.15,
scrollThresholdStart: 44,
});
useEffect(() => {
2023-01-14 14:42:04 +03:00
if (nearReachEnd && showMore) {
loadStatuses();
}
2023-01-14 14:42:04 +03:00
}, [nearReachEnd]);
useEffect(() => {
2023-01-14 14:42:04 +03:00
if (reachStart) {
loadStatuses(true);
}
2023-01-14 14:42:04 +03:00
}, [reachStart]);
useEffect(() => {
(async () => {
const keys = await db.drafts.keys();
if (keys.length) {
const ns = getCurrentAccountNS();
const ownKeys = keys.filter((key) => key.startsWith(ns));
if (ownKeys.length) {
states.showDrafts = true;
}
}
})();
}, []);
2023-01-14 14:42:04 +03:00
const snapHome = snapStates.settings.boostsCarousel
? snapStates.specialHome
: snapStates.home;
2022-12-10 12:14:48 +03:00
return (
2022-12-29 11:11:58 +03:00
<div
2022-12-30 15:37:57 +03:00
id="home-page"
2022-12-29 11:11:58 +03:00
class="deck-container"
hidden={hidden}
ref={scrollableRef}
tabIndex="-1"
>
<button
2023-01-14 14:42:04 +03:00
hidden={scrollDirection === 'down' && !nearReachStart}
type="button"
id="compose-button"
onClick={(e) => {
if (e.shiftKey) {
const newWin = openCompose();
if (!newWin) {
alert('Looks like your browser is blocking popups.');
states.showCompose = true;
}
} else {
states.showCompose = true;
}
}}
>
<Icon icon="quill" size="xxl" alt="Compose" />
</button>
2022-12-10 12:14:48 +03:00
<div class="timeline-deck deck">
<header
2023-01-14 14:42:04 +03:00
hidden={scrollDirection === 'down' && !nearReachStart}
2022-12-10 12:14:48 +03:00
onClick={() => {
scrollableRef.current?.scrollTo({ top: 0, behavior: 'smooth' });
}}
onDblClick={() => {
loadStatuses(true);
}}
2022-12-10 12:14:48 +03:00
>
<div class="header-side">
<button
type="button"
class="plain"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
states.showSettings = true;
}}
>
<Icon icon="gear" size="l" alt="Settings" />
</button>
</div>
<h1>Home</h1>
<div class="header-side">
<Loader hidden={uiState !== 'loading'} />{' '}
<a
href="#/notifications"
class={`button plain ${
snapStates.notificationsNew.length > 0 ? 'has-badge' : ''
}`}
onClick={(e) => {
e.stopPropagation();
}}
2022-12-10 12:14:48 +03:00
>
<Icon icon="notification" size="l" alt="Notifications" />
</a>
</div>
</header>
2023-01-02 19:52:16 +03:00
{snapStates.homeNew.length > 0 &&
scrollDirection === 'up' &&
2023-01-14 14:42:04 +03:00
!nearReachStart &&
!nearReachEnd && (
2023-01-02 19:52:16 +03:00
<button
class="updates-button"
type="button"
onClick={() => {
const uniqueHomeNew = snapStates.homeNew.filter(
(status) => !states.home.some((s) => s.id === status.id),
);
states.home.unshift(...uniqueHomeNew);
loadStatuses(true);
states.homeNew = [];
2023-01-02 19:52:16 +03:00
scrollableRef.current?.scrollTo({
top: 0,
behavior: 'smooth',
});
}}
>
<Icon icon="arrow-up" /> New posts
</button>
)}
2023-01-14 14:42:04 +03:00
{snapHome.length ? (
2022-12-10 12:14:48 +03:00
<>
<ul class="timeline">
2023-01-14 14:42:04 +03:00
{snapHome.map(({ id: statusID, reblog, boosts }) => {
2022-12-10 12:14:48 +03:00
const actualStatusID = reblog || statusID;
2023-01-14 14:42:04 +03:00
if (boosts) {
return (
<li key={statusID}>
<BoostsCarousel boosts={boosts} />
</li>
);
}
2022-12-10 12:14:48 +03:00
return (
<li key={statusID}>
<Link
activeClassName="active"
class="status-link"
href={`#/s/${actualStatusID}`}
>
<Status statusID={statusID} />
</Link>
</li>
);
})}
{showMore && (
<>
{/* <InView
as="li"
2022-12-10 12:14:48 +03:00
style={{
height: '20vh',
}}
onChange={(inView) => {
if (inView) loadStatuses();
2022-12-10 12:14:48 +03:00
}}
root={scrollableRef.current}
rootMargin="100px 0px"
> */}
2023-01-02 19:56:11 +03:00
<li
style={{
height: '20vh',
}}
>
<Status skeleton />
</li>
{/* </InView> */}
2022-12-10 12:14:48 +03:00
<li
style={{
height: '25vh',
}}
>
<Status skeleton />
</li>
</>
2022-12-10 12:14:48 +03:00
)}
</ul>
</>
) : (
<>
{uiState === 'loading' && (
<ul class="timeline">
{Array.from({ length: 5 }).map((_, i) => (
<li key={i}>
<Status skeleton />
</li>
))}
</ul>
)}
{uiState === 'error' && (
<p class="ui-state">
Unable to load statuses
<br />
<br />
<button
type="button"
onClick={() => {
loadStatuses(true);
}}
>
Try again
</button>
</p>
2022-12-10 12:14:48 +03:00
)}
</>
)}
</div>
</div>
);
2022-12-16 08:27:04 +03:00
}
2023-01-14 14:42:04 +03:00
function BoostsCarousel({ boosts }) {
const carouselRef = useRef();
const { reachStart, reachEnd } = useScroll({
scrollableElement: carouselRef.current,
direction: 'horizontal',
});
console.log({ reachStart, reachEnd });
return (
<div class="boost-carousel">
<header>
<h3>{boosts.length} Boosts</h3>
<span>
<button
type="button"
class="small plain2"
disabled={reachStart}
onClick={() => {
carouselRef.current?.scrollBy({
left: -Math.min(320, carouselRef.current?.offsetWidth),
behavior: 'smooth',
});
}}
>
<Icon icon="chevron-left" />
</button>{' '}
<button
type="button"
class="small plain2"
disabled={reachEnd}
onClick={() => {
carouselRef.current?.scrollBy({
left: Math.min(320, carouselRef.current?.offsetWidth),
behavior: 'smooth',
});
}}
>
<Icon icon="chevron-right" />
</button>
</span>
</header>
<ul ref={carouselRef}>
{boosts.map((boost) => {
const { id: statusID, reblog } = boost;
const actualStatusID = reblog || statusID;
return (
<li>
<a class="status-boost-link" href={`#/s/${actualStatusID}`}>
<Status statusID={statusID} size="s" />
</a>
</li>
);
})}
</ul>
</div>
);
}
2023-01-07 09:45:04 +03:00
export default memo(Home);