use std::{borrow::Cow, convert::TryInto};
use euclid::Size2D;
use unicode_segmentation::UnicodeSegmentation;
use crate::{event::Event, unit::Cell, Printer, View as ViewTrait};
pub struct View<'a> {
inner: &'a str,
}
impl<'a> View<'a> {
pub fn new(s: &'a str) -> Self {
Self {
inner: s,
}
}
fn size_and_lines(
&self,
width_constraint: u16,
) -> (Size2D<u16, Cell>, Vec<Cow<'_, str>>) {
let lines = textwrap::wrap(&self.inner, width_constraint as usize);
let max_width = lines
.iter()
.map(|x| x.graphemes(true).count())
.max()
.unwrap_or(0)
.try_into()
.unwrap_or(0);
let rows = lines.iter().count().try_into().unwrap_or(0);
((max_width, rows).into(), lines)
}
}
pub fn new(s: &str) -> View<'_> {
View::new(s)
}
impl<T, M> ViewTrait<T, M> for View<'_>
where
M: 'static,
{
fn draw(&self, printer: &Printer, _focused: bool) {
let (size, lines) = self.size_and_lines(printer.size().width);
for (line, row) in lines.iter().zip(0..size.height) {
printer.print(&line, (0, row)).unwrap();
}
}
fn width(&self) -> Size2D<u16, Cell> {
let longest_word_len: u16 = self
.inner
.split_whitespace()
.map(|w| w.graphemes(true).count())
.max()
.unwrap_or(0)
.try_into()
.expect("u16 overflow");
self.size_and_lines(longest_word_len).0
}
fn height(&self) -> Size2D<u16, Cell> {
let longest_line_len = self
.inner
.lines()
.map(|l| l.graphemes(true).count())
.max()
.unwrap_or(0)
.try_into()
.expect("u16 overflow");
self.size_and_lines(longest_line_len).0
}
fn layout(&self, constraint: Size2D<u16, Cell>) -> Size2D<u16, Cell> {
self.size_and_lines(constraint.width).0
}
fn event(&mut self, _: &Event<T>, _: bool) -> Box<dyn Iterator<Item = M>> {
Box::new(std::iter::empty())
}
fn interactive(&self) -> bool {
false
}
}