49 lines
1.8 KiB
Python
49 lines
1.8 KiB
Python
"""在大屏 JSON 副本上新增组件,用于后端校验动作能否执行"""
|
|
|
|
from app.actions.base import BaseActionHandler
|
|
from app.schemas.actions import AddAction
|
|
from app.schemas.screen import Screen, ScreenNode
|
|
|
|
|
|
class AddHandler(BaseActionHandler[AddAction]):
|
|
def apply(self, screen: Screen, action: AddAction) -> Screen:
|
|
# 重新校验节点,避免模型创建后被修改成无效内容
|
|
node = ScreenNode.model_validate(action.node.model_dump())
|
|
|
|
# 如果新节点 ID 与已有组件重复,拒绝新增,避免后续按 ID 查找时产生歧义
|
|
if any(existing.id == node.id for existing in screen.nodes):
|
|
raise ValueError(f"新增组件 ID 已存在: {node.id}")
|
|
|
|
# 深拷贝整个大屏,新增操作只影响返回的副本
|
|
result = screen.model_copy(deep=True)
|
|
# 追加到末尾,不共享动作中的嵌套配置
|
|
result.nodes.append(node.model_copy(deep=True))
|
|
|
|
# 返回新增后的完整大屏,供后续动作继续模拟执行
|
|
return result
|
|
|
|
|
|
if __name__ == "__main__":
|
|
screen = Screen.model_validate(
|
|
{"canvas": {"width": 1920, "height": 1080}, "nodes": []}
|
|
)
|
|
action = AddAction.model_validate(
|
|
{
|
|
"type": "add",
|
|
"node": {
|
|
"id": "screen-title",
|
|
"type": "text",
|
|
"layout": {"x": 100, "y": 50, "width": 400, "height": 60},
|
|
"props": {},
|
|
},
|
|
}
|
|
)
|
|
handler = AddHandler()
|
|
final_screen = handler.apply(screen, action)
|
|
print(final_screen.model_dump_json(indent=2))
|
|
print("原始组件数:", len(screen.nodes))
|
|
try:
|
|
handler.apply(final_screen, action)
|
|
except ValueError as error:
|
|
print("重复新增:", error)
|