feat: 添加判断修改范围、规划和资源需求节点
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
"""动作处理器公共接口"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
from app.schemas.actions import BaseAction
|
||||
from app.schemas.screen import Screen, ScreenNode
|
||||
|
||||
ActionT = TypeVar("ActionT", bound=BaseAction)
|
||||
|
||||
|
||||
class BaseActionHandler(ABC, Generic[ActionT]):
|
||||
@abstractmethod
|
||||
def apply(self, screen: Screen, action: ActionT) -> Screen:
|
||||
"""校验并在副本上执行动作,返回新的大屏"""
|
||||
raise NotImplementedError
|
||||
|
||||
def copy_target(self, screen: Screen, target_id: str) -> tuple[Screen, ScreenNode]:
|
||||
# 先确认目标存在,再复制,避免修改原始快照
|
||||
for index, node in enumerate(screen.nodes):
|
||||
if node.id == target_id:
|
||||
result = screen.model_copy(deep=True)
|
||||
return result, result.nodes[index]
|
||||
raise ValueError(f"目标组件不存在: {target_id}")
|
||||
@@ -0,0 +1,41 @@
|
||||
"""移动组件的后端模拟执行"""
|
||||
|
||||
from app.actions.base import BaseActionHandler
|
||||
from app.schemas.actions import MoveAction
|
||||
from app.schemas.screen import Layout, Screen
|
||||
|
||||
|
||||
class MoveHandler(BaseActionHandler[MoveAction]):
|
||||
def apply(self, screen: Screen, action: MoveAction) -> Screen:
|
||||
result, target = self.copy_target(screen, action.target_id)
|
||||
layout = target.layout.model_dump()
|
||||
layout["x"] += action.delta_x
|
||||
layout["y"] += action.delta_y
|
||||
# 重新校验计算结果,防止浮点溢出产生无效坐标
|
||||
target.layout = Layout.model_validate(layout)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
screen = Screen.model_validate(
|
||||
{
|
||||
"canvas": {"width": 1920, "height": 1080},
|
||||
"nodes": [
|
||||
{
|
||||
"id": "sales-chart",
|
||||
"type": "chart",
|
||||
"layout": {"x": 100, "y": 200, "width": 400, "height": 300},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
action = MoveAction(target_id="sales-chart", delta_x=50)
|
||||
handler = MoveHandler()
|
||||
final_screen = handler.apply(screen, action)
|
||||
print(final_screen.model_dump_json(indent=2))
|
||||
print("原始坐标:", screen.nodes[0].layout.x, screen.nodes[0].layout.y)
|
||||
|
||||
try:
|
||||
handler.apply(screen, MoveAction(target_id="missing", delta_x=50))
|
||||
except ValueError as error:
|
||||
print("无效目标:", error)
|
||||
@@ -0,0 +1,25 @@
|
||||
"""显式注册动作处理器"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.actions.base import BaseActionHandler
|
||||
from app.actions.move import MoveHandler
|
||||
from app.actions.resize import ResizeHandler
|
||||
from app.actions.update import UpdateHandler
|
||||
from app.schemas.actions import Action
|
||||
from app.schemas.screen import Screen
|
||||
|
||||
# 新增操作时在此注册,未实现的操作明确报错
|
||||
ACTION_HANDLERS: dict[str, BaseActionHandler[Any]] = {
|
||||
"move": MoveHandler(),
|
||||
"resize": ResizeHandler(),
|
||||
"update": UpdateHandler(),
|
||||
}
|
||||
|
||||
|
||||
def apply_action(screen: Screen, action: Action) -> Screen:
|
||||
"""接收已通过 Schema 校验的动作,返回执行后的副本"""
|
||||
handler = ACTION_HANDLERS.get(action.type)
|
||||
if handler is None:
|
||||
raise ValueError(f"尚未实现动作处理器: {action.type}")
|
||||
return handler.apply(screen, action)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""设置组件尺寸的后端模拟执行"""
|
||||
|
||||
from app.actions.base import BaseActionHandler
|
||||
from app.schemas.actions import ResizeAction
|
||||
from app.schemas.screen import Layout, Screen
|
||||
|
||||
|
||||
class ResizeHandler(BaseActionHandler[ResizeAction]):
|
||||
def apply(self, screen: Screen, action: ResizeAction) -> Screen:
|
||||
result, target = self.copy_target(screen, action.target_id)
|
||||
layout = target.layout.model_dump()
|
||||
# 仅替换提供的尺寸,位置和其他布局字段保持不变
|
||||
if action.width is not None:
|
||||
layout["width"] = action.width
|
||||
if action.height is not None:
|
||||
layout["height"] = action.height
|
||||
target.layout = Layout.model_validate(layout)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
screen = Screen.model_validate(
|
||||
{
|
||||
"canvas": {"width": 1920, "height": 1080},
|
||||
"nodes": [
|
||||
{
|
||||
"id": "sales-chart",
|
||||
"type": "chart",
|
||||
"layout": {"x": 100, "y": 200, "width": 400, "height": 300},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
action = ResizeAction(target_id="sales-chart", width=500)
|
||||
handler = ResizeHandler()
|
||||
final_screen = handler.apply(screen, action)
|
||||
print(final_screen.model_dump_json(indent=2))
|
||||
print("原始尺寸:", screen.nodes[0].layout.width, screen.nodes[0].layout.height)
|
||||
|
||||
try:
|
||||
handler.apply(screen, ResizeAction(target_id="missing", width=500))
|
||||
except ValueError as error:
|
||||
print("无效目标:", error)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""按路径更新组件属性"""
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
from app.actions.base import BaseActionHandler
|
||||
from app.schemas.actions import UpdateAction
|
||||
from app.schemas.screen import Screen
|
||||
|
||||
|
||||
class UpdateHandler(BaseActionHandler[UpdateAction]):
|
||||
def apply(self, screen: Screen, action: UpdateAction) -> Screen:
|
||||
result, target = self.copy_target(screen, action.target_id)
|
||||
# 未设置的 style 视为空对象,只允许直接添加末级字段
|
||||
if action.section == "style" and target.style is None:
|
||||
target.style = {}
|
||||
current = getattr(target, action.section)
|
||||
for index, segment in enumerate(action.path):
|
||||
last = index == len(action.path) - 1
|
||||
location = f"{action.section} {action.path[: index + 1]!r}"
|
||||
if isinstance(current, dict):
|
||||
if not isinstance(segment, str):
|
||||
raise ValueError(f"对象路径必须使用字符串键: {location}")
|
||||
if not last and segment not in current:
|
||||
raise ValueError(f"中间路径不存在: {location}")
|
||||
elif isinstance(current, list):
|
||||
if type(segment) is not int:
|
||||
raise ValueError(f"数组路径必须使用整数下标: {location}")
|
||||
if not 0 <= segment < len(current):
|
||||
raise ValueError(f"数组下标越界: {location}")
|
||||
else:
|
||||
raise ValueError(f"路径无法继续访问,当前值不是对象或数组: {location}")
|
||||
|
||||
if last:
|
||||
# 新值也复制,避免后续修改结果时影响 Action
|
||||
current[segment] = deepcopy(action.value)
|
||||
else:
|
||||
current = current[segment]
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
screen = Screen.model_validate(
|
||||
{
|
||||
"canvas": {"width": 1920, "height": 1080},
|
||||
"nodes": [
|
||||
{
|
||||
"id": "sales-chart",
|
||||
"type": "chart",
|
||||
"layout": {"x": 100, "y": 200, "width": 400, "height": 300},
|
||||
"props": {"option": {"title": {"text": "销售额", "show": True}}},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
action = UpdateAction(
|
||||
target_id="sales-chart",
|
||||
section="props",
|
||||
path=["option", "title", "text"],
|
||||
value="月度销售额",
|
||||
)
|
||||
handler = UpdateHandler()
|
||||
final_screen = handler.apply(screen, action)
|
||||
print(final_screen.model_dump_json(indent=2))
|
||||
print("原始标题:", screen.nodes[0].props["option"]["title"]["text"])
|
||||
|
||||
try:
|
||||
handler.apply(
|
||||
screen,
|
||||
UpdateAction(
|
||||
target_id="sales-chart",
|
||||
section="props",
|
||||
path=["missing", "text"],
|
||||
value="新标题",
|
||||
),
|
||||
)
|
||||
except ValueError as error:
|
||||
print("无效路径:", error)
|
||||
Reference in New Issue
Block a user