phanpy/src/pages/account-statuses.jsx

622 lines
18 KiB
React
Raw Normal View History

2023-10-03 10:07:47 +03:00
import { MenuItem } from '@szhsin/react-menu';
2023-11-01 13:02:54 +03:00
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'preact/hooks';
2023-04-03 05:36:31 +03:00
import { useParams, useSearchParams } from 'react-router-dom';
2023-02-03 16:08:08 +03:00
import { useSnapshot } from 'valtio';
import AccountInfo from '../components/account-info';
import EmojiText from '../components/emoji-text';
2023-04-03 05:36:31 +03:00
import Icon from '../components/icon';
import Link from '../components/link';
2023-06-13 12:46:37 +03:00
import Menu2 from '../components/menu2';
import Timeline from '../components/timeline';
import { api } from '../utils/api';
2023-10-20 15:48:30 +03:00
import pmem from '../utils/pmem';
2023-04-08 20:01:36 +03:00
import showToast from '../utils/show-toast';
2023-01-31 14:08:10 +03:00
import states from '../utils/states';
import { saveStatus } from '../utils/states';
2023-02-03 16:08:08 +03:00
import useTitle from '../utils/useTitle';
const LIMIT = 20;
2023-10-20 14:24:01 +03:00
const MIN_YEAR = 1983;
const MIN_YEAR_MONTH = `${MIN_YEAR}-01`; // Birth of the Internet
const supportsInputMonth = (() => {
try {
const input = document.createElement('input');
input.setAttribute('type', 'month');
return input.type === 'month';
} catch (e) {
return false;
}
})();
2023-10-20 15:54:24 +03:00
async function _isSearchEnabled(instance) {
2023-10-20 15:48:30 +03:00
const { masto } = api({ instance });
2023-10-20 15:54:24 +03:00
const results = await masto.v2.search.fetch({
2023-10-20 15:48:30 +03:00
q: 'from:me',
type: 'statuses',
limit: 1,
});
return !!results?.statuses?.length;
}
const isSearchEnabled = pmem(_isSearchEnabled);
function AccountStatuses() {
2023-02-03 16:08:08 +03:00
const snapStates = useSnapshot(states);
const { id, ...params } = useParams();
2023-04-03 05:36:31 +03:00
const [searchParams, setSearchParams] = useSearchParams();
const month = searchParams.get('month');
2023-04-03 05:36:31 +03:00
const excludeReplies = !searchParams.get('replies');
2023-04-04 06:01:53 +03:00
const excludeBoosts = !!searchParams.get('boosts');
2023-04-03 05:36:31 +03:00
const tagged = searchParams.get('tagged');
const media = !!searchParams.get('media');
const { masto, instance, authenticated } = api({ instance: params.instance });
const accountStatusesIterator = useRef();
const allSearchParams = [month, excludeReplies, excludeBoosts, tagged, media];
const [account, setAccount] = useState();
const searchOffsetRef = useRef(0);
useEffect(() => {
searchOffsetRef.current = 0;
}, allSearchParams);
const sameCurrentInstance = useMemo(
() => instance === api().instance,
[instance],
);
const [searchEnabled, setSearchEnabled] = useState(false);
useEffect(() => {
// Only enable for current logged-in instance
// Most remote instances don't allow unauthenticated searches
if (!sameCurrentInstance) return;
if (!account?.acct) return;
(async () => {
2023-10-20 15:48:30 +03:00
const enabled = await isSearchEnabled(instance);
2023-10-20 15:54:24 +03:00
console.log({ enabled });
2023-10-20 15:48:30 +03:00
setSearchEnabled(enabled);
})();
2023-10-20 15:48:30 +03:00
}, [instance, sameCurrentInstance, account?.acct]);
async function fetchAccountStatuses(firstLoad) {
2023-10-20 14:24:01 +03:00
const isValidMonth = /^\d{4}-[01]\d$/.test(month);
const isValidYear = month?.split?.('-')?.[0] >= MIN_YEAR;
if (isValidMonth && isValidYear) {
if (!account) {
return {
value: [],
done: true,
};
}
const [_year, _month] = month.split('-');
const monthIndex = parseInt(_month, 10) - 1;
// YYYY-MM (no day)
// Search options:
// - from:account
// - after:YYYY-MM-DD (non-inclusive)
// - before:YYYY-MM-DD (non-inclusive)
// Last day of previous month
const after = new Date(_year, monthIndex, 0);
const afterStr = `${after.getFullYear()}-${(after.getMonth() + 1)
.toString()
.padStart(2, '0')}-${after.getDate().toString().padStart(2, '0')}`;
// First day of next month
const before = new Date(_year, monthIndex + 1, 1);
const beforeStr = `${before.getFullYear()}-${(before.getMonth() + 1)
.toString()
.padStart(2, '0')}-${before.getDate().toString().padStart(2, '0')}`;
console.log({
month,
_year,
_month,
monthIndex,
after,
before,
afterStr,
beforeStr,
});
let limit;
if (firstLoad) {
limit = LIMIT + 1;
searchOffsetRef.current = 0;
} else {
limit = LIMIT + searchOffsetRef.current + 1;
searchOffsetRef.current += LIMIT;
}
const searchResults = await masto.v2.search.fetch({
q: `from:${account.acct} after:${afterStr} before:${beforeStr}`,
type: 'statuses',
limit,
offset: searchOffsetRef.current,
});
if (searchResults?.statuses?.length) {
const value = searchResults.statuses.slice(0, LIMIT);
value.forEach((item) => {
saveStatus(item, instance);
});
const done = searchResults.statuses.length <= LIMIT;
return { value, done };
} else {
return { value: [], done: true };
}
}
2023-02-17 05:12:59 +03:00
const results = [];
if (firstLoad) {
const { value: pinnedStatuses } = await masto.v1.accounts
.$select(id)
.statuses.list({
2023-02-17 05:12:59 +03:00
pinned: true,
})
.next();
2023-04-03 05:36:31 +03:00
if (pinnedStatuses?.length && !tagged && !media) {
2023-02-17 05:12:59 +03:00
pinnedStatuses.forEach((status) => {
status._pinned = true;
2023-03-18 17:25:02 +03:00
saveStatus(status, instance);
2023-02-17 05:12:59 +03:00
});
if (pinnedStatuses.length >= 3) {
const pinnedStatusesIds = pinnedStatuses.map((status) => status.id);
results.push({
id: pinnedStatusesIds,
items: pinnedStatuses,
type: 'pinned',
});
} else {
results.push(...pinnedStatuses);
}
2023-02-17 05:12:59 +03:00
}
}
if (firstLoad || !accountStatusesIterator.current) {
accountStatusesIterator.current = masto.v1.accounts
.$select(id)
.statuses.list({
limit: LIMIT,
exclude_replies: excludeReplies,
exclude_reblogs: excludeBoosts,
only_media: media,
tagged,
});
}
2023-02-17 05:12:59 +03:00
const { value, done } = await accountStatusesIterator.current.next();
if (value?.length) {
results.push(...value);
value.forEach((item) => {
saveStatus(item, instance);
});
2023-02-17 05:12:59 +03:00
}
return {
value: results,
done,
};
}
2023-04-03 05:36:31 +03:00
const [featuredTags, setFeaturedTags] = useState([]);
useTitle(
2023-10-30 13:04:17 +03:00
account?.acct
? `${account?.displayName ? account.displayName + ' ' : ''}@${
account.acct
}${
!excludeReplies
? ' (+ Replies)'
: excludeBoosts
? ' (- Boosts)'
: tagged
? ` (#${tagged})`
: media
? ' (Media)'
: month
? ` (${new Date(month).toLocaleString('default', {
month: 'long',
year: 'numeric',
})})`
: ''
}`
: 'Account posts',
2023-02-11 11:27:40 +03:00
'/:instance?/a/:id',
);
2023-11-01 13:02:54 +03:00
const fetchAccountPromiseRef = useRef();
const fetchAccount = useCallback(() => {
const fetchPromise =
fetchAccountPromiseRef.current || masto.v1.accounts.$select(id).fetch();
fetchAccountPromiseRef.current = fetchPromise;
return fetchPromise;
}, [id, masto]);
useEffect(() => {
(async () => {
try {
2023-11-01 13:02:54 +03:00
const acc = await fetchAccount();
console.log(acc);
setAccount(acc);
} catch (e) {
console.error(e);
}
2023-04-03 05:36:31 +03:00
try {
const featuredTags = await masto.v1.accounts
.$select(id)
2023-10-20 12:11:10 +03:00
.featuredTags.list();
2023-04-03 05:36:31 +03:00
console.log({ featuredTags });
setFeaturedTags(featuredTags);
} catch (e) {
console.error(e);
}
})();
}, [id]);
const { displayName, acct, emojis } = account || {};
2023-11-01 13:02:54 +03:00
const accountInfoMemo = useMemo(() => {
const cachedAccount = snapStates.accounts[`${id}@${instance}`];
return (
<AccountInfo
instance={instance}
account={cachedAccount || id}
fetchAccount={fetchAccount}
authenticated={authenticated}
standalone
/>
);
}, [id, instance, authenticated, fetchAccount]);
const filterBarRef = useRef();
const TimelineStart = useMemo(() => {
const filtered =
!excludeReplies || excludeBoosts || tagged || media || !!month;
2023-11-01 13:02:54 +03:00
return (
2023-04-03 05:36:31 +03:00
<>
2023-11-01 13:02:54 +03:00
{accountInfoMemo}
<div
class="filter-bar"
ref={filterBarRef}
style={{
position: 'relative',
}}
>
{filtered ? (
<Link
to={`/${instance}/a/${id}`}
class="insignificant filter-clear"
title="Clear filters"
key="clear-filters"
>
<Icon icon="x" size="l" />
</Link>
) : (
<Icon icon="filter" class="insignificant" size="l" />
)}
2023-04-03 05:36:31 +03:00
<Link
to={`/${instance}/a/${id}${excludeReplies ? '?replies=1' : ''}`}
2023-04-08 20:01:36 +03:00
onClick={() => {
if (excludeReplies) {
showToast('Showing post with replies');
}
}}
2023-04-03 05:36:31 +03:00
class={excludeReplies ? '' : 'is-active'}
>
+ Replies
</Link>
2023-04-04 06:01:53 +03:00
<Link
to={`/${instance}/a/${id}${excludeBoosts ? '' : '?boosts=0'}`}
2023-04-08 20:01:36 +03:00
onClick={() => {
if (!excludeBoosts) {
showToast('Showing posts without boosts');
}
}}
2023-04-04 06:01:53 +03:00
class={!excludeBoosts ? '' : 'is-active'}
>
- Boosts
</Link>
2023-04-03 05:36:31 +03:00
<Link
to={`/${instance}/a/${id}${media ? '' : '?media=1'}`}
2023-04-08 20:01:36 +03:00
onClick={() => {
if (!media) {
showToast('Showing posts with media');
}
}}
2023-04-03 05:36:31 +03:00
class={media ? 'is-active' : ''}
>
Media
</Link>
{featuredTags.map((tag) => (
<Link
key={tag.id}
2023-04-03 05:36:31 +03:00
to={`/${instance}/a/${id}${
tagged === tag.name
? ''
: `?tagged=${encodeURIComponent(tag.name)}`
}`}
2023-04-08 20:01:36 +03:00
onClick={() => {
if (tagged !== tag.name) {
showToast(`Showing posts tagged with #${tag.name}`);
}
}}
2023-04-03 05:36:31 +03:00
class={tagged === tag.name ? 'is-active' : ''}
>
<span>
<span class="more-insignificant">#</span>
{tag.name}
</span>
{
// The count differs based on instance 😅
}
{/* <span class="filter-count">{tag.statusesCount}</span> */}
</Link>
))}
{searchEnabled &&
(supportsInputMonth ? (
2023-10-20 14:24:01 +03:00
<label class={`filter-field ${month ? 'is-active' : ''}`}>
<Icon icon="month" size="l" />
<input
type="month"
disabled={!account?.acct}
value={month || ''}
min={MIN_YEAR_MONTH}
max={new Date().toISOString().slice(0, 7)}
onInput={(e) => {
const { value, validity } = e.currentTarget;
if (!validity.valid) return;
2023-10-20 14:24:01 +03:00
setSearchParams(
value
? {
month: value,
}
: {},
);
showToast(
`Showing posts in ${new Date(value).toLocaleString(
'default',
{
month: 'long',
year: 'numeric',
},
)}`,
);
2023-10-20 14:24:01 +03:00
}}
/>
</label>
) : (
// Fallback to <select> for month and <input type="number"> for year
<MonthPicker
class={`filter-field ${month ? 'is-active' : ''}`}
disabled={!account?.acct}
value={month || ''}
2023-10-20 14:24:01 +03:00
min={MIN_YEAR_MONTH}
max={new Date().toISOString().slice(0, 7)}
onInput={(e) => {
const { value, validity } = e;
if (!validity.valid) return;
setSearchParams(
value
? {
month: value,
}
: {},
);
}}
/>
))}
2023-04-03 05:36:31 +03:00
</div>
</>
);
2023-04-03 05:36:31 +03:00
}, [
id,
instance,
authenticated,
featuredTags,
searchEnabled,
...allSearchParams,
2023-04-03 05:36:31 +03:00
]);
useEffect(() => {
// Focus on .is-active
const active = filterBarRef.current?.querySelector('.is-active');
if (active) {
console.log('active', active, active.offsetLeft);
filterBarRef.current.scrollTo({
behavior: 'smooth',
left:
active.offsetLeft -
(filterBarRef.current.offsetWidth - active.offsetWidth) / 2,
});
}
2023-10-20 17:00:56 +03:00
}, [featuredTags, searchEnabled, ...allSearchParams]);
const accountInstance = useMemo(() => {
if (!account?.url) return null;
const domain = new URL(account.url).hostname;
return domain;
}, [account]);
const sameInstance = instance === accountInstance;
const allowSwitch = !!account && !sameInstance;
return (
<Timeline
key={id}
title={`${account?.acct ? '@' + account.acct : 'Posts'}`}
2023-01-31 14:08:10 +03:00
titleComponent={
<h1
class="header-account"
2023-02-17 05:14:44 +03:00
// onClick={() => {
// states.showAccount = {
// account,
// instance,
// };
// }}
2023-01-31 14:08:10 +03:00
>
<b>
<EmojiText text={displayName} emojis={emojis} />
</b>
2023-01-31 14:08:10 +03:00
<div>
<span>@{acct}</span>
2023-01-31 14:08:10 +03:00
</div>
</h1>
}
2023-02-27 18:59:41 +03:00
id="account-statuses"
instance={instance}
emptyText="Nothing to see here yet."
2023-04-29 17:22:07 +03:00
errorText="Unable to load posts"
fetchItems={fetchAccountStatuses}
useItemID
2023-10-29 16:41:03 +03:00
view={media ? 'media' : undefined}
2023-02-03 16:08:08 +03:00
boostsCarousel={snapStates.settings.boostsCarousel}
timelineStart={TimelineStart}
refresh={[
excludeReplies,
excludeBoosts,
tagged,
media,
month + account?.acct,
].toString()}
headerEnd={
2023-06-13 12:46:37 +03:00
<Menu2
portal
// setDownOverflow
overflow="auto"
viewScroll="close"
position="anchor"
menuButton={
<button type="button" class="plain">
<Icon icon="more" size="l" />
</button>
}
>
<MenuItem
disabled={!allowSwitch}
onClick={() => {
(async () => {
try {
const { masto } = api({
instance: accountInstance,
});
const acc = await masto.v1.accounts.lookup({
acct: account.acct,
});
const { id } = acc;
location.hash = `/${accountInstance}/a/${id}`;
} catch (e) {
console.error(e);
alert('Unable to fetch account info');
}
})();
}}
>
<Icon icon="transfer" />{' '}
<small class="menu-double-lines">
Switch to account's instance (<b>{accountInstance}</b>)
</small>
</MenuItem>
2023-06-13 12:46:37 +03:00
</Menu2>
}
/>
);
}
function MonthPicker(props) {
const {
class: className,
disabled,
value,
min,
max,
onInput = () => {},
} = props;
const [_year, _month] = value?.split('-') || [];
const monthFieldRef = useRef();
const yearFieldRef = useRef();
const checkValidity = (month, year) => {
const [minYear, minMonth] = min?.split('-') || [];
const [maxYear, maxMonth] = max?.split('-') || [];
if (year < minYear) return false;
if (year > maxYear) return false;
if (year === minYear && month < minMonth) return false;
if (year === maxYear && month > maxMonth) return false;
return true;
};
return (
<div class={className}>
2023-10-20 14:24:01 +03:00
<Icon icon="month" size="l" />
<select
ref={monthFieldRef}
disabled={disabled}
value={_month || ''}
onInput={(e) => {
const { value: month } = e.currentTarget;
const year = yearFieldRef.current.value;
if (!checkValidity(month, year))
return {
value: '',
validity: {
valid: false,
},
};
onInput({
value: month ? `${year}-${month}` : '',
validity: {
valid: true,
},
});
}}
>
<option value="">Month</option>
<option disabled>-----</option>
{Array.from({ length: 12 }, (_, i) => (
<option
value={
// Month is 1-indexed
(i + 1).toString().padStart(2, '0')
}
key={i}
>
{new Date(0, i).toLocaleString('default', {
month: 'long',
})}
</option>
))}
</select>{' '}
<input
ref={yearFieldRef}
type="number"
disabled={disabled}
value={_year || new Date().getFullYear()}
2023-10-20 14:24:01 +03:00
min={min?.slice(0, 4) || MIN_YEAR}
max={max?.slice(0, 4) || new Date().getFullYear()}
onInput={(e) => {
const { value: year, validity } = e.currentTarget;
const month = monthFieldRef.current.value;
if (!validity.valid || !checkValidity(month, year))
return {
value: '',
validity: {
valid: false,
},
};
onInput({
value: year ? `${year}-${month}` : '',
validity: {
valid: true,
},
});
}}
style={{
width: '4.5em',
}}
/>
</div>
);
}
export default AccountStatuses;