use std::{ops::Range, sync::Arc};
use crate::app::component::{DevtoolsFormatter, DevtoolsInspectable};
pub use crate::components::text::OBJECT_CHARACTER;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct InlineObject {
pub at: usize,
pub source: Arc<str>,
pub label: Arc<str>,
pub width: Option<u32>,
}
impl InlineObject {
pub fn new(at: usize, source: impl Into<Arc<str>>) -> Self {
Self {
at,
source: source.into(),
label: Arc::from(""),
width: None,
}
}
pub fn label(mut self, label: impl Into<Arc<str>>) -> Self {
self.label = label.into();
self
}
pub fn width(mut self, width: u32) -> Self {
self.width = Some(width);
self
}
pub fn range(&self) -> Range<usize> {
self.at..self.at + OBJECT_CHARACTER.len_utf8()
}
pub(crate) fn same_thing(&self, other: &Self) -> bool {
self.source == other.source && self.label == other.label
}
}
impl DevtoolsInspectable for InlineObject {
fn inspect(&self, formatter: &mut DevtoolsFormatter<'_>) {
formatter.value_debug(self);
}
}
pub(crate) fn normalize_objects(text: &str, mut objects: Vec<InlineObject>) -> Vec<InlineObject> {
let in_order = objects.windows(2).all(|pair| pair[0].at < pair[1].at);
if !in_order {
objects.sort_by_key(|object| object.at);
}
let mut out: Vec<InlineObject> = Vec::with_capacity(objects.len());
for object in objects {
if !text
.get(object.at..)
.is_some_and(|rest| rest.starts_with(OBJECT_CHARACTER))
{
continue;
}
match out.last_mut() {
Some(last) if last.at == object.at => *last = object,
_ => out.push(object),
}
}
out
}
pub(crate) fn splice_objects(objects: &[InlineObject], range: Range<usize>, inserted: usize) -> Vec<InlineObject> {
objects
.iter()
.filter(|object| object.at < range.start || object.at >= range.end)
.map(|object| InlineObject {
at: if object.at >= range.end {
object.at - (range.end - range.start) + inserted
} else {
object.at
},
..object.clone()
})
.collect()
}
pub(crate) fn slice_objects(objects: &[InlineObject], range: Range<usize>) -> Vec<InlineObject> {
objects
.iter()
.filter(|object| range.start <= object.at && object.at < range.end)
.map(|object| InlineObject {
at: object.at - range.start,
..object.clone()
})
.collect()
}
pub(crate) fn place_objects(mut objects: Vec<InlineObject>, start: usize, added: &[InlineObject]) -> Vec<InlineObject> {
objects.extend(added.iter().map(|object| InlineObject {
at: object.at + start,
..object.clone()
}));
objects.sort_by_key(|object| object.at);
objects
}
pub(crate) fn text_with_labels(text: &str, objects: &[InlineObject]) -> String {
let mut out = String::with_capacity(text.len());
let mut at = 0;
for object in objects {
let range = object.range();
if range.start < at || !text.is_char_boundary(range.start) || range.end > text.len() {
continue;
}
out.push_str(&text[at..range.start]);
out.push_str(&object.label);
at = range.end;
}
out.push_str(&text[at..]);
out
}
#[cfg(test)]
#[path = "../../../tests/input/text_input/object_ops.rs"]
mod tests;