use serde::{Deserialize, Serialize};
use crate::node::{Common, IntoNode, Node};
use crate::text::{Alignment, Text};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Wrap {
Disabled(bool),
Enabled {
trim: bool,
},
}
impl Wrap {
#[must_use]
pub fn trim(trim: bool) -> Self {
Self::Enabled { trim }
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Paragraph {
#[serde(flatten)]
pub common: Common,
pub text: Text,
#[serde(skip_serializing_if = "Option::is_none")]
pub wrap: Option<Wrap>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scroll: Option<[u16; 2]>,
#[serde(skip_serializing_if = "Option::is_none")]
pub alignment: Option<Alignment>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scrollbar: Option<bool>,
}
impl Paragraph {
#[must_use]
pub fn new(text: impl Into<Text>) -> Self {
Self {
text: text.into(),
..Self::default()
}
}
#[must_use]
pub fn wrap(mut self, wrap: Wrap) -> Self {
self.wrap = Some(wrap);
self
}
#[must_use]
pub fn scroll(mut self, y: u16, x: u16) -> Self {
self.scroll = Some([y, x]);
self
}
#[must_use]
pub fn alignment(mut self, alignment: Alignment) -> Self {
self.alignment = Some(alignment);
self
}
#[must_use]
pub fn scrollbar(mut self, scrollbar: bool) -> Self {
self.scrollbar = Some(scrollbar);
self
}
}
impl IntoNode for Paragraph {}
impl From<Paragraph> for Node {
fn from(p: Paragraph) -> Self {
Node::Paragraph(p)
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
reason = "tests assert by unwrapping"
)]
use super::*;
#[test]
fn wrap_false_form() {
let w: Wrap = serde_json::from_str("false").expect("false parses");
assert_eq!(w, Wrap::Disabled(false));
let w: Wrap = serde_json::from_str(r#"{"trim":true}"#).expect("object parses");
assert_eq!(w, Wrap::Enabled { trim: true });
}
}