revite/src/pages/Open.tsx

84 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-07-05 06:23:23 -04:00
import { useHistory, useParams } from "react-router-dom";
import { Text } from "preact-i18n";
import { useContext, useEffect } from "preact/hooks";
2021-07-05 06:23:23 -04:00
import { useIntermediate } from "../context/intermediate/Intermediate";
2021-07-05 06:23:23 -04:00
import {
AppContext,
ClientStatus,
StatusContext,
} from "../context/revoltjs/RevoltClient";
import {
useChannels,
useForceUpdate,
useUser,
} from "../context/revoltjs/hooks";
import Header from "../components/ui/Header";
export default function Open() {
2021-07-05 06:23:23 -04:00
const history = useHistory();
const client = useContext(AppContext);
const status = useContext(StatusContext);
const { id } = useParams<{ id: string }>();
const { openScreen } = useIntermediate();
2021-07-05 06:23:23 -04:00
if (status !== ClientStatus.ONLINE) {
return (
<Header placement="primary">
<Text id="general.loading" />
</Header>
);
}
2021-07-05 06:23:23 -04:00
const ctx = useForceUpdate();
const channels = useChannels(undefined, ctx);
const user = useUser(id, ctx);
2021-07-05 06:23:23 -04:00
useEffect(() => {
if (id === "saved") {
for (const channel of channels) {
if (channel?.channel_type === "SavedMessages") {
history.push(`/channel/${channel._id}`);
return;
}
}
2021-07-05 06:23:23 -04:00
client.users
.openDM(client.user?._id as string)
.then((channel) => history.push(`/channel/${channel?._id}`))
.catch((error) => openScreen({ id: "error", error }));
2021-07-05 06:23:23 -04:00
return;
}
2021-07-05 06:23:23 -04:00
if (user) {
const channel: string | undefined = channels.find(
(channel) =>
channel?.channel_type === "DirectMessage" &&
channel.recipients.includes(id),
)?._id;
2021-07-05 06:23:23 -04:00
if (channel) {
history.push(`/channel/${channel}`);
} else {
client.users
.openDM(id)
.then((channel) => history.push(`/channel/${channel?._id}`))
.catch((error) => openScreen({ id: "error", error }));
}
2021-07-05 06:23:23 -04:00
return;
}
2021-07-05 06:23:23 -04:00
history.push("/");
}, []);
2021-07-05 06:23:23 -04:00
return (
<Header placement="primary">
<Text id="general.loading" />
</Header>
);
}