Skip to main content

velox_engine/element/
mod.rs

1//! 闭合枚举 `Element<'a>`、`Div<'a>`、`Text<'a>`、`Img<'a>`、侵入式单向兄弟链表与 `View` / `Widget` 组件接口。
2//!
3//! 模块职责划分:
4//! - `div`:`Div<'a>` 弹性盒容器构造器、`DivNode` / `DivVisual` / `DivInteractivity` 与过渡动画配置;
5//! - `text`:`Text<'a>` 文本原子节点与排版修饰符;
6//! - `image`:`SpriteSource<'a>` 与 `Img<'a>` 位图/矢量精灵/GPU 原生圆弧节点。
7
8mod div;
9mod div_node;
10mod image;
11mod text;
12
13use core::cell::Cell;
14
15use crate::pod::{FrameScope, Handle, PodId, Scope};
16
17pub use div::{div, Div};
18pub use div_node::{
19    DivInteractivity, DivNode, DivRareHandlers, DivVisual, EnterFrom, TransitionSpec,
20};
21pub use image::{
22    img, img_arc, img_rotated_rgb565, img_shader, svg, svg_a4, svg_icon, svg_path, svg_str, Img,
23    SpriteSource,
24};
25pub use text::{text, Text};
26
27/// 有状态视图接口(常驻 `PodPool`,拥有独立局部刷新边界)。
28pub trait View: Sized + 'static {
29    fn render<'a>(&mut self, cx: &'a mut Scope<Self>) -> Element<'a>;
30}
31
32/// 无状态轻量组件接口(不占 `PodPool` 槽位,直接在 `ScratchArena` 中内联展开为 `div` 树)。
33pub trait Widget<'a>: Sized {
34    fn render_once(self, cx: &'a FrameScope) -> Element<'a>;
35}
36
37/// 将基础原语或无状态 `Widget` 统一转换为 `Element<'a>` 的转换 Trait。
38pub trait IntoElement<'a>: Sized {
39    fn into_element(self, cx: &'a FrameScope) -> Element<'a>;
40
41    /// 与 GPUI `.into_any_element()` 对应的语义别名(零堆分配返回闭合枚举 `Element<'a>`)。
42    #[inline(always)]
43    fn into_any_element(self, cx: &'a FrameScope) -> Element<'a> {
44        self.into_element(cx)
45    }
46}
47
48impl<'a> IntoElement<'a> for Element<'a> {
49    #[inline(always)]
50    fn into_element(self, _cx: &'a FrameScope) -> Element<'a> {
51        self
52    }
53}
54
55
56impl<'a, W: Widget<'a>> IntoElement<'a> for W {
57    #[inline(always)]
58    fn into_element(self, cx: &'a FrameScope) -> Element<'a> {
59        self.render_once(cx)
60    }
61}
62
63impl<'a, V: View> IntoElement<'a> for Handle<V> {
64    #[inline(always)]
65    fn into_element(self, _cx: &'a FrameScope) -> Element<'a> {
66        Element::SubView {
67            id: self.id,
68            generation: self.generation,
69            resolved: Cell::new(None),
70        }
71    }
72}
73
74/// 侵入式单向链表节点(分配在 `ScratchArena` 中,使用 `Cell` 提供安全的内部可变性)。
75pub struct ElementNode<'a> {
76    pub element: Element<'a>,
77    /// 指向 `ScratchArena` 中的下一个同级兄弟节点(实现零 `Vec` 扩容的无限 `.child()` 追加)。
78    pub next_sibling: Cell<Option<&'a ElementNode<'a>>>,
79}
80
81/// 闭合 UI 元素枚举(严格限定 4 种核心节点,彻底消除 `Box<dyn Element>` 虚表开销与内存碎片)。
82pub enum Element<'a> {
83    /// 弹性盒容器节点(64B 紧凑核心 + 按需分配在 `ScratchArena` 中的视觉/交互扩展)。
84    Div(DivNode<'a>),
85    /// 文本节点。
86    Text(Text<'a>),
87    /// 位图/图标掩码或过程化贴图节点(对应 `DrawPayload::Sprite`)。
88    Img(Img<'a>),
89    /// 视图边界:引用另一个常驻 `Handle<T>`(`PodId` + `generation`),作为局部重绘与独立布局的隔离点。
90    SubView {
91        id: PodId,
92        generation: u16,
93        resolved: Cell<Option<&'a Element<'a>>>,
94    },
95}
96