Files
lucko-paste/src/App.js

94 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-03-26 22:00:12 +00:00
import { useEffect, useState } from 'react';
import Editor from './components/Editor';
import parseContentType from 'content-type-parser';
2021-04-02 18:54:37 +01:00
import { languageIds } from './util/highlighting';
2021-03-26 22:00:12 +00:00
function getPasteIdFromUrl() {
const path = window.location.pathname;
if (path && /^\/[a-zA-Z0-9]+$/.test(path)) {
return path.substring(1);
} else {
return undefined;
}
}
async function loadFromBytebin(id) {
try {
const resp = await fetch('https://bytebin.lucko.me/' + id);
if (resp.ok) {
const content = await resp.text();
2021-04-02 13:05:15 +01:00
const type = parseLanguageFromContentType(
resp.headers.get('content-type')
);
2021-03-26 22:00:12 +00:00
document.title = 'paste | ' + id;
2021-03-27 13:09:03 +00:00
return { ok: true, content, type };
2021-03-26 22:00:12 +00:00
} else {
return { ok: false };
}
} catch (e) {
return { ok: false };
}
}
2021-03-27 13:09:03 +00:00
function parseLanguageFromContentType(contentType) {
const { type, subtype: subType } = parseContentType(contentType);
if (type === 'application' && subType === 'json') {
return 'json';
}
if (type === 'text' && languageIds.includes(subType.toLowerCase())) {
return subType.toLowerCase();
}
}
2021-03-26 22:00:12 +00:00
const INITIAL = Symbol();
const LOADING = Symbol();
const LOADED = Symbol();
export default function App() {
const [pasteId] = useState(getPasteIdFromUrl);
const [state, setState] = useState(INITIAL);
const [content, setContent] = useState('');
const [contentType, setContentType] = useState();
useEffect(() => {
if (pasteId && state === INITIAL) {
setState(LOADING);
2021-04-02 13:05:15 +01:00
setContent('Loading...');
2021-03-26 22:00:12 +00:00
loadFromBytebin(pasteId).then(({ ok, content, type }) => {
if (ok) {
setContent(content);
if (type) {
setContentType(type);
}
} else {
2021-03-27 21:23:47 +00:00
setContent(get404Message(pasteId));
2021-03-26 22:00:12 +00:00
}
setState(LOADED);
2021-04-02 13:05:15 +01:00
});
2021-03-26 22:00:12 +00:00
}
2021-04-02 13:05:15 +01:00
}, [pasteId, state, setContent]);
2021-03-26 22:00:12 +00:00
2021-04-02 13:05:15 +01:00
return (
<Editor
content={content}
setContent={setContent}
contentType={contentType}
/>
);
2021-03-26 22:00:12 +00:00
}
2021-03-27 21:23:47 +00:00
function get404Message(pasteId) {
return `
not found: '${pasteId}'
maybe the paste expired?
`;
2021-04-02 13:05:15 +01:00
}