/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { API, showError } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import MarkdownRenderer from '../markdown/MarkdownRenderer';
import {
Shield,
ScrollText,
ExternalLink,
ChevronUp,
ArrowLeft,
BookOpen,
Scale,
Printer,
} from 'lucide-react';
import { useNavigate, useLocation } from 'react-router-dom';
// 检查是否为 URL
const isUrl = (content) => {
try {
new URL(content.trim());
return true;
} catch {
return false;
}
};
// 检查是否为 HTML 内容
const isHtmlContent = (content) => {
if (!content || typeof content !== 'string') return false;
const htmlTagRegex = /<\/?[a-z][\s\S]*>/i;
return htmlTagRegex.test(content);
};
/**
* 抽取 HTML body 内容与 style 标签。
* 注意:此函数 NOT 是真正的 XSS 消毒,仅做结构整理;
* 信任来源:内容由后台管理员设置(需登录管理后台),如需在不受信场景使用应替换为 DOMPurify。
*/
const extractHtml = (html) => {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
const styles = Array.from(tempDiv.querySelectorAll('style'))
.map((style) => style.innerHTML)
.join('\n');
// 主动剔除 script 标签,降低风险
tempDiv.querySelectorAll('script').forEach((el) => el.remove());
const bodyContent = tempDiv.querySelector('body');
const content = bodyContent ? bodyContent.innerHTML : tempDiv.innerHTML;
return { content, styles };
};
// 根据 type / 标题获取对应的图标
const getIcon = ({ type, title }) => {
if (type === 'privacy') return Shield;
if (type === 'agreement') return Scale;
// 兜底(i18n 友好度有限):按标题关键字推断
if (title?.includes('隐私') || title?.toLowerCase().includes('privacy')) {
return Shield;
}
if (
title?.includes('服务') ||
title?.includes('用户') ||
title?.toLowerCase().includes('terms') ||
title?.toLowerCase().includes('service')
) {
return Scale;
}
return ScrollText;
};
/**
* 智能返回:
* 1) 有真实历史(length>1)→ navigate(-1)
* 2) 尝试 window.close()(脚本打开的标签页会成功,否则被忽略)
* 3) 兜底跳首页
*
* 说明:因 LoginForm 的协议链接使用了 rel="noopener noreferrer",
* 新标签里的 window.opener 为 null、document.referrer 为空,无法用 referrer 判同源。
*/
const useSmartBack = () => {
const navigate = useNavigate();
return useCallback(() => {
if (window.history.length > 1) {
navigate(-1);
return;
}
try {
window.close();
} catch (e) {
// 浏览器拒绝则继续走兜底
}
// 短延时给 close() 一个机会
setTimeout(() => {
if (!window.closed) navigate('/');
}, 50);
}, [navigate]);
};
/**
* 通用文档渲染组件
* @param {string} apiEndpoint API 接口地址
* @param {string} title 文档标题
* @param {string} cacheKey 本地存储缓存键
* @param {string} emptyMessage 空内容时的提示消息
* @param {'page'|'embedded'} mode page=独立页面(默认),embedded=嵌入式(无背景/头部)
* @param {'agreement'|'privacy'} [docType] 文档类型(用于图标识别,比标题更可靠)
* @param {function} [onProgressChange] 进度变化回调(嵌入模式用于宿主显示进度条)
*/
const DocumentRenderer = ({
apiEndpoint,
title,
cacheKey,
emptyMessage,
mode = 'page',
docType,
onProgressChange,
}) => {
const { t } = useTranslation();
const smartBack = useSmartBack();
const location = useLocation();
const [content, setContent] = useState('');
const [loading, setLoading] = useState(true);
const [htmlStyles, setHtmlStyles] = useState('');
const [processedHtmlContent, setProcessedHtmlContent] = useState('');
const [showBackToTop, setShowBackToTop] = useState(false);
const [readProgress, setReadProgress] = useState(0);
const scrollContainerRef = useRef(null);
const rootRef = useRef(null);
const isMountedRef = useRef(true);
const abortControllerRef = useRef(null);
const isEmbedded = mode === 'embedded';
const IconComponent = getIcon({ type: docType, title });
const processContent = useCallback((rawContent) => {
if (isHtmlContent(rawContent)) {
const { content: htmlContent, styles } = extractHtml(rawContent);
setProcessedHtmlContent(htmlContent);
setHtmlStyles(styles);
} else {
setProcessedHtmlContent('');
setHtmlStyles('');
}
}, []);
// 加载内容(含取消保护,避免在卸载后 setState)
useEffect(() => {
isMountedRef.current = true;
const controller = new AbortController();
abortControllerRef.current = controller;
const load = async () => {
const cachedContent = localStorage.getItem(cacheKey) || '';
if (cachedContent) {
setContent(cachedContent);
processContent(cachedContent);
setLoading(false);
}
try {
const res = await API.get(apiEndpoint, { signal: controller.signal });
if (!isMountedRef.current) return;
const { success, message, data } = res.data;
if (success && data) {
setContent(data);
processContent(data);
localStorage.setItem(cacheKey, data);
} else if (!cachedContent) {
showError(message || emptyMessage);
setContent('');
}
} catch (error) {
if (controller.signal.aborted) return; // 用户离开页面
if (!isMountedRef.current) return;
const cached = localStorage.getItem(cacheKey) || '';
if (!cached) {
showError(emptyMessage);
setContent('');
}
} finally {
if (isMountedRef.current) setLoading(false);
}
};
load();
return () => {
isMountedRef.current = false;
controller.abort();
};
}, [apiEndpoint, cacheKey, emptyMessage, processContent]);
// 滚动监听 + 阅读进度计算(page 模式监听 window,embedded 模式监听容器)
const handleScroll = useCallback(
(e) => {
let scrollTop;
let scrollHeight;
let clientHeight;
if (
e?.target &&
e.target !== window &&
e.target.scrollHeight !== undefined
) {
scrollTop = e.target.scrollTop;
scrollHeight = e.target.scrollHeight;
clientHeight = e.target.clientHeight;
} else {
scrollTop = window.scrollY;
scrollHeight = document.documentElement.scrollHeight;
clientHeight = window.innerHeight;
}
setShowBackToTop(scrollTop > 300);
const denom = scrollHeight - clientHeight;
const progress =
denom > 0 ? Math.min(100, Math.max(0, (scrollTop / denom) * 100)) : 0;
setReadProgress(progress);
if (isEmbedded && onProgressChange) {
onProgressChange(progress);
}
},
[isEmbedded, onProgressChange],
);
const scrollToTop = () => {
const target =
(isEmbedded && scrollContainerRef.current) || pageScrollElRef.current;
if (target) {
target.scrollTo({ top: 0, behavior: 'smooth' });
} else {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
};
// page 模式的实际滚动容器不是 window:PageLayout 外层是 height:100vh + overflow:hidden,
// 真正滚动的是内层 Semi Layout(一个普通 div)。元素的 scroll 事件不冒泡到 window,
// 所以原来只监听 window 时 showBackToTop 永远为 false、阅读进度条恒为 0。
// 这里向上找到真正可滚动的祖先来监听;找不到再回退 window(独立页/未来结构变化)。
const pageScrollElRef = useRef(null);
useEffect(() => {
if (isEmbedded) return;
const findScrollParent = (node) => {
let el = node?.parentElement;
while (el && el !== document.body) {
const overflowY = window.getComputedStyle(el).overflowY;
if (
(overflowY === 'auto' || overflowY === 'scroll') &&
el.scrollHeight > el.clientHeight
) {
return el;
}
el = el.parentElement;
}
return null;
};
const target = findScrollParent(rootRef.current) || window;
pageScrollElRef.current = target === window ? null : target;
const onScroll = (e) => {
if (target === window) {
handleScroll();
return;
}
handleScroll({ target });
};
target.addEventListener('scroll', onScroll, { passive: true });
return () => target.removeEventListener('scroll', onScroll);
}, [isEmbedded, handleScroll]);
// 处理 HTML 样式注入
useEffect(() => {
const styleId = `document-renderer-styles-${cacheKey}-${mode}`;
if (htmlStyles) {
let styleEl = document.getElementById(styleId);
if (!styleEl) {
styleEl = document.createElement('style');
styleEl.id = styleId;
styleEl.type = 'text/css';
document.head.appendChild(styleEl);
}
styleEl.innerHTML = htmlStyles;
} else {
const el = document.getElementById(styleId);
if (el) el.remove();
}
return () => {
const el = document.getElementById(styleId);
if (el) el.remove();
};
}, [htmlStyles, cacheKey, mode]);
// URL hash 自动滚动到对应 h2/h3 anchor(仅 page 模式 + 内容加载完成后)
useEffect(() => {
if (isEmbedded || loading || !content || !location.hash) return;
const id = decodeURIComponent(location.hash.slice(1));
if (!id) return;
const t = setTimeout(() => {
const el = document.getElementById(id);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 200);
return () => clearTimeout(t);
}, [isEmbedded, loading, content, location.hash]);
// 为 h2/h3 注入 id + 锚点链接(page 模式 + Markdown 已渲染 DOM 后)
const contentRef = useRef(null);
useEffect(() => {
if (isEmbedded || loading || !contentRef.current) return;
const root = contentRef.current;
const slugify = (text) =>
String(text || '')
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\-一-龥]+/g, '')
.slice(0, 80);
const seen = new Map();
const headings = root.querySelectorAll('h2, h3');
headings.forEach((h) => {
const existing = h.querySelector('.doc-anchor');
if (existing) {
// 已处理;切换语言时只刷新读屏文案
existing.setAttribute('aria-label', t('复制段落链接'));
return;
}
let base = h.id || slugify(h.textContent);
if (!base) return;
let id = base;
const n = seen.get(base) || 0;
if (n > 0) id = `${base}-${n}`;
seen.set(base, n + 1);
h.id = id;
const a = document.createElement('a');
a.href = `#${id}`;
a.className = 'doc-anchor';
a.setAttribute('aria-label', t('复制段落链接'));
a.textContent = '#';
a.addEventListener('click', (e) => {
e.preventDefault();
const url = `${window.location.origin}${window.location.pathname}#${id}`;
if (navigator.clipboard) {
navigator.clipboard.writeText(url).catch(() => {});
}
history.replaceState(null, '', `#${id}`);
});
h.prepend(a);
});
}, [isEmbedded, loading, content, processedHtmlContent, t]);
// 文档内容样式(prose)—— 同时兼顾浅色与深色
const proseClass = `prose prose-base dark:prose-invert max-w-none
prose-headings:font-semibold prose-headings:text-gray-900 dark:prose-headings:text-gray-50 prose-headings:scroll-mt-24 prose-headings:tracking-tight
prose-h1:text-2xl prose-h1:mb-4 prose-h1:mt-0
prose-h2:text-lg prose-h2:mt-8 prose-h2:mb-3 prose-h2:pb-2 prose-h2:border-b prose-h2:border-gray-200 dark:prose-h2:border-gray-800
prose-h3:text-base prose-h3:mt-5 prose-h3:mb-2
prose-p:text-gray-700 dark:prose-p:text-gray-300 prose-p:leading-[1.75] prose-p:my-3
prose-a:text-brand-deep dark:prose-a:text-brand-from prose-a:no-underline prose-a:font-medium hover:prose-a:underline hover:prose-a:underline-offset-4
prose-strong:text-gray-900 dark:prose-strong:text-white prose-strong:font-semibold
prose-code:bg-brand/10 dark:prose-code:bg-brand/15 prose-code:text-brand-deep dark:prose-code:text-brand-from prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-[0.875em] prose-code:font-mono prose-code:before:content-none prose-code:after:content-none prose-code:border prose-code:border-brand/15 dark:prose-code:border-brand/20
prose-pre:bg-gray-50 dark:prose-pre:bg-gray-900/60 prose-pre:border prose-pre:border-gray-200 dark:prose-pre:border-gray-800 prose-pre:rounded-lg
prose-ul:my-3 prose-ol:my-3 prose-ul:space-y-1 prose-ol:space-y-1
prose-li:text-gray-700 dark:prose-li:text-gray-300 prose-li:my-0.5 prose-li:marker:text-brand
prose-blockquote:border-l-4 prose-blockquote:border-brand prose-blockquote:bg-brand/5 dark:prose-blockquote:bg-brand/10 prose-blockquote:py-2 prose-blockquote:px-4 prose-blockquote:rounded-r prose-blockquote:not-italic prose-blockquote:text-gray-700 dark:prose-blockquote:text-gray-300
prose-hr:border-gray-200 dark:prose-hr:border-gray-800 prose-hr:my-6
prose-table:rounded-lg prose-table:overflow-hidden
prose-th:bg-gray-50 dark:prose-th:bg-gray-800/50 prose-th:text-gray-900 dark:prose-th:text-gray-100
prose-td:border-gray-200 dark:prose-td:border-gray-800
prose-img:rounded-lg prose-img:border prose-img:border-gray-200 dark:prose-img:border-gray-800`;
// ============ Skeleton(短暂加载也更稳) ============
const renderLoading = () => (
);
// ============ 空状态 ============
const renderEmpty = () => (
{t('内容正在准备中')}
{t('管理员尚未设置{{title}}内容', { title })}
);
// ============ URL 卡片 ============
const renderUrlCard = () => (
);
// ============ HTML / Markdown 主体 ============
const renderDocumentBody = () => {
if (isHtmlContent(content)) {
return (
);
}
return (
);
};
// ============ 主体决策 ============
const renderBody = () => {
if (loading) return renderLoading();
if (!content || content.trim() === '') return renderEmpty();
if (isUrl(content)) return renderUrlCard();
return renderDocumentBody();
};
// ============ 嵌入模式 ============
if (isEmbedded) {
return (
{renderBody()}
);
}
// ============ 页面模式 ============
const hasRealContent =
!loading && content && content.trim() !== '' && !isUrl(content);
return (
{/* 阅读进度条 */}
{/* 顶部环境光 */}
{/* Sticky Header */}
{/* 打印按钮 */}
{/* 文档主体 */}
{/* 文档标题区 */}
{hasRealContent && (
{title}
{t('最后更新')}:{new Date().toLocaleDateString()}
)}
{/* 文档卡片 */}
{renderBody()}
{/* 底部返回入口 */}
{!loading && (
)}
{/* 返回顶部 FAB */}
);
};
export default DocumentRenderer;