bexa-ui-core 0.1.0

Core widgets, layout, and signals for BexaUI — the hacker's UI toolkit for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use taffy::geometry::Point;
use taffy::prelude::*;
use winit::event::WindowEvent;

use crate::framework::{DrawContext, EventContext, Widget};
use crate::renderer::Renderer;

const SCROLLBAR_WIDTH: f32 = 8.0;
const SCROLLBAR_MARGIN: f32 = 2.0;
const SCROLLBAR_MIN_THUMB: f32 = 20.0;

pub struct WidgetNode {
    pub(crate) widget: Box<dyn Widget>,
    pub(crate) children: Vec<WidgetNode>,
    pub(crate) node: Option<NodeId>,
    pub(crate) scroll_y: f32,
    // Scrollbar drag state
    pub(crate) scrollbar_dragging: bool,
    pub(crate) scrollbar_drag_start_y: f32,
    pub(crate) scrollbar_drag_start_scroll: f32,
}

impl WidgetNode {
    pub fn new(widget: impl Widget + 'static, children: Vec<WidgetNode>) -> Self {
        Self {
            widget: Box::new(widget),
            children,
            node: None,
            scroll_y: 0.0,
            scrollbar_dragging: false,
            scrollbar_drag_start_y: 0.0,
            scrollbar_drag_start_scroll: 0.0,
        }
    }
}

pub fn build_taffy(node: &mut WidgetNode, taffy: &mut TaffyTree) -> NodeId {
    let child_nodes = node
        .children
        .iter_mut()
        .map(|child| build_taffy(child, taffy))
        .collect::<Vec<_>>();

    let style = node.widget.style();
    let node_id = if child_nodes.is_empty() {
        taffy.new_leaf(style).expect("create leaf")
    } else {
        taffy
            .new_with_children(style, &child_nodes)
            .expect("create node")
    };

    node.node = Some(node_id);
    node_id
}

pub fn sync_styles(node: &mut WidgetNode, taffy: &mut TaffyTree, width: f32, height: f32, is_root: bool) {
    let Some(node_id) = node.node else {
        return;
    };

    let mut style = node.widget.style();
    if is_root {
        style.size = Size {
            width: Dimension::Length(width),
            height: Dimension::Length(height),
        };
    }

    taffy.set_style(node_id, style).expect("set style");

    for child in &mut node.children {
        sync_styles(child, taffy, width, height, false);
    }
}

pub fn collect_focus_paths(node: &WidgetNode, path: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
    if node.widget.is_focusable() {
        out.push(path.clone());
    }

    for (index, child) in node.children.iter().enumerate() {
        path.push(index);
        collect_focus_paths(child, path, out);
        path.pop();
    }
}

pub fn widget_mut_at_path<'a>(node: &'a mut WidgetNode, path: &[usize]) -> Option<&'a mut dyn Widget> {
    if path.is_empty() {
        return Some(node.widget.as_mut());
    }

    let idx = path[0];
    if idx >= node.children.len() {
        return None;
    }

    widget_mut_at_path(&mut node.children[idx], &path[1..])
}

pub fn draw_widgets(node: &WidgetNode, taffy: &TaffyTree, renderer: &mut Renderer) {
    draw_widgets_offset(node, taffy, renderer, 0.0, 0.0);
}

fn draw_widgets_offset(node: &WidgetNode, taffy: &TaffyTree, renderer: &mut Renderer, parent_x: f32, parent_y: f32) {
    let Some(node_id) = node.node else {
        return;
    };

    let layout = taffy.layout(node_id).expect("layout");
    let abs_x = parent_x + layout.location.x;
    let abs_y = parent_y + layout.location.y;

    let mut absolute_layout = *layout;
    absolute_layout.location = Point { x: abs_x, y: abs_y };

    let mut ctx = DrawContext {
        renderer,
        layout: &absolute_layout,
    };
    node.widget.draw(&mut ctx);

    let is_scroll = node.widget.is_scrollable();
    if is_scroll {
        renderer.push_clip((abs_x, abs_y, layout.size.width, layout.size.height));
    }

    let child_y = abs_y - node.scroll_y;
    for child in &node.children {
        draw_widgets_offset(child, taffy, renderer, abs_x, child_y);
    }

    if is_scroll {
        renderer.pop_clip();

        // Draw scrollbar overlay (after pop_clip so it's not clipped with children)
        let container_h = layout.size.height;
        let content_h = content_height(node, taffy);
        if content_h > container_h {
            draw_scrollbar(renderer, abs_x, abs_y, layout.size.width, container_h, content_h, node.scroll_y);
        }
    }
}

fn content_height(node: &WidgetNode, taffy: &TaffyTree) -> f32 {
    let mut h: f32 = 0.0;
    for child in &node.children {
        if let Some(child_id) = child.node {
            let cl = taffy.layout(child_id).expect("child layout");
            let bottom = cl.location.y + cl.size.height;
            h = h.max(bottom);
        }
    }
    h
}

fn draw_scrollbar(
    renderer: &mut Renderer,
    container_x: f32,
    container_y: f32,
    container_w: f32,
    container_h: f32,
    content_h: f32,
    scroll_y: f32,
) {
    let track_x = container_x + container_w - SCROLLBAR_WIDTH - SCROLLBAR_MARGIN;
    let track_y = container_y + SCROLLBAR_MARGIN;
    let track_h = container_h - SCROLLBAR_MARGIN * 2.0;

    // Track background
    renderer.fill_rect_rounded(
        (track_x, track_y, SCROLLBAR_WIDTH, track_h),
        [0.3, 0.3, 0.3, 0.15],
        SCROLLBAR_WIDTH / 2.0,
    );

    // Thumb
    let ratio = container_h / content_h;
    let thumb_h = (ratio * track_h).max(SCROLLBAR_MIN_THUMB);
    let max_scroll = (content_h - container_h).max(0.0);
    let scroll_ratio = if max_scroll > 0.0 { scroll_y / max_scroll } else { 0.0 };
    let thumb_y = track_y + scroll_ratio * (track_h - thumb_h);

    renderer.fill_rect_rounded(
        (track_x, thumb_y, SCROLLBAR_WIDTH, thumb_h),
        [0.6, 0.6, 0.6, 0.5],
        SCROLLBAR_WIDTH / 2.0,
    );
}

pub fn dispatch_event(
    node: &mut WidgetNode,
    taffy: &TaffyTree,
    event: &WindowEvent,
    path: &mut Vec<usize>,
) -> Option<Vec<usize>> {
    dispatch_event_offset(node, taffy, event, path, 0.0, 0.0)
}

fn dispatch_event_offset(
    node: &mut WidgetNode,
    taffy: &TaffyTree,
    event: &WindowEvent,
    path: &mut Vec<usize>,
    parent_x: f32,
    parent_y: f32,
) -> Option<Vec<usize>> {
    let Some(node_id) = node.node else {
        return None;
    };
    let layout = taffy.layout(node_id).expect("layout");
    let abs_x = parent_x + layout.location.x;
    let abs_y = parent_y + layout.location.y;

    let child_y = abs_y - node.scroll_y;
    for (index, child) in node.children.iter_mut().enumerate() {
        path.push(index);
        if let Some(found) = dispatch_event_offset(child, taffy, event, path, abs_x, child_y) {
            return Some(found);
        }
        path.pop();
    }

    let mut absolute_layout = *layout;
    absolute_layout.location = Point { x: abs_x, y: abs_y };

    let mut ctx = EventContext {
        event,
        layout: &absolute_layout,
    };
    if node.widget.handle_event(&mut ctx) {
        return Some(path.clone());
    }

    None
}

/// Dispatches a scroll event to the deepest scrollable node under cursor,
/// falling back to the root node.
pub fn dispatch_scroll(node: &mut WidgetNode, delta_y: f32, cursor_x: f32, cursor_y: f32, taffy: &TaffyTree) {
    if !dispatch_scroll_offset(node, delta_y, cursor_x, cursor_y, taffy, 0.0, 0.0) {
        // Fallback: scroll root
        scroll_node(node, delta_y, taffy);
    }
}

fn dispatch_scroll_offset(
    node: &mut WidgetNode,
    delta_y: f32,
    cx: f32,
    cy: f32,
    taffy: &TaffyTree,
    parent_x: f32,
    parent_y: f32,
) -> bool {
    let Some(node_id) = node.node else { return false; };
    let layout = taffy.layout(node_id).expect("layout");
    let abs_x = parent_x + layout.location.x;
    let abs_y = parent_y + layout.location.y;

    // Check if cursor is inside this node
    let inside = cx >= abs_x
        && cx <= abs_x + layout.size.width
        && cy >= abs_y
        && cy <= abs_y + layout.size.height;

    if !inside {
        return false;
    }

    // Try children first (deepest scrollable wins)
    let child_y = abs_y - node.scroll_y;
    for child in &mut node.children {
        if dispatch_scroll_offset(child, delta_y, cx, cy, taffy, abs_x, child_y) {
            return true;
        }
    }

    // If this node is scrollable, consume the scroll
    if node.widget.is_scrollable() {
        scroll_node(node, delta_y, taffy);
        return true;
    }

    false
}

fn scroll_node(node: &mut WidgetNode, delta_y: f32, taffy: &TaffyTree) {
    let Some(node_id) = node.node else { return; };
    let layout = taffy.layout(node_id).expect("layout");
    let container_h = layout.size.height;

    // Content height = max bottom edge of all children
    let mut content_h: f32 = 0.0;
    for child in &node.children {
        if let Some(child_id) = child.node {
            let cl = taffy.layout(child_id).expect("child layout");
            let bottom = cl.location.y + cl.size.height;
            content_h = content_h.max(bottom);
        }
    }

    let max_scroll = (content_h - container_h).max(0.0);
    node.scroll_y = (node.scroll_y - delta_y).clamp(0.0, max_scroll);
}

/// Scrolls the root node (backward compat).
pub fn scroll_root(node: &mut WidgetNode, delta_y: f32, viewport_h: f32, taffy: &TaffyTree) {
    let _ = viewport_h;
    scroll_node(node, delta_y, taffy);
}

pub fn update_widget_measures(node: &mut WidgetNode, measures: &[Vec<f32>]) {
    node.widget.update_measures(measures);
    for child in &mut node.children {
        update_widget_measures(child, measures);
    }
}

/// Handle mouse events on scrollbar overlays. Returns true if a scrollbar consumed the event.
pub fn handle_scrollbar_event(
    node: &mut WidgetNode,
    taffy: &TaffyTree,
    event: &WindowEvent,
) -> bool {
    handle_scrollbar_event_offset(node, taffy, event, 0.0, 0.0)
}

fn handle_scrollbar_event_offset(
    node: &mut WidgetNode,
    taffy: &TaffyTree,
    event: &WindowEvent,
    parent_x: f32,
    parent_y: f32,
) -> bool {
    let Some(node_id) = node.node else { return false; };
    let layout = taffy.layout(node_id).expect("layout");
    let abs_x = parent_x + layout.location.x;
    let abs_y = parent_y + layout.location.y;

    // Check children first
    let child_y = abs_y - node.scroll_y;
    for child in &mut node.children {
        if handle_scrollbar_event_offset(child, taffy, event, abs_x, child_y) {
            return true;
        }
    }

    if !node.widget.is_scrollable() {
        return false;
    }

    let container_h = layout.size.height;
    let content_h = content_height(node, taffy);
    if content_h <= container_h {
        return false;
    }

    let _track_y = abs_y + SCROLLBAR_MARGIN;
    let track_h = container_h - SCROLLBAR_MARGIN * 2.0;
    let max_scroll = (content_h - container_h).max(0.0);
    let ratio = container_h / content_h;
    let thumb_h = (ratio * track_h).max(SCROLLBAR_MIN_THUMB);

    match event {
        WindowEvent::CursorMoved { position, .. } => {
            let _cx = position.x as f32;
            let cy = position.y as f32;

            if node.scrollbar_dragging {
                // Update scroll based on drag delta
                let delta_y = cy - node.scrollbar_drag_start_y;
                let scroll_per_pixel = max_scroll / (track_h - thumb_h);
                node.scroll_y = (node.scrollbar_drag_start_scroll + delta_y * scroll_per_pixel)
                    .clamp(0.0, max_scroll);
                return true;
            }
            false
        }
        _ => false,
    }
}

/// Start scrollbar drag if the press landed on the scrollbar thumb/track.
/// Call this specifically on MouseInput::Pressed events with cursor position.
pub fn try_start_scrollbar_drag(
    node: &mut WidgetNode,
    taffy: &TaffyTree,
    cx: f32,
    cy: f32,
) -> bool {
    try_start_scrollbar_drag_offset(node, taffy, cx, cy, 0.0, 0.0)
}

fn try_start_scrollbar_drag_offset(
    node: &mut WidgetNode,
    taffy: &TaffyTree,
    cx: f32,
    cy: f32,
    parent_x: f32,
    parent_y: f32,
) -> bool {
    let Some(node_id) = node.node else { return false; };
    let layout = taffy.layout(node_id).expect("layout");
    let abs_x = parent_x + layout.location.x;
    let abs_y = parent_y + layout.location.y;

    let child_y = abs_y - node.scroll_y;
    for child in &mut node.children {
        if try_start_scrollbar_drag_offset(child, taffy, cx, cy, abs_x, child_y) {
            return true;
        }
    }

    if !node.widget.is_scrollable() {
        return false;
    }

    let container_h = layout.size.height;
    let content_h = content_height(node, taffy);
    if content_h <= container_h {
        return false;
    }

    let track_x = abs_x + layout.size.width - SCROLLBAR_WIDTH - SCROLLBAR_MARGIN;
    let track_y = abs_y + SCROLLBAR_MARGIN;
    let track_h = container_h - SCROLLBAR_MARGIN * 2.0;

    // Check if click is in the scrollbar area
    let in_scrollbar = cx >= track_x
        && cx <= track_x + SCROLLBAR_WIDTH + SCROLLBAR_MARGIN
        && cy >= abs_y
        && cy <= abs_y + container_h;

    if !in_scrollbar {
        return false;
    }

    let max_scroll = (content_h - container_h).max(0.0);
    let ratio = container_h / content_h;
    let thumb_h = (ratio * track_h).max(SCROLLBAR_MIN_THUMB);
    let scroll_ratio = if max_scroll > 0.0 { node.scroll_y / max_scroll } else { 0.0 };
    let thumb_y = track_y + scroll_ratio * (track_h - thumb_h);

    // Check if click is on the thumb
    if cy >= thumb_y && cy <= thumb_y + thumb_h {
        // Start dragging from thumb
        node.scrollbar_dragging = true;
        node.scrollbar_drag_start_y = cy;
        node.scrollbar_drag_start_scroll = node.scroll_y;
    } else {
        // Click on track: jump to position
        let click_ratio = (cy - track_y) / track_h;
        node.scroll_y = (click_ratio * max_scroll).clamp(0.0, max_scroll);
    }

    true
}

/// Release scrollbar drag on all scrollable nodes.
pub fn release_scrollbar_drag(node: &mut WidgetNode) {
    node.scrollbar_dragging = false;
    for child in &mut node.children {
        release_scrollbar_drag(child);
    }
}

pub fn clear_active_widgets(node: &mut WidgetNode) {
    node.widget.clear_active();
    for child in &mut node.children {
        clear_active_widgets(child);
    }
}