Skip to main content

velox_engine/element/
div_node.rs

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