use std::cmp::Ordering;
use std::ops::Range;
use canvist_model::Block;
use canvist_model::BlockId;
use canvist_model::Content;
use canvist_model::Document;
use canvist_model::InlineText;
use canvist_model::Point;
use canvist_model::Selection;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TextRange {
pub from: Point,
pub to: Point,
}
impl TextRange {
#[must_use]
pub fn is_empty(&self) -> bool {
self.from == self.to
}
}
#[must_use]
pub fn text_range(doc: &Document, selection: Selection) -> Option<TextRange> {
let Selection::Text { anchor, head } = selection else {
return None;
};
if compare_points(doc, anchor, head) == Ordering::Greater {
return Some(TextRange {
from: head,
to: anchor,
});
}
Some(TextRange {
from: anchor,
to: head,
})
}
#[must_use]
pub fn compare_points(doc: &Document, a: Point, b: Point) -> Ordering {
if a.block == b.block {
return a.offset.cmp(&b.offset);
}
compare_blocks(doc, a.block, b.block)
}
#[must_use]
pub fn compare_blocks(doc: &Document, a: BlockId, b: BlockId) -> Ordering {
path(doc, a).cmp(&path(doc, b))
}
fn path(doc: &Document, id: BlockId) -> Vec<usize> {
let mut indexes: Vec<usize> = ancestors_or_self(doc, id)
.filter_map(|block| doc.index_in_parent(block))
.collect();
indexes.reverse();
indexes
}
pub fn ancestors_or_self(doc: &Document, id: BlockId) -> impl Iterator<Item = BlockId> + '_ {
std::iter::successors(Some(id), |¤t| {
doc.block(current).and_then(Block::parent)
})
.filter(|¤t| doc.contains(current))
}
#[must_use]
pub fn parent_of(doc: &Document, id: BlockId) -> Option<BlockId> {
doc.block(id).and_then(Block::parent)
}
#[must_use]
pub fn text_len(doc: &Document, id: BlockId) -> u32 {
doc.inline(id).map_or(0, InlineText::len)
}
#[must_use]
pub fn end_of(doc: &Document, id: BlockId) -> Point {
Point::new(id, text_len(doc, id))
}
#[must_use]
pub fn is_leaf(doc: &Document, id: BlockId) -> bool {
doc.block(id)
.is_some_and(|block| matches!(block.content(), Content::Leaf))
}
#[must_use]
pub fn last_descendant(doc: &Document, id: BlockId) -> BlockId {
let mut current = id;
while let Some(&last) = doc.children(Some(current)).last() {
current = last;
}
current
}
#[must_use]
pub fn start_selection(doc: &Document) -> Selection {
if let Some(first) = doc.first_text_block() {
return Selection::caret(Point::new(first, 0));
}
let first = doc.children(None).first().copied();
first.map_or_else(
|| Selection::caret(Point::new(BlockId::new(0, 0), 0)),
Selection::block,
)
}
#[must_use]
pub fn end_selection(doc: &Document) -> Selection {
doc.last_text_block().map_or_else(
|| start_selection(doc),
|last| Selection::caret(end_of(doc, last)),
)
}
#[must_use]
pub fn valid_selection(doc: &Document, selection: Selection) -> Selection {
match selection {
Selection::Text { anchor, head } => {
match (valid_point(doc, anchor), valid_point(doc, head)) {
(Some(anchor), Some(head)) => Selection::Text { anchor, head },
(Some(point), None) | (None, Some(point)) => Selection::caret(point),
(None, None) => start_selection(doc),
}
}
Selection::Blocks { anchor, head } => {
let siblings = doc.contains(anchor)
&& doc.contains(head)
&& parent_of(doc, anchor) == parent_of(doc, head);
if siblings {
selection
} else {
start_selection(doc)
}
}
}
}
fn valid_point(doc: &Document, point: Point) -> Option<Point> {
let text = doc.inline(point.block)?.as_str();
let mut offset = (point.offset as usize).min(text.len());
while !text.is_char_boundary(offset) {
offset -= 1;
}
Some(Point::new(point.block, offset as u32))
}
#[must_use]
pub fn sibling_range(
doc: &Document,
first: BlockId,
last: BlockId,
) -> Option<(Option<BlockId>, Range<usize>)> {
let first_chain: Vec<BlockId> = ancestors_or_self(doc, first).collect();
for candidate in ancestors_or_self(doc, last) {
let parent = parent_of(doc, candidate);
let start = first_chain
.iter()
.find(|&&block| parent_of(doc, block) == parent)
.copied();
if let Some(start) = start {
let end = doc.index_in_parent(candidate)?;
let start = if start == candidate {
end
} else {
doc.index_in_parent(start)?
};
return (start <= end).then(|| (parent, start..end + 1));
}
}
None
}
#[must_use]
pub fn covered_text(doc: &Document, range: TextRange) -> Vec<(BlockId, Range<u32>)> {
let mut covered = Vec::new();
let mut current = Some(range.from.block);
while let Some(block) = current {
let start = if block == range.from.block {
range.from.offset
} else {
0
};
if block == range.to.block {
covered.push((block, start..range.to.offset));
break;
}
covered.push((block, start..text_len(doc, block)));
current = doc.next_text_block(block);
}
covered
}
#[must_use]
pub fn covered_blocks(
doc: &Document,
anchor: BlockId,
head: BlockId,
) -> Vec<(BlockId, Range<u32>)> {
let Some((parent, range)) = sibling_range(doc, anchor, head) else {
return Vec::new();
};
let mut covered = Vec::new();
for &child in &doc.children(parent)[range] {
collect_text(doc, child, &mut covered);
}
covered
}
fn collect_text(doc: &Document, id: BlockId, covered: &mut Vec<(BlockId, Range<u32>)>) {
if doc.inline(id).is_some() {
covered.push((id, 0..text_len(doc, id)));
}
for &child in doc.children(Some(id)) {
collect_text(doc, child, covered);
}
}
#[must_use]
pub fn selected_text(doc: &Document, selection: Selection) -> Vec<(BlockId, Range<u32>)> {
match selection {
Selection::Text { .. } => {
text_range(doc, selection).map_or_else(Vec::new, |range| covered_text(doc, range))
}
Selection::Blocks { anchor, head } => covered_blocks(doc, anchor, head),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stop {
Text(Point),
Leaf(BlockId),
}
#[must_use]
pub fn next_stop(doc: &Document, id: BlockId) -> Option<Stop> {
let mut current = doc.next_block(last_descendant(doc, id));
while let Some(block) = current {
if doc.inline(block).is_some() {
return Some(Stop::Text(Point::new(block, 0)));
}
if is_leaf(doc, block) {
return Some(Stop::Leaf(block));
}
current = doc.next_block(block);
}
None
}
#[must_use]
pub fn prev_stop(doc: &Document, id: BlockId) -> Option<Stop> {
let mut current = doc.prev_block(id);
while let Some(block) = current {
if doc.inline(block).is_some() {
return Some(Stop::Text(end_of(doc, block)));
}
if is_leaf(doc, block) {
return Some(Stop::Leaf(block));
}
current = doc.prev_block(block);
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing;
#[test]
fn orders_points_across_nesting() {
let doc = testing::nested_doc();
let texts: Vec<BlockId> = doc.text_blocks().map(Block::id).collect();
for pair in texts.windows(2) {
assert_eq!(compare_blocks(&doc, pair[0], pair[1]), Ordering::Less);
}
let list = doc.children(None)[1];
assert_eq!(compare_blocks(&doc, list, texts[1]), Ordering::Less);
}
#[test]
fn sibling_range_finds_the_common_parent() {
let doc = testing::nested_doc();
let texts: Vec<BlockId> = doc.text_blocks().map(Block::id).collect();
let list = doc.children(None)[1];
assert_eq!(
sibling_range(&doc, texts[1], texts[2]),
Some((Some(list), 0..2))
);
assert_eq!(sibling_range(&doc, texts[0], texts[3]), Some((None, 0..3)));
assert_eq!(sibling_range(&doc, texts[3], texts[0]), None);
}
#[test]
fn repairs_invalid_selections() {
let doc = testing::nested_doc();
let first = doc.first_text_block().expect("text");
let broken = Selection::caret(Point::new(first, 99));
assert_eq!(
valid_selection(&doc, broken),
Selection::caret(Point::new(first, 5))
);
let gone = Selection::caret(Point::new(BlockId::new(7, 7), 0));
assert_eq!(valid_selection(&doc, gone), start_selection(&doc));
}
}