Merge branch 'PingChuan' into shiy-login
# Conflicts: # app/components/reviews/ReviewTabs.tsx
This commit is contained in:
@@ -10,30 +10,50 @@
|
|||||||
* @encoding UTF-8
|
* @encoding UTF-8
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useRef } from 'react';
|
import { useRef, forwardRef, useImperativeHandle, useState } from 'react';
|
||||||
import type { CollaboraViewerProps } from './types';
|
import type { CollaboraViewerProps, CollaboraViewerHandle } from './types';
|
||||||
import { useCollaboraConfig, useDocumentReady, useCollaboraUnoCommands } from './hooks';
|
import { useCollaboraConfig, useDocumentReady, useCollaboraUnoCommands } from './hooks';
|
||||||
|
import { sendUnoCommand } from './Uno';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Collabora 文档查看器组件
|
* Collabora 文档查看器组件
|
||||||
* @param props - 组件属性
|
* @param props - 组件属性
|
||||||
|
* @param ref - 父组件传入的 ref,用于暴露命令接口
|
||||||
*/
|
*/
|
||||||
export function CollaboraViewer({
|
export const CollaboraViewer = forwardRef<CollaboraViewerHandle, CollaboraViewerProps>(
|
||||||
fileId,
|
function CollaboraViewer(
|
||||||
mode = 'view',
|
{
|
||||||
userId = 'guest',
|
fileId,
|
||||||
userName = '访客',
|
mode = 'view',
|
||||||
}: CollaboraViewerProps) {
|
userId = 'guest',
|
||||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
userName = '访客',
|
||||||
|
},
|
||||||
|
ref
|
||||||
|
) {
|
||||||
|
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||||
|
|
||||||
// 1. 加载 Collabora 配置
|
// 调试面板状态
|
||||||
const { config, loading, error } = useCollaboraConfig(fileId, mode, userId, userName);
|
const [unoCmd, setUnoCmd] = useState('.uno:GoToStartOfDoc');
|
||||||
|
const [unoArgs, setUnoArgs] = useState('{}');
|
||||||
|
const [unoResult, setUnoResult] = useState<string | null>(null);
|
||||||
|
|
||||||
// 2. 监听文档加载状态
|
// 1. 加载 Collabora 配置
|
||||||
const { isDocumentLoaded } = useDocumentReady(iframeRef);
|
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]);
|
||||||
|
|
||||||
// 3. UNO 命令封装
|
|
||||||
const unoCommands = useCollaboraUnoCommands(iframeRef);
|
|
||||||
|
|
||||||
// 加载中状态
|
// 加载中状态
|
||||||
if (loading) {
|
if (loading) {
|
||||||
@@ -60,8 +80,68 @@ export function CollaboraViewer({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 发送 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('发送失败,请查看控制台');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="collabora-viewer relative w-full h-full min-h-[600px]">
|
<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>
|
||||||
|
|
||||||
{/* 文档加载提示 */}
|
{/* 文档加载提示 */}
|
||||||
{!isDocumentLoaded && (
|
{!isDocumentLoaded && (
|
||||||
<div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90 z-10">
|
<div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90 z-10">
|
||||||
@@ -73,7 +153,8 @@ export function CollaboraViewer({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Collabora iframe */}
|
{/* Collabora iframe - tabIndex is needed for keyboard navigation */}
|
||||||
|
{/* eslint-disable jsx-a11y/no-noninteractive-tabindex */}
|
||||||
<iframe
|
<iframe
|
||||||
ref={iframeRef}
|
ref={iframeRef}
|
||||||
src={config.iframeUrl}
|
src={config.iframeUrl}
|
||||||
@@ -85,10 +166,13 @@ export function CollaboraViewer({
|
|||||||
allow="clipboard-read; clipboard-write"
|
allow="clipboard-read; clipboard-write"
|
||||||
title={`Collabora Online - ${config.fileName}`}
|
title={`Collabora Online - ${config.fileName}`}
|
||||||
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-modals"
|
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-modals"
|
||||||
|
tabIndex={0}
|
||||||
/>
|
/>
|
||||||
|
{/* eslint-enable jsx-a11y/no-noninteractive-tabindex */}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
});
|
||||||
|
|
||||||
// 导出 UNO 命令 hook 供父组件使用(如果需要)
|
// 导出类型和 hook
|
||||||
|
export type { CollaboraViewerHandle };
|
||||||
export { useCollaboraUnoCommands };
|
export { useCollaboraUnoCommands };
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* Collabora Online UNO 命令工具函数
|
* Collabora Online UNO 命令核心工具
|
||||||
*
|
*
|
||||||
* 职责: 封装 Collabora iframe 的 UNO 命令调用
|
* 职责: 提供基础的 UNO 命令发送和状态监听功能
|
||||||
*
|
*
|
||||||
* @encoding UTF-8
|
* @encoding UTF-8
|
||||||
*/
|
*/
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
export function sendUnoCommand(
|
export function sendUnoCommand(
|
||||||
iframeWindow: Window,
|
iframeWindow: Window,
|
||||||
command: string,
|
command: string,
|
||||||
args: Record<string, any> = {}
|
args: Record<string, unknown> = {}
|
||||||
): void {
|
): void {
|
||||||
const message = {
|
const message = {
|
||||||
MessageId: 'Send_UNO_Command',
|
MessageId: 'Send_UNO_Command',
|
||||||
@@ -30,121 +30,6 @@ export function sendUnoCommand(
|
|||||||
iframeWindow.postMessage(JSON.stringify(message), '*');
|
iframeWindow.postMessage(JSON.stringify(message), '*');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 搜索文本
|
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
|
||||||
* @param text - 要搜索的文本
|
|
||||||
*/
|
|
||||||
export function unoSearchText(iframeWindow: Window, text: string): void {
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
|
||||||
'SearchItem.SearchString': { type: 'string', value: text },
|
|
||||||
'SearchItem.Command': { type: 'long', value: 1 }, // 1 = Search Next (搜索下一个)
|
|
||||||
'SearchItem.Backward': { type: 'boolean', value: false },
|
|
||||||
'SearchItem.Pattern': { type: 'boolean', value: false },
|
|
||||||
'SearchItem.Content': { type: 'boolean', value: false },
|
|
||||||
'SearchItem.AsianOptions': { type: 'boolean', value: false },
|
|
||||||
'SearchItem.AlgorithmType': { type: 'short', value: 0 }, // 普通搜索
|
|
||||||
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
|
||||||
'SearchItem.Start': { type: 'boolean', value: true }, // 从头开始搜索
|
|
||||||
'SearchItem.Quiet': { type: 'boolean', value: true }, // 静默模式
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 替换文本
|
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
|
||||||
* @param searchText - 要搜索的文本
|
|
||||||
* @param replaceText - 替换后的文本
|
|
||||||
*/
|
|
||||||
export function unoReplaceText(
|
|
||||||
iframeWindow: Window,
|
|
||||||
searchText: string,
|
|
||||||
replaceText: string
|
|
||||||
): void {
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
|
||||||
'SearchItem.SearchString': { type: 'string', value: searchText },
|
|
||||||
'SearchItem.ReplaceString': { type: 'string', value: replaceText },
|
|
||||||
'SearchItem.Command': { type: 'long', value: 3 }, // 3 = ReplaceAll
|
|
||||||
'SearchItem.AlgorithmType': { type: 'short', value: 0 },
|
|
||||||
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
|
||||||
'SearchItem.Backward': { type: 'boolean', value: false },
|
|
||||||
'Quiet': { type: 'boolean', value: true },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 高亮文本
|
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
|
||||||
* @param text - 要高亮的文本
|
|
||||||
* @param color - 高亮颜色,默认 16776960 = 黄色
|
|
||||||
*/
|
|
||||||
export function unoHighlightText(
|
|
||||||
iframeWindow: Window,
|
|
||||||
text: string,
|
|
||||||
color: number = 16776960
|
|
||||||
): void {
|
|
||||||
// 1. 查找所有
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
|
||||||
'SearchItem.SearchString': { type: 'string', value: text },
|
|
||||||
'SearchItem.Command': { type: 'long', value: 1 }, // 1 = FindAll
|
|
||||||
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
|
||||||
'SearchItem.AlgorithmType': { type: 'short', value: 0 },
|
|
||||||
'SearchItem.Backward': { type: 'boolean', value: false },
|
|
||||||
'Quiet': { type: 'boolean', value: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
// 2. 设置背景色
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:BackColor', {
|
|
||||||
BackColor: { type: 'long', value: color },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 移除高亮
|
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
|
||||||
* @param text - 要移除高亮的文本
|
|
||||||
*/
|
|
||||||
export function unoRemoveHighlight(iframeWindow: Window, text: string): void {
|
|
||||||
// 1. 查找所有
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
|
||||||
'SearchItem.SearchString': { type: 'string', value: text },
|
|
||||||
'SearchItem.Command': { type: 'long', value: 1 }, // 1 = FindAll
|
|
||||||
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
|
||||||
'SearchItem.AlgorithmType': { type: 'short', value: 0 },
|
|
||||||
'SearchItem.Backward': { type: 'boolean', value: false },
|
|
||||||
'Quiet': { type: 'boolean', value: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
// 2. 移除背景色 -1 = 无色
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:BackColor', {
|
|
||||||
BackColor: { type: 'long', value: -1 },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 取消 - Escape
|
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
|
||||||
*/
|
|
||||||
export function unoEscape(iframeWindow: Window): void {
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:Escape', {});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 滚动到文档开头
|
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
|
||||||
*/
|
|
||||||
export function unoScrollToTop(iframeWindow: Window): void {
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:GoToStartOfDoc', {});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 保存文档
|
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
|
||||||
*/
|
|
||||||
export function unoSave(iframeWindow: Window): void {
|
|
||||||
sendUnoCommand(iframeWindow, '.uno:Save');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取文档状态 (用于检测命令队列完成)
|
* 获取文档状态 (用于检测命令队列完成)
|
||||||
* @param iframeWindow - iframe 的 contentWindow
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
|||||||
@@ -21,7 +21,10 @@ import {
|
|||||||
unoEscape,
|
unoEscape,
|
||||||
unoScrollToTop,
|
unoScrollToTop,
|
||||||
unoSave,
|
unoSave,
|
||||||
} from './Uno';
|
unoZoomPlus,
|
||||||
|
unoZoomMinus,
|
||||||
|
unoSetZoom,
|
||||||
|
} from './lib';
|
||||||
import { COLLABORA_URL } from '~/config/api-config';
|
import { COLLABORA_URL } from '~/config/api-config';
|
||||||
|
|
||||||
// ==================== 1. 配置加载 ====================
|
// ==================== 1. 配置加载 ====================
|
||||||
@@ -61,7 +64,8 @@ export function useCollaboraConfig(
|
|||||||
// 检查错误
|
// 检查错误
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (fetcher.data && 'error' in fetcher.data) {
|
if (fetcher.data && 'error' in fetcher.data) {
|
||||||
const errorMessage = (fetcher.data as any).error || '加载配置失败';
|
const errorData = fetcher.data as { error: string };
|
||||||
|
const errorMessage = errorData.error || '加载配置失败';
|
||||||
setError(errorMessage);
|
setError(errorMessage);
|
||||||
toastService.error(`加载文档配置失败: ${errorMessage}`);
|
toastService.error(`加载文档配置失败: ${errorMessage}`);
|
||||||
}
|
}
|
||||||
@@ -131,9 +135,8 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
console.warn('[UNO] iframe 不可用');
|
console.warn('[UNO] iframe 不可用');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[UNO] 搜索文本: "${text}"`);
|
console.log(`[UNO] 搜索文本: "${text}"`);
|
||||||
unoSearchText(iframeRef.current.contentWindow, text);
|
await unoSearchText(iframeRef.current.contentWindow, text);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
},
|
},
|
||||||
[iframeRef]
|
[iframeRef]
|
||||||
@@ -175,9 +178,8 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
console.warn('[UNO] iframe 不可用');
|
console.warn('[UNO] iframe 不可用');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[UNO] 替换文本: "${searchText}" -> "${replaceText}"`);
|
console.log(`[UNO] 替换文本: "${searchText}" -> "${replaceText}"`);
|
||||||
unoReplaceText(iframeRef.current.contentWindow, searchText, replaceText);
|
await unoReplaceText(iframeRef.current.contentWindow, searchText, replaceText);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||||
},
|
},
|
||||||
[iframeRef]
|
[iframeRef]
|
||||||
@@ -192,9 +194,8 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
console.warn('[UNO] iframe 不可用');
|
console.warn('[UNO] iframe 不可用');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[UNO] 高亮文本: "${text}"`);
|
console.log(`[UNO] 高亮文本: "${text}"`);
|
||||||
unoHighlightText(iframeRef.current.contentWindow, text, color);
|
await unoHighlightText(iframeRef.current.contentWindow, text, color);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||||
},
|
},
|
||||||
[iframeRef]
|
[iframeRef]
|
||||||
@@ -209,9 +210,8 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
console.warn('[UNO] iframe 不可用');
|
console.warn('[UNO] iframe 不可用');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[UNO] 移除高亮: "${text}"`);
|
console.log(`[UNO] 移除高亮: "${text}"`);
|
||||||
unoRemoveHighlight(iframeRef.current.contentWindow, text);
|
await unoRemoveHighlight(iframeRef.current.contentWindow, text);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||||
},
|
},
|
||||||
[iframeRef]
|
[iframeRef]
|
||||||
@@ -227,7 +227,7 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log('[UNO] 取消选中');
|
console.log('[UNO] 取消选中');
|
||||||
unoEscape(iframeRef.current.contentWindow);
|
await unoEscape(iframeRef.current.contentWindow);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||||
}, [iframeRef]);
|
}, [iframeRef]);
|
||||||
|
|
||||||
@@ -241,7 +241,7 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log('[UNO] 滚动到顶部');
|
console.log('[UNO] 滚动到顶部');
|
||||||
unoScrollToTop(iframeRef.current.contentWindow);
|
await unoScrollToTop(iframeRef.current.contentWindow);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
}, [iframeRef]);
|
}, [iframeRef]);
|
||||||
|
|
||||||
@@ -255,10 +255,57 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log('[UNO] 保存文档');
|
console.log('[UNO] 保存文档');
|
||||||
unoSave(iframeRef.current.contentWindow);
|
await unoSave(iframeRef.current.contentWindow);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
}, [iframeRef]);
|
}, [iframeRef]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 放大文档
|
||||||
|
*/
|
||||||
|
const zoomIn = useCallback(async () => {
|
||||||
|
if (!iframeRef.current?.contentWindow) {
|
||||||
|
console.warn('[UNO] iframe 不可用');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[UNO] 放大文档');
|
||||||
|
await unoZoomPlus(iframeRef.current.contentWindow);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
}, [iframeRef]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缩小文档
|
||||||
|
*/
|
||||||
|
const zoomOut = useCallback(async () => {
|
||||||
|
if (!iframeRef.current?.contentWindow) {
|
||||||
|
console.warn('[UNO] iframe 不可用');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[UNO] 缩小文档');
|
||||||
|
await unoZoomMinus(iframeRef.current.contentWindow);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
}, [iframeRef]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置缩放比例
|
||||||
|
* @param percentage - 缩放百分比 (例如:100 表示 100%)
|
||||||
|
*/
|
||||||
|
const setZoom = useCallback(
|
||||||
|
async (percentage: number) => {
|
||||||
|
if (!iframeRef.current?.contentWindow) {
|
||||||
|
console.warn('[UNO] iframe 不可用');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[UNO] 设置缩放比例: ${percentage}%`);
|
||||||
|
await unoSetZoom(iframeRef.current.contentWindow, percentage);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
},
|
||||||
|
[iframeRef]
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
return useMemo(
|
return useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
searchText,
|
searchText,
|
||||||
@@ -269,6 +316,9 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
escapeSelection,
|
escapeSelection,
|
||||||
scrollToTop,
|
scrollToTop,
|
||||||
saveDocument,
|
saveDocument,
|
||||||
|
zoomIn,
|
||||||
|
zoomOut,
|
||||||
|
setZoom,
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
searchText,
|
searchText,
|
||||||
@@ -279,6 +329,9 @@ export function useCollaboraUnoCommands(iframeRef: RefObject<HTMLIFrameElement>)
|
|||||||
escapeSelection,
|
escapeSelection,
|
||||||
scrollToTop,
|
scrollToTop,
|
||||||
saveDocument,
|
saveDocument,
|
||||||
|
zoomIn,
|
||||||
|
zoomOut,
|
||||||
|
setZoom,
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
# Collabora 功能模块说明
|
||||||
|
|
||||||
|
本目录包含按功能拆分的 Collabora UNO 命令封装模块。
|
||||||
|
|
||||||
|
## 文件结构
|
||||||
|
|
||||||
|
```
|
||||||
|
lib/
|
||||||
|
├── README.md # 本说明文档
|
||||||
|
├── index.ts # 统一导出所有功能模块
|
||||||
|
├── search.ts # 搜索功能
|
||||||
|
├── replace.ts # 替换功能
|
||||||
|
├── highlight.ts # 高亮功能
|
||||||
|
├── navigation.ts # 导航/跳转功能
|
||||||
|
├── zoom.ts # 缩放功能
|
||||||
|
├── document.ts # 文档操作
|
||||||
|
├── pageInfo.ts # 页数信息获取
|
||||||
|
└── gotoPage.ts # 自定义页面跳转(不使用 UNO 命令)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 功能模块
|
||||||
|
|
||||||
|
### 1. search.ts - 搜索功能
|
||||||
|
- `unoSearchText(iframeWindow, text)` - 搜索文本
|
||||||
|
|
||||||
|
### 2. replace.ts - 替换功能
|
||||||
|
- `unoReplaceText(iframeWindow, searchText, replaceText)` - 替换文本
|
||||||
|
|
||||||
|
### 3. highlight.ts - 高亮功能
|
||||||
|
- `unoHighlightText(iframeWindow, text, color)` - 高亮文本
|
||||||
|
- `unoRemoveHighlight(iframeWindow, text)` - 移除高亮
|
||||||
|
- `unoEscape(iframeWindow)` - 取消(Escape)
|
||||||
|
|
||||||
|
### 4. navigation.ts - 导航/跳转功能
|
||||||
|
- `unoScrollToTop(iframeWindow)` - 滚动到文档开头(带焦点请求)
|
||||||
|
|
||||||
|
### 5. zoom.ts - 缩放功能
|
||||||
|
- `unoZoomPlus(iframeWindow)` - 放大文档
|
||||||
|
- `unoZoomMinus(iframeWindow)` - 缩小文档
|
||||||
|
- `unoSetZoom(iframeWindow, percentage)` - 设置缩放比例
|
||||||
|
|
||||||
|
### 6. document.ts - 文档操作
|
||||||
|
- `unoSave(iframeWindow)` - 保存文档
|
||||||
|
|
||||||
|
### 7. pageInfo.ts - 页数信息获取
|
||||||
|
- `listenPageNumberChanged(iframeWindow, callback)` - 监听文档页数变化事件
|
||||||
|
- `requestPageInfo(iframeWindow)` - 请求页数信息(返回 Promise)
|
||||||
|
- `getPageInfoFromCollabora()` - 从 Collabora 内部直接获取页数(仅 iframe 内部可用)
|
||||||
|
- `PageInfo` 接口 - 页数信息类型定义
|
||||||
|
|
||||||
|
### 8. gotoPage.ts - 自定义页面跳转(不使用 UNO 命令)
|
||||||
|
- `customGotoPage(iframeWindow, pageNumber)` - 跳转到指定页面(使用自定义 PostMessage 协议)
|
||||||
|
- `GotoPageResponse` 接口 - 页面跳转响应信息类型定义
|
||||||
|
|
||||||
|
## 使用方式
|
||||||
|
|
||||||
|
### 方式 1: 从统一入口导入(推荐)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import {
|
||||||
|
unoSearchText,
|
||||||
|
unoReplaceText,
|
||||||
|
unoHighlightText,
|
||||||
|
unoScrollToTop,
|
||||||
|
unoSave,
|
||||||
|
customGotoPage,
|
||||||
|
requestPageInfo,
|
||||||
|
} from '~/components/collabora/lib';
|
||||||
|
```
|
||||||
|
|
||||||
|
### 方式 2: 从具体模块导入
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { unoSearchText } from '~/components/collabora/lib/search';
|
||||||
|
import { unoScrollToTop } from '~/components/collabora/lib/navigation';
|
||||||
|
import { customGotoPage } from '~/components/collabora/lib/gotoPage';
|
||||||
|
import { requestPageInfo } from '~/components/collabora/lib/pageInfo';
|
||||||
|
```
|
||||||
|
|
||||||
|
## 核心工具函数
|
||||||
|
|
||||||
|
核心的命令发送和状态监听函数位于 `../Uno.ts`:
|
||||||
|
|
||||||
|
- `sendUnoCommand(iframeWindow, command, args)` - 发送 UNO 命令
|
||||||
|
- `unoGetState(iframeWindow)` - 获取文档状态(用于检测命令队列完成)
|
||||||
|
|
||||||
|
## 设计原则
|
||||||
|
|
||||||
|
1. **单一职责**: 每个文件只负责一个功能领域
|
||||||
|
2. **清晰命名**: 文件名直接反映功能(search, replace, highlight 等)
|
||||||
|
3. **统一接口**: 所有函数第一个参数都是 `iframeWindow: Window`
|
||||||
|
4. **依赖注入**: 通过 import `sendUnoCommand` 而不是重复实现
|
||||||
|
5. **便于维护**: 功能独立,修改某个模块不影响其他模块
|
||||||
|
|
||||||
|
## 扩展指南
|
||||||
|
|
||||||
|
如果需要添加新功能模块:
|
||||||
|
|
||||||
|
1. 在 `lib/` 下创建新文件,如 `lib/print.ts`
|
||||||
|
2. 实现功能函数,import `sendUnoCommand` from `../Uno`
|
||||||
|
3. 在 `lib/index.ts` 中添加导出
|
||||||
|
4. 在本 README 中补充说明
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// lib/print.ts
|
||||||
|
import { sendUnoCommand } from '../Uno';
|
||||||
|
|
||||||
|
export function unoPrint(iframeWindow: Window): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:Print', {});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// lib/index.ts
|
||||||
|
export { unoPrint } from './print';
|
||||||
|
```
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 文档操作功能模块
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { sendUnoCommand } from '../Uno';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存文档
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
*/
|
||||||
|
export function unoSave(iframeWindow: Window): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:Save');
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 自定义页面跳转模块
|
||||||
|
*
|
||||||
|
* 使用自定义 PostMessage 协议实现页面跳转,不依赖 UNO 命令
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页面跳转响应接口
|
||||||
|
*/
|
||||||
|
export interface GotoPageResponse {
|
||||||
|
pageNumber: number;
|
||||||
|
pageIndex: number;
|
||||||
|
totalPages: number;
|
||||||
|
currentOffset: number;
|
||||||
|
targetOffset: number;
|
||||||
|
scrollDelta: number;
|
||||||
|
timestamp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collabora PostMessage 数据类型
|
||||||
|
*/
|
||||||
|
interface CollaboraMessageData {
|
||||||
|
MessageId?: string;
|
||||||
|
msgId?: string;
|
||||||
|
Values?: {
|
||||||
|
Command?: string;
|
||||||
|
Status?: string;
|
||||||
|
pageNumber?: number;
|
||||||
|
pageIndex?: number;
|
||||||
|
totalPages?: number;
|
||||||
|
currentOffset?: number;
|
||||||
|
targetOffset?: number;
|
||||||
|
scrollDelta?: number;
|
||||||
|
timestamp?: number;
|
||||||
|
Error?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
args?: {
|
||||||
|
Command?: string;
|
||||||
|
Status?: string;
|
||||||
|
pageNumber?: number;
|
||||||
|
pageIndex?: number;
|
||||||
|
totalPages?: number;
|
||||||
|
currentOffset?: number;
|
||||||
|
targetOffset?: number;
|
||||||
|
scrollDelta?: number;
|
||||||
|
timestamp?: number;
|
||||||
|
Error?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 PostMessage 数据
|
||||||
|
*/
|
||||||
|
function parseMessageData(data: unknown): CollaboraMessageData {
|
||||||
|
if (typeof data === 'string') {
|
||||||
|
return JSON.parse(data) as CollaboraMessageData;
|
||||||
|
}
|
||||||
|
return data as CollaboraMessageData;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 跳转到指定页面 (自定义实现,不使用 UNO 命令)
|
||||||
|
*
|
||||||
|
* 使用自定义 custompostMessage 插件实现页面跳转。
|
||||||
|
* 注意: Collabora 的页码是从 0 开始的,但此函数接受从 1 开始的页码。
|
||||||
|
*
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
* @param pageNumber - 页码 (从1开始)
|
||||||
|
* @returns Promise,解析为跳转响应信息
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const response = await customGotoPage(iframeWindow, 5);
|
||||||
|
* console.log(`成功跳转到第 ${response.pageNumber} 页`);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export async function customGotoPage(
|
||||||
|
iframeWindow: Window,
|
||||||
|
pageNumber: number
|
||||||
|
): Promise<GotoPageResponse> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
cleanup();
|
||||||
|
reject(new Error('页面跳转超时'));
|
||||||
|
}, 5000);
|
||||||
|
|
||||||
|
const handleMessage = (event: MessageEvent) => {
|
||||||
|
try {
|
||||||
|
if (event.source !== iframeWindow) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = parseMessageData(event.data);
|
||||||
|
|
||||||
|
// bundle.js 的 _postMessage 会将消息转换为:
|
||||||
|
// { MessageId: 'custompostMessage_Resp', Values: { Command: 'GOTO_PAGE', ... } }
|
||||||
|
if (
|
||||||
|
data.MessageId === 'custompostMessage_Resp' &&
|
||||||
|
data.Values?.Command === 'GOTO_PAGE'
|
||||||
|
) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
cleanup();
|
||||||
|
|
||||||
|
if (data.Values.Status === 'success') {
|
||||||
|
const response: GotoPageResponse = {
|
||||||
|
pageNumber: data.Values.pageNumber || pageNumber,
|
||||||
|
pageIndex: data.Values.pageIndex || pageNumber - 1,
|
||||||
|
totalPages: data.Values.totalPages || 0,
|
||||||
|
currentOffset: data.Values.currentOffset || 0,
|
||||||
|
targetOffset: data.Values.targetOffset || 0,
|
||||||
|
scrollDelta: data.Values.scrollDelta || 0,
|
||||||
|
timestamp: data.Values.timestamp || Date.now(),
|
||||||
|
};
|
||||||
|
resolve(response);
|
||||||
|
} else {
|
||||||
|
reject(new Error(data.Values.Error || '页面跳转失败'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
cleanup();
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
window.removeEventListener('message', handleMessage);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('message', handleMessage);
|
||||||
|
|
||||||
|
// 发送跳转请求消息
|
||||||
|
const message = {
|
||||||
|
MessageId: 'custompostMessage',
|
||||||
|
Values: {
|
||||||
|
Command: 'GOTO_PAGE',
|
||||||
|
Args: {
|
||||||
|
pageNumber: pageNumber,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
iframeWindow.postMessage(JSON.stringify(message), '*');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 高亮功能模块
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { sendUnoCommand } from '../Uno';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 高亮文本
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
* @param text - 要高亮的文本
|
||||||
|
* @param color - 高亮颜色,默认 16776960 = 黄色
|
||||||
|
*/
|
||||||
|
export function unoHighlightText(
|
||||||
|
iframeWindow: Window,
|
||||||
|
text: string,
|
||||||
|
color: number = 16776960
|
||||||
|
): void {
|
||||||
|
// 1. 查找所有
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
||||||
|
'SearchItem.SearchString': { type: 'string', value: text },
|
||||||
|
'SearchItem.Command': { type: 'long', value: 1 }, // 1 = FindAll
|
||||||
|
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
||||||
|
'SearchItem.AlgorithmType': { type: 'short', value: 0 },
|
||||||
|
'SearchItem.Backward': { type: 'boolean', value: false },
|
||||||
|
'Quiet': { type: 'boolean', value: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. 设置背景色
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:BackColor', {
|
||||||
|
BackColor: { type: 'long', value: color },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除高亮
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
* @param text - 要移除高亮的文本
|
||||||
|
*/
|
||||||
|
export function unoRemoveHighlight(iframeWindow: Window, text: string): void {
|
||||||
|
// 1. 查找所有
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
||||||
|
'SearchItem.SearchString': { type: 'string', value: text },
|
||||||
|
'SearchItem.Command': { type: 'long', value: 1 }, // 1 = FindAll
|
||||||
|
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
||||||
|
'SearchItem.AlgorithmType': { type: 'short', value: 0 },
|
||||||
|
'SearchItem.Backward': { type: 'boolean', value: false },
|
||||||
|
'Quiet': { type: 'boolean', value: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. 移除背景色 -1 = 无色
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:BackColor', {
|
||||||
|
BackColor: { type: 'long', value: -1 },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消 - Escape
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
*/
|
||||||
|
export function unoEscape(iframeWindow: Window): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:Escape', {});
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 功能模块统一导出
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 搜索功能
|
||||||
|
export { unoSearchText } from './search';
|
||||||
|
|
||||||
|
// 替换功能
|
||||||
|
export { unoReplaceText } from './replace';
|
||||||
|
|
||||||
|
// 高亮功能
|
||||||
|
export { unoHighlightText, unoRemoveHighlight, unoEscape } from './highlight';
|
||||||
|
|
||||||
|
// 导航/跳转功能
|
||||||
|
export {
|
||||||
|
unoScrollToTop,
|
||||||
|
} from './navigation';
|
||||||
|
|
||||||
|
// 缩放功能
|
||||||
|
export { unoZoomPlus, unoZoomMinus, unoSetZoom } from './zoom';
|
||||||
|
|
||||||
|
// 文档操作
|
||||||
|
export { unoSave } from './document';
|
||||||
|
|
||||||
|
// 页数信息
|
||||||
|
export {
|
||||||
|
requestPageInfo,
|
||||||
|
type PageInfo,
|
||||||
|
} from './pageInfo';
|
||||||
|
|
||||||
|
// 自定义页面跳转功能
|
||||||
|
export {
|
||||||
|
customGotoPage,
|
||||||
|
type GotoPageResponse,
|
||||||
|
} from './gotoPage';
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 导航/跳转功能模块
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { sendUnoCommand } from '../Uno';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 滚动到文档开头 (带焦点请求)
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
*/
|
||||||
|
export async function unoScrollToTop(iframeWindow: Window): Promise<void> {
|
||||||
|
// 1. 先请求 iframe 获取焦点
|
||||||
|
const focusMessage = {
|
||||||
|
MessageId: 'custompostMessage',
|
||||||
|
Values: {
|
||||||
|
Command: 'REQUEST_FOCUS',
|
||||||
|
Args: {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
console.log('[custompostMessage] 请求焦点 (滚动到顶部)');
|
||||||
|
iframeWindow.postMessage(JSON.stringify(focusMessage), '*');
|
||||||
|
|
||||||
|
// 2. 等待焦点激活
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
|
||||||
|
// 3. 发送滚动命令,要发三次,有时候卡在表格里面就是需要多发几次
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:GoToStartOfDoc', {});
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:GoToStartOfDoc', {});
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:GoToStartOfDoc', {});
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 页数信息获取模块
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页数信息接口
|
||||||
|
*/
|
||||||
|
export interface PageInfo {
|
||||||
|
totalPages: number;
|
||||||
|
currentPage: number;
|
||||||
|
timestamp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collabora PostMessage 数据类型
|
||||||
|
*/
|
||||||
|
interface CollaboraMessageData {
|
||||||
|
MessageId?: string;
|
||||||
|
msgId?: string;
|
||||||
|
// bundle.js _postMessage 发送的格式
|
||||||
|
Values?: {
|
||||||
|
Command?: string;
|
||||||
|
Status?: string;
|
||||||
|
totalPages?: number;
|
||||||
|
currentPage?: number;
|
||||||
|
timestamp?: number;
|
||||||
|
pages?: number;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
// 原始插件返回的格式
|
||||||
|
args?: {
|
||||||
|
Command?: string;
|
||||||
|
Status?: string;
|
||||||
|
totalPages?: number;
|
||||||
|
currentPage?: number;
|
||||||
|
timestamp?: number;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 PostMessage 数据
|
||||||
|
*/
|
||||||
|
function parseMessageData(data: unknown): CollaboraMessageData {
|
||||||
|
if (typeof data === 'string') {
|
||||||
|
return JSON.parse(data) as CollaboraMessageData;
|
||||||
|
}
|
||||||
|
return data as CollaboraMessageData;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过 PostMessage 请求页数信息
|
||||||
|
*
|
||||||
|
* 使用自定义 custompostMessage 插件获取文档页数。
|
||||||
|
* 注意: Collabora 的页码是从 0 开始的。
|
||||||
|
*
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
* @returns Promise,解析为页数信息
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* const info = await requestPageInfo(iframeWindow);
|
||||||
|
* console.log(`文档共 ${info.totalPages} 页,当前在第 ${info.currentPage + 1} 页`);
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export async function requestPageInfo(iframeWindow: Window): Promise<PageInfo> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
cleanup();
|
||||||
|
reject(new Error('请求页数信息超时'));
|
||||||
|
}, 5000);
|
||||||
|
|
||||||
|
const handleMessage = (event: MessageEvent) => {
|
||||||
|
try {
|
||||||
|
if (event.source !== iframeWindow) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = parseMessageData(event.data);
|
||||||
|
|
||||||
|
// bundle.js 的 _postMessage 会将消息转换为:
|
||||||
|
// { MessageId: 'custompostMessage_Resp', Values: { Command: 'GET_PAGE_INFO', ... } }
|
||||||
|
// 所以我们需要监听 MessageId 而不是 msgId
|
||||||
|
if (
|
||||||
|
data.MessageId === 'custompostMessage_Resp' &&
|
||||||
|
data.Values?.Command === 'GET_PAGE_INFO' &&
|
||||||
|
data.Values?.Status === 'success'
|
||||||
|
) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
cleanup();
|
||||||
|
|
||||||
|
const info: PageInfo = {
|
||||||
|
totalPages: data.Values.totalPages || 0,
|
||||||
|
currentPage: data.Values.currentPage || 0,
|
||||||
|
timestamp: data.Values.timestamp || Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
resolve(info);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
cleanup();
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
window.removeEventListener('message', handleMessage);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('message', handleMessage);
|
||||||
|
|
||||||
|
// 发送请求消息
|
||||||
|
const message = {
|
||||||
|
MessageId: 'custompostMessage',
|
||||||
|
Values: {
|
||||||
|
Command: 'GET_PAGE_INFO',
|
||||||
|
Args: {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
iframeWindow.postMessage(JSON.stringify(message), '*');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 替换功能模块
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { sendUnoCommand } from '../Uno';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 替换文本
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
* @param searchText - 要搜索的文本
|
||||||
|
* @param replaceText - 替换后的文本
|
||||||
|
*/
|
||||||
|
export function unoReplaceText(
|
||||||
|
iframeWindow: Window,
|
||||||
|
searchText: string,
|
||||||
|
replaceText: string
|
||||||
|
): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
||||||
|
'SearchItem.SearchString': { type: 'string', value: searchText },
|
||||||
|
'SearchItem.ReplaceString': { type: 'string', value: replaceText },
|
||||||
|
'SearchItem.Command': { type: 'long', value: 3 }, // 3 = ReplaceAll
|
||||||
|
'SearchItem.AlgorithmType': { type: 'short', value: 0 },
|
||||||
|
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
||||||
|
'SearchItem.Backward': { type: 'boolean', value: false },
|
||||||
|
'Quiet': { type: 'boolean', value: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 搜索功能模块
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { sendUnoCommand } from '../Uno';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 搜索文本
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
* @param text - 要搜索的文本
|
||||||
|
*/
|
||||||
|
export function unoSearchText(iframeWindow: Window, text: string): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:ExecuteSearch', {
|
||||||
|
'SearchItem.SearchString': { type: 'string', value: text },
|
||||||
|
'SearchItem.Command': { type: 'long', value: 1 }, // 1 = Search Next (搜索下一个)
|
||||||
|
'SearchItem.Backward': { type: 'boolean', value: false },
|
||||||
|
'SearchItem.Pattern': { type: 'boolean', value: false },
|
||||||
|
'SearchItem.Content': { type: 'boolean', value: false },
|
||||||
|
'SearchItem.AsianOptions': { type: 'boolean', value: false },
|
||||||
|
'SearchItem.AlgorithmType': { type: 'short', value: 0 }, // 普通搜索
|
||||||
|
'SearchItem.SearchFlags': { type: 'long', value: 0 },
|
||||||
|
'SearchItem.Start': { type: 'boolean', value: true }, // 从头开始搜索
|
||||||
|
'SearchItem.Quiet': { type: 'boolean', value: true }, // 静默模式
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/**
|
||||||
|
* Collabora 缩放功能模块
|
||||||
|
*
|
||||||
|
* @encoding UTF-8
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { sendUnoCommand } from '../Uno';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 放大文档(固定步长)
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
*/
|
||||||
|
export function unoZoomPlus(iframeWindow: Window): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:ZoomPlus', {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缩小文档(固定步长)
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
*/
|
||||||
|
export function unoZoomMinus(iframeWindow: Window): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:ZoomMinus', {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置文档缩放比例
|
||||||
|
* @param iframeWindow - iframe 的 contentWindow
|
||||||
|
* @param percentage - 缩放百分比(例如:100 表示 100%)
|
||||||
|
*/
|
||||||
|
export function unoSetZoom(iframeWindow: Window, percentage: number): void {
|
||||||
|
sendUnoCommand(iframeWindow, '.uno:Zoom', {
|
||||||
|
Zoom: {
|
||||||
|
type: 'short',
|
||||||
|
value: percentage,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -35,3 +35,29 @@ export interface CollaboraViewerProps {
|
|||||||
/** 用户名称 */
|
/** 用户名称 */
|
||||||
userName?: string;
|
userName?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CollaboraViewer 暴露给父组件的方法接口
|
||||||
|
*/
|
||||||
|
export interface CollaboraViewerHandle {
|
||||||
|
/** UNO 命令方法集合 */
|
||||||
|
unoCommands: {
|
||||||
|
searchText: (text: string) => Promise<void>;
|
||||||
|
locateText: (text: string) => Promise<void>;
|
||||||
|
replaceText: (searchText: string, replaceText: string) => Promise<void>;
|
||||||
|
highlightText: (text: string, color?: number) => Promise<void>;
|
||||||
|
removeHighlight: (text: string) => Promise<void>;
|
||||||
|
escapeSelection: () => Promise<void>;
|
||||||
|
scrollToTop: () => Promise<void>;
|
||||||
|
saveDocument: () => Promise<void>;
|
||||||
|
zoomIn: () => Promise<void>;
|
||||||
|
zoomOut: () => Promise<void>;
|
||||||
|
setZoom: (percentage: number) => Promise<void>;
|
||||||
|
};
|
||||||
|
/** 文档是否已加载完成 */
|
||||||
|
isReady: boolean;
|
||||||
|
/** 当前模式 */
|
||||||
|
mode: 'view' | 'edit';
|
||||||
|
/** 获取 iframe 的 contentWindow (用于发送 PostMessage) */
|
||||||
|
getIframeWindow: () => Window | null;
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,7 +5,8 @@
|
|||||||
import { useState, useEffect, useRef, ChangeEvent } from 'react';
|
import { useState, useEffect, useRef, ChangeEvent } from 'react';
|
||||||
import { Document, Page, pdfjs } from 'react-pdf';
|
import { Document, Page, pdfjs } from 'react-pdf';
|
||||||
import { DOCUMENT_URL } from '~/api/axios-client';
|
import { DOCUMENT_URL } from '~/api/axios-client';
|
||||||
import { CollaboraViewer } from '~/components/collabora/CollaboraViewer';
|
import { CollaboraViewer, type CollaboraViewerHandle } from '~/components/collabora/CollaboraViewer';
|
||||||
|
import { requestPageInfo, customGotoPage } from '~/components/collabora/lib';
|
||||||
|
|
||||||
// 导入react-pdf的CSS样式(文本层和注释层必需)
|
// 导入react-pdf的CSS样式(文本层和注释层必需)
|
||||||
import 'react-pdf/dist/esm/Page/TextLayer.css';
|
import 'react-pdf/dist/esm/Page/TextLayer.css';
|
||||||
@@ -89,10 +90,60 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
|
|||||||
const [zoomLevel, setZoomLevel] = useState(100);
|
const [zoomLevel, setZoomLevel] = useState(100);
|
||||||
// const [highlightsVisible, setHighlightsVisible] = useState(true);
|
// const [highlightsVisible, setHighlightsVisible] = useState(true);
|
||||||
const contentRef = useRef<HTMLDivElement>(null);
|
const contentRef = useRef<HTMLDivElement>(null);
|
||||||
|
const collaboraViewerRef = useRef<CollaboraViewerHandle>(null);
|
||||||
const [numPages, setNumPages] = useState<number | null>(null);
|
const [numPages, setNumPages] = useState<number | null>(null);
|
||||||
const [loadError, setLoadError] = useState<string | null>(null);
|
const [loadError, setLoadError] = useState<string | null>(null);
|
||||||
const [pageInputValue, setPageInputValue] = useState<string>('');
|
const [pageInputValue, setPageInputValue] = useState<string>('');
|
||||||
|
|
||||||
|
// 获取文件类型
|
||||||
|
const real_path = fileContent.path || fileContent.template_contract_path || '';
|
||||||
|
const fileExtension = real_path.split('.').pop()?.toLowerCase();
|
||||||
|
const isDocx = fileExtension === 'docx';
|
||||||
|
const isPdf = fileExtension === 'pdf';
|
||||||
|
|
||||||
|
// DOCX 页数获取: 使用 requestPageInfo 方法
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isDocx) return;
|
||||||
|
|
||||||
|
// console.log('[FilePreview] DOCX 文档加载,尝试获取页数');
|
||||||
|
|
||||||
|
let intervalCleared = false;
|
||||||
|
|
||||||
|
// 等待 CollaboraViewer 准备就绪
|
||||||
|
const checkInterval = setInterval(() => {
|
||||||
|
if (intervalCleared) return;
|
||||||
|
|
||||||
|
if (!collaboraViewerRef.current?.isReady) {
|
||||||
|
console.log('[FilePreview] 等待 Collabora 就绪...');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// console.log('[FilePreview] Collabora 已就绪,尝试获取页数');
|
||||||
|
clearInterval(checkInterval);
|
||||||
|
intervalCleared = true;
|
||||||
|
|
||||||
|
const iframeWindow = collaboraViewerRef.current.getIframeWindow?.();
|
||||||
|
if (!iframeWindow) {
|
||||||
|
console.warn('[FilePreview] 无法获取 iframe window');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用 requestPageInfo 获取页数
|
||||||
|
requestPageInfo(iframeWindow)
|
||||||
|
.then((info) => {
|
||||||
|
setNumPages(info.totalPages);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('[FilePreview] 获取 DOCX 页数失败:', error.message);
|
||||||
|
});
|
||||||
|
}, 500);
|
||||||
|
|
||||||
|
// 清理定时器
|
||||||
|
return () => {
|
||||||
|
clearInterval(checkInterval);
|
||||||
|
};
|
||||||
|
}, [isDocx]);
|
||||||
|
|
||||||
// 拖拽状态管理
|
// 拖拽状态管理
|
||||||
const [dragMode, setDragMode] = useState(false); // 是否处于拖拽模式
|
const [dragMode, setDragMode] = useState(false); // 是否处于拖拽模式
|
||||||
const [isDragging, setIsDragging] = useState(false);
|
const [isDragging, setIsDragging] = useState(false);
|
||||||
@@ -101,15 +152,35 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
|
|||||||
|
|
||||||
// 放大文档
|
// 放大文档
|
||||||
const handleZoomIn = () => {
|
const handleZoomIn = () => {
|
||||||
if (zoomLevel < 200) {
|
if (isDocx) {
|
||||||
setZoomLevel(prevZoom => prevZoom + 10);
|
// DOCX 文件:调用 Collabora UNO 命令
|
||||||
|
if (!collaboraViewerRef.current?.isReady) {
|
||||||
|
toastService.warning('文档尚未加载完成,请稍候...');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
collaboraViewerRef.current?.unoCommands.zoomIn();
|
||||||
|
} else if (isPdf) {
|
||||||
|
// PDF 文件:修改 zoomLevel 状态
|
||||||
|
if (zoomLevel < 200) {
|
||||||
|
setZoomLevel(prevZoom => prevZoom + 10);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 缩小文档
|
// 缩小文档
|
||||||
const handleZoomOut = () => {
|
const handleZoomOut = () => {
|
||||||
if (zoomLevel > 50) {
|
if (isDocx) {
|
||||||
setZoomLevel(prevZoom => prevZoom - 10);
|
// DOCX 文件:调用 Collabora UNO 命令
|
||||||
|
if (!collaboraViewerRef.current?.isReady) {
|
||||||
|
toastService.warning('文档尚未加载完成,请稍候...');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
collaboraViewerRef.current?.unoCommands.zoomOut();
|
||||||
|
} else if (isPdf) {
|
||||||
|
// PDF 文件:修改 zoomLevel 状态
|
||||||
|
if (zoomLevel > 50) {
|
||||||
|
setZoomLevel(prevZoom => prevZoom - 10);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -246,22 +317,47 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 处理页码跳转
|
// 处理页码跳转
|
||||||
const handlePageJump = () => {
|
const handlePageJump = async () => {
|
||||||
if (!pageInputValue || !numPages) return;
|
if (!pageInputValue) return;
|
||||||
|
|
||||||
const targetPageNum = parseInt(pageInputValue, 10);
|
const targetPageNum = parseInt(pageInputValue, 10);
|
||||||
|
|
||||||
// 验证页码是否在有效范围内
|
if (isDocx) {
|
||||||
if (targetPageNum > 0 && targetPageNum <= numPages) {
|
// DOCX 文件:调用自定义页面跳转
|
||||||
// 找到目标页面元素并滚动到该位置
|
const iframeWindow = collaboraViewerRef.current?.getIframeWindow?.();
|
||||||
const pageElement = document.getElementById(`page-${targetPageNum}`);
|
if (!iframeWindow) {
|
||||||
if (pageElement) {
|
toastService.warning('文档尚未加载完成,请稍候...');
|
||||||
pageElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetPageNum > 0) {
|
||||||
|
try {
|
||||||
|
await customGotoPage(iframeWindow, targetPageNum);
|
||||||
|
// 跳转成功,清空输入框
|
||||||
|
setPageInputValue('');
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
toastService.error(`跳转失败: ${errorMessage}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
toastService.warning('请输入有效页码');
|
||||||
|
setPageInputValue('');
|
||||||
|
}
|
||||||
|
} else if (isPdf) {
|
||||||
|
// PDF 文件:验证页码并滚动到目标页面
|
||||||
|
if (!numPages) return;
|
||||||
|
|
||||||
|
if (targetPageNum > 0 && targetPageNum <= numPages) {
|
||||||
|
// 找到目标页面元素并滚动到该位置
|
||||||
|
const pageElement = document.getElementById(`page-${targetPageNum}`);
|
||||||
|
if (pageElement) {
|
||||||
|
pageElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 页码超出范围,显示错误信息或重置输入
|
||||||
|
toastService.warning(`请输入有效页码 (1-${numPages})`);
|
||||||
|
setPageInputValue('');
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
// 页码超出范围,显示错误信息或重置输入
|
|
||||||
toastService.warning(`请输入有效页码 (1-${numPages})`);
|
|
||||||
setPageInputValue('');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -289,8 +385,18 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
|
|||||||
|
|
||||||
// 滚动到顶部
|
// 滚动到顶部
|
||||||
const handleScrollToTop = () => {
|
const handleScrollToTop = () => {
|
||||||
if (contentRef.current) {
|
if (isDocx) {
|
||||||
contentRef.current.scrollTo({ top: 0, behavior: 'smooth' });
|
// DOCX 文件:调用 Collabora UNO 命令
|
||||||
|
if (!collaboraViewerRef.current?.isReady) {
|
||||||
|
toastService.warning('文档尚未加载完成,请稍候...');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
collaboraViewerRef.current?.unoCommands.scrollToTop();
|
||||||
|
} else {
|
||||||
|
// PDF 文件:滚动容器到顶部
|
||||||
|
if (contentRef.current) {
|
||||||
|
contentRef.current.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -389,8 +495,6 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
|
|||||||
|
|
||||||
// 渲染文档内容
|
// 渲染文档内容
|
||||||
const renderDocumentContent = () => {
|
const renderDocumentContent = () => {
|
||||||
const real_path = fileContent.path || fileContent.template_contract_path || '';
|
|
||||||
|
|
||||||
// 如果路径无效,显示错误信息
|
// 如果路径无效,显示错误信息
|
||||||
if (!real_path) {
|
if (!real_path) {
|
||||||
if(!fileContent.template_contract_path){
|
if(!fileContent.template_contract_path){
|
||||||
@@ -408,9 +512,7 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
|
|||||||
}
|
}
|
||||||
|
|
||||||
// console.log('real_path',real_path);
|
// console.log('real_path',real_path);
|
||||||
// 获取文件扩展名
|
|
||||||
const fileExtension = real_path.split('.').pop()?.toLowerCase();
|
|
||||||
|
|
||||||
// PDF内容渲染
|
// PDF内容渲染
|
||||||
const renderPdfContent = () => (
|
const renderPdfContent = () => (
|
||||||
<div
|
<div
|
||||||
@@ -474,8 +576,9 @@ export function FilePreview({ fileContent, activeReviewPointResultId, targetPage
|
|||||||
// DOCX文件使用Collabora Online预览
|
// DOCX文件使用Collabora Online预览
|
||||||
return (
|
return (
|
||||||
<CollaboraViewer
|
<CollaboraViewer
|
||||||
|
ref={collaboraViewerRef}
|
||||||
fileId={real_path}
|
fileId={real_path}
|
||||||
mode="view"
|
mode="edit"
|
||||||
userId={userInfo?.sub || 'guest'}
|
userId={userInfo?.sub || 'guest'}
|
||||||
userName={userInfo?.nick_name || '访客'}
|
userName={userInfo?.nick_name || '访客'}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -792,6 +792,7 @@ export default function RolePermissions() {
|
|||||||
type: 'role' | 'userRole';
|
type: 'role' | 'userRole';
|
||||||
role?: RoleInfo;
|
role?: RoleInfo;
|
||||||
user?: UserInfo;
|
user?: UserInfo;
|
||||||
|
userCount?: number; // 删除角色时,关联的用户数量
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
const [deleteCountdown, setDeleteCountdown] = useState(3);
|
const [deleteCountdown, setDeleteCountdown] = useState(3);
|
||||||
|
|
||||||
@@ -899,7 +900,7 @@ export default function RolePermissions() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 删除角色 - 显示确认Modal
|
// 删除角色 - 显示确认Modal
|
||||||
const handleDeleteRole = (role: RoleInfo) => {
|
const handleDeleteRole = async (role: RoleInfo) => {
|
||||||
// 系统角色禁止删除
|
// 系统角色禁止删除
|
||||||
if (role.is_system_role) {
|
if (role.is_system_role) {
|
||||||
toastService.error('系统角色不能删除');
|
toastService.error('系统角色不能删除');
|
||||||
@@ -913,8 +914,12 @@ export default function RolePermissions() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 获取该角色关联的用户数量
|
||||||
|
const users = await getRoleUsers(role.id);
|
||||||
|
const userCount = users.length;
|
||||||
|
|
||||||
// 打开确认删除Modal
|
// 打开确认删除Modal
|
||||||
setDeleteTarget({ type: 'role', role });
|
setDeleteTarget({ type: 'role', role, userCount });
|
||||||
setDeleteCountdown(3);
|
setDeleteCountdown(3);
|
||||||
setShowDeleteConfirm(true);
|
setShowDeleteConfirm(true);
|
||||||
};
|
};
|
||||||
@@ -924,6 +929,7 @@ export default function RolePermissions() {
|
|||||||
if (!deleteTarget || deleteTarget.type !== 'role' || !deleteTarget.role) return;
|
if (!deleteTarget || deleteTarget.type !== 'role' || !deleteTarget.role) return;
|
||||||
|
|
||||||
const role = deleteTarget.role;
|
const role = deleteTarget.role;
|
||||||
|
const userCount = deleteTarget.userCount || 0;
|
||||||
setShowDeleteConfirm(false);
|
setShowDeleteConfirm(false);
|
||||||
setDeleteTarget(null);
|
setDeleteTarget(null);
|
||||||
|
|
||||||
@@ -931,7 +937,12 @@ export default function RolePermissions() {
|
|||||||
const result = await deleteRole(role.id, false);
|
const result = await deleteRole(role.id, false);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
toastService.success(result.message);
|
// 根据是否有用户解绑,显示不同的成功提示
|
||||||
|
if (userCount > 0) {
|
||||||
|
toastService.success(`角色删除成功,已自动解除 ${userCount} 个用户的角色绑定`);
|
||||||
|
} else {
|
||||||
|
toastService.success(result.message);
|
||||||
|
}
|
||||||
// 重新加载数据
|
// 重新加载数据
|
||||||
await loadData();
|
await loadData();
|
||||||
// 如果删除的是当前选中的角色,清除选中状态
|
// 如果删除的是当前选中的角色,清除选中状态
|
||||||
@@ -939,23 +950,7 @@ export default function RolePermissions() {
|
|||||||
setSelectedRole(null);
|
setSelectedRole(null);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 如果有用户关联,询问是否强制删除
|
toastService.error(result.message);
|
||||||
if (result.message.includes('用户')) {
|
|
||||||
if (confirm(result.message + '\n\n是否强制删除并解除所有用户关联?')) {
|
|
||||||
const forceResult = await deleteRole(role.id, true);
|
|
||||||
if (forceResult.success) {
|
|
||||||
toastService.success('角色已强制删除');
|
|
||||||
await loadData();
|
|
||||||
if (selectedRole?.id === role.id) {
|
|
||||||
setSelectedRole(null);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
toastService.error(forceResult.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
toastService.error(result.message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('删除角色失败:', error);
|
console.error('删除角色失败:', error);
|
||||||
@@ -1364,8 +1359,21 @@ export default function RolePermissions() {
|
|||||||
<p style={{ marginBottom: '16px', fontSize: '15px', lineHeight: '1.6' }}>
|
<p style={{ marginBottom: '16px', fontSize: '15px', lineHeight: '1.6' }}>
|
||||||
您确定要删除角色 <strong>"{deleteTarget.role.role_name}"</strong> 吗?
|
您确定要删除角色 <strong>"{deleteTarget.role.role_name}"</strong> 吗?
|
||||||
</p>
|
</p>
|
||||||
|
{deleteTarget.userCount !== undefined && deleteTarget.userCount > 0 && (
|
||||||
|
<p style={{
|
||||||
|
marginBottom: '16px',
|
||||||
|
color: '#ff6b00',
|
||||||
|
fontSize: '14px',
|
||||||
|
padding: '12px',
|
||||||
|
backgroundColor: '#fff7e6',
|
||||||
|
borderLeft: '3px solid #ff6b00',
|
||||||
|
borderRadius: '4px'
|
||||||
|
}}>
|
||||||
|
⚠️ 该角色当前关联了 <strong>{deleteTarget.userCount}</strong> 个用户,删除后将自动解除这些用户的角色绑定。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<p style={{ marginBottom: '16px', color: '#666', fontSize: '14px' }}>
|
<p style={{ marginBottom: '16px', color: '#666', fontSize: '14px' }}>
|
||||||
此操作将永久删除该角色,且无法恢复。
|
此操作将永久删除该角色、相关的权限配置和路由分配,且无法恢复。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
Generated
+317
-774
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user