use meo_canvas_core::diagnostic::Diagnostic;
use meo_canvas_scene::{
Length, Scene, SceneError, Size,
node::{
HttpOptions, ImageSource, LineCap, LineJoin, Node, NodeId, NodeKind,
PathPaint,
},
style::{
effect::FillRule,
paint::{Color, ColorValue, ObjectFit},
text::{ParagraphStyle, TextSegment},
},
};
use crate::{Style, Styled};
#[derive(Debug, Clone, PartialEq)]
pub enum ElementKind {
Node(NodeKind),
Markup {
content: String,
paragraph: ParagraphStyle,
},
}
impl From<NodeKind> for ElementKind {
fn from(kind: NodeKind) -> Self {
Self::Node(kind)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Element {
pub kind: ElementKind,
pub style: Style,
pub children: Vec<Self>,
pub name: Option<String>,
}
impl Element {
#[must_use]
pub const fn new(kind: NodeKind) -> Self {
Self {
kind: ElementKind::Node(kind),
style: Style::new(),
children: Vec::new(),
name: None,
}
}
#[must_use]
pub fn with_style(mut self, style: Style) -> Self {
self.style = core::mem::take(&mut self.style).merge(style);
self
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn children(mut self, children: impl IntoElements) -> Self {
let mut collected = Vec::new();
children.write_elements(&mut collected);
self.children = collected;
self
}
pub fn into_scene(
self,
width: f32,
height: f32,
) -> Result<(Scene, Vec<Diagnostic>), SceneError> {
let size = Size::new(width, height);
if !meo_canvas_scene::size_is_pixels(size) {
return Err(SceneError::canvas_size(width, height));
}
let mut scene = Scene::new(size);
let root = scene.root().ok_or(SceneError::NoPages)?;
let mut found = Vec::new();
write_page(&mut scene, root, self, &mut found)?;
Ok((scene, found))
}
}
impl Element {
const fn paragraph_mut(&mut self) -> Option<&mut ParagraphStyle> {
match &mut self.kind {
ElementKind::Node(NodeKind::Text { paragraph, .. })
| ElementKind::Markup { paragraph, .. } => Some(paragraph),
ElementKind::Node(_) => None,
}
}
}
impl Styled for Element {
fn style_mut(&mut self) -> &mut Style {
&mut self.style
}
}
pub trait IntoElements {
fn write_elements(self, out: &mut Vec<Element>);
}
impl IntoElements for Element {
fn write_elements(self, out: &mut Vec<Element>) {
out.push(self);
}
}
impl IntoElements for Option<Element> {
fn write_elements(self, out: &mut Vec<Element>) {
if let Some(inner) = self {
out.push(inner);
}
}
}
impl<T: IntoElements> IntoElements for Vec<T> {
fn write_elements(self, out: &mut Vec<Element>) {
for item in self {
item.write_elements(out);
}
}
}
impl<T: IntoElements, const N: usize> IntoElements for [T; N] {
fn write_elements(self, out: &mut Vec<Element>) {
for item in self {
item.write_elements(out);
}
}
}
pub const fn each<I>(items: I) -> Each<I>
where
I: IntoIterator,
I::Item: IntoElements,
{
Each(items)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Each<I>(I);
impl<I> IntoElements for Each<I>
where
I: IntoIterator,
I::Item: IntoElements,
{
fn write_elements(self, out: &mut Vec<Element>) {
for item in self.0 {
item.write_elements(out);
}
}
}
fn resolve(kind: ElementKind, found: &mut Vec<Diagnostic>) -> NodeKind {
match kind {
ElementKind::Node(node) => node,
ElementKind::Markup { content, paragraph } => {
let (segments, reported) =
meo_canvas_core::markup::parse_paragraph_reporting(&content);
found.extend(reported);
NodeKind::Text {
segments,
paragraph,
}
}
}
}
pub(crate) fn write_page(
scene: &mut Scene,
root: NodeId,
element: Element,
found: &mut Vec<Diagnostic>,
) -> Result<(), SceneError> {
let mut kind = resolve(element.kind, found);
apply_image_style(&mut kind, &element.style);
let (layout, paint, text, effects) = element.style.into_parts();
if let Some(node) = scene.get_mut(root) {
node.kind = kind;
node.layout = layout;
node.paint = paint;
node.text = text;
node.effects = effects;
node.name = element.name;
}
for child in element.children {
push(scene, root, child, found)?;
}
Ok(())
}
const fn apply_image_style(kind: &mut NodeKind, style: &Style) {
if let NodeKind::Image {
fit,
position,
frame,
..
} = kind
{
if let Some(value) = style.object_fit {
*fit = value;
}
if let Some(value) = style.object_position {
*position = value;
}
if style.frame.is_some() {
*frame = style.frame;
}
}
}
fn push(
scene: &mut Scene,
parent: NodeId,
element: Element,
found: &mut Vec<Diagnostic>,
) -> Result<NodeId, SceneError> {
let mut kind = resolve(element.kind, found);
apply_image_style(&mut kind, &element.style);
let (layout, paint, text, effects) = element.style.into_parts();
let mut node = Node::new(kind);
node.layout = layout;
node.paint = paint;
node.text = text;
node.effects = effects;
node.name = element.name;
let id = scene.push(parent, node)?;
for child in element.children {
push(scene, id, child, found)?;
}
Ok(id)
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Box;
impl Box {
#[must_use]
#[expect(
clippy::new_ret_no_self,
reason = "the node types are constructors for `Element`, not types a caller holds"
)]
pub fn new() -> Element {
Element::new(NodeKind::Box)
.display(meo_canvas_scene::style::layout::Display::Flex)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Row;
impl Row {
#[must_use]
#[expect(
clippy::new_ret_no_self,
reason = "the node types are constructors for `Element`, not types a caller holds"
)]
pub fn new() -> Element {
Element::new(NodeKind::Box)
.display(meo_canvas_scene::style::layout::Display::Flex)
.flex_direction(meo_canvas_scene::style::layout::FlexDirection::Row)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Column;
impl Column {
#[must_use]
#[expect(
clippy::new_ret_no_self,
reason = "the node types are constructors for `Element`, not types a caller holds"
)]
pub fn new() -> Element {
Element::new(NodeKind::Box)
.display(meo_canvas_scene::style::layout::Display::Flex)
.flex_direction(
meo_canvas_scene::style::layout::FlexDirection::Column,
)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Grid;
impl Grid {
#[must_use]
#[expect(
clippy::new_ret_no_self,
reason = "the node types are constructors for `Element`, not types a caller holds"
)]
pub fn new() -> Element {
Element::new(NodeKind::Box)
.display(meo_canvas_scene::style::layout::Display::Grid)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Text;
impl Text {
#[must_use]
#[expect(
clippy::new_ret_no_self,
reason = "the node types are constructors for `Element`, not types a caller holds"
)]
pub fn new(content: impl Into<String>) -> Element {
Element {
kind: ElementKind::Markup {
content: content.into(),
paragraph: ParagraphStyle::default(),
},
style: Style::new(),
children: Vec::new(),
name: None,
}
}
#[must_use]
pub fn rich(
segments: impl IntoIterator<Item = (String, Style)>,
) -> Element {
let segments = segments
.into_iter()
.map(|(text, style)| {
let (_, _, text_style, _) = style.into_parts();
TextSegment {
text,
style: text_style,
}
})
.collect();
Element::new(NodeKind::Text {
segments,
paragraph: ParagraphStyle::default(),
})
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Image;
impl Image {
#[must_use]
pub fn path(path: impl Into<String>) -> Element {
Self::source(ImageSource::Path(path.into()))
}
#[must_use]
pub fn bytes(bytes: impl Into<Vec<u8>>) -> Element {
Self::source(ImageSource::Bytes(bytes.into()))
}
#[must_use]
pub fn url(url: impl Into<String>) -> Element {
Self::source(ImageSource::url(url))
}
#[must_use]
pub fn url_with(url: impl Into<String>, http: HttpOptions) -> Element {
Self::source(ImageSource::url_with(url, http))
}
#[must_use]
pub const fn source(source: ImageSource) -> Element {
Element::new(NodeKind::Image {
source,
fit: ObjectFit::Fill,
position: (Length::Percent(0.5), Length::Percent(0.5)),
frame: None,
})
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Path;
impl Element {
#[must_use]
pub const fn max_lines(mut self, lines: u32) -> Self {
if let Some(paragraph) = self.paragraph_mut() {
paragraph.max_lines = Some(lines);
}
self
}
#[must_use]
pub fn ellipsis(mut self, marker: impl Into<String>) -> Self {
if let Some(paragraph) = self.paragraph_mut() {
paragraph.ellipsis = Some(marker.into());
}
self
}
#[must_use]
pub fn fill(mut self, paint: Option<PathPaint>) -> Self {
if let ElementKind::Node(NodeKind::Path { fill, .. }) = &mut self.kind {
*fill = paint;
}
self
}
#[must_use]
pub const fn view_box(
mut self,
view: Option<(f32, f32, f32, f32)>,
) -> Self {
if let ElementKind::Node(NodeKind::Path { view_box, .. }) =
&mut self.kind
{
*view_box = view;
}
self
}
#[must_use]
pub const fn stretch(mut self, stretched: bool) -> Self {
if let ElementKind::Node(NodeKind::Path { stretch, .. }) =
&mut self.kind
{
*stretch = stretched;
}
self
}
#[must_use]
pub fn stroke(mut self, paint: Option<PathPaint>) -> Self {
if let ElementKind::Node(NodeKind::Path { stroke, .. }) = &mut self.kind
{
*stroke = paint;
}
self
}
#[must_use]
pub const fn line_width(mut self, width: f32) -> Self {
if let ElementKind::Node(NodeKind::Path { line_width, .. }) =
&mut self.kind
{
*line_width = width;
}
self
}
#[must_use]
pub const fn fill_rule(mut self, rule: FillRule) -> Self {
if let ElementKind::Node(NodeKind::Path { fill_rule, .. }) =
&mut self.kind
{
*fill_rule = rule;
}
self
}
#[must_use]
pub const fn line_cap(mut self, cap: LineCap) -> Self {
if let ElementKind::Node(NodeKind::Path { line_cap, .. }) =
&mut self.kind
{
*line_cap = cap;
}
self
}
#[must_use]
pub const fn line_join(mut self, join: LineJoin) -> Self {
if let ElementKind::Node(NodeKind::Path { line_join, .. }) =
&mut self.kind
{
*line_join = join;
}
self
}
#[must_use]
pub fn line_dash(mut self, pattern: impl IntoIterator<Item = f32>) -> Self {
if let ElementKind::Node(NodeKind::Path { line_dash, .. }) =
&mut self.kind
{
*line_dash = pattern.into_iter().collect();
}
self
}
#[must_use]
pub const fn line_dash_offset(mut self, offset: f32) -> Self {
if let ElementKind::Node(NodeKind::Path {
line_dash_offset, ..
}) = &mut self.kind
{
*line_dash_offset = offset;
}
self
}
}
impl Path {
#[must_use]
pub fn d(data: impl Into<String>) -> Element {
Element::new(NodeKind::Path {
data: data.into(),
view_box: None,
stretch: false,
fill: Some(PathPaint::Solid(ColorValue::Rgba(Color::BLACK))),
stroke: None,
line_width: 1.0,
fill_rule: FillRule::NonZero,
line_cap: LineCap::Butt,
line_join: LineJoin::Miter,
line_dash: Vec::new(),
line_dash_offset: 0.0,
})
}
}
#[cfg(test)]
mod tests {
use meo_canvas_scene::{
SceneError,
node::{ImageSource, LineCap, LineJoin, NodeKind, PathPaint},
style::{
PaintOrder,
effect::{FillRule, Mask, MaskShape},
layout::{
Align, BoxSizing, Direction, Display, FlexDirection, FlexWrap,
GridAutoFlow, Justify, JustifyItems, JustifySelf,
LegacyPosition, Overflow, OverflowPosition, PositionType,
SelfPosition,
},
paint::{
BackgroundImage, BackgroundRepeat, BlendMode, BorderStyle,
Color, ColorValue, Gradient, GradientGeometry, ObjectFit,
},
text::{
FontStyle, LineHeight, ParagraphStyle, TextAlign,
TextDecoration, TextStroke, VerticalAlign,
},
},
};
use super::{
Box, Column, Element, ElementKind, Grid, Image, Path, Row, Text,
};
use crate::{Style, Styled, hex_rgb, pct, px};
#[test]
fn a_paragraph_setter_writes_the_node_and_not_the_style() {
let ElementKind::Markup { paragraph, .. } =
Text::new("x").max_lines(2).ellipsis("…").kind
else {
unreachable!("Text::new builds a text node");
};
assert_eq!(paragraph.max_lines, Some(2));
assert_eq!(paragraph.ellipsis.as_deref(), Some("…"));
}
#[test]
fn a_path_setter_writes_every_part_of_the_payload() {
let ElementKind::Node(NodeKind::Path {
fill,
stroke,
line_width,
fill_rule,
line_cap,
line_join,
line_dash,
line_dash_offset,
..
}) = Path::d("M0 0 L4 4")
.fill(None)
.stroke(Some(PathPaint::Solid(Color::rgba(5, 6, 7, 8).into())))
.line_width(2.5)
.fill_rule(FillRule::EvenOdd)
.line_cap(LineCap::Round)
.line_join(LineJoin::Bevel)
.line_dash([1.0, 2.0])
.line_dash_offset(0.5)
.kind
else {
unreachable!("Path::d builds a path node");
};
assert_eq!(fill, None);
assert_eq!(
stroke,
Some(PathPaint::Solid(Color::rgba(5, 6, 7, 8).into()))
);
assert!((line_width - 2.5).abs() < f32::EPSILON);
assert_eq!(fill_rule, FillRule::EvenOdd);
assert_eq!(line_cap, LineCap::Round);
assert_eq!(line_join, LineJoin::Bevel);
assert_eq!(line_dash, vec![1.0, 2.0]);
assert!((line_dash_offset - 0.5).abs() < f32::EPSILON);
}
#[test]
fn a_setter_for_the_wrong_kind_is_ignored() {
let box_node = Box::new().max_lines(2).ellipsis("…").line_width(9.0);
assert_eq!(box_node.kind, ElementKind::Node(NodeKind::Box));
let ElementKind::Markup { paragraph, .. } =
Text::new("x").line_width(9.0).kind
else {
unreachable!("Text::new builds a text node");
};
assert_eq!(paragraph, ParagraphStyle::default());
}
fn runs_of(
element: Element,
) -> Vec<meo_canvas_scene::style::text::TextSegment> {
let (scene, _) = element
.into_scene(100.0, 40.0)
.unwrap_or_else(|error| unreachable!("{error}"));
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the page has a root"));
match &root.kind {
NodeKind::Text { segments, .. } => segments.clone(),
other => unreachable!("expected text, found {other:?}"),
}
}
#[test]
fn text_new_reads_its_string_as_markup() {
let segments = runs_of(Text::new("plain <b>bold</b>"));
let texts: Vec<&str> =
segments.iter().map(|s| s.text.as_str()).collect();
assert_eq!(texts, vec!["plain ", "bold"]);
assert!(segments[1].style.font_weight.is_some());
assert!(segments[0].style.font_weight.is_none());
}
#[test]
fn text_rich_reads_nothing_so_a_literal_angle_bracket_survives() {
let segments =
runs_of(Text::rich([("a <b> b".to_owned(), Style::new())]));
assert_eq!(segments.len(), 1);
assert_eq!(segments[0].text, "a <b> b");
}
#[test]
fn text_that_says_nothing_is_still_a_paragraph() {
let segments = runs_of(Text::new("<b></b>"));
assert_eq!(segments.len(), 1);
assert!(segments[0].text.is_empty());
}
#[test]
fn the_root_element_styles_the_page_rather_than_becoming_a_child_of_it() {
let scene = Box::new()
.with_style(
Style::new().background_color(hex_rgb(0x10_10_14).into()),
)
.into_scene(100.0, 50.0)
.map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);
assert_eq!(scene.nodes.len(), 1);
assert_eq!(scene.size.width.to_bits(), 100.0_f32.to_bits());
assert_eq!(scene.size.height.to_bits(), 50.0_f32.to_bits());
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the page has a root"));
assert_eq!(root.paint.background_color, hex_rgb(0x10_10_14).into());
}
#[test]
fn a_canvas_size_that_is_not_a_length_is_refused() {
for (width, height) in [
(f32::NAN, 10.0),
(10.0, f32::NAN),
(-1.0, 10.0),
(10.0, -1.0),
(f32::INFINITY, 10.0),
(10.0, f32::NEG_INFINITY),
] {
let refused = Box::new().into_scene(width, height);
assert!(
matches!(refused, Err(SceneError::CanvasSize { .. })),
"{width} by {height} was accepted"
);
}
assert!(Box::new().into_scene(0.0, 0.0).is_ok());
}
#[test]
fn the_nested_tree_flattens_into_the_arena_in_order() {
let scene = Column::new()
.children([
Text::new("one"),
Row::new().children([Text::new("two"), Text::new("three")]),
])
.into_scene(10.0, 10.0)
.map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);
assert_eq!(scene.nodes.len(), 5);
assert!(scene.validate().is_ok(), "a built tree is a valid scene");
}
#[test]
fn the_container_constructors_set_the_direction_they_name() {
let (row, ..) = Row::new().style.into_parts();
assert_eq!(row.flex_direction, FlexDirection::Row);
let (column, ..) = Column::new().style.into_parts();
assert_eq!(column.flex_direction, FlexDirection::Column);
let (grid, ..) = Grid::new().style.into_parts();
assert_eq!(grid.display, Display::Grid);
}
#[test]
fn a_style_merges_rather_than_replaces() {
let element = Box::new()
.with_style(Style::new().gap(px(4.0)))
.with_style(Style::new().opacity(0.5));
assert_eq!(element.style.gap, Some((px(4.0), px(4.0))));
assert_eq!(element.style.opacity, Some(0.5));
}
#[test]
fn a_constructor_property_the_style_does_not_name_survives_it() {
let column = Column::new().with_style(Style::new().width(pct(100.0)));
assert_eq!(column.style.flex_direction, Some(FlexDirection::Column));
assert!(column.style.width.is_some(), "the style still applied");
}
#[test]
fn a_constructor_property_the_style_does_name_is_overridden() {
let row = Column::new()
.with_style(Style::new().flex_direction(FlexDirection::Row));
assert_eq!(row.style.flex_direction, Some(FlexDirection::Row));
}
#[test]
fn a_none_in_the_style_leaves_what_the_node_already_had() {
let kept = Box::new().gap(px(12.0)).with_style(Style::new());
assert_eq!(kept.style.gap, Some((px(12.0), px(12.0))));
}
#[test]
fn merge_carries_every_property_it_is_given() {
let full = Style {
display: Some(Display::Flex),
position_type: Some(PositionType::Absolute),
position: Some(<_>::default()),
width: Some(<_>::default()),
height: Some(<_>::default()),
min_width: Some(<_>::default()),
min_height: Some(<_>::default()),
max_width: Some(<_>::default()),
max_height: Some(<_>::default()),
aspect_ratio: Some(<_>::default()),
margin: Some(<_>::default()),
padding: Some(<_>::default()),
border: Some(<_>::default()),
flex_direction: Some(FlexDirection::Row),
flex_wrap: Some(FlexWrap::NoWrap),
flex_grow: Some(<_>::default()),
flex_shrink: Some(<_>::default()),
flex_basis: Some(<_>::default()),
justify_content: Some(Justify::FlexStart),
align_items: Some(Align::FlexStart),
align_self: Some(Align::FlexStart),
align_content: Some(Align::FlexStart),
justify_items: Some(JustifyItems::Legacy(LegacyPosition::Right)),
justify_self: Some(JustifySelf::Position {
position: SelfPosition::SelfEnd,
overflow: Some(OverflowPosition::Safe),
}),
gap: Some(<_>::default()),
overflow: Some((Overflow::Visible, Overflow::Visible)),
box_sizing: Some(BoxSizing::BorderBox),
direction: Some(Direction::Ltr),
grid_template_columns: Some(<_>::default()),
grid_template_rows: Some(<_>::default()),
grid_auto_rows: Some(<_>::default()),
grid_auto_columns: Some(<_>::default()),
grid_auto_flow: Some(GridAutoFlow::Row),
grid_column: Some(<_>::default()),
grid_row: Some(<_>::default()),
background_color: Some(ColorValue::Current),
gradient: Some(Gradient {
geometry: GradientGeometry::Linear {
direction: <_>::default(),
},
stops: Vec::new(),
}),
background_image: Some(BackgroundImage {
source: ImageSource::Path("a.png".to_owned()),
repeat: BackgroundRepeat::Repeat,
size: <_>::default(),
position: <_>::default(),
}),
border_color: Some(<_>::default()),
border_color_all: Some(ColorValue::Current),
border_style: Some(BorderStyle::Solid),
border_radius: Some(<_>::default()),
opacity: Some(<_>::default()),
mix_blend_mode: Some(BlendMode::Normal),
dither: Some(<_>::default()),
z_index: Some(<_>::default()),
object_fit: Some(ObjectFit::Fill),
object_position: Some(<_>::default()),
frame: Some(<_>::default()),
font_family: Some(<_>::default()),
font_size: Some(<_>::default()),
font_weight: Some(<_>::default()),
font_style: Some(FontStyle::Normal),
color: Some(ColorValue::Current),
text_align: Some(TextAlign::Start),
text_decoration: Some(TextDecoration::None),
vertical_align: Some(VerticalAlign::Top),
paint_order: Some(PaintOrder::Fill),
line_height: Some(LineHeight::Number(1.5)),
line_gap: Some(<_>::default()),
font_variant: Some(<_>::default()),
letter_spacing: Some(<_>::default()),
word_spacing: Some(<_>::default()),
text_stroke: Some(TextStroke {
width: 1.0,
color: ColorValue::Current,
}),
transform: Some(<_>::default()),
box_shadows: Some(<_>::default()),
text_shadows: Some(<_>::default()),
mask: Some(Mask::Shape(MaskShape::Circle)),
filter: Some(<_>::default()),
backdrop_filter: Some(<_>::default()),
};
assert_eq!(Style::new().merge(full.clone()), full);
assert_eq!(Box::new().with_style(full.clone()).style, full);
}
#[test]
fn children_takes_anything_iterable() {
let from_map =
Row::new().children(super::each((0..3).map(|_| Text::new("x"))));
assert_eq!(from_map.children.len(), 3);
let from_vec = Row::new().children(vec![Text::new("x")]);
assert_eq!(from_vec.children.len(), 1);
}
#[test]
fn the_image_properties_reach_the_image_node_and_nothing_else() {
let styled = Style::new().object_fit(ObjectFit::Cover).frame(-1);
let image = Image::path("a.png").with_style(styled.clone());
let scene = image
.into_scene(10.0, 10.0)
.map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the page has a root"));
match &root.kind {
NodeKind::Image { fit, frame, .. } => {
assert_eq!(*fit, ObjectFit::Cover);
assert_eq!(*frame, Some(-1));
}
other => unreachable!("expected an image, found {other:?}"),
}
let boxed = Box::new().with_style(styled);
let scene = boxed
.into_scene(10.0, 10.0)
.map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the page has a root"));
assert_eq!(root.kind, NodeKind::Box);
}
#[test]
fn each_image_source_is_carried_as_the_kind_it_is() {
let cases = [
(Image::path("a.png"), ImageSource::Path("a.png".to_owned())),
(
Image::url("https://example.invalid/a.png"),
ImageSource::url("https://example.invalid/a.png"),
),
(Image::bytes(vec![1, 2]), ImageSource::Bytes(vec![1, 2])),
];
for (element, expected) in cases {
match element.kind {
ElementKind::Node(NodeKind::Image { source, .. }) => {
assert_eq!(source, expected);
}
other => unreachable!("expected an image, found {other:?}"),
}
}
}
#[test]
fn text_carries_its_content_and_rich_text_carries_a_run_per_segment() {
let segments = runs_of(Text::new("hello"));
assert_eq!(segments.len(), 1);
assert_eq!(segments[0].text, "hello");
let rich = Text::rich([
("plain ".to_owned(), Style::new()),
("bold".to_owned(), Style::new().bold()),
]);
match rich.kind {
ElementKind::Node(NodeKind::Text { segments, .. }) => {
assert_eq!(segments.len(), 2);
assert!(segments[0].style.font_weight.is_none());
assert!(segments[1].style.font_weight.is_some());
}
other => unreachable!("expected text, found {other:?}"),
}
}
#[test]
fn a_path_carries_its_data() {
match Path::d("M0 0 L1 1").kind {
ElementKind::Node(NodeKind::Path { data, .. }) => {
assert_eq!(data, "M0 0 L1 1");
}
other => unreachable!("expected a path, found {other:?}"),
}
}
#[test]
fn the_canvas_takes_the_size_it_was_given() {
let scene = Box::new()
.into_scene(120.0, 40.0)
.map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene);
assert_eq!(scene.size.width.to_bits(), 120.0_f32.to_bits());
assert_eq!(scene.size.height.to_bits(), 40.0_f32.to_bits());
}
#[test]
fn an_element_can_be_built_from_a_kind_directly() {
let element = Element::new(NodeKind::Box);
assert_eq!(element.children.len(), 0);
assert_eq!(element.style, Style::new());
}
}