import * as React from "react"; import classnames from "classnames"; import { useTranslation } from "react-i18next"; import { getHttpTimelineClient, HttpTimelinePostInfo, } from "~src/http/timeline"; import TimelinePostBuilder from "~src/services/TimelinePostBuilder"; import FlatButton from "~src/components/button/FlatButton"; import TabPages from "~src/components/tab/TabPages"; import ConfirmDialog from "~src/components/dialog/ConfirmDialog"; import Spinner from "~src/components/Spinner"; import IconButton from "~src/components/button/IconButton"; import "./MarkdownPostEdit.css"; import { DialogProvider, useDialog } from "~src/components/dialog"; export interface MarkdownPostEditProps { owner: string; timeline: string; onPosted: (post: HttpTimelinePostInfo) => void; onPostError: () => void; onClose: () => void; className?: string; style?: React.CSSProperties; } const MarkdownPostEdit: React.FC = ({ owner: ownerUsername, timeline: timelineName, onPosted, onClose, onPostError, className, style, }) => { const { t } = useTranslation(); const [canLeave, setCanLeave] = React.useState(true); const [process, setProcess] = React.useState(false); const { controller, switchDialog } = useDialog({ "leave-confirm": ( ), }); const [text, _setText] = React.useState(""); const [images, _setImages] = React.useState<{ file: File; url: string }[]>( [], ); const [previewHtml, _setPreviewHtml] = React.useState(""); const _builder = React.useRef(null); const getBuilder = (): TimelinePostBuilder => { if (_builder.current == null) { const builder = new TimelinePostBuilder(() => { setCanLeave(builder.isEmpty); _setText(builder.text); _setImages(builder.images); _setPreviewHtml(builder.renderHtml()); }); _builder.current = builder; } return _builder.current; }; const canSend = text.length > 0; React.useEffect(() => { return () => { getBuilder().dispose(); }; }, []); React.useEffect(() => { window.onbeforeunload = (): unknown => { if (!canLeave) { return t("timeline.confirmLeave"); } }; return () => { window.onbeforeunload = null; }; }, [canLeave, t]); const send = async (): Promise => { setProcess(true); try { const dataList = await getBuilder().build(); const post = await getHttpTimelineClient().postPost( ownerUsername, timelineName, { dataList, }, ); onPosted(post); onClose(); } catch (e) { setProcess(false); onPostError(); } }; return ( <> ) : (
{ if (canLeave) { onClose(); } else { switchDialog("leave-confirm"); } }} /> {canSend && ( void send()} /> )}
) } pages={[ { name: "text", text: "edit", page: (