Debian Codegraph @

web/src/components/PublishDialog.jsx

raw
1 import * as React from "react";
2 import { Suspense, lazy, useContext, useEffect, useRef, useState } from "react";
3 import {
4 Checkbox,
5 Chip,
6 FormControl,
7 FormControlLabel,
8 InputLabel,
9 Link,
10 Select,
11 Tooltip,
12 useMediaQuery,
13 TextField,
14 Dialog,
15 DialogTitle,
16 DialogContent,
17 Button,
18 Typography,
19 IconButton,
20 MenuItem,
21 Box,
22 useTheme,
23 } from "@mui/material";
24 import InsertEmoticonIcon from "@mui/icons-material/InsertEmoticon";
25 import Close from "@mui/icons-material/Close";
26 import { Trans, useTranslation } from "react-i18next";
27 import priority1 from "../img/priority-1.svg";
28 import priority2 from "../img/priority-2.svg";
29 import priority3 from "../img/priority-3.svg";
30 import priority4 from "../img/priority-4.svg";
31 import priority5 from "../img/priority-5.svg";
32 import { formatBytes, maybeWithAuth, topicShortUrl, topicUrl, validTopic, validUrl } from "../app/utils";
33 import { imageRegex } from "../app/notificationUtils";
34 import AttachmentIcon from "./AttachmentIcon";
35 import DialogFooter from "./DialogFooter";
36 import api from "../app/Api";
37 import userManager from "../app/UserManager";
38 import session from "../app/Session";
39 import routes from "./routes";
40 import accountApi from "../app/AccountApi";
41 import { UnauthorizedError } from "../app/errors";
42 import AccountContext from "./AccountContext";
43
44 // Loaded lazily so the full emoji dataset (~300 KB) is only fetched when the publish
45 // dialog is opened, not in the initial app bundle (see EmojiPicker.jsx).
46 const EmojiPicker = lazy(() => import("./EmojiPicker"));
47
48 const PublishDialog = (props) => {
49 const theme = useTheme();
50 const { t } = useTranslation();
51 const { account } = useContext(AccountContext);
52 const [baseUrl, setBaseUrl] = useState("");
53 const [topic, setTopic] = useState("");
54 const [message, setMessage] = useState("");
55 const [messageFocused, setMessageFocused] = useState(true);
56 const [title, setTitle] = useState("");
57 const [tags, setTags] = useState("");
58 const [priority, setPriority] = useState(3);
59 const [clickUrl, setClickUrl] = useState("");
60 const [attachUrl, setAttachUrl] = useState("");
61 const [attachFile, setAttachFile] = useState(null);
62 const [filename, setFilename] = useState("");
63 const [filenameEdited, setFilenameEdited] = useState(false);
64 const [email, setEmail] = useState("");
65 const [call, setCall] = useState("");
66 const [delay, setDelay] = useState("");
67 const [publishAnother, setPublishAnother] = useState(false);
68 const [markdownEnabled, setMarkdownEnabled] = useState(false);
69
70 const [showTopicUrl, setShowTopicUrl] = useState("");
71 const [showClickUrl, setShowClickUrl] = useState(false);
72 const [showAttachUrl, setShowAttachUrl] = useState(false);
73 const [showEmail, setShowEmail] = useState(false);
74 const [showCall, setShowCall] = useState(false);
75 const [showDelay, setShowDelay] = useState(false);
76
77 const showAttachFile = !!attachFile && !showAttachUrl;
78 const attachFileInput = useRef();
79 const [attachFileError, setAttachFileError] = useState("");
80
81 const [activeRequest, setActiveRequest] = useState(null);
82 const [status, setStatus] = useState("");
83 const disabled = !!activeRequest;
84
85 const [emojiPickerAnchorEl, setEmojiPickerAnchorEl] = useState(null);
86
87 const [dropZone, setDropZone] = useState(false);
88 const [sendButtonEnabled, setSendButtonEnabled] = useState(true);
89
90 const open = !!props.openMode;
91 const fullScreen = useMediaQuery(theme.breakpoints.down("sm"));
92
93 useEffect(() => {
94 window.addEventListener("dragenter", () => {
95 props.onDragEnter();
96 setDropZone(true);
97 });
98 }, []);
99
100 useEffect(() => {
101 setBaseUrl(props.baseUrl);
102 setTopic(props.topic);
103 setShowTopicUrl(!props.baseUrl || !props.topic);
104 setMessageFocused(!!props.topic); // Focus message only if topic is set
105 }, [props.baseUrl, props.topic]);
106
107 useEffect(() => {
108 const valid = validUrl(baseUrl) && validTopic(topic) && !attachFileError;
109 setSendButtonEnabled(valid);
110 }, [baseUrl, topic, attachFileError]);
111
112 useEffect(() => {
113 setMessage(props.message);
114 }, [props.message]);
115
116 const updateBaseUrl = (newVal) => {
117 if (validUrl(newVal)) {
118 setBaseUrl(newVal.replace(/\/$/, "")); // strip traililng slash after https?://
119 } else {
120 setBaseUrl(newVal);
121 }
122 };
123
124 const handleSubmit = async () => {
125 const url = new URL(topicUrl(baseUrl, topic));
126 if (title.trim()) {
127 url.searchParams.append("title", title.trim());
128 }
129 if (tags.trim()) {
130 url.searchParams.append("tags", tags.trim());
131 }
132 if (priority && priority !== 3) {
133 url.searchParams.append("priority", priority.toString());
134 }
135 if (clickUrl.trim()) {
136 url.searchParams.append("click", clickUrl.trim());
137 }
138 if (attachUrl.trim()) {
139 url.searchParams.append("attach", attachUrl.trim());
140 }
141 if (filename.trim()) {
142 url.searchParams.append("filename", filename.trim());
143 }
144 if (email.trim()) {
145 url.searchParams.append("email", email.trim());
146 }
147 if (call.trim()) {
148 url.searchParams.append("call", call.trim());
149 }
150 if (delay.trim()) {
151 url.searchParams.append("delay", delay.trim());
152 }
153 if (attachFile && message.trim()) {
154 url.searchParams.append("message", message.replaceAll("\n", "\\n").trim());
155 }
156 if (markdownEnabled) {
157 url.searchParams.append("markdown", "true");
158 }
159
160 const body = attachFile || message;
161 try {
162 const user = await userManager.get(baseUrl);
163 const headers = maybeWithAuth({}, user);
164 const progressFn = (ev) => {
165 if (ev.loaded > 0 && ev.total > 0) {
166 setStatus(
167 t("publish_dialog_progress_uploading_detail", {
168 loaded: formatBytes(ev.loaded),
169 total: formatBytes(ev.total),
170 percent: Math.round((ev.loaded * 100.0) / ev.total),
171 }),
172 );
173 } else {
174 setStatus(t("publish_dialog_progress_uploading"));
175 }
176 };
177 const request = api.publishXHR(url, body, headers, progressFn);
178 setActiveRequest(request);
179 await request;
180 if (!publishAnother) {
181 props.onClose();
182 } else {
183 setStatus(t("publish_dialog_message_published"));
184 setActiveRequest(null);
185 }
186 } catch (e) {
187 setStatus(<Typography sx={{ color: "error.main", maxWidth: "400px" }}>{e}</Typography>);
188 setActiveRequest(null);
189 }
190 };
191
192 const checkAttachmentLimits = async (file) => {
193 try {
194 const apiAccount = await accountApi.get();
195 const fileSizeLimit = apiAccount.limits.attachment_file_size ?? 0;
196 const remainingBytes = apiAccount.stats.attachment_total_size_remaining;
197 const fileSizeLimitReached = fileSizeLimit > 0 && file.size > fileSizeLimit;
198 const quotaReached = remainingBytes > 0 && file.size > remainingBytes;
199 if (fileSizeLimitReached && quotaReached) {
200 setAttachFileError(
201 t("publish_dialog_attachment_limits_file_and_quota_reached", {
202 fileSizeLimit: formatBytes(fileSizeLimit),
203 remainingBytes: formatBytes(remainingBytes),
204 }),
205 );
206 } else if (fileSizeLimitReached) {
207 setAttachFileError(
208 t("publish_dialog_attachment_limits_file_reached", {
209 fileSizeLimit: formatBytes(fileSizeLimit),
210 }),
211 );
212 } else if (quotaReached) {
213 setAttachFileError(
214 t("publish_dialog_attachment_limits_quota_reached", {
215 remainingBytes: formatBytes(remainingBytes),
216 }),
217 );
218 } else {
219 setAttachFileError("");
220 }
221 } catch (e) {
222 console.log(`[PublishDialog] Retrieving attachment limits failed`, e);
223 if (e instanceof UnauthorizedError) {
224 await session.resetAndRedirect(routes.login);
225 } else {
226 setAttachFileError(""); // Reset error (rely on server-side checking)
227 }
228 }
229 };
230
231 const handleAttachFileClick = () => {
232 attachFileInput.current.click();
233 };
234
235 const updateAttachFile = async (file) => {
236 setAttachFile(file);
237 setFilename(file.name);
238 props.onResetOpenMode();
239 await checkAttachmentLimits(file);
240 };
241
242 useEffect(() => {
243 if (props.attachFile) {
244 updateAttachFile(props.attachFile);
245 }
246 }, [props.attachFile]);
247
248 const handlePaste = (ev) => {
249 const blob = props.getPastedImage(ev);
250 if (blob) {
251 updateAttachFile(blob);
252 }
253 };
254
255 const handleAttachFileChanged = async (ev) => {
256 await updateAttachFile(ev.target.files[0]);
257 };
258
259 const handleAttachFileDrop = async (ev) => {
260 ev.preventDefault();
261 setDropZone(false);
262 await updateAttachFile(ev.dataTransfer.files[0]);
263 };
264
265 const handleAttachFileDragLeave = () => {
266 setDropZone(false);
267 if (props.openMode === PublishDialog.OPEN_MODE_DRAG) {
268 props.onClose(); // Only close dialog if it was not open before dragging file in
269 }
270 };
271
272 const handleEmojiClick = (ev) => {
273 setEmojiPickerAnchorEl(ev.currentTarget);
274 };
275
276 const handleEmojiPick = (emoji) => {
277 setTags((prevTags) => (prevTags.trim() ? `${prevTags.trim()}, ${emoji}` : emoji));
278 };
279
280 const handleEmojiClose = () => {
281 setEmojiPickerAnchorEl(null);
282 };
283
284 const priorities = {
285 1: { label: t("publish_dialog_priority_min"), file: priority1 },
286 2: { label: t("publish_dialog_priority_low"), file: priority2 },
287 3: { label: t("publish_dialog_priority_default"), file: priority3 },
288 4: { label: t("publish_dialog_priority_high"), file: priority4 },
289 5: { label: t("publish_dialog_priority_max"), file: priority5 },
290 };
291
292 return (
293 <>
294 {dropZone && <DropArea onDrop={handleAttachFileDrop} onDragLeave={handleAttachFileDragLeave} />}
295 <Dialog maxWidth="md" open={open} onClose={props.onClose} fullScreen={fullScreen}>
296 <DialogTitle>
297 {baseUrl && topic
298 ? t("publish_dialog_title_topic", {
299 topic: topicShortUrl(baseUrl, topic),
300 })
301 : t("publish_dialog_title_no_topic")}
302 </DialogTitle>
303 <DialogContent>
304 {dropZone && <DropBox />}
305 {showTopicUrl && (
306 <ClosableRow
307 closable={!!props.baseUrl && !!props.topic}
308 disabled={disabled}
309 closeLabel={t("publish_dialog_topic_reset")}
310 onClose={() => {
311 setBaseUrl(props.baseUrl);
312 setTopic(props.topic);
313 setShowTopicUrl(false);
314 }}
315 >
316 <TextField
317 margin="dense"
318 label={t("publish_dialog_base_url_label")}
319 placeholder={t("publish_dialog_base_url_placeholder")}
320 value={baseUrl}
321 onChange={(ev) => updateBaseUrl(ev.target.value)}
322 disabled={disabled}
323 type="url"
324 variant="standard"
325 sx={{ flexGrow: 1, marginRight: 1 }}
326 slotProps={{
327 htmlInput: {
328 "aria-label": t("publish_dialog_base_url_label"),
329 },
330 }}
331 />
332 <TextField
333 margin="dense"
334 label={t("publish_dialog_topic_label")}
335 placeholder={t("publish_dialog_topic_placeholder")}
336 value={topic}
337 onChange={(ev) => setTopic(ev.target.value)}
338 disabled={disabled}
339 type="text"
340 variant="standard"
341 autoFocus={!messageFocused}
342 sx={{ flexGrow: 1 }}
343 slotProps={{
344 htmlInput: {
345 "aria-label": t("publish_dialog_topic_label"),
346 },
347 }}
348 />
349 </ClosableRow>
350 )}
351 <TextField
352 margin="dense"
353 label={t("publish_dialog_title_label")}
354 placeholder={t("publish_dialog_title_placeholder")}
355 value={title}
356 onChange={(ev) => setTitle(ev.target.value)}
357 disabled={disabled}
358 type="text"
359 fullWidth
360 variant="standard"
361 slotProps={{
362 htmlInput: {
363 "aria-label": t("publish_dialog_title_label"),
364 },
365 }}
366 />
367 <TextField
368 margin="dense"
369 label={t("publish_dialog_message_label")}
370 placeholder={t("publish_dialog_message_placeholder")}
371 value={message}
372 onChange={(ev) => setMessage(ev.target.value)}
373 disabled={disabled}
374 type="text"
375 variant="standard"
376 rows={5}
377 autoFocus={messageFocused}
378 fullWidth
379 multiline
380 slotProps={{
381 htmlInput: {
382 "aria-label": t("publish_dialog_message_label"),
383 },
384 }}
385 onPaste={handlePaste}
386 />
387 <FormControlLabel
388 label={t("publish_dialog_checkbox_markdown")}
389 sx={{ marginRight: 2 }}
390 control={
391 <Checkbox
392 size="small"
393 checked={markdownEnabled}
394 onChange={(ev) => setMarkdownEnabled(ev.target.checked)}
395 slotProps={{
396 input: {
397 "aria-label": t("publish_dialog_checkbox_markdown"),
398 },
399 }}
400 />
401 }
402 />
403 <div style={{ display: "flex" }}>
404 <Suspense fallback={null}>
405 <EmojiPicker anchorEl={emojiPickerAnchorEl} onEmojiPick={handleEmojiPick} onClose={handleEmojiClose} />
406 </Suspense>
407 <DialogIconButton disabled={disabled} onClick={handleEmojiClick} aria-label={t("publish_dialog_emoji_picker_show")}>
408 <InsertEmoticonIcon />
409 </DialogIconButton>
410 <TextField
411 margin="dense"
412 label={t("publish_dialog_tags_label")}
413 placeholder={t("publish_dialog_tags_placeholder")}
414 value={tags}
415 onChange={(ev) => setTags(ev.target.value)}
416 disabled={disabled}
417 type="text"
418 variant="standard"
419 sx={{ flexGrow: 1, marginRight: 1 }}
420 slotProps={{
421 htmlInput: {
422 "aria-label": t("publish_dialog_tags_label"),
423 },
424 }}
425 />
426 <FormControl variant="standard" margin="dense" sx={{ minWidth: 170, maxWidth: 300, flexGrow: 1 }}>
427 <InputLabel />
428 <Select
429 label={t("publish_dialog_priority_label")}
430 margin="dense"
431 value={priority}
432 onChange={(ev) => setPriority(ev.target.value)}
433 disabled={disabled}
434 inputProps={{
435 "aria-label": t("publish_dialog_priority_label"),
436 }}
437 >
438 {[5, 4, 3, 2, 1].map((p) => (
439 <MenuItem
440 key={`priorityMenuItem${p}`}
441 value={p}
442 aria-label={t("notifications_priority_x", {
443 priority: p,
444 })}
445 >
446 <div style={{ display: "flex", alignItems: "center" }}>
447 <img
448 src={priorities[p].file}
449 style={{ marginRight: "8px" }}
450 alt={t("notifications_priority_x", {
451 priority: p,
452 })}
453 />
454 <div>{priorities[p].label}</div>
455 </div>
456 </MenuItem>
457 ))}
458 </Select>
459 </FormControl>
460 </div>
461 {showClickUrl && (
462 <ClosableRow
463 disabled={disabled}
464 closeLabel={t("publish_dialog_click_reset")}
465 onClose={() => {
466 setClickUrl("");
467 setShowClickUrl(false);
468 }}
469 >
470 <TextField
471 margin="dense"
472 label={t("publish_dialog_click_label")}
473 placeholder={t("publish_dialog_click_placeholder")}
474 value={clickUrl}
475 onChange={(ev) => setClickUrl(ev.target.value)}
476 disabled={disabled}
477 type="url"
478 fullWidth
479 variant="standard"
480 slotProps={{
481 htmlInput: {
482 "aria-label": t("publish_dialog_click_label"),
483 },
484 }}
485 />
486 </ClosableRow>
487 )}
488 {showEmail && (
489 <ClosableRow
490 disabled={disabled}
491 closeLabel={t("publish_dialog_email_reset")}
492 onClose={() => {
493 setEmail("");
494 setShowEmail(false);
495 }}
496 >
497 <TextField
498 margin="dense"
499 label={t("publish_dialog_email_label")}
500 placeholder={t("publish_dialog_email_placeholder")}
501 value={email}
502 onChange={(ev) => setEmail(ev.target.value)}
503 disabled={disabled}
504 type="email"
505 variant="standard"
506 fullWidth
507 slotProps={{
508 htmlInput: {
509 "aria-label": t("publish_dialog_email_label"),
510 },
511 }}
512 />
513 </ClosableRow>
514 )}
515 {showCall && (
516 <ClosableRow
517 disabled={disabled}
518 closeLabel={t("publish_dialog_call_reset")}
519 onClose={() => {
520 setCall("");
521 setShowCall(false);
522 }}
523 >
524 <FormControl fullWidth variant="standard" margin="dense">
525 <InputLabel />
526 <Select
527 label={t("publish_dialog_call_label")}
528 margin="dense"
529 value={call}
530 onChange={(ev) => setCall(ev.target.value)}
531 disabled={disabled}
532 inputProps={{
533 "aria-label": t("publish_dialog_call_label"),
534 }}
535 >
536 {account?.phone_numbers?.map((phoneNumber) => (
537 <MenuItem key={phoneNumber} value={phoneNumber} aria-label={phoneNumber}>
538 {t("publish_dialog_call_item", { number: phoneNumber })}
539 </MenuItem>
540 ))}
541 </Select>
542 </FormControl>
543 </ClosableRow>
544 )}
545 {showAttachUrl && (
546 <ClosableRow
547 disabled={disabled}
548 closeLabel={t("publish_dialog_attach_reset")}
549 onClose={() => {
550 setAttachUrl("");
551 setFilename("");
552 setFilenameEdited(false);
553 setShowAttachUrl(false);
554 }}
555 >
556 <TextField
557 margin="dense"
558 label={t("publish_dialog_attach_label")}
559 placeholder={t("publish_dialog_attach_placeholder")}
560 value={attachUrl}
561 onChange={(ev) => {
562 const url = ev.target.value;
563 setAttachUrl(url);
564 if (!filenameEdited) {
565 try {
566 const u = new URL(url);
567 const parts = u.pathname.split("/");
568 if (parts.length > 0) {
569 setFilename(parts[parts.length - 1]);
570 }
571 } catch (e) {
572 // Do nothing
573 }
574 }
575 }}
576 disabled={disabled}
577 type="url"
578 variant="standard"
579 sx={{ flexGrow: 5, marginRight: 1 }}
580 slotProps={{
581 htmlInput: {
582 "aria-label": t("publish_dialog_attach_label"),
583 },
584 }}
585 />
586 <TextField
587 margin="dense"
588 label={t("publish_dialog_filename_label")}
589 placeholder={t("publish_dialog_filename_placeholder")}
590 value={filename}
591 onChange={(ev) => {
592 setFilename(ev.target.value);
593 setFilenameEdited(true);
594 }}
595 disabled={disabled}
596 type="text"
597 variant="standard"
598 sx={{ flexGrow: 1 }}
599 slotProps={{
600 htmlInput: {
601 "aria-label": t("publish_dialog_filename_label"),
602 },
603 }}
604 />
605 </ClosableRow>
606 )}
607 <input type="file" ref={attachFileInput} onChange={handleAttachFileChanged} style={{ display: "none" }} aria-hidden />
608 {showAttachFile && (
609 <AttachmentBox
610 file={attachFile}
611 filename={filename}
612 disabled={disabled}
613 error={attachFileError}
614 onChangeFilename={(f) => setFilename(f)}
615 onClose={() => {
616 setAttachFile(null);
617 setAttachFileError("");
618 setFilename("");
619 }}
620 />
621 )}
622 {showDelay && (
623 <ClosableRow
624 disabled={disabled}
625 closeLabel={t("publish_dialog_delay_reset")}
626 onClose={() => {
627 setDelay("");
628 setShowDelay(false);
629 }}
630 >
631 <TextField
632 margin="dense"
633 label={t("publish_dialog_delay_label")}
634 placeholder={t("publish_dialog_delay_placeholder", {
635 unixTimestamp: "1649029748",
636 relativeTime: "30m",
637 naturalLanguage: "tomorrow, 9am",
638 })}
639 value={delay}
640 onChange={(ev) => setDelay(ev.target.value)}
641 disabled={disabled}
642 type="text"
643 variant="standard"
644 fullWidth
645 slotProps={{
646 htmlInput: {
647 "aria-label": t("publish_dialog_delay_label"),
648 },
649 }}
650 />
651 </ClosableRow>
652 )}
653 <Typography variant="body1" sx={{ marginTop: 2, marginBottom: 1 }}>
654 {t("publish_dialog_other_features")}
655 </Typography>
656 <div>
657 {!showClickUrl && (
658 <Chip
659 clickable
660 disabled={disabled}
661 label={t("publish_dialog_chip_click_label")}
662 aria-label={t("publish_dialog_chip_click_label")}
663 onClick={() => setShowClickUrl(true)}
664 sx={{ marginRight: 1, marginBottom: 1 }}
665 />
666 )}
667 {!showEmail && (
668 <Chip
669 clickable
670 disabled={disabled}
671 label={t("publish_dialog_chip_email_label")}
672 aria-label={t("publish_dialog_chip_email_label")}
673 onClick={() => setShowEmail(true)}
674 sx={{ marginRight: 1, marginBottom: 1 }}
675 />
676 )}
677 {account?.phone_numbers?.length > 0 && !showCall && (
678 <Chip
679 clickable
680 disabled={disabled}
681 label={t("publish_dialog_chip_call_label")}
682 aria-label={t("publish_dialog_chip_call_label")}
683 onClick={() => {
684 setShowCall(true);
685 setCall(account.phone_numbers[0]);
686 }}
687 sx={{ marginRight: 1, marginBottom: 1 }}
688 />
689 )}
690 {!showAttachUrl && !showAttachFile && (
691 <Chip
692 clickable
693 disabled={disabled}
694 label={t("publish_dialog_chip_attach_url_label")}
695 aria-label={t("publish_dialog_chip_attach_url_label")}
696 onClick={() => setShowAttachUrl(true)}
697 sx={{ marginRight: 1, marginBottom: 1 }}
698 />
699 )}
700 {!showAttachFile && !showAttachUrl && (
701 <Chip
702 clickable
703 disabled={disabled}
704 label={t("publish_dialog_chip_attach_file_label")}
705 aria-label={t("publish_dialog_chip_attach_file_label")}
706 onClick={() => handleAttachFileClick()}
707 sx={{ marginRight: 1, marginBottom: 1 }}
708 />
709 )}
710 {!showDelay && (
711 <Chip
712 clickable
713 disabled={disabled}
714 label={t("publish_dialog_chip_delay_label")}
715 aria-label={t("publish_dialog_chip_delay_label")}
716 onClick={() => setShowDelay(true)}
717 sx={{ marginRight: 1, marginBottom: 1 }}
718 />
719 )}
720 {!showTopicUrl && (
721 <Chip
722 clickable
723 disabled={disabled}
724 label={t("publish_dialog_chip_topic_label")}
725 aria-label={t("publish_dialog_chip_topic_label")}
726 onClick={() => setShowTopicUrl(true)}
727 sx={{ marginRight: 1, marginBottom: 1 }}
728 />
729 )}
730 {account && !account?.phone_numbers && (
731 <Tooltip title={t("publish_dialog_chip_call_no_verified_numbers_tooltip")}>
732 <span>
733 <Chip
734 clickable
735 disabled
736 label={t("publish_dialog_chip_call_label")}
737 aria-label={t("publish_dialog_chip_call_label")}
738 sx={{ marginRight: 1, marginBottom: 1 }}
739 />
740 </span>
741 </Tooltip>
742 )}
743 </div>
744 <Typography variant="body1" sx={{ marginTop: 1, marginBottom: 1 }}>
745 <Trans
746 i18nKey="publish_dialog_details_examples_description"
747 components={{
748 docsLink: <Link href="https://ntfy.sh/docs" target="_blank" rel="noopener" />,
749 }}
750 />
751 </Typography>
752 </DialogContent>
753 <DialogFooter status={status}>
754 {activeRequest && <Button onClick={() => activeRequest.abort()}>{t("publish_dialog_button_cancel_sending")}</Button>}
755 {!activeRequest && (
756 <>
757 <FormControlLabel
758 label={t("publish_dialog_checkbox_publish_another")}
759 sx={{ marginRight: 2 }}
760 control={
761 <Checkbox
762 size="small"
763 checked={publishAnother}
764 onChange={(ev) => setPublishAnother(ev.target.checked)}
765 slotProps={{
766 input: {
767 "aria-label": t("publish_dialog_checkbox_publish_another"),
768 },
769 }}
770 />
771 }
772 />
773 <Button onClick={props.onClose}>{t("publish_dialog_button_cancel")}</Button>
774 <Button onClick={handleSubmit} disabled={!sendButtonEnabled}>
775 {t("publish_dialog_button_send")}
776 </Button>
777 </>
778 )}
779 </DialogFooter>
780 </Dialog>
781 </>
782 );
783 };
784
785 const Row = (props) => (
786 <div style={{ display: "flex" }} role="row">
787 {props.children}
788 </div>
789 );
790
791 const ClosableRow = (props) => {
792 const closable = props.closable !== undefined ? props.closable : true;
793 return (
794 <Row>
795 {props.children}
796 {closable && (
797 <DialogIconButton disabled={props.disabled} onClick={props.onClose} sx={{ marginLeft: "6px" }} aria-label={props.closeLabel}>
798 <Close />
799 </DialogIconButton>
800 )}
801 </Row>
802 );
803 };
804
805 const DialogIconButton = (props) => {
806 const sx = props.sx || {};
807 return (
808 <IconButton
809 color="inherit"
810 size="large"
811 edge="start"
812 sx={{ height: "45px", marginTop: "17px", ...sx }}
813 onClick={props.onClick}
814 disabled={props.disabled}
815 aria-label={props["aria-label"]}
816 >
817 {props.children}
818 </IconButton>
819 );
820 };
821
822 const AttachmentBox = (props) => {
823 const { t } = useTranslation();
824 const { file } = props;
825 return (
826 <>
827 <Typography variant="body1" sx={{ marginTop: 2 }}>
828 {t("publish_dialog_attached_file_title")}
829 </Typography>
830 <Box
831 sx={{
832 display: "flex",
833 alignItems: "center",
834 padding: 0.5,
835 borderRadius: "4px",
836 }}
837 >
838 <AttachmentIcon type={file.type} href={imageRegex.test(file.name) ? URL.createObjectURL(file) : undefined} />
839 <Box sx={{ marginLeft: 1, textAlign: "left" }}>
840 <ExpandingTextField
841 minWidth={140}
842 variant="body2"
843 placeholder={t("publish_dialog_attached_file_filename_placeholder")}
844 value={props.filename}
845 onChange={(ev) => props.onChangeFilename(ev.target.value)}
846 disabled={props.disabled}
847 />
848 <br />
849 <Typography variant="body2" sx={{ color: "text.primary" }}>
850 {formatBytes(file.size)}
851 {props.error && (
852 <Typography component="span" sx={{ color: "error.main" }} aria-live="polite">
853 {" "}
854 ({props.error})
855 </Typography>
856 )}
857 </Typography>
858 </Box>
859 <DialogIconButton
860 disabled={props.disabled}
861 onClick={props.onClose}
862 sx={{ marginLeft: "6px" }}
863 aria-label={t("publish_dialog_attached_file_remove")}
864 >
865 <Close />
866 </DialogIconButton>
867 </Box>
868 </>
869 );
870 };
871
872 const ExpandingTextField = (props) => {
873 const theme = useTheme();
874 const invisibleFieldRef = useRef();
875 const [textWidth, setTextWidth] = useState(props.minWidth);
876 const determineTextWidth = () => {
877 const boundingRect = invisibleFieldRef?.current?.getBoundingClientRect();
878 if (!boundingRect) {
879 return props.minWidth;
880 }
881 return boundingRect.width >= props.minWidth ? Math.round(boundingRect.width) : props.minWidth;
882 };
883 useEffect(() => {
884 setTextWidth(determineTextWidth() + 5);
885 }, [props.value]);
886 return (
887 <>
888 <Typography ref={invisibleFieldRef} component="span" variant={props.variant} aria-hidden sx={{ position: "absolute", left: "-200%" }}>
889 {props.value}
890 </Typography>
891 <TextField
892 margin="dense"
893 placeholder={props.placeholder}
894 value={props.value}
895 onChange={props.onChange}
896 type="text"
897 variant="standard"
898 sx={{ width: `${textWidth}px`, borderBottom: "none" }}
899 slotProps={{
900 input: {
901 style: { fontSize: theme.typography[props.variant].fontSize },
902 },
903 htmlInput: {
904 style: { paddingBottom: 0, paddingTop: 0 },
905 "aria-label": props.placeholder,
906 },
907 }}
908 disabled={props.disabled}
909 />
910 </>
911 );
912 };
913
914 const DropArea = (props) => {
915 const allowDrag = (ev) => {
916 // This is where we could disallow certain files to be dragged in.
917 // For now we allow all files.
918
919 // eslint-disable-next-line no-param-reassign
920 ev.dataTransfer.dropEffect = "copy";
921 ev.preventDefault();
922 };
923
924 return (
925 <Box
926 sx={{
927 position: "absolute",
928 left: 0,
929 top: 0,
930 right: 0,
931 bottom: 0,
932 zIndex: 10002,
933 }}
934 onDrop={props.onDrop}
935 onDragEnter={allowDrag}
936 onDragOver={allowDrag}
937 onDragLeave={props.onDragLeave}
938 />
939 );
940 };
941
942 const DropBox = () => {
943 const { t } = useTranslation();
944 return (
945 <Box
946 sx={{
947 position: "absolute",
948 left: 0,
949 top: 0,
950 right: 0,
951 bottom: 0,
952 zIndex: 10000,
953 backgroundColor: "#ffffffbb",
954 }}
955 >
956 <Box
957 sx={{
958 position: "absolute",
959 border: "3px dashed #ccc",
960 borderRadius: "5px",
961 left: "40px",
962 top: "40px",
963 right: "40px",
964 bottom: "40px",
965 zIndex: 10001,
966 display: "flex",
967 justifyContent: "center",
968 alignItems: "center",
969 }}
970 >
971 <Typography variant="h5">{t("publish_dialog_drop_file_here")}</Typography>
972 </Box>
973 </Box>
974 );
975 };
976
977 PublishDialog.OPEN_MODE_DEFAULT = "default";
978 PublishDialog.OPEN_MODE_DRAG = "drag";
979
980 export default PublishDialog;