fission_core/ui/widgets/
image.rs1use crate::lowering::{LoweringContext, NodeBuilder};
2use crate::ui::traits::Lower;
3use fission_ir::{
4 op::{ImageFit, LayoutOp, Op, PaintOp},
5 NodeId,
6};
7use serde::{Deserialize, Serialize};
8
9fn resolve_svg_content(source: &str) -> Option<String> {
10 let trimmed = source.trim_start();
11 if trimmed.starts_with("<svg") {
12 return Some(source.to_string());
13 }
14
15 if source.to_ascii_lowercase().ends_with(".svg") {
16 return std::fs::read_to_string(source).ok();
17 }
18
19 None
20}
21
22#[derive(Debug, Default, Clone, Serialize, Deserialize)]
39pub struct Image {
40 pub id: Option<NodeId>,
42 pub source: String,
44 pub width: Option<f32>,
46 pub height: Option<f32>,
48 pub fit: Option<ImageFit>,
50}
51
52impl Image {
53 pub fn into_node(self) -> crate::ui::Node {
54 crate::ui::Node::Image(self)
55 }
56}
57
58impl Lower for Image {
59 fn lower(&self, cx: &mut LoweringContext) -> NodeId {
60 let layout_id = self.id.unwrap_or_else(|| cx.next_node_id());
61 let paint_op = if let Some(content) = resolve_svg_content(&self.source) {
62 PaintOp::DrawSvg {
63 content,
64 fill: None,
65 stroke: None,
66 }
67 } else {
68 PaintOp::DrawImage {
69 source: self.source.clone(),
70 fit: self.fit.unwrap_or(ImageFit::Contain),
71 }
72 };
73 let paint_id = NodeBuilder::new(cx.next_node_id(), Op::Paint(paint_op)).build(cx);
74
75 let mut layout_builder = NodeBuilder::new(
76 layout_id,
77 Op::Layout(LayoutOp::Box {
78 width: self.width,
79 height: self.height,
80 min_width: None,
81 max_width: None,
82 min_height: None,
83 max_height: None,
84 padding: [0.0; 4],
85 flex_grow: 0.0,
86 flex_shrink: 0.0,
87 aspect_ratio: None,
88 }),
89 );
90 layout_builder.add_child(paint_id);
91 layout_builder.build(cx)
92 }
93}