docs: 逐模块细化中文逻辑注释并覆盖测试与示例
This commit is contained in:
+45
-3
@@ -13,6 +13,7 @@ use crate::ui_bridge::UiNode;
|
||||
#[derive(Debug, Clone)]
|
||||
/// 稳定组成 slot 与子 Block 的配对;slot 不依赖孩子当前的屏幕位置。
|
||||
pub struct Child {
|
||||
// slot 标识父组件中这条组成边,移动行序不改变它;同一 Block 可通过不同 slot 出现多次。
|
||||
pub slot: u64,
|
||||
pub block: ObjectRef,
|
||||
}
|
||||
@@ -57,6 +58,7 @@ pub enum Kind {
|
||||
#[derive(Debug, Clone)]
|
||||
/// 对共享 Cell 的稳定包装。赋值可让所有别名一起改指向,而每次出现的 Mount 仍独立。
|
||||
pub struct Block {
|
||||
// 共享赋值单元 Cell;其值可为最终 Data 或另一个 Block,从而保留别名身份并转发属性/类型查询。
|
||||
pub state: ObjectRef,
|
||||
pub page: bool,
|
||||
pub tasks: Option<ObjectRef>,
|
||||
@@ -72,6 +74,7 @@ impl ObjectPayload for Block {
|
||||
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 {
|
||||
@@ -94,6 +97,7 @@ impl ObjectPayload for Block {
|
||||
Ok(Some(value))
|
||||
} else {
|
||||
store.payload::<Data>(value, "Block data")?;
|
||||
// 到达最终 Data 时停止类型转发,使用当前 Block 自身名义类型;只有替换为其他 Block 才继续转发类型。
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@@ -126,11 +130,13 @@ impl ObjectPayload for Block {
|
||||
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))
|
||||
}
|
||||
@@ -150,6 +156,7 @@ pub struct Data {
|
||||
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,
|
||||
@@ -160,19 +167,23 @@ pub struct Data {
|
||||
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,
|
||||
@@ -215,6 +226,7 @@ impl Data {
|
||||
}
|
||||
/// 检查原生组件种类是否承载子组成,供树修改和布局选择使用。
|
||||
pub fn is_container(&self) -> bool {
|
||||
// 这些类别允许通过通用 Children 方法编辑;Viewport3D 的面板内容来自 Scene3D 提取,不是普通 children 列表。
|
||||
matches!(
|
||||
self.kind,
|
||||
Kind::Row
|
||||
@@ -244,6 +256,7 @@ impl ObjectPayload for Data {
|
||||
}
|
||||
/// 枚举本对象真正拥有的托管强引用,供 Aster 引用追踪和循环回收使用。
|
||||
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
|
||||
// 所有结构字段中出现的托管强引用必须枚举:场景/相机、属性存储、孩子、历史、绑定、订阅和回调。
|
||||
if let Some(scene) = self.scene3d {
|
||||
visit(scene);
|
||||
}
|
||||
@@ -280,15 +293,18 @@ impl ObjectPayload for Data {
|
||||
/// 分配 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,
|
||||
@@ -314,6 +330,7 @@ pub fn resolve_tracked(
|
||||
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"));
|
||||
}
|
||||
@@ -322,6 +339,7 @@ pub fn resolve_tracked(
|
||||
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((
|
||||
@@ -336,7 +354,7 @@ pub fn resolve_tracked(
|
||||
|
||||
/// 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,
|
||||
@@ -356,11 +374,13 @@ pub fn validate(
|
||||
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",
|
||||
@@ -375,6 +395,7 @@ pub fn validate(
|
||||
"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));
|
||||
@@ -388,8 +409,9 @@ pub fn validate(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 将当前托管或可变状态提取为后续阶段使用的派生表示。
|
||||
/// 用一次性空 RenderCache 提取不可变视觉树;不跨调用保存快照缓存。
|
||||
pub fn snapshot(store: &ObjectStore, root: ObjectRef) -> Result<Arc<UiNode>, VmError> {
|
||||
// 一次性提取使用空缓存,不保留跨调用结果;有增量复用需求的窗口应使用自己的 RenderCache。
|
||||
crate::snapshot::RenderCache::default().snapshot(store, root)
|
||||
}
|
||||
|
||||
@@ -401,6 +423,7 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, 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])),
|
||||
@@ -455,6 +478,7 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
|
||||
{
|
||||
fields.push((
|
||||
name,
|
||||
// 单边 padding 的 auto 编码成文本,不用数值哨兵,读取时才能区分“继承统一值”和显式零。
|
||||
edge.map_or_else(|| Value::Text("auto".into()), number),
|
||||
));
|
||||
}
|
||||
@@ -505,6 +529,7 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
|
||||
Kind::Spacer(size) => fields.push(("size", number(*size))),
|
||||
_ => {}
|
||||
}
|
||||
// 容器才暴露统一 padding/gap 与主交叉轴策略;叶节点不因同名自定义字段被当成通用容器。
|
||||
if data.is_container() {
|
||||
fields.extend([
|
||||
("padding", number(data.padding)),
|
||||
@@ -518,6 +543,7 @@ pub fn native_properties(data: &Data) -> Vec<(&'static str, Value)> {
|
||||
|
||||
/// 复制原生描述并用当前托管属性覆盖它;结果只用于展示,不反向修改业务对象。
|
||||
pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
||||
// 只改本轮派生副本,逐个读取实际属性并验证;读取字段名集合来自 native_properties,不遍历任意用户字段。
|
||||
let mut data = data.clone();
|
||||
let properties = data
|
||||
.properties
|
||||
@@ -526,6 +552,7 @@ pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
||||
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"));
|
||||
}
|
||||
@@ -541,6 +568,7 @@ pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
||||
"CanvasViewport requires a Camera2D",
|
||||
))?,
|
||||
)?;
|
||||
// CanvasViewport 只容纳一个 Scene2D 根,允许其内部无限空间布局,但不接受多个普通孩子冒充场景。
|
||||
if data.children.len() != 1
|
||||
|| !matches!(
|
||||
resolve(store, data.children[0].block)?.1.kind,
|
||||
@@ -558,6 +586,7 @@ pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
||||
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(
|
||||
@@ -578,6 +607,7 @@ pub fn visual_data(store: &ObjectStore, data: &Data) -> Result<Data, VmError> {
|
||||
/// 按属性名检查和解码源值,再更新对应视觉字段;非法尺寸、枚举或颜色被拒绝。
|
||||
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());
|
||||
@@ -588,6 +618,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
}
|
||||
Ok(n)
|
||||
};
|
||||
// x/y 对所有组件生效;页面 pan/zoom 只作用 Page。这里不是任意字段存在性校验,不适用种类会跳过更新。
|
||||
if matches!(name, "x" | "y" | "panX" | "panY" | "zoom") {
|
||||
let n = crate::scroll::coordinate(value)?;
|
||||
match name {
|
||||
@@ -596,6 +627,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
"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());
|
||||
}
|
||||
@@ -613,6 +645,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
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),
|
||||
@@ -621,6 +654,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
};
|
||||
return Ok(());
|
||||
}
|
||||
// camera/scene 这里仅检查 Object 并记录身份,实际 payload/结构验证由各视口快照入口继续执行。
|
||||
"camera"
|
||||
if matches!(
|
||||
data.kind,
|
||||
@@ -647,6 +681,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
"paddingBottom" => 2,
|
||||
_ => 3,
|
||||
};
|
||||
// 单边 auto 清除覆盖值;数值零保留 Some(0),从而确实覆盖统一 padding。
|
||||
data.padding_edges[index] = if matches!(value, Value::Text(text) if text == "auto") {
|
||||
None
|
||||
} else {
|
||||
@@ -682,6 +717,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
let Value::Text(overflow) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
// overflow 只切换可见/裁剪,不暗中启用滚动;需要偏移与输入消费必须使用 ScrollBlock。
|
||||
data.clip_children = match overflow.as_str() {
|
||||
"clip" => true,
|
||||
"visible" => false,
|
||||
@@ -733,6 +769,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
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")
|
||||
@@ -762,6 +799,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
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());
|
||||
@@ -793,6 +831,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
let Value::Text(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
// 文本属性按 UTF-8 字节设 16 KiB 上限,防止单个 Block 超过原生视觉文本预算。
|
||||
if value.len() > 16_384 {
|
||||
return Err(bad());
|
||||
}
|
||||
@@ -800,6 +839,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
}
|
||||
(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());
|
||||
}
|
||||
@@ -809,6 +849,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
let Value::Text(value) = value else {
|
||||
return Err(bad());
|
||||
};
|
||||
// 颜色赋值先验证文本格式再替换派生颜色,避免错误字符串进入软件渲染器。
|
||||
crate::document::parse_color(value).map_err(|_| bad())?;
|
||||
color.clone_from(value);
|
||||
}
|
||||
@@ -824,6 +865,7 @@ pub fn apply_visual_property(data: &mut Data, name: &str, value: &Value) -> Resu
|
||||
(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()?,
|
||||
_ => {}
|
||||
|
||||
Reference in New Issue
Block a user