diff --git a/apps/application/tests/test_workflow_file_access.py b/apps/application/tests/test_workflow_file_access.py index 307cfac1370..326bca98223 100644 --- a/apps/application/tests/test_workflow_file_access.py +++ b/apps/application/tests/test_workflow_file_access.py @@ -53,8 +53,19 @@ def test_own_chat_upload_is_allowed(self): file = _file(FileSourceType.CHAT, CHAT, user_id=USER) self.assertIs(self._get(file, _app_root()), file) - def test_another_users_upload_is_denied(self): - self.assertDenied(_file(FileSourceType.CHAT, CHAT, user_id=OTHER_USER), _app_root()) + def test_another_users_upload_to_root_chat_is_allowed(self): + # 工具等以其他身份上传到根对话的文件:与 OSS 下载一致,能访问该对话即可读取 + file = _file(FileSourceType.CHAT, CHAT, user_id=OTHER_USER) + self.assertIs(self._get(file, _app_root()), file) + self.assertIs(self._get(file, _sub_tool(_app_root(), TOOL_A)), file) + + def test_another_users_upload_to_other_chat_is_denied(self): + self.assertDenied(_file(FileSourceType.CHAT, OTHER_CHAT, user_id=OTHER_USER), _app_root()) + + def test_chat_file_is_denied_outside_application_root(self): + file = _file(FileSourceType.CHAT, CHAT, user_id=OTHER_USER) + self.assertDenied(file, root_context("SYSTEM_USER", USER, WorkflowType.TOOL, TOOL_A)) + self.assertDenied(file, root_context("SYSTEM_USER", USER, WorkflowType.KNOWLEDGE, KNOWLEDGE)) @patch("application.workflow.file_access._is_knowledge_bound", return_value=False) def test_unbound_knowledge_source_file_is_denied(self, _bound): diff --git a/apps/application/tests/test_workflow_reply_file.py b/apps/application/tests/test_workflow_reply_file.py new file mode 100644 index 00000000000..982271768f8 --- /dev/null +++ b/apps/application/tests/test_workflow_reply_file.py @@ -0,0 +1,111 @@ +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +from django.test import SimpleTestCase + +from application.workflow.content_type import ContentType +from application.workflow.message.aggregator.aggregation_manager import AggregationManager +from application.workflow.message.struct.file_content import FileContent +from application.workflow.nodes.reply_node.handle.impl.file_reply import to_file_id_list +from application.workflow.nodes.reply_node.reply_node import ReplyNode, get_reply_handle +from application.workflow.status import Status +from common.exception.app_exception import AppUnauthorizedFailed + +FILE_A = "019a0000-0000-7000-8000-0000000000a1" +FILE_B = "019a0000-0000-7000-8000-0000000000b1" +WORKFLOW_PARAMS = {"root_user_id": "019a0000-0000-7000-8000-0000000000aa"} + + +def _reply_node(node_params, reference_value=None): + node = ReplyNode.__new__(ReplyNode) + node.data = {} + node.context = {} + node.workflow_manage = MagicMock() + node.workflow_manage.get_reference_field.return_value = reference_value + node.workflow_manage.generate_prompt.side_effect = lambda prompt: prompt + node.get_parameters = lambda: node_params + node.get_workflow_parameters = lambda: WORKFLOW_PARAMS + node.get_node_id = lambda: "reply" + node.get_node_name = lambda: "Reply" + node.write_context = lambda key, value: node.context.__setitem__(key, value) + return node + + +def _stored_file(file_id): + return SimpleNamespace(id=file_id, file_name=f"{file_id[-2:]}.png", file_size=10) + + +class FileIdListTest(SimpleTestCase): + def test_accepts_file_objects_urls_and_ids_in_order_without_duplicates(self): + value = [{"file_id": FILE_A, "url": f"./oss/file/{FILE_A}"}, {"url": f"./oss/file/{FILE_B}"}, FILE_A] + self.assertEqual(to_file_id_list(value), [FILE_A, FILE_B]) + + def test_accepts_rendered_text(self): + self.assertEqual(to_file_id_list(str([{"file_id": FILE_A}])), [FILE_A]) + self.assertEqual(to_file_id_list(f'["{FILE_A}", "{FILE_B}"]'), [FILE_A, FILE_B]) + self.assertEqual(to_file_id_list(f"{FILE_A}, ./oss/file/{FILE_B}"), [FILE_A, FILE_B]) + + def test_empty_values(self): + self.assertEqual(to_file_id_list(None), []) + self.assertEqual(to_file_id_list(""), []) + self.assertEqual(to_file_id_list([{"name": "no-id"}]), []) + + +class ReplyFileTest(SimpleTestCase): + def test_unknown_content_type_falls_back_to_text(self): + self.assertTrue(get_reply_handle("UNKNOWN").support("TEXT")) + + @patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file") + def test_file_reply_reads_metadata_from_authorized_files(self, get_authorized_file): + get_authorized_file.side_effect = lambda file_id, params: _stored_file(file_id) + node = _reply_node( + {"reply_type": "referencing", "fields": ["image", "image"], "content_type": "FILE", "is_result": True}, + reference_value=[{"file_id": FILE_A, "url": f"./oss/file/{FILE_A}"}, {"file_id": FILE_B}], + ) + node.execute() + + self.assertEqual( + [call.args for call in get_authorized_file.call_args_list], + [(FILE_A, WORKFLOW_PARAMS), (FILE_B, WORKFLOW_PARAMS)], + ) + expected = [ + {"file_id": FILE_A, "name": "a1.png", "url": f"./oss/file/{FILE_A}", "size": 10}, + {"file_id": FILE_B, "name": "b1.png", "url": f"./oss/file/{FILE_B}", "size": 10}, + ] + self.assertEqual(node.context["answer"], expected) + (message,) = [call.args[0] for call in node.workflow_manage.write.call_args_list] + self.assertIsInstance(message, FileContent) + self.assertEqual(message.to_dict()["file_list"], expected) + + @patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file") + def test_file_reply_rejects_unauthorized_file(self, get_authorized_file): + get_authorized_file.side_effect = AppUnauthorizedFailed(403, "No permission to access") + node = _reply_node({"reply_type": "content", "content": FILE_A, "content_type": "FILE", "is_result": True}) + with self.assertRaises(AppUnauthorizedFailed): + node.execute() + node.workflow_manage.write.assert_not_called() + + @patch("application.workflow.nodes.reply_node.handle.impl.file_reply.get_authorized_file") + def test_file_reply_hidden_when_not_result(self, get_authorized_file): + get_authorized_file.side_effect = lambda file_id, params: _stored_file(file_id) + node = _reply_node({"reply_type": "content", "content": FILE_A, "content_type": "FILE", "is_result": False}) + node.execute() + self.assertEqual(len(node.context["answer"]), 1) + node.workflow_manage.write.assert_not_called() + + def test_file_contents_aggregate_by_id(self): + manager = AggregationManager() + manager.aggregate(FileContent("1", [{"file_id": FILE_A, "name": "a.png"}], Status.RUNNING, None, None)) + manager.aggregate( + FileContent( + "1", + [{"file_id": FILE_B, "name": "b.pdf"}, {"file_id": FILE_A, "name": "a2.png"}], + Status.SUCCESS, + None, + None, + ) + ) + (content,) = manager.get_contents() + self.assertEqual(content["type"], ContentType.FILE.value) + self.assertEqual(content["status"], Status.SUCCESS.value) + self.assertEqual([file["name"] for file in content["file_list"]], ["a2.png", "b.pdf"]) diff --git a/apps/application/workflow/content_type.py b/apps/application/workflow/content_type.py index 45cceee814f..26de4a1d3ae 100644 --- a/apps/application/workflow/content_type.py +++ b/apps/application/workflow/content_type.py @@ -13,6 +13,7 @@ class ContentType(Enum): TEXT = "TEXT" HTML = "HTML" + FILE = "FILE" REASONING = "REASONING" FAILURE = "FAILURE" TOOL = "TOOL" diff --git a/apps/application/workflow/file_access.py b/apps/application/workflow/file_access.py index ebc956a190e..14ee7978afd 100644 --- a/apps/application/workflow/file_access.py +++ b/apps/application/workflow/file_access.py @@ -115,6 +115,15 @@ def _in_root_resource(file, workflow_params): and str(file.source_id) == str(resource_id) and (file.meta or {}).get("chat_id") in (None, root_chat_id) ) + if file.source_type == FileSourceType.CHAT: + # 根对话的文件(含工具等以其他身份上传到该对话的文件):入口已校验根对话归属发起者, + # 与 OSS 下载「能访问该对话即可访问其文件」一致 + root_chat_id = workflow_params.get("root_chat_id") + return ( + resource_type == ResourceType.APPLICATION + and bool(root_chat_id) + and str(file.source_id) == str(root_chat_id) + ) if file.source_type == FileSourceType.TOOL: return resource_type == ResourceType.TOOL and str(file.source_id) == str(resource_id) knowledge_id = _get_file_knowledge_id(file) @@ -129,7 +138,7 @@ def get_authorized_file(file_id, workflow_params): """ 工作流节点读取文件的唯一入口。允许: 1. 发起者本人上传的文件,或本次运行(含嵌套子工作流)生成的文件 - 2. 根资源的文件(应用当前对话的文件、知识库文件、根应用/工具关联知识库的文件), + 2. 根资源的文件(应用当前对话的文件,含他人身份上传到该对话的文件、知识库文件、根应用/工具关联知识库的文件), 但他人运行时生成的工具/应用文件除外 """ workflow_params = workflow_params or {} diff --git a/apps/application/workflow/message/aggregator/aggregator_factory.py b/apps/application/workflow/message/aggregator/aggregator_factory.py index b0d582a0924..854518e3fe9 100644 --- a/apps/application/workflow/message/aggregator/aggregator_factory.py +++ b/apps/application/workflow/message/aggregator/aggregator_factory.py @@ -9,11 +9,12 @@ from typing import Dict, Type, Optional from application.workflow.message.aggregator.content_aggregator import ContentAggregator -from application.workflow.message.aggregator.impl import FormAggregator, HtmlAggregator +from application.workflow.message.aggregator.impl import FileAggregator, FormAggregator, HtmlAggregator from application.workflow.message.aggregator.impl.reasoning_aggregator import ReasoningAggregator from application.workflow.message.aggregator.impl.text_aggregator import TextAggregator from application.workflow.message.aggregator.impl.tool_aggregator import ToolAggregator from application.workflow.message.struct.content import Content +from application.workflow.message.struct.file_content import FileContent from application.workflow.message.struct.form_content import FormContent from application.workflow.message.struct.html_content import HtmlContent from application.workflow.message.struct.reasoning_content import ReasoningContent @@ -33,6 +34,7 @@ class AggregatorFactory: ToolContent: ToolAggregator(), FormContent: FormAggregator(), HtmlContent: HtmlAggregator(), + FileContent: FileAggregator(), } @classmethod diff --git a/apps/application/workflow/message/aggregator/impl/__init__.py b/apps/application/workflow/message/aggregator/impl/__init__.py index 66969800a6b..04ca7479309 100644 --- a/apps/application/workflow/message/aggregator/impl/__init__.py +++ b/apps/application/workflow/message/aggregator/impl/__init__.py @@ -11,5 +11,13 @@ from application.workflow.message.aggregator.impl.tool_aggregator import ToolAggregator from application.workflow.message.aggregator.impl.form_aggregator import FormAggregator from application.workflow.message.aggregator.impl.html_aggregator import HtmlAggregator +from application.workflow.message.aggregator.impl.file_aggregator import FileAggregator -__all__ = ["TextAggregator", "ReasoningAggregator", "ToolAggregator", "FormAggregator", "HtmlAggregator"] +__all__ = [ + "TextAggregator", + "ReasoningAggregator", + "ToolAggregator", + "FormAggregator", + "HtmlAggregator", + "FileAggregator", +] diff --git a/apps/application/workflow/message/aggregator/impl/file_aggregator.py b/apps/application/workflow/message/aggregator/impl/file_aggregator.py new file mode 100644 index 00000000000..d7fbbd3f498 --- /dev/null +++ b/apps/application/workflow/message/aggregator/impl/file_aggregator.py @@ -0,0 +1,38 @@ +# coding=utf-8 +""" +@project: MaxKB +@file: file_aggregator.py +@date:2026/12/4 +@desc: FileContent 聚合器 +""" + +from application.workflow.message.aggregator.content_aggregator import ContentAggregator +from application.workflow.message.struct.file_content import FileContent + + +def _file_key(file: dict): + return file.get("file_id") or file.get("url") + + +class FileAggregator(ContentAggregator[FileContent]): + """ + 文件内容聚合器 + 按顺序追加文件,file_id(无则 url)相同的文件后到覆盖先到 + """ + + def aggregate(self, prev: FileContent, chunk: FileContent) -> FileContent: + if prev is None: + return chunk + file_list = list(prev.file_list) + key_to_index = {_file_key(file): index for index, file in enumerate(file_list) if _file_key(file)} + for file in chunk.file_list: + key = _file_key(file) + if key and key in key_to_index: + file_list[key_to_index[key]] = file + else: + if key: + key_to_index[key] = len(file_list) + file_list.append(file) + result = FileContent(prev.id, file_list, prev.status, prev.node_info, prev.position) + self.merge_base_fields(prev, chunk, result) + return result diff --git a/apps/application/workflow/message/struct/file_content.py b/apps/application/workflow/message/struct/file_content.py new file mode 100644 index 00000000000..f1187944936 --- /dev/null +++ b/apps/application/workflow/message/struct/file_content.py @@ -0,0 +1,41 @@ +# coding=utf-8 +""" +@project: MaxKB +@Author:虎虎 +@file: file_content.py +@date:2026/12/4 +@desc: 文件内容,前端按文件类型渲染(图片预览、音视频播放、其他文件下载) +""" + +from typing import Dict, List, Optional + +from application.workflow.content_type import ContentType +from application.workflow.message.struct.content import Content, NodeInfo, Position +from application.workflow.status import Status + + +class FileContent(Content): + """ + file_list 中每一项: + file_id: 文件 id + name: 文件名(前端据扩展名决定图标与渲染方式) + url: 访问地址 + size: 文件大小(字节,可选) + """ + + def __init__( + self, + _id, + file_list: Optional[List[Dict]], + status: Status, + node_info: NodeInfo, + position: Position, + **kwargs, + ): + self.file_list = list(file_list or []) + super().__init__(_id, status, ContentType.FILE, node_info, position, **kwargs) + + def to_dict(self): + result = super().to_dict() + result["file_list"] = self.file_list + return result diff --git a/apps/application/workflow/nodes/reply_node/handle/__init__.py b/apps/application/workflow/nodes/reply_node/handle/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/apps/application/workflow/nodes/reply_node/handle/impl/__init__.py b/apps/application/workflow/nodes/reply_node/handle/impl/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/apps/application/workflow/nodes/reply_node/handle/impl/file_reply.py b/apps/application/workflow/nodes/reply_node/handle/impl/file_reply.py new file mode 100644 index 00000000000..1b3796ec257 --- /dev/null +++ b/apps/application/workflow/nodes/reply_node/handle/impl/file_reply.py @@ -0,0 +1,98 @@ +# coding=utf-8 +""" +@project: MaxKB +@Author:虎虎 +@file: file_reply.py +@date:2026/12/4 +@desc: 文件回复:按 file_id 鉴权后从文件表取文件名与大小,前端按扩展名渲染 +""" + +import ast +import json +import re +from typing import List + +import uuid_utils.compat as uuid + +from application.workflow.file_access import get_authorized_file +from application.workflow.message.struct.content import Content, NodeInfo, Position +from application.workflow.message.struct.file_content import FileContent +from application.workflow.nodes.reply_node.handle.reply_base_handle import ReplyBaseHandle +from application.workflow.status import Status + +OSS_FILE_PREFIX = "/oss/file/" + + +def _parse_text(text: str): + """回复文本可能是 JSON、Python 字面量(模板渲染列表/字典)或以逗号、空白分隔的 file_id / 文件地址""" + text = text.strip() + if not text: + return [] + for parse in (json.loads, ast.literal_eval): + try: + parsed = parse(text) + except (ValueError, SyntaxError): + continue + if not isinstance(parsed, str): + return parsed + return [token for token in re.split(r"[\s,]+", text) if token] + + +def _token_to_file_id(token: str): + token = token.strip() + if OSS_FILE_PREFIX in token: + token = token.split(OSS_FILE_PREFIX, 1)[1].split("?", 1)[0].split("/", 1)[0] + return token or None + + +def to_file_id_list(value): + """ + 把回复值归一化为 file_id 列表(保持顺序、去重)。 + 支持 file_id、./oss/file/{file_id} 地址、带 file_id/url 的文件对象,以及它们组成的列表或其文本形式。 + """ + file_id_list = [] + + def collect(item): + if item is None: + return + if isinstance(item, (list, tuple)): + for child in item: + collect(child) + elif isinstance(item, dict): + if item.get("file_id"): + collect(str(item.get("file_id"))) + elif isinstance(item.get("url"), str): + collect(item.get("url")) + elif isinstance(item, str): + file_id = _token_to_file_id(item) + if file_id and file_id not in file_id_list: + file_id_list.append(file_id) + + collect(_parse_text(value) if isinstance(value, str) else value) + return file_id_list + + +class FileReply(ReplyBaseHandle): + def support(self, content_type: str) -> bool: + return content_type == "FILE" + + def get_answer(self, node, value): + workflow_params = node.get_workflow_parameters() + file_list = [] + for file_id in to_file_id_list(value): + # 与图片理解等节点一致:只允许发起者本人或根资源的文件,无权限直接拒绝 + file = get_authorized_file(file_id, workflow_params) + file_list.append( + { + "file_id": str(file.id), + "name": file.file_name, + "url": f"./oss/file/{file.id}", + "size": file.file_size, + } + ) + return file_list + + def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]: + if not answer: + return [] + return [FileContent(str(uuid.uuid7()), answer, Status.SUCCESS, node_info, position)] diff --git a/apps/application/workflow/nodes/reply_node/handle/impl/html_reply.py b/apps/application/workflow/nodes/reply_node/handle/impl/html_reply.py new file mode 100644 index 00000000000..3cd732837cc --- /dev/null +++ b/apps/application/workflow/nodes/reply_node/handle/impl/html_reply.py @@ -0,0 +1,28 @@ +# coding=utf-8 +""" +@project: MaxKB +@Author:虎虎 +@file: html_reply.py +@date:2026/12/4 +@desc: HTML 回复,前端在沙箱 iframe 中渲染 +""" + +from typing import List + +import uuid_utils.compat as uuid + +from application.workflow.message.struct.content import Content, NodeInfo, Position +from application.workflow.message.struct.html_content import HtmlContent +from application.workflow.nodes.reply_node.handle.reply_base_handle import ReplyBaseHandle, to_text +from application.workflow.status import Status + + +class HtmlReply(ReplyBaseHandle): + def support(self, content_type: str) -> bool: + return content_type == "HTML" + + def get_answer(self, node, value): + return to_text(value) + + def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]: + return [HtmlContent(str(uuid.uuid7()), answer, Status.SUCCESS, node_info, position)] diff --git a/apps/application/workflow/nodes/reply_node/handle/impl/text_reply.py b/apps/application/workflow/nodes/reply_node/handle/impl/text_reply.py new file mode 100644 index 00000000000..1b7d2c56c0c --- /dev/null +++ b/apps/application/workflow/nodes/reply_node/handle/impl/text_reply.py @@ -0,0 +1,28 @@ +# coding=utf-8 +""" +@project: MaxKB +@Author:虎虎 +@file: text_reply.py +@date:2026/12/4 +@desc: 文本回复 +""" + +from typing import List + +import uuid_utils.compat as uuid + +from application.workflow.message.struct.content import Content, NodeInfo, Position +from application.workflow.message.struct.text_content import TextContent +from application.workflow.nodes.reply_node.handle.reply_base_handle import ReplyBaseHandle, to_text +from application.workflow.status import Status + + +class TextReply(ReplyBaseHandle): + def support(self, content_type: str) -> bool: + return content_type == "TEXT" + + def get_answer(self, node, value): + return to_text(value) + + def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]: + return [TextContent(str(uuid.uuid7()), answer, Status.SUCCESS, node_info, position)] diff --git a/apps/application/workflow/nodes/reply_node/handle/impl/tool_reply.py b/apps/application/workflow/nodes/reply_node/handle/impl/tool_reply.py new file mode 100644 index 00000000000..b9136cebef7 --- /dev/null +++ b/apps/application/workflow/nodes/reply_node/handle/impl/tool_reply.py @@ -0,0 +1,76 @@ +# coding=utf-8 +""" +@project: MaxKB +@Author:虎虎 +@file: tool_reply.py +@date:2026/12/4 +@desc: 工具调用回复,输出为工具卡片 +""" + +import json +from typing import List + +import uuid_utils.compat as uuid +from django.utils.translation import gettext_lazy as _ + +from application.workflow.message.struct.content import Content, NodeInfo, Position +from application.workflow.message.struct.tool_content import ToolContent +from application.workflow.nodes.reply_node.handle.reply_base_handle import ReplyBaseHandle, to_text +from application.workflow.status import Status + + +def _to_json_text(value): + if value is None: + return "" + return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) + + +def _first(item: dict, *keys): + for key in keys: + if item.get(key) is not None: + return item.get(key) + return None + + +def to_tool_list(value): + """ + 把工具回复内容归一化为工具调用列表。 + 支持对象或对象数组(或其 JSON 字符串),元素字段: + id 调用id(缺省自动生成) / name 函数名 / arguments 参数 / content 工具结果; + 同时兼容 toolName、functionArguments、function_name、function_arguments、result 写法。 + """ + if isinstance(value, str): + try: + value = json.loads(value) if value.strip() else [] + except ValueError: + raise Exception(_("Tool reply content must be a JSON object or array")) + if isinstance(value, dict): + value = [value] + if not isinstance(value, list): + raise Exception(_("Tool reply content must be a JSON object or array")) + return [ + { + "id": to_text(item.get("id")) or str(uuid.uuid7()), + "name": to_text(_first(item, "name", "toolName", "tool_name", "function_name")), + "arguments": _to_json_text(_first(item, "arguments", "functionArguments", "function_arguments")), + "content": _to_json_text(_first(item, "content", "result")), + } + for item in value + if isinstance(item, dict) + ] + + +class ToolReply(ReplyBaseHandle): + def support(self, content_type: str) -> bool: + return content_type == "TOOL" + + def get_answer(self, node, value): + return to_tool_list(value) + + def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]: + return [ + ToolContent( + tool["id"], tool["name"], tool["arguments"], tool["content"], Status.SUCCESS, node_info, position + ) + for tool in answer + ] diff --git a/apps/application/workflow/nodes/reply_node/handle/reply_base_handle.py b/apps/application/workflow/nodes/reply_node/handle/reply_base_handle.py new file mode 100644 index 00000000000..231eace0776 --- /dev/null +++ b/apps/application/workflow/nodes/reply_node/handle/reply_base_handle.py @@ -0,0 +1,37 @@ +# coding=utf-8 +""" +@project: MaxKB +@Author:虎虎 +@file: reply_base_handle.py +@date:2026/12/4 +@desc: 指定回复内容处理器:每种回复格式(content_type)一个实现 +""" + +from abc import ABC, abstractmethod +from typing import List + +from application.workflow.message.struct.content import Content, NodeInfo, Position + + +class ReplyBaseHandle(ABC): + @abstractmethod + def support(self, content_type: str) -> bool: + pass + + @abstractmethod + def get_answer(self, node, value): + """ + 把回复值归一化为节点输出 answer + @param node: 指定回复节点 + @param value: 引用变量的值或渲染后的回复文本 + """ + pass + + @abstractmethod + def to_content_list(self, answer, node_info: NodeInfo, position: Position) -> List[Content]: + """把 answer 转换为输出给前端的内容""" + pass + + +def to_text(value): + return "" if value is None else str(value) diff --git a/apps/application/workflow/nodes/reply_node/reply_node.py b/apps/application/workflow/nodes/reply_node/reply_node.py index 9051c49fb49..b94d845246e 100644 --- a/apps/application/workflow/nodes/reply_node/reply_node.py +++ b/apps/application/workflow/nodes/reply_node/reply_node.py @@ -7,10 +7,8 @@ @desc: """ -import json from typing import List -import uuid_utils.compat as uuid from django.utils.translation import gettext_lazy as _ from rest_framework import serializers @@ -18,84 +16,51 @@ from application.workflow.content_type import ContentType from application.workflow.i_node import INode from application.workflow.message.struct.content import Content, NodeInfo, Position -from application.workflow.message.struct.html_content import HtmlContent -from application.workflow.message.struct.text_content import TextContent -from application.workflow.message.struct.tool_content import ToolContent +from application.workflow.nodes.reply_node.handle.impl.file_reply import FileReply +from application.workflow.nodes.reply_node.handle.impl.html_reply import HtmlReply +from application.workflow.nodes.reply_node.handle.impl.text_reply import TextReply +from application.workflow.nodes.reply_node.handle.impl.tool_reply import ToolReply +from application.workflow.nodes.reply_node.handle.reply_base_handle import ReplyBaseHandle from application.workflow.status import Status +# 回复格式处理器,未匹配时按文本回复 +reply_handles: List[ReplyBaseHandle] = [TextReply(), HtmlReply(), ToolReply(), FileReply()] +default_reply_handle = reply_handles[0] + + +def get_reply_handle(content_type: str) -> ReplyBaseHandle: + return next((handle for handle in reply_handles if handle.support(content_type)), default_reply_handle) + class ReplyNodeSerializer(serializers.Serializer): reply_type = serializers.CharField(required=True, label=_("Response Type")) - # 输出内容类型:TEXT 文本(默认) / HTML / TOOL 工具调用 + # 输出内容类型:TEXT 文本(默认) / HTML / TOOL 工具调用 / FILE 文件 content_type = serializers.ChoiceField( - required=False, default="TEXT", choices=["TEXT", "HTML", "TOOL"], label=_("Content Type") + required=False, default="TEXT", choices=["TEXT", "HTML", "TOOL", "FILE"], label=_("Content Type") ) fields = serializers.ListField(required=False, label=_("Reference Field")) content = serializers.CharField(required=False, allow_blank=True, allow_null=True, label=_("Direct answer content")) is_result = serializers.BooleanField(required=False, label=_("Whether to return content")) -def _to_text(value): - return "" if value is None else str(value) - - -def _to_json_text(value): - if value is None: - return "" - return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) - - -def _first(item: dict, *keys): - for key in keys: - if item.get(key) is not None: - return item.get(key) - return None - - -def _to_tool_list(value): - """ - 把工具回复内容归一化为工具调用列表。 - 支持对象或对象数组(或其 JSON 字符串),元素字段: - id 调用id(缺省自动生成) / name 函数名 / arguments 参数 / content 工具结果; - 同时兼容 toolName、functionArguments、function_name、function_arguments、result 写法。 - """ - if isinstance(value, str): - try: - value = json.loads(value) if value.strip() else [] - except ValueError: - raise Exception(_("Tool reply content must be a JSON object or array")) - if isinstance(value, dict): - value = [value] - if not isinstance(value, list): - raise Exception(_("Tool reply content must be a JSON object or array")) - return [ - { - "id": _to_text(item.get("id")) or str(uuid.uuid7()), - "name": _to_text(_first(item, "name", "toolName", "tool_name", "function_name")), - "arguments": _to_json_text(_first(item, "arguments", "functionArguments", "function_arguments")), - "content": _to_json_text(_first(item, "content", "result")), - } - for item in value - if isinstance(item, dict) - ] - - class ReplyNode(INode): serializer_class = ReplyNodeSerializer supported_workflow_type_list = [WorkflowType.APPLICATION, WorkflowType.KNOWLEDGE, WorkflowType.TOOL] type = "reply-node" def write(self, message: Content): - """is_result 关闭时不向用户输出回复内容(文本/HTML/工具)""" - if message.type in (ContentType.TEXT, ContentType.HTML, ContentType.TOOL) and not self.get_parameters().get( - "is_result", False - ): + """is_result 关闭时不向用户输出回复内容(文本/HTML/工具/文件)""" + if message.type in ( + ContentType.TEXT, + ContentType.HTML, + ContentType.TOOL, + ContentType.FILE, + ) and not self.get_parameters().get("is_result", False): return super().write(message) def execute(self): node_params = self.get_parameters() - chunk_id = uuid.uuid7() reply_type = node_params.get("reply_type") fields = node_params.get("fields") @@ -110,27 +75,11 @@ def execute(self): node_info = NodeInfo(self.get_node_id(), self.get_node_name(), Status.SUCCESS) position = Position(self.get_node_id()) - if content_type == "TOOL": - tool_list = _to_tool_list(value) - self.write_context("answer", tool_list) - for tool in tool_list: - self.write( - ToolContent( - tool["id"], - tool["name"], - tool["arguments"], - tool["content"], - Status.SUCCESS, - node_info, - position, - ) - ) - return - - result = _to_text(value) - self.write_context("answer", result) - content_class = HtmlContent if content_type == "HTML" else TextContent - self.write(content_class(str(chunk_id), result, Status.SUCCESS, node_info, position)) + reply_handle = get_reply_handle(content_type) + answer = reply_handle.get_answer(self, value) + self.write_context("answer", answer) + for content_item in reply_handle.to_content_list(answer, node_info, position): + self.write(content_item) def _generate_reply_content(self, prompt): if prompt is None: diff --git a/apps/chat/serializers/chat.py b/apps/chat/serializers/chat.py index b0adda63e08..5f97c0127b0 100644 --- a/apps/chat/serializers/chat.py +++ b/apps/chat/serializers/chat.py @@ -501,7 +501,7 @@ def valid_limit(self): 额度校验:token 配额 + 当日访问次数。失败由 chat 落库并按对话格式返回。 访问次数校验会占用一次计数,放在最后,避免被其它校验拒绝的请求白白扣次数。 """ - ChatUserTokenQuota.check_available(self.data.get("chat_user_id")) + # ChatUserTokenQuota.check_available(self.data.get("chat_user_id")) self.is_valid_intraday_access_num() def save_failure_record(self, instance: dict, chat_record_id, block: dict): diff --git a/apps/common/tests/test_messages_util.py b/apps/common/tests/test_messages_util.py index 4055ca32c09..4a607b3e992 100644 --- a/apps/common/tests/test_messages_util.py +++ b/apps/common/tests/test_messages_util.py @@ -3,7 +3,7 @@ from django.test import SimpleTestCase from langchain_core.messages import AIMessage, ToolMessage -from common.utils.messages_util import to_ai_message_list +from common.utils.messages_util import filter_tool_messages, to_ai_message_list class ToAiMessageListTests(SimpleTestCase): @@ -57,3 +57,22 @@ def test_no_content_returns_fallback_message(self): self.assertEqual(len(result), 1) self.assertIsInstance(result[0], AIMessage) self.assertTrue(result[0].content) + + +class FilterToolMessagesTests(SimpleTestCase): + def test_keeps_only_upload_tool_calls_in_order(self): + upload_a = {"type": "TOOL", "id": "a", "name": "upload", "arguments": "{}", "content": "ok"} + upload_b = {"type": "TOOL", "id": "b", "name": "upload", "arguments": "{}", "content": "ok"} + messages = [ + {"type": "TEXT", "content": "upload"}, + upload_a, + {"type": "TOOL", "id": "c", "name": "search", "arguments": "{}", "content": ""}, + "not a dict", + upload_b, + ] + self.assertEqual(filter_tool_messages(messages), [upload_a, upload_b]) + + def test_custom_name_and_empty_messages(self): + search = {"type": "TOOL", "name": "search"} + self.assertEqual(filter_tool_messages([search], "search"), [search]) + self.assertEqual(filter_tool_messages(None), []) diff --git a/apps/common/utils/messages_util.py b/apps/common/utils/messages_util.py index 02be36ffe29..5ab3238e638 100644 --- a/apps/common/utils/messages_util.py +++ b/apps/common/utils/messages_util.py @@ -83,3 +83,14 @@ def to_ai_message_list(messages): ) ] return ai_message_list + + +def filter_tool_messages(messages, tool_name="upload"): + """ + 过滤出 messages 中函数名为 tool_name 的工具调用内容块(type=TOOL),保持原顺序。 + """ + return [ + message + for message in messages or [] + if isinstance(message, dict) and message.get("type") == "TOOL" and message.get("name") == tool_name + ] diff --git a/ui/package.json b/ui/package.json index 8a03f65d6d6..62de1f8c3a0 100644 --- a/ui/package.json +++ b/ui/package.json @@ -16,6 +16,7 @@ "format": "prettier --write --experimental-cli src/" }, "dependencies": { + "@aiden0z/pptx-renderer": "^1.4.0", "@antv/layout": "^2.0.0", "@codemirror/lang-json": "^6.0.2", "@codemirror/lang-python": "^6.2.1", @@ -35,13 +36,16 @@ "cropperjs": "^1.6.3", "dayjs": "^1.11.23", "dingtalk-jsapi": "^3.2.9", + "docx-preview": "^0.4.1", "dompurify": "^3.4.14", "echarts": "^6.1.0", "element-plus": "2.14.8", + "exceljs": "^4.4.0", "highlight.js": "^11.12.0", "html-to-image": "^1.11.13", "jsencrypt": "^3.5.4", "jspdf": "^4.2.1", + "jszip": "^3.10.2", "katex": "^0.16.47", "lodash": "^4.18.1", "marked": "^18.2.0", diff --git a/ui/src/api/types/chat-log.ts b/ui/src/api/types/chat-log.ts index ece89c0e193..42d6de63cb9 100644 --- a/ui/src/api/types/chat-log.ts +++ b/ui/src/api/types/chat-log.ts @@ -26,6 +26,14 @@ export interface ChatLog { update_time: string } +/** FILE 内容项中的单个文件,渲染方式由文件名扩展名决定。 */ +export interface ChatFile { + file_id?: string + name: string + url?: string + size?: number +} + /** 历史消息与流式分片共用的内容项,未约定的扩展字段保留为 unknown。 */ export interface ChatContent { type: string @@ -43,6 +51,7 @@ export interface ChatContent { is_submit?: boolean position?: unknown chat_record_id?: string + file_list?: ChatFile[] [key: string]: unknown } diff --git a/ui/src/assets/file-type/pptx-icon.svg b/ui/src/assets/file-type/pptx-icon.svg new file mode 100644 index 00000000000..9389568f484 --- /dev/null +++ b/ui/src/assets/file-type/pptx-icon.svg @@ -0,0 +1 @@ + diff --git a/ui/src/conversation-panel/components/content-list/index.vue b/ui/src/conversation-panel/components/content-list/index.vue index e7a5bbdc778..44a81e3bc96 100644 --- a/ui/src/conversation-panel/components/content-list/index.vue +++ b/ui/src/conversation-panel/components/content-list/index.vue @@ -14,11 +14,12 @@ interface ContentItem { const props = defineProps<{ contentList: ContentItem[] }>() -// 隐藏审批和空正文;sort 为稳定排序,相同 id 的内容保留原始顺序。 +// 隐藏审批、空正文和空文件列表;sort 为稳定排序,相同 id 的内容保留原始顺序。 const displayContents = computed(() => { const sortedContents = props.contentList .filter((content) => { if (content.type === 'APPROVAL') return false + if (content.type === 'FILE') return Array.isArray(content.file_list) && content.file_list.length > 0 return !((content.type === 'TEXT' || content.type === 'HTML') && !content.content) }) .sort((leftContent, rightContent) => (leftContent.id || '').localeCompare(rightContent.id || '')) diff --git a/ui/src/conversation-panel/components/content/index.vue b/ui/src/conversation-panel/components/content/index.vue index d507ad5bfb4..eba1b42154c 100644 --- a/ui/src/conversation-panel/components/content/index.vue +++ b/ui/src/conversation-panel/components/content/index.vue @@ -3,6 +3,7 @@ import { computed } from 'vue' import type { Component } from 'vue' import EchartsItem from './items/echarts.vue' import FailureItem from './items/failure.vue' +import FileItem from './items/file.vue' import FormItem from './items/form.vue' import GroupToolItem from './items/group-tool/index.vue' import GroupItem from './items/group/index.vue' @@ -21,6 +22,7 @@ const props = defineProps<{ const typeRenderers: Partial> = { TEXT: TextItem, HTML: HtmlItem, + FILE: FileItem, ECHARTS: EchartsItem, REASONING: ReasoningItem, TOOL: ToolItem, diff --git a/ui/src/conversation-panel/components/content/items/file.vue b/ui/src/conversation-panel/components/content/items/file.vue new file mode 100644 index 00000000000..aefbd55d02a --- /dev/null +++ b/ui/src/conversation-panel/components/content/items/file.vue @@ -0,0 +1,98 @@ + + + diff --git a/ui/src/conversation-panel/core/aggregators.ts b/ui/src/conversation-panel/core/aggregators.ts index 0f418120c15..01c7f676bd8 100644 --- a/ui/src/conversation-panel/core/aggregators.ts +++ b/ui/src/conversation-panel/core/aggregators.ts @@ -1,4 +1,4 @@ -import type { ChatContent } from '@/api/types' +import type { ChatContent, ChatFile } from '@/api/types' interface ContentAggregator { // 分片提供 id 时,所有聚合器均优先保留该 id,供调用方继续使用稳定消息键。 @@ -6,7 +6,7 @@ interface ContentAggregator { (previous: Partial | undefined, chunk: Partial): ChatContent } -// 流式分片聚合:按 id+type 把分片累积成一条内容项(TEXT/REASONING/FAILURE/TOOL/FORM/PROGRESS/GROUP)。 +// 流式分片聚合:按 id+type 把分片累积成一条内容项(TEXT/REASONING/FAILURE/TOOL/FORM/PROGRESS/GROUP/HTML/FILE)。 // GROUP 为通用分组容器,分片以嵌套 children 携带组内内容,组内同样按 id+type 合并(可再嵌套 GROUP)。 const TEXT = (prev: Partial = {}, chunk: Partial) => { return { @@ -111,6 +111,28 @@ const HTML = (prev: Partial = {}, chunk: Partial) => { extra: chunk.extra ?? prev.extra, } } +// 文件按 file_id(无则 url)去重,后到的覆盖先到的,其余按顺序追加 +const mergeFiles = (files: ChatFile[] = [], chunkFiles: ChatFile[] = []): ChatFile[] => { + const mergedFiles = [...files] + chunkFiles.forEach((file) => { + const fileKey = file.file_id ?? file.url + const index = fileKey ? mergedFiles.findIndex((mergedFile) => (mergedFile.file_id ?? mergedFile.url) === fileKey) : -1 + if (index >= 0) mergedFiles[index] = file + else mergedFiles.push(file) + }) + return mergedFiles +} + +const FILE = (prev: Partial = {}, chunk: Partial) => { + return { + type: 'FILE', + id: chunk.id ?? prev.id, + file_list: mergeFiles(prev.file_list, chunk.file_list), + status: chunk.status ?? prev.status, + workflowRunId: chunk.workflowRunId ?? prev.workflowRunId, + extra: chunk.extra ?? prev.extra, + } +} export const aggregators = { TEXT, REASONING, @@ -119,5 +141,6 @@ export const aggregators = { FORM, PROGRESS, GROUP, - HTML + HTML, + FILE, } as Record diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/components/sheet-table/index.ts b/ui/src/conversation-panel/right-sidebar/file-preview/components/sheet-table/index.ts new file mode 100644 index 00000000000..877ac46b961 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/components/sheet-table/index.ts @@ -0,0 +1,79 @@ +import type { EChartsCoreOption } from 'echarts/core' +import type { CSSProperties } from 'vue' + +/** 预览只展示每个工作表的前若干行列,完整内容需下载查看。 */ +export const SPREADSHEET_PREVIEW_MAX_ROWS = 500 +export const SPREADSHEET_PREVIEW_MAX_COLUMNS = 100 + +export interface SpreadsheetColumn { + /** 列标题 A、B、C… */ + label: string + /** 列宽(px),CSV 按内容自适应时不设置 */ + width?: number +} + +/** 单元格:被合并单元格覆盖的格子不出现在行中。 */ +export interface SpreadsheetCell { + /** 所在列标题,作为渲染 key */ + key: string + text: string + colSpan?: number + rowSpan?: number + /** 填充、边框、字体,作用于表格单元格 */ + style?: CSSProperties + /** 尺寸、对齐、换行,作用于单元格内容 */ + contentStyle?: CSSProperties +} + +export interface SpreadsheetRow { + /** 行号 */ + label: string + /** 固定行高(px),未设置时随内容撑开 */ + height?: number + cells: SpreadsheetCell[] +} + +/** 浮动对象的锚点:所在的已渲染行、列序号(从 0 开始)及在该单元格内的偏移(px)。 */ +export interface SpreadsheetAnchor { + rowIndex: number + columnIndex: number + x: number + y: number +} + +/** 工作表上的浮动图表或图片。 */ +export interface SpreadsheetDrawing { + key: string + from: SpreadsheetAnchor + /** 双单元格锚点的终点,尺寸随行列变化;没有终点时使用 width / height */ + to?: SpreadsheetAnchor + width: number + height: number + /** 图表的 ECharts 配置 */ + chart?: EChartsCoreOption + /** 图表区背景与边框 */ + style?: CSSProperties + /** 图片 data URL */ + image?: string +} + +/** 预览用的工作表数据,单元格已转换为展示文本。 */ +export interface SpreadsheetSheet { + name: string + columns: SpreadsheetColumn[] + rows: SpreadsheetRow[] + truncated: boolean + /** xlsx 按原始列宽与单元格格式绘制;CSV 按内容自适应 */ + styled: boolean + showGridLines: boolean + drawings: SpreadsheetDrawing[] +} + +/** 列序号(从 1 开始)转为 Excel 列名。 */ +export function toColumnLabel(columnNumber: number): string { + let label = '' + for (let rest = columnNumber; rest > 0; rest = Math.floor((rest - 1) / 26)) { + label = String.fromCharCode(65 + ((rest - 1) % 26)) + label + } + return label +} diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/components/sheet-table/index.vue b/ui/src/conversation-panel/right-sidebar/file-preview/components/sheet-table/index.vue new file mode 100644 index 00000000000..44ce6417205 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/components/sheet-table/index.vue @@ -0,0 +1,187 @@ + + + + + diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/index.ts b/ui/src/conversation-panel/right-sidebar/file-preview/index.ts new file mode 100644 index 00000000000..ff25d4ecd5b --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/index.ts @@ -0,0 +1,65 @@ +import { computed, ref } from 'vue' +import { getFileExtension } from '@/utils/icon' + +/** 右侧可预览的文件类型,每种类型的实现在 items/ 下同名小写文件夹中。 */ +export const FILE_PREVIEW_TYPE = { + PDF: 'PDF', + HTML: 'HTML', + MARKDOWN: 'MARKDOWN', + TEXT: 'TEXT', + EXCEL: 'EXCEL', + CSV: 'CSV', + WORD: 'WORD', + PPT: 'PPT', +} as const + +export type FilePreviewType = (typeof FILE_PREVIEW_TYPE)[keyof typeof FILE_PREVIEW_TYPE] + +/** 待预览的文件。 */ +export interface PreviewFile { + name: string + url: string +} + +const PREVIEW_TYPE_BY_EXTENSION: Readonly> = { + PDF: FILE_PREVIEW_TYPE.PDF, + HTML: FILE_PREVIEW_TYPE.HTML, + HTM: FILE_PREVIEW_TYPE.HTML, + MD: FILE_PREVIEW_TYPE.MARKDOWN, + MARKDOWN: FILE_PREVIEW_TYPE.MARKDOWN, + TXT: FILE_PREVIEW_TYPE.TEXT, + JSON: FILE_PREVIEW_TYPE.TEXT, + LOG: FILE_PREVIEW_TYPE.TEXT, + XML: FILE_PREVIEW_TYPE.TEXT, + YAML: FILE_PREVIEW_TYPE.TEXT, + YML: FILE_PREVIEW_TYPE.TEXT, + // 旧版 xls 为二进制格式,exceljs 不支持,仍按下载处理 + XLSX: FILE_PREVIEW_TYPE.EXCEL, + CSV: FILE_PREVIEW_TYPE.CSV, + // 旧版 doc 为二进制格式,docx-preview 不支持,仍按下载处理 + DOCX: FILE_PREVIEW_TYPE.WORD, + // 旧版 ppt 为二进制格式,pptx-renderer 不支持,仍按下载处理 + PPTX: FILE_PREVIEW_TYPE.PPT, +} + +/** 按扩展名判断预览方式,不支持预览时返回 null。 */ +export function getFilePreviewType(fileName: string): FilePreviewType | null { + return PREVIEW_TYPE_BY_EXTENSION[getFileExtension(fileName)] ?? null +} + +/** + * 文件预览面板 store:当前预览的文件。 + * 由右侧栏 store 创建并组合,右侧开合与面板切换由右侧栏 store 维护。 + */ +export function createFilePreviewStore() { + const previewFile = ref(null) + const previewType = computed(() => (previewFile.value ? getFilePreviewType(previewFile.value.name) : null)) + + const setPreviewFile = (file: PreviewFile) => { + previewFile.value = file + } + + return { previewFile, previewType, setPreviewFile } +} + +export type FilePreviewStore = ReturnType diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/index.vue b/ui/src/conversation-panel/right-sidebar/file-preview/index.vue new file mode 100644 index 00000000000..30de8418df3 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/index.vue @@ -0,0 +1,92 @@ + + + diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/csv/csv.ts b/ui/src/conversation-panel/right-sidebar/file-preview/items/csv/csv.ts new file mode 100644 index 00000000000..60527539a97 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/csv/csv.ts @@ -0,0 +1,85 @@ +import type { SpreadsheetSheet } from '../../components/sheet-table/index' +import { SPREADSHEET_PREVIEW_MAX_COLUMNS, SPREADSHEET_PREVIEW_MAX_ROWS, toColumnLabel } from '../../components/sheet-table/index' + +// Excel 导出的 CSV 常为 GBK 编码:UTF-8 解码失败时按 GBK 解码;UTF-8 BOM 由解码器去除 +function decodeCsv(buffer: ArrayBuffer) { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(buffer) + } catch { + return new TextDecoder('gbk').decode(buffer) + } +} + +/** + * 按 RFC 4180 解析 CSV:逗号分隔,双引号包裹的字段可含逗号、换行,"" 表示一个引号;兼容 CRLF / LF / CR 换行。 + * 读到 maxRows 行后停止,truncated 表示后面还有数据。 + */ +export function parseCsv(text: string, maxRows: number): { rows: string[][]; truncated: boolean } { + const rows: string[][] = [] + let row: string[] = [] + let field = '' + let inQuotes = false + let index = 0 + + const endRow = () => { + row.push(field) + rows.push(row) + row = [] + field = '' + } + + while (index < text.length) { + const char = text[index] + if (inQuotes) { + if (char === '"' && text[index + 1] === '"') { + field += '"' + index += 2 + continue + } + if (char === '"') inQuotes = false + else field += char + index++ + continue + } + if (char === '"' && field === '') { + inQuotes = true + } else if (char === ',') { + row.push(field) + field = '' + } else if (char === '\r' || char === '\n') { + if (rows.length === maxRows) return { rows, truncated: true } + endRow() + if (char === '\r' && text[index + 1] === '\n') index++ + } else { + field += char + } + index++ + } + // 末尾没有换行时补上最后一行;以换行结尾不产生空行 + if (field !== '' || row.length > 0) { + if (rows.length === maxRows) return { rows, truncated: true } + endRow() + } + return { rows, truncated: false } +} + +/** CSV 作为单个工作表,不带单元格格式。 */ +export function loadCsvSheet(name: string, buffer: ArrayBuffer): SpreadsheetSheet { + const text = decodeCsv(buffer) + const { rows, truncated } = parseCsv(text, SPREADSHEET_PREVIEW_MAX_ROWS) + const totalColumns = rows.reduce((max, row) => Math.max(max, row.length), 0) + const columnCount = Math.min(totalColumns, SPREADSHEET_PREVIEW_MAX_COLUMNS) + const columns = Array.from({ length: columnCount }, (_, index) => ({ label: toColumnLabel(index + 1) })) + return { + name, + columns, + rows: rows.map((row, rowIndex) => ({ + label: String(rowIndex + 1), + cells: columns.map((column, index) => ({ key: column.label, text: row[index] ?? '' })), + })), + truncated: truncated || totalColumns > SPREADSHEET_PREVIEW_MAX_COLUMNS, + styled: false, + showGridLines: true, + drawings: [], + } +} diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/csv/index.vue b/ui/src/conversation-panel/right-sidebar/file-preview/items/csv/index.vue new file mode 100644 index 00000000000..6de285821d8 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/csv/index.vue @@ -0,0 +1,27 @@ + + + diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/index.vue b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/index.vue new file mode 100644 index 00000000000..56d215f5e70 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/index.vue @@ -0,0 +1,39 @@ + + + diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-chart.ts b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-chart.ts new file mode 100644 index 00000000000..9e4541d39e3 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-chart.ts @@ -0,0 +1,509 @@ +import type { EChartsCoreOption } from 'echarts/core' +import type { CSSProperties } from 'vue' +import { adjustLightness } from './xlsx-color' +import { childElement, childElements, descendantElement } from './xlsx-drawing' + +/** 引用区域的数据:texts 为按单元格格式显示的文本,numbers 为数值(非数值为 null),format 为首个数值单元格的数字格式。 */ +export interface ChartRangeData { + texts: string[] + numbers: (number | null)[] + format?: string +} + +/** 图表取数与数值格式化,由工作簿解析方提供。 */ +export interface ChartDataSource { + readRange(reference: string): ChartRangeData | undefined + formatNumber(value: number, format?: string): string +} + +export interface ChartPreview { + option: EChartsCoreOption + /** 图表区背景与边框 */ + frameStyle: CSSProperties +} + +type ChartKind = 'line' | 'area' | 'bar' | 'scatter' | 'pie' | 'doughnut' + +const CHART_KINDS: Readonly> = { + lineChart: 'line', + line3DChart: 'line', + areaChart: 'area', + area3DChart: 'area', + barChart: 'bar', + bar3DChart: 'bar', + scatterChart: 'scatter', + bubbleChart: 'scatter', + pieChart: 'pie', + pie3DChart: 'pie', + ofPieChart: 'pie', + doughnutChart: 'doughnut', +} + +/** 主题色名到 Excel 主题色序号(见 xlsx-color 的 DEFAULT_THEME_COLORS) */ +const SCHEME_COLOR_INDEX: Readonly> = { + lt1: 0, + bg1: 0, + dk1: 1, + tx1: 1, + lt2: 2, + bg2: 2, + dk2: 3, + tx2: 3, + accent1: 4, + accent2: 5, + accent3: 6, + accent4: 7, + accent5: 8, + accent6: 9, + hlink: 10, + folHlink: 11, +} + +const LINE_DASH: Readonly> = { + dash: 'dashed', + lgDash: 'dashed', + dashDot: 'dashed', + lgDashDot: 'dashed', + lgDashDotDot: 'dashed', + sysDash: 'dashed', + sysDashDot: 'dashed', + sysDashDotDot: 'dashed', + dot: 'dotted', + sysDot: 'dotted', +} + +const MARKER_SYMBOLS: Readonly> = { + circle: 'circle', + square: 'rect', + diamond: 'diamond', + triangle: 'triangle', + star: 'pin', +} + +const TEXT_COLOR = '#595959' +const AXIS_LINE_COLOR = '#BFBFBF' +const GRID_LINE_COLOR = '#D9D9D9' +const EMU_PER_POINT = 12700 +const POINT_TO_PIXEL = 4 / 3 + +const getValue = (element: Element | undefined, name: string) => childElement(element, name)?.getAttribute('val') ?? undefined + +// 布尔属性元素:存在且未写 val 时为真 +function isEnabled(element: Element | undefined, name: string, fallback = false) { + const flag = childElement(element, name) + if (!flag) return fallback + const value = flag.getAttribute('val') + return value === null || value === '1' || value === 'true' +} + +/** 解析 DrawingML 颜色(srgbClr、schemeClr、sysClr、prstClr),含亮度调整 lumMod / lumOff / shade / tint。 */ +function readColor(colorElement: Element | undefined, themeColors: string[]): string | undefined { + if (!colorElement) return undefined + const value = colorElement.getAttribute('val') ?? '' + if (colorElement.localName === 'prstClr') return value || undefined + const hex = + colorElement.localName === 'srgbClr' + ? value + : colorElement.localName === 'sysClr' + ? colorElement.getAttribute('lastClr') + : colorElement.localName === 'schemeClr' + ? themeColors[SCHEME_COLOR_INDEX[value] ?? -1] + : undefined + if (!hex || !/^[0-9A-F]{6}$/i.test(hex)) return undefined + const modifier = (name: string) => { + const modifierValue = getValue(colorElement, name) + return modifierValue === undefined ? undefined : Number(modifierValue) / 100000 + } + const lumMod = modifier('lumMod') + const lumOff = modifier('lumOff') + const shade = modifier('shade') + const tint = modifier('tint') + if (lumMod === undefined && lumOff === undefined && shade === undefined && tint === undefined) return `#${hex}` + return `#${adjustLightness(hex, (lightness) => { + let adjusted = lightness * (lumMod ?? 1) + (lumOff ?? 0) + if (shade !== undefined) adjusted *= shade + if (tint !== undefined) adjusted = adjusted * tint + (1 - tint) + return adjusted + })}` +} + +/** 读取填充颜色:纯色、渐变取第一个色标,noFill 返回 transparent。 */ +function readFillColor(element: Element | undefined, themeColors: string[]): string | undefined { + if (!element) return undefined + if (childElement(element, 'noFill')) return 'transparent' + const solid = childElement(element, 'solidFill') + if (solid) return readColor(solid.firstElementChild ?? undefined, themeColors) + const gradientStop = descendantElement(childElement(element, 'gradFill'), 'gs') + return readColor(gradientStop?.firstElementChild ?? undefined, themeColors) +} + +function readLine(shapeProperties: Element | undefined, themeColors: string[]) { + const line = childElement(shapeProperties, 'ln') + const width = line?.getAttribute('w') + return { + color: readFillColor(line, themeColors), + width: width ? (Number(width) / EMU_PER_POINT) * POINT_TO_PIXEL : undefined, + type: LINE_DASH[getValue(line, 'prstDash') ?? ''], + } +} + +function readRichText(rich: Element | undefined) { + if (!rich) return '' + return Array.from(rich.getElementsByTagNameNS('*', 'p'), (paragraph) => + Array.from(paragraph.getElementsByTagNameNS('*', 't'), (text) => text.textContent ?? '').join(''), + ) + .filter(Boolean) + .join('\n') +} + +/** 读取数据:优先按引用从单元格取数,引用无法解析(外部链接、名称等)时使用图表缓存或字面量。 */ +function readData(element: Element | undefined, source: ChartDataSource): ChartRangeData | undefined { + if (!element) return undefined + const reference = descendantElement(element, 'f')?.textContent?.trim() + const fromCells = reference ? source.readRange(reference) : undefined + if (fromCells) return fromCells + const cache = ['numCache', 'strCache', 'numLit', 'strLit'].map((name) => descendantElement(element, name)).find(Boolean) + if (!cache) return undefined + const texts: string[] = Array.from({ length: Number(getValue(cache, 'ptCount') ?? 0) }, () => '') + childElements(cache, 'pt').forEach((point) => { + texts[Number(point.getAttribute('idx') ?? texts.length)] = childElement(point, 'v')?.textContent ?? '' + }) + return { + texts, + numbers: texts.map((text) => (text === '' || Number.isNaN(Number(text)) ? null : Number(text))), + format: childElement(cache, 'formatCode')?.textContent ?? undefined, + } +} + +function readTitle(title: Element | undefined, source: ChartDataSource) { + const text = childElement(title, 'tx') + if (!text) return undefined + const rich = childElement(text, 'rich') + return rich ? readRichText(rich) : readData(childElement(text, 'strRef'), source)?.texts.join(' ') +} + +// 标题字号与加粗取自第一个设置了的文字属性;未设置时按 Excel 默认标题(加粗) +function readTitleFont(title: Element | undefined) { + const properties = [ + ...Array.from(title?.getElementsByTagNameNS('*', 'rPr') ?? []), + ...Array.from(title?.getElementsByTagNameNS('*', 'defRPr') ?? []), + ] + const size = properties.map((element) => element.getAttribute('sz')).find(Boolean) + const bold = properties.map((element) => element.getAttribute('b')).find((value) => value !== null) + return { fontSize: size ? (Number(size) / 100) * POINT_TO_PIXEL : 18, fontWeight: bold === '0' ? 'normal' : 'bold' } +} + +interface ParsedSeries { + name: string + categories?: ChartRangeData + values?: ChartRangeData + xValues?: ChartRangeData + element: Element +} + +function readSeries(group: Element, source: ChartDataSource): ParsedSeries[] { + return childElements(group, 'ser') + .sort((first, second) => Number(getValue(first, 'order') ?? 0) - Number(getValue(second, 'order') ?? 0)) + .map((series, index) => { + const nameElement = childElement(series, 'tx') + const name = + childElement(nameElement, 'v')?.textContent ?? readData(childElement(nameElement, 'strRef'), source)?.texts[0] ?? `Series${index + 1}` + return { + name, + element: series, + categories: readData(childElement(series, 'cat'), source), + values: readData(childElement(series, 'val') ?? childElement(series, 'yVal'), source), + xValues: readData(childElement(series, 'xVal'), source), + } + }) +} + +// 数据标签:显示数值 / 类别名 / 百分比(饼图) +function readLabel(series: Element, group: Element, kind: ChartKind, format: (value: number) => string) { + const labels = childElement(series, 'dLbls') ?? childElement(group, 'dLbls') + if (!labels || isEnabled(labels, 'delete')) return undefined + const showValue = isEnabled(labels, 'showVal') + const showCategory = isEnabled(labels, 'showCatName') + const showPercent = isEnabled(labels, 'showPercent') + if (!showValue && !showCategory && !showPercent) return undefined + return { + show: true, + color: TEXT_COLOR, + position: kind === 'pie' || kind === 'doughnut' ? 'outside' : 'top', + formatter: (params: { name: string; value: unknown; percent?: number }) => { + const value = Array.isArray(params.value) ? params.value[1] : params.value + return [ + showCategory ? params.name : '', + showValue && typeof value === 'number' ? format(value) : '', + showPercent && params.percent !== undefined ? `${params.percent}%` : '', + ] + .filter(Boolean) + .join(' ') + }, + } +} + +function legendOption(chart: Element) { + const legend = childElement(chart, 'legend') + if (!legend) return { show: false } + const position = getValue(legend, 'legendPos') ?? 'r' + const base = { show: true, type: 'scroll', textStyle: { color: TEXT_COLOR, fontSize: 12 }, itemWidth: 16, itemHeight: 8 } + if (position === 'b') return { ...base, bottom: 4, left: 'center' } + if (position === 't') return { ...base, top: 36, left: 'center' } + if (position === 'l') return { ...base, left: 4, top: 'middle', orient: 'vertical' } + if (position === 'tr') return { ...base, right: 4, top: 36, orient: 'vertical' } + return { ...base, right: 4, top: 'middle', orient: 'vertical' } +} + +function chartFrameStyle(chartSpace: Element, themeColors: string[]): CSSProperties { + const shape = childElement(chartSpace, 'spPr') + const background = readFillColor(shape, themeColors) + const line = childElement(shape, 'ln') + const borderColor = line ? readFillColor(line, themeColors) : '#D9D9D9' + return { + backgroundColor: background ?? '#FFFFFF', + border: borderColor && borderColor !== 'transparent' ? `1px solid ${borderColor}` : 'none', + } +} + +function axisNameStyle(axis: Element | undefined, source: ChartDataSource) { + const name = readTitle(childElement(axis, 'title'), source) + return name ? { name, nameLocation: 'middle', nameTextStyle: { color: TEXT_COLOR, fontSize: 13, fontWeight: 'bold' } } : {} +} + +/** 数值轴:最值、反向、网格线、数字格式(未链接源数据时使用坐标轴自己的格式)。 */ +function valueAxisOption(axis: Element | undefined, source: ChartDataSource, fallbackFormat: string | undefined, scale: boolean) { + const scaling = childElement(axis, 'scaling') + const min = getValue(scaling, 'min') + const max = getValue(scaling, 'max') + const numberFormat = childElement(axis, 'numFmt') + const format = + numberFormat && numberFormat.getAttribute('sourceLinked') !== '1' ? (numberFormat.getAttribute('formatCode') ?? undefined) : fallbackFormat + return { + type: 'value', + show: !isEnabled(axis, 'delete'), + min: min === undefined ? undefined : Number(min), + max: max === undefined ? undefined : Number(max), + scale: scale && min === undefined, + inverse: getValue(scaling, 'orientation') === 'maxMin', + position: getValue(axis, 'axPos') === 'r' ? 'right' : getValue(axis, 'axPos') === 't' ? 'top' : undefined, + splitLine: { show: Boolean(childElement(axis, 'majorGridlines')), lineStyle: { color: GRID_LINE_COLOR } }, + axisLine: { show: false }, + axisLabel: { color: TEXT_COLOR, formatter: (value: number) => source.formatNumber(value, format) }, + ...axisNameStyle(axis, source), + } +} + +function pieOption(group: Element, kind: ChartKind, source: ChartDataSource, themeColors: string[]) { + const [series] = readSeries(group, source) + if (!series?.values) return undefined + const format = (value: number) => source.formatNumber(value, series.values?.format) + const pointColors = new Map( + childElements(series.element, 'dPt').map((point) => [Number(getValue(point, 'idx')), readFillColor(childElement(point, 'spPr'), themeColors)]), + ) + const holeSize = Number(getValue(group, 'holeSize') ?? 50) + return { + // 饼图默认按数据点轮换主题强调色 + color: themeColors.slice(4, 10).map((hex) => `#${hex}`), + tooltip: { trigger: 'item', valueFormatter: (value: unknown) => (typeof value === 'number' ? format(value) : String(value ?? '')) }, + series: [ + { + type: 'pie', + name: series.name, + radius: kind === 'doughnut' ? [`${(holeSize * 0.65).toFixed(0)}%`, '65%'] : '65%', + center: ['50%', '55%'], + label: readLabel(series.element, group, kind, format) ?? { show: false }, + data: series.values.numbers.map((value, index) => ({ + name: series.categories?.texts[index] ?? String(index + 1), + value, + itemStyle: pointColors.get(index) ? { color: pointColors.get(index) } : undefined, + })), + }, + ], + } +} + +/** 类别图(折线、面积、柱形 / 条形及其组合)与散点图,最多一主一次两条数值轴。 */ +function axisChartOption( + plotArea: Element, + groups: Array<{ element: Element; kind: ChartKind }>, + chart: Element, + source: ChartDataSource, + themeColors: string[], +) { + const axes = new Map( + Array.from(plotArea.children) + .filter((element) => ['catAx', 'valAx', 'dateAx', 'serAx'].includes(element.localName)) + .map((element) => [getValue(element, 'axId') ?? '', element]), + ) + const scatter = groups.every((group) => group.kind === 'scatter') + const horizontal = groups.some((group) => group.kind === 'bar' && getValue(group.element, 'barDir') === 'bar') + const valueAxisIds: string[] = [] + const series: Record[] = [] + let categoryAxis: Element | undefined + let xValueAxis: Element | undefined + let categories: string[] = [] + let firstFormat: string | undefined + let colorIndex = 0 + const accentColors = themeColors.slice(4, 10).map((hex) => `#${hex}`) + const blanksAsSpan = getValue(chart, 'dispBlanksAs') === 'span' + + groups.forEach(({ element: group, kind }, groupIndex) => { + if (scatter !== (kind === 'scatter')) return + const axisIds = childElements(group, 'axId').map((axisId) => axisId.getAttribute('val') ?? '') + const valueAxisId = scatter ? axisIds[1] : axisIds.find((axisId) => axes.get(axisId)?.localName === 'valAx') + if (scatter) xValueAxis ??= axes.get(axisIds[0] ?? '') + else categoryAxis ??= axisIds.map((axisId) => axes.get(axisId)).find((axis) => axis && axis.localName !== 'valAx') + if (valueAxisId && !valueAxisIds.includes(valueAxisId) && valueAxisIds.length < 2) valueAxisIds.push(valueAxisId) + const valueAxisIndex = Math.max(0, valueAxisIds.indexOf(valueAxisId ?? '')) + const grouping = getValue(group, 'grouping') ?? 'standard' + const stacked = grouping === 'stacked' || grouping === 'percentStacked' + const groupSeries = readSeries(group, source) + // 百分比堆积:按类别换算为各系列所占比例 + const totals = + grouping === 'percentStacked' + ? groupSeries.reduce((sums, item) => { + item.values?.numbers.forEach((value, index) => (sums[index] = (sums[index] ?? 0) + Math.abs(value ?? 0))) + return sums + }, []) + : undefined + const gapWidth = Number(getValue(group, 'gapWidth') ?? 150) + const overlap = Number(getValue(group, 'overlap') ?? (stacked ? 100 : 0)) + const lineMarkers = isEnabled(group, 'marker', kind === 'line') + const scatterStyle = getValue(group, 'scatterStyle') ?? 'marker' + + groupSeries.forEach((item) => { + if (!item.values) return + if (!categories.length && item.categories) categories = item.categories.texts + const format = totals ? '0%' : item.values.format + firstFormat ??= format + const formatValue = (value: number) => source.formatNumber(value, format) + const shape = childElement(item.element, 'spPr') + const line = readLine(shape, themeColors) + const defaultColor = accentColors[colorIndex++ % accentColors.length] + const seriesColor = kind === 'line' || kind === 'scatter' ? line.color : readFillColor(shape, themeColors) + const color = seriesColor && seriesColor !== 'transparent' ? seriesColor : defaultColor + const marker = childElement(item.element, 'marker') + const markerSymbol = getValue(marker, 'symbol') + const showSymbol = markerSymbol ? markerSymbol !== 'none' : kind === 'scatter' || (kind === 'line' && lineMarkers) + const values = totals + ? item.values.numbers.map((value, index) => (value === null || !totals[index] ? null : value / totals[index]!)) + : item.values.numbers + const axisIndex = horizontal ? { xAxisIndex: valueAxisIndex } : { yAxisIndex: valueAxisIndex } + const common = { + name: item.name, + ...axisIndex, + stack: stacked ? `stack-${groupIndex}` : undefined, + label: readLabel(item.element, group, kind, formatValue), + tooltip: { valueFormatter: (value: unknown) => (typeof value === 'number' ? formatValue(value) : String(value ?? '—')) }, + itemStyle: { color }, + } + if (kind === 'bar') { + series.push({ + ...common, + type: 'bar', + data: values, + barGap: `${-overlap}%`, + barCategoryGap: `${Math.round((gapWidth / (gapWidth + 100)) * 100)}%`, + }) + } else if (kind === 'scatter') { + const xValues = item.xValues?.numbers + // 散点图样式为 marker / none 或系列线条为 noFill 时只画点 + const showLine = line.color !== 'transparent' && scatterStyle !== 'marker' && scatterStyle !== 'none' + series.push({ + ...common, + type: showLine ? 'line' : 'scatter', + lineStyle: { color, width: line.width ?? 2, type: line.type }, + showSymbol, + symbol: MARKER_SYMBOLS[markerSymbol ?? ''] ?? 'circle', + smooth: isEnabled(item.element, 'smooth'), + data: values.map((value, index) => [xValues?.[index] ?? index + 1, value]), + }) + } else { + series.push({ + ...common, + type: 'line', + data: values, + showSymbol, + symbol: MARKER_SYMBOLS[markerSymbol ?? ''] ?? 'circle', + smooth: isEnabled(item.element, 'smooth'), + connectNulls: blanksAsSpan, + lineStyle: { color, width: line.width ?? 2, type: line.type }, + areaStyle: kind === 'area' ? { color, opacity: 1 } : undefined, + }) + } + }) + }) + if (!series.length) return undefined + + const lineLike = groups.every((group) => group.kind !== 'bar' && group.kind !== 'area') + const valueAxes = (valueAxisIds.length ? valueAxisIds : ['']).map((axisId, index) => ({ + ...valueAxisOption(axes.get(axisId), source, firstFormat, lineLike), + ...(index === 1 && !getValue(axes.get(axisId), 'axPos') ? { position: horizontal ? 'top' : 'right' } : {}), + nameGap: 0, + nameRotate: horizontal ? 0 : 90, + })) + const firstAxis = scatter + ? { ...valueAxisOption(xValueAxis, source, undefined, true), nameGap: 0 } + : { + type: 'category', + data: categories, + show: !isEnabled(categoryAxis, 'delete'), + inverse: getValue(childElement(categoryAxis, 'scaling'), 'orientation') === 'maxMin', + boundaryGap: groups.some((group) => group.kind === 'bar') || getValue(categoryAxis, 'crossBetween') !== 'midCat', + axisLine: { lineStyle: { color: AXIS_LINE_COLOR } }, + axisTick: { show: false }, + axisLabel: { color: TEXT_COLOR, hideOverlap: true, rotate: !horizontal && categories.length > 12 ? 45 : 0 }, + ...axisNameStyle(categoryAxis, source), + nameGap: 0, + nameRotate: horizontal ? 90 : 0, + } + return { + color: accentColors, + tooltip: { trigger: scatter ? 'item' : 'axis', confine: true }, + xAxis: horizontal ? valueAxes : firstAxis, + yAxis: horizontal ? firstAxis : valueAxes, + series, + } +} + +/** 把图表 XML 转换为 ECharts 配置;雷达图、股价图、曲面图等不支持的类型返回 undefined。 */ +export function toChartPreview(chartDocument: Document, source: ChartDataSource, themeColors: string[]): ChartPreview | undefined { + const chartSpace = chartDocument.documentElement + const chart = childElement(chartSpace, 'chart') + const plotArea = childElement(chart, 'plotArea') + if (!chart || !plotArea) return undefined + const groups = Array.from(plotArea.children) + .filter((element) => CHART_KINDS[element.localName]) + .map((element) => ({ element, kind: CHART_KINDS[element.localName]! })) + if (!groups.length) return undefined + const [firstGroup] = groups as [(typeof groups)[number]] + const pie = firstGroup.kind === 'pie' || firstGroup.kind === 'doughnut' + const plotOption = pie + ? pieOption(firstGroup.element, firstGroup.kind, source, themeColors) + : axisChartOption(plotArea, groups, chart, source, themeColors) + if (!plotOption) return undefined + + // 没有标题元素时,Excel 对单系列图表以系列名作为标题 + const titleElement = childElement(chart, 'title') + const autoTitle = + !titleElement && !isEnabled(chart, 'autoTitleDeleted') && pie ? (plotOption.series[0] as { name?: string } | undefined)?.name : undefined + const title = readTitle(titleElement, source) ?? autoTitle + const titleFont = readTitleFont(titleElement) + const legend = legendOption(chart) + return { + option: { + animation: false, + title: title ? { text: title, left: 'center', top: 8, textStyle: { color: '#333333', ...titleFont } } : undefined, + legend, + grid: { + top: title ? 52 : 16, + bottom: legend.show && 'bottom' in legend ? 40 : 16, + left: legend.show && 'left' in legend && legend.left === 4 ? 96 : 16, + right: legend.show && 'right' in legend ? 96 : 16, + }, + ...plotOption, + }, + frameStyle: chartFrameStyle(chartSpace, themeColors), + } +} diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-color.ts b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-color.ts new file mode 100644 index 00000000000..62495fc065b --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-color.ts @@ -0,0 +1,84 @@ +import type { Color } from 'exceljs' + +export type CellColor = Partial & { tint?: number; indexed?: number } + +/** Excel 默认主题色,文件未带主题时使用;顺序为 Excel 主题色序号:浅 1、深 1、浅 2、深 2、强调 1–6、超链接、已访问超链接。 */ +export const DEFAULT_THEME_COLORS = [ + 'FFFFFF', + '000000', + 'E7E6E6', + '44546A', + '4472C4', + 'ED7D31', + 'A5A5A5', + 'FFC000', + '5B9BD5', + '70AD47', + '0563C1', + '954F72', +] + +/** Excel 旧版索引色(0–63),64、65 为系统前景色与背景色,按未设置处理。 */ +const INDEXED_COLORS = ( + '000000 FFFFFF FF0000 00FF00 0000FF FFFF00 FF00FF 00FFFF 000000 FFFFFF FF0000 00FF00 0000FF FFFF00 FF00FF 00FFFF ' + + '800000 008000 000080 808000 800080 008080 C0C0C0 808080 9999FF 993366 FFFFCC CCFFFF 660066 FF8080 0066CC CCCCFF ' + + '000080 FF00FF FFFF00 00FFFF 800080 800000 008080 0000FF 00CCFF CCFFFF CCFFCC FFFF99 99CCFF FF99CC CC99FF FFCC99 ' + + '3366FF 33CCCC 99CC00 FFCC00 FF9900 FF6600 666699 969696 003366 339966 003300 333300 993300 993366 333399 333333' +).split(' ') + +/** 主题 XML 中颜色的排列顺序为深 1、浅 1、深 2、浅 2,Excel 的主题色序号把每组深浅对调。 */ +export function parseThemeColors(xml: string): string[] { + const scheme = new DOMParser().parseFromString(xml, 'application/xml').getElementsByTagNameNS('*', 'clrScheme')[0] + if (!scheme) return DEFAULT_THEME_COLORS + const colors = Array.from(scheme.children, (element) => { + const color = element.firstElementChild + return (color?.getAttribute('val') && color.localName === 'srgbClr' ? color.getAttribute('val') : color?.getAttribute('lastClr')) ?? '' + }) + const [dark1, light1, dark2, light2, ...rest] = colors + const themeColors = [light1, dark1, light2, dark2, ...rest] + return DEFAULT_THEME_COLORS.map((fallback, index) => (/^[0-9A-F]{6}$/i.test(themeColors[index] ?? '') ? themeColors[index]! : fallback)) +} + +/** 在 HSL 空间调整颜色亮度,返回 6 位十六进制。 */ +export function adjustLightness(hex: string, adjust: (lightness: number) => number) { + const [red, green, blue] = [0, 2, 4].map((offset) => parseInt(hex.slice(offset, offset + 2), 16) / 255) as [number, number, number] + const max = Math.max(red, green, blue) + const min = Math.min(red, green, blue) + let hue = 0 + let saturation = 0 + let lightness = (max + min) / 2 + if (max !== min) { + const delta = max - min + saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min) + if (max === red) hue = (green - blue) / delta + (green < blue ? 6 : 0) + else if (max === green) hue = (blue - red) / delta + 2 + else hue = (red - green) / delta + 4 + hue /= 6 + } + lightness = Math.min(1, Math.max(0, adjust(lightness))) + const toChannel = (offset: number) => { + const k = (offset + hue * 12) % 12 + const amount = saturation * Math.min(lightness, 1 - lightness) + const value = lightness - amount * Math.max(-1, Math.min(k - 3, 9 - k, 1)) + return Math.round(value * 255) + .toString(16) + .padStart(2, '0') + } + return `${toChannel(0)}${toChannel(8)}${toChannel(4)}` +} + +/** 按 Excel 规则调整主题色明暗:tint 小于 0 变暗,大于 0 变亮。 */ +function applyTint(hex: string, tint: number) { + return adjustLightness(hex, (lightness) => (tint < 0 ? lightness * (1 + tint) : lightness * (1 - tint) + tint)) +} + +/** 解析单元格颜色:ARGB(忽略透明度,openpyxl 常写为 00)、主题色(含明暗调整)或旧版索引色。 */ +export function resolveColor(color: CellColor | undefined, themeColors: string[]): string | undefined { + if (!color) return undefined + let hex: string | undefined + if (typeof color.argb === 'string' && /^([0-9A-F]{2})?[0-9A-F]{6}$/i.test(color.argb)) hex = color.argb.slice(-6) + else if (typeof color.theme === 'number') hex = themeColors[color.theme] + else if (typeof color.indexed === 'number') hex = INDEXED_COLORS[color.indexed] + if (!hex) return undefined + return `#${color.tint ? applyTint(hex, color.tint) : hex}` +} diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-drawing.ts b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-drawing.ts new file mode 100644 index 00000000000..dd773855aae --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx-drawing.ts @@ -0,0 +1,152 @@ +import type JSZip from 'jszip' + +/** 绘图锚点:Excel 中从 0 开始的列、行号及格内偏移(px)。 */ +export interface DrawingAnchorPoint { + column: number + row: number + x: number + y: number +} + +/** 从 xlsx 包中读取的浮动对象,图表保留原始 XML,转换时再按单元格取数。 */ +export interface SheetDrawing { + from: DrawingAnchorPoint + to?: DrawingAnchorPoint + width: number + height: number + chart?: Document + image?: string +} + +const RELATIONSHIP_NAMESPACE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' +const EMU_PER_PIXEL = 9525 +/** 单张图片上限,超出时不显示,避免 data URL 占用过多内存 */ +const MAX_IMAGE_SIZE = 10 * 1024 * 1024 +const IMAGE_MIME_TYPES: Readonly> = { + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + bmp: 'image/bmp', + webp: 'image/webp', + svg: 'image/svg+xml', +} + +interface Relationship { + type: string + path: string +} + +export const parseXml = (xml: string) => new DOMParser().parseFromString(xml, 'application/xml') + +/** 按本地名查找直接子元素,兼容带前缀(xdr:、c:)与不带前缀的写法。 */ +export function childElement(element: Element | null | undefined, name: string) { + return element ? Array.from(element.children).find((child) => child.localName === name) : undefined +} + +export function childElements(element: Element | null | undefined, name: string) { + return element ? Array.from(element.children).filter((child) => child.localName === name) : [] +} + +export function descendantElement(element: Element | Document | null | undefined, name: string) { + return element?.getElementsByTagNameNS('*', name)[0] +} + +const toPixels = (emu: string | null | undefined) => Math.round(Number(emu ?? 0) / EMU_PER_PIXEL) || 0 + +// 关系目标为绝对路径(/xl/...)或相对当前部件的路径(../drawings/...) +function resolvePartPath(sourcePath: string, target: string) { + if (target.startsWith('/')) return target.slice(1) + const segments = sourcePath.split('/').slice(0, -1) + target.split('/').forEach((segment) => { + if (segment === '..') segments.pop() + else if (segment && segment !== '.') segments.push(segment) + }) + return segments.join('/') +} + +async function readXml(zip: JSZip, path: string) { + const file = zip.file(path) + return file ? parseXml(await file.async('string')) : undefined +} + +async function readRelationships(zip: JSZip, partPath: string): Promise> { + const slash = partPath.lastIndexOf('/') + const document = await readXml(zip, `${partPath.slice(0, slash + 1)}_rels/${partPath.slice(slash + 1)}.rels`) + if (!document) return new Map() + return new Map( + Array.from(document.getElementsByTagNameNS('*', 'Relationship'), (relationship) => [ + relationship.getAttribute('Id') ?? '', + { + type: relationship.getAttribute('Type') ?? '', + path: relationship.getAttribute('TargetMode') === 'External' ? '' : resolvePartPath(partPath, relationship.getAttribute('Target') ?? ''), + }, + ]), + ) +} + +function readAnchorPoint(element: Element | undefined): DrawingAnchorPoint | undefined { + if (!element) return undefined + const value = (name: string) => childElement(element, name)?.textContent + return { column: Number(value('col') ?? 0), row: Number(value('row') ?? 0), x: toPixels(value('colOff')), y: toPixels(value('rowOff')) } +} + +async function readImage(zip: JSZip, path: string) { + const mimeType = IMAGE_MIME_TYPES[path.split('.').pop()?.toLowerCase() ?? ''] + const file = zip.file(path) + if (!mimeType || !file) return undefined + const data = await file.async('base64') + return data.length * 0.75 > MAX_IMAGE_SIZE ? undefined : `data:${mimeType};base64,${data}` +} + +/** 读取一个绘图部件中的图表与图片;形状、文本框、组合对象不显示。 */ +async function readDrawing(zip: JSZip, drawingPath: string): Promise { + const document = await readXml(zip, drawingPath) + if (!document?.documentElement) return [] + const relationships = await readRelationships(zip, drawingPath) + const drawings: SheetDrawing[] = [] + for (const anchor of Array.from(document.documentElement.children)) { + const extent = childElement(anchor, 'ext') + let from = readAnchorPoint(childElement(anchor, 'from')) + const to = anchor.localName === 'twoCellAnchor' ? readAnchorPoint(childElement(anchor, 'to')) : undefined + if (anchor.localName === 'absoluteAnchor') { + const position = childElement(anchor, 'pos') + from = { column: 0, row: 0, x: toPixels(position?.getAttribute('x')), y: toPixels(position?.getAttribute('y')) } + } + if (!from) continue + const size = { width: toPixels(extent?.getAttribute('cx')), height: toPixels(extent?.getAttribute('cy')) } + const chartId = childElement(anchor, 'graphicFrame') && descendantElement(anchor, 'chart')?.getAttributeNS(RELATIONSHIP_NAMESPACE, 'id') + const imageId = childElement(anchor, 'pic') && descendantElement(anchor, 'blip')?.getAttributeNS(RELATIONSHIP_NAMESPACE, 'embed') + const chartPath = chartId ? relationships.get(chartId)?.path : undefined + const imagePath = imageId ? relationships.get(imageId)?.path : undefined + if (chartPath) { + const chart = await readXml(zip, chartPath) + if (chart) drawings.push({ from, to, ...size, chart }) + } else if (imagePath) { + const image = await readImage(zip, imagePath) + if (image) drawings.push({ from, to, ...size, image }) + } + } + return drawings +} + +/** 按工作表名读取各工作表的浮动图表与图片:工作簿 → 工作表 → 绘图部件 → 图表 / 图片。 */ +export async function readSheetDrawings(zip: JSZip): Promise> { + const result = new Map() + const rootRelationships = await readRelationships(zip, '') + const workbookPath = + [...rootRelationships.values()].find((relationship) => relationship.type.endsWith('/officeDocument'))?.path || 'xl/workbook.xml' + const workbook = await readXml(zip, workbookPath) + if (!workbook) return result + const workbookRelationships = await readRelationships(zip, workbookPath) + for (const sheet of Array.from(workbook.getElementsByTagNameNS('*', 'sheet'))) { + const sheetPath = workbookRelationships.get(sheet.getAttributeNS(RELATIONSHIP_NAMESPACE, 'id') ?? '')?.path + if (!sheetPath) continue + const sheetRelationships = await readRelationships(zip, sheetPath) + const drawingPath = [...sheetRelationships.values()].find((relationship) => relationship.type.endsWith('/drawing'))?.path + if (!drawingPath) continue + const drawings = await readDrawing(zip, drawingPath) + if (drawings.length) result.set(sheet.getAttribute('name') ?? '', drawings) + } + return result +} diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx.ts b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx.ts new file mode 100644 index 00000000000..d90f6a00365 --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/excel/xlsx.ts @@ -0,0 +1,420 @@ +import type { + SpreadsheetAnchor, + SpreadsheetCell, + SpreadsheetColumn, + SpreadsheetDrawing, + SpreadsheetRow, + SpreadsheetSheet, +} from '../../components/sheet-table/index' +import type { ChartDataSource, ChartRangeData } from './xlsx-chart' +import type { DrawingAnchorPoint, SheetDrawing } from './xlsx-drawing' +import type { Border, Cell, Fill, Font, Workbook, Worksheet } from 'exceljs' +import type { CSSProperties } from 'vue' +import { SPREADSHEET_PREVIEW_MAX_COLUMNS, SPREADSHEET_PREVIEW_MAX_ROWS, toColumnLabel } from '../../components/sheet-table/index' +import { toChartPreview } from './xlsx-chart' +import { DEFAULT_THEME_COLORS, parseThemeColors, resolveColor } from './xlsx-color' +import { readSheetDrawings } from './xlsx-drawing' + +type ExcelJsModule = typeof import('exceljs') +type JSZipModule = typeof import('jszip') +type CellKind = 'text' | 'number' | 'boolean' + +// exceljs 体积较大,首次预览时才加载;浏览器构建为 UMD,具名导出可能挂在 default 上 +let excelJsLoader: Promise | undefined +function loadExcelJs() { + excelJsLoader ??= import('exceljs').then((module) => ((module as ExcelJsModule & { default?: ExcelJsModule }).default ?? module) as ExcelJsModule) + return excelJsLoader +} + +// 读取主题、绘图部件时使用;与 docx-preview 共用同一份 jszip +let jsZipLoader: Promise | undefined +function loadJSZip() { + jsZipLoader ??= import('jszip').then((module) => ((module as JSZipModule & { default?: JSZipModule }).default ?? module) as JSZipModule) + return jsZipLoader +} + +const DRAWING_PART_PATTERN = /^xl\/(drawings|charts)\// +const THEME_PART_PATTERN = /^xl\/theme\/theme\d*\.xml$/ + +interface PreparedWorkbook { + data: ArrayBuffer + themeColors: string[] + drawings: Map +} + +/** + * 读取主题色与各工作表的图表、图片,再把绘图部件交给 exceljs 前移除: + * exceljs 不需要绘图,且 openpyxl 等工具生成的绘图 XML 不带 xdr: 前缀,exceljs 无法解析,会导致整个文件加载失败。 + */ +async function prepareWorkbook(buffer: ArrayBuffer): Promise { + const JSZip = await loadJSZip() + const zip = await JSZip.loadAsync(buffer) + const themePart = zip.file(THEME_PART_PATTERN)[0] + const themeColors = themePart ? parseThemeColors(await themePart.async('string')) : DEFAULT_THEME_COLORS + const drawings = await readSheetDrawings(zip) + const drawingParts = zip.file(DRAWING_PART_PATTERN) + if (!drawingParts.length) return { data: buffer, themeColors, drawings } + drawingParts.forEach((part) => zip.remove(part.name)) + return { data: await zip.generateAsync({ type: 'arraybuffer' }), themeColors, drawings } +} + +// 去掉格式中的颜色、条件([Red]、[>100])、对齐占位(_x、*x)与转义符,引号内文字原样保留 +function cleanFormatSection(section: string) { + return section + .replace(/\[[^\]]*\]/g, '') + .replace(/[_*]./g, '') + .replace(/"([^"]*)"|\\(.)/g, (_, quoted: string | undefined, escaped: string | undefined) => quoted ?? escaped ?? '') +} + +// 未设置格式的数字去掉浮点误差,如 0.07200000000000001 显示为 0.072 +function formatGeneralNumber(value: number) { + return String(Number(value.toPrecision(15))) +} + +/** + * 按单元格数字格式显示数值:支持小数位、千分位、百分比及前后缀文字(如 0.00" 元"、#,##0.0、0.0%); + * 负数分段、分数、科学计数等复杂格式按常规数字显示。 + */ +export function formatNumberCell(value: number, numFmt?: string): string { + const section = cleanFormatSection((numFmt ?? '').split(';')[0] ?? '') + const pattern = section.match(/[#0?][#0?,]*(\.[#0?]+)?/) + if (!pattern || /E[+-]|\//i.test(section)) return formatGeneralNumber(value) + const fraction = pattern[1] ?? '' + const formatted = new Intl.NumberFormat('en-US', { + minimumFractionDigits: (fraction.match(/0/g) ?? []).length, + maximumFractionDigits: Math.max(fraction.length - 1, 0), + useGrouping: pattern[0].includes(','), + }).format(section.includes('%') ? value * 100 : value) + return section.replace(pattern[0], formatted) +} + +/** exceljs 按 UTC 还原日期;格式含时分秒时带上时间,纯时间格式只显示时间。 */ +export function formatDateCell(value: Date, numFmt?: string): string { + if (Number.isNaN(value.getTime())) return '' + const [date, time] = value.toISOString().slice(0, 19).split('T') as [string, string] + const section = cleanFormatSection(numFmt ?? '') + const hasDate = /[yd]/i.test(section) || !section + const hasTime = /[hs]/i.test(section) + if (hasDate && hasTime) return `${date} ${time}` + return hasTime ? time : date +} + +// 数值与日期按格式显示(公式取缓存的计算结果),文本、富文本、超链接等使用 exceljs 的展示文本;kind 决定常规对齐方式 +function readCell(cell: Cell): { text: string; kind: CellKind } { + const value = cell.value + const result = value !== null && typeof value === 'object' && 'result' in value ? value.result : value + if (typeof result === 'number') return { text: formatNumberCell(result, cell.numFmt), kind: 'number' } + if (result instanceof Date) return { text: formatDateCell(result, cell.numFmt), kind: 'number' } + if (typeof result === 'boolean') return { text: result ? 'TRUE' : 'FALSE', kind: 'boolean' } + return { text: cell.text ?? '', kind: result !== null && typeof result === 'object' && 'error' in result ? 'boolean' : 'text' } +} + +// Excel 列宽以字符数计,按默认字体(最大数字宽 7px)换算;行高以磅计 +const DEFAULT_COLUMN_WIDTH = 64 +const POINT_TO_PIXEL = 4 / 3 +const CELL_PADDING = 3 +const INDENT_WIDTH = 9 +/** 文本向右溢出到空白单元格时最多跨越的列数 */ +const MAX_OVERFLOW_COLUMNS = 20 + +const toColumnWidth = (width: number | undefined) => (width ? Math.round(width * 7) : DEFAULT_COLUMN_WIDTH) + +function toBorderCss(border: Partial | undefined, themeColors: string[]) { + if (!border?.style) return undefined + const color = resolveColor(border.color, themeColors) ?? '#000' + const style = border.style + if (style === 'double') return `3px double ${color}` + if (style === 'thick') return `3px solid ${color}` + const width = style.startsWith('medium') ? 2 : 1 + if (style === 'dotted' || style === 'hair') return `${width}px dotted ${color}` + if (style.includes('ash') || style.includes('Dot')) return `${width}px dashed ${color}` + return `${width}px solid ${color}` +} + +function toFillColor(fill: Fill | undefined, themeColors: string[]) { + if (!fill) return undefined + if (fill.type === 'gradient') return resolveColor(fill.stops?.[0]?.color, themeColors) + if (!fill.pattern || fill.pattern === 'none') return undefined + return resolveColor(fill.fgColor, themeColors) +} + +function toFontStyle(font: Partial | undefined, themeColors: string[]): CSSProperties { + if (!font) return {} + const decorations = [font.underline && font.underline !== 'none' ? 'underline' : '', font.strike ? 'line-through' : ''].filter(Boolean) + return { + color: resolveColor(font.color, themeColors), + fontSize: font.size ? `${font.size}pt` : undefined, + fontWeight: font.bold ? 'bold' : undefined, + fontStyle: font.italic ? 'italic' : undefined, + textDecoration: decorations.length ? decorations.join(' ') : undefined, + textDecorationStyle: typeof font.underline === 'string' && font.underline.startsWith('double') ? 'double' : undefined, + } +} + +const TEXT_ALIGN: Readonly> = { + left: 'left', + center: 'center', + centerContinuous: 'center', + right: 'right', + justify: 'justify', + distributed: 'justify', + fill: 'left', +} +const DEFAULT_TEXT_ALIGN: Readonly> = { text: 'left', number: 'right', boolean: 'center' } +const VERTICAL_ALIGN: Readonly> = { top: 'flex-start', middle: 'center' } + +interface MergeRange { + top: number + left: number + bottom: number + right: number +} + +interface CellData { + cell: Cell + text: string + kind: CellKind +} + +// 从起始行 / 列及格内偏移开始,累加行高 / 列宽直到覆盖指定尺寸,返回最后覆盖到的序号(从 1 开始) +function lastCoveredIndex(start: number, offset: number, size: number, measure: (index: number) => number, limit: number) { + let index = start + let covered = measure(index) - offset + while (covered < size && index < limit) covered += measure(++index) + return index +} + +/** + * 把工作表转换为预览数据:按原始列宽、行高、合并单元格及字体、填充、边框、对齐绘制; + * 隐藏的行列不显示,未设置换行的文本可溢出到右侧空白单元格。 + * 网格范围延伸到浮动图表、图片所在的行列,与 Excel 中一致。 + */ +function toStyledSheet(worksheet: Worksheet, themeColors: string[], sheetDrawings: SheetDrawing[], source: ChartDataSource): SpreadsheetSheet { + const truncated = worksheet.rowCount > SPREADSHEET_PREVIEW_MAX_ROWS || worksheet.columnCount > SPREADSHEET_PREVIEW_MAX_COLUMNS + const defaultRowHeight = (worksheet.properties.defaultRowHeight || 15) * POINT_TO_PIXEL + const measureColumn = (columnNumber: number) => { + const column = worksheet.getColumn(columnNumber) + return column.hidden ? 0 : toColumnWidth(column.width) + } + const measureRow = (rowNumber: number) => { + const row = worksheet.findRow(rowNumber) + return row?.hidden ? 0 : row?.height ? row.height * POINT_TO_PIXEL : defaultRowHeight + } + const drawingColumnEnd = Math.max( + 0, + ...sheetDrawings.map(({ from, to, width }) => + to ? to.column + 1 : lastCoveredIndex(from.column + 1, from.x, width, measureColumn, SPREADSHEET_PREVIEW_MAX_COLUMNS), + ), + ) + const drawingRowEnd = Math.max( + 0, + ...sheetDrawings.map(({ from, to, height }) => + to ? to.row + 1 : lastCoveredIndex(from.row + 1, from.y, height, measureRow, SPREADSHEET_PREVIEW_MAX_ROWS), + ), + ) + const rowLimit = Math.min(Math.max(worksheet.rowCount, drawingRowEnd), SPREADSHEET_PREVIEW_MAX_ROWS) + const columnLimit = Math.min(Math.max(worksheet.columnCount, drawingColumnEnd), SPREADSHEET_PREVIEW_MAX_COLUMNS) + const columnNumbers = Array.from({ length: columnLimit }, (_, index) => index + 1).filter( + (columnNumber) => !worksheet.getColumn(columnNumber).hidden, + ) + const rowNumbers = Array.from({ length: rowLimit }, (_, index) => index + 1).filter((rowNumber) => !worksheet.getRow(rowNumber).hidden) + const columnWidths = new Map(columnNumbers.map((columnNumber) => [columnNumber, toColumnWidth(worksheet.getColumn(columnNumber).width)])) + const rowHeights = new Map( + rowNumbers.map((rowNumber) => { + const height = worksheet.getRow(rowNumber).height + return [rowNumber, { height: height ? height * POINT_TO_PIXEL : defaultRowHeight, fixed: Boolean(height) }] + }), + ) + + // 读取单元格、合并区域与边框。边框按格线记录:某格的右边框与右侧格的左边框是同一条线,两侧单元格绘制时取同一值,避免折叠边框时互相覆盖 + const cells = new Map() + const merges = new Map() + const horizontalLines = new Map() + const verticalLines = new Map() + const setLine = (lines: Map, key: string, border: Partial | undefined) => { + const css = toBorderCss(border, themeColors) + if (css) lines.set(key, css) + } + for (let rowNumber = 1; rowNumber <= rowLimit; rowNumber++) { + const row = worksheet.getRow(rowNumber) + for (let columnNumber = 1; columnNumber <= columnLimit; columnNumber++) { + const cell = row.getCell(columnNumber) + cells.set(`${rowNumber}:${columnNumber}`, { cell, ...readCell(cell) }) + if (cell.isMerged) { + const master = cell.master + const range = merges.get(master.address) ?? { top: Number(master.row), left: Number(master.col), bottom: rowNumber, right: columnNumber } + range.bottom = Math.max(range.bottom, rowNumber) + range.right = Math.max(range.right, columnNumber) + merges.set(master.address, range) + } + const border = cell.border + if (!border) continue + setLine(horizontalLines, `${rowNumber}:${columnNumber}`, border.top) + setLine(horizontalLines, `${rowNumber + 1}:${columnNumber}`, border.bottom) + setLine(verticalLines, `${rowNumber}:${columnNumber}`, border.left) + setLine(verticalLines, `${rowNumber}:${columnNumber + 1}`, border.right) + } + } + const coveredCells = new Set() + merges.forEach((range, address) => { + for (let rowNumber = range.top; rowNumber <= range.bottom; rowNumber++) { + for (let columnNumber = range.left; columnNumber <= range.right; columnNumber++) { + const key = `${rowNumber}:${columnNumber}` + if (cells.get(key)?.cell.address !== address) coveredCells.add(key) + } + } + }) + const firstLine = (lines: Map, keys: string[]) => keys.map((key) => lines.get(key)).find(Boolean) + const between = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, index) => from + index) + + const rows: SpreadsheetRow[] = rowNumbers.map((rowNumber) => { + const rowCells: SpreadsheetCell[] = [] + columnNumbers.forEach((columnNumber, columnIndex) => { + const key = `${rowNumber}:${columnNumber}` + if (coveredCells.has(key)) return + const { cell, text, kind } = cells.get(key)! + const range = merges.get(cell.address) ?? { top: rowNumber, left: columnNumber, bottom: rowNumber, right: columnNumber } + const spannedRows = rowNumbers.filter((number) => number >= range.top && number <= range.bottom) + const spannedColumns = columnNumbers.filter((number) => number >= range.left && number <= range.right) + const alignment = cell.alignment ?? {} + const textAlign = (alignment.horizontal && TEXT_ALIGN[alignment.horizontal]) || DEFAULT_TEXT_ALIGN[kind] + const indent = (alignment.indent ?? 0) * INDENT_WIDTH + const wrap = Boolean(alignment.wrapText) + const height = spannedRows.reduce((total, number) => total + rowHeights.get(number)!.height, 0) + const fixedHeight = spannedRows.every((number) => rowHeights.get(number)!.fixed) + let width = spannedColumns.reduce((total, number) => total + columnWidths.get(number)!, 0) + // 左对齐且不换行的文本可延伸到右侧连续的空白单元格,遇到有内容或被合并的单元格为止 + if (kind === 'text' && text && !wrap && textAlign === 'left' && spannedColumns.length === 1) { + for (const nextColumn of columnNumbers.slice(columnIndex + 1, columnIndex + 1 + MAX_OVERFLOW_COLUMNS)) { + const nextKey = `${rowNumber}:${nextColumn}` + if (cells.get(nextKey)?.text || merges.has(cells.get(nextKey)!.cell.address) || coveredCells.has(nextKey)) break + width += columnWidths.get(nextColumn)! + } + } + rowCells.push({ + key: toColumnLabel(columnNumber), + text, + colSpan: spannedColumns.length > 1 ? spannedColumns.length : undefined, + rowSpan: spannedRows.length > 1 ? spannedRows.length : undefined, + style: { + backgroundColor: toFillColor(cell.fill, themeColors), + borderTop: firstLine( + horizontalLines, + between(range.left, range.right).map((number) => `${range.top}:${number}`), + ), + borderBottom: firstLine( + horizontalLines, + between(range.left, range.right).map((number) => `${range.bottom + 1}:${number}`), + ), + borderLeft: firstLine( + verticalLines, + between(range.top, range.bottom).map((number) => `${number}:${range.left}`), + ), + borderRight: firstLine( + verticalLines, + between(range.top, range.bottom).map((number) => `${number}:${range.right + 1}`), + ), + ...toFontStyle(cell.font, themeColors), + }, + contentStyle: { + width: `${width}px`, + [fixedHeight ? 'height' : 'minHeight']: `${height}px`, + justifyContent: VERTICAL_ALIGN[alignment.vertical ?? ''] ?? 'flex-end', + textAlign, + whiteSpace: wrap ? 'pre-wrap' : 'pre', + paddingLeft: textAlign === 'left' ? `${CELL_PADDING + indent}px` : undefined, + paddingRight: textAlign === 'right' ? `${CELL_PADDING + indent}px` : undefined, + }, + }) + }) + const rowHeight = rowHeights.get(rowNumber)! + return { label: String(rowNumber), height: rowHeight.fixed ? rowHeight.height : undefined, cells: rowCells } + }) + + const columns: SpreadsheetColumn[] = columnNumbers.map((columnNumber) => ({ + label: toColumnLabel(columnNumber), + width: columnWidths.get(columnNumber), + })) + + // 锚点换算为已渲染的行列序号:锚定在隐藏行列上时移到其后第一个可见行列,格内偏移归零 + const toAnchor = (point: DrawingAnchorPoint): SpreadsheetAnchor | undefined => { + const columnIndex = columnNumbers.findIndex((columnNumber) => columnNumber >= point.column + 1) + const rowIndex = rowNumbers.findIndex((rowNumber) => rowNumber >= point.row + 1) + if (columnIndex < 0 || rowIndex < 0) return undefined + return { + columnIndex, + rowIndex, + x: columnNumbers[columnIndex] === point.column + 1 ? point.x : 0, + y: rowNumbers[rowIndex] === point.row + 1 ? point.y : 0, + } + } + const drawings: SpreadsheetDrawing[] = sheetDrawings.flatMap((drawing, index): SpreadsheetDrawing[] => { + const from = toAnchor(drawing.from) + const to = drawing.to ? toAnchor(drawing.to) : undefined + if (!from || (!to && (!drawing.width || !drawing.height))) return [] + const base = { key: String(index), from, to, width: drawing.width, height: drawing.height } + if (drawing.image) return [{ ...base, image: drawing.image }] + const preview = drawing.chart ? toChartPreview(drawing.chart, source, themeColors) : undefined + return preview ? [{ ...base, chart: preview.option, style: preview.frameStyle }] : [] + }) + + return { + name: worksheet.name, + columns, + rows, + truncated, + styled: true, + showGridLines: worksheet.views?.[0]?.showGridLines !== false, + drawings, + } +} + +const RANGE_REFERENCE = /^(?:'((?:[^']|'')+)'|([^'!]+))!\$?([A-Z]{1,3})\$?(\d+)(?::\$?([A-Z]{1,3})\$?(\d+))?$/i +/** 单个图表引用最多读取的单元格数 */ +const MAX_CHART_POINTS = 10000 + +const toColumnNumber = (label: string) => [...label.toUpperCase()].reduce((total, letter) => total * 26 + letter.charCodeAt(0) - 64, 0) + +/** 图表按引用(如 '日线数据'!$A$5:$A$246)从工作簿单元格取数;名称、多区域、外部引用交给图表缓存处理。 */ +function createChartDataSource(workbook: Workbook): ChartDataSource { + return { + readRange(reference) { + const match = reference.match(RANGE_REFERENCE) + if (!match) return undefined + const worksheet = workbook.getWorksheet(match[1]?.replace(/''/g, "'") ?? match[2]) + if (!worksheet) return undefined + const [left, right] = [toColumnNumber(match[3]!), toColumnNumber(match[5] ?? match[3]!)].sort((a, b) => a - b) as [number, number] + const [top, bottom] = [Number(match[4]), Number(match[6] ?? match[4])].sort((a, b) => a - b) as [number, number] + if ((bottom - top + 1) * (right - left + 1) > MAX_CHART_POINTS) return undefined + const data: ChartRangeData = { texts: [], numbers: [] } + for (let rowNumber = top; rowNumber <= bottom; rowNumber++) { + for (let columnNumber = left; columnNumber <= right; columnNumber++) { + const cell = worksheet.findCell(rowNumber, columnNumber) + const value = cell?.value + const result = value !== null && typeof value === 'object' && 'result' in value ? value.result : value + data.texts.push(cell ? readCell(cell).text : '') + data.numbers.push(typeof result === 'number' ? result : null) + if (typeof result === 'number') data.format ??= cell?.numFmt + } + } + return data + }, + formatNumber: formatNumberCell, + } +} + +function toWorkbookSheets(workbook: Workbook, themeColors: string[], drawings: Map): SpreadsheetSheet[] { + const source = createChartDataSource(workbook) + return workbook.worksheets + .filter((worksheet) => worksheet.state === 'visible') + .map((worksheet) => toStyledSheet(worksheet, themeColors, drawings.get(worksheet.name) ?? [], source)) +} + +/** 解析 xlsx:读取单元格展示文本与格式、浮动图表与图片,不执行公式与宏。 */ +export async function loadXlsxSheets(buffer: ArrayBuffer): Promise { + const [{ data, themeColors, drawings }, ExcelJS] = await Promise.all([prepareWorkbook(buffer), loadExcelJs()]) + const workbook = new ExcelJS.Workbook() + // 绘图部件已移除,工作表中指向绘图的 节点一并忽略 + await workbook.xlsx.load(data, { ignoreNodes: ['drawing'] }) + return toWorkbookSheets(workbook, themeColors, drawings) +} diff --git a/ui/src/conversation-panel/right-sidebar/file-preview/items/html/index.vue b/ui/src/conversation-panel/right-sidebar/file-preview/items/html/index.vue new file mode 100644 index 00000000000..baf5e757cef --- /dev/null +++ b/ui/src/conversation-panel/right-sidebar/file-preview/items/html/index.vue @@ -0,0 +1,19 @@ + + +