• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 mod common {
2     pub mod image;
3     pub mod text;
4 }
5 use common::image::{image_measure_function, ImageContext};
6 use common::text::{text_measure_function, FontMetrics, TextContext, WritingMode, LOREM_IPSUM};
7 use taffy::prelude::*;
8 
9 enum NodeContext {
10     Text(TextContext),
11     Image(ImageContext),
12 }
13 
measure_function( known_dimensions: taffy::geometry::Size<Option<f32>>, available_space: taffy::geometry::Size<taffy::style::AvailableSpace>, node_context: Option<&mut NodeContext>, font_metrics: &FontMetrics, ) -> Size<f32>14 fn measure_function(
15     known_dimensions: taffy::geometry::Size<Option<f32>>,
16     available_space: taffy::geometry::Size<taffy::style::AvailableSpace>,
17     node_context: Option<&mut NodeContext>,
18     font_metrics: &FontMetrics,
19 ) -> Size<f32> {
20     if let Size { width: Some(width), height: Some(height) } = known_dimensions {
21         return Size { width, height };
22     }
23 
24     match node_context {
25         None => Size::ZERO,
26         Some(NodeContext::Text(text_context)) => {
27             text_measure_function(known_dimensions, available_space, &*text_context, font_metrics)
28         }
29         Some(NodeContext::Image(image_context)) => image_measure_function(known_dimensions, image_context),
30     }
31 }
32 
main() -> Result<(), taffy::TaffyError>33 fn main() -> Result<(), taffy::TaffyError> {
34     let mut taffy: TaffyTree<NodeContext> = TaffyTree::new();
35 
36     let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
37 
38     let text_node = taffy.new_leaf_with_context(
39         Style::default(),
40         NodeContext::Text(TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal }),
41     )?;
42 
43     let image_node = taffy
44         .new_leaf_with_context(Style::default(), NodeContext::Image(ImageContext { width: 400.0, height: 300.0 }))?;
45 
46     let root = taffy.new_with_children(
47         Style {
48             display: Display::Flex,
49             flex_direction: FlexDirection::Column,
50             size: Size { width: length(200.0), height: auto() },
51             ..Default::default()
52         },
53         &[text_node, image_node],
54     )?;
55 
56     // Compute layout and print result
57     taffy.compute_layout_with_measure(
58         root,
59         Size::MAX_CONTENT,
60         // Note: this closure is a FnMut closure and can be used to borrow external context for the duration of layout
61         // For example, you may wish to borrow a global font registry and pass it into your text measuring function
62         |known_dimensions, available_space, _node_id, node_context, _style| {
63             measure_function(known_dimensions, available_space, node_context, &font_metrics)
64         },
65     )?;
66     taffy.print_tree(root);
67 
68     Ok(())
69 }
70