use std::{ops::Range, sync::Arc};
use crate::{
AttributedText,
geometry::{Bounds, Point, Points, point, size},
text::escape_html,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct TextPosition {
pub text: usize,
pub offset: u32,
}
impl TextPosition {
pub const fn new(text: usize, offset: u32) -> Self {
Self { text, offset }
}
}
pub trait SelectionTexts {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn content(&self, i: usize) -> &str;
fn copied(&self, i: usize, range: Range<u32>) -> String {
let content = self.content(i);
content[byte_offset(content, range.start)..byte_offset(content, range.end)]
.chars()
.filter(|&c| c != OBJECT_REPLACEMENT)
.collect()
}
#[doc(hidden)]
fn attributed(&self, i: usize) -> Option<&AttributedText> {
let _ = i;
None
}
fn frame(&self, i: usize) -> Bounds<Points>;
fn offset_at(&self, i: usize, point: Point<Points>) -> u32;
fn key(&self, i: usize) -> u64 {
i as u64
}
fn continues(&self, i: usize) -> bool {
let _ = i;
false
}
fn marker(&self, i: usize) -> Option<&str> {
let _ = i;
None
}
fn range_bounds(&self, i: usize, range: Range<u32>) -> Option<Bounds<Points>> {
let _ = (i, range);
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Granularity {
#[default]
Character,
Word,
Paragraph,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum Unit {
#[default]
Character,
Word,
Token,
Paragraph,
}
impl From<Granularity> for Unit {
fn from(granularity: Granularity) -> Self {
match granularity {
Granularity::Character => Unit::Character,
Granularity::Word => Unit::Word,
Granularity::Paragraph => Unit::Paragraph,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Handle {
Start,
End,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Movement {
Character,
Word,
Line,
LineEdge,
Paragraph,
Document,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
Backward,
Forward,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SelectionModel {
anchor: Option<TextPosition>,
focus: Option<TextPosition>,
granularity: Unit,
anchor_unit: Option<(TextPosition, TextPosition)>,
keys: [Option<u64>; 4],
goal_x: Option<f32>,
upstream: bool,
}
impl SelectionModel {
pub fn new() -> Self {
Self::default()
}
pub fn is_empty(&self) -> bool {
self.bounds().is_none_or(|(start, end)| start == end)
}
pub fn press(
&mut self,
texts: &impl SelectionTexts,
point: Point<Points>,
clicks: u32,
extend: bool,
) -> bool {
let before = self.bounds();
let Some(pos) = hit(texts, point) else {
return self.clear();
};
self.forget_keys();
if extend && self.anchor.is_some() {
self.extend_to(texts, pos);
self.remember(texts);
return self.bounds() != before;
}
let granularity = match clicks {
0 | 1 => Granularity::Character,
2 => Granularity::Word,
_ => Granularity::Paragraph,
};
self.select_unit(texts, pos, granularity.into());
self.remember(texts);
self.bounds() != before
}
pub fn drag(&mut self, texts: &impl SelectionTexts, point: Point<Points>) -> bool {
if self.anchor.is_none() {
return false;
}
let Some(pos) = hit(texts, point) else {
return false;
};
let before = self.bounds();
self.forget_keys();
self.extend_to(texts, pos);
self.remember(texts);
self.bounds() != before
}
pub fn select_word_at(&mut self, texts: &impl SelectionTexts, point: Point<Points>) -> bool {
let before = self.bounds();
let Some(pos) = hit(texts, point) else {
return self.clear();
};
self.forget_keys();
self.select_unit(texts, pos, Unit::Token);
self.remember(texts);
self.bounds() != before
}
pub fn move_handle(
&mut self,
texts: &impl SelectionTexts,
handle: Handle,
point: Point<Points>,
) -> bool {
let Some((start, end)) = self.bounds() else {
return false;
};
let Some(pos) = hit(texts, point) else {
return false;
};
let fixed = match handle {
Handle::Start => end,
Handle::End => start,
};
self.anchor = Some(fixed);
self.focus = Some(pos);
self.granularity = Unit::Character;
self.anchor_unit = None;
self.forget_keys();
self.remember(texts);
self.bounds() != Some((start, end))
}
pub fn select_range(
&mut self,
texts: &impl SelectionTexts,
start: TextPosition,
end: TextPosition,
) -> bool {
if start.text >= texts.len() || end.text >= texts.len() {
return self.clear();
}
let before = self.bounds();
self.anchor = Some(clamp_position(texts, start));
self.focus = Some(clamp_position(texts, end));
self.granularity = Unit::Character;
self.anchor_unit = None;
self.forget_keys();
self.remember(texts);
self.bounds() != before
}
pub fn select_all(&mut self, texts: &impl SelectionTexts) -> bool {
if texts.is_empty() {
return self.clear();
}
let last = texts.len() - 1;
self.select_range(
texts,
TextPosition::new(0, 0),
TextPosition::new(last, utf16_len(texts.content(last))),
)
}
pub fn clear(&mut self) -> bool {
let had = self.anchor.is_some();
*self = Self::default();
had
}
pub fn extend(
&mut self,
texts: &impl SelectionTexts,
movement: Movement,
direction: Direction,
) -> bool {
let (Some(anchor), Some(focus)) = (self.anchor, self.focus) else {
return false;
};
if anchor.text >= texts.len() || focus.text >= texts.len() {
return false;
}
let before = self.bounds();
let (anchor, focus) = if self.granularity == Unit::Character {
(anchor, focus)
} else {
let (start, end) = (anchor.min(focus), anchor.max(focus));
match direction {
Direction::Backward => (end, start),
Direction::Forward => (start, end),
}
};
let forward = direction == Direction::Forward;
let mut goal_x = None;
let mut upstream = false;
let to = match movement {
Movement::Character => step(texts, focus, forward),
Movement::Word => word_step(texts, focus, forward),
Movement::Line => {
let caret = caret(texts, focus, self.upstream);
let x = self.goal_x.unwrap_or(caret.left().0);
goal_x = Some(x);
line_step(texts, focus, caret, x, forward)
}
Movement::LineEdge => {
let caret = caret(texts, focus, self.upstream);
upstream = forward;
line_edge(texts, focus, caret, forward)
}
Movement::Paragraph => paragraph_step(texts, focus, forward),
Movement::Document => document_edge(texts, forward),
};
self.anchor = Some(anchor);
self.focus = Some(clamp_position(texts, to));
self.granularity = Unit::Character;
self.anchor_unit = None;
self.goal_x = goal_x;
self.upstream = upstream;
self.remember(texts);
self.bounds() != before
}
pub fn focus_caret(&self, texts: &impl SelectionTexts) -> Option<Bounds<Points>> {
let focus = self.focus.filter(|f| f.text < texts.len())?;
Some(caret(texts, focus, self.upstream))
}
fn forget_keys(&mut self) {
self.goal_x = None;
self.upstream = false;
}
pub fn texts_changed(&mut self, texts: &impl SelectionTexts) -> bool {
let (Some(mut anchor), Some(mut focus)) = (self.anchor, self.focus) else {
return false;
};
let find = |key: Option<u64>, at: usize| -> Option<usize> {
let key = key?;
if at < texts.len() && texts.key(at) == key {
return Some(at);
}
(0..texts.len()).find(|&i| texts.key(i) == key)
};
let (Some(a), Some(f)) = (
find(self.keys[0], anchor.text),
find(self.keys[1], focus.text),
) else {
return self.clear();
};
let moved = a != anchor.text || f != focus.text;
anchor.text = a;
focus.text = f;
self.anchor = Some(anchor);
self.focus = Some(focus);
if let Some((u0, u1)) = self.anchor_unit {
self.anchor_unit = match (find(self.keys[2], u0.text), find(self.keys[3], u1.text)) {
(Some(i), Some(j)) => Some((
TextPosition::new(i, u0.offset),
TextPosition::new(j, u1.offset),
)),
_ => None,
};
}
let before = self.bounds();
self.anchor = Some(clamp_position(texts, anchor));
self.focus = Some(clamp_position(texts, focus));
self.anchor_unit = self.anchor_unit.and_then(|(a, b)| {
(a.text < texts.len() && b.text < texts.len())
.then(|| (clamp_position(texts, a), clamp_position(texts, b)))
});
if self.anchor_unit.is_none() {
self.granularity = Unit::Character;
}
self.remember(texts);
moved || self.bounds() != before
}
fn remember(&mut self, texts: &impl SelectionTexts) {
let key = |p: Option<TextPosition>| {
p.filter(|p| p.text < texts.len())
.map(|p| texts.key(p.text))
};
self.keys = [
key(self.anchor),
key(self.focus),
key(self.anchor_unit.map(|u| u.0)),
key(self.anchor_unit.map(|u| u.1)),
];
}
pub fn focus(&self) -> Option<TextPosition> {
self.focus
}
pub fn bounds(&self) -> Option<(TextPosition, TextPosition)> {
let (anchor, focus) = (self.anchor?, self.focus?);
Some((anchor.min(focus), anchor.max(focus)))
}
pub fn ranges(&self, texts: &impl SelectionTexts) -> Vec<(usize, Range<u32>)> {
let Some((start, end)) = self.bounds() else {
return Vec::new();
};
if texts.is_empty() || start == end {
return Vec::new();
}
let last = end.text.min(texts.len() - 1);
(start.text..=last)
.filter_map(|i| {
let len = utf16_len(texts.content(i));
let from = if i == start.text {
start.offset.min(len)
} else {
0
};
let to = if i == end.text {
end.offset.min(len)
} else {
len
};
(from < to).then_some((i, from..to))
})
.collect()
}
pub fn text(&self, texts: &impl SelectionTexts) -> String {
let rows = self.rows(texts, |i, range, marker| {
let mut part = String::new();
if let Some(marker) = marker {
part.push_str(marker);
part.push(' ');
}
part.push_str(&texts.copied(i, range));
part
});
let mut out = String::new();
for (n, (gap, cells)) in rows.iter().enumerate() {
if n > 0 {
out.push('\n');
if block_break(&rows, n, *gap) {
out.push('\n');
}
}
out.push_str(&cells.join("\t"));
}
out
}
#[doc(hidden)]
pub fn html(&self, texts: &impl SelectionTexts) -> Option<String> {
let mut formatted = false;
let rows = self.rows(texts, |i, range, marker| {
let mut part = String::new();
if let Some(marker) = marker {
escape_html(&mut part, marker);
part.push(' ');
}
match texts.attributed(i) {
Some(text) => {
let (html, styled) = text.copied_html(range);
formatted |= styled;
part.push_str(&html);
}
None => escape_html(&mut part, &texts.copied(i, range)),
}
part
});
if !formatted {
return None;
}
let mut out = String::from("<meta charset=\"utf-8\"><p>");
for (n, (gap, cells)) in rows.iter().enumerate() {
if n > 0 {
out.push_str(if block_break(&rows, n, *gap) {
"</p><p>"
} else {
"<br>"
});
}
out.push_str(&cells.join("\t"));
}
out.push_str("</p>");
Some(out)
}
fn rows(
&self,
texts: &impl SelectionTexts,
mut part: impl FnMut(usize, Range<u32>, Option<&str>) -> String,
) -> Vec<(bool, Vec<String>)> {
let mut rows: Vec<(bool, Vec<String>)> = Vec::new();
let mut previous: Option<(usize, Bounds<Points>)> = None;
let ranges = self.ranges(texts);
let (Some(&(first, _)), Some(&(last, _))) = (ranges.first(), ranges.last()) else {
return rows;
};
let mut ranges = ranges.into_iter().peekable();
for i in first..=last {
let range = match ranges.next_if(|&(at, _)| at == i) {
Some((_, range)) => range,
None if texts.content(i).is_empty() => 0..0,
None => continue,
};
let frame = texts.frame(i);
let marker = if range.start == 0 && !range.is_empty() {
texts.marker(i)
} else {
None
};
let part = part(i, range, marker);
match previous {
Some((before, _)) if before + 1 == i && continues(texts, i) => {
if let Some(cell) = rows.last_mut().and_then(|r| r.1.last_mut()) {
cell.push_str(&part);
}
}
Some((_, previous))
if previous.top() < frame.bottom() && frame.top() < previous.bottom() =>
{
if let Some(row) = rows.last_mut() {
row.1.push(part);
}
}
Some((_, previous)) => {
rows.push((frame.top() - previous.bottom() >= BLOCK_BREAK, vec![part]))
}
None => rows.push((false, vec![part])),
}
previous = Some((i, frame));
}
rows
}
pub fn selected_bounds(&self, texts: &impl SelectionTexts) -> Option<Bounds<Points>> {
self.ranges(texts)
.into_iter()
.filter_map(|(i, range)| texts.range_bounds(i, range))
.reduce(|a, b| a.union(&b))
}
pub fn start_offset(&self, texts: &impl SelectionTexts) -> u32 {
self.bounds()
.map_or(0, |(start, _)| copy_offset(texts, start))
}
pub fn ends(&self, texts: &impl SelectionTexts) -> Option<[(u64, u32); 2]> {
if self.is_empty() {
return None;
}
let (anchor, focus) = (self.anchor?, self.focus?);
(anchor.text < texts.len() && focus.text < texts.len()).then(|| {
[
(texts.key(anchor.text), anchor.offset),
(texts.key(focus.text), focus.offset),
]
})
}
fn select_unit(&mut self, texts: &impl SelectionTexts, pos: TextPosition, granularity: Unit) {
self.granularity = granularity;
if granularity == Unit::Character {
self.anchor = Some(pos);
self.focus = Some(pos);
self.anchor_unit = None;
} else {
let unit = unit_at(texts, pos, granularity);
self.anchor = Some(unit.0);
self.focus = Some(unit.1);
self.anchor_unit = Some(unit);
}
}
fn extend_to(&mut self, texts: &impl SelectionTexts, pos: TextPosition) {
let Some((unit_start, unit_end)) = self.anchor_unit else {
self.focus = Some(pos);
return;
};
let (start, end) = unit_at(texts, pos, self.granularity);
if pos < unit_start {
self.anchor = Some(unit_end);
self.focus = Some(start.min(unit_start));
} else {
self.anchor = Some(unit_start);
self.focus = Some(end.max(unit_end));
}
}
}
pub fn copy_offset(texts: &impl SelectionTexts, pos: TextPosition) -> u32 {
if texts.is_empty() || (pos.text == 0 && pos.offset == 0) {
return 0;
}
let copied = |to: TextPosition| {
let before = SelectionModel {
anchor: Some(TextPosition { text: 0, offset: 0 }),
focus: Some(to),
..SelectionModel::default()
};
utf16_len(&before.text(texts))
};
if pos.offset > 0 || pos.text >= texts.len() {
return copied(pos);
}
let end = utf16_len(texts.content(pos.text));
if end > 0 {
let own = SelectionModel {
anchor: Some(pos),
focus: Some(TextPosition::new(pos.text, end)),
..SelectionModel::default()
};
return copied(TextPosition::new(pos.text, end)) - utf16_len(&own.text(texts));
}
match copied(pos) {
0 => 0,
len => len + 1,
}
}
#[doc(hidden)]
pub const END_FIELDS: [(&str, &str); 2] = [
("anchorNode", "anchorNodeOffset"),
("focusNode", "focusNodeOffset"),
];
#[doc(hidden)]
pub fn end_fields(ends: [(u64, u32); 2]) -> [(&'static str, crate::PayloadValue); 4] {
let number = |n: u64| crate::PayloadValue::Number(n as f64);
let [(anchor, anchor_offset), (focus, focus_offset)] = END_FIELDS;
let [(a, a_at), (f, f_at)] = ends;
[
(anchor, number(a)),
(anchor_offset, number(u64::from(a_at))),
(focus, number(f)),
(focus_offset, number(u64::from(f_at))),
]
}
#[doc(hidden)]
pub const ITEM_FIELDS: [(&str, &str); 2] =
[("anchorKey", "anchorOffset"), ("focusKey", "focusOffset")];
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ListItemKey {
Named(String),
NotMine,
Failed,
}
const OBJECT_REPLACEMENT: char = '\u{FFFC}';
pub trait TextTree {
type View: Clone;
fn hidden(&self, view: &Self::View) -> bool;
fn text(&self, view: &Self::View) -> Option<(Arc<AttributedText>, Bounds<Points>)>;
fn children(&self, view: &Self::View, out: &mut Vec<(Self::View, Bounds<Points>)>);
fn content_offset(&self, view: &Self::View) -> (Point<Points>, f32) {
let _ = view;
(Point::default(), 1.0)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ListedText<V> {
pub view: V,
pub text: Arc<AttributedText>,
pub origin: Point<Points>,
pub zoom: f32,
pub frame: Bounds<Points>,
pub marker: Option<String>,
}
pub fn list_texts<T: TextTree>(tree: &T, root: &T::View) -> Vec<ListedText<T::View>> {
fn walk<T: TextTree>(
tree: &T,
view: &T::View,
origin: Point<Points>,
zoom: f32,
out: &mut Vec<ListedText<T::View>>,
chrome: &mut Option<(String, Bounds<Points>)>,
) {
if tree.hidden(view) {
return;
}
if let Some((text, content)) = tree.text(view) {
let frame = Bounds::new(
point(
origin.x + content.origin.x * zoom,
origin.y + content.origin.y * zoom,
),
size(content.size.width * zoom, content.size.height * zoom),
);
if text.selectable == Some(false) {
*chrome = Some((text.text.clone(), frame));
} else {
let marker = marker_of(chrome.take().as_ref(), frame);
out.push(ListedText {
view: view.clone(),
text,
origin,
zoom,
frame,
marker,
});
}
}
let (offset, own_zoom) = tree.content_offset(view);
let inner = zoom * own_zoom;
let mut children = Vec::new();
tree.children(view, &mut children);
let start = out.len();
let mut runs = Vec::with_capacity(children.len());
for (child, frame) in children {
let at = point(
origin.x + (frame.origin.x - offset.x) * inner,
origin.y + (frame.origin.y - offset.y) * inner,
);
let from = out.len();
walk(tree, &child, at, inner, out, chrome);
runs.push((frame, from..out.len()));
}
if let Some(order) = reading_order(&runs) {
reorder(out, start, &order);
}
}
let mut out = Vec::new();
walk(tree, root, Point::default(), 1.0, &mut out, &mut None);
out
}
pub fn reading_order(runs: &[(Bounds<Points>, Range<usize>)]) -> Option<Vec<usize>> {
let runs: Vec<_> = runs.iter().filter(|(_, r)| !r.is_empty()).collect();
let stacked = runs.iter().enumerate().all(|(i, (a, _))| {
runs[i + 1..]
.iter()
.all(|(b, _)| a.bottom() <= b.top() || b.bottom() <= a.top())
});
let mut order: Vec<usize> = (0..runs.len()).collect();
if stacked {
order.sort_by(|&a, &b| {
runs[a]
.0
.top()
.partial_cmp(&runs[b].0.top())
.unwrap_or(std::cmp::Ordering::Equal)
});
}
if order.iter().enumerate().all(|(i, &o)| i == o) {
return None;
}
Some(order.into_iter().flat_map(|i| runs[i].1.clone()).collect())
}
pub fn reorder<T>(items: &mut Vec<T>, start: usize, order: &[usize]) {
let mut taken: Vec<Option<T>> = items.drain(start..).map(Some).collect();
items.extend(order.iter().filter_map(|&i| taken[i - start].take()));
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct KeptRows(Vec<u64>);
impl KeptRows {
pub fn changed(&mut self, model: &SelectionModel) -> Option<Vec<u64>> {
let mut keys: Vec<u64> = if model.anchor.is_some() {
model.keys.iter().flatten().copied().collect()
} else {
Vec::new()
};
keys.sort_unstable();
keys.dedup();
(keys != self.0).then(|| {
self.0 = keys.clone();
keys
})
}
pub fn release(&mut self) -> Option<Vec<u64>> {
(!self.0.is_empty()).then(|| {
self.0.clear();
Vec::new()
})
}
}
pub fn autoscroll_step(at: Points, extent: Points) -> Points {
let into = if at < AUTOSCROLL_INSIDE {
at - AUTOSCROLL_INSIDE
} else if at > extent - AUTOSCROLL_INSIDE {
at - (extent - AUTOSCROLL_INSIDE)
} else {
return Points(0.0);
};
let t = (into.0.abs() / AUTOSCROLL_RAMP.0).min(1.0);
Points(into.0.signum() * (AUTOSCROLL_MIN.0 + t * (AUTOSCROLL_MAX.0 - AUTOSCROLL_MIN.0)))
}
pub const AUTOSCROLL_INSIDE: Points = Points(16.0);
pub const AUTOSCROLL_MIN: Points = Points(12.0);
pub const AUTOSCROLL_MAX: Points = Points(64.0);
pub const AUTOSCROLL_RAMP: Points = Points(96.0);
const LINE_SLACK: Points = Points(2.0);
fn hit(texts: &impl SelectionTexts, point: Point<Points>) -> Option<TextPosition> {
let count = texts.len();
if count == 0 {
return None;
}
let at = |i: usize| {
let frame = texts.frame(i);
let clamped = Point::new(
point.x.clamp(frame.left(), frame.right().max(frame.left())),
point.y.clamp(frame.top(), frame.bottom().max(frame.top())),
);
clamp_position(texts, TextPosition::new(i, texts.offset_at(i, clamped)))
};
let end_of = |i: usize| TextPosition::new(i, utf16_len(texts.content(i)));
let start_of = |i: usize| TextPosition::new(i, 0);
let h_dist = |frame: Bounds<Points>| {
if point.x < frame.left() {
frame.left() - point.x
} else if point.x > frame.right() {
point.x - frame.right()
} else {
Points::ZERO
}
};
let v_dist = |frame: Bounds<Points>| {
if point.y < frame.top() {
frame.top() - point.y
} else if point.y > frame.bottom() {
point.y - frame.bottom()
} else {
Points::ZERO
}
};
let h_overlaps =
|a: Bounds<Points>, b: Bounds<Points>| a.left() < b.right() && b.left() < a.right();
if let Some(i) = (0..count).rfind(|&i| texts.frame(i).contains(&point)) {
return Some(at(i));
}
let mut col_above: Option<(usize, Points)> = None;
let mut col_below: Option<(usize, Points)> = None;
let mut any_covering_x = false;
for i in 0..count {
let frame = texts.frame(i);
if h_dist(frame) != Points::ZERO {
continue;
}
any_covering_x = true;
if frame.bottom() <= point.y {
let d = point.y - frame.bottom();
if col_above.is_none_or(|(_, best)| d <= best) {
col_above = Some((i, d));
}
}
if frame.top() > point.y {
let d = frame.top() - point.y;
if col_below.is_none_or(|(_, best)| d < best) {
col_below = Some((i, d));
}
}
}
let nearest_in_column = |anchor: Bounds<Points>, above: bool, base: Option<(usize, Points)>| {
let mut best = base;
for i in 0..count {
let frame = texts.frame(i);
if !h_overlaps(frame, anchor) {
continue;
}
if above && frame.bottom() <= point.y {
let d = point.y - frame.bottom();
if best.is_none_or(|(bi, b)| {
d < b || (d == b && h_dist(frame) <= h_dist(texts.frame(bi)))
}) {
best = Some((i, d));
}
} else if !above && frame.top() > point.y {
let d = frame.top() - point.y;
if best.is_none_or(|(bi, b)| {
d < b || (d == b && h_dist(frame) < h_dist(texts.frame(bi)))
}) {
best = Some((i, d));
}
}
}
best
};
let refine_covering = |anchor_idx: usize,
other_idx: Option<usize>,
above: bool,
base: Option<(usize, Points)>| {
let anchor = texts.frame(anchor_idx);
let restrict = other_idx
.map(|o| texts.frame(o))
.filter(|o| o.size.width < anchor.size.width && h_overlaps(*o, anchor));
let sub_anchor = (0..count)
.filter(|&i| {
let frame = texts.frame(i);
if frame.size.width <= Points::ZERO || !h_overlaps(frame, anchor) {
return false;
}
if let Some(r) = restrict
&& !h_overlaps(frame, r)
{
return false;
}
if above {
frame.bottom() <= point.y
&& base.is_none_or(|(_, b)| point.y - frame.bottom() < b)
} else {
frame.top() > point.y && base.is_none_or(|(_, b)| frame.top() - point.y < b)
}
})
.min_by(|&a, &b| {
let (fa, fb) = (texts.frame(a), texts.frame(b));
h_dist(fa)
.partial_cmp(&h_dist(fb))
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| {
v_dist(fa)
.partial_cmp(&v_dist(fb))
.unwrap_or(std::cmp::Ordering::Equal)
})
.then_with(|| if above { b.cmp(&a) } else { a.cmp(&b) })
});
match sub_anchor {
Some(sub) => nearest_in_column(texts.frame(sub), above, base),
None => base,
}
};
if any_covering_x {
let (orig_above, orig_below) = (col_above, col_below);
if let Some((a, _)) = orig_above {
col_above = refine_covering(a, orig_below.map(|(b, _)| b), true, orig_above);
}
if let Some((b, _)) = orig_below {
col_below = refine_covering(b, col_above.map(|(a, _)| a), false, orig_below);
} else if let Some((a, _)) = col_above {
col_below = refine_covering(a, None, false, None);
}
if orig_above.is_none()
&& let Some((b, _)) = col_below
{
col_above = refine_covering(b, None, true, None);
}
} else if let Some(anchor) = (0..count)
.filter(|&i| texts.frame(i).size.width > Points::ZERO)
.min_by(|&a, &b| {
let (fa, fb) = (texts.frame(a), texts.frame(b));
h_dist(fa)
.partial_cmp(&h_dist(fb))
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| {
v_dist(fa)
.partial_cmp(&v_dist(fb))
.unwrap_or(std::cmp::Ordering::Equal)
})
})
{
let anchor_frame = texts.frame(anchor);
col_above = nearest_in_column(anchor_frame, true, None);
col_below = nearest_in_column(anchor_frame, false, None);
}
let mut nearest: Option<(usize, Points)> = None;
let mut row_bottom = Points::ZERO;
for i in 0..count {
let frame = texts.frame(i);
if point.y >= frame.top() && point.y < frame.bottom() {
row_bottom = row_bottom.max(frame.bottom());
let distance = h_dist(frame);
if nearest.is_none_or(|(_, best)| distance < best) {
nearest = Some((i, distance));
}
}
}
if let Some((i, row_h_dist)) = nearest {
let row_frame = texts.frame(i);
let tail_of_line_above = |a: usize| {
let af = texts.frame(a);
let line_above = (0..count)
.map(|q| texts.frame(q))
.filter(|qf| h_overlaps(*qf, row_frame) && qf.bottom() <= row_frame.top())
.map(|qf| qf.bottom())
.reduce(Points::max);
line_above.is_some_and(|bottom| {
(0..count).any(|p| {
let pf = texts.frame(p);
p != a
&& pf.bottom() == bottom
&& h_overlaps(pf, row_frame)
&& af.top() >= pf.top() - LINE_SLACK
&& af.bottom() <= pf.bottom() + LINE_SLACK
})
})
};
if let Some((a, to_above)) = col_above
&& !h_overlaps(texts.frame(a), row_frame)
&& h_dist(texts.frame(a)) < row_h_dist
&& !tail_of_line_above(a)
{
return Some(match col_below {
Some((b, to_below))
if to_below < to_above
&& h_dist(texts.frame(b)) < row_h_dist
&& texts.frame(b).top() < row_bottom =>
{
start_of(b)
}
_ => end_of(a),
});
}
return Some(at(i));
}
if (0..count).all(|i| texts.frame(i).bottom() > point.y) {
return Some(start_of(0));
}
let below_all = (0..count).all(|i| texts.frame(i).bottom() <= point.y);
if below_all && !any_covering_x {
return Some(end_of(count - 1));
}
let v_overlaps =
|a: Bounds<Points>, b: Bounds<Points>| a.top() < b.bottom() && b.top() < a.bottom();
match (col_above, col_below) {
(Some((a, to_above)), Some((b, to_below))) => {
return Some(if to_above <= to_below {
end_of(a)
} else {
start_of(b)
});
}
(Some((a, _)), None) => {
let target = if below_all {
let af = texts.frame(a);
(a..count)
.rev()
.find(|&i| v_overlaps(texts.frame(i), af))
.unwrap_or(a)
} else {
a
};
return Some(end_of(target));
}
(None, Some((b, _))) => return Some(start_of(b)),
(None, None) => {}
}
let above = (0..count)
.rev()
.find(|&i| texts.frame(i).bottom() <= point.y);
let below = (0..count).find(|&i| texts.frame(i).top() > point.y);
Some(match (above, below) {
(Some(a), Some(b)) => {
let to_above = point.y - texts.frame(a).bottom();
let to_below = texts.frame(b).top() - point.y;
if to_above <= to_below {
end_of(a)
} else {
start_of(b)
}
}
(Some(a), None) => end_of(a),
(None, Some(b)) => start_of(b),
(None, None) => end_of(count - 1),
})
}
fn unit_at(
texts: &impl SelectionTexts,
pos: TextPosition,
granularity: Unit,
) -> (TextPosition, TextPosition) {
let content = texts.content(pos.text);
match granularity {
Unit::Character => (pos, pos),
Unit::Word | Unit::Token => {
let (first, last) = line_of(texts, pos.text);
let mut line = String::new();
let mut starts = Vec::with_capacity(last - first + 1);
for i in first..=last {
starts.push(utf16_len(&line));
line.push_str(texts.content(i));
}
let mut at = starts[pos.text - first] + pos.offset;
if pos.offset > 0 && pos.offset == utf16_len(content) {
let before = content.chars().next_back().map_or(0, char::len_utf16);
at -= before as u32;
}
let range = word_range(&line, at, granularity == Unit::Token);
if range.is_empty() {
return (pos, pos);
}
let start_text = starts.partition_point(|&s| s <= range.start) - 1;
let end_text = starts.partition_point(|&s| s < range.end) - 1;
(
TextPosition::new(first + start_text, range.start - starts[start_text]),
TextPosition::new(first + end_text, range.end - starts[end_text]),
)
}
Unit::Paragraph => {
let (first, last) = line_of(texts, pos.text);
(
TextPosition::new(first, 0),
TextPosition::new(last, utf16_len(texts.content(last))),
)
}
}
}
pub const BLOCK_BREAK: Points = Points(8.0);
pub fn marker_of(
chrome: Option<&(String, Bounds<Points>)>,
frame: Bounds<Points>,
) -> Option<String> {
let (text, at) = chrome?;
let text = text.trim();
let short = !text.is_empty() && text.chars().count() <= 4 && !text.contains('\n');
let beside = at.right() <= frame.left() + Points(1.0)
&& at.top() < frame.top() + Points(24.0)
&& frame.top() < at.bottom();
(short && beside).then(|| text.to_string())
}
fn block_break(rows: &[(bool, Vec<String>)], n: usize, gap: bool) -> bool {
gap && rows[n].1.len() == 1 && rows[n - 1].1.len() == 1
}
fn continues(texts: &impl SelectionTexts, i: usize) -> bool {
i > 0 && i < texts.len() && texts.continues(i)
}
fn line_of(texts: &impl SelectionTexts, i: usize) -> (usize, usize) {
let mut first = i;
while continues(texts, first) {
first -= 1;
}
let mut last = i;
while last + 1 < texts.len() && continues(texts, last + 1) {
last += 1;
}
(first, last)
}
fn caret_stops(text: &str) -> Vec<u32> {
let mut stops = vec![0];
let mut at = 0u32;
let mut previous: Option<char> = None;
let mut flags = 0;
for c in text.chars() {
let regional = matches!(c, '\u{1F1E6}'..='\u{1F1FF}');
let joins = at > 0
&& (is_combining_mark(c)
|| previous == Some('\u{200D}')
|| matches!(c,
'\u{FE00}'..='\u{FE0F}'
| '\u{1F3FB}'..='\u{1F3FF}'
| '\u{E0020}'..='\u{E007F}'
| '\u{E0100}'..='\u{E01EF}')
|| (regional && flags == 1)
|| (c == '\n' && previous == Some('\r')));
if !joins && at > 0 {
stops.push(at);
flags = 0;
}
if regional {
flags += 1;
}
at += c.len_utf16() as u32;
previous = Some(c);
}
if at > 0 {
stops.push(at);
}
stops
}
fn step(texts: &impl SelectionTexts, pos: TextPosition, forward: bool) -> TextPosition {
let stops = caret_stops(texts.content(pos.text));
let len = stops.last().copied().unwrap_or(0);
if forward {
if pos.offset < len {
let next = stops.iter().copied().find(|&s| s > pos.offset);
return TextPosition::new(pos.text, next.unwrap_or(len));
}
if pos.text + 1 >= texts.len() {
return pos;
}
let next = TextPosition::new(pos.text + 1, 0);
if continues(texts, next.text) {
step(texts, next, true)
} else {
next
}
} else {
if pos.offset > 0 {
let before = stops.iter().copied().rev().find(|&s| s < pos.offset);
return TextPosition::new(pos.text, before.unwrap_or(0));
}
if pos.text == 0 {
return pos;
}
let end = TextPosition::new(pos.text - 1, utf16_len(texts.content(pos.text - 1)));
if continues(texts, pos.text) {
step(texts, end, false)
} else {
end
}
}
}
fn char_beside(
texts: &impl SelectionTexts,
pos: TextPosition,
forward: bool,
) -> Option<(char, TextPosition)> {
let content = texts.content(pos.text);
let len = utf16_len(content);
let inside = if forward {
pos.offset < len
} else {
pos.offset > 0
};
if inside {
let at = byte_offset(content, pos.offset);
let c = if forward {
content[at..].chars().next()
} else {
content[..at].chars().next_back()
}?;
let width = c.len_utf16() as u32;
let offset = if forward {
pos.offset + width
} else {
pos.offset - width
};
return Some((c, TextPosition::new(pos.text, offset)));
}
let to = if forward {
(pos.text + 1 < texts.len()).then(|| TextPosition::new(pos.text + 1, 0))?
} else {
let i = pos.text.checked_sub(1)?;
TextPosition::new(i, utf16_len(texts.content(i)))
};
let joined = continues(texts, if forward { to.text } else { pos.text });
if joined {
char_beside(texts, to, forward)
} else {
Some(('\n', to))
}
}
fn word_step(texts: &impl SelectionTexts, pos: TextPosition, forward: bool) -> TextPosition {
let is_word = |c: char| CharKind::of(c) == CharKind::Word;
let mut at = pos;
while let Some((c, next)) = char_beside(texts, at, forward) {
if is_word(c) || is_spaceless_script(c) {
break;
}
at = next;
}
if let Some((c, next)) = char_beside(texts, at, forward)
&& is_spaceless_script(c)
{
return next;
}
while let Some((c, next)) = char_beside(texts, at, forward) {
if !is_word(c) {
break;
}
at = next;
}
at
}
fn caret(texts: &impl SelectionTexts, pos: TextPosition, upstream: bool) -> Bounds<Points> {
let content = texts.content(pos.text);
let stops = caret_stops(content);
let at = byte_offset(content, pos.offset);
let breaks =
|c: Option<char>| c.is_some_and(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'));
let before = stops
.iter()
.copied()
.rev()
.find(|&s| s < pos.offset)
.filter(|_| !breaks(content[..at].chars().next_back()))
.and_then(|s| texts.range_bounds(pos.text, s..pos.offset))
.map(|b| (b.right(), b));
let after = stops
.iter()
.copied()
.find(|&s| s > pos.offset)
.filter(|_| !breaks(content[at..].chars().next()))
.and_then(|s| texts.range_bounds(pos.text, pos.offset..s))
.map(|b| (b.left(), b));
let edge = if upstream {
before.or(after)
} else {
after.or(before)
};
match edge {
Some((x, b)) => Bounds::new(point(x, b.top()), size(Points(0.0), b.size.height)),
None => {
let frame = texts.frame(pos.text);
Bounds::new(frame.origin, size(Points(0.0), frame.size.height))
}
}
}
fn line_step(
texts: &impl SelectionTexts,
pos: TextPosition,
caret: Bounds<Points>,
x: f32,
forward: bool,
) -> TextPosition {
let half = caret.size.height.0 / 2.0;
let frame = texts.frame(pos.text);
let in_text = |i: usize, y: f32| {
let frame = texts.frame(i);
let x = x.clamp(frame.left().0, frame.right().0.max(frame.left().0));
let y = y.clamp(frame.top().0, frame.bottom().0.max(frame.top().0));
TextPosition::new(i, texts.offset_at(i, point(Points(x), Points(y))))
};
const SLACK: f32 = 0.5;
if forward {
let y = caret.bottom().0 + half;
if y < frame.bottom().0 {
return in_text(pos.text, y);
}
let below = (pos.text + 1..texts.len())
.find(|&i| texts.frame(i).top().0 >= caret.bottom().0 - SLACK);
match below {
Some(i) => {
let top = texts.frame(i).top().0;
in_text(i, top + half.min(texts.frame(i).size.height.0 / 2.0))
}
None => document_edge(texts, true),
}
} else {
let y = caret.top().0 - half;
if y > frame.top().0 {
return in_text(pos.text, y);
}
let above = (0..pos.text)
.rev()
.find(|&i| texts.frame(i).bottom().0 <= caret.top().0 + SLACK);
match above {
Some(i) => {
let bottom = texts.frame(i).bottom().0;
in_text(i, bottom - half.min(texts.frame(i).size.height.0 / 2.0))
}
None => document_edge(texts, false),
}
}
}
fn line_edge(
texts: &impl SelectionTexts,
pos: TextPosition,
caret: Bounds<Points>,
forward: bool,
) -> TextPosition {
let frame = texts.frame(pos.text);
let x = if forward { frame.right() } else { frame.left() };
let y = caret.top() + caret.size.height * 0.5;
TextPosition::new(pos.text, texts.offset_at(pos.text, point(x, y)))
}
fn paragraph_step(texts: &impl SelectionTexts, pos: TextPosition, forward: bool) -> TextPosition {
let (first, last) = line_of(texts, pos.text);
if forward {
let end = TextPosition::new(last, utf16_len(texts.content(last)));
if pos < end || last + 1 >= texts.len() {
return end;
}
let (_, next) = line_of(texts, last + 1);
TextPosition::new(next, utf16_len(texts.content(next)))
} else {
let start = TextPosition::new(first, 0);
if pos > start || first == 0 {
return start;
}
let (previous, _) = line_of(texts, first - 1);
TextPosition::new(previous, 0)
}
}
fn document_edge(texts: &impl SelectionTexts, forward: bool) -> TextPosition {
if forward && !texts.is_empty() {
let last = texts.len() - 1;
TextPosition::new(last, utf16_len(texts.content(last)))
} else {
TextPosition::new(0, 0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CharKind {
Word,
Space,
Single,
}
impl CharKind {
fn of(c: char) -> Self {
if c == '\n' || c == '\r' || c == '\u{2028}' || c == '\u{2029}' {
CharKind::Single
} else if c.is_whitespace() {
CharKind::Space
} else if is_spaceless_script(c) {
CharKind::Single
} else if c.is_alphanumeric() || c == '_' || is_combining_mark(c) {
CharKind::Word
} else {
CharKind::Single
}
}
}
fn is_spaceless_script(c: char) -> bool {
matches!(c,
'\u{3040}'..='\u{30FF}' | '\u{31F0}'..='\u{31FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{FF66}'..='\u{FF9F}' | '\u{20000}'..='\u{3FFFF}' )
}
fn is_combining_mark(c: char) -> bool {
matches!(c,
'\u{0300}'..='\u{036F}'
| '\u{1AB0}'..='\u{1AFF}'
| '\u{1DC0}'..='\u{1DFF}'
| '\u{20D0}'..='\u{20FF}'
| '\u{FE20}'..='\u{FE2F}'
| '\u{200D}' | '\u{FE0F}' )
}
fn word_range(text: &str, offset: u32, tokens: bool) -> Range<u32> {
let chars: Vec<(u32, char)> = text
.chars()
.scan(0u32, |at, c| {
let start = *at;
*at += c.len_utf16() as u32;
Some((start, c))
})
.collect();
let len = utf16_len(text);
let offset = snap(text, offset.min(len));
let after = chars.partition_point(|&(start, _)| start < offset);
let is_break = |i: usize| matches!(chars.get(i), Some((_, '\n' | '\r')) | None);
let index = if is_break(after) {
match after.checked_sub(1) {
Some(before) if !is_break(before) => before,
_ => return offset..offset,
}
} else {
after
};
if let Some((first, last)) = tokens.then(|| token_at(&chars, index)).flatten() {
let end = chars[last].0 + chars[last].1.len_utf16() as u32;
return chars[first].0..end;
}
let kind = CharKind::of(chars[index].1);
let (mut first, mut last) = (index, index);
if kind != CharKind::Single {
while first > 0 && CharKind::of(chars[first - 1].1) == kind {
first -= 1;
}
while last + 1 < chars.len() && CharKind::of(chars[last + 1].1) == kind {
last += 1;
}
}
let end = chars[last].0 + chars[last].1.len_utf16() as u32;
chars[first].0..end
}
fn is_joiner(c: char, query: bool) -> bool {
matches!(c, '-' | '.' | '/' | ':' | '@' | '~' | '%') || (query && is_query(c))
}
fn is_query(c: char) -> bool {
matches!(c, '?' | '=' | '&' | '#')
}
fn is_leading(c: char) -> bool {
matches!(c, '/' | '~' | '.' | '-' | '@')
}
fn token_at(chars: &[(u32, char)], index: usize) -> Option<(usize, usize)> {
let (first, last) = grow_token(chars, index, true)?;
match (first..=last).find(|&i| is_query(chars[i].1)) {
Some(q) if !(first..q).any(|i| chars[i].1 == '/') => grow_token(chars, index, false),
_ => Some((first, last)),
}
}
fn grow_token(chars: &[(u32, char)], index: usize, query: bool) -> Option<(usize, usize)> {
let word = |i: usize| CharKind::of(chars[i].1) == CharKind::Word;
let joiner = |i: usize| is_joiner(chars[i].1, query);
let n = chars.len();
let core = if word(index) {
index
} else if joiner(index) {
let (mut a, mut b) = (index, index);
while a > 0 && joiner(a - 1) {
a -= 1;
}
while b + 1 < n && joiner(b + 1) {
b += 1;
}
let before = a > 0 && word(a - 1);
let after = b + 1 < n && word(b + 1);
if before && after {
a - 1
} else if after && !before && (a..=b).all(|i| is_leading(chars[i].1)) {
b + 1
} else {
return None;
}
} else {
return None;
};
let (mut first, mut last) = (core, core);
loop {
while last + 1 < n && word(last + 1) {
last += 1;
}
let mut j = last + 1;
while j < n && joiner(j) {
j += 1;
}
if j > last + 1 && j < n && word(j) {
last = j;
} else {
break;
}
}
loop {
while first > 0 && word(first - 1) {
first -= 1;
}
let mut j = first;
while j > 0 && joiner(j - 1) {
j -= 1;
}
if j < first && j > 0 && word(j - 1) {
first = j - 1;
} else {
break;
}
}
while first > 0 && is_leading(chars[first - 1].1) {
first -= 1;
}
if last + 1 < n && chars[last + 1].1 == '/' {
last += 1;
}
Some((first, last))
}
fn utf16_len(text: &str) -> u32 {
text.chars().map(|c| c.len_utf16() as u32).sum()
}
fn byte_offset(text: &str, offset: u32) -> usize {
let mut at = 0u32;
for (byte, c) in text.char_indices() {
let next = at + c.len_utf16() as u32;
if next > offset {
return byte;
}
at = next;
}
text.len()
}
fn snap(text: &str, offset: u32) -> u32 {
let mut at = 0u32;
for c in text.chars() {
let next = at + c.len_utf16() as u32;
if next > offset {
return at;
}
at = next;
}
at
}
fn clamp_position(texts: &impl SelectionTexts, pos: TextPosition) -> TextPosition {
TextPosition::new(pos.text, snap(texts.content(pos.text), pos.offset))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::{bounds, point, px, size};
struct Fake(Vec<(String, Bounds<Points>)>);
type Frame = (f32, f32, f32, f32);
impl Fake {
fn new(texts: &[(&str, Frame)]) -> Self {
Fake(
texts
.iter()
.map(|&(text, (x, y, w, h))| {
(
text.to_string(),
bounds(point(px(x), px(y)), size(px(w), px(h))),
)
})
.collect(),
)
}
}
impl SelectionTexts for Fake {
fn len(&self) -> usize {
self.0.len()
}
fn content(&self, i: usize) -> &str {
&self.0[i].0
}
fn frame(&self, i: usize) -> Bounds<Points> {
self.0[i].1
}
fn offset_at(&self, i: usize, point: Point<Points>) -> u32 {
let (text, frame) = &self.0[i];
let lines: Vec<&str> = text.split('\n').collect();
let line =
(((point.y - frame.top()).0 / 20.0).floor().max(0.0) as usize).min(lines.len() - 1);
let column = ((point.x - frame.left()).0 / 8.0).round().max(0.0) as usize;
let before: u32 = lines[..line].iter().map(|l| utf16_len(l) + 1).sum();
let within: u32 = lines[line]
.chars()
.take(column)
.map(|c| c.len_utf16() as u32)
.sum();
before + within
}
fn range_bounds(&self, i: usize, range: Range<u32>) -> Option<Bounds<Points>> {
let (text, frame) = &self.0[i];
let place = |offset: u32| {
let before = &text[..offset as usize];
let line = before.matches('\n').count();
let column = before.len() - before.rfind('\n').map_or(0, |n| n + 1);
(line as f32, column as f32)
};
let ((l0, c0), (l1, c1)) = (place(range.start), place(range.end));
let (left, width) = if l0 == l1 {
(c0 * 8.0, (c1 - c0) * 8.0)
} else {
(0.0, frame.size.width.0)
};
Some(bounds(
point(frame.left() + px(left), frame.top() + px(l0 * 20.0)),
size(px(width), px((l1 - l0 + 1.0) * 20.0)),
))
}
}
#[test]
fn explicit_ranges_snap_utf16_and_clear_missing_texts() {
let texts = Fake::new(&[("前😀日本", (0.0, 0.0, 100.0, 20.0))]);
let mut model = SelectionModel::new();
assert!(model.select_range(&texts, TextPosition::new(0, 2), TextPosition::new(0, 99)));
assert!(!model.select_range(&texts, TextPosition::new(0, 1), TextPosition::new(0, 5)));
assert_eq!(model.text(&texts), "😀日本");
assert_eq!(model.start_offset(&texts), 1);
model.select_range(&texts, TextPosition::new(0, 3), TextPosition::new(0, 1));
assert_eq!(model.text(&texts), "😀");
assert!(model.select_range(&texts, TextPosition::new(1, 0), TextPosition::new(0, 1)));
assert!(model.is_empty());
}
fn column() -> Fake {
Fake::new(&[
("Hello world", (0.0, 0.0, 200.0, 20.0)),
("Second line\nmore text", (0.0, 40.0, 200.0, 40.0)),
("Last", (0.0, 100.0, 200.0, 20.0)),
])
}
fn at(x: f32, y: f32) -> Point<Points> {
point(px(x), px(y))
}
fn pos(text: usize, offset: u32) -> TextPosition {
TextPosition::new(text, offset)
}
#[test]
fn one_click_puts_the_anchor() {
let texts = column();
let mut model = SelectionModel::new();
assert!(model.is_empty());
assert!(model.press(&texts, at(17.0, 5.0), 1, false));
assert!(model.is_empty());
assert_eq!(model.bounds(), Some((pos(0, 2), pos(0, 2))));
assert!(model.ranges(&texts).is_empty());
assert_eq!(model.text(&texts), "");
}
#[test]
fn drags_forward_and_backward_across_texts() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(16.0, 5.0), 1, false);
assert!(model.drag(&texts, at(24.0, 105.0)));
assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 3))));
assert_eq!(
model.ranges(&texts),
vec![(0, 2..11), (1, 0..21), (2, 0..3)]
);
assert_eq!(
model.text(&texts),
"llo world\n\nSecond line\nmore text\n\nLas"
);
assert!(
!model.drag(&texts, at(24.0, 105.0)),
"the same point changes nothing"
);
let mut model = SelectionModel::new();
model.press(&texts, at(24.0, 105.0), 1, false);
model.drag(&texts, at(16.0, 5.0));
assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 3))));
assert_eq!(
model.ranges(&texts),
vec![(0, 2..11), (1, 0..21), (2, 0..3)]
);
}
#[test]
fn the_selected_bounds_unite_each_texts_part() {
let texts = column();
let mut model = SelectionModel::new();
assert_eq!(model.selected_bounds(&texts), None);
model.press(&texts, at(16.0, 5.0), 1, false);
assert_eq!(model.selected_bounds(&texts), None);
model.drag(&texts, at(40.0, 5.0));
assert_eq!(
model.selected_bounds(&texts),
Some(bounds(point(px(16.0), px(0.0)), size(px(24.0), px(20.0))))
);
model.drag(&texts, at(24.0, 105.0));
assert_eq!(
model.selected_bounds(&texts),
Some(bounds(point(px(0.0), px(0.0)), size(px(200.0), px(120.0))))
);
}
#[test]
fn drag_without_a_press_does_nothing() {
let texts = column();
let mut model = SelectionModel::new();
assert!(!model.drag(&texts, at(10.0, 10.0)));
assert_eq!(model.bounds(), None);
}
#[test]
fn between_rows_goes_to_the_nearer_edge() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(0.0, 5.0), 1, false);
model.drag(&texts, at(50.0, 25.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 11))));
model.drag(&texts, at(50.0, 35.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(1, 0))));
model.drag(&texts, at(50.0, 30.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 11))));
}
#[test]
fn above_and_below_all_texts() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(40.0, 105.0), 1, false);
model.drag(&texts, at(50.0, -10.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(2, 4))));
model.press(&texts, at(0.0, 5.0), 1, false);
model.drag(&texts, at(10.0, 500.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(2, 4))));
assert_eq!(
model.text(&texts),
"Hello world\n\nSecond line\nmore text\n\nLast"
);
}
#[test]
fn beside_a_text_on_its_row() {
let texts = Fake::new(&[
("left", (0.0, 0.0, 32.0, 20.0)),
("right", (100.0, 0.0, 40.0, 20.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(8.0, 5.0), 1, false);
model.drag(&texts, at(50.0, 5.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 4))));
model.drag(&texts, at(90.0, 5.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(1, 0))));
model.drag(&texts, at(300.0, 5.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(1, 5))));
assert_eq!(model.text(&texts), "eft\tright");
}
#[test]
fn double_click_selects_and_drags_by_words() {
let texts = column();
let mut model = SelectionModel::new();
assert!(model.press(&texts, at(56.0, 5.0), 2, false));
assert_eq!(model.bounds(), Some((pos(0, 6), pos(0, 11))));
assert_eq!(model.text(&texts), "world");
model.drag(&texts, at(9.0, 45.0));
assert_eq!(model.bounds(), Some((pos(0, 6), pos(1, 6))));
model.drag(&texts, at(8.0, 5.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 11))));
assert_eq!(model.text(&texts), "Hello world");
model.drag(&texts, at(64.0, 5.0));
assert_eq!(model.bounds(), Some((pos(0, 6), pos(0, 11))));
}
#[test]
fn double_click_at_a_line_end_selects_the_word_before() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(150.0, 45.0), 2, false);
assert_eq!(model.text(&texts), "line");
model.press(&texts, at(150.0, 5.0), 2, false);
assert_eq!(model.text(&texts), "world");
}
#[test]
fn triple_click_selects_and_drags_by_paragraphs() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(20.0, 65.0), 3, false);
assert_eq!(model.bounds(), Some((pos(1, 0), pos(1, 21))));
model.drag(&texts, at(8.0, 105.0));
assert_eq!(model.bounds(), Some((pos(1, 0), pos(2, 4))));
assert_eq!(model.text(&texts), "Second line\nmore text\n\nLast");
model.drag(&texts, at(8.0, 5.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(1, 21))));
}
#[test]
fn shift_click_extends_from_the_anchor() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(16.0, 5.0), 1, false);
assert!(model.press(&texts, at(24.0, 105.0), 1, true));
assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 3))));
model.press(&texts, at(8.0, 5.0), 1, true);
assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 2))));
model.press(&texts, at(56.0, 5.0), 2, false);
model.press(&texts, at(8.0, 105.0), 1, true);
assert_eq!(model.bounds(), Some((pos(0, 6), pos(2, 4))));
let mut model = SelectionModel::new();
model.press(&texts, at(16.0, 5.0), 1, true);
assert_eq!(model.bounds(), Some((pos(0, 2), pos(0, 2))));
}
#[test]
fn long_press_selects_a_word() {
let texts = column();
let mut model = SelectionModel::new();
assert!(model.select_word_at(&texts, at(10.0, 65.0)));
assert_eq!(model.text(&texts), "more");
}
#[test]
fn handles_move_their_end_and_swap_when_crossing() {
let texts = column();
let mut model = SelectionModel::new();
assert!(!model.move_handle(&texts, Handle::End, at(0.0, 0.0)));
assert!(model.select_all(&texts));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(2, 4))));
assert!(model.move_handle(&texts, Handle::End, at(16.0, 5.0)));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 2))));
assert!(model.move_handle(&texts, Handle::Start, at(8.0, 45.0)));
assert_eq!(model.bounds(), Some((pos(0, 2), pos(1, 1))));
assert_eq!(model.text(&texts), "llo world\n\nS");
assert!(model.move_handle(&texts, Handle::End, at(24.0, 5.0)));
assert_eq!(model.bounds(), Some((pos(0, 2), pos(0, 3))));
}
struct Rich(Vec<(AttributedText, Option<&'static str>)>, f32);
impl SelectionTexts for Rich {
fn len(&self) -> usize {
self.0.len()
}
fn content(&self, i: usize) -> &str {
&self.0[i].0.text
}
fn copied(&self, i: usize, range: Range<u32>) -> String {
self.0[i].0.copied_text(range)
}
fn attributed(&self, i: usize) -> Option<&AttributedText> {
Some(&self.0[i].0)
}
fn marker(&self, i: usize) -> Option<&str> {
self.0[i].1
}
fn frame(&self, i: usize) -> Bounds<Points> {
bounds(
point(px(0.0), px(i as f32 * (20.0 + self.1))),
size(px(400.0), px(20.0)),
)
}
fn offset_at(&self, _: usize, _: Point<Points>) -> u32 {
0
}
}
fn rich(parts: &[(&str, u16, bool, Option<&str>)]) -> AttributedText {
let mut t = AttributedText::default();
for &(s, weight, italic, href) in parts {
let start = t.len_utf16();
t.push(
s,
crate::ResolvedTextStyle {
font_weight: weight,
italic,
..Default::default()
},
);
if let Some(href) = href {
t.link_hrefs
.push(crate::text::LinkHref::new(t.links.len() as u32, href));
t.links.push(crate::text::TextLink {
start,
end: t.len_utf16(),
node: 0,
events: Default::default(),
focus_stop: true,
});
}
}
t
}
#[test]
fn html_keeps_bold_italic_and_links() {
let texts = Rich(
vec![
(rich(&[("Title", 700, false, None)]), None),
(
rich(&[
("See ", 400, false, None),
("the <docs>", 400, false, Some("https://x.y/?a=1&b=\"2\"")),
(" and ", 400, false, None),
("this", 600, true, None),
]),
None,
),
(rich(&[("one & two", 400, true, None)]), Some("\u{2022}")),
],
12.0,
);
let mut model = SelectionModel::new();
assert!(model.select_all(&texts));
assert_eq!(
model.text(&texts),
"Title\n\nSee the <docs> and this\n\n\u{2022} one & two"
);
assert_eq!(
model.html(&texts).as_deref(),
Some(
"<meta charset=\"utf-8\"><p><b>Title</b></p><p>See \
<a href=\"https://x.y/?a=1&b="2"\">the <docs></a> and \
<b><i>this</i></b></p><p>\u{2022} <i>one & two</i></p>"
)
);
}
#[test]
fn html_of_plain_text_is_none() {
let texts = Rich(
vec![
(rich(&[("one", 400, false, None)]), None),
(rich(&[("two\nthree", 400, false, None)]), None),
],
0.0,
);
let mut model = SelectionModel::new();
assert!(model.select_all(&texts));
assert_eq!(model.text(&texts), "one\ntwo\nthree");
assert_eq!(model.html(&texts), None);
let texts = Rich(
vec![
(rich(&[("one", 700, false, None)]), None),
(rich(&[("two\nthree", 400, false, None)]), None),
],
0.0,
);
assert_eq!(
model.html(&texts).as_deref(),
Some("<meta charset=\"utf-8\"><p><b>one</b><br>two<br>three</p>")
);
}
#[test]
fn copied_html_skips_hidden_runs_and_uses_copy_texts() {
let bold = crate::ResolvedTextStyle {
font_weight: 700,
..Default::default()
};
let mut t = AttributedText::default();
t.push("a", bold);
t.push("hidden", bold.hide());
t.copy_texts
.push(crate::AttachmentCopyText::new(t.len_utf16(), "$x<1$"));
t.push_attachment(crate::geometry::size_pt(8.0, 8.0), bold);
t.push_attachment(crate::geometry::size_pt(8.0, 8.0), bold);
let len = t.len_utf16();
assert_eq!(
t.copied_html(0..len),
("<b>a$x<1$</b>".to_string(), true)
);
assert_eq!(t.copied_html(1..7), (String::new(), false));
}
#[test]
fn select_all_and_clear() {
let texts = column();
let mut model = SelectionModel::new();
assert!(model.select_all(&texts));
assert!(!model.select_all(&texts));
assert_eq!(
model.ranges(&texts),
vec![(0, 0..11), (1, 0..21), (2, 0..4)]
);
assert!(model.clear());
assert!(!model.clear());
assert_eq!(model.bounds(), None);
let none = Fake(Vec::new());
assert!(!model.select_all(&none));
assert!(!model.press(&none, at(0.0, 0.0), 1, false));
}
#[test]
fn copies_rows_with_tabs_and_leaves_attachments_out() {
let texts = Fake::new(&[
("ab\u{FFFC}c", (0.0, 0.0, 80.0, 20.0)),
("de", (100.0, 5.0, 80.0, 20.0)),
("fg", (0.0, 40.0, 80.0, 20.0)),
("", (0.0, 60.0, 80.0, 20.0)),
("h", (0.0, 80.0, 80.0, 20.0)),
]);
let mut model = SelectionModel::new();
model.select_all(&texts);
assert_eq!(model.text(&texts), "abc\tde\nfg\n\nh");
assert_eq!(model.ranges(&texts).len(), 4, "the empty text has no range");
}
#[test]
fn never_splits_surrogate_pairs() {
let texts = Fake::new(&[("a😀b c", (0.0, 0.0, 200.0, 20.0))]);
let mut model = SelectionModel::new();
model.press(&texts, at(9.0, 5.0), 2, false);
assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 3))));
assert_eq!(model.text(&texts), "😀");
model.press(&texts, at(0.0, 5.0), 1, false);
model.drag(&texts, at(16.0, 5.0));
assert_eq!(model.text(&texts), "a😀");
assert_eq!(snap("a😀b", 2), 1);
assert_eq!(snap("a😀b", 3), 3);
assert_eq!(snap("a😀b", 9), 4);
assert_eq!(byte_offset("a😀b", 3), 5);
assert_eq!(word_range("a😀b", 2, false), 1..3);
}
#[test]
fn words_in_latin_and_cjk() {
let text = "中文abc 测试, café_1 x\n\nend";
let word = |offset| {
let range = word_range(text, offset, false);
let (from, to) = (byte_offset(text, range.start), byte_offset(text, range.end));
text[from..to].to_string()
};
assert_eq!(word(0), "中");
assert_eq!(word(1), "文");
assert_eq!(word(2), "abc");
assert_eq!(word(4), "abc");
assert_eq!(word(5), " ");
assert_eq!(word(6), "测");
assert_eq!(word(8), ",");
assert_eq!(word(10), "café_1");
assert_eq!(word(16), " ");
assert_eq!(word(19), "x");
assert_eq!(word(20), "");
assert_eq!(word(24), "end");
assert_eq!(word_range("", 0, false), 0..0);
}
fn word_at(text: &str, at: &str, skip: usize) -> String {
let byte = text.find(at).expect("in the text") + at.char_indices().nth(skip).unwrap().0;
let offset = utf16_len(&text[..byte]);
let range = word_range(text, offset, true);
text[byte_offset(text, range.start)..byte_offset(text, range.end)].to_string()
}
#[test]
fn hostnames_urls_paths_and_ids_are_one_word() {
let host = "Open demo-app.pages.dev now.";
for (at, skip) in [
("demo", 0),
("demo", 3),
("-app", 0),
("app", 1),
(".pages", 0),
("dev", 2),
] {
assert_eq!(
word_at(host, at, skip),
"demo-app.pages.dev",
"at {at}+{skip}"
);
}
let url = "See https://x.y/a-b?c=1, then";
for (at, skip) in [("https", 0), ("://", 1), ("x.y", 2), ("a-b", 2), ("c=1", 2)] {
assert_eq!(
word_at(url, at, skip),
"https://x.y/a-b?c=1",
"at {at}+{skip}"
);
}
assert_eq!(word_at("edit ~/a/b-c.md today", "b-c", 0), "~/a/b-c.md");
assert_eq!(word_at("edit ~/a/b-c.md today", "~", 0), "~/a/b-c.md");
assert_eq!(word_at("(in /etc/hosts)", "hosts", 0), "/etc/hosts");
assert_eq!(word_at("cd client/ui/ first", "ui", 0), "client/ui/");
assert_eq!(word_at("run with --force-all", "force", 0), "--force-all");
assert_eq!(word_at("mail me@x.io.", "me", 0), "me@x.io");
assert_eq!(word_at("NSH v0.5.1 is out", "5", 0), "v0.5.1");
assert_eq!(word_at("id ab-1234cdef ok", "12", 0), "ab-1234cdef");
assert_eq!(word_at("worker `abc_def-1` here", "def", 0), "abc_def-1");
assert_eq!(word_at("It ends with foo.", "foo", 1), "foo");
assert_eq!(word_at("It ends with foo.", ".", 0), ".");
assert_eq!(
word_at("(see demo-app.pages.dev)", "dev", 0),
"demo-app.pages.dev"
);
assert_eq!(word_at("one, two", "one", 0), "one");
assert_eq!(word_at("a - b", "-", 0), "-");
assert_eq!(word_at("so -- then", "--", 0), "-");
assert_eq!(word_at("the quick brown fox", "quick", 2), "quick");
assert_eq!(word_at("it's here", "it", 0), "it");
assert_eq!(word_at("中文demo-app.pages.dev。", "中", 0), "中");
assert_eq!(
word_at("中文demo-app.pages.dev。", "app", 0),
"demo-app.pages.dev"
);
assert_eq!(word_at("测试。日本", "。", 0), "。");
assert_eq!(word_at("测试-日本", "-", 0), "-");
}
#[test]
fn a_long_press_selects_a_hostname_whole_and_a_double_click_its_word() {
let texts = Fake::new(&[("Open demo-app.pages.dev now.", (0.0, 0.0, 300.0, 20.0))]);
let mut model = SelectionModel::new();
assert!(model.select_word_at(&texts, at(44.0, 10.0)));
assert_eq!(model.text(&texts), "demo-app.pages.dev");
model.press(&texts, at(44.0, 10.0), 2, false);
assert_eq!(model.text(&texts), "demo");
model.drag(&texts, at(124.0, 10.0));
assert_eq!(model.text(&texts), "demo-app.pages");
}
#[test]
fn a_query_joins_only_in_a_url_and_operators_never() {
assert_eq!(
word_at("go to https://x.y/a?b=1&c=2#d now", "c=2", 0),
"https://x.y/a?b=1&c=2#d"
);
assert_eq!(word_at("go to x.y/a?b=1 now", "b=1", 2), "x.y/a?b=1");
assert_eq!(word_at("set a=b first", "a=b", 0), "a");
assert_eq!(word_at("set a=b first", "a=b", 2), "b");
assert_eq!(word_at("then x+y is", "x+y", 0), "x");
assert_eq!(word_at("really?yes", "yes", 0), "yes");
assert_eq!(word_at("issue#12 here", "issue", 0), "issue");
assert_eq!(word_at("at 12:30 today", "30", 0), "12:30");
assert_eq!(
word_at("on localhost:8080 now", "8080", 0),
"localhost:8080"
);
assert_eq!(word_at("key:value pairs", "key", 0), "key:value");
assert_eq!(word_at("the end.Next one", "end", 0), "end.Next");
}
#[test]
fn a_token_a_wrap_cut_after_a_hyphen_is_one_word() {
let texts = Wrapped(
Fake::new(&[
("Open demo-", (0.0, 0.0, 80.0, 20.0)),
("app.pages.dev now.", (0.0, 20.0, 144.0, 20.0)),
]),
vec![false, true],
);
let mut model = SelectionModel::new();
model.select_word_at(&texts, at(44.0, 5.0));
assert_eq!(model.text(&texts), "demo-app.pages.dev");
assert_eq!(model.bounds(), Some((pos(0, 5), pos(1, 13))));
model.select_word_at(&texts, at(4.0, 25.0));
assert_eq!(model.text(&texts), "demo-app.pages.dev");
model.press(&texts, at(44.0, 5.0), 2, false);
assert_eq!(model.text(&texts), "demo");
}
#[test]
fn texts_changed_clamps_and_clears() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(16.0, 5.0), 1, false);
model.drag(&texts, at(24.0, 105.0));
let shorter = Fake::new(&[
("Hello world", (0.0, 0.0, 200.0, 20.0)),
("Second", (0.0, 40.0, 200.0, 20.0)),
("L", (0.0, 100.0, 200.0, 20.0)),
]);
assert!(model.texts_changed(&shorter));
assert_eq!(model.bounds(), Some((pos(0, 2), pos(2, 1))));
assert!(!model.texts_changed(&shorter));
let fewer = Fake::new(&[("Hello world", (0.0, 0.0, 200.0, 20.0))]);
assert!(model.texts_changed(&fewer));
assert_eq!(model.bounds(), None);
assert!(!model.texts_changed(&fewer));
}
struct Keyed(Fake, Vec<u64>);
impl SelectionTexts for Keyed {
fn len(&self) -> usize {
self.0.len()
}
fn content(&self, i: usize) -> &str {
self.0.content(i)
}
fn frame(&self, i: usize) -> Bounds<Points> {
self.0.frame(i)
}
fn offset_at(&self, i: usize, point: Point<Points>) -> u32 {
self.0.offset_at(i, point)
}
fn key(&self, i: usize) -> u64 {
self.1[i]
}
}
#[test]
fn the_ends_keep_the_order_the_user_made_them_in() {
let texts = Keyed(column(), vec![10, 20, 30]);
let mut model = SelectionModel::new();
assert_eq!(model.ends(&texts), None);
model.press(&texts, at(16.0, 105.0), 1, false);
assert_eq!(model.ends(&texts), None, "a caret has no ends");
model.drag(&texts, at(8.0, 45.0));
assert_eq!(model.ends(&texts), Some([(30, 2), (20, 1)]));
assert_eq!(
end_fields([(30, 2), (20, 1)]).map(|(k, _)| k),
[
"anchorNode",
"anchorNodeOffset",
"focusNode",
"focusNodeOffset"
]
);
}
#[test]
fn a_copy_offset_counts_the_breaks_a_copy_puts_between_texts() {
let texts = column();
assert_eq!(copy_offset(&texts, pos(0, 0)), 0);
assert_eq!(copy_offset(&texts, pos(1, 0)), 13);
assert_eq!(copy_offset(&texts, pos(1, 3)), 16);
assert_eq!(copy_offset(&texts, pos(2, 0)), 13 + 21 + 2);
}
#[test]
fn a_selection_follows_its_texts_by_key() {
let texts = Keyed(column(), vec![10, 20, 30]);
let mut model = SelectionModel::new();
model.press(&texts, at(0.0, 45.0), 1, false);
model.drag(&texts, at(16.0, 105.0));
assert_eq!(model.bounds(), Some((pos(1, 0), pos(2, 2))));
let more = Keyed(
Fake::new(&[
("New", (0.0, 0.0, 200.0, 20.0)),
("Hello world", (0.0, 30.0, 200.0, 20.0)),
("Second line\nmore text", (0.0, 70.0, 200.0, 40.0)),
("Last", (0.0, 130.0, 200.0, 20.0)),
]),
vec![5, 10, 20, 30],
);
assert!(model.texts_changed(&more));
assert_eq!(model.bounds(), Some((pos(2, 0), pos(3, 2))));
assert_eq!(model.text(&more), "Second line\nmore text\n\nLa");
let gone = Keyed(
Fake::new(&[
("New", (0.0, 0.0, 200.0, 20.0)),
("Second line\nmore text", (0.0, 70.0, 200.0, 40.0)),
]),
vec![5, 20],
);
assert!(model.texts_changed(&gone));
assert!(model.bounds().is_none());
}
#[test]
fn stacked_children_go_by_their_tops_and_rows_stay_in_mount_order() {
let frame = |x: f32, y: f32, h: f32| bounds(point(px(x), px(y)), size(px(100.0), px(h)));
let runs = [
(frame(0.0, 200.0, 100.0), 0..2),
(frame(0.0, 0.0, 300.0), 2..2),
(frame(0.0, 0.0, 100.0), 2..3),
(frame(0.0, 100.0, 100.0), 3..4),
];
let order = reading_order(&runs).unwrap();
assert_eq!(order, [2, 3, 0, 1]);
let mut items = vec!["x", "c1", "c2", "a", "b"];
let shifted: Vec<usize> = order.iter().map(|i| i + 1).collect();
reorder(&mut items, 1, &shifted);
assert_eq!(items, ["x", "a", "b", "c1", "c2"]);
let in_order = [
(frame(0.0, 0.0, 10.0), 0..1),
(frame(0.0, 10.0, 10.0), 1..2),
];
assert_eq!(reading_order(&in_order), None);
let row = [
(frame(200.0, 0.0, 20.0), 0..1),
(frame(0.0, 0.0, 20.0), 1..2),
];
assert_eq!(reading_order(&row), None);
let overlay = [
(frame(0.0, 50.0, 100.0), 0..1),
(frame(0.0, 0.0, 100.0), 1..2),
];
assert_eq!(reading_order(&overlay), None);
}
#[test]
fn kept_rows_follow_the_ends_texts() {
let texts = column();
let mut model = SelectionModel::new();
let mut kept = KeptRows::default();
assert_eq!(kept.changed(&model), None);
model.press(&texts, at(4.0, 4.0), 1, false);
model.drag(&texts, at(4.0, 64.0));
assert!(!kept.changed(&model).unwrap().is_empty());
assert_eq!(kept.changed(&model), None);
model.clear();
assert_eq!(kept.changed(&model), Some(Vec::new()));
}
#[test]
fn autoscroll_starts_inside_the_edge_and_speeds_up_outward() {
let step = |at: f32| autoscroll_step(Points(at), Points(400.0));
assert_eq!(step(200.0), Points(0.0));
assert_eq!(step(17.0), Points(0.0));
assert!(step(15.0) < Points(0.0));
assert!(step(385.0) > Points(0.0));
assert_eq!(step(400.0 - 16.0 + 96.0), AUTOSCROLL_MAX);
assert_eq!(step(-500.0), Points(-AUTOSCROLL_MAX.0));
assert!(step(420.0) > step(390.0));
}
struct Wrapped(Fake, Vec<bool>);
impl SelectionTexts for Wrapped {
fn len(&self) -> usize {
self.0.len()
}
fn content(&self, i: usize) -> &str {
self.0.content(i)
}
fn frame(&self, i: usize) -> Bounds<Points> {
self.0.frame(i)
}
fn offset_at(&self, i: usize, point: Point<Points>) -> u32 {
self.0.offset_at(i, point)
}
fn continues(&self, i: usize) -> bool {
self.1[i]
}
}
#[test]
fn a_copy_keeps_the_blank_lines_inside_the_selection() {
let texts = Fake::new(&[
("}", (0.0, 0.0, 200.0, 20.0)),
("", (0.0, 20.0, 0.0, 20.0)),
("next", (0.0, 40.0, 200.0, 20.0)),
]);
let mut model = SelectionModel::new();
model.select_all(&texts);
assert_eq!(model.text(&texts), "}\n\nnext");
}
fn keyed(texts: &impl SelectionTexts, from: TextPosition) -> SelectionModel {
let mut model = SelectionModel::new();
model.select_range(texts, from, from);
model
}
#[test]
fn keys_do_nothing_before_a_press() {
let texts = column();
let mut model = SelectionModel::new();
assert!(!model.extend(&texts, Movement::Character, Direction::Forward));
assert_eq!(model.bounds(), None);
}
#[test]
fn a_character_key_extends_from_a_press_and_crosses_texts() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(72.0, 5.0), 1, false);
assert_eq!(model.focus(), Some(pos(0, 9)));
for _ in 0..2 {
assert!(model.extend(&texts, Movement::Character, Direction::Forward));
}
assert_eq!(model.text(&texts), "ld");
assert!(model.extend(&texts, Movement::Character, Direction::Forward));
assert_eq!(model.focus(), Some(pos(1, 0)));
assert!(model.extend(&texts, Movement::Character, Direction::Forward));
assert_eq!(model.text(&texts), "ld\n\nS");
for _ in 0..6 {
model.extend(&texts, Movement::Character, Direction::Backward);
}
assert_eq!(model.bounds(), Some((pos(0, 7), pos(0, 9))));
assert_eq!(model.text(&texts), "or");
let mut model = keyed(&texts, pos(0, 0));
assert!(!model.extend(&texts, Movement::Character, Direction::Backward));
let mut model = keyed(&texts, pos(2, 4));
assert!(!model.extend(&texts, Movement::Character, Direction::Forward));
}
#[test]
fn a_character_key_steps_over_clusters() {
let texts = Fake::new(&[("e\u{301}🇩🇪👍🏽\r\nx", (0.0, 0.0, 200.0, 40.0))]);
let mut model = keyed(&texts, pos(0, 0));
let mut stops = Vec::new();
while model.extend(&texts, Movement::Character, Direction::Forward) {
stops.push(model.focus().unwrap().offset);
}
assert_eq!(stops, vec![2, 6, 10, 12, 13]);
let mut back = Vec::new();
while model.extend(&texts, Movement::Character, Direction::Backward) {
back.push(model.focus().unwrap().offset);
}
assert_eq!(back, vec![12, 10, 6, 2, 0]);
}
#[test]
fn a_character_key_runs_on_across_a_wrapped_lines_parts() {
let texts = wrapped();
let mut model = keyed(&texts, pos(1, 8));
model.extend(&texts, Movement::Character, Direction::Forward);
assert_eq!(model.focus(), Some(pos(1, 9)));
model.extend(&texts, Movement::Character, Direction::Forward);
assert_eq!(model.focus(), Some(pos(2, 1)));
assert_eq!(model.text(&texts), "in");
model.extend(&texts, Movement::Character, Direction::Backward);
model.extend(&texts, Movement::Character, Direction::Backward);
assert_eq!(model.focus(), Some(pos(1, 8)));
}
#[test]
fn a_word_key_goes_over_spaces_and_punctuation_to_a_words_edge() {
let texts = Fake::new(&[
("foo, bar.baz ", (0.0, 0.0, 200.0, 20.0)),
(" next 日本", (0.0, 20.0, 200.0, 20.0)),
]);
let mut model = keyed(&texts, pos(0, 0));
let mut stops = Vec::new();
while model.extend(&texts, Movement::Word, Direction::Forward) {
stops.push(model.focus().unwrap());
}
assert_eq!(
stops,
vec![
pos(0, 3),
pos(0, 8),
pos(0, 12),
pos(1, 6),
pos(1, 8),
pos(1, 9)
]
);
let mut back = Vec::new();
while model.extend(&texts, Movement::Word, Direction::Backward) {
back.push(model.focus().unwrap());
}
assert_eq!(
back,
vec![
pos(1, 8),
pos(1, 7),
pos(1, 2),
pos(0, 9),
pos(0, 5),
pos(0, 0)
]
);
}
#[test]
fn a_line_key_keeps_its_x_across_short_lines_and_texts() {
let texts = Fake::new(&[
(
"a long first line\nab\nanother long line",
(0.0, 0.0, 200.0, 60.0),
),
("x", (0.0, 70.0, 200.0, 20.0)),
("the last long line", (0.0, 100.0, 200.0, 20.0)),
]);
let mut model = keyed(&texts, pos(0, 10));
model.extend(&texts, Movement::Line, Direction::Forward);
assert_eq!(model.focus(), Some(pos(0, 20)), "the end of `ab`");
model.extend(&texts, Movement::Line, Direction::Forward);
assert_eq!(model.focus(), Some(pos(0, 31)), "column 10 again");
model.extend(&texts, Movement::Line, Direction::Forward);
assert_eq!(model.focus(), Some(pos(1, 1)), "the end of `x`");
model.extend(&texts, Movement::Line, Direction::Forward);
assert_eq!(model.focus(), Some(pos(2, 10)));
model.extend(&texts, Movement::Line, Direction::Forward);
assert_eq!(model.focus(), Some(pos(2, 18)));
let mut model = keyed(&texts, pos(2, 10));
model.extend(&texts, Movement::Line, Direction::Backward);
assert_eq!(model.focus(), Some(pos(1, 1)));
model.extend(&texts, Movement::Character, Direction::Backward);
model.extend(&texts, Movement::Line, Direction::Backward);
assert_eq!(model.focus(), Some(pos(0, 21)), "column 0 of the last line");
model.extend(&texts, Movement::Line, Direction::Backward);
model.extend(&texts, Movement::Line, Direction::Backward);
assert_eq!(model.focus(), Some(pos(0, 0)));
model.extend(&texts, Movement::Line, Direction::Backward);
assert_eq!(model.focus(), Some(pos(0, 0)));
}
#[test]
fn a_line_key_skips_the_texts_beside_on_a_row() {
let texts = Fake::new(&[
("name", (0.0, 0.0, 100.0, 20.0)),
("value", (100.0, 0.0, 100.0, 20.0)),
("below the row", (0.0, 30.0, 200.0, 20.0)),
]);
let mut model = keyed(&texts, pos(0, 2));
model.extend(&texts, Movement::Line, Direction::Forward);
assert_eq!(model.focus(), Some(pos(2, 2)));
model.extend(&texts, Movement::Line, Direction::Backward);
assert_eq!(model.focus(), Some(pos(1, 0)), "the last text above");
}
#[test]
fn a_line_edge_key_goes_to_the_ends_of_the_focus_line() {
let texts = Fake::new(&[("first line\nsecond", (0.0, 0.0, 200.0, 40.0))]);
let mut model = keyed(&texts, pos(0, 3));
model.extend(&texts, Movement::LineEdge, Direction::Forward);
assert_eq!(model.focus(), Some(pos(0, 10)));
assert!(!model.extend(&texts, Movement::LineEdge, Direction::Forward));
model.extend(&texts, Movement::LineEdge, Direction::Backward);
assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 3))));
let mut model = keyed(&texts, pos(0, 14));
model.extend(&texts, Movement::LineEdge, Direction::Backward);
assert_eq!(model.focus(), Some(pos(0, 11)));
model.extend(&texts, Movement::LineEdge, Direction::Forward);
assert_eq!(model.focus(), Some(pos(0, 17)));
}
#[test]
fn paragraph_and_document_keys() {
let texts = wrapped();
let mut model = keyed(&texts, pos(1, 3));
model.extend(&texts, Movement::Paragraph, Direction::Forward);
assert_eq!(model.focus(), Some(pos(2, 10)), "the wrapped line's end");
model.extend(&texts, Movement::Paragraph, Direction::Forward);
assert_eq!(model.focus(), Some(pos(3, 4)));
model.extend(&texts, Movement::Paragraph, Direction::Backward);
assert_eq!(model.focus(), Some(pos(3, 0)));
model.extend(&texts, Movement::Paragraph, Direction::Backward);
assert_eq!(model.focus(), Some(pos(1, 0)), "the wrapped line's start");
model.extend(&texts, Movement::Document, Direction::Backward);
assert_eq!(model.bounds(), Some((pos(0, 0), pos(1, 3))));
model.extend(&texts, Movement::Document, Direction::Forward);
assert_eq!(model.bounds(), Some((pos(1, 3), pos(3, 4))));
}
#[test]
fn a_double_clicked_word_extends_from_the_end_the_key_points_to() {
let texts = column();
let mut model = SelectionModel::new();
model.press(&texts, at(56.0, 5.0), 2, false);
assert_eq!(model.text(&texts), "world");
model.extend(&texts, Movement::Character, Direction::Backward);
assert_eq!(model.text(&texts), " world");
let mut model = SelectionModel::new();
model.press(&texts, at(56.0, 5.0), 2, false);
model.extend(&texts, Movement::Character, Direction::Forward);
assert_eq!(model.bounds(), Some((pos(0, 6), pos(1, 0))));
}
#[test]
fn the_focus_caret_follows_the_keys() {
let texts = column();
let mut model = keyed(&texts, pos(1, 3));
assert_eq!(
model.focus_caret(&texts),
Some(bounds(point(px(24.0), px(40.0)), size(px(0.0), px(20.0))))
);
model.extend(&texts, Movement::Line, Direction::Forward);
assert_eq!(
model.focus_caret(&texts),
Some(bounds(point(px(24.0), px(60.0)), size(px(0.0), px(20.0))))
);
}
fn wrapped() -> Wrapped {
Wrapped(
Fake::new(&[
("first line", (0.0, 0.0, 200.0, 20.0)),
("a long li", (0.0, 20.0, 200.0, 20.0)),
("ne wrapped", (0.0, 40.0, 200.0, 20.0)),
("last", (0.0, 60.0, 200.0, 20.0)),
]),
vec![false, false, true, false],
)
}
#[test]
fn a_copy_joins_a_wrapped_lines_parts_with_nothing_between() {
let texts = wrapped();
let mut model = SelectionModel::new();
model.select_all(&texts);
assert_eq!(model.text(&texts), "first line\na long line wrapped\nlast");
model.press(&texts, at(16.0, 25.0), 1, false);
model.drag(&texts, at(16.0, 45.0));
assert_eq!(model.text(&texts), "long line");
}
#[test]
fn a_continued_text_whose_part_before_is_not_selected_starts_the_copy() {
let texts = wrapped();
let mut model = SelectionModel::new();
model.press(&texts, at(0.0, 45.0), 1, false);
model.drag(&texts, at(32.0, 65.0));
assert_eq!(model.text(&texts), "ne wrapped\nlast");
}
#[test]
fn a_triple_click_selects_a_wrapped_line_whole() {
let texts = wrapped();
let mut model = SelectionModel::new();
model.press(&texts, at(16.0, 45.0), 3, false);
assert_eq!(model.bounds(), Some((pos(1, 0), pos(2, 10))));
assert_eq!(model.text(&texts), "a long line wrapped");
model.press(&texts, at(8.0, 5.0), 3, false);
assert_eq!(model.text(&texts), "first line");
}
#[test]
fn a_double_click_selects_a_word_a_wrap_cut_across_its_parts() {
let texts = wrapped();
let mut model = SelectionModel::new();
model.press(&texts, at(60.0, 25.0), 2, false);
assert_eq!(model.text(&texts), "line");
model.press(&texts, at(8.0, 45.0), 2, false);
assert_eq!(model.text(&texts), "line");
model.press(&texts, at(60.0, 5.0), 2, false);
assert_eq!(model.text(&texts), "line");
assert_eq!(model.bounds(), Some((pos(0, 6), pos(0, 10))));
}
#[test]
fn two_column_gaps_and_short_sidebar_stay_in_their_column() {
let texts = Fake::new(&[
("Left 1", (12.0, 12.0, 200.0, 40.0)),
("Left 2", (12.0, 66.0, 200.0, 40.0)),
("Left 3", (12.0, 120.0, 200.0, 40.0)),
("Sidebar", (240.0, 20.0, 140.0, 70.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(20.0, 20.0), 1, false);
model.drag(&texts, at(80.0, 59.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 6))));
assert_eq!(model.text(&texts), "eft 1");
model.drag(&texts, at(80.0, 80.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(1, 6))));
model.drag(&texts, at(80.0, 190.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(2, 6))));
model.drag(&texts, at(280.0, 50.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(3, 5))));
model.drag(&texts, at(280.0, 140.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(3, 7))));
model.drag(&texts, at(280.0, 220.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(3, 7))));
}
#[test]
fn absolute_top_badge_does_not_hijack_body_gaps_or_bottom() {
let texts = Fake::new(&[
("Title", (14.0, 14.0, 360.0, 22.0)),
("Body 1", (14.0, 50.0, 360.0, 40.0)),
("Body 2", (14.0, 104.0, 360.0, 40.0)),
("BADGE", (310.0, 15.0, 60.0, 18.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(20.0, 20.0), 1, false);
model.drag(&texts, at(100.0, 43.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 5))));
assert_eq!(model.text(&texts), "itle");
model.drag(&texts, at(100.0, 160.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(2, 6))));
assert!(!model.text(&texts).contains("BADGE"));
model.drag(&texts, at(330.0, 160.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(2, 6))));
}
#[test]
fn wrapped_table_cell_blank_space_does_not_jump_back_to_tall_sibling() {
let texts = Fake::new(&[
("Long wrapped cell", (0.0, 40.0, 200.0, 60.0)),
("UIKit", (220.0, 40.0, 100.0, 20.0)),
("CoreText", (340.0, 40.0, 100.0, 20.0)),
("Next row left", (0.0, 110.0, 200.0, 20.0)),
("Views", (220.0, 110.0, 100.0, 20.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(228.0, 48.0), 1, false);
model.drag(&texts, at(260.0, 75.0));
assert_eq!(model.bounds(), Some((pos(1, 1), pos(1, 5))));
assert_eq!(model.text(&texts), "IKit");
}
#[test]
fn a_tall_wrapped_cell_keeps_a_drag_beside_it_in_its_row() {
let texts = Fake::new(&[
("Name", (12.0, 8.0, 136.0, 20.0)),
("Notes", (172.0, 8.0, 236.0, 20.0)),
("Alpha", (12.0, 44.0, 136.0, 20.0)),
("One\nTwo\nThree\nFour", (172.0, 44.0, 236.0, 80.0)),
("Beta", (12.0, 140.0, 136.0, 20.0)),
("Five", (172.0, 140.0, 236.0, 20.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(12.0, 50.0), 1, false);
for y in [70.0, 90.0, 110.0, 123.0] {
model.drag(&texts, at(80.0, y));
assert_eq!(model.bounds(), Some((pos(2, 0), pos(2, 5))), "at y={y}");
assert_eq!(model.text(&texts), "Alpha", "at y={y}");
}
model.drag(&texts, at(36.0, 150.0));
assert_eq!(model.bounds(), Some((pos(2, 0), pos(4, 3))));
}
#[test]
fn past_the_end_of_a_shorter_row_selects_to_its_end() {
let texts = Fake::new(&[
("1,891.5 - 3,026", (0.0, 0.0, 120.0, 20.0)),
("Phys", (128.0, 0.0, 32.0, 20.0)),
("105 - 592.5", (0.0, 30.0, 88.0, 20.0)),
("Ltng", (96.0, 30.0, 32.0, 20.0)),
("190 - 280", (0.0, 60.0, 72.0, 20.0)),
("Cold", (80.0, 60.0, 32.0, 20.0)),
]);
for x in [136.0, 150.0, 300.0] {
for y in [32.0, 40.0, 49.0] {
let mut model = SelectionModel::new();
model.press(&texts, at(0.0, 40.0), 1, false);
model.drag(&texts, at(x, y));
assert_eq!(
model.bounds(),
Some((pos(2, 0), pos(3, 4))),
"at ({x}, {y})"
);
assert_eq!(model.text(&texts), "105 - 592.5\tLtng", "at ({x}, {y})");
}
}
let mut model = SelectionModel::new();
model.press(&texts, at(128.0, 40.0), 1, false);
model.drag(&texts, at(-40.0, 40.0));
assert_eq!(model.bounds(), Some((pos(2, 0), pos(3, 4))));
let mut model = SelectionModel::new();
model.press(&texts, at(0.0, 40.0), 1, false);
model.drag(&texts, at(300.0, 120.0));
assert_eq!(model.bounds(), Some((pos(2, 0), pos(5, 4))));
}
#[test]
fn single_column_short_lines_still_hit_their_row_and_bottom() {
let texts = Fake::new(&[
("Hi", (0.0, 0.0, 40.0, 20.0)),
("A much wider middle paragraph", (0.0, 30.0, 300.0, 20.0)),
("End", (0.0, 60.0, 40.0, 20.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(0.0, 10.0), 1, false);
model.drag(&texts, at(150.0, 10.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(0, 2))));
model.drag(&texts, at(150.0, 120.0));
assert_eq!(model.bounds(), Some((pos(0, 0), pos(2, 3))));
}
#[test]
fn margins_and_short_column_lines_stay_in_nearest_column() {
let texts = Fake::new(&[
("Apple", (20.0, 12.0, 50.0, 20.0)),
("Banana", (20.0, 48.0, 60.0, 20.0)),
("Cherry", (20.0, 84.0, 60.0, 20.0)),
("Sidebar", (300.0, 12.0, 120.0, 50.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(28.0, 20.0), 1, false);
model.drag(&texts, at(4.0, 38.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 5))));
model.drag(&texts, at(120.0, 38.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(0, 5))));
model.drag(&texts, at(340.0, 30.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(3, 5))));
model.drag(&texts, at(440.0, 92.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(3, 7))));
}
#[test]
fn full_width_header_and_footer_around_two_columns_stay_monotonic() {
let texts = Fake::new(&[
("Header", (0.0, 0.0, 500.0, 20.0)),
("Left 1", (0.0, 40.0, 200.0, 40.0)),
("Left 2", (0.0, 100.0, 200.0, 80.0)),
("Right", (300.0, 40.0, 200.0, 60.0)),
("Footer", (0.0, 200.0, 500.0, 20.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(10.0, 10.0), 1, false);
model.drag(&texts, at(220.0, 140.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(2, 6))));
model.drag(&texts, at(350.0, 70.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(3, 5))));
model.drag(&texts, at(350.0, 130.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(3, 5))));
model.drag(&texts, at(350.0, 180.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(4, 0))));
}
#[test]
fn full_width_header_does_not_pull_sibling_column_into_narrow_right_column() {
let texts = Fake::new(&[
("Full-width Header", (16.0, 12.0, 420.0, 22.0)),
("Left column item 1", (16.0, 50.0, 190.0, 36.0)),
("Left column item 2", (16.0, 98.0, 190.0, 24.0)),
("Left column item 3", (16.0, 134.0, 190.0, 44.0)),
("Right", (280.0, 50.0, 56.0, 48.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(288.0, 66.0), 1, false);
for y in [126.0, 129.0, 132.0, 156.0] {
model.drag(&texts, at(356.0, y));
assert_eq!(model.bounds(), Some((pos(4, 1), pos(4, 5))), "at y={y}");
assert_eq!(model.text(&texts), "ight", "at y={y}");
}
}
#[test]
fn dragging_below_a_multi_column_table_reaches_the_last_cell() {
let texts = Fake::new(&[
("Column A", (16.0, 20.0, 160.0, 24.0)),
("Column B", (200.0, 20.0, 160.0, 24.0)),
("Row 1 Left", (16.0, 58.0, 160.0, 24.0)),
("Row 1 Right", (200.0, 58.0, 160.0, 24.0)),
("Row 2 Left", (16.0, 96.0, 160.0, 24.0)),
("Row 2 Right", (200.0, 96.0, 160.0, 24.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(24.0, 32.0), 1, false);
model.drag(&texts, at(80.0, 156.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(5, 11))));
assert_eq!(
model.text(&texts),
"olumn A\tColumn B\nRow 1 Left\tRow 1 Right\nRow 2 Left\tRow 2 Right"
);
}
#[test]
fn same_bottom_side_by_side_texts_under_wide_title_keep_right_text() {
let texts = Fake::new(&[
(
"Wide section title above two tags",
(16.0, 20.0, 360.0, 24.0),
),
("Status:", (16.0, 60.0, 64.0, 24.0)),
("Ready", (96.0, 60.0, 56.0, 24.0)),
("Next paragraph below", (16.0, 140.0, 240.0, 24.0)),
]);
let mut model = SelectionModel::new();
model.press(&texts, at(24.0, 32.0), 1, false);
model.drag(&texts, at(230.0, 96.0));
assert_eq!(model.bounds(), Some((pos(0, 1), pos(2, 5))));
assert_eq!(
model.text(&texts),
"ide section title above two tags\nStatus:\tReady"
);
}
}