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
#![warn(missing_docs)]
use crate::layout::Rect;
/// Position in the terminal
///
/// The position is relative to the top left corner of the terminal window, with the top left corner
/// being (0, 0). The x axis is horizontal increasing to the right, and the y axis is vertical
/// increasing downwards.
///
/// # Examples
///
/// ```
/// use ratatui::layout::{Position, Rect};
///
/// // the following are all equivalent
/// let position = Position { x: 1, y: 2 };
/// let position = Position::new(1, 2);
/// let position = Position::from((1, 2));
/// let position = Position::from(Rect::new(1, 2, 3, 4));
///
/// // position can be converted back into the components when needed
/// let (x, y) = position.into();
/// ```
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct Position {
/// The x coordinate of the position
///
/// The x coordinate is relative to the left edge of the terminal window, with the left edge
/// being 0.
pub x: u16,
/// The y coordinate of the position
///
/// The y coordinate is relative to the top edge of the terminal window, with the top edge
/// being 0.
pub y: u16,
}
impl Position {
/// Create a new position
pub const fn new(x: u16, y: u16) -> Self {
Self { x, y }
}
}
impl From<(u16, u16)> for Position {
fn from((x, y): (u16, u16)) -> Self {
Self { x, y }
}
}
impl From<Position> for (u16, u16) {
fn from(position: Position) -> Self {
(position.x, position.y)
}
}
impl From<Rect> for Position {
fn from(rect: Rect) -> Self {
rect.as_position()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new() {
let position = Position::new(1, 2);
assert_eq!(position.x, 1);
assert_eq!(position.y, 2);
}
#[test]
fn from_tuple() {
let position = Position::from((1, 2));
assert_eq!(position.x, 1);
assert_eq!(position.y, 2);
}
#[test]
fn into_tuple() {
let position = Position::new(1, 2);
let (x, y) = position.into();
assert_eq!(x, 1);
assert_eq!(y, 2);
}
#[test]
fn from_rect() {
let rect = Rect::new(1, 2, 3, 4);
let position = Position::from(rect);
assert_eq!(position.x, 1);
assert_eq!(position.y, 2);
}
}