import { useEffect, useRef, useState } from "react"; import { useTranslate } from "@/utils/i18n"; import { marked } from "@/labs/marked"; import { useUserStore } from "@/store/module"; import Icon from "./Icon"; import "@/less/memo-content.less"; const MAX_EXPAND_HEIGHT = 384; interface Props { content: string; className?: string; showFull?: boolean; onMemoContentClick?: (e: React.MouseEvent) => void; onMemoContentDoubleClick?: (e: React.MouseEvent) => void; } type ExpandButtonStatus = -1 | 0 | 1; interface State { expandButtonStatus: ExpandButtonStatus; } const MemoContent: React.FC = (props: Props) => { const { className, content, showFull, onMemoContentClick, onMemoContentDoubleClick } = props; const t = useTranslate(); const userStore = useUserStore(); const [state, setState] = useState({ expandButtonStatus: -1, }); const memoContentContainerRef = useRef(null); const isVisitorMode = userStore.isVisitorMode(); const autoCollapse: boolean = !showFull && (isVisitorMode ? true : (userStore.state.user as User).localSetting.enableAutoCollapse); useEffect(() => { if (!autoCollapse) { return; } if (memoContentContainerRef.current) { const height = memoContentContainerRef.current.scrollHeight; if (height > MAX_EXPAND_HEIGHT) { setState({ expandButtonStatus: 0, }); } } }, [autoCollapse]); const handleMemoContentClick = async (e: React.MouseEvent) => { if (onMemoContentClick) { onMemoContentClick(e); } }; const handleMemoContentDoubleClick = async (e: React.MouseEvent) => { if (onMemoContentDoubleClick) { onMemoContentDoubleClick(e); } }; const handleExpandBtnClick = () => { const expandButtonStatus = Boolean(!state.expandButtonStatus); setState({ expandButtonStatus: Number(expandButtonStatus) as ExpandButtonStatus, }); }; return (
{marked(content)}
{autoCollapse && state.expandButtonStatus !== -1 && (
{state.expandButtonStatus === 0 ? t("common.expand") : t("common.fold")}
)}
); }; export default MemoContent;