use canvist_model::Document;
use canvist_model::Point;
use crate::position;
use crate::text;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Affinity {
Upstream,
#[default]
Downstream,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Caret {
pub point: Point,
pub affinity: Affinity,
}
impl Caret {
#[must_use]
pub const fn new(point: Point) -> Self {
Self {
point,
affinity: Affinity::Downstream,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VerticalDirection {
Up,
Down,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LineEdge {
Start,
End,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VerticalMotion {
pub caret: Caret,
pub goal_x: f32,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct NavigationError(String);
impl NavigationError {
#[must_use]
pub fn new(error: &impl std::fmt::Display) -> Self {
Self(error.to_string())
}
}
pub trait LineNavigator {
fn vertical(
&mut self,
doc: &Document,
from: Caret,
direction: VerticalDirection,
goal_x: Option<f32>,
) -> Result<Option<VerticalMotion>, NavigationError>;
fn line_edge(
&mut self,
doc: &Document,
at: Caret,
edge: LineEdge,
) -> Result<Caret, NavigationError>;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ParagraphNavigator;
impl LineNavigator for ParagraphNavigator {
fn vertical(
&mut self,
doc: &Document,
from: Caret,
direction: VerticalDirection,
goal_x: Option<f32>,
) -> Result<Option<VerticalMotion>, NavigationError> {
let point = from.point;
let Some(current) = doc.inline(point.block) else {
return Ok(None);
};
let goal_x = goal_x.unwrap_or_else(|| text::column(current.as_str(), point.offset) as f32);
let next = match direction {
VerticalDirection::Up => doc.prev_text_block(point.block),
VerticalDirection::Down => doc.next_text_block(point.block),
};
let Some((next, text)) = next.and_then(|id| Some((id, doc.inline(id)?.as_str()))) else {
return Ok(None);
};
let offset = text::offset_at_column(text, goal_x.max(0.0) as usize);
Ok(Some(VerticalMotion {
caret: Caret::new(Point::new(next, offset)),
goal_x,
}))
}
fn line_edge(
&mut self,
doc: &Document,
at: Caret,
edge: LineEdge,
) -> Result<Caret, NavigationError> {
let point = match edge {
LineEdge::Start => Point::new(at.point.block, 0),
LineEdge::End => position::end_of(doc, at.point.block),
};
Ok(Caret::new(point))
}
}