revite/src/components/common/messaging/attachments/TextFile.tsx

81 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-07-05 06:23:23 -04:00
import axios from "axios";
2021-07-30 17:40:49 -04:00
import { Attachment } from "revolt-api/types/Autumn";
2021-07-05 06:23:23 -04:00
import styles from "./Attachment.module.scss";
import { useContext, useEffect, useState } from "preact/hooks";
import RequiresOnline from "../../../../context/revoltjs/RequiresOnline";
import {
2021-07-05 06:25:20 -04:00
AppContext,
StatusContext,
2021-07-05 06:23:23 -04:00
} from "../../../../context/revoltjs/RevoltClient";
import Preloader from "../../../ui/Preloader";
2021-06-20 17:09:18 -04:00
interface Props {
2021-07-05 06:25:20 -04:00
attachment: Attachment;
2021-06-20 17:09:18 -04:00
}
const fileCache: { [key: string]: string } = {};
export default function TextFile({ attachment }: Props) {
2021-07-05 06:25:20 -04:00
const [content, setContent] = useState<undefined | string>(undefined);
const [loading, setLoading] = useState(false);
const status = useContext(StatusContext);
const client = useContext(AppContext);
2021-07-05 06:23:23 -04:00
2021-07-05 06:25:20 -04:00
const url = client.generateFileURL(attachment)!;
2021-07-05 06:23:23 -04:00
2021-07-05 06:25:20 -04:00
useEffect(() => {
if (typeof content !== "undefined") return;
if (loading) return;
if (attachment.size > 100_000) {
2021-07-06 14:29:27 -04:00
setContent(
"This file is > 100 KB, for your sake I did not load it.\nSee tracking issue here for previews: https://github.com/revoltchat/revite/issues/35",
2021-07-06 14:29:27 -04:00
);
return;
}
2021-07-05 06:25:20 -04:00
setLoading(true);
2021-07-05 06:23:23 -04:00
const cached = fileCache[attachment._id];
2021-07-05 06:25:20 -04:00
if (cached) {
setContent(cached);
setLoading(false);
} else {
axios
.get(url, { transformResponse: [] })
2021-07-05 06:25:20 -04:00
.then((res) => {
setContent(res.data);
fileCache[attachment._id] = res.data;
setLoading(false);
})
.catch(() => {
console.error(
"Failed to load text file. [",
attachment._id,
"]",
);
setLoading(false);
});
}
2021-08-05 09:47:00 -04:00
}, [content, loading, status, attachment._id, attachment.size, url]);
2021-07-05 06:23:23 -04:00
2021-07-05 06:25:20 -04:00
return (
<div
className={styles.textContent}
data-loading={typeof content === "undefined"}>
{content ? (
<pre>
<code>{content}</code>
</pre>
) : (
<RequiresOnline>
<Preloader type="ring" />
</RequiresOnline>
)}
</div>
);
2021-06-20 17:09:18 -04:00
}