Skip to main content

velox_engine/element/
div_node.rs

1//! 紧凑 64B `DivNode`、按需分配视觉/交互扩展(`DivVisual` / `DivInteractivity`)与过渡动画配置(`TransitionSpec`)。
2
3use core::time::Duration;
4
5use crate::pod::{ActionScope, CursorShape};
6use crate::style::{AlignItems, Color, Easing, Edges, LoopMode, Style, StyleRefinement};
7
8use super::ElementNode;
9
10const VIS_FLAG_HAS_POS: u8 = 1 << 0;
11const VIS_FLAG_HAS_SCROLL: u8 = 1 << 1;
12const VIS_FLAG_HAS_BG_GRAD: u8 = 1 << 2;
13const VIS_FLAG_BG_GRAD_HORIZ: u8 = 1 << 3;
14const VIS_FLAG_ITEMS_BASELINE: u8 = 1 << 4;
15const VIS_ALIGN_SHIFT: u8 = 5;
16pub(super) const FOCUS_BORDER_NONE: u8 = u8::MAX;
17
18#[inline(always)]
19pub(super) const fn pack_visual_flags(
20    has_pos: bool,
21    has_scroll: bool,
22    has_bg_grad: bool,
23    bg_grad_horiz: bool,
24    items_baseline: bool,
25    align_self: Option<AlignItems>,
26) -> u8 {
27    let mut f = 0u8;
28    if has_pos {
29        f |= VIS_FLAG_HAS_POS;
30    }
31    if has_scroll {
32        f |= VIS_FLAG_HAS_SCROLL;
33    }
34    if has_bg_grad {
35        f |= VIS_FLAG_HAS_BG_GRAD;
36    }
37    if bg_grad_horiz {
38        f |= VIS_FLAG_BG_GRAD_HORIZ;
39    }
40    if items_baseline {
41        f |= VIS_FLAG_ITEMS_BASELINE;
42    }
43    let align_code: u8 = match align_self {
44        None => 0,
45        Some(AlignItems::Stretch) => 1,
46        Some(AlignItems::Center) => 2,
47        Some(AlignItems::Start) => 3,
48        Some(AlignItems::End) => 4,
49    };
50    f | (align_code << VIS_ALIGN_SHIFT)
51}
52
53const STATE_FLAG_HAS_TEXT_COLOR: u8 = 1 << 0;
54
55/// 按需分配在 [`crate::arena::ScratchArena`] 中的容器级文本继承与交互态样式覆写表(仅 **32 字节**,普通 `DivVisual` 零分配开销)。
56#[derive(Copy, Clone, Debug, Default)]
57pub struct DivStateStyles<'a> {
58    pub hover_style: Option<&'a StyleRefinement>,
59    pub active_style: Option<&'a StyleRefinement>,
60    pub focus_style: Option<&'a StyleRefinement>,
61    pub text_color: Color,
62    pub text_size: u8,
63    pub flags: u8,
64}
65
66#[cfg(target_pointer_width = "64")]
67const _: () = assert!(core::mem::size_of::<DivStateStyles<'static>>() == 32);
68
69/// 按需分配在 [`crate::arena::ScratchArena`] 中的扩展视觉与布局约束属性(严格紧凑 **64 字节**,零对齐空洞)。
70#[derive(Copy, Clone, Debug)]
71pub struct DivVisual<'a> {
72    pub state_styles: Option<&'a DivStateStyles<'a>>,
73    pub transition: Option<&'a TransitionSpec>,
74    pub margin: Edges<i16>,
75    pub extra_padding: Edges<i16>,
76    pub bg_grad_to: Color,
77    pub focus_border_color: Color,
78    pub shadow_color: Color,
79    pub min_w: i16,
80    pub max_w: i16,
81    pub min_h: i16,
82    pub max_h: i16,
83    pub pos_x: i16,
84    pub pos_y: i16,
85    pub raw_scrollable_max: i16,
86    pub extra_flags: u8,
87    pub focus_border_w: u8,
88    pub shadow_blur: u8,
89    pub shadow_ox: i8,
90    pub shadow_oy: i8,
91    pub cursor: Option<CursorShape>,
92}
93
94#[cfg(target_pointer_width = "64")]
95const _: () = assert!(core::mem::size_of::<DivVisual<'static>>() == 64);
96
97impl<'a> DivVisual<'a> {
98    #[inline(always)]
99    pub const fn pos(&self) -> Option<(i16, i16)> {
100        if (self.extra_flags & VIS_FLAG_HAS_POS) != 0 {
101            Some((self.pos_x, self.pos_y))
102        } else {
103            None
104        }
105    }
106
107    #[inline(always)]
108    pub const fn scrollable_max(&self) -> Option<i16> {
109        if (self.extra_flags & VIS_FLAG_HAS_SCROLL) != 0 {
110            Some(self.raw_scrollable_max)
111        } else {
112            None
113        }
114    }
115
116    #[inline(always)]
117    pub const fn bg_grad(&self) -> Option<(Color, bool)> {
118        if (self.extra_flags & VIS_FLAG_HAS_BG_GRAD) != 0 {
119            Some((
120                self.bg_grad_to,
121                (self.extra_flags & VIS_FLAG_BG_GRAD_HORIZ) != 0,
122            ))
123        } else {
124            None
125        }
126    }
127
128    #[inline(always)]
129    pub const fn focus_border(&self) -> Option<(u8, Color)> {
130        if self.focus_border_w != FOCUS_BORDER_NONE {
131            Some((self.focus_border_w, self.focus_border_color))
132        } else {
133            None
134        }
135    }
136
137    #[inline(always)]
138    pub const fn shadow(&self) -> Option<(u8, i8, i8, Color)> {
139        if self.shadow_blur > 0 {
140            Some((
141                self.shadow_blur,
142                self.shadow_ox,
143                self.shadow_oy,
144                self.shadow_color,
145            ))
146        } else {
147            None
148        }
149    }
150
151    #[inline(always)]
152    pub const fn items_baseline(&self) -> bool {
153        (self.extra_flags & VIS_FLAG_ITEMS_BASELINE) != 0
154    }
155
156    #[inline(always)]
157    pub const fn align_self(&self) -> Option<AlignItems> {
158        match self.extra_flags >> VIS_ALIGN_SHIFT {
159            1 => Some(AlignItems::Stretch),
160            2 => Some(AlignItems::Center),
161            3 => Some(AlignItems::Start),
162            4 => Some(AlignItems::End),
163            _ => None,
164        }
165    }
166
167    #[inline(always)]
168    pub fn transition_spec(&self) -> Option<TransitionSpec> {
169        self.transition.copied()
170    }
171}
172
173static DEFAULT_DIV_VISUAL: DivVisual<'static> = DivVisual {
174    state_styles: None,
175    transition: None,
176    margin: Edges::all(0),
177    extra_padding: Edges::all(0),
178    bg_grad_to: Color::TRANSPARENT,
179    focus_border_color: Color::TRANSPARENT,
180    shadow_color: Color::TRANSPARENT,
181    min_w: 0,
182    max_w: 0,
183    min_h: 0,
184    max_h: 0,
185    pos_x: 0,
186    pos_y: 0,
187    raw_scrollable_max: 0,
188    extra_flags: 0,
189    focus_border_w: FOCUS_BORDER_NONE,
190    shadow_blur: 0,
191    shadow_ox: 0,
192    shadow_oy: 0,
193    cursor: None,
194};
195
196/// 仅禁用了默认焦点边框(`.no_focus_border()`)的零分配共享只读扩展节点。
197pub(super) static NO_FOCUS_BORDER_DIV_VISUAL: DivVisual<'static> = DivVisual {
198    state_styles: None,
199    transition: None,
200    margin: Edges::all(0),
201    extra_padding: Edges::all(0),
202    bg_grad_to: Color::TRANSPARENT,
203    focus_border_color: Color::TRANSPARENT,
204    shadow_color: Color::TRANSPARENT,
205    min_w: 0,
206    max_w: 0,
207    min_h: 0,
208    max_h: 0,
209    pos_x: 0,
210    pos_y: 0,
211    raw_scrollable_max: 0,
212    extra_flags: 0,
213    focus_border_w: 0,
214    shadow_blur: 0,
215    shadow_ox: 0,
216    shadow_oy: 0,
217    cursor: None,
218};
219
220/// 按需分配在 [`crate::arena::ScratchArena`] 中的高级手势与键盘事件回调表(普通点击按钮零分配开销)。
221#[derive(Copy, Clone)]
222pub struct DivRareHandlers<'a> {
223    pub on_long_press: Option<&'a dyn Fn(&mut ActionScope)>,
224    pub on_drag: Option<&'a dyn Fn(&mut ActionScope)>,
225    pub on_swipe: Option<&'a dyn Fn(crate::pod::SwipeDir, &mut ActionScope)>,
226    pub on_key_input: Option<&'a dyn Fn(crate::pod::KeyCode, &mut ActionScope)>,
227    pub on_key_nav: Option<&'a dyn Fn(crate::pod::KeyCode, &mut ActionScope)>,
228    pub on_navigate_back: Option<&'a dyn Fn(&mut ActionScope)>,
229    pub on_secondary_click: Option<&'a dyn Fn(&mut ActionScope)>,
230}
231
232/// 按需分配在 [`crate::arena::ScratchArena`] 中的紧凑交互入口(仅 24 Bytes)。
233#[derive(Copy, Clone)]
234pub struct DivInteractivity<'a> {
235    pub on_click: Option<&'a dyn Fn(&mut ActionScope)>,
236    pub rare: Option<&'a DivRareHandlers<'a>>,
237}
238
239/// 存储在 [`super::Element::Div`] 中的紧凑容器节点(固定 64 Bytes,将 `ElementNode` 压缩至 72B)。
240pub struct DivNode<'a> {
241    pub style: Style,
242    pub first_child: Option<&'a ElementNode<'a>>,
243    pub visual: Option<&'a DivVisual<'a>>,
244    pub interact: Option<&'a DivInteractivity<'a>>,
245    pub raw_id: u32,
246    pub raw_active_bg: Color,
247    pub raw_hover_bg: Color,
248    pub opacity: u8,
249    pub z_index: i8,
250    pub grid_cols: u8,
251    pub flags: u8,
252}
253
254impl<'a> core::ops::Deref for DivNode<'a> {
255    type Target = DivVisual<'a>;
256    #[inline(always)]
257    fn deref(&self) -> &Self::Target {
258        self.visual.unwrap_or(&DEFAULT_DIV_VISUAL)
259    }
260}
261
262impl<'a> DivNode<'a> {
263    #[inline(always)]
264    pub fn text_color(&self) -> Option<Color> {
265        self.state_styles.and_then(|s| {
266            if (s.flags & STATE_FLAG_HAS_TEXT_COLOR) != 0 {
267                Some(s.text_color)
268            } else {
269                None
270            }
271        })
272    }
273
274    #[inline(always)]
275    pub fn text_size(&self) -> Option<u8> {
276        self.state_styles
277            .and_then(|s| if s.text_size > 0 { Some(s.text_size) } else { None })
278    }
279
280    #[inline(always)]
281    pub fn hover_style(&self) -> Option<StyleRefinement> {
282        self.state_styles.and_then(|s| s.hover_style.copied())
283    }
284
285    #[inline(always)]
286    pub fn active_style(&self) -> Option<StyleRefinement> {
287        self.state_styles.and_then(|s| s.active_style.copied())
288    }
289
290    #[inline(always)]
291    pub fn focus_style(&self) -> Option<StyleRefinement> {
292        self.state_styles.and_then(|s| s.focus_style.copied())
293    }
294
295    #[inline(always)]
296    pub const fn id(&self) -> Option<u32> {
297        if (self.flags & (1 << 5)) != 0 {
298            Some(self.raw_id)
299        } else {
300            None
301        }
302    }
303
304    #[inline(always)]
305    pub const fn active_bg(&self) -> Option<Color> {
306        if (self.flags & (1 << 6)) != 0 {
307            Some(self.raw_active_bg)
308        } else {
309            None
310        }
311    }
312
313    #[inline(always)]
314    pub const fn hover_bg(&self) -> Option<Color> {
315        if (self.flags & (1 << 7)) != 0 {
316            Some(self.raw_hover_bg)
317        } else {
318            None
319        }
320    }
321
322    #[inline(always)]
323    pub const fn focusable(&self) -> bool {
324        (self.flags & (1 << 0)) != 0
325    }
326
327    #[inline(always)]
328    pub const fn is_overlay(&self) -> bool {
329        (self.flags & (1 << 1)) != 0
330    }
331
332    #[inline(always)]
333    pub const fn occlude_hit(&self) -> bool {
334        (self.flags & (1 << 2)) != 0
335    }
336
337    #[inline(always)]
338    pub const fn auto_repeat(&self) -> bool {
339        (self.flags & (1 << 3)) != 0
340    }
341
342    #[inline(always)]
343    pub const fn clip_children(&self) -> bool {
344        (self.flags & (1 << 4)) != 0
345    }
346
347    #[inline(always)]
348    pub fn on_click(&self) -> Option<&'a dyn Fn(&mut ActionScope)> {
349        self.interact.and_then(|i| i.on_click)
350    }
351
352    #[inline(always)]
353    pub fn on_long_press(&self) -> Option<&'a dyn Fn(&mut ActionScope)> {
354        self.interact.and_then(|i| i.rare).and_then(|r| r.on_long_press)
355    }
356
357    #[inline(always)]
358    pub fn on_drag(&self) -> Option<&'a dyn Fn(&mut ActionScope)> {
359        self.interact.and_then(|i| i.rare).and_then(|r| r.on_drag)
360    }
361
362    #[inline(always)]
363    pub fn on_swipe(&self) -> Option<&'a dyn Fn(crate::pod::SwipeDir, &mut ActionScope)> {
364        self.interact.and_then(|i| i.rare).and_then(|r| r.on_swipe)
365    }
366
367    #[inline(always)]
368    pub fn on_key_input(&self) -> Option<&'a dyn Fn(crate::pod::KeyCode, &mut ActionScope)> {
369        self.interact.and_then(|i| i.rare).and_then(|r| r.on_key_input)
370    }
371
372    #[inline(always)]
373    pub fn on_key_nav(&self) -> Option<&'a dyn Fn(crate::pod::KeyCode, &mut ActionScope)> {
374        self.interact.and_then(|i| i.rare).and_then(|r| r.on_key_nav)
375    }
376
377    #[inline(always)]
378    pub fn on_navigate_back(&self) -> Option<&'a dyn Fn(&mut ActionScope)> {
379        self.interact.and_then(|i| i.rare).and_then(|r| r.on_navigate_back)
380    }
381
382    #[inline(always)]
383    pub fn on_secondary_click(&self) -> Option<&'a dyn Fn(&mut ActionScope)> {
384        self.interact.and_then(|i| i.rare).and_then(|r| r.on_secondary_click)
385    }
386}
387
388/// 将 `Duration` 饱和转换为 `u16` 毫秒(上限约 65 秒)。
389#[inline(always)]
390pub(super) fn duration_to_ms(d: Duration) -> u16 {
391    d.as_millis().min(u16::MAX as u128) as u16
392}
393
394/// 元素首次出现(挂载)时的入场起始状态(从该状态平滑过渡到布局目标状态)。
395#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
396pub struct EnterFrom {
397    /// 入场起始不透明度(`0` 为完全透明淡入)。
398    pub opacity: u8,
399    /// 入场起始水平偏移(像素,相对布局目标位置)。
400    pub dx: i16,
401    /// 入场起始垂直偏移(像素,相对布局目标位置)。
402    pub dy: i16,
403}
404
405/// 声明式过渡动画属性配置。
406#[derive(Copy, Clone, PartialEq, Eq, Debug)]
407pub struct TransitionSpec {
408    /// 过渡动画时长(毫秒)。
409    pub duration_ms: u16,
410    /// 动画开始前的延迟(毫秒,对入场与每次属性变更均生效;循环动画仅首轮生效)。
411    pub delay_ms: u16,
412    /// 是否插值背景色与边框/文本颜色。
413    pub animate_color: bool,
414    /// 是否插值几何位置与尺寸(子树随容器位移同步平移)。
415    pub animate_bounds: bool,
416    /// 是否插值容器整体不透明度(`.opacity(...)` 变化时淡入淡出,作用于整个子树)。
417    pub animate_opacity: bool,
418    /// 缓动曲线类型。
419    pub easing: Easing,
420    /// 循环模式(单次、无限循环、往复呼吸)。
421    pub loop_mode: LoopMode,
422    /// 往复呼吸/循环动画的起始背景色(若设置则自动在 `pulse_from_bg` 与 `style.bg` 之间循环插值)。
423    pub pulse_from_bg: Option<Color>,
424    /// 入场动画起始状态(元素首次出现时从该状态过渡至目标状态)。
425    pub enter: Option<EnterFrom>,
426}
427
428impl Default for TransitionSpec {
429    #[inline(always)]
430    fn default() -> Self {
431        Self {
432            duration_ms: 180,
433            delay_ms: 0,
434            animate_color: false,
435            animate_bounds: false,
436            animate_opacity: false,
437            easing: Easing::EaseOut,
438            loop_mode: LoopMode::Once,
439            pulse_from_bg: None,
440            enter: None,
441        }
442    }
443}
444