blinc_layout 0.4.0

Blinc layout engine - Flexbox layout powered by Taffy
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Element handle for programmatic element manipulation

use std::sync::Arc;

use blinc_core::context_state::MotionAnimationState;
use blinc_core::BlincContextState;

use crate::element::{ElementBounds, RenderProps};
use crate::tree::LayoutNodeId;

use super::registry::{ElementRegistry, OnReadyCallback};
use super::ScrollOptions;

/// Handle to a queried element for programmatic manipulation
///
/// Returned by `ctx.query("element-id")` for element manipulation.
/// The handle can be created even before the element exists in the tree,
/// allowing operations like `on_ready` to be registered early.
#[derive(Clone)]
pub struct ElementHandle<T = ()> {
    /// The string ID used to query this element
    string_id: String,
    /// Cached node_id (may be default if element doesn't exist yet)
    node_id: LayoutNodeId,
    registry: Arc<ElementRegistry>,
    /// Typed element data (if available)
    _marker: std::marker::PhantomData<T>,
}

impl<T> ElementHandle<T> {
    /// Create a new element handle from a string ID
    ///
    /// The handle is valid even if the element doesn't exist yet.
    /// Operations like `on_ready` will work and fire when the element is laid out.
    pub fn new(string_id: impl Into<String>, registry: Arc<ElementRegistry>) -> Self {
        let string_id = string_id.into();
        let node_id = registry.get(&string_id).unwrap_or_default();
        Self {
            string_id,
            node_id,
            registry,
            _marker: std::marker::PhantomData,
        }
    }

    /// Get the underlying layout node ID
    ///
    /// Returns a default ID if the element doesn't exist yet.
    pub fn node_id(&self) -> LayoutNodeId {
        // Refresh from registry in case element was created after handle
        self.registry.get(&self.string_id).unwrap_or(self.node_id)
    }

    /// Get the string ID of this element
    pub fn id(&self) -> &str {
        &self.string_id
    }

    /// Check if the element currently exists in the tree
    pub fn exists(&self) -> bool {
        self.registry.get(&self.string_id).is_some()
    }

    // =========================================================================
    // Layout & Visibility
    // =========================================================================

    /// Get the computed bounds of this element
    ///
    /// Returns None if layout hasn't been computed yet or the element doesn't exist.
    pub fn bounds(&self) -> Option<ElementBounds> {
        // Get bounds from the registry cache (populated by RenderTree after layout)
        let bounds = self.registry.get_bounds(&self.string_id)?;
        Some(ElementBounds::new(
            bounds.x,
            bounds.y,
            bounds.width,
            bounds.height,
        ))
    }

    /// Check if this element is visible in the viewport
    ///
    /// An element is visible if its bounds intersect with the window viewport.
    /// This is a simple viewport check - does not account for scroll container clipping.
    pub fn is_visible(&self) -> bool {
        let Some(bounds) = self.registry.get_bounds(&self.string_id) else {
            return false;
        };

        // Get viewport size from BlincContextState
        if let Some(ctx) = BlincContextState::try_get() {
            let (vw, vh) = ctx.viewport_size();
            // Check if element bounds intersect viewport
            bounds.x < vw
                && bounds.x + bounds.width > 0.0
                && bounds.y < vh
                && bounds.y + bounds.height > 0.0
        } else {
            // No context state, assume visible
            true
        }
    }

    // =========================================================================
    // Tree Traversal
    // =========================================================================

    /// Get the parent element handle
    pub fn parent(&self) -> Option<ElementHandle<()>> {
        let current_node_id = self.node_id();
        let parent_node_id = self.registry.get_parent(current_node_id)?;
        let parent_string_id = self.registry.get_id(parent_node_id)?;
        Some(ElementHandle::new(parent_string_id, self.registry.clone()))
    }

    /// Get all ancestors (immediate parent to root)
    pub fn ancestors(&self) -> impl Iterator<Item = ElementHandle<()>> {
        let current_node_id = self.node_id();
        let ancestors = self.registry.ancestors(current_node_id);
        let registry = self.registry.clone();
        ancestors.into_iter().filter_map(move |id| {
            let string_id = registry.get_id(id)?;
            Some(ElementHandle::new(string_id, registry.clone()))
        })
    }

    // =========================================================================
    // Navigation (scroll, focus)
    // =========================================================================

    /// Scroll this element into view using default options
    pub fn scroll_into_view(&self) {
        self.scroll_into_view_with(ScrollOptions::default());
    }

    /// Scroll this element into view with custom options
    pub fn scroll_into_view_with(&self, _options: ScrollOptions) {
        // Use BlincContextState callback to scroll the element
        if let Some(ctx) = BlincContextState::try_get() {
            ctx.scroll_element_into_view(&self.string_id);
        }
    }

    /// Focus this element
    ///
    /// For focusable elements like TextInput, this sets keyboard focus.
    /// For other elements, this updates the EventRouter's focus state.
    pub fn focus(&self) {
        if let Some(ctx) = BlincContextState::try_get() {
            ctx.set_focus(Some(&self.string_id));
        }
    }

    /// Remove focus from this element
    pub fn blur(&self) {
        if let Some(ctx) = BlincContextState::try_get() {
            // Only blur if this element is currently focused
            if ctx.is_focused(&self.string_id) {
                ctx.set_focus(None);
            }
        }
    }

    /// Check if this element is currently focused
    pub fn is_focused(&self) -> bool {
        BlincContextState::try_get()
            .map(|ctx| ctx.is_focused(&self.string_id))
            .unwrap_or(false)
    }

    // =========================================================================
    // Signal Operations
    // =========================================================================

    /// Emit a signal to trigger reactive updates
    ///
    /// This notifies stateful elements that depend on this signal, triggering
    /// only the affected subtree rebuilds through the reactive system.
    ///
    /// Note: For typed signal updates, use `State::set()` directly which
    /// automatically triggers dependent updates.
    pub fn emit_signal(&self, signal_id: blinc_core::SignalId) {
        if let Some(ctx) = BlincContextState::try_get() {
            // Notify stateful elements via the callback - this triggers
            // targeted subtree rebuilds, not a full UI rebuild
            ctx.notify_stateful_deps(&[signal_id]);
        }
    }

    /// Mark this element as dirty, forcing a rebuild
    ///
    /// This triggers a UI rebuild. The hash-based diffing system will
    /// determine what actually needs to be updated.
    pub fn mark_dirty(&self) {
        if let Some(ctx) = BlincContextState::try_get() {
            ctx.request_rebuild();
        }
    }

    /// Mark this element's subtree as dirty with new children
    ///
    /// This queues an explicit subtree rebuild with the provided new children.
    /// Use this for more efficient updates when you know exactly what the
    /// new children should be.
    pub fn mark_dirty_subtree(&self, new_children: crate::div::Div) {
        if let Some(node_id) = self.registry.get(&self.string_id) {
            crate::stateful::queue_subtree_rebuild(node_id, new_children);
        }
    }

    /// Mark this element as visually dirty with new render props
    ///
    /// This queues a visual-only update that **skips layout recomputation**.
    /// Use this for changes to background, opacity, shadows, transforms, etc.
    ///
    /// This is the most efficient update method when you only need to change
    /// visual properties without affecting layout.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Change background color without triggering layout
    /// ctx.query("my-button").mark_visual_dirty(
    ///     RenderProps::default().with_background(Color::RED.into())
    /// );
    /// ```
    pub fn mark_visual_dirty(&self, props: RenderProps) {
        if let Some(node_id) = self.registry.get(&self.string_id) {
            crate::stateful::queue_prop_update(node_id, props);
        }
    }

    // =========================================================================
    // Event Simulation
    // =========================================================================

    /// Simulate a click event on this element
    pub fn click(&self) {
        self.dispatch_event(ElementEvent::Click { x: 0.0, y: 0.0 });
    }

    /// Simulate a click at specific coordinates within the element
    pub fn click_at(&self, x: f32, y: f32) {
        self.dispatch_event(ElementEvent::Click { x, y });
    }

    /// Simulate hover enter or leave
    pub fn hover(&self, enter: bool) {
        if enter {
            self.dispatch_event(ElementEvent::MouseEnter);
        } else {
            self.dispatch_event(ElementEvent::MouseLeave);
        }
    }

    /// Dispatch a custom event to this element
    pub fn dispatch_event(&self, _event: ElementEvent) {
        // TODO: Wire up to EventRouter/HandlerRegistry
        // This needs access to the event dispatch system
    }

    // =========================================================================
    // On-Ready Callback
    // =========================================================================

    /// Register an on_ready callback for this element
    ///
    /// The callback will be invoked once after the element's first successful
    /// layout computation. The callback receives the element's computed bounds.
    ///
    /// This works even if the element doesn't exist yet - the callback will
    /// fire when the element is first laid out. If the element already exists
    /// and has been laid out, the callback fires on the next layout pass.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Query element and register callback
    /// ctx.query("progress-bar").on_ready(|bounds| {
    ///     progress_anim.lock().unwrap().set_target(bounds.width * 0.75);
    /// });
    /// ```
    pub fn on_ready<F>(&self, callback: F)
    where
        F: Fn(ElementBounds) + Send + Sync + 'static,
    {
        self.registry
            .register_on_ready_for_id(&self.string_id, Arc::new(callback));
    }

    /// Register an on_ready callback (Arc version for shared callbacks)
    pub fn on_ready_arc(&self, callback: OnReadyCallback) {
        self.registry
            .register_on_ready_for_id(&self.string_id, callback);
    }
}

/// Events that can be programmatically dispatched to elements
#[derive(Debug, Clone)]
pub enum ElementEvent {
    /// Mouse click at local coordinates
    Click { x: f32, y: f32 },
    /// Mouse entered element bounds
    MouseEnter,
    /// Mouse left element bounds
    MouseLeave,
    /// Element received focus
    Focus,
    /// Element lost focus
    Blur,
    /// Key pressed while focused
    KeyDown {
        key: u32,      // Key code
        modifiers: u8, // Modifier flags
    },
    /// Custom user-defined event
    Custom(u32),
}

/// Trait for elements that can be queried by type
///
/// Implement this for your element types to enable typed queries:
/// ```rust,ignore
/// ctx.query::<Image>("my-image")
/// ```
pub trait Queryable: Sized {
    /// Try to extract this type from an element handle
    fn from_handle(handle: &ElementHandle<()>) -> Option<Self>;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_handle_creation() {
        let registry = Arc::new(ElementRegistry::new());
        let node_id = LayoutNodeId::default();

        registry.register("test", node_id);

        let handle: ElementHandle<()> = ElementHandle::new("test", registry);
        assert_eq!(handle.node_id(), node_id);
        assert_eq!(handle.id(), "test");
        assert!(handle.exists());
    }

    #[test]
    fn test_handle_for_nonexistent_element() {
        let registry = Arc::new(ElementRegistry::new());

        // Handle can be created for element that doesn't exist yet
        let handle: ElementHandle<()> = ElementHandle::new("future-element", registry);
        assert_eq!(handle.id(), "future-element");
        assert!(!handle.exists());
    }

    #[test]
    fn test_parent_traversal() {
        let registry = Arc::new(ElementRegistry::new());
        let parent_id = LayoutNodeId::default();
        let child_id = LayoutNodeId::default();

        registry.register("parent", parent_id);
        registry.register("child", child_id);
        registry.register_parent(child_id, parent_id);

        let child_handle: ElementHandle<()> = ElementHandle::new("child", registry);
        let parent = child_handle.parent();

        assert!(parent.is_some());
        // Note: In real usage with distinct IDs this would work properly
    }

    // =========================================================================
    // On-Ready Callback Tests
    // =========================================================================

    #[test]
    fn test_handle_on_ready_registers_callback() {
        let registry = Arc::new(ElementRegistry::new());

        // Create handle for element that doesn't exist yet
        let handle: ElementHandle<()> = ElementHandle::new("my-element", registry.clone());

        // Register on_ready callback
        handle.on_ready(|_bounds| {
            // Callback logic here
        });

        // Should have pending callback
        assert!(registry.has_pending_on_ready());

        let pending = registry.take_pending_on_ready();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].0, "my-element");
    }

    #[test]
    fn test_handle_on_ready_uses_string_id() {
        let registry = Arc::new(ElementRegistry::new());
        let node_id = LayoutNodeId::default();

        // Register element
        registry.register("progress-bar", node_id);

        // Create handle and register callback
        let handle: ElementHandle<()> = ElementHandle::new("progress-bar", registry.clone());
        handle.on_ready(|_| {});

        // Callback should be registered with string ID
        let pending = registry.take_pending_on_ready();
        assert_eq!(pending[0].0, "progress-bar");
    }

    #[test]
    fn test_handle_on_ready_skips_if_already_triggered() {
        let registry = Arc::new(ElementRegistry::new());

        // Mark as already triggered
        registry.mark_on_ready_triggered("my-element");

        // Create handle and try to register callback
        let handle: ElementHandle<()> = ElementHandle::new("my-element", registry.clone());
        handle.on_ready(|_| {});

        // Should NOT have pending callback
        assert!(!registry.has_pending_on_ready());
    }

    #[test]
    fn test_handle_on_ready_works_before_element_exists() {
        let registry = Arc::new(ElementRegistry::new());

        // Create handle for nonexistent element
        let handle: ElementHandle<()> = ElementHandle::new("future-element", registry.clone());
        assert!(!handle.exists());

        // Register callback anyway
        handle.on_ready(|_| {});

        // Callback should be pending
        assert!(registry.has_pending_on_ready());

        let pending = registry.take_pending_on_ready();
        assert_eq!(pending[0].0, "future-element");
    }

    #[test]
    fn test_handle_on_ready_arc() {
        let registry = Arc::new(ElementRegistry::new());
        let handle: ElementHandle<()> = ElementHandle::new("my-element", registry.clone());

        // Use Arc version for shared callback
        let callback: OnReadyCallback = Arc::new(|_| {});
        handle.on_ready_arc(callback);

        assert!(registry.has_pending_on_ready());
    }
}

// =============================================================================
// MotionHandle - Handle for querying motion animation state
// =============================================================================

/// Handle to a motion animation for querying its state
///
/// Returned by `query_motion("motion-key")` for animation state queries.
/// Use this to check if a parent motion animation has settled before
/// rendering child content with hover effects, etc.
///
/// # Example
///
/// ```ignore
/// use blinc_layout::selector::query_motion;
///
/// // Inside a Stateful on_state callback:
/// let motion = query_motion("dialog-content");
/// if motion.is_settled() {
///     // Safe to render hover effects
///     container.merge(button_with_hover());
/// } else {
///     // Render without hover effects during animation
///     container.merge(button_static());
/// }
/// ```
#[derive(Clone, Debug)]
pub struct MotionHandle {
    /// The stable key used to query this motion
    key: String,
    /// Current animation state
    state: MotionAnimationState,
}

impl MotionHandle {
    /// Create a new motion handle from a stable key
    ///
    /// Queries the current animation state via `BlincContextState`.
    pub fn new(key: impl Into<String>) -> Self {
        let key = key.into();
        let state = BlincContextState::try_get()
            .map(|ctx| ctx.query_motion(&key))
            .unwrap_or(MotionAnimationState::NotFound);
        Self { key, state }
    }

    /// Get the stable key for this motion
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Get the current animation state
    pub fn state(&self) -> MotionAnimationState {
        self.state
    }

    /// Check if the animation is still playing (not settled)
    ///
    /// Returns true if the motion is in `Suspended`, `Waiting`, `Entering`, or `Exiting` state.
    pub fn is_animating(&self) -> bool {
        self.state.is_animating()
    }

    /// Check if the animation has settled (fully visible)
    ///
    /// Returns true if the motion is in `Visible` state.
    /// This is when it's safe to render child content with hover effects.
    pub fn is_settled(&self) -> bool {
        self.state.is_settled()
    }

    /// Check if the motion is suspended (waiting for explicit start)
    ///
    /// A suspended motion is mounted with opacity 0 and waits for `start()` to be called.
    pub fn is_suspended(&self) -> bool {
        self.state.is_suspended()
    }

    /// Check if the element is entering
    pub fn is_entering(&self) -> bool {
        self.state.is_entering()
    }

    /// Check if the element is exiting
    pub fn is_exiting(&self) -> bool {
        self.state.is_exiting()
    }

    /// Get the animation progress (0.0 to 1.0)
    ///
    /// Returns 0.0 for Suspended/Waiting, 1.0 for Visible/Removed, and the actual
    /// progress for Entering/Exiting states.
    pub fn progress(&self) -> f32 {
        self.state.progress()
    }

    /// Check if a motion with this key exists
    pub fn exists(&self) -> bool {
        !matches!(self.state, MotionAnimationState::NotFound)
    }

    /// Start the enter animation for a suspended motion
    ///
    /// Use this to explicitly trigger the enter animation for a motion that was
    /// created with `.suspended()`. The motion transitions from `Suspended` →
    /// `Waiting` or `Entering` state.
    ///
    /// This is useful for tab transitions and other cases where you want to:
    /// 1. Mount the content invisibly (opacity 0)
    /// 2. Perform any setup/measurement
    /// 3. Then trigger the animation manually
    ///
    /// No-op if the motion is not in `Suspended` state.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // In tabs.rs on_state callback:
    /// let motion_key = format!("tabs_motion:{}", active_tab);
    ///
    /// // Create suspended motion first
    /// let m = motion_derived(&motion_key)
    ///     .suspended()
    ///     .enter_animation(enter)
    ///     .child(content);
    ///
    /// // Then trigger the animation after mounting
    /// query_motion(&motion_key).start();
    /// ```
    pub fn start(&self) {
        // Queue the start to be processed during the next render frame
        crate::queue_global_motion_start(self.key.clone());
    }

    /// Cancel the exit animation and return the motion to Visible state
    ///
    /// Used when an overlay's close is cancelled (e.g., mouse re-enters hover card).
    /// This interrupts the exit animation and immediately sets the motion to fully visible.
    ///
    /// No-op if the motion is not in Exiting state.
    pub fn cancel_exit(&self) {
        // Queue the cancellation to be processed during the next render frame
        crate::queue_global_motion_exit_cancel(self.key.clone());
    }

    /// Trigger the exit animation for this motion
    ///
    /// Used to explicitly trigger the exit animation (e.g., when a hover card
    /// close countdown completes). This transitions the motion from Visible → Exiting.
    ///
    /// No-op if the motion is not in Visible state.
    pub fn exit(&self) {
        // Queue the exit to be processed during the next render frame
        crate::queue_global_motion_exit_start(self.key.clone());
    }
}