Almost there

This commit is contained in:
Philipp Heckel 2022-04-03 19:51:32 -04:00
parent aba7e86cbc
commit 6791c7395b
4 changed files with 365 additions and 308 deletions

View file

@ -52,14 +52,22 @@ class Api {
const send = new Promise(function (resolve, reject) { const send = new Promise(function (resolve, reject) {
xhr.open("PUT", url); xhr.open("PUT", url);
xhr.addEventListener('readystatechange', (ev) => { xhr.addEventListener('readystatechange', (ev) => {
console.log("read change", xhr.readyState, xhr.status, xhr.responseText, xhr)
if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) { if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) {
console.log(`[Api] Publish successful (HTTP ${xhr.status})`, xhr.response); console.log(`[Api] Publish successful (HTTP ${xhr.status})`, xhr.response);
resolve(xhr.response); resolve(xhr.response);
} else if (xhr.readyState === 4) { } else if (xhr.readyState === 4) {
console.log(`[Api] Publish failed`, xhr.status, xhr.responseText, xhr); console.log(`[Api] Publish failed (HTTP ${xhr.status})`, xhr.responseText);
let errorText;
try {
const error = JSON.parse(xhr.responseText);
if (error.code && error.error) {
errorText = `Error ${error.code}: ${error.error}`;
}
} catch (e) {
// Nothing
}
xhr.abort(); xhr.abort();
reject(ev); reject(errorText ?? "An error occurred");
} }
}) })
xhr.upload.addEventListener("progress", onProgress); xhr.upload.addEventListener("progress", onProgress);

View file

@ -18,10 +18,8 @@ import {expandUrl, topicUrl} from "../app/utils";
import ErrorBoundary from "./ErrorBoundary"; import ErrorBoundary from "./ErrorBoundary";
import routes from "./routes"; import routes from "./routes";
import {useAutoSubscribe, useBackgroundProcesses, useConnectionListeners} from "./hooks"; import {useAutoSubscribe, useBackgroundProcesses, useConnectionListeners} from "./hooks";
import {Backdrop} from "@mui/material";
import Paper from "@mui/material/Paper"; import Paper from "@mui/material/Paper";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import {MoreVert} from "@mui/icons-material";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import SendIcon from "@mui/icons-material/Send"; import SendIcon from "@mui/icons-material/Send";
import api from "../app/Api"; import api from "../app/Api";
@ -127,50 +125,54 @@ const Main = (props) => {
const Messaging = (props) => { const Messaging = (props) => {
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const [dialogKey, setDialogKey] = useState(0); const [dialogKey, setDialogKey] = useState(0);
const [dialogOpenMode, setDialogOpenMode] = useState("");
const [showDialog, setShowDialog] = useState(false); const [showDialog, setShowDialog] = useState(false);
const [showDropZone, setShowDropZone] = useState(false); const [showDropZone, setShowDropZone] = useState(false);
const subscription = props.selected; const subscription = props.selected;
const selectedTopicUrl = (subscription) ? topicUrl(subscription.baseUrl, subscription.topic) : ""; const selectedTopicUrl = (subscription) ? topicUrl(subscription.baseUrl, subscription.topic) : "";
useEffect(() => { const handleWindowDragEnter = () => {
window.addEventListener('dragenter', () => { setDialogOpenMode(prev => (prev) ? prev : SendDialog.OPEN_MODE_DRAG); // Only update if not already open
setShowDialog(true); setShowDialog(true);
setShowDropZone(true); setShowDropZone(true);
}); };
useEffect(() => {
window.addEventListener('dragenter', handleWindowDragEnter);
}, []); }, []);
const handleOpenDialogClick = () => {
setDialogOpenMode(SendDialog.OPEN_MODE_DEFAULT);
setShowDialog(true);
setShowDropZone(false);
};
const handleSendDialogClose = () => { const handleSendDialogClose = () => {
setShowDialog(false); setShowDialog(false);
setShowDropZone(false); setShowDropZone(false);
setDialogOpenMode("");
setDialogKey(prev => prev+1); setDialogKey(prev => prev+1);
}; };
const allowSubmit = () => true;
const allowDrag = (e) => {
if (allowSubmit()) {
e.dataTransfer.dropEffect = 'copy';
e.preventDefault();
}
};
return ( return (
<> <>
{subscription && <MessageBar {subscription && <MessageBar
subscription={subscription} subscription={subscription}
message={message} message={message}
onMessageChange={setMessage} onMessageChange={setMessage}
onOpenDialogClick={() => setShowDialog(true)} onOpenDialogClick={handleOpenDialogClick}
/>} />}
<SendDialog <SendDialog
key={`sendDialog${dialogKey}`} // Resets dialog when canceled/closed key={`sendDialog${dialogKey}`} // Resets dialog when canceled/closed
open={showDialog}
dropZone={showDropZone}
onClose={handleSendDialogClose}
onDrop={() => setShowDropZone(false)}
topicUrl={selectedTopicUrl} topicUrl={selectedTopicUrl}
message={message} message={message}
open={showDialog}
openMode={dialogOpenMode}
dropZone={showDropZone}
onClose={handleSendDialogClose}
onHideDropZone={() => setShowDropZone(false)}
onResetOpenMode={() => setDialogOpenMode(SendDialog.OPEN_MODE_DEFAULT)}
/> />
</> </>
); );

View file

@ -10,16 +10,16 @@ const DialogFooter = (props) => {
flexDirection: 'row', flexDirection: 'row',
justifyContent: 'space-between', justifyContent: 'space-between',
paddingLeft: '24px', paddingLeft: '24px',
paddingTop: '8px 24px', paddingBottom: '8px',
paddingBottom: '8px 24px',
}}> }}>
<DialogContentText sx={{ <DialogContentText component="div" sx={{
margin: '0px', margin: '0px',
paddingTop: '12px', paddingTop: '12px',
paddingBottom: '4px'
}}> }}>
{props.status} {props.status}
</DialogContentText> </DialogContentText>
<DialogActions> <DialogActions sx={{paddingRight: 2}}>
{props.children} {props.children}
</DialogActions> </DialogActions>
</Box> </Box>

View file

@ -27,7 +27,7 @@ import userManager from "../app/UserManager";
const SendDialog = (props) => { const SendDialog = (props) => {
const [topicUrl, setTopicUrl] = useState(""); const [topicUrl, setTopicUrl] = useState("");
const [message, setMessage] = useState(props.message || ""); const [message, setMessage] = useState("");
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
const [tags, setTags] = useState(""); const [tags, setTags] = useState("");
const [priority, setPriority] = useState(3); const [priority, setPriority] = useState(3);
@ -51,7 +51,7 @@ const SendDialog = (props) => {
const [attachFileError, setAttachFileError] = useState(""); const [attachFileError, setAttachFileError] = useState("");
const [activeRequest, setActiveRequest] = useState(null); const [activeRequest, setActiveRequest] = useState(null);
const [statusText, setStatusText] = useState(""); const [status, setStatus] = useState("");
const disabled = !!activeRequest; const disabled = !!activeRequest;
const [sendButtonEnabled, setSendButtonEnabled] = useState(true); const [sendButtonEnabled, setSendButtonEnabled] = useState(true);
@ -65,9 +65,14 @@ const SendDialog = (props) => {
}, [props.topicUrl]); }, [props.topicUrl]);
useEffect(() => { useEffect(() => {
setSendButtonEnabled(validTopicUrl(topicUrl) && !attachFileError); const valid = validTopicUrl(topicUrl) && !attachFileError;
setSendButtonEnabled(valid);
}, [topicUrl, attachFileError]); }, [topicUrl, attachFileError]);
useEffect(() => {
setMessage(props.message);
}, [props.message]);
const handleSubmit = async () => { const handleSubmit = async () => {
const { baseUrl, topic } = splitTopicUrl(topicUrl); const { baseUrl, topic } = splitTopicUrl(topicUrl);
const headers = {}; const headers = {};
@ -105,12 +110,11 @@ const SendDialog = (props) => {
headers["Authorization"] = basicAuth(user.username, user.password); headers["Authorization"] = basicAuth(user.username, user.password);
} }
const progressFn = (ev) => { const progressFn = (ev) => {
console.log(ev);
if (ev.loaded > 0 && ev.total > 0) { if (ev.loaded > 0 && ev.total > 0) {
const percent = Math.round(ev.loaded * 100.0 / ev.total); const percent = Math.round(ev.loaded * 100.0 / ev.total);
setStatusText(`Uploading ${formatBytes(ev.loaded)}/${formatBytes(ev.total)} (${percent}%) ...`); setStatus(`Uploading ${formatBytes(ev.loaded)}/${formatBytes(ev.total)} (${percent}%) ...`);
} else { } else {
setStatusText(`Uploading ...`); setStatus(`Uploading ...`);
} }
}; };
const request = api.publishXHR(baseUrl, topic, body, headers, progressFn); const request = api.publishXHR(baseUrl, topic, body, headers, progressFn);
@ -119,13 +123,13 @@ const SendDialog = (props) => {
if (!publishAnother) { if (!publishAnother) {
props.onClose(); props.onClose();
} else { } else {
setStatusText("Message published"); setStatus("Message published");
setActiveRequest(null);
} }
} catch (e) { } catch (e) {
console.log("error", e); setStatus(<Typography sx={{color: 'error.main', maxWidth: "400px"}}>{e}</Typography>);
setStatusText("An error occurred");
}
setActiveRequest(null); setActiveRequest(null);
}
}; };
const checkAttachmentLimits = async (file) => { const checkAttachmentLimits = async (file) => {
@ -133,17 +137,17 @@ const SendDialog = (props) => {
const { baseUrl } = splitTopicUrl(topicUrl); const { baseUrl } = splitTopicUrl(topicUrl);
const stats = await api.userStats(baseUrl); const stats = await api.userStats(baseUrl);
console.log(`[SendDialog] Visitor attachment limits`, stats); console.log(`[SendDialog] Visitor attachment limits`, stats);
const fileSizeLimit = stats.attachmentFileSizeLimit ?? 0; const fileSizeLimit = stats.attachmentFileSizeLimit ?? 0;
if (fileSizeLimit > 0 && file.size > fileSizeLimit) {
return setAttachFileError(`exceeds ${formatBytes(fileSizeLimit)} limit`);
}
const remainingBytes = stats.visitorAttachmentBytesRemaining ?? 0; const remainingBytes = stats.visitorAttachmentBytesRemaining ?? 0;
if (remainingBytes > 0 && file.size > remainingBytes) { const fileSizeLimitReached = fileSizeLimit > 0 && file.size > fileSizeLimit;
const quotaReached = remainingBytes > 0 && file.size > remainingBytes;
if (fileSizeLimitReached && quotaReached) {
return setAttachFileError(`exceeds ${formatBytes(fileSizeLimit)} file limit, quota reached: ${formatBytes(remainingBytes)} remaining`);
} else if (fileSizeLimitReached) {
return setAttachFileError(`exceeds ${formatBytes(fileSizeLimit)} file limit`);
} else if (quotaReached) {
return setAttachFileError(`quota reached, only ${formatBytes(remainingBytes)} remaining`); return setAttachFileError(`quota reached, only ${formatBytes(remainingBytes)} remaining`);
} }
setAttachFileError(""); setAttachFileError("");
} catch (e) { } catch (e) {
console.log(`[SendDialog] Retrieving attachment limits failed`, e); console.log(`[SendDialog] Retrieving attachment limits failed`, e);
@ -161,59 +165,39 @@ const SendDialog = (props) => {
const handleAttachFileDrop = async (ev) => { const handleAttachFileDrop = async (ev) => {
ev.preventDefault(); ev.preventDefault();
props.onDrop(); props.onHideDropZone();
await updateAttachFile(ev.dataTransfer.files[0]); await updateAttachFile(ev.dataTransfer.files[0]);
}; };
const updateAttachFile = async (file) => { const updateAttachFile = async (file) => {
setAttachFile(file); setAttachFile(file);
setFilename(file.name); setFilename(file.name);
props.onResetOpenMode();
await checkAttachmentLimits(file); await checkAttachmentLimits(file);
}; };
const allowDrag = (ev) => { const handleAttachFileDragLeave = () => {
if (true /* allowSubmit */) { // When the dialog was opened by dragging a file in, close it. If it was open
ev.dataTransfer.dropEffect = 'copy'; // before, keep it open.
ev.preventDefault();
console.log(`open mode ${props.openMode}`);
if (props.openMode === SendDialog.OPEN_MODE_DRAG) {
props.onClose();
} else {
props.onHideDropZone();
} }
}; };
return ( return (
<>
{dropZone && <DropArea
onDrop={handleAttachFileDrop}
onDragLeave={handleAttachFileDragLeave}/>
}
<Dialog maxWidth="md" open={props.open} onClose={props.onCancel} fullScreen={fullScreen}> <Dialog maxWidth="md" open={props.open} onClose={props.onCancel} fullScreen={fullScreen}>
<DialogTitle>Publish to {shortUrl(topicUrl)}</DialogTitle> <DialogTitle>Publish to {shortUrl(topicUrl)}</DialogTitle>
<DialogContent> <DialogContent>
{dropZone && {dropZone && <DropBox/>}
<Box sx={{
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
zIndex: 10000,
backgroundColor: "#ffffffbb"
}}>
<Box
sx={{
position: 'absolute',
border: '3px dashed #ccc',
borderRadius: '5px',
left: "40px",
top: "40px",
right: "40px",
bottom: "40px",
zIndex: 10001,
display: 'flex',
justifyContent: "center",
alignItems: "center",
}}
onDrop={handleAttachFileDrop}
onDragEnter={allowDrag}
onDragOver={allowDrag}
>
<Typography variant="h5">Drop file here</Typography>
</Box>
</Box>
}
{showTopicUrl && {showTopicUrl &&
<ClosableRow disabled={disabled} onClose={() => { <ClosableRow disabled={disabled} onClose={() => {
setTopicUrl(props.topicUrl); setTopicUrl(props.topicUrl);
@ -404,7 +388,7 @@ const SendDialog = (props) => {
<TextField <TextField
margin="dense" margin="dense"
label="Delay" label="Delay"
placeholder="Unix timestamp, duration or English natural language" placeholder="Delay delivery, e.g. 1649029748, 30m, or tomorrow, 9am"
value={delay} value={delay}
onChange={ev => setDelay(ev.target.value)} onChange={ev => setDelay(ev.target.value)}
disabled={disabled} disabled={disabled}
@ -427,10 +411,10 @@ const SendDialog = (props) => {
</div> </div>
<Typography variant="body1" sx={{marginTop: 1, marginBottom: 1}}> <Typography variant="body1" sx={{marginTop: 1, marginBottom: 1}}>
For examples and a detailed description of all send features, please For examples and a detailed description of all send features, please
refer to the <Link href="/docs">documentation</Link>. refer to the <Link href="/docs" target="_blank">documentation</Link>.
</Typography> </Typography>
</DialogContent> </DialogContent>
<DialogFooter status={statusText}> <DialogFooter status={status}>
{activeRequest && <Button onClick={() => activeRequest.abort()}>Cancel sending</Button>} {activeRequest && <Button onClick={() => activeRequest.abort()}>Cancel sending</Button>}
{!activeRequest && {!activeRequest &&
<> <>
@ -446,6 +430,7 @@ const SendDialog = (props) => {
} }
</DialogFooter> </DialogFooter>
</Dialog> </Dialog>
</>
); );
}; };
@ -539,7 +524,7 @@ const ExpandingTextField = (props) => {
ref={invisibleFieldRef} ref={invisibleFieldRef}
component="span" component="span"
variant={props.variant} variant={props.variant}
sx={{position: "absolute", left: "-100%"}} sx={{position: "absolute", left: "-200%"}}
> >
{props.value} {props.value}
</Typography> </Typography>
@ -559,12 +544,74 @@ const ExpandingTextField = (props) => {
) )
}; };
const DropArea = (props) => {
const allowDrag = (ev) => {
// This is where we could disallow certain files to be dragged in.
// For now we allow all files.
ev.dataTransfer.dropEffect = 'copy';
ev.preventDefault();
};
return (
<Box
sx={{
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
zIndex: 10002,
}}
onDrop={props.onDrop}
onDragEnter={allowDrag}
onDragOver={allowDrag}
onDragLeave={props.onDragLeave}
/>
);
};
const DropBox = () => {
return (
<Box sx={{
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
zIndex: 10000,
backgroundColor: "#ffffffbb"
}}>
<Box
sx={{
position: 'absolute',
border: '3px dashed #ccc',
borderRadius: '5px',
left: "40px",
top: "40px",
right: "40px",
bottom: "40px",
zIndex: 10001,
display: 'flex',
justifyContent: "center",
alignItems: "center",
}}
>
<Typography variant="h5">Drop file here</Typography>
</Box>
</Box>
);
}
const priorities = { const priorities = {
1: { label: "Minimum priority", file: priority1 }, 1: { label: "Min. priority", file: priority1 },
2: { label: "Low priority", file: priority2 }, 2: { label: "Low priority", file: priority2 },
3: { label: "Default priority", file: priority3 }, 3: { label: "Default priority", file: priority3 },
4: { label: "High priority", file: priority4 }, 4: { label: "High priority", file: priority4 },
5: { label: "Maximum priority", file: priority5 } 5: { label: "Max. priority", file: priority5 }
}; };
SendDialog.OPEN_MODE_DEFAULT = "default";
SendDialog.OPEN_MODE_DRAG = "drag";
export default SendDialog; export default SendDialog;