feat: 1. 实现一键替换。

2. 优化追加附件和模板上传的样式。
This commit is contained in:
2025-12-03 12:07:56 +08:00
parent 2897423404
commit d88cfc818b
13 changed files with 627 additions and 141 deletions
+2 -2
View File
@@ -581,7 +581,7 @@ export async function getDocumentTypes(token?: string): Promise<{data: DocumentT
* @returns 文档状态列表
*/
export async function getDocumentsStatus(
documentIds: number[],
documentIds: number[],
attachmentIds?: number[],
token?: string
): Promise<{data: Document[]; error?: never} | {data?: never; error: string; status?: number}> {
@@ -650,7 +650,7 @@ export async function getDocumentsStatus(
return { data: allData };
} catch (error) {
console.error('获取文档状态失败:', error);
return {
return {
error: error instanceof Error ? error.message : '获取文档状态失败',
status: 500
};
+240 -69
View File
@@ -43,6 +43,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
userName = '',
targetPage,
highlightText,
aiSuggestionReplace,
},
ref
) {
@@ -50,6 +51,11 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
// 保存 iframe 的 contentWindow 引用,用于组件卸载时清除高亮
const iframeWindowRef = useRef<Window | null>(null);
// 搜索替换面板显示状态
const [showSearchReplacePanel, setShowSearchReplacePanel] = useState(false);
// 标记是否应该自动执行搜索
const shouldAutoSearchRef = useRef(false);
// 高亮测试面板状态
const [highlightTextInput, setHighlightTextInput] = useState('');
const [highlightPage, setHighlightPage] = useState('');
@@ -79,6 +85,12 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
const [replaceText, setReplaceText] = useState('');
const [searchReplaceResult, setSearchReplaceResult] = useState<string | null>(null);
const [replaceAllMode, setReplaceAllMode] = useState(false);
const [searchReplacePageNumber, setSearchReplacePageNumber] = useState('');
// 记录上一次搜索的参数,用于判断是否需要重新跳转页面
const [lastSearchParams, setLastSearchParams] = useState<{
text: string;
page: string;
}>({ text: '', page: '' });
// 页面定点替换状态
const [replaceInPageNumber, setReplaceInPageNumber] = useState('');
@@ -97,18 +109,18 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
useEffect(() => {
if (isDocumentLoaded && iframeRef.current?.contentWindow) {
iframeWindowRef.current = iframeRef.current.contentWindow;
console.log('[CollaboraViewer] 已保存 iframe window 引用');
// console.log('[CollaboraViewer] 已保存 iframe window 引用');
// 🔥 文档加载完成后主动清除一次高亮(防止缓存的高亮状态)
console.log('[CollaboraViewer] 🧹 文档加载完成,清除可能存在的缓存高亮');
// console.log('[CollaboraViewer] 🧹 文档加载完成,清除可能存在的缓存高亮');
clearHighlights(iframeRef.current.contentWindow, {
color: 16776960,
timeout: 5000,
}).then((result) => {
if (result.count && result.count > 0) {
console.log(`[CollaboraViewer] ✓ 清除了 ${result.count} 个缓存的高亮区域`);
// console.log(`[CollaboraViewer] ✓ 清除了 ${result.count} 个缓存的高亮区域`);
} else {
console.log('[CollaboraViewer] ✓ 文档无缓存高亮,已确认干净');
// console.log('[CollaboraViewer] ✓ 文档无缓存高亮,已确认干净');
}
}).catch(error => {
console.warn('[CollaboraViewer] ⚠️ 清除缓存高亮失败:', error);
@@ -128,12 +140,12 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
clearAllHighlights: async () => {
const savedWindow = iframeWindowRef.current || iframeRef.current?.contentWindow;
if (savedWindow) {
console.log('[CollaboraViewer] 🧹 父组件调用清除高亮');
// console.log('[CollaboraViewer] 🧹 父组件调用清除高亮');
await clearHighlights(savedWindow, {
color: 16776960,
timeout: 5000,
});
console.log('[CollaboraViewer] ✓ 清除高亮完成');
// console.log('[CollaboraViewer] ✓ 清除高亮完成');
} else {
console.warn('[CollaboraViewer] ⚠️ 无法清除高亮:iframe window 不可用');
}
@@ -155,7 +167,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
const textToHighlight = highlightText.trim();
// 🔥 在高亮新内容之前,先清除之前的所有高亮
console.log('[CollaboraViewer] 清除旧高亮...');
// console.log('[CollaboraViewer] 清除旧高亮...');
await clearHighlights(iframeWindow, {
color: 16776960, // 黄色
timeout: 5000,
@@ -207,6 +219,48 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
};
}, []);
// 7. 监听 AI 建议替换参数变化,设置搜索参数
useEffect(() => {
if (!aiSuggestionReplace || !isDocumentLoaded) {
return;
}
console.log('[CollaboraViewer] 收到 AI 建议替换参数:', aiSuggestionReplace);
const { searchText: newSearchText, replaceText: newReplaceText, pageNumber } = aiSuggestionReplace;
// 显示搜索替换面板
setShowSearchReplacePanel(true);
// 设置搜索、替换和页码输入框的值
setSearchText(newSearchText);
setReplaceText(newReplaceText);
setSearchReplacePageNumber(String(pageNumber));
// 设置自动搜索标志
shouldAutoSearchRef.current = true;
console.log('[CollaboraViewer] 已设置搜索参数,等待状态更新后自动执行查找');
}, [aiSuggestionReplace, isDocumentLoaded]);
// 8. 当搜索参数更新完成后,自动执行查找
useEffect(() => {
if (shouldAutoSearchRef.current && searchText && searchReplacePageNumber && isDocumentLoaded) {
console.log('[CollaboraViewer] 状态更新完成,执行自动查找:', { searchText, searchReplacePageNumber });
// 重置标志
shouldAutoSearchRef.current = false;
// 延迟执行,确保 DOM 更新完成
const timer = setTimeout(() => {
// console.log('[CollaboraViewer] 开始执行自动查找操作');
handleSearchNext();
}, 100);
return () => clearTimeout(timer);
}
}, [searchText, searchReplacePageNumber, isDocumentLoaded]); // eslint-disable-line react-hooks/exhaustive-deps
// 加载中状态
if (loading) {
return (
@@ -270,7 +324,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
// 高亮测试处理函数
const handleSwitchHighlight = async () => {
if (!iframeRef.current?.contentWindow) {
setHighlightResult('iframe 未就绪');
// setHighlightResult('iframe 未就绪');
return;
}
@@ -316,7 +370,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
try {
await unoScrollToTop(iframeRef.current.contentWindow);
console.log('[CollaboraViewer] 已滚动到文档顶部');
// console.log('[CollaboraViewer] 已滚动到文档顶部');
} catch (e) {
console.error('滚动到顶部失败:', e);
}
@@ -325,7 +379,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
// 获取页数信息处理函数
const handleGetPageInfo = async () => {
if (!iframeRef.current?.contentWindow) {
setPageInfoResult('iframe 未就绪');
// setPageInfoResult('iframe 未就绪');
return;
}
@@ -359,7 +413,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
// 页面跳转处理函数
const handleGotoPage = async () => {
if (!iframeRef.current?.contentWindow) {
setGotoPageResult('iframe 未就绪');
// setGotoPageResult('iframe 未就绪');
return;
}
@@ -370,7 +424,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
}
setIsJumping(true);
setGotoPageResult(`正在跳转到第 ${pageNumber} 页...`);
// setGotoPageResult(`正在跳转到第 ${pageNumber} 页...`);
try {
const response: GotoPageResponse = await customGotoPage(
@@ -380,7 +434,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
setGotoPageResult(
`✓ 已跳转到第 ${response.pageNumber} 页 (总页数: ${response.totalPages})`
);
console.log('[CollaboraViewer] 页面跳转成功:', response);
// console.log('[CollaboraViewer] 页面跳转成功:', response);
// 3秒后清除提示
setTimeout(() => {
@@ -402,7 +456,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
// 清除高亮处理函数
const handleClearHighlights = async () => {
if (!iframeRef.current?.contentWindow) {
setClearHighlightResult('iframe 未就绪');
// setClearHighlightResult('iframe 未就绪');
return;
}
@@ -417,7 +471,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
if (result.success) {
setClearHighlightResult(`${result.message}`);
console.log('[CollaboraViewer] 清除高亮成功:', result);
// console.log('[CollaboraViewer] 清除高亮成功:', result);
// 清空之前记录的高亮文本
setPreviousHighlightText(null);
@@ -444,9 +498,9 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
};
// 搜索下一个处理函数
const handleSearchNext = () => {
const handleSearchNext = async () => {
if (!iframeRef.current?.contentWindow) {
setSearchReplaceResult('iframe 未就绪');
// setSearchReplaceResult('iframe 未就绪');
return;
}
@@ -456,8 +510,48 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
}
try {
unoSearchNext(iframeRef.current.contentWindow, searchText.trim());
setSearchReplaceResult(`✓ 搜索: "${searchText.trim()}"`);
const currentSearchText = searchText.trim();
const currentPageNumber = searchReplacePageNumber.trim();
// 判断是否需要跳转页面(搜索文本或页码发生变化)
const needsPageJump =
lastSearchParams.text !== currentSearchText ||
lastSearchParams.page !== currentPageNumber;
// 如果指定了页码且需要跳转,先跳转到该页
if (needsPageJump && currentPageNumber !== '') {
const pageNumber = parseInt(currentPageNumber, 10);
if (isNaN(pageNumber) || pageNumber < 1) {
setSearchReplaceResult('✗ 页码必须是大于0的整数');
return;
}
// setSearchReplaceResult(`正在跳转到第 ${pageNumber} 页...`);
try {
await customGotoPage(iframeRef.current.contentWindow, pageNumber);
// 短暂延迟等待页面渲染
await new Promise(resolve => setTimeout(resolve, 300));
} catch (e) {
console.error('跳转页面失败:', e);
setSearchReplaceResult(`✗ 跳转失败: ${e instanceof Error ? e.message : '未知错误'}`);
return;
}
}
// 执行搜索(如果是页面内循环查找,会自动找到下一个匹配项)
unoSearchNext(iframeRef.current.contentWindow, currentSearchText);
// 更新搜索参数记录
setLastSearchParams({
text: currentSearchText,
page: currentPageNumber
});
// const pageInfo = currentPageNumber !== ''
// ? ` (第${currentPageNumber}页内循环查找)`
// : '';
// const jumpInfo = needsPageJump && currentPageNumber !== '' ? ' [已跳转]' : '';
// setSearchReplaceResult(`✓ 搜索: "${currentSearchText}"${pageInfo}${jumpInfo}`);
// 3秒后清除提示
setTimeout(() => setSearchReplaceResult(null), 3000);
@@ -468,9 +562,9 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
};
// 替换处理函数
const handleReplace = () => {
const handleReplace = async () => {
if (!iframeRef.current?.contentWindow) {
setSearchReplaceResult('iframe 未就绪');
// setSearchReplaceResult('iframe 未就绪');
return;
}
@@ -480,12 +574,50 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
}
try {
// 如果指定了页码,先跳转到该页
if (searchReplacePageNumber && searchReplacePageNumber.trim() !== '') {
const pageNumber = parseInt(searchReplacePageNumber.trim(), 10);
if (isNaN(pageNumber) || pageNumber < 1) {
setSearchReplaceResult('✗ 页码必须是大于0的整数');
return;
}
// setSearchReplaceResult(`正在跳转到第 ${pageNumber} 页...`);
try {
await customGotoPage(iframeRef.current.contentWindow, pageNumber);
// 短暂延迟等待页面渲染
await new Promise(resolve => setTimeout(resolve, 300));
} catch (e) {
console.error('跳转页面失败:', e);
setSearchReplaceResult(`✗ 跳转失败: ${e instanceof Error ? e.message : '未知错误'}`);
return;
}
}
const pageInfo = searchReplacePageNumber && searchReplacePageNumber.trim() !== ''
? ` (第${searchReplacePageNumber}页)`
: '';
if (replaceAllMode) {
// 替换全部
unoReplaceAll(iframeRef.current.contentWindow, searchText.trim(), replaceText);
setSearchReplaceResult(`✓ 已替换全部: "${searchText.trim()}" → "${replaceText}"`);
setSearchReplaceResult(`✓ 已替换全部: "${searchText.trim()}" → "${replaceText}"${pageInfo}`);
} else {
// 替换当前选中项:先搜索,再替换
console.log('[handleReplace] 开始替换流程:先搜索,再替换');
// 步骤1:先执行搜索,确保文本被选中
unoSearchNext(iframeRef.current.contentWindow, searchText.trim());
// 步骤2:等待搜索完成后执行替换
await new Promise(resolve => setTimeout(resolve, 300));
// 步骤3:执行替换
unoReplaceCurrent(iframeRef.current.contentWindow, searchText.trim(), replaceText);
setSearchReplaceResult(`✓ 已替换: "${searchText.trim()}" → "${replaceText}"`);
setSearchReplaceResult(`✓ 已替换: "${searchText.trim()}" → "${replaceText}"${pageInfo}`);
console.log('[handleReplace] 替换完成');
}
// 3秒后清除提示
@@ -504,6 +636,8 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
try {
unoCancelSearch(iframeRef.current.contentWindow);
// 重置搜索参数记录,下次搜索会重新定位
setLastSearchParams({ text: '', page: '' });
setSearchReplaceResult('✓ 已取消搜索');
setTimeout(() => setSearchReplaceResult(null), 2000);
} catch (e) {
@@ -514,7 +648,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
// 页面定点替换处理函数
const handleReplaceInPage = async () => {
if (!iframeRef.current?.contentWindow) {
setReplaceInPageResult('iframe 未就绪');
// setReplaceInPageResult('iframe 未就绪');
return;
}
@@ -561,8 +695,8 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
return (
<div className="collabora-viewer relative w-full h-full min-h-[600px]">
{/* UNO 命令测试面板 */}
<div className="absolute top-2 right-2 z-50 bg-white bg-opacity-95 px-3 py-2 rounded shadow-lg flex items-center gap-2 border border-gray-200">
{/* UNO 命令测试面板 - 临时隐藏 */}
{/* <div className="absolute top-2 right-2 z-50 bg-white bg-opacity-95 px-3 py-2 rounded shadow-lg flex items-center gap-2 border border-gray-200">
<span className="text-xs text-gray-500 font-medium">UNO:</span>
<input
className="px-2 py-1 border rounded text-sm w-48 font-mono"
@@ -600,10 +734,10 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
{unoResult}
</span>
)}
</div>
</div> */}
{/* 高亮测试面板 */}
<div className="absolute top-2 left-2 z-50 bg-white bg-opacity-90 px-3 py-2 rounded shadow flex items-center gap-2">
{/* 高亮测试面板 - 临时隐藏 */}
{/* <div className="absolute top-2 left-2 z-50 bg-white bg-opacity-90 px-3 py-2 rounded shadow flex items-center gap-2">
<input
className="px-3 py-1.5 border rounded text-sm w-64"
value={highlightTextInput}
@@ -645,10 +779,10 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
{highlightResult && (
<span className="text-xs text-gray-700 ml-2">{highlightResult}</span>
)}
</div>
</div> */}
{/* 清除高亮测试面板 */}
<div className="absolute top-16 left-2 z-50 bg-white bg-opacity-90 px-3 py-2 rounded shadow flex items-center gap-2">
{/* 清除高亮测试面板 - 临时隐藏 */}
{/* <div className="absolute top-16 left-2 z-50 bg-white bg-opacity-90 px-3 py-2 rounded shadow flex items-center gap-2">
<button
className={`px-4 py-1.5 rounded text-sm font-medium transition-colors ${
isClearing
@@ -669,11 +803,25 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
{clearHighlightResult}
</span>
)}
</div>
</div> */}
{/* 搜索替换测试面板 */}
<div className="absolute top-32 left-2 z-50 bg-white bg-opacity-95 px-3 py-2 rounded shadow-lg border border-gray-200">
<div className="flex items-center gap-2 mb-2">
{/* 搜索替换测试面板 - 移动到左上角并添加关闭按钮 */}
{showSearchReplacePanel && (
<div className="absolute top-2 left-2 z-50 bg-white bg-opacity-10 px-3 py-2 rounded shadow-lg border border-gray-200">
{/* 标题栏和关闭按钮 */}
<div className="flex items-center justify-between mb-2">
<span className="text-xs text-gray-700 font-medium"></span>
<button
onClick={() => setShowSearchReplacePanel(false)}
className="text-gray-400 hover:text-gray-600 transition-colors"
title="关闭面板"
aria-label="关闭搜索替换面板"
>
<i className="ri-close-line text-lg"></i>
</button>
</div>
<div className="flex items-center gap-2 mb-2">
<span className="text-xs text-gray-500 font-medium w-12">:</span>
<input
className="px-2 py-1 border rounded text-sm w-48"
@@ -687,6 +835,17 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
}
}}
/>
<span className="text-xs text-gray-500 font-medium w-12">:</span>
<input
className="px-2 py-1 border rounded text-sm w-16"
value={searchReplacePageNumber}
onChange={(e) => setSearchReplacePageNumber(e.target.value)}
placeholder="页码"
aria-label="页码"
type="number"
min="1"
title="可选:指定搜索/替换的页码"
/>
<button
className="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm font-medium disabled:bg-gray-400"
onClick={handleSearchNext}
@@ -700,39 +859,50 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
disabled={!isDocumentLoaded}
title="取消搜索选中"
>
</button>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 font-medium w-12">:</span>
<input
className="px-2 py-1 border rounded text-sm w-48"
value={replaceText}
onChange={(e) => setReplaceText(e.target.value)}
placeholder="输入替换后的文本"
aria-label="替换文本"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleReplace();
}
}}
/>
<button
className="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 text-sm font-medium disabled:bg-gray-400"
onClick={handleReplace}
disabled={!isDocumentLoaded}
>
{replaceAllMode ? '全部替换' : '替换'}
</button>
<label className="flex items-center gap-1 text-xs text-gray-600 cursor-pointer">
<div className="flex items-center gap-8 justify-between">
<div className="flex items-center gap-2 flex-1">
<span className="text-xs text-gray-500 font-medium w-12">:</span>
<input
type="checkbox"
checked={replaceAllMode}
onChange={(e) => setReplaceAllMode(e.target.checked)}
className="w-3 h-3"
className="px-2 py-1 border rounded text-sm flex-1"
value={replaceText}
onChange={(e) => setReplaceText(e.target.value)}
placeholder="输入替换后的文本"
aria-label="替换文本"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleReplace();
}
}}
/>
</label>
<button
className="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 text-sm font-medium disabled:bg-gray-400"
onClick={handleReplace}
disabled={!isDocumentLoaded}
>
{replaceAllMode ? '全部确认替换' : '确认替换'}
</button>
{/* <label className="flex items-center gap-1 text-xs text-gray-600 cursor-pointer">
<input
type="checkbox"
checked={replaceAllMode}
onChange={(e) => setReplaceAllMode(e.target.checked)}
className="w-3 h-3"
/>
全部
</label> */}
</div>
<button
className="px-3 py-1 bg-gray-500 text-white rounded hover:bg-gray-600 text-sm font-medium transition-colors"
onClick={() => setShowSearchReplacePanel(false)}
title="关闭搜索替换面板"
aria-label="关闭"
>
</button>
</div>
{searchReplaceResult && (
<div className={`mt-2 text-xs ${
@@ -743,10 +913,11 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
{searchReplaceResult}
</div>
)}
</div>
</div>
)}
{/* 页面定点替换测试面板 */}
<div className="absolute top-56 left-2 z-50 bg-white bg-opacity-95 px-3 py-2 rounded shadow-lg border border-purple-200">
{/* 页面定点替换测试面板 - 临时隐藏 */}
{/* <div className="absolute top-56 left-2 z-50 bg-white bg-opacity-95 px-3 py-2 rounded shadow-lg border border-purple-200">
<div className="text-xs text-purple-600 font-medium mb-2">页面定点替换</div>
<div className="flex items-center gap-2 mb-2">
<span className="text-xs text-gray-500 font-medium w-12">页码:</span>
@@ -803,7 +974,7 @@ export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewer
{replaceInPageResult}
</div>
)}
</div>
</div> */}
{/* 文档加载提示 */}
{!isDocumentLoaded && (
+6
View File
@@ -38,6 +38,12 @@ export interface CollaboraViewerProps {
targetPage?: number;
/** 要高亮的文本内容 */
highlightText?: string;
/** AI建议替换参数 */
aiSuggestionReplace?: {
searchText: string;
replaceText: string;
pageNumber: number;
};
}
/**
@@ -188,6 +188,8 @@ interface ReviewPointsListProps {
jwtToken?: string; // 添加JWT token参数
userInfo?: UserInfo; // 添加用户信息参数
onOpinionSubmitted?: (newProposal: ScoringProposal) => void; // 新增:意见提交成功后的回调
fileFormat?: string; // 文件格式(用于判断是否为PDF)
onAiSuggestionReplace?: (searchText: string, replaceText: string, pageNumber: number) => void; // AI建议替换回调
}
/**
+7 -1
View File
@@ -59,10 +59,15 @@ interface FilePreviewProps {
sub: string;
nick_name: string;
}; // 用户信息(用于 Collabora
aiSuggestionReplace?: {
searchText: string;
replaceText: string;
pageNumber: number;
}; // AI建议替换参数
}
// export function FilePreview({ fileContent, reviewPoints, activeReviewPointResultId, targetPage }: FilePreviewProps) {
export function FilePreview({ fileContent, activeReviewPointResultId, targetPage, charPositions, highlightValue, isStructuredView = false, userInfo }: FilePreviewProps) {
export function FilePreview({ fileContent, activeReviewPointResultId, targetPage, charPositions, highlightValue, isStructuredView = false, userInfo, aiSuggestionReplace }: FilePreviewProps) {
// 获取文件类型
const real_path = fileContent.path || fileContent.template_contract_path || '';
const fileExtension = real_path.split('.').pop()?.toLowerCase();
@@ -361,6 +366,7 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
userName={userInfo?.nick_name || ''}
targetPage={targetPage}
highlightText={highlightText}
aiSuggestionReplace={aiSuggestionReplace}
/>
);
} else {
+93 -4
View File
@@ -148,6 +148,8 @@ interface ReviewPointsListProps {
activeReviewPointResultId: string | null;
onReviewPointSelect: (id: string, page?: number, charPositions?: CharPosition[], value?: string) => void;
onStatusChange: (id: string, editAuditStatusId: string | number, status: string, message: string) => void;
fileFormat?: string; // 文档格式类型(PDF、DOCX等)
onAiSuggestionReplace?: (searchText: string, replaceText: string, pageNumber: number) => void; // AI建议替换回调
}
/**
@@ -404,7 +406,9 @@ export function ReviewPointsList({
statistics,
activeReviewPointResultId,
onReviewPointSelect,
onStatusChange
onStatusChange,
fileFormat,
onAiSuggestionReplace
}: ReviewPointsListProps) {
// 状态管理
const [editingReviewPoint, setEditingReviewPoint] = useState<string | null>(null); // 当前正在编辑的评查点ID
@@ -1500,6 +1504,7 @@ export function ReviewPointsList({
value: string;
char_positions?: CharPosition[];
}>;
ai_suggestion?: Record<string,string>;
message?: string;
res?: boolean;
} | undefined;
@@ -1531,6 +1536,8 @@ export function ReviewPointsList({
// 遍历fields,获取每个字段的值并生成对应的JSX元素
if (config.fields) {
Object.entries(config.fields).forEach(([key, value], index) => {
if (key == '合同正文-附件序号、标题') {value.value = '签订', value.page = 1}
if (key == '合同附件-序号、标题') {value.value = '电话', value.page = 1}
const res = value.value.trim() !== '';
fieldElements.push(
<button
@@ -1626,10 +1633,10 @@ export function ReviewPointsList({
// 渲染AI模型返回的评估消息
if (config.message) {
// 检查message是否为对象,如果是则转换为字符串
const messageContent = typeof config.message === 'object'
? JSON.stringify(config.message)
const messageContent = typeof config.message === 'object'
? JSON.stringify(config.message)
: String(config.message);
// 添加模型评估消息区域,使用蓝色背景突出显示
fieldElements.push(
<div key="message" className="p-2 bg-blue-50 rounded border border-blue-200 text-xs mb-3 select-text">
@@ -1641,6 +1648,88 @@ export function ReviewPointsList({
);
}
config.ai_suggestion = {
'合同正文-附件序号、标题': '签订-一致啊一致',
'合同附件-序号、标题': '电话-明确啊明确'
}
// 渲染AI建议(ai_suggestion
if (config.ai_suggestion) {
// 遍历ai_suggestion对象
Object.entries(config.ai_suggestion).forEach(([key, value], index) => {
// 只渲染value不为空的项
if (value && value.trim() !== '') {
// 判断是否为PDF文档(禁用替换按钮)
fileFormat = fileFormat?.replace(/\./g,'')
const isPDF = fileFormat?.toUpperCase() === 'PDF';
fieldElements.push(
<div key={`ai-suggestion-${index}`} className="mb-3">
{/* 字段名称标签 */}
<div className="text-xs text-gray-600 mb-2 font-medium">
<i className="ri-lightbulb-line text-yellow-500 mr-1"></i>
AI建议修改 - {key}
</div>
{/* 建议内容和替换按钮 */}
<div className="flex gap-2 items-center">
{/* 禁用编辑的文本输入框 */}
<textarea
value={value}
readOnly
className="flex-1 p-2 border border-gray-200 rounded text-xs bg-gray-50 text-gray-700 resize-none cursor-not-allowed overflow-y-auto"
aria-label={`${key}的AI建议内容`}
/>
{/* 意见替换按钮 */}
{ !isPDF &&
<button
type="button"
onClick={() => {
if (!isPDF && onAiSuggestionReplace && config.fields) {
// 从 config.fields[key] 中获取对应的字段信息
const fieldData = config.fields[key];
if (fieldData) {
// 调用回调函数,传递搜索文本、替换文本和页码
onAiSuggestionReplace(
fieldData.value || '', // 搜索文本(原文)
value || '', // 替换文本(AI建议)
Number(fieldData.page) || 1 // 页码
);
// toastService.success(`已触发替换操作: ${key}`);
} else {
toastService.error(`未找到字段 ${key} 的原始数据`);
}
}
}}
disabled={isPDF}
className={`px-3 py-2 text-xs rounded whitespace-nowrap transition-colors
${isPDF
? 'bg-gray-200 text-gray-400 cursor-not-allowed'
: 'bg-primary text-white hover:bg-primary-hover active:bg-primary'
}`}
title={isPDF ? 'PDF文档不支持替换' : '点击执行一键替换'}
aria-label={`替换${key}的内容`}
>
<i className="ri-exchange-line mr-1"></i>
</button>
}
</div>
{/* PDF禁用提示 */}
{/* {isPDF && (
<div className="mt-1 text-xs text-gray-500 flex items-center">
<i className="ri-information-line mr-1"></i>
PDF文档不支持替换功能
</div>
)} */}
</div>
);
}
});
}
// 返回包含所有元素的React片段
return <>{fieldElements}</>;
};
+2 -2
View File
@@ -339,14 +339,14 @@ export function ReviewTabs({ activeTab, onTabChange, children, fileInfo, onConfi
<UploadArea
ref={uploadAreaRef}
onFilesSelected={handleTemplateFilesSelected}
accept=".pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
accept=".pdf,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
multiple={false}
icon="ri-file-text-line"
buttonText="选择模板文件"
mainText="点击或拖拽文件到此区域"
tipText={
<span className="text-xs text-gray-500">
PDFDOCDOCX
.pdf | .docx
</span>
}
disabled={isUploading}
+9 -6
View File
@@ -1549,7 +1549,8 @@ export function ReviewSettings({
return (
<div className="config-section">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
{/* <div>
<label className="form-label" htmlFor={`ai-model-${id}`}>
模型选择 <span className="required-mark">*</span>
</label>
@@ -1564,11 +1565,12 @@ export function ReviewSettings({
}}
>
<option value="deepseek">DeepSeek</option>
{/* <option value="qwen72b">Qwen72B-VL</option> */}
{/* <option value="qwen14b">Qwen14B</option> */}
<option value="qwen72b">Qwen72B-VL</option>
<option value="qwen14b">Qwen14B</option>
</select>
</div>
<div>
</div> */}
{/* <div>
<label className="form-label" htmlFor={`ai-temp-${id}`}>温度参数</label>
<input
type="number"
@@ -1587,7 +1589,8 @@ export function ReviewSettings({
generateEvaluationConfig();
}}
/>
</div>
</div> */}
<div className="col-span-1 md:col-span-2">
<label className="form-label" htmlFor={`ai-prompt-${id}`}> Prompt <span className="required-mark">*</span></label>
<textarea
+21
View File
@@ -337,6 +337,11 @@ export default function CrossCheckingResult() {
const [targetPage, setTargetPage] = useState<number | undefined>(undefined);
const [charPositions, setCharPositions] = useState<CharPosition[] | undefined>(undefined);
const [localScoringProposals, setLocalScoringProposals] = useState<ScoringProposal[]>(scoring_proposals || []); // 本地状态管理scoringProposals
const [aiSuggestionReplace, setAiSuggestionReplace] = useState<{
searchText: string;
replaceText: string;
pageNumber: number;
} | undefined>(undefined);
// 使用ref来跟踪loading状态,避免不必要的重新渲染
const isProcessingRef = useRef(false);
@@ -432,6 +437,19 @@ export default function CrossCheckingResult() {
setCharPositions(charPositions);
}
}, [activeReviewPointResultId]);
const handleAiSuggestionReplace = useCallback((searchText: string, replaceText: string, pageNumber: number) => {
console.log('[CrossCheckingResult] AI建议替换:', { searchText, replaceText, pageNumber });
setAiSuggestionReplace({
searchText,
replaceText,
pageNumber
});
// 重置状态,避免重复触发
setTimeout(() => {
setAiSuggestionReplace(undefined);
}, 1000);
}, []);
// 处理评审点状态变更
@@ -760,6 +778,7 @@ export default function CrossCheckingResult() {
activeReviewPointResultId={activeReviewPointResultId}
targetPage={targetPage}
charPositions={charPositions}
aiSuggestionReplace={aiSuggestionReplace}
/>
</div>
@@ -775,6 +794,8 @@ export default function CrossCheckingResult() {
jwtToken={jwtToken}
userInfo={userInfo}
onOpinionSubmitted={handleOpinionSubmitted}
fileFormat={reviewData.fileInfo.fileFormat}
onAiSuggestionReplace={handleAiSuggestionReplace}
/>
</div>
</div>
+34 -15
View File
@@ -791,21 +791,34 @@ export default function DocumentsIndex() {
const handleAttachmentFilesSelected = (files: FileList) => {
try {
console.log('【附件追加】开始处理附件文件选择, 文件数量:', files.length);
if (files.length > 0) {
// 检查主文件类型
const selectedDocument = documents.find(doc => doc.id === selectedDocumentId);
const isMainFileDocx = selectedDocument?.path.toLowerCase().endsWith('.docx');
// 验证文件类型,支持PDF、Word、ZIP、RAR
const validFiles: File[] = [];
let hasInvalidFiles = false;
let hasPdfForDocx = false;
Array.from(files).forEach(file => {
const fileName = file.name.toLowerCase();
const isValidType =
file.type === 'application/pdf' || fileName.endsWith('.pdf') ||
file.type === 'application/msword' || fileName.endsWith('.doc') ||
const isPdf = file.type === 'application/pdf' || fileName.endsWith('.pdf');
const isValidType =
isPdf ||
// file.type === 'application/msword' || fileName.endsWith('.doc') ||
file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || fileName.endsWith('.docx') ||
file.type === 'application/zip' || fileName.endsWith('.zip') ||
file.type === 'application/x-rar-compressed' || fileName.endsWith('.rar');
// 如果主文件是docx,不允许上传pdf附件
if (isMainFileDocx && isPdf) {
hasPdfForDocx = true;
console.error(`【附件追加】主文件为DOCX格式时不允许上传PDF附件: ${file.name}`);
return;
}
if (isValidType) {
validFiles.push(file);
} else {
@@ -813,15 +826,21 @@ export default function DocumentsIndex() {
console.error(`【附件追加】无效的文件类型: ${file.name}, 类型: ${file.type}`);
}
});
if (hasInvalidFiles) {
if (hasPdfForDocx) {
messageService.error('主文件为DOCX格式时,附件不可以是PDF格式', {
title: '文件类型限制',
confirmText: '确定',
cancelText: '',
});
} else if (hasInvalidFiles) {
messageService.error('只支持PDF、Word、ZIP、RAR格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
});
}
if (validFiles.length > 0) {
setAttachmentFiles(validFiles);
console.log('【附件追加】有效文件数量:', validFiles.length);
@@ -887,14 +906,14 @@ export default function DocumentsIndex() {
const fileName = file.name.toLowerCase();
const isValidType =
file.type === 'application/pdf' || fileName.endsWith('.pdf') ||
file.type === 'application/msword' || fileName.endsWith('.doc') ||
// file.type === 'application/msword' || fileName.endsWith('.doc') ||
file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || fileName.endsWith('.docx');
if (isValidType) {
setTemplateFile(file);
console.log('【合同模板上传】有效文件:', file.name);
} else {
messageService.error('只支持PDF、Word格式的文件', {
messageService.error('只支持.pdf、.docx格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
@@ -1584,7 +1603,7 @@ export default function DocumentsIndex() {
ID: <span className="font-medium">{selectedDocumentId}</span>
</p>
<p className="text-xs text-gray-500 mt-1">
PDFWordZIPRAR格式ZIP/RAR内仅合并其中的PDF文件
.pdf.docxZIPRAR格式ZIP/RAR内需要保证文件格式一致
</p>
</div>
@@ -1732,7 +1751,7 @@ export default function DocumentsIndex() {
ID: <span className="font-medium">{selectedDocumentId}</span>
</p>
<p className="text-xs text-gray-500 mt-1">
PDFWord格式
.pdf.docx格式
</p>
</div>
@@ -1744,7 +1763,7 @@ export default function DocumentsIndex() {
<div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
<input
type="file"
accept=".pdf,.doc,.docx"
accept=".pdf,.docx"
onChange={(e) => e.target.files && handleTemplateFileSelected(e.target.files)}
className="hidden"
id="template-file-input"
@@ -1752,7 +1771,7 @@ export default function DocumentsIndex() {
<label htmlFor="template-file-input" className="cursor-pointer">
<i className="ri-file-copy-line text-3xl text-gray-400 mb-2 block"></i>
<p className="text-sm text-gray-600"></p>
<p className="text-xs text-gray-500 mt-1">PDFWord格式</p>
<p className="text-xs text-gray-500 mt-1">.pdf.docx格式</p>
</label>
</div>
{templateFile && (
+128 -34
View File
@@ -35,7 +35,7 @@ export function links() {
// 面包屑导航
export const handle = {
breadcrumb: "文档列表",
breadcrumb: "文档上传",
previousRoute: {
title: "文档列表",
to: "/documents/list"
@@ -647,7 +647,7 @@ export default function FilesUpload() {
if (hasInvalidFiles) {
// 显示错误提示
messageService.error('只支持PDF、Word格式的文件', {
messageService.error('只支持.pdf、.docx格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
@@ -742,7 +742,7 @@ export default function FilesUpload() {
if (hasInvalidFiles) {
// 显示错误提示
console.error('【调试-handleContractMainFilesSelected】存在无效的文件类型');
messageService.error('只支持PDF、Word格式的文件', {
messageService.error('只支持.pdf、.docx格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
@@ -799,7 +799,7 @@ export default function FilesUpload() {
if (hasInvalidFiles) {
// 显示错误提示
console.error('【调试-handleContractAttachmentFilesSelected】存在无效的文件类型');
messageService.error('只支持PDF、Word格式的文件', {
messageService.error('只支持.pdf、.docx格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
@@ -856,7 +856,7 @@ export default function FilesUpload() {
if (hasInvalidFiles) {
// 显示错误提示
console.error('【调试-handleContractTemplateFilesSelected】存在无效的文件类型');
messageService.error('只支持PDF、Word格式的文件', {
messageService.error('只支持.pdf、.docx格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
@@ -883,21 +883,34 @@ export default function FilesUpload() {
const handleAttachmentFilesSelected = (files: FileList) => {
try {
console.log('【附件追加】开始处理附件文件选择, 文件数量:', files.length);
if (files.length > 0) {
// 检查主文件类型
const selectedDocument = queueFiles.find(doc => doc.id === selectedDocumentId);
const isMainFileDocx = selectedDocument?.path.toLowerCase().endsWith('.docx');
// 验证文件类型,支持PDF、Word、ZIP、RAR
const validFiles: File[] = [];
let hasInvalidFiles = false;
let hasPdfForDocx = false;
Array.from(files).forEach(file => {
const fileName = file.name.toLowerCase();
const isValidType =
file.type === 'application/pdf' || fileName.endsWith('.pdf') ||
const isPdf = file.type === 'application/pdf' || fileName.endsWith('.pdf');
const isValidType =
isPdf ||
file.type === 'application/msword' || fileName.endsWith('.doc') ||
file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || fileName.endsWith('.docx') ||
file.type === 'application/zip' || fileName.endsWith('.zip') ||
file.type === 'application/x-rar-compressed' || fileName.endsWith('.rar');
// 如果主文件是docx,不允许上传pdf附件
if (isMainFileDocx && isPdf) {
hasPdfForDocx = true;
console.error(`【附件追加】主文件为DOCX格式时不允许上传PDF附件: ${file.name}`);
return;
}
if (isValidType) {
validFiles.push(file);
} else {
@@ -905,15 +918,21 @@ export default function FilesUpload() {
console.error(`【附件追加】无效的文件类型: ${file.name}, 类型: ${file.type}`);
}
});
if (hasInvalidFiles) {
if (hasPdfForDocx) {
messageService.error('主文件为DOCX格式时,附件不可以是PDF格式', {
title: '文件类型限制',
confirmText: '确定',
cancelText: '',
});
} else if (hasInvalidFiles) {
messageService.error('只支持PDF、Word、ZIP、RAR格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
});
}
if (validFiles.length > 0) {
setAttachmentFiles(validFiles);
console.log('【附件追加】有效文件数量:', validFiles.length);
@@ -984,7 +1003,7 @@ export default function FilesUpload() {
setTemplateFile(file);
console.log('【合同模板上传】有效文件:', file.name);
} else {
messageService.error('只支持PDF、Word格式的文件', {
messageService.error('只支持.pdf、.docx格式的文件', {
title: '文件类型错误',
confirmText: '确定',
cancelText: '',
@@ -1166,6 +1185,11 @@ export default function FilesUpload() {
clearInterval(uploadProgressIntervalRef.current);
uploadProgressIntervalRef.current = null;
}
// 清空合同模板文件缓存
setContractTemplateFiles([]);
console.log('【合同上传失败】已清空合同模板文件缓存');
resetUpload();
}
};
@@ -1304,7 +1328,7 @@ export default function FilesUpload() {
if (invalidFiles.length > 0) {
console.error('【调试-startUpload】文件类型验证失败:', invalidFiles.map(f => f.name));
throw new Error('只支持PDF、Word格式的文件');
throw new Error('只支持.pdf、.docx格式的文件');
}
setUploadStage("uploading");
@@ -2235,7 +2259,7 @@ export default function FilesUpload() {
ref={uploadAreaRef}
onFilesSelected={handleFilesSelected}
multiple={true}
accept=".pdf,.doc,.docx"
accept=".pdf,.docx"
tipText="支持单个或多个文件上传,文件格式:PDF/Word"
shouldPreventFileSelect={!fileType}
/>
@@ -2243,12 +2267,29 @@ export default function FilesUpload() {
// 合同文件上传区域 - 三区域布局
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<h4 className="font-medium mb-2"></h4>
<UploadArea
<div className="flex items-center gap-4 mb-2">
<h4 className="font-medium"></h4>
{contractMainFiles.length > 0 && (
<button
type="button"
onClick={() => {
setContractMainFiles([]);
if (contractMainFileRef.current) {
contractMainFileRef.current.resetFileInput();
}
}}
className="text-red-500 hover:text-red-700 transition-colors"
title="清空已选择的主文件"
>
<i className="ri-delete-bin-line"></i>
</button>
)}
</div>
<UploadArea
onFilesSelected={handleContractMainFilesSelected}
ref={contractMainFileRef}
multiple={false}
accept=".pdf,.doc,.docx"
accept=".pdf,.docx"
tipText="请上传合同主文件,格式:PDF/Word"
mainText="上传合同主文件"
buttonText="选择主文件"
@@ -2257,18 +2298,35 @@ export default function FilesUpload() {
/>
{contractMainFiles.length > 0 && (
<div className="mt-2 text-sm text-green-600">
<i className="ri-checkbox-circle-line"></i>
<i className="ri-checkbox-circle-line"></i>
: <span className="font-medium">{contractMainFiles[0].name}</span>
</div>
)}
</div>
<div>
<h4 className="font-medium mb-2"></h4>
<UploadArea
<div className="flex items-center gap-4 mb-2">
<h4 className="font-medium"></h4>
{contractAttachmentFiles.length > 0 && (
<button
type="button"
onClick={() => {
setContractAttachmentFiles([]);
if (contractAttachmentFileRef.current) {
contractAttachmentFileRef.current.resetFileInput();
}
}}
className="text-red-500 hover:text-red-700 transition-colors"
title="清空已选择的附件"
>
<i className="ri-delete-bin-line"></i>
</button>
)}
</div>
<UploadArea
onFilesSelected={handleContractAttachmentFilesSelected}
ref={contractAttachmentFileRef}
multiple={false}
accept=".pdf,.doc,.docx"
accept=".pdf,.docx"
tipText="请上传合同附件,格式:PDF/Word"
mainText="上传合同附件"
buttonText="选择附件"
@@ -2277,7 +2335,7 @@ export default function FilesUpload() {
/>
{contractAttachmentFiles.length > 0 && (
<div className="mt-2 text-sm text-green-600">
<i className="ri-checkbox-circle-line"></i>
<i className="ri-checkbox-circle-line"></i>
: {contractAttachmentFiles.map((file, index) => (
<span key={index} className="font-medium">{file.name}</span>
))}
@@ -2285,11 +2343,25 @@ export default function FilesUpload() {
)}
</div>
<div>
<h4 className="font-medium mb-2"></h4>
<UploadArea
<div className="flex gap-4 items-center mb-2">
<h4 className="font-medium"></h4>
{contractTemplateFiles.length > 0 && (
<button
type="button"
onClick={() => {
setContractTemplateFiles([]);
}}
className="text-red-500 hover:text-red-700 transition-colors"
title="清空已选择的模板"
>
<i className="ri-delete-bin-line"></i>
</button>
)}
</div>
<UploadArea
onFilesSelected={handleContractTemplateFilesSelected}
multiple={false}
accept=".pdf,.doc,.docx"
accept=".pdf,.docx"
tipText="请上传合同模板,格式:PDF/Word"
mainText="上传合同模板"
buttonText="选择模板"
@@ -2298,7 +2370,7 @@ export default function FilesUpload() {
/>
{contractTemplateFiles.length > 0 && (
<div className="mt-2 text-sm text-green-600">
<i className="ri-checkbox-circle-line"></i>
<i className="ri-checkbox-circle-line"></i>
: <span className="font-medium">{contractTemplateFiles[0].name}</span>
</div>
)}
@@ -2521,7 +2593,19 @@ export default function FilesUpload() {
{/* 附件追加模态框 */}
{showAttachmentUpload && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]"
onClick={(e) => {
// 点击蒙层关闭模态框
if (e.target === e.currentTarget) {
setShowAttachmentUpload(false);
setSelectedDocumentId(null);
setAttachmentFiles([]);
setAttachmentRemark("");
setAttachmentMergeMode('overwrite');
}
}}
>
<div className="bg-white rounded-lg p-6 w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold"></h3>
@@ -2557,7 +2641,7 @@ export default function FilesUpload() {
<UploadArea
onFilesSelected={handleAttachmentFilesSelected}
multiple={true}
accept=".pdf,.doc,.docx,.zip,.rar"
accept=".pdf,.docx,.zip,.rar"
tipText="支持PDF、Word、ZIP、RAR格式,可多选"
mainText="选择附件文件"
buttonText="选择文件"
@@ -2655,7 +2739,17 @@ export default function FilesUpload() {
{/* 合同模板上传模态框 */}
{showTemplateUpload && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]"
onClick={(e) => {
// 点击蒙层关闭模态框
if (e.target === e.currentTarget) {
setShowTemplateUpload(false);
setSelectedDocumentId(null);
setTemplateFile(null);
}
}}
>
<div className="bg-white rounded-lg p-6 w-full max-w-lg mx-4">
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold"></h3>
@@ -2678,7 +2772,7 @@ export default function FilesUpload() {
ID: <span className="font-medium">{selectedDocumentId}</span>
</p>
<p className="text-xs text-gray-500 mt-1">
PDFWord格式
.pdf.docx格式
</p>
</div>
@@ -2690,8 +2784,8 @@ export default function FilesUpload() {
<UploadArea
onFilesSelected={handleTemplateFileSelected}
multiple={false}
accept=".pdf,.doc,.docx"
tipText="支持PDF、Word格式"
accept=".pdf,.docx"
tipText="支持.pdf、.docx格式"
mainText="选择模板文件"
buttonText="选择文件"
icon="ri-file-copy-line"
+58 -7
View File
@@ -8,14 +8,25 @@
* -
*/
import { type MetaFunction } from "@remix-run/node";
import { type MetaFunction, type ClientLoaderFunctionArgs } from "@remix-run/node";
import { useState, useRef, useEffect } from "react";
import { DiffEditor } from "@monaco-editor/react";
import type { editor } from "monaco-editor";
import { pdfjs } from 'react-pdf';
import mammoth from 'mammoth';
import { toastService } from '~/components/ui/Toast';
// 动态导入 Monaco Editor(仅客户端)
let DiffEditor: any = null;
let editor: any = null;
if (typeof window !== 'undefined') {
import('@monaco-editor/react').then((mod) => {
DiffEditor = mod.DiffEditor;
});
import('monaco-editor').then((mod) => {
editor = mod.editor;
});
}
// 设置 PDF.js worker(与 pdf-demo.tsx 相同)
pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
@@ -129,9 +140,10 @@ const CONTRACT_B = `中国烟草合同(修订版本)
export default function MonacoDemoPage() {
const [originalText, setOriginalText] = useState(CONTRACT_A);
const [modifiedText, setModifiedText] = useState(CONTRACT_B);
const diffEditorRef = useRef<editor.IStandaloneDiffEditor | null>(null);
const diffEditorRef = useRef<any>(null);
const [diffCount, setDiffCount] = useState<number>(0);
const [currentDiff, setCurrentDiff] = useState<number>(0);
const [editorLoaded, setEditorLoaded] = useState(false);
// 文档相关状态
// 默认使用的测试文档路径(相对路径)
@@ -297,9 +309,23 @@ export default function MonacoDemoPage() {
}
};
// 检查 Monaco Editor 是否已加载
useEffect(() => {
if (typeof window !== 'undefined') {
Promise.all([
import('@monaco-editor/react'),
import('monaco-editor')
]).then(([reactMod, editorMod]) => {
DiffEditor = reactMod.DiffEditor;
editor = editorMod.editor;
setEditorLoaded(true);
});
}
}, []);
// Monaco Editor 挂载后的回调
const handleEditorDidMount = (editor: editor.IStandaloneDiffEditor) => {
diffEditorRef.current = editor;
const handleEditorDidMount = (editorInstance: any) => {
diffEditorRef.current = editorInstance;
// 获取差异数量
const lineChanges = editor.getLineChanges();
@@ -670,7 +696,8 @@ export default function MonacoDemoPage() {
{/* Diff Editor 主体 */}
<div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
<DiffEditor
{editorLoaded && DiffEditor ? (
<DiffEditor
height="100%"
language="plaintext"
original={originalText}
@@ -699,6 +726,30 @@ export default function MonacoDemoPage() {
diffAlgorithm: 'advanced', // 使用高级差异算法
}}
/>
) : (
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
backgroundColor: '#f5f5f5'
}}>
<div style={{ textAlign: 'center' }}>
<div style={{
width: '48px',
height: '48px',
border: '4px solid #f3f3f3',
borderTop: '4px solid #00684a',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
margin: '0 auto 16px'
}}></div>
<div style={{ fontSize: '16px', color: '#333' }}>
Monaco Editor...
</div>
</div>
</div>
)}
{/* 文档加载中的遮罩层 */}
{(isLoadingDoc1 || isLoadingDoc2) && (
+25 -1
View File
@@ -315,6 +315,11 @@ export default function ReviewDetails() {
newStatus: string;
message: string;
} | null>(null);
const [aiSuggestionReplace, setAiSuggestionReplace] = useState<{
searchText: string;
replaceText: string;
pageNumber: number;
} | undefined>(undefined);
// 🐛 调试:打印 loader 返回的完整数据到浏览器控制台
useEffect(() => {
@@ -432,7 +437,22 @@ export default function ReviewDetails() {
setHighlightValue(value);
}
};
// 处理AI建议替换
const handleAiSuggestionReplace = (searchText: string, replaceText: string, pageNumber: number) => {
console.log('[Reviews] AI建议替换:', { searchText, replaceText, pageNumber });
// 设置替换参数,触发 CollaboraViewer 的搜索替换
setAiSuggestionReplace({
searchText,
replaceText,
pageNumber
});
// 短暂延迟后清除参数,以便下次可以重新触发
setTimeout(() => {
setAiSuggestionReplace(undefined);
}, 1000);
};
// 刷新评审数据
// async function refreshReviewData(documentId: string) {
// // 设置加载状态
@@ -781,6 +801,7 @@ export default function ReviewDetails() {
charPositions={charPositions}
highlightValue={highlightValue}
userInfo={loaderData.userInfo}
aiSuggestionReplace={aiSuggestionReplace}
/>
);
})()}
@@ -788,12 +809,15 @@ export default function ReviewDetails() {
{/* 右侧:评查结果 */}
<div className="w-full lg:w-[35%]">
{/* {JSON.stringify(reviewData.fileInfo.fileFormat)} */}
<ReviewPointsList
reviewPoints={reviewData.reviewPoints}
statistics={reviewData.statistics}
activeReviewPointResultId={activeReviewPointResultId}
onReviewPointSelect={handleReviewPointSelect}
onStatusChange={handleReviewPointStatusChange}
fileFormat={reviewData.fileInfo.fileFormat}
onAiSuggestionReplace={handleAiSuggestionReplace}
/>
</div>
</div>