Skip to main content

fc_ui/capabilities/foundation/
util.rs

1//! # Utility Extensions and Helper Functions
2//!
3//! Common extension traits and utility functions that enhance GPUI's standard types
4//! with convenient methods used throughout the component library.
5//! ## Extension Traits
6//!
7//! - **`AxisExt`**: Convenient methods for checking axis orientation
8//! - **`PixelsExt`**: Conversion utilities for Pixels type
9//! - **`ScrollHandleOffsetable`**: Trait for scroll handle offset operations
10//! - **Color utilities**: Color manipulation and conversion helpers
11//! - **Layout helpers**: Common layout calculations and measurements
12//!
13//! ## Design Decisions
14//!
15//! - **Minimal Surface Area**: Only essential utilities that are reused across components
16//! - **Type Safety**: Extension traits maintain strong typing and prevent errors
17//! - **Performance**: Zero-cost abstractions that compile to efficient machine code
18//! - **Consistency**: Standardized patterns for common operations
19//! - **Discoverability**: Clear naming that makes functionality obvious
20//!
21
22use gpui::{Pixels, Point, ScrollHandle, Size};
23
24/// Extension trait for Axis
25pub trait AxisExt {
26    /// Returns true if the axis is horizontal
27    fn is_horizontal(self) -> bool;
28    /// Returns true if the axis is vertical
29    fn is_vertical(self) -> bool;
30}
31
32impl AxisExt for gpui::Axis {
33    fn is_horizontal(self) -> bool {
34        self == gpui::Axis::Horizontal
35    }
36
37    fn is_vertical(self) -> bool {
38        self == gpui::Axis::Vertical
39    }
40}
41
42/// Extension trait for converting Pixels to f32 and f64
43pub trait PixelsExt {
44    /// Convert to f32
45    fn as_f32(&self) -> f32;
46    /// Convert to f64
47    fn as_f64(self) -> f64;
48}
49
50impl PixelsExt for Pixels {
51    fn as_f32(&self) -> f32 {
52        f32::from(*self)
53    }
54
55    fn as_f64(self) -> f64 {
56        f64::from(self)
57    }
58}
59
60/// Trait for types that can be used as scroll handles with offset tracking
61pub trait ScrollHandleOffsetable {
62    /// Get the current scroll offset
63    fn offset(&self) -> Point<Pixels>;
64    /// Set the scroll offset
65    fn set_offset(&self, offset: Point<Pixels>);
66    /// Get the full content size
67    fn content_size(&self) -> Size<Pixels>;
68}
69
70impl ScrollHandleOffsetable for ScrollHandle {
71    fn offset(&self) -> Point<Pixels> {
72        self.offset()
73    }
74
75    fn set_offset(&self, offset: Point<Pixels>) {
76        self.set_offset(offset);
77    }
78
79    fn content_size(&self) -> Size<Pixels> {
80        self.max_offset() + self.bounds().size
81    }
82}