ailloli_ui_widgets/layout/
resize_bar.rs

1//! Standalone draggable split-resize handle and provider-neutral event model.
2
3use std::rc::Rc;
4
5use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
6use ailloli_ui_core::event::Event;
7use ailloli_ui_core::geometry::{Constraints, Point, Rect, Size};
8use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
9use ailloli_ui_core::{Color, Theme};
10use ailloli_ui_runtime::component::{ComponentNode, Context, IntoView, Signal, View, Widget};
11use ailloli_ui_runtime::input::{ActivationPolicy, EventCtx, HoverCursorRole};
12use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
13use ailloli_ui_runtime::scene::PaintCtx;
14use ailloli_ui_runtime::{DrawCmd, DrawRRect, Invalidation};
15
16use super::layout_ext::{apply_layout_size, finish_view_sized};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19/// Main axis changed by a resize handle.
20///
21/// `X` represents a vertical divider with horizontal movement; `Y` represents
22/// a horizontal divider with vertical movement.
23///
24/// # Examples
25///
26/// ```
27/// use ailloli_ui_runtime::input::HoverCursorRole;
28/// use ailloli_ui_widgets::layout::ResizeAxis;
29/// assert_eq!(ResizeAxis::X.cursor_role(), HoverCursorRole::ResizeX);
30/// ```
31pub enum ResizeAxis {
32    /// Horizontal position changed by a vertical bar.
33    X,
34    /// Vertical position changed by a horizontal bar.
35    Y,
36}
37
38impl ResizeAxis {
39    /// Returns the matching horizontal or vertical resize cursor role.
40    ///
41    /// # Examples
42    ///
43    /// ```
44    /// use ailloli_ui_runtime::input::HoverCursorRole;
45    /// use ailloli_ui_widgets::layout::ResizeAxis;
46    /// assert_eq!(ResizeAxis::Y.cursor_role(), HoverCursorRole::ResizeY);
47    /// ```
48    pub fn cursor_role(self) -> HoverCursorRole {
49        match self {
50            Self::X => HoverCursorRole::ResizeX,
51            Self::Y => HoverCursorRole::ResizeY,
52        }
53    }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57/// Emitted pointer-drag lifecycle for a resize interaction.
58///
59/// Pointer cancellation clears internal state without emitting `End`.
60///
61/// # Examples
62///
63/// ```
64/// use ailloli_ui_widgets::layout::ResizeDragPhase;
65/// assert_ne!(ResizeDragPhase::Start, ResizeDragPhase::End);
66/// ```
67pub enum ResizeDragPhase {
68    /// Initial left-button press inside the bar.
69    Start,
70    /// Pointer movement while captured.
71    Drag,
72    /// Left-button release after capture.
73    End,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq)]
77/// Resize event expressed along one logical-pixel main axis.
78///
79/// `delta` is relative to the previous event; `total_delta` is relative to the
80/// initial press. `position` is the current split or bar-local pointer position.
81///
82/// # Examples
83///
84/// ```
85/// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeDragPhase, SplitResizeEvent};
86/// let event = SplitResizeEvent { axis: ResizeAxis::X, phase: ResizeDragPhase::Drag, position: 120.0, delta: 4.0, total_delta: 12.0 };
87/// assert_eq!(event.total_delta, 12.0);
88/// ```
89pub struct SplitResizeEvent {
90    /// Horizontal (`X`) or vertical (`Y`) split coordinate.
91    pub axis: ResizeAxis,
92    /// Start, incremental drag, or end phase.
93    pub phase: ResizeDragPhase,
94    /// Current split position, in logical pixels on the main axis.
95    /// For standalone `ResizeBar`, this is the current main-axis pointer
96    /// coordinate inside the bar bounds.
97    pub position: f32,
98    /// Delta since the previous emitted event, in logical pixels.
99    pub delta: f32,
100    /// Delta since drag start, in logical pixels.
101    pub total_delta: f32,
102}
103
104#[derive(Clone, Copy, Debug, PartialEq)]
105/// Hit geometry, visible line geometry, and colors for [`ResizeBar`].
106///
107/// All dimensions are logical pixels and are consumed without global
108/// normalization. Defaults use an 8-pixel hit target, a 2-pixel line, and a
109/// 64-pixel intrinsic extent along the bar.
110///
111/// # Examples
112///
113/// ```
114/// use ailloli_ui_widgets::layout::ResizeBarStyle;
115/// let style = ResizeBarStyle::default();
116/// assert_eq!(style.hit_thickness, 8.0);
117/// assert_eq!(style.line_thickness, 2.0);
118/// ```
119pub struct ResizeBarStyle {
120    /// Hit target thickness on the resize axis.
121    pub hit_thickness: f32,
122    /// Centered visible line thickness.
123    pub line_thickness: f32,
124    /// Line color when neither hovered nor dragging.
125    pub idle_color: Color,
126    /// Line color while hovered.
127    pub hover_color: Color,
128    /// Line color while dragging.
129    pub active_color: Color,
130    /// Visible line corner radius.
131    pub radius: f32,
132    /// Default height of a vertical (`X`) bar.
133    pub vertical_extent: f32,
134    /// Default width of a horizontal (`Y`) bar.
135    pub horizontal_extent: f32,
136}
137
138/// Derives resize-bar defaults from [`Theme::default`].
139impl Default for ResizeBarStyle {
140    fn default() -> Self {
141        Self::from_theme(Theme::default())
142    }
143}
144
145impl ResizeBarStyle {
146    /// Derives colors from `theme` and uses the standard geometry defaults.
147    ///
148    /// # Examples
149    ///
150    /// ```
151    /// use ailloli_ui_core::Theme;
152    /// use ailloli_ui_widgets::layout::ResizeBarStyle;
153    /// assert_eq!(ResizeBarStyle::from_theme(Theme::dark()).vertical_extent, 64.0);
154    /// ```
155    pub fn from_theme(theme: Theme) -> Self {
156        let palette = theme.palette();
157        Self {
158            hit_thickness: 8.0,
159            line_thickness: 2.0,
160            idle_color: Color::TRANSPARENT,
161            hover_color: palette.focus.with_alpha(0.72),
162            active_color: palette.accent,
163            radius: 2.0,
164            vertical_extent: 64.0,
165            horizontal_extent: 64.0,
166        }
167    }
168
169    /// Returns the axis-oriented intrinsic size in logical pixels.
170    ///
171    /// Values are passed through without clamping.
172    ///
173    /// # Examples
174    ///
175    /// ```
176    /// use ailloli_ui_core::Size;
177    /// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeBarStyle};
178    /// let style = ResizeBarStyle::default();
179    /// assert_eq!(style.intrinsic_size(ResizeAxis::X), Size::new(8.0, 64.0));
180    /// assert_eq!(style.intrinsic_size(ResizeAxis::Y), Size::new(64.0, 8.0));
181    /// ```
182    pub fn intrinsic_size(&self, axis: ResizeAxis) -> Size {
183        match axis {
184            ResizeAxis::X => Size::new(self.hit_thickness, self.vertical_extent),
185            ResizeAxis::Y => Size::new(self.horizontal_extent, self.hit_thickness),
186        }
187    }
188}
189
190/// Shared retained callback invoked for emitted resize events.
191type ResizeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, SplitResizeEvent)>;
192
193/// Declarative draggable resize bar.
194///
195/// The default is vertical (`ResizeAxis::X`), uses theme-derived styling, and
196/// has no handler. Drag capture starts only on a left press inside its bounds.
197///
198/// # Examples
199///
200/// ```
201/// use ailloli_ui_widgets::layout::ResizeBar;
202/// let bar: ResizeBar<()> = ResizeBar::vertical();
203/// let _ = bar;
204/// ```
205pub struct ResizeBar<A = ()> {
206    /// Outer logical sizing policy inherited by the retained view.
207    pub(crate) layout: LayoutStyle,
208    /// Parent-flex participation metadata preserved during conversion.
209    pub(crate) flex_item: FlexItemStyle,
210    /// Coordinate axis changed by a drag.
211    axis: ResizeAxis,
212    /// Hit target and visual line geometry in logical pixels.
213    style: ResizeBarStyle,
214    /// Optional callback receiving start, drag, and end events.
215    on_resize: Option<ResizeHandler<A>>,
216}
217
218crate::impl_layout_builders!(ResizeBar);
219
220impl<A: 'static> ResizeBar<A> {
221    /// Creates a vertical bar that changes the x coordinate.
222    ///
223    /// # Examples
224    ///
225    /// ```
226    /// use ailloli_ui_widgets::layout::ResizeBar;
227    /// let bar: ResizeBar<()> = ResizeBar::vertical();
228    /// let _ = bar;
229    /// ```
230    pub fn vertical() -> Self {
231        Self::new(ResizeAxis::X)
232    }
233
234    /// Creates a horizontal bar that changes the y coordinate.
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// use ailloli_ui_widgets::layout::ResizeBar;
240    /// let bar: ResizeBar<()> = ResizeBar::horizontal();
241    /// let _ = bar;
242    /// ```
243    pub fn horizontal() -> Self {
244        Self::new(ResizeAxis::Y)
245    }
246
247    /// Creates a resize bar for the explicit main axis.
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeBar};
253    /// let bar: ResizeBar<()> = ResizeBar::new(ResizeAxis::Y);
254    /// let _ = bar;
255    /// ```
256    pub fn new(axis: ResizeAxis) -> Self {
257        Self {
258            layout: LayoutStyle::default(),
259            flex_item: FlexItemStyle::default(),
260            axis,
261            style: ResizeBarStyle::default(),
262            on_resize: None,
263        }
264    }
265
266    /// Replaces all hit, line, extent, radius, and color values.
267    ///
268    /// # Examples
269    ///
270    /// ```
271    /// use ailloli_ui_widgets::layout::{ResizeBar, ResizeBarStyle};
272    /// let style = ResizeBarStyle { hit_thickness: 12.0, ..Default::default() };
273    /// let bar: ResizeBar<()> = ResizeBar::vertical().resize_bar_style(style);
274    /// let _ = bar;
275    /// ```
276    pub fn resize_bar_style(mut self, style: ResizeBarStyle) -> Self {
277        self.style = style;
278        self
279    }
280
281    /// Maps each emitted resize event into an application action.
282    ///
283    /// # Examples
284    ///
285    /// ```
286    /// use ailloli_ui_widgets::layout::{ResizeBar, SplitResizeEvent};
287    /// enum Action { Resize(SplitResizeEvent) }
288    /// let bar: ResizeBar<Action> = ResizeBar::vertical().on_resize(Action::Resize);
289    /// let _ = bar;
290    /// ```
291    pub fn on_resize(mut self, f: impl Fn(SplitResizeEvent) -> A + 'static) -> Self {
292        self.on_resize = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
293        self
294    }
295
296    /// Handles resize events with mutable runtime event-context access.
297    ///
298    /// # Examples
299    ///
300    /// ```
301    /// use ailloli_ui_widgets::layout::ResizeBar;
302    /// let bar: ResizeBar<()> = ResizeBar::vertical().on_resize_ctx(|_ctx, _event| {});
303    /// let _ = bar;
304    /// ```
305    pub fn on_resize_ctx(
306        mut self,
307        f: impl Fn(&mut EventCtx<A>, SplitResizeEvent) + 'static,
308    ) -> Self {
309        self.on_resize = Some(Rc::new(f));
310        self
311    }
312}
313
314/// Creates a vertical resize bar.
315impl<A: 'static> Default for ResizeBar<A> {
316    fn default() -> Self {
317        Self::vertical()
318    }
319}
320
321/// Retained builder snapshot used to allocate drag state.
322struct ResizeBarComponent<A> {
323    /// Outer logical sizing policy.
324    layout: LayoutStyle,
325    /// Coordinate axis changed by a drag.
326    axis: ResizeAxis,
327    /// Hit target and visual line geometry in logical pixels.
328    style: ResizeBarStyle,
329    /// Optional retained resize callback.
330    on_resize: Option<ResizeHandler<A>>,
331}
332
333/// Builds a leaf widget with persistent optional drag state.
334impl<A: 'static> ComponentNode<A> for ResizeBarComponent<A> {
335    fn build(&self, context: &mut Context<A>) -> View<A> {
336        View::leaf(ResizeBarWidget {
337            layout: self.layout,
338            axis: self.axis,
339            style: self.style,
340            on_resize: self.on_resize.clone(),
341            drag: context.signal_with_invalidation(None, Invalidation::Paint),
342        })
343    }
344}
345
346#[derive(Debug, Clone, Copy, PartialEq)]
347/// Captured initial and previous pointer positions in logical pixels.
348///
349/// # Examples
350///
351/// ```
352/// use ailloli_ui_core::Point;
353/// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeDragPhase, SplitResizeEvent};
354/// let event = SplitResizeEvent { axis: ResizeAxis::X, phase: ResizeDragPhase::Start, position: Point::new(3.0, 4.0).x, delta: 0.0, total_delta: 0.0 };
355/// assert_eq!(event.position, 3.0);
356/// ```
357pub(crate) struct ResizeDragState {
358    /// Pointer at the initial press.
359    pub start: Point,
360    /// Pointer used as the next incremental-delta origin.
361    pub last: Point,
362}
363
364/// Retained leaf implementing layout, paint, pointer capture, and cursor role.
365struct ResizeBarWidget<A> {
366    /// Outer logical sizing policy.
367    layout: LayoutStyle,
368    /// Coordinate axis changed by a drag.
369    axis: ResizeAxis,
370    /// Hit target and visual line geometry in logical pixels.
371    style: ResizeBarStyle,
372    /// Optional retained resize callback.
373    on_resize: Option<ResizeHandler<A>>,
374    /// Captured pointer state, or `None` outside an active drag.
375    drag: Signal<Option<ResizeDragState>>,
376}
377
378/// Implements the standalone resize-bar interaction contract.
379impl<A: 'static> Widget<A> for ResizeBarWidget<A> {
380    fn debug_name(&self) -> &'static str {
381        "ResizeBar"
382    }
383
384    fn layout(
385        &self,
386        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
387        _ctx: &mut LayoutCtx<'_>,
388        _children: &mut [LayoutChild],
389        constraints: Constraints,
390    ) -> LayoutResult {
391        let size = apply_layout_size(
392            self.style.intrinsic_size(self.axis),
393            self.layout,
394            constraints,
395        );
396        let bounds = Rect::new(0.0, 0.0, size.w, size.h);
397        LayoutResult {
398            size,
399            children: Vec::new(),
400            paint_bounds: bounds,
401            visual_bounds: bounds,
402            overlay_hit_bounds: Vec::new(),
403            clip: None,
404            is_window_root_clip: false,
405            artifact: None,
406        }
407    }
408
409    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
410        let dragging = self.drag.read().is_some();
411        let color = if dragging {
412            self.style.active_color
413        } else if ctx.interaction().hovered {
414            self.style.hover_color
415        } else {
416            self.style.idle_color
417        };
418        paint_resize_line(ctx, bounds, self.axis, &self.style, color);
419    }
420
421    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
422        match event {
423            Event::Pointer(PointerEvent::Button {
424                pos,
425                button: MouseButton::Left,
426                pressed: true,
427                ..
428            }) if bounds.contains(pos.x, pos.y) => {
429                self.drag.set(Some(ResizeDragState {
430                    start: *pos,
431                    last: *pos,
432                }));
433                self.emit(ctx, ResizeDragPhase::Start, *pos, *pos, *pos, bounds);
434                ctx.request_repaint();
435                ctx.stop_propagation();
436            }
437            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
438                if let Some(drag) = self.drag.read() {
439                    self.emit(
440                        ctx,
441                        ResizeDragPhase::Drag,
442                        *pos,
443                        drag.last,
444                        drag.start,
445                        bounds,
446                    );
447                    self.drag.set(Some(ResizeDragState {
448                        start: drag.start,
449                        last: *pos,
450                    }));
451                    ctx.stop_propagation();
452                }
453            }
454            Event::Pointer(PointerEvent::Button {
455                pos,
456                button: MouseButton::Left,
457                pressed: false,
458                ..
459            }) => {
460                if let Some(drag) = self.drag.read() {
461                    self.emit(
462                        ctx,
463                        ResizeDragPhase::End,
464                        *pos,
465                        drag.last,
466                        drag.start,
467                        bounds,
468                    );
469                    self.drag.set(None);
470                    ctx.request_repaint();
471                    ctx.stop_propagation();
472                }
473            }
474            Event::Pointer(PointerEvent::Cancelled { .. }) if self.drag.read().is_some() => {
475                self.drag.set(None);
476                ctx.request_repaint();
477                ctx.stop_propagation();
478            }
479            _ => {}
480        }
481    }
482
483    fn activation_policy(&self) -> ActivationPolicy {
484        ActivationPolicy::AllowOnFocusOnly
485    }
486
487    fn hover_cursor_role(&self) -> HoverCursorRole {
488        self.axis.cursor_role()
489    }
490}
491
492/// Constructs and dispatches one resize event when a handler exists.
493impl<A: 'static> ResizeBarWidget<A> {
494    /// Builds and dispatches one axis-projected resize event when configured.
495    fn emit(
496        &self,
497        ctx: &mut EventCtx<A>,
498        phase: ResizeDragPhase,
499        current: Point,
500        last: Point,
501        start: Point,
502        bounds: Rect,
503    ) {
504        let event = resize_event(self.axis, phase, current, last, start, bounds, 0.0);
505        if let Some(on_resize) = &self.on_resize {
506            on_resize(ctx, event);
507        }
508    }
509}
510
511/// Converts the builder into a retained component and preserves flex metadata.
512impl<A: 'static> IntoView<A> for ResizeBar<A> {
513    fn into_view(self) -> View<A> {
514        finish_view_sized(
515            View::component(ResizeBarComponent {
516                layout: self.layout,
517                axis: self.axis,
518                style: self.style,
519                on_resize: self.on_resize,
520            }),
521            self.flex_item,
522            LayoutSizeHint::from_layout(self.layout),
523        )
524    }
525}
526
527/// Selects x for [`ResizeAxis::X`] or y for [`ResizeAxis::Y`].
528///
529/// # Examples
530///
531/// ```
532/// use ailloli_ui_core::Point;
533/// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeDragPhase, SplitResizeEvent};
534/// let point = Point::new(7.0, 9.0);
535/// let event = SplitResizeEvent { axis: ResizeAxis::Y, phase: ResizeDragPhase::Drag, position: point.y, delta: 0.0, total_delta: 0.0 };
536/// assert_eq!(event.position, 9.0);
537/// ```
538pub(crate) fn axis_value(axis: ResizeAxis, point: Point) -> f32 {
539    match axis {
540        ResizeAxis::X => point.x,
541        ResizeAxis::Y => point.y,
542    }
543}
544
545/// Builds axis-relative deltas and resolves the split-position sentinel.
546///
547/// A strictly positive explicit `position` wins. Zero, negative, or `NaN`
548/// instead uses the pointer position relative to `bounds`, clamped to the
549/// corresponding bound extent.
550///
551/// # Examples
552///
553/// ```
554/// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeDragPhase, SplitResizeEvent};
555/// let event = SplitResizeEvent { axis: ResizeAxis::X, phase: ResizeDragPhase::Drag, position: 20.0, delta: 3.0, total_delta: 8.0 };
556/// assert_eq!((event.position, event.delta), (20.0, 3.0));
557/// ```
558pub(crate) fn resize_event(
559    axis: ResizeAxis,
560    phase: ResizeDragPhase,
561    current: Point,
562    last: Point,
563    start: Point,
564    bounds: Rect,
565    position: f32,
566) -> SplitResizeEvent {
567    let current_main = axis_value(axis, current);
568    let last_main = axis_value(axis, last);
569    let start_main = axis_value(axis, start);
570    let fallback_position = match axis {
571        ResizeAxis::X => (current.x - bounds.x).clamp(0.0, bounds.w),
572        ResizeAxis::Y => (current.y - bounds.y).clamp(0.0, bounds.h),
573    };
574    SplitResizeEvent {
575        axis,
576        phase,
577        position: if position > 0.0 {
578            position
579        } else {
580            fallback_position
581        },
582        delta: current_main - last_main,
583        total_delta: current_main - start_main,
584    }
585}
586
587/// Centers the visible line across the complete bar extent.
588///
589/// # Examples
590///
591/// ```
592/// use ailloli_ui_core::Size;
593/// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeBarStyle};
594/// assert_eq!(ResizeBarStyle::default().intrinsic_size(ResizeAxis::X), Size::new(8.0, 64.0));
595/// ```
596pub(crate) fn line_rect(bounds: Rect, axis: ResizeAxis, style: &ResizeBarStyle) -> Rect {
597    match axis {
598        ResizeAxis::X => Rect::new(
599            bounds.x + (bounds.w - style.line_thickness) * 0.5,
600            bounds.y,
601            style.line_thickness,
602            bounds.h,
603        ),
604        ResizeAxis::Y => Rect::new(
605            bounds.x,
606            bounds.y + (bounds.h - style.line_thickness) * 0.5,
607            bounds.w,
608            style.line_thickness,
609        ),
610    }
611}
612
613/// Appends one rounded line unless color alpha or bounds dimensions are non-positive.
614///
615/// # Examples
616///
617/// ```
618/// use ailloli_ui_widgets::layout::{ResizeAxis, ResizeBar, ResizeBarStyle};
619/// let bar: ResizeBar<()> = ResizeBar::new(ResizeAxis::X).resize_bar_style(ResizeBarStyle::default());
620/// let _ = bar;
621/// ```
622pub(crate) fn paint_resize_line(
623    ctx: &mut PaintCtx<'_>,
624    bounds: Rect,
625    axis: ResizeAxis,
626    style: &ResizeBarStyle,
627    color: Color,
628) {
629    if color.a <= 0.0 || bounds.w <= 0.0 || bounds.h <= 0.0 {
630        return;
631    }
632    ctx.push(DrawCmd::RRect(DrawRRect {
633        rect: line_rect(bounds, axis, style),
634        radius: Radius::uniform(style.radius).tl,
635        color,
636    }));
637}