phanpy/src/app.jsx

510 wiersze
15 KiB
React
Czysty Zwykły widok Historia

2022-12-10 09:14:48 +00:00
import './app.css';
2022-12-26 06:02:05 +00:00
import 'toastify-js/src/toastify.css';
2022-12-10 09:14:48 +00:00
2023-01-01 04:01:54 +00:00
import debounce from 'just-debounce-it';
import {
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'preact/hooks';
2023-02-09 14:27:49 +00:00
import {
matchPath,
Route,
Routes,
useLocation,
useNavigate,
} from 'react-router-dom';
2022-12-26 06:02:05 +00:00
import Toastify from 'toastify-js';
2022-12-10 09:14:48 +00:00
import { useSnapshot } from 'valtio';
import Account from './components/account';
import Compose from './components/compose';
import Drafts from './components/drafts';
import Icon from './components/icon';
import Link from './components/link';
2022-12-10 09:14:48 +00:00
import Loader from './components/loader';
import MediaModal from './components/media-modal';
2022-12-10 09:14:48 +00:00
import Modal from './components/modal';
import NotFound from './pages/404';
import AccountStatuses from './pages/account-statuses';
import Bookmarks from './pages/bookmarks';
import Favourites from './pages/favourites';
2023-02-03 13:08:08 +00:00
import Following from './pages/following';
import Hashtags from './pages/hashtags';
2022-12-10 09:14:48 +00:00
import Home from './pages/home';
2023-02-09 14:27:49 +00:00
import HomeV1 from './pages/home-v1';
import Lists from './pages/lists';
2022-12-10 09:14:48 +00:00
import Login from './pages/login';
import Notifications from './pages/notifications';
import Public from './pages/public';
2022-12-10 09:14:48 +00:00
import Settings from './pages/settings';
import Status from './pages/status';
import Welcome from './pages/welcome';
2023-02-09 15:59:57 +00:00
import {
api,
initAccount,
initClient,
initInstance,
initPreferences,
} from './utils/api';
2022-12-10 09:14:48 +00:00
import { getAccessToken } from './utils/auth';
import states, { getStatus, saveStatus } from './utils/states';
2022-12-10 09:14:48 +00:00
import store from './utils/store';
import { getCurrentAccount } from './utils/store-utils';
2022-12-10 09:14:48 +00:00
window.__STATES__ = states;
2022-12-10 09:14:48 +00:00
2022-12-31 17:46:08 +00:00
function App() {
2022-12-10 09:14:48 +00:00
const snapStates = useSnapshot(states);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [uiState, setUIState] = useState('loading');
const navigate = useNavigate();
2022-12-10 09:14:48 +00:00
useLayoutEffect(() => {
const theme = store.local.get('theme');
if (theme) {
document.documentElement.classList.add(`is-${theme}`);
document
.querySelector('meta[name="color-scheme"]')
.setAttribute('content', theme === 'auto' ? 'dark light' : theme);
2022-12-10 09:14:48 +00:00
}
}, []);
useEffect(() => {
const instanceURL = store.local.get('instanceURL');
const code = (window.location.search.match(/code=([^&]+)/) || [])[1];
if (code) {
console.log({ code });
// Clear the code from the URL
window.history.replaceState({}, document.title, '/');
const clientID = store.session.get('clientID');
const clientSecret = store.session.get('clientSecret');
(async () => {
setUIState('loading');
const { access_token: accessToken } = await getAccessToken({
2022-12-10 09:14:48 +00:00
instanceURL,
client_id: clientID,
client_secret: clientSecret,
code,
});
const masto = initClient({ instance: instanceURL, accessToken });
await Promise.allSettled([
initInstance(masto),
initAccount(masto, instanceURL, accessToken),
]);
2023-02-09 15:59:57 +00:00
initPreferences(masto);
2022-12-10 09:14:48 +00:00
setIsLoggedIn(true);
setUIState('default');
})();
} else {
const account = getCurrentAccount();
if (account) {
store.session.set('currentAccount', account.info.id);
const { masto } = api({ account });
2023-02-09 15:59:57 +00:00
initPreferences(masto);
2023-02-07 16:31:46 +00:00
(async () => {
await initInstance(masto);
setIsLoggedIn(true);
})();
}
setUIState('default');
2022-12-10 09:14:48 +00:00
}
}, []);
let location = useLocation();
states.currentLocation = location.pathname;
const locationDeckMap = {
'/': 'home-page',
'/notifications': 'notifications-page',
};
2022-12-30 12:37:57 +00:00
const focusDeck = () => {
let timer = setTimeout(() => {
const page = document.getElementById(locationDeckMap[location.pathname]);
console.debug('FOCUS', location.pathname, page);
2022-12-30 12:37:57 +00:00
if (page) {
page.focus();
}
}, 100);
return () => clearTimeout(timer);
};
useEffect(focusDeck, [location]);
2022-12-30 12:37:57 +00:00
useEffect(() => {
if (
!snapStates.showCompose &&
!snapStates.showSettings &&
!snapStates.showAccount
) {
focusDeck();
}
}, [snapStates.showCompose, snapStates.showSettings, snapStates.showAccount]);
2022-12-10 09:14:48 +00:00
2023-02-09 14:27:49 +00:00
// useEffect(() => {
// // HACK: prevent this from running again due to HMR
// if (states.init) return;
// if (isLoggedIn) {
// requestAnimationFrame(startVisibility);
// states.init = true;
// }
// }, [isLoggedIn]);
2022-12-10 09:14:48 +00:00
const { prevLocation } = snapStates;
const backgroundLocation = useRef(prevLocation || null);
const isModalPage =
matchPath('/:instance/s/:id', location.pathname) ||
matchPath('/s/:id', location.pathname);
if (isModalPage) {
if (!backgroundLocation.current) backgroundLocation.current = prevLocation;
} else {
backgroundLocation.current = null;
}
console.debug({
backgroundLocation: backgroundLocation.current,
location,
});
const nonRootLocation = useMemo(() => {
const { pathname } = location;
return !/^\/(login|welcome)/.test(pathname);
}, [location]);
2022-12-10 09:14:48 +00:00
return (
<>
<Routes location={nonRootLocation || location}>
<Route
path="/"
element={
isLoggedIn ? (
<Home />
) : uiState === 'loading' ? (
<Loader />
) : (
<Welcome />
)
2022-12-10 09:14:48 +00:00
}
/>
<Route path="/login" element={<Login />} />
<Route path="/welcome" element={<Welcome />} />
</Routes>
<Routes location={backgroundLocation.current || location}>
{isLoggedIn && (
<Route path="/notifications" element={<Notifications />} />
)}
2023-02-03 13:08:08 +00:00
{isLoggedIn && <Route path="/l/f" element={<Following />} />}
2023-02-09 14:27:49 +00:00
{isLoggedIn && <Route path="/homev1" element={<HomeV1 />} />}
{isLoggedIn && <Route path="/b" element={<Bookmarks />} />}
{isLoggedIn && <Route path="/f" element={<Favourites />} />}
{isLoggedIn && <Route path="/l/:id" element={<Lists />} />}
2023-02-06 11:54:18 +00:00
<Route path="/:instance?/t/:hashtag" element={<Hashtags />} />
<Route path="/:instance?/a/:id" element={<AccountStatuses />} />
2023-02-06 12:17:07 +00:00
<Route path="/:instance?/p">
<Route index element={<Public />} />
<Route path="l" element={<Public local />} />
</Route>
{/* <Route path="/:instance?/p/l?" element={<Public />} /> */}
{/* <Route path="/:anything" element={<NotFound />} /> */}
</Routes>
<Routes>
2023-02-06 11:54:18 +00:00
<Route path="/:instance?/s/:id" element={<Status />} />
</Routes>
<nav id="tab-bar" hidden>
<li>
<Link to="/">
<Icon icon="home" alt="Home" size="xl" />
</Link>
</li>
<li>
<Link to="/notifications">
<Icon icon="notification" alt="Notifications" size="xl" />
</Link>
</li>
<li>
<Link to="/bookmarks">
<Icon icon="bookmark" alt="Bookmarks" size="xl" />
</Link>
</li>
</nav>
2022-12-10 09:14:48 +00:00
{!!snapStates.showCompose && (
<Modal>
<Compose
replyToStatus={
typeof snapStates.showCompose !== 'boolean'
? snapStates.showCompose.replyToStatus
: window.__COMPOSE__?.replyToStatus || null
}
editStatus={
states.showCompose?.editStatus ||
window.__COMPOSE__?.editStatus ||
null
}
draftStatus={
states.showCompose?.draftStatus ||
window.__COMPOSE__?.draftStatus ||
null
2022-12-10 09:14:48 +00:00
}
onClose={(results) => {
const { newStatus } = results || {};
2022-12-10 09:14:48 +00:00
states.showCompose = false;
window.__COMPOSE__ = null;
if (newStatus) {
2022-12-10 09:14:48 +00:00
states.reloadStatusPage++;
2022-12-28 10:05:22 +00:00
setTimeout(() => {
const toast = Toastify({
text: 'Status posted. Check it out.',
duration: 10_000, // 10 seconds
gravity: 'bottom',
position: 'center',
// destination: `/#/s/${newStatus.id}`,
onClick: () => {
toast.hideToast();
states.prevLocation = location;
navigate(`/s/${newStatus.id}`);
2022-12-28 10:05:22 +00:00
},
});
toast.showToast();
}, 1000);
2022-12-10 09:14:48 +00:00
}
}}
/>
</Modal>
)}
{!!snapStates.showSettings && (
<Modal
onClick={(e) => {
if (e.target === e.currentTarget) {
states.showSettings = false;
}
}}
>
<Settings
onClose={() => {
states.showSettings = false;
}}
/>
</Modal>
)}
{!!snapStates.showAccount && (
<Modal
class="light"
onClick={(e) => {
if (e.target === e.currentTarget) {
states.showAccount = false;
}
}}
>
<Account
account={snapStates.showAccount?.account || snapStates.showAccount}
instance={snapStates.showAccount?.instance}
onClose={() => {
states.showAccount = false;
}}
/>
2022-12-10 09:14:48 +00:00
</Modal>
)}
{!!snapStates.showDrafts && (
<Modal
onClick={(e) => {
if (e.target === e.currentTarget) {
states.showDrafts = false;
}
}}
>
<Drafts />
</Modal>
)}
{!!snapStates.showMediaModal && (
<Modal
onClick={(e) => {
if (
e.target === e.currentTarget ||
e.target.classList.contains('media')
) {
states.showMediaModal = false;
}
}}
>
<MediaModal
mediaAttachments={snapStates.showMediaModal.mediaAttachments}
instance={snapStates.showMediaModal.instance}
index={snapStates.showMediaModal.index}
statusID={snapStates.showMediaModal.statusID}
onClose={() => {
states.showMediaModal = false;
}}
/>
</Modal>
)}
2022-12-10 09:14:48 +00:00
</>
);
}
2022-12-31 17:46:08 +00:00
let ws;
2022-12-31 17:46:08 +00:00
async function startStream() {
const { masto, instance } = api();
if (
ws &&
(ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN)
) {
return;
}
2022-12-31 17:46:08 +00:00
const stream = await masto.v1.stream.streamUser();
console.log('STREAM START', { stream });
ws = stream.ws;
2023-01-01 04:01:54 +00:00
const handleNewStatus = debounce((status) => {
2022-12-31 17:46:08 +00:00
console.log('UPDATE', status);
if (document.visibilityState === 'hidden') return;
2022-12-31 17:46:08 +00:00
const inHomeNew = states.homeNew.find((s) => s.id === status.id);
const inHome = status.id === states.homeLast?.id;
2022-12-31 17:46:08 +00:00
if (!inHomeNew && !inHome) {
if (states.settings.boostsCarousel && status.reblog) {
// do nothing
} else {
states.homeNew.unshift({
id: status.id,
reblog: status.reblog?.id,
reply: !!status.inReplyToAccountId,
});
console.log('homeNew 1', [...states.homeNew]);
}
2022-12-31 17:46:08 +00:00
}
saveStatus(status, instance);
2023-01-01 04:01:54 +00:00
}, 5000);
stream.on('update', handleNewStatus);
2022-12-31 17:46:08 +00:00
stream.on('status.update', (status) => {
console.log('STATUS.UPDATE', status);
saveStatus(status, instance);
2022-12-31 17:46:08 +00:00
});
stream.on('delete', (statusID) => {
console.log('DELETE', statusID);
// delete states.statuses[statusID];
const s = getStatus(statusID);
2022-12-31 17:46:08 +00:00
if (s) s._deleted = true;
});
stream.on('notification', (notification) => {
console.log('NOTIFICATION', notification);
const inNotificationsNew = states.notificationsNew.find(
(n) => n.id === notification.id,
);
const inNotifications = notification.id === states.notificationsLast?.id;
2022-12-31 17:46:08 +00:00
if (!inNotificationsNew && !inNotifications) {
states.notificationsNew.unshift(notification);
}
saveStatus(notification.status, instance, { override: false });
2022-12-31 17:46:08 +00:00
});
stream.ws.onclose = () => {
console.log('STREAM CLOSED!');
if (document.visibilityState !== 'hidden') {
2022-12-31 17:46:08 +00:00
startStream();
}
2022-12-31 17:46:08 +00:00
};
return {
stream,
stopStream: () => {
stream.ws.close();
},
};
}
let lastHidden;
2022-12-31 17:46:08 +00:00
function startVisibility() {
const { masto, instance } = api();
const handleVisible = (visible) => {
if (!visible) {
2022-12-31 17:46:08 +00:00
const timestamp = Date.now();
lastHidden = timestamp;
2022-12-31 17:46:08 +00:00
} else {
const timestamp = Date.now();
const diff = timestamp - lastHidden;
const diffMins = Math.round(diff / 1000 / 60);
console.log(`visible: ${visible}`, { lastHidden, diffMins });
if (!lastHidden || diffMins > 1) {
(async () => {
try {
2023-01-27 06:36:47 +00:00
const firstStatusID = states.homeLast?.id;
const firstNotificationID = states.notificationsLast?.id;
console.log({ states, firstNotificationID, firstStatusID });
const fetchHome = masto.v1.timelines.listHome({
2023-01-27 06:36:47 +00:00
limit: 5,
...(firstStatusID && { sinceId: firstStatusID }),
});
const fetchNotifications = masto.v1.notifications.list({
limit: 1,
...(firstNotificationID && { sinceId: firstNotificationID }),
});
const newStatuses = await fetchHome;
2023-01-27 06:36:47 +00:00
const hasOneAndReblog =
newStatuses.length === 1 && newStatuses?.[0]?.reblog;
2023-01-27 07:17:56 +00:00
if (newStatuses.length) {
2023-01-27 06:36:47 +00:00
if (states.settings.boostsCarousel && hasOneAndReblog) {
// do nothing
} else {
2022-12-31 17:46:08 +00:00
states.homeNew = newStatuses.map((status) => {
saveStatus(status, instance);
2022-12-31 17:46:08 +00:00
return {
id: status.id,
reblog: status.reblog?.id,
reply: !!status.inReplyToAccountId,
};
});
console.log('homeNew 2', [...states.homeNew]);
2022-12-31 17:46:08 +00:00
}
}
2022-12-31 17:46:08 +00:00
const newNotifications = await fetchNotifications;
if (newNotifications.length) {
const notification = newNotifications[0];
const inNotificationsNew = states.notificationsNew.find(
(n) => n.id === notification.id,
);
const inNotifications =
notification.id === states.notificationsLast?.id;
if (!inNotificationsNew && !inNotifications) {
states.notificationsNew.unshift(notification);
2022-12-31 17:46:08 +00:00
}
saveStatus(notification.status, instance, { override: false });
2022-12-31 17:46:08 +00:00
}
} catch (e) {
// Silently fail
console.error(e);
} finally {
startStream();
}
})();
2022-12-31 17:46:08 +00:00
}
}
};
const handleVisibilityChange = () => {
const hidden = document.visibilityState === 'hidden';
handleVisible(!hidden);
console.log('VISIBILITY: ' + (hidden ? 'hidden' : 'visible'));
};
2022-12-31 17:46:08 +00:00
document.addEventListener('visibilitychange', handleVisibilityChange);
requestAnimationFrame(handleVisibilityChange);
2022-12-31 17:46:08 +00:00
return {
stop: () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
},
};
}
export { App };