Skip to content

Commit

Permalink
Implement TaffyLayout widget (#140)
Browse files Browse the repository at this point in the history
* Fix text widget layout invalidation

* Gitignore .DS_Store files

* Add downcast_ref method to Pod

* Add compute_max_intrinsic method to Pod

Implement compute_max_intrinsic for Box<dyn AnyWidget>

* Add TaffyLayout view and widget

* Add background_color support to TaffyLayout

* Add taffy example
  • Loading branch information
nicoburns authored Nov 28, 2023
1 parent f643dc4 commit c439885
Show file tree
Hide file tree
Showing 11 changed files with 787 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ Cargo.lock

.vscode
.cspell
.DS_Store
18 changes: 18 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,15 @@ default-target = "x86_64-pc-windows-msvc"
cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]

[features]
default = ["x11"]
default = ["x11", "taffy"]

x11 = ["glazier/x11"]
wayland = ["glazier/wayland"]
taffy = ["dep:taffy"]

[dependencies]
xilem_core.workspace = true
taffy = { git = "https://github.com/DioxusLabs/taffy", rev = "7781c70241f7f572130c13106f2a869a9cf80885", optional = true }
vello = { git = "https://github.com/linebender/vello", rev = "9d7c4f00d8db420337706771a37937e9025e089c" }
wgpu = "0.17.0"
parley = { git = "https://github.com/dfrg/parley", rev = "2371bf4b702ec91edee2d58ffb2d432539580e1e" }
Expand Down
127 changes: 127 additions & 0 deletions examples/taffy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
use xilem::{view::View, App, AppLauncher};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct AppState {
count: u32,
}

impl AppState {
fn new() -> Self {
Self { count: 1 }
}
}

#[cfg(not(feature = "taffy"))]
fn app_logic(_data: &mut AppState) -> impl View<AppState> {
"Error: this example requires the 'taffy' feature to be enabled"
}

#[cfg(feature = "taffy")]
fn app_logic(state: &mut AppState) -> impl View<AppState> {
use taffy::style::{AlignItems, FlexWrap, JustifyContent};
use taffy::style_helpers::length;
use vello::peniko::Color;
use xilem::view::{button, div, flex_column, flex_row};

const COLORS: [Color; 4] = [
Color::LIGHT_GREEN,
Color::BLACK,
Color::AZURE,
Color::HOT_PINK,
];

// Some logic, deriving state for the view from our app state
let label = if state.count == 1 {
"Square count: 1".to_string()
} else {
format!("Square count: {}", state.count)
};

// The actual UI Code starts here
flex_column((

// Header
div(String::from("Xilem Example"))
.with_background_color(Color::RED)
.with_style(|s| s.padding = length(20.0)),

// Body
flex_column((

// Counter control buttons
flex_row((
label,
button("increase", |state: &mut AppState| {
println!("clicked increase");
state.count += 1;
}),
button("decrease", |state: &mut AppState| {
println!("clicked decrease");
if state.count > 0 {
state.count -= 1;
}
}),
button("reset", |state: &mut AppState| {
println!("clicked reset");
state.count = 1;
}),
))
.with_background_color(Color::BLUE_VIOLET)
.with_style(|s| {
s.gap.width = length(20.0);
s.padding = length(20.0);
s.justify_content = Some(JustifyContent::Start);
s.align_items = Some(AlignItems::Center);
}),

// Description text
div(String::from("The number of squares below is controlled by the counter above.\n\nTry clicking \"increase\" until the square count increases enough that the view becomes scrollable."))
.with_background_color(Color::RED)
.with_style(|s| s.padding = length(20.0)),

// Lorem Ipsum text
div(String::from("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."))
.with_background_color(Color::RED)
.with_style(|s| s.padding = length(20.0)),

// Wrapping container (number of children controlled by counter)
flex_row(
(0..state.count).map(|i| {
div(())
.with_background_color(COLORS[(i % 4) as usize])
.with_style(|s| {
s.size.width = length(200.0);
s.size.height = length(200.0);
})
}).collect::<Vec<_>>()
)
.with_background_color(Color::FOREST_GREEN)
.with_style(|s| {
s.flex_grow = 1.0;
s.flex_wrap = FlexWrap::Wrap;
s.gap = length(20.0);
s.padding = length(20.0);
}),

))
.with_style(|s| {
s.gap.height = length(20.0);
s.padding.left = length(20.0);
s.padding.right = length(20.0);
s.padding.top = length(20.0);
s.padding.bottom = length(20.0);
})
.with_background_color(Color::WHITE)
)).with_style(|s| {
s.padding.left = length(20.0);
s.padding.right = length(20.0);
s.padding.top = length(20.0);
s.padding.bottom = length(20.0);
})
.with_background_color(Color::DARK_GRAY)
}

fn main() {
let app = App::new(AppState::new(), app_logic);
AppLauncher::new(app).run()
}
5 changes: 5 additions & 0 deletions src/view/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,8 @@ pub use linear_layout::{h_stack, v_stack, LinearLayout};
pub use list::{list, List};
pub use switch::switch;
pub use view::{Adapt, AdaptState, Cx, Memoize, View, ViewMarker, ViewSequence};

#[cfg(feature = "taffy")]
mod taffy_layout;
#[cfg(feature = "taffy")]
pub use taffy_layout::{div, flex_column, flex_row, grid, TaffyLayout};
154 changes: 154 additions & 0 deletions src/view/taffy_layout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright 2022 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{any::Any, marker::PhantomData};

use vello::peniko::Color;

use crate::view::{Id, VecSplice, ViewMarker, ViewSequence};
use crate::widget::{self, ChangeFlags};
use crate::MessageResult;

use super::{Cx, View};

/// TaffyLayout is a container view which does layout for the specified ViewSequence.
///
/// Children are positioned according to the Block, Flexbox or CSS Grid algorithm, depending
/// on the display style set. If the children are themselves instances of TaffyLayout, then
/// they can set styles to control how they placed, sized, and aligned.
pub struct TaffyLayout<T, A, VT: ViewSequence<T, A>> {
children: VT,
style: taffy::Style,
background_color: Option<Color>,
phantom: PhantomData<fn() -> (T, A)>,
}

/// Creates a Flexbox Column [`TaffyLayout`].
pub fn flex_column<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new_flex(children, taffy::FlexDirection::Column)
}

/// Creates a Flexbox Row [`TaffyLayout`].
pub fn flex_row<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new_flex(children, taffy::FlexDirection::Row)
}

/// Creates a Block layout [`TaffyLayout`].
pub fn div<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new(children, taffy::Display::Block)
}

/// Creates a CSS Grid [`TaffyLayout`].
pub fn grid<T, A, VT: ViewSequence<T, A>>(children: VT) -> TaffyLayout<T, A, VT> {
TaffyLayout::new(children, taffy::Display::Grid)
}

impl<T, A, VT: ViewSequence<T, A>> TaffyLayout<T, A, VT> {
pub fn new(children: VT, display: taffy::Display) -> Self {
let phantom = Default::default();
TaffyLayout {
children,
style: taffy::Style {
display,
..Default::default()
},
background_color: None,
phantom,
}
}

pub fn new_flex(children: VT, flex_direction: taffy::FlexDirection) -> Self {
let phantom = Default::default();
let display = taffy::Display::Flex;
TaffyLayout {
children,
style: taffy::Style {
display,
flex_direction,
..Default::default()
},
background_color: None,
phantom,
}
}

pub fn with_style(mut self, style_modifier: impl FnOnce(&mut taffy::Style)) -> Self {
style_modifier(&mut self.style);
self
}

pub fn with_background_color(mut self, color: impl Into<Color>) -> Self {
self.background_color = Some(color.into());
self
}
}

impl<T, A, VT: ViewSequence<T, A>> ViewMarker for TaffyLayout<T, A, VT> {}

impl<T, A, VT: ViewSequence<T, A>> View<T, A> for TaffyLayout<T, A, VT> {
type State = VT::State;

type Element = widget::TaffyLayout;

fn build(&self, cx: &mut Cx) -> (Id, Self::State, Self::Element) {
let mut elements = vec![];
let (id, state) = cx.with_new_id(|cx| self.children.build(cx, &mut elements));
let column = widget::TaffyLayout::new(elements, self.style.clone(), self.background_color);
(id, state, column)
}

fn rebuild(
&self,
cx: &mut Cx,
prev: &Self,
id: &mut Id,
state: &mut Self::State,
element: &mut Self::Element,
) -> ChangeFlags {
let mut scratch = vec![];
let mut splice = VecSplice::new(&mut element.children, &mut scratch);

let mut flags = cx.with_id(*id, |cx| {
self.children
.rebuild(cx, &prev.children, state, &mut splice)
});

if self.background_color != prev.background_color {
element.background_color = self.background_color;
flags |= ChangeFlags::PAINT
}

if self.style != prev.style {
element.style = self.style.clone();
flags |= ChangeFlags::LAYOUT | ChangeFlags::PAINT;
}

// Clear layout cache if the layout ChangeFlag is set
if flags.contains(ChangeFlags::LAYOUT) || flags.contains(ChangeFlags::TREE) {
element.cache.clear()
}

flags
}

fn message(
&self,
id_path: &[Id],
state: &mut Self::State,
event: Box<dyn Any>,
app_state: &mut T,
) -> MessageResult<A> {
self.children.message(id_path, state, event, app_state)
}
}
19 changes: 19 additions & 0 deletions src/widget/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use vello::kurbo::{Affine, Point, Rect, Size};
use vello::{SceneBuilder, SceneFragment};

use super::widget::{AnyWidget, Widget};
use crate::Axis;
use crate::{id::Id, Bloom};

use super::{
Expand Down Expand Up @@ -184,6 +185,11 @@ impl Pod {
}
}

/// Returns the wrapped widget.
pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
(*self.widget).as_any().downcast_ref()
}

/// Returns the wrapped widget.
pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
(*self.widget).as_any_mut().downcast_mut()
Expand Down Expand Up @@ -391,6 +397,19 @@ impl Pod {
self.state.size
}

pub fn compute_max_intrinsic(
&mut self,
axis: Axis,
cx: &mut LayoutCx,
bc: &BoxConstraints,
) -> f64 {
let mut child_cx = LayoutCx {
cx_state: cx.cx_state,
widget_state: &mut self.state,
};
self.widget.compute_max_intrinsic(axis, &mut child_cx, bc)
}

///
pub fn accessibility(&mut self, cx: &mut AccessCx) {
if self.state.flags.intersects(
Expand Down
Loading

0 comments on commit c439885

Please sign in to comment.