880 lines
35 KiB
Rust
880 lines
35 KiB
Rust
//! Block 的共享赋值、底层 Data 与视觉属性实现。Block 通过 Cell 间接指向 Data,使别名能观察到同一次替换。
|
|
//! Data 保存子组件 slot、布局配置、绑定和订阅。属性读写需要沿有效的类型/存储路径解析,不能把快照当成可变业务对象。
|
|
//! 提取视觉数据时将托管属性覆盖到原生描述;校验负责拒绝循环、非法尺寸和不符合类型的组成。
|
|
//!
|
|
//! Live visual objects. All semantic references are owned by Aster's heap;
|
|
//! native Arcs are reserved for immutable rendering snapshots.
|
|
use std::sync::Arc;
|
|
|
|
use endor_core::{NativeContext, ObjectPayload, ObjectRef, ObjectStore, Value, VmError};
|
|
|
|
use crate::ui_bridge::UiNode;
|
|
|
|
#[derive(Debug, Clone)]
|
|
/// 稳定组成 slot 与子 Block 的配对;slot 不依赖孩子当前的屏幕位置。
|
|
pub struct Child {
|
|
// slot 标识父组件中这条组成边,移动行序不改变它;同一 Block 可通过不同 slot 出现多次。
|
|
pub slot: u64,
|
|
pub block: ObjectRef,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
/// 原生组件分类,只描述业务组件种类;每种展示几何由布局和 Mount 另行生成。
|
|
pub enum Kind {
|
|
Text {
|
|
value: String,
|
|
size: u32,
|
|
color: String,
|
|
},
|
|
Rect {
|
|
width: f32,
|
|
height: f32,
|
|
radius: f32,
|
|
color: String,
|
|
},
|
|
Spacer(f32),
|
|
Scroll {
|
|
width: f32,
|
|
height: f32,
|
|
},
|
|
Row,
|
|
Column,
|
|
Overlay,
|
|
Scene2D,
|
|
Viewport3D {
|
|
width: f32,
|
|
height: f32,
|
|
},
|
|
CanvasViewport {
|
|
width: f32,
|
|
height: f32,
|
|
},
|
|
Button,
|
|
Page,
|
|
}
|
|
|
|
/// The VM owns the Block -> Cell -> Data relationship. Shared assignment
|
|
/// changes the Cell to point at another Block, retaining the original identity.
|
|
#[derive(Debug, Clone)]
|
|
/// 对共享 Cell 的稳定包装。赋值可让所有别名一起改指向,而每次出现的 Mount 仍独立。
|
|
pub struct Block {
|
|
// 共享赋值单元 Cell;其值可为最终 Data 或另一个 Block,从而保留别名身份并转发属性/类型查询。
|
|
pub state: ObjectRef,
|
|
pub page: bool,
|
|
pub tasks: Option<ObjectRef>,
|
|
}
|
|
|
|
impl ObjectPayload for Block {
|
|
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
|
|
fn reference_assignment_only(&self) -> bool {
|
|
true
|
|
}
|
|
/// 沿 Block 的共享 Cell 定位属性存储,使别名替换后读取到同一份新 Data。
|
|
fn attribute_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
|
|
let Value::Object(value) = store.cell_get(self.state)? else {
|
|
return Err(VmError::InvalidArgument("Block state is not an object"));
|
|
};
|
|
// 若 Cell 指向替代 Block,将属性查询继续转发;否则读取 Data.properties 的普通托管字段。
|
|
if store.object(value)?.payload().as_any().is::<Block>() {
|
|
Ok(Some(value))
|
|
} else {
|
|
store
|
|
.payload::<Data>(value, "Block data")?
|
|
.properties
|
|
.map(Some)
|
|
.ok_or(VmError::InvalidArgument(
|
|
"Block has no managed property storage",
|
|
))
|
|
}
|
|
}
|
|
|
|
/// 从 Block 当前 Data 解析其类型转发目标,使共享替换后的类型查询仍一致。
|
|
fn type_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
|
|
let Value::Object(value) = store.cell_get(self.state)? else {
|
|
return Err(VmError::InvalidArgument("Block state is not an object"));
|
|
};
|
|
if store.object(value)?.payload().as_any().is::<Block>() {
|
|
Ok(Some(value))
|
|
} else {
|
|
store.payload::<Data>(value, "Block data")?;
|
|
// 到达最终 Data 时停止类型转发,使用当前 Block 自身名义类型;只有替换为其他 Block 才继续转发类型。
|
|
Ok(None)
|
|
}
|
|
}
|
|
|
|
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
|
|
fn as_any(&self) -> &dyn std::any::Any {
|
|
self
|
|
}
|
|
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
|
|
fn kind_name(&self) -> &'static str {
|
|
"tessera-block"
|
|
}
|
|
/// 声明此 payload 是否允许使用托管属性存储,具体字段仍由类型与调用检查约束。
|
|
fn allows_attributes(&self) -> bool {
|
|
true
|
|
}
|
|
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
|
|
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
|
visit(self.state);
|
|
if let Some(tasks) = self.tasks {
|
|
visit(tasks);
|
|
}
|
|
}
|
|
/// 向 VM 暴露共享赋值单元;替换的是指向关系,不是逐项复制组件业务字段。
|
|
fn assignment_cell(
|
|
&self,
|
|
source: ObjectRef,
|
|
store: &ObjectStore,
|
|
) -> Result<Option<ObjectRef>, VmError> {
|
|
if !store.object(source)?.payload().as_any().is::<Self>() {
|
|
return Ok(None);
|
|
}
|
|
// Page 与普通组件不能交叉共享赋值,防止把窗口/页面生命周期能力替换成普通叶组件。
|
|
if store.payload::<Self>(source, "Block")?.page != self.page {
|
|
return Err(VmError::InvalidArgument(
|
|
"Page assignment requires another Page",
|
|
));
|
|
}
|
|
// 建立转发前检查源展开图不能回到本 Cell,禁止共享赋值在别名或组成关系中形成环。
|
|
validate(store, source, Some(self.state))?;
|
|
Ok(Some(self.state))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
/// 组件当前业务描述与组成。与一次求出的屏幕几何分开保存,替换或属性变化会触发派生快照失效。
|
|
pub struct Data {
|
|
pub kind: Kind,
|
|
pub children: Vec<Child>,
|
|
pub padding: f32,
|
|
pub gap: f32,
|
|
pub flex: f32,
|
|
pub flex_policy: crate::layout::FlexPolicy,
|
|
pub main_align: crate::layout::MainAlign,
|
|
pub cross_align: crate::layout::CrossAlign,
|
|
pub align_self: Option<crate::layout::CrossAlign>,
|
|
pub margin: crate::layout::Insets,
|
|
pub sizing: crate::box_model::Sizing,
|
|
// 四边覆盖顺序为上、右、下、左;None 表示回退统一 padding,不等于零。
|
|
pub padding_edges: [Option<f32>; 4],
|
|
pub border: crate::layout::Insets,
|
|
pub border_color: String,
|
|
pub clip_children: bool,
|
|
pub camera: Option<ObjectRef>,
|
|
pub scene3d: Option<ObjectRef>,
|
|
pub controller: Option<ObjectRef>,
|
|
pub scroll_axis: crate::scroll::Axis,
|
|
pub position: [f32; 2],
|
|
pub surface: crate::page::Surface,
|
|
// 下次插入的单调 slot,初始孩子按 0..len 编号,后续重排不把旧 slot 重新编号。
|
|
pub next_slot: u64,
|
|
// Page 导航历史是真实托管拥有边;后退/前进可重新展示同一个对象,而非复制快照。
|
|
pub history: Vec<ObjectRef>,
|
|
pub history_index: usize,
|
|
pub bindings: Vec<ObjectRef>,
|
|
pub text_binding: Option<(ObjectRef, String)>,
|
|
pub click: Option<ObjectRef>,
|
|
pub subscriptions: Vec<ObjectRef>,
|
|
// 源可读写的视觉字段存储;Data 自身保存结构边与构造默认值,提取时再将当前属性覆盖到派生副本。
|
|
pub properties: Option<ObjectRef>,
|
|
}
|
|
|
|
impl Data {
|
|
/// 建立组件业务描述,为初始孩子分配稳定 slot,并初始化无绑定、无订阅的默认布局策略。
|
|
pub fn new(kind: Kind, children: Vec<ObjectRef>, padding: f32, gap: f32) -> Self {
|
|
// 先为输入孩子分配稳定 slot,next_slot 从当前长度继续,后续追加不会复用被删除条目的编号。
|
|
let next_slot = children.len() as u64;
|
|
Self {
|
|
kind,
|
|
children: children
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(slot, block)| Child {
|
|
slot: slot as u64,
|
|
block,
|
|
})
|
|
.collect(),
|
|
padding,
|
|
gap,
|
|
flex: 0.0,
|
|
flex_policy: crate::layout::FlexPolicy::default(),
|
|
main_align: crate::layout::MainAlign::Start,
|
|
cross_align: crate::layout::CrossAlign::Start,
|
|
align_self: None,
|
|
margin: crate::layout::Insets::default(),
|
|
sizing: crate::box_model::Sizing::default(),
|
|
padding_edges: [None; 4],
|
|
border: crate::layout::Insets::default(),
|
|
border_color: "#D8DCE2".into(),
|
|
clip_children: false,
|
|
camera: None,
|
|
scene3d: None,
|
|
controller: None,
|
|
scroll_axis: crate::scroll::Axis::Both,
|
|
position: [0.0, 0.0],
|
|
surface: crate::page::Surface::new(crate::page::Mode::Window),
|
|
next_slot,
|
|
history: vec![],
|
|
history_index: 0,
|
|
bindings: vec![],
|
|
text_binding: None,
|
|
click: None,
|
|
subscriptions: vec![],
|
|
properties: None,
|
|
}
|
|
}
|
|
/// 检查原生组件种类是否承载子组成,供树修改和布局选择使用。
|
|
pub fn is_container(&self) -> bool {
|
|
// 这些类别允许通过通用 Children 方法编辑;Viewport3D 的面板内容来自 Scene3D 提取,不是普通 children 列表。
|
|
matches!(
|
|
self.kind,
|
|
Kind::Row
|
|
| Kind::Column
|
|
| Kind::Overlay
|
|
| Kind::Scene2D
|
|
| Kind::CanvasViewport { .. }
|
|
| Kind::Button
|
|
| Kind::Page
|
|
| Kind::Scroll { .. }
|
|
)
|
|
}
|
|
}
|
|
|
|
impl ObjectPayload for Data {
|
|
/// 声明此 payload 的赋值遵循引用身份语义,避免把内部宿主状态当作可复制值。
|
|
fn reference_assignment_only(&self) -> bool {
|
|
true
|
|
}
|
|
/// 提供受检查的 Any 下转型入口,让宿主按具体 payload 类型读取数据。
|
|
fn as_any(&self) -> &dyn std::any::Any {
|
|
self
|
|
}
|
|
/// 返回运行时诊断/类型检查使用的稳定 payload 名称。
|
|
fn kind_name(&self) -> &'static str {
|
|
"tessera-block-data"
|
|
}
|
|
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
|
|
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
|
// 所有结构字段中出现的托管强引用必须枚举:场景/相机、属性存储、孩子、历史、绑定、订阅和回调。
|
|
if let Some(scene) = self.scene3d {
|
|
visit(scene);
|
|
}
|
|
if let Some(controller) = self.controller {
|
|
visit(controller);
|
|
}
|
|
if let Some(camera) = self.camera {
|
|
visit(camera);
|
|
}
|
|
if let Some(properties) = self.properties {
|
|
visit(properties);
|
|
}
|
|
for child in &self.children {
|
|
visit(child.block);
|
|
}
|
|
for item in &self.history {
|
|
visit(*item);
|
|
}
|
|
if let Some((source, _)) = &self.text_binding {
|
|
visit(*source);
|
|
}
|
|
for binding in &self.bindings {
|
|
visit(*binding);
|
|
}
|
|
for token in &self.subscriptions {
|
|
visit(*token);
|
|
}
|
|
if let Some(handler) = self.click {
|
|
visit(handler);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 分配 Data、共享 Cell 和 Block 包装,并让托管图拥有必要引用。
|
|
pub fn allocate(cx: &mut NativeContext<'_>, mut data: Data) -> Result<ObjectRef, VmError> {
|
|
let page = matches!(data.kind, Kind::Page);
|
|
// 分配拥有边前检查每个孩子都是有效有限 Block 图;非法组成直接失败,不截断部分 UI。
|
|
for child in &data.children {
|
|
validate(cx.store(), child.block, None)?;
|
|
}
|
|
// 把原生默认参数显式写成普通属性,使源赋值、绑定及精确依赖跟踪观察到同一存储。
|
|
let properties = cx.new_object()?;
|
|
for (name, value) in native_properties(&data) {
|
|
cx.set_attr(properties, name, value)?;
|
|
}
|
|
data.properties = Some(properties);
|
|
let data = cx.allocate(data)?;
|
|
// 最终建立 Block -> Cell -> Data -> properties/children 拥有链,均在 VM 中参与追踪和循环回收。
|
|
let state = cx.new_cell(Some(Value::Object(data)))?;
|
|
cx.allocate(Block {
|
|
state,
|
|
page,
|
|
tasks: None,
|
|
})
|
|
}
|
|
|
|
/// Borrowed final data; forwarding is part of the managed graph, never an Arc
|
|
/// ownership graph hidden from the VM's cycle collector.
|
|
/// 解析一个 Block 当前指向的 Data,返回底层身份和借用描述。
|
|
pub fn resolve(store: &ObjectStore, block: ObjectRef) -> Result<(ObjectRef, &Data), VmError> {
|
|
let (reference, data, _) = resolve_tracked(store, block)?;
|
|
Ok((reference, data))
|
|
}
|
|
|
|
/// 解析 Block 的完整引用路径,并返回快照失效所需的依赖身份。
|
|
pub fn resolve_tracked(
|
|
store: &ObjectStore,
|
|
block: ObjectRef,
|
|
) -> Result<(ObjectRef, &Data, Vec<ObjectRef>), VmError> {
|
|
let mut current = block;
|
|
let mut seen = std::collections::HashSet::new();
|
|
let mut dependencies = Vec::new();
|
|
loop {
|
|
// 解析整条转发路径防环;依赖收集同时记录每层 Block 与 Cell,任一转发变更都会让视觉缓存失效。
|
|
if !seen.insert(current) {
|
|
return Err(VmError::InvalidArgument("cyclic Block reference"));
|
|
}
|
|
let state = store.payload::<Block>(current, "Block")?.state;
|
|
dependencies.extend([current, state]);
|
|
let Value::Object(value) = store.cell_get(state)? else {
|
|
return Err(VmError::InvalidArgument("Block state is not an object"));
|
|
};
|
|
// 遇到 Data 返回最终存储身份与借用引用;否则下一轮要求该值必须是 Block,不接受任意对象。
|
|
if store.object(value)?.payload().as_any().is::<Data>() {
|
|
dependencies.push(value);
|
|
return Ok((
|
|
value,
|
|
store.payload::<Data>(value, "Block data")?,
|
|
dependencies,
|
|
));
|
|
}
|
|
current = value;
|
|
}
|
|
}
|
|
|
|
/// Validate the entire finite expansion before establishing a new composition
|
|
/// edge. The node count is an explicit rejected resource quota, not truncated UI.
|
|
/// 完整展开 Block/Cell/孩子图,拒绝环、禁止目标回边及超过 10000 次展开的组成。
|
|
pub fn validate(
|
|
store: &ObjectStore,
|
|
root: ObjectRef,
|
|
forbidden_state: Option<ObjectRef>,
|
|
) -> Result<(), VmError> {
|
|
// 显式进入/退出栈模拟深度优先遍历;退出时移除祖先链标记,允许共享子树。
|
|
enum Step {
|
|
Enter(ObjectRef),
|
|
Exit(ObjectRef),
|
|
}
|
|
let mut work = vec![Step::Enter(root)];
|
|
let mut path = std::collections::HashSet::new();
|
|
let mut visits = 0;
|
|
while let Some(step) = work.pop() {
|
|
match step {
|
|
Step::Exit(state) => {
|
|
path.remove(&state);
|
|
}
|
|
Step::Enter(block) => {
|
|
// 预算按实际展开次数而非不同对象数计算,共享子树重复出现也计入资源工作量。
|
|
visits += 1;
|
|
if visits > 10_000 {
|
|
return Err(VmError::ExecutionLimit("expanded Block graph"));
|
|
}
|
|
let state = store.payload::<Block>(block, "Block")?.state;
|
|
// path 只追踪当前祖先 Cell,允许其他分支共享同一组件;forbidden_state 额外阻止新边回到将被修改的目标。
|
|
if forbidden_state == Some(state) || !path.insert(state) {
|
|
return Err(VmError::InvalidArgument(
|
|
"Block composition would create a cycle",
|
|
));
|
|
}
|
|
work.push(Step::Exit(state));
|
|
let Value::Object(value) = store.cell_get(state)? else {
|
|
return Err(VmError::InvalidArgument("invalid Block state"));
|
|
};
|
|
if forbidden_state == Some(value) {
|
|
return Err(VmError::InvalidArgument(
|
|
"Block composition would create a cycle",
|
|
));
|
|
}
|
|
// Data 展开孩子,非 Data 则沿共享赋值转发链继续;显式 Exit 在子树完成后清除祖先标记。
|
|
if let Ok(data) = store.payload::<Data>(value, "Block data") {
|
|
for child in data.children.iter().rev() {
|
|
work.push(Step::Enter(child.block));
|
|
}
|
|
} else {
|
|
work.push(Step::Enter(value));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// 用一次性空 RenderCache 提取不可变视觉树;不跨调用保存快照缓存。
|
|
pub fn snapshot(store: &ObjectStore, root: ObjectRef) -> Result<Arc<UiNode>, VmError> {
|
|
// 一次性提取使用空缓存,不保留跨调用结果;有增量复用需求的窗口应使用自己的 RenderCache。
|
|
crate::snapshot::RenderCache::default().snapshot(store, root)
|
|
}
|
|
|
|
/// Native visual parameters are ordinary managed attributes too. Composition,
|
|
/// histories and connections remain structural payload edges.
|
|
/// 列出本类型可投影到托管属性的原生字段及默认值。
|
|
pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
|
|
/// 在源 Value 与所需数值表示之间转换,并沿用本调用的有限值/范围检查。
|
|
fn number(value: f32) -> Value {
|
|
Value::Number((value as f64).into())
|
|
}
|
|
// 先枚举每种 Block 都有的定位、弹性、盒尺寸、边框与对齐属性,再按 kind 增补专有字段。
|
|
let mut fields = vec![
|
|
("x", number(data.position[0])),
|
|
("y", number(data.position[1])),
|
|
("flex", number(data.flex)),
|
|
(
|
|
"flexBasis",
|
|
data.flex_policy
|
|
.basis
|
|
.map_or_else(|| Value::Text("auto".into()), number),
|
|
),
|
|
("flexMin", number(data.flex_policy.min)),
|
|
("flexMax", number(data.flex_policy.max)),
|
|
("flexShrink", number(data.flex_policy.shrink)),
|
|
("marginTop", number(data.margin.top)),
|
|
("marginRight", number(data.margin.right)),
|
|
("marginBottom", number(data.margin.bottom)),
|
|
("marginLeft", number(data.margin.left)),
|
|
("boxWidth", data.sizing.width.value()),
|
|
("boxHeight", data.sizing.height.value()),
|
|
("minWidth", number(data.sizing.min_width)),
|
|
("minHeight", number(data.sizing.min_height)),
|
|
("maxWidth", number(data.sizing.max_width)),
|
|
("maxHeight", number(data.sizing.max_height)),
|
|
("borderTop", number(data.border.top)),
|
|
("borderRight", number(data.border.right)),
|
|
("borderBottom", number(data.border.bottom)),
|
|
("borderLeft", number(data.border.left)),
|
|
("borderColor", Value::Text(data.border_color.clone())),
|
|
(
|
|
"overflow",
|
|
Value::Text(
|
|
if data.clip_children {
|
|
"clip"
|
|
} else {
|
|
"visible"
|
|
}
|
|
.into(),
|
|
),
|
|
),
|
|
(
|
|
"alignSelf",
|
|
Value::Text(
|
|
data.align_self
|
|
.map_or("auto", crate::layout::CrossAlign::name)
|
|
.into(),
|
|
),
|
|
),
|
|
];
|
|
for (name, edge) in ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"]
|
|
.into_iter()
|
|
.zip(data.padding_edges)
|
|
{
|
|
fields.push((
|
|
name,
|
|
// 单边 padding 的 auto 编码成文本,不用数值哨兵,读取时才能区分“继承统一值”和显式零。
|
|
edge.map_or_else(|| Value::Text("auto".into()), number),
|
|
));
|
|
}
|
|
match &data.kind {
|
|
Kind::Viewport3D { width, height } => fields.extend([
|
|
("width", number(*width)),
|
|
("height", number(*height)),
|
|
("scene", data.scene3d.map_or(Value::Nil, Value::Object)),
|
|
(
|
|
"controller",
|
|
data.controller
|
|
.map_or_else(|| Value::Text("none".into()), Value::Object),
|
|
),
|
|
("camera", data.camera.map_or(Value::Nil, Value::Object)),
|
|
]),
|
|
Kind::CanvasViewport { width, height } => fields.extend([
|
|
("width", number(*width)),
|
|
("height", number(*height)),
|
|
("camera", data.camera.map_or(Value::Nil, Value::Object)),
|
|
]),
|
|
Kind::Page => fields.extend([
|
|
("mode", Value::Text(data.surface.mode.name().into())),
|
|
("panX", number(data.surface.pan.x)),
|
|
("panY", number(data.surface.pan.y)),
|
|
("zoom", number(data.surface.zoom)),
|
|
]),
|
|
Kind::Text { value, size, color } => fields.extend([
|
|
("text", Value::Text(value.clone())),
|
|
("size", Value::Number((*size as i64).into())),
|
|
("color", Value::Text(color.clone())),
|
|
]),
|
|
Kind::Rect {
|
|
width,
|
|
height,
|
|
radius,
|
|
color,
|
|
} => fields.extend([
|
|
("width", number(*width)),
|
|
("height", number(*height)),
|
|
("radius", number(*radius)),
|
|
("color", Value::Text(color.clone())),
|
|
]),
|
|
Kind::Scroll { width, height } => fields.extend([
|
|
("width", number(*width)),
|
|
("height", number(*height)),
|
|
("axis", Value::Text(data.scroll_axis.name().into())),
|
|
]),
|
|
Kind::Spacer(size) => fields.push(("size", number(*size))),
|
|
_ => {}
|
|
}
|
|
// 容器才暴露统一 padding/gap 与主交叉轴策略;叶节点不因同名自定义字段被当成通用容器。
|
|
if data.is_container() {
|
|
fields.extend([
|
|
("padding", number(data.padding)),
|
|
("gap", number(data.gap)),
|
|
("mainAlign", Value::Text(data.main_align.name().into())),
|
|
("crossAlign", Value::Text(data.cross_align.name().into())),
|
|
]);
|
|
}
|
|
fields
|
|
}
|
|
|
|
/// 复制原生描述并用当前托管属性覆盖它;结果只用于展示,不反向修改业务对象。
|
|
pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
|
// 只改本轮派生副本,逐个读取实际属性并验证;读取字段名集合来自 native_properties,不遍历任意用户字段。
|
|
let mut data = data.clone();
|
|
let properties = data
|
|
.properties
|
|
.ok_or(VmError::InvalidArgument("missing Block properties"))?;
|
|
for (name, _) in native_properties(&data) {
|
|
let value = store.get_attr(properties, name)?;
|
|
apply_visual_property(&mut data, name, &value)?;
|
|
}
|
|
// 各单值合法仍可能存在跨字段矛盾,必须在全部覆盖完成后校验 min/max 关系。
|
|
if data.flex_policy.min > data.flex_policy.max {
|
|
return Err(VmError::InvalidArgument("flexMin exceeds flexMax"));
|
|
}
|
|
if data.sizing.min_width > data.sizing.max_width
|
|
|| data.sizing.min_height > data.sizing.max_height
|
|
{
|
|
return Err(VmError::InvalidArgument("box minimum exceeds maximum"));
|
|
}
|
|
if matches!(data.kind, Kind::CanvasViewport { .. }) {
|
|
crate::viewport::camera(
|
|
store,
|
|
data.camera.ok_or(VmError::InvalidArgument(
|
|
"CanvasViewport requires a Camera2D",
|
|
))?,
|
|
)?;
|
|
// CanvasViewport 只容纳一个 Scene2D 根,允许其内部无限空间布局,但不接受多个普通孩子冒充场景。
|
|
if data.children.len() != 1
|
|
|| !matches!(
|
|
resolve(store, data.children[0].block)?.1.kind,
|
|
Kind::Scene2D
|
|
)
|
|
{
|
|
return Err(VmError::InvalidArgument(
|
|
"CanvasViewport requires exactly one Scene2D",
|
|
));
|
|
}
|
|
}
|
|
if matches!(data.kind, Kind::Viewport3D { .. })
|
|
&& let Some(controller) = data.controller
|
|
{
|
|
let definition = store.type_of(controller)?.ok_or(VmError::InvalidArgument(
|
|
"3D controller requires a nominal update method",
|
|
))?;
|
|
// 3D 控制器要求名义类型上的 update,接受含接收者在内三参;调用执行与预算在输入分发路径处理。
|
|
let method = store
|
|
.lookup_method(definition, "update")?
|
|
.ok_or(VmError::InvalidArgument(
|
|
"3D controller must define update(camera, gesture)",
|
|
))?;
|
|
if store
|
|
.call_arity(method)?
|
|
.is_none_or(|arity| !arity.accepts(3))
|
|
{
|
|
return Err(VmError::InvalidArgument(
|
|
"3D controller update expects camera and CameraGesture",
|
|
));
|
|
}
|
|
}
|
|
Ok(data)
|
|
}
|
|
|
|
/// 按属性名检查和解码源值,再更新对应视觉字段;非法尺寸、枚举或颜色被拒绝。
|
|
pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Result<(), VmError> {
|
|
let bad = || VmError::InvalidArgument("invalid native visual property");
|
|
// 常规视觉长度/系数只接受非负有限值;坐标和 pan 在下面走允许负数的独立路径。
|
|
let number = || -> Result<f32, VmError> {
|
|
let Value::Number(value) = value else {
|
|
return Err(bad());
|
|
};
|
|
let n = value.to_string().parse::<f32>().map_err(|_| bad())?;
|
|
if !n.is_finite() || !(0.0..=crate::ui_bridge::MAX_DIMENSION as f32).contains(&n) {
|
|
return Err(bad());
|
|
}
|
|
Ok(n)
|
|
};
|
|
// x/y 对所有组件生效;页面 pan/zoom 只作用 Page。这里不是任意字段存在性校验,不适用种类会跳过更新。
|
|
if matches!(name, "x" | "y" | "panX" | "panY" | "zoom") {
|
|
let n = crate::scroll::coordinate(value)?;
|
|
match name {
|
|
"x" => data.position[0] = n,
|
|
"y" => data.position[1] = n,
|
|
"panX" if matches!(data.kind, Kind::Page) => data.surface.pan.x = n,
|
|
"panY" if matches!(data.kind, Kind::Page) => data.surface.pan.y = n,
|
|
"zoom" if matches!(data.kind, Kind::Page) => {
|
|
// Page 兼容相机缩放范围不同于独立 Camera2D 的 0.01..100,保持两套源协议各自限制。
|
|
if !(0.1..=4.0).contains(&n) {
|
|
return Err(invalid_zoom());
|
|
}
|
|
data.surface.zoom = n;
|
|
}
|
|
_ => {}
|
|
}
|
|
return Ok(());
|
|
}
|
|
if matches!(data.kind, Kind::Page) && name == "mode" {
|
|
let Value::Text(name) = value else {
|
|
return Err(bad());
|
|
};
|
|
data.surface.mode = crate::page::Mode::parse(name)?;
|
|
return Ok(());
|
|
}
|
|
match name {
|
|
// controller 接受对象或明确的字符串 none,不能拿 Nil 隐式取消;后续 visual_data 检查其名义方法。
|
|
"controller" if matches!(data.kind, Kind::Viewport3D { .. }) => {
|
|
data.controller = match value {
|
|
Value::Object(controller) => Some(*controller),
|
|
Value::Text(text) if text == "none" => None,
|
|
_ => return Err(bad()),
|
|
};
|
|
return Ok(());
|
|
}
|
|
// camera/scene 这里仅检查 Object 并记录身份,实际 payload/结构验证由各视口快照入口继续执行。
|
|
"camera"
|
|
if matches!(
|
|
data.kind,
|
|
Kind::CanvasViewport { .. } | Kind::Viewport3D { .. }
|
|
) =>
|
|
{
|
|
let Value::Object(camera) = value else {
|
|
return Err(bad());
|
|
};
|
|
data.camera = Some(*camera);
|
|
return Ok(());
|
|
}
|
|
"scene" if matches!(data.kind, Kind::Viewport3D { .. }) => {
|
|
let Value::Object(scene) = value else {
|
|
return Err(bad());
|
|
};
|
|
data.scene3d = Some(*scene);
|
|
return Ok(());
|
|
}
|
|
"paddingTop" | "paddingRight" | "paddingBottom" | "paddingLeft" => {
|
|
let index = match name {
|
|
"paddingTop" => 0,
|
|
"paddingRight" => 1,
|
|
"paddingBottom" => 2,
|
|
_ => 3,
|
|
};
|
|
// 单边 auto 清除覆盖值;数值零保留 Some(0),从而确实覆盖统一 padding。
|
|
data.padding_edges[index] = if matches!(value, Value::Text(text) if text == "auto") {
|
|
None
|
|
} else {
|
|
Some(number()?)
|
|
};
|
|
return Ok(());
|
|
}
|
|
"borderTop" => {
|
|
data.border.top = number()?;
|
|
return Ok(());
|
|
}
|
|
"borderRight" => {
|
|
data.border.right = number()?;
|
|
return Ok(());
|
|
}
|
|
"borderBottom" => {
|
|
data.border.bottom = number()?;
|
|
return Ok(());
|
|
}
|
|
"borderLeft" => {
|
|
data.border.left = number()?;
|
|
return Ok(());
|
|
}
|
|
"borderColor" => {
|
|
let Value::Text(color) = value else {
|
|
return Err(bad());
|
|
};
|
|
crate::document::parse_color(color).map_err(|_| bad())?;
|
|
data.border_color.clone_from(color);
|
|
return Ok(());
|
|
}
|
|
"overflow" => {
|
|
let Value::Text(overflow) = value else {
|
|
return Err(bad());
|
|
};
|
|
// overflow 只切换可见/裁剪,不暗中启用滚动;需要偏移与输入消费必须使用 ScrollBlock。
|
|
data.clip_children = match overflow.as_str() {
|
|
"clip" => true,
|
|
"visible" => false,
|
|
_ => {
|
|
return Err(VmError::InvalidArgument(
|
|
"overflow expects visible or clip; use ScrollBlock for scrolling",
|
|
));
|
|
}
|
|
};
|
|
return Ok(());
|
|
}
|
|
"boxWidth" => {
|
|
data.sizing.width = crate::box_model::Dimension::parse(value)?;
|
|
return Ok(());
|
|
}
|
|
"boxHeight" => {
|
|
data.sizing.height = crate::box_model::Dimension::parse(value)?;
|
|
return Ok(());
|
|
}
|
|
"minWidth" => {
|
|
data.sizing.min_width = number()?;
|
|
return Ok(());
|
|
}
|
|
"minHeight" => {
|
|
data.sizing.min_height = number()?;
|
|
return Ok(());
|
|
}
|
|
"maxWidth" => {
|
|
data.sizing.max_width = number()?;
|
|
return Ok(());
|
|
}
|
|
"maxHeight" => {
|
|
data.sizing.max_height = number()?;
|
|
return Ok(());
|
|
}
|
|
"marginTop" => {
|
|
data.margin.top = number()?;
|
|
return Ok(());
|
|
}
|
|
"marginRight" => {
|
|
data.margin.right = number()?;
|
|
return Ok(());
|
|
}
|
|
"marginBottom" => {
|
|
data.margin.bottom = number()?;
|
|
return Ok(());
|
|
}
|
|
"marginLeft" => {
|
|
data.margin.left = number()?;
|
|
return Ok(());
|
|
}
|
|
// basis 的 Nil 与 auto 都表示内容基准;其他值使用非负长度检查。flexMin/Max 的相互关系在完整提取后验证。
|
|
"flexBasis" => {
|
|
data.flex_policy.basis = if matches!(value, Value::Nil)
|
|
|| matches!(value, Value::Text(text) if text == "auto")
|
|
{
|
|
None
|
|
} else {
|
|
Some(number()?)
|
|
};
|
|
return Ok(());
|
|
}
|
|
"flexMin" => {
|
|
data.flex_policy.min = number()?;
|
|
return Ok(());
|
|
}
|
|
"flexMax" => {
|
|
data.flex_policy.max = number()?;
|
|
return Ok(());
|
|
}
|
|
"flexShrink" => {
|
|
data.flex_policy.shrink = number()?;
|
|
return Ok(());
|
|
}
|
|
_ => {}
|
|
}
|
|
if name == "flex" {
|
|
data.flex = number()?;
|
|
return Ok(());
|
|
}
|
|
let container = data.is_container();
|
|
// alignSelf 可由任何孩子独立声明,crossAlign 只解释容器配置;auto 恢复继承父交叉轴策略。
|
|
if name == "alignSelf" || (container && name == "crossAlign") {
|
|
let Value::Text(value) = value else {
|
|
return Err(bad());
|
|
};
|
|
if name == "alignSelf" {
|
|
data.align_self = if value == "auto" {
|
|
None
|
|
} else {
|
|
Some(crate::layout::CrossAlign::parse(value)?)
|
|
};
|
|
} else {
|
|
data.cross_align = crate::layout::CrossAlign::parse(value)?;
|
|
}
|
|
return Ok(());
|
|
}
|
|
if container && name == "mainAlign" {
|
|
let Value::Text(value) = value else {
|
|
return Err(bad());
|
|
};
|
|
data.main_align = crate::layout::MainAlign::parse(value)?;
|
|
return Ok(());
|
|
}
|
|
match (&mut data.kind, name) {
|
|
(Kind::Viewport3D { width, .. }, "width") => *width = number()?,
|
|
(Kind::Viewport3D { height, .. }, "height") => *height = number()?,
|
|
(Kind::CanvasViewport { width, .. }, "width") => *width = number()?,
|
|
(Kind::CanvasViewport { height, .. }, "height") => *height = number()?,
|
|
(Kind::Text { value: text, .. }, "text") => {
|
|
let Value::Text(value) = value else {
|
|
return Err(bad());
|
|
};
|
|
// 文本属性按 UTF-8 字节设 16 KiB 上限,防止单个 Block 超过原生视觉文本预算。
|
|
if value.len() > 16_384 {
|
|
return Err(bad());
|
|
}
|
|
text.clone_from(value);
|
|
}
|
|
(Kind::Text { size, .. }, "size") => {
|
|
let n = number()?;
|
|
// Text size 是 1..8 的离散倍率,不能把任意浮点字号通过 as u32 悄悄截断。
|
|
if !(1.0..=8.0).contains(&n) || n.fract() != 0.0 {
|
|
return Err(bad());
|
|
}
|
|
*size = n as u32;
|
|
}
|
|
(Kind::Text { color, .. } | Kind::Rect { color, .. }, "color") => {
|
|
let Value::Text(value) = value else {
|
|
return Err(bad());
|
|
};
|
|
// 颜色赋值先验证文本格式再替换派生颜色,避免错误字符串进入软件渲染器。
|
|
crate::document::parse_color(value).map_err(|_| bad())?;
|
|
color.clone_from(value);
|
|
}
|
|
(Kind::Scroll { .. }, "axis") => {
|
|
let Value::Text(name) = value else {
|
|
return Err(bad());
|
|
};
|
|
data.scroll_axis = crate::scroll::Axis::parse(name)?;
|
|
}
|
|
(Kind::Scroll { width, .. }, "width") => *width = number()?,
|
|
(Kind::Scroll { height, .. }, "height") => *height = number()?,
|
|
(Kind::Rect { width, .. }, "width") => *width = number()?,
|
|
(Kind::Rect { height, .. }, "height") => *height = number()?,
|
|
(Kind::Rect { radius, .. }, "radius") => *radius = number()?,
|
|
(Kind::Spacer(size), "size") => *size = number()?,
|
|
// 剩余 kind 专有尺寸与容器字段按各自规则覆盖;未知字段忽略,不在此处删除或修改用户自定义属性。
|
|
(_, "padding") if container => data.padding = number()?,
|
|
(_, "gap") if container => data.gap = number()?,
|
|
_ => {}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// 统一返回非法页面缩放错误,确保属性写入与输入路径使用相同限制。
|
|
fn invalid_zoom() -> VmError {
|
|
VmError::InvalidArgument("Page.zoom expects a number from 0.1 to 4")
|
|
}
|