Files
lucko-paste/src/App.tsx

78 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-01-08 19:10:27 +00:00
import { useCallback, useEffect, useState } from 'react';
2021-03-26 22:00:12 +00:00
import Editor from './components/Editor';
2022-11-06 22:46:13 +00:00
import { loadFromBytebin } from './util/storage';
2021-03-27 13:09:03 +00:00
2021-03-26 22:00:12 +00:00
const INITIAL = Symbol();
const LOADING = Symbol();
const LOADED = Symbol();
2022-11-06 22:46:13 +00:00
type LoadingState = typeof INITIAL | typeof LOADING | typeof LOADED;
2021-03-26 22:00:12 +00:00
export default function App() {
2022-11-06 22:46:13 +00:00
const [pasteId] = useState<string | undefined>(getPasteIdFromUrl);
const [state, setState] = useState<LoadingState>(INITIAL);
const [forcedContent, setForcedContent] = useState<string>('');
const [actualContent, setActualContent] = useState<string>('');
const [contentType, setContentType] = useState<string>();
2021-03-26 22:00:12 +00:00
2022-11-06 22:46:13 +00:00
const setContent = useCallback(
(content: string) => {
setActualContent(content);
setForcedContent(content);
},
[setActualContent, setForcedContent]
);
2022-01-08 19:10:27 +00:00
2021-03-26 22:00:12 +00:00
useEffect(() => {
if (pasteId && state === INITIAL) {
setState(LOADING);
2022-01-08 19:10:27 +00:00
setForcedContent('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
2022-01-08 19:10:27 +00:00
forcedContent={forcedContent}
setForcedContent={setContent}
actualContent={actualContent}
setActualContent={setActualContent}
2021-04-02 13:05:15 +01:00
contentType={contentType}
pasteId={pasteId}
2021-04-02 13:05:15 +01:00
/>
);
2021-03-26 22:00:12 +00:00
}
2021-03-27 21:23:47 +00:00
2022-11-06 22:46:13 +00:00
function get404Message(pasteId: string) {
2021-03-27 21:23:47 +00:00
return `
not found: '${pasteId}'
maybe the paste expired?
`;
2021-04-02 13:05:15 +01:00
}
2022-11-06 22:46:13 +00:00
function getPasteIdFromUrl() {
const path = window.location.pathname;
if (path && /^\/[a-zA-Z0-9]+$/.test(path)) {
return path.substring(1);
} else {
return undefined;
}
}