Files
leaudit-platform-frontend/app/components/collabora/CollaboraViewer.tsx
T
2025-11-27 16:13:51 +08:00

345 lines
11 KiB
TypeScript

/**
* Collabora Online 文档查看器组件
*
* 功能:
* - 加载 Collabora Online iframe
* - 管理文档加载状态
* - 提供 UNO 命令接口
* - 支持只读和编辑模式
*
* @encoding UTF-8
*/
import { useRef, forwardRef, useImperativeHandle, useState } from 'react';
import type { CollaboraViewerProps, CollaboraViewerHandle } from './types';
import { useCollaboraConfig, useDocumentReady, useCollaboraUnoCommands } from './hooks';
import { sendUnoCommand } from './Uno';
import { switchHighlight } from './lib/Highlightselecttext';
import { clearHighlights } from './lib/ClearHighlight';
/**
* Collabora 文档查看器组件
* @param props - 组件属性
* @param ref - 父组件传入的 ref,用于暴露命令接口
*/
export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewerProps>(
function CollaboraViewer(
{
fileId,
mode = 'view',
userId = 'guest',
userName = '',
},
ref
) {
const iframeRef = useRef<HTMLIFrameElement>(null);
// 调试面板状态
const [unoCmd, setUnoCmd] = useState('.uno:GoToStartOfDoc');
const [unoArgs, setUnoArgs] = useState('{}');
const [unoResult, setUnoResult] = useState<string | null>(null);
// 高亮测试面板状态
const [highlightText, setHighlightText] = useState('');
const [highlightPage, setHighlightPage] = useState('');
const [previousHighlightText, setPreviousHighlightText] = useState<string | null>(null);
const [highlightResult, setHighlightResult] = useState<string | null>(null);
// 清除高亮测试面板状态
const [clearHighlightResult, setClearHighlightResult] = useState<string | null>(null);
const [isClearing, setIsClearing] = useState(false);
// 1. 加载 Collabora 配置
const { config, loading, error } = useCollaboraConfig(fileId, mode, userId, userName);
// 2. 监听文档加载状态
const { isDocumentLoaded } = useDocumentReady(iframeRef);
// 3. UNO 命令封装
const unoCommands = useCollaboraUnoCommands(iframeRef);
// 4. 暴露接口给父组件
useImperativeHandle(ref, () => ({
unoCommands,
isReady: isDocumentLoaded,
mode,
getIframeWindow: () => iframeRef.current?.contentWindow || null,
}), [unoCommands, isDocumentLoaded, mode]);
// 加载中状态
if (loading) {
return (
<div className="flex justify-center items-center h-full min-h-[600px]">
<div className="text-center">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
<p className="mt-4 text-gray-600">...</p>
</div>
</div>
);
}
// 错误状态
if (error || !config) {
return (
<div className="flex justify-center items-center h-full min-h-[600px]">
<div className="text-center text-red-500">
<i className="ri-error-warning-line text-4xl mb-2"></i>
<p className="text-lg">{error || '加载配置失败'}</p>
<p className="text-sm text-gray-500 mt-2"></p>
</div>
</div>
);
}
// 发送 UNO 命令的处理函数(测试用)
// const sendUno = () => {
// if (!iframeRef.current?.contentWindow) {
// setUnoResult('iframe 不可用');
// return;
// }
// let args: Record<string, unknown> = {};
// const raw = (unoArgs || '').trim();
// if (raw !== '') {
// try {
// args = JSON.parse(raw) as Record<string, unknown>;
// } catch (err) {
// try {
// // fallback: replace single quotes with double quotes and parse
// args = JSON.parse(raw.replace(/'(.*?)'/g, '"$1"')) as Record<string, unknown>;
// } catch (err2) {
// console.error('解析 UNO Args 失败:', err2);
// setUnoResult('Args 解析失败,请使用有效 JSON');
// return;
// }
// }
// }
// try {
// // 使用正确的 sendUnoCommand 方法
// sendUnoCommand(iframeRef.current.contentWindow, unoCmd, args);
// setUnoResult(`已发送: ${unoCmd}`);
// console.log('[UNO Debug] 发送命令:', unoCmd, args);
// } catch (e) {
// console.error('发送 UNO 失败:', e);
// setUnoResult('发送失败,请查看控制台');
// }
// };
// 高亮测试处理函数
const handleSwitchHighlight = async () => {
if (!iframeRef.current?.contentWindow) {
setHighlightResult('iframe 未就绪');
return;
}
if (!highlightText || highlightText.trim() === '') {
setHighlightResult('请输入要高亮的文本');
return;
}
try {
// 解析页码 (可选)
const page = highlightPage && highlightPage.trim() !== ''
? parseInt(highlightPage.trim(), 10)
: undefined;
// 验证页码
if (page !== undefined && (isNaN(page) || page < 1)) {
setHighlightResult('页码必须是大于0的整数');
return;
}
await switchHighlight(
iframeRef.current.contentWindow,
previousHighlightText,
highlightText.trim(),
{ page }
);
// 更新上一次高亮的文本
setPreviousHighlightText(highlightText.trim());
const pageInfo = page ? ` (第${page}页)` : '';
setHighlightResult(`✓ 已切换高亮: ${highlightText.trim()}${pageInfo}`);
} catch (e) {
console.error('切换高亮失败:', e);
setHighlightResult(`切换失败: ${e instanceof Error ? e.message : '未知错误'}`);
}
};
// 清除高亮处理函数
const handleClearHighlights = async () => {
if (!iframeRef.current?.contentWindow) {
setClearHighlightResult('iframe 未就绪');
return;
}
setIsClearing(true);
setClearHighlightResult('正在清除高亮...');
try {
const result = await clearHighlights(iframeRef.current.contentWindow, {
color: 16776960, // 黄色
timeout: 10000,
});
if (result.success) {
setClearHighlightResult(`${result.message}`);
console.log('[CollaboraViewer] 清除高亮成功:', result);
// 清空之前记录的高亮文本
setPreviousHighlightText(null);
} else {
setClearHighlightResult(`✗ 清除失败: ${result.message}`);
console.error('[CollaboraViewer] 清除高亮失败:', result);
}
// 3秒后清除提示
setTimeout(() => {
setClearHighlightResult(null);
}, 3000);
} catch (e) {
console.error('清除高亮失败:', e);
setClearHighlightResult(`✗ 清除失败: ${e instanceof Error ? e.message : '未知错误'}`);
// 5秒后清除错误提示
setTimeout(() => {
setClearHighlightResult(null);
}, 5000);
} finally {
setIsClearing(false);
}
};
return (
<div className="collabora-viewer relative w-full h-full min-h-[600px]">
{/* UNO 命令测试面板 */}
{/* <div className="absolute top-2 left-2 z-50 bg-white bg-opacity-90 px-2 py-1 rounded shadow flex items-center gap-2">
<input
className="px-2 py-1 border rounded text-sm w-48"
value={unoCmd}
onChange={(e) => setUnoCmd(e.target.value)}
placeholder="UNO 命令"
aria-label="UNO 命令"
/>
<input
className="px-2 py-1 border rounded text-sm w-64"
value={unoArgs}
onChange={(e) => setUnoArgs(e.target.value)}
placeholder="UNO Args (JSON)"
aria-label="UNO Args (JSON)"
/>
<button
className="px-3 py-1 bg-indigo-600 text-white rounded hover:bg-indigo-700 text-sm"
onClick={sendUno}
>
发送 UNO
</button>
{unoResult && <span className="text-xs text-gray-500 ml-2">{unoResult}</span>}
</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">
<input
className="px-3 py-1.5 border rounded text-sm w-64"
value={highlightText}
onChange={(e) => setHighlightText(e.target.value)}
placeholder="输入要高亮的文本 (如: 合同编号)"
aria-label="高亮文本"
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleSwitchHighlight();
}
}}
/>
<input
className="px-3 py-1.5 border rounded text-sm w-20"
value={highlightPage}
onChange={(e) => setHighlightPage(e.target.value)}
placeholder="页码"
aria-label="页码"
type="number"
min="1"
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleSwitchHighlight();
}
}}
/>
<button
className="px-4 py-1.5 bg-yellow-500 text-white rounded hover:bg-yellow-600 text-sm font-medium"
onClick={handleSwitchHighlight}
disabled={!isDocumentLoaded}
>
</button>
{previousHighlightText && (
<span className="text-xs text-gray-600">
: {previousHighlightText}
</span>
)}
{highlightResult && (
<span className="text-xs text-gray-700 ml-2">{highlightResult}</span>
)}
</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">
<button
className={`px-4 py-1.5 rounded text-sm font-medium transition-colors ${
isClearing
? 'bg-gray-400 text-white cursor-not-allowed'
: 'bg-red-500 text-white hover:bg-red-600'
}`}
onClick={handleClearHighlights}
disabled={!isDocumentLoaded || isClearing}
>
{isClearing ? '清除中...' : '清除所有高亮'}
</button>
{clearHighlightResult && (
<span className={`text-xs ml-2 ${
clearHighlightResult.startsWith('✓') ? 'text-green-600' :
clearHighlightResult.startsWith('✗') ? 'text-red-600' :
'text-gray-600'
}`}>
{clearHighlightResult}
</span>
)}
</div>
{/* 文档加载提示 */}
{!isDocumentLoaded && (
<div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90 z-10">
<div className="text-center">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
<p className="mt-4 text-gray-600">...</p>
<p className="text-sm text-gray-500 mt-2">{config.fileName}</p>
</div>
</div>
)}
{/* Collabora iframe - tabIndex is needed for keyboard navigation */}
{/* eslint-disable jsx-a11y/no-noninteractive-tabindex */}
<iframe
ref={iframeRef}
src={config.iframeUrl}
className="w-full h-full border-0"
style={{
minHeight: '600px',
height: '100%',
}}
allow="clipboard-read; clipboard-write"
title={`Collabora Online - ${config.fileName}`}
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-modals"
tabIndex={0}
/>
{/* eslint-enable jsx-a11y/no-noninteractive-tabindex */}
</div>
);
});
// 导出类型和 hook
export type { CollaboraViewerHandle };
export { useCollaboraUnoCommands };