summaryrefslogtreecommitdiff
path: root/library
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2023-02-12 18:58:39 +0100
committerLaurenz <laurmaedje@gmail.com>2023-02-12 19:57:28 +0100
commit3ffa7393f0632d9ee5dd9c821685a1a033d5c0ab (patch)
treeaf09b0683352c4028436a2e5251dce54cf41d4aa /library
parentf4856c18b9cf3f6952276cc61b557aebeb2fa651 (diff)
Make all nodes block-level
Diffstat (limited to 'library')
-rw-r--r--library/src/layout/container.rs4
-rw-r--r--library/src/layout/flow.rs33
-rw-r--r--library/src/layout/hide.rs19
-rw-r--r--library/src/layout/mod.rs25
-rw-r--r--library/src/layout/par.rs14
-rw-r--r--library/src/layout/repeat.rs4
-rw-r--r--library/src/layout/stack.rs24
-rw-r--r--library/src/layout/transform.rs63
-rw-r--r--library/src/math/mod.rs4
-rw-r--r--library/src/prelude.rs2
-rw-r--r--library/src/visualize/image.rs45
-rw-r--r--library/src/visualize/line.rs6
-rw-r--r--library/src/visualize/shape.rs135
13 files changed, 203 insertions, 175 deletions
diff --git a/library/src/layout/container.rs b/library/src/layout/container.rs
index b7e7aa18..7bb6a6e9 100644
--- a/library/src/layout/container.rs
+++ b/library/src/layout/container.rs
@@ -38,7 +38,7 @@ use crate::prelude::*;
/// ## Category
/// layout
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
pub struct BoxNode {
/// How to size the content horizontally and vertically.
@@ -99,8 +99,6 @@ impl Layout for BoxNode {
}
}
-impl Inline for BoxNode {}
-
/// # Block
/// A block-level container that places content into a separate flow.
///
diff --git a/library/src/layout/flow.rs b/library/src/layout/flow.rs
index e21dcd2a..7b721c59 100644
--- a/library/src/layout/flow.rs
+++ b/library/src/layout/flow.rs
@@ -2,6 +2,7 @@ use typst::model::Style;
use super::{AlignNode, BlockNode, ColbreakNode, ParNode, PlaceNode, Spacing, VNode};
use crate::prelude::*;
+use crate::visualize::{CircleNode, EllipseNode, ImageNode, RectNode, SquareNode};
/// Arrange spacing, paragraphs and block-level nodes into a flow.
///
@@ -31,8 +32,17 @@ impl Layout for FlowNode {
let barrier = Style::Barrier(child.id());
let styles = styles.chain_one(&barrier);
layouter.layout_par(vt, node, styles)?;
+ } else if child.is::<RectNode>()
+ || child.is::<SquareNode>()
+ || child.is::<EllipseNode>()
+ || child.is::<CircleNode>()
+ || child.is::<ImageNode>()
+ {
+ let barrier = Style::Barrier(child.id());
+ let styles = styles.chain_one(&barrier);
+ layouter.layout_single(vt, child, styles)?;
} else if child.has::<dyn Layout>() {
- layouter.layout_block(vt, child, styles)?;
+ layouter.layout_multiple(vt, child, styles)?;
} else if child.is::<ColbreakNode>() {
layouter.finish_region();
} else {
@@ -157,8 +167,25 @@ impl<'a> FlowLayouter<'a> {
Ok(())
}
- /// Layout a block.
- fn layout_block(
+ /// Layout into a single region.
+ fn layout_single(
+ &mut self,
+ vt: &mut Vt,
+ content: &Content,
+ styles: StyleChain,
+ ) -> SourceResult<()> {
+ let aligns = styles.get(AlignNode::ALIGNS).resolve(styles);
+ let sticky = styles.get(BlockNode::STICKY);
+ let pod = Regions::one(self.regions.base(), Axes::splat(false));
+ let layoutable = content.with::<dyn Layout>().unwrap();
+ let frame = layoutable.layout(vt, styles, pod)?.into_frame();
+ self.layout_item(FlowItem::Frame(frame, aligns, sticky));
+ self.last_was_par = false;
+ Ok(())
+ }
+
+ /// Layout into multiple regions.
+ fn layout_multiple(
&mut self,
vt: &mut Vt,
block: &Content,
diff --git a/library/src/layout/hide.rs b/library/src/layout/hide.rs
index cedc2489..4f46324f 100644
--- a/library/src/layout/hide.rs
+++ b/library/src/layout/hide.rs
@@ -21,7 +21,7 @@ use crate::prelude::*;
/// ## Category
/// layout
#[func]
-#[capable(Layout, Inline)]
+#[capable(Show)]
#[derive(Debug, Hash)]
pub struct HideNode(pub Content);
@@ -39,19 +39,8 @@ impl HideNode {
}
}
-impl Layout for HideNode {
- fn layout(
- &self,
- vt: &mut Vt,
- styles: StyleChain,
- regions: Regions,
- ) -> SourceResult<Fragment> {
- let mut fragment = self.0.layout(vt, styles, regions)?;
- for frame in &mut fragment {
- frame.clear();
- }
- Ok(fragment)
+impl Show for HideNode {
+ fn show(&self, _: &mut Vt, _: &Content, _: StyleChain) -> SourceResult<Content> {
+ Ok(self.0.clone().styled(Meta::DATA, vec![Meta::Hidden]))
}
}
-
-impl Inline for HideNode {}
diff --git a/library/src/layout/mod.rs b/library/src/layout/mod.rs
index f603ef6c..3294a96c 100644
--- a/library/src/layout/mod.rs
+++ b/library/src/layout/mod.rs
@@ -57,6 +57,7 @@ use crate::meta::DocumentNode;
use crate::prelude::*;
use crate::shared::BehavedBuilder;
use crate::text::{LinebreakNode, SmartQuoteNode, SpaceNode, TextNode};
+use crate::visualize::{CircleNode, EllipseNode, ImageNode, RectNode, SquareNode};
/// Root-level layout.
#[capability]
@@ -144,10 +145,6 @@ impl Layout for Content {
}
}
-/// Inline-level layout.
-#[capability]
-pub trait Inline: Layout {}
-
/// Realize into a node that is capable of root-level layout.
fn realize_root<'a>(
vt: &mut Vt,
@@ -173,7 +170,14 @@ fn realize_block<'a>(
content: &'a Content,
styles: StyleChain<'a>,
) -> SourceResult<(Content, StyleChain<'a>)> {
- if content.has::<dyn Layout>() && !applicable(content, styles) {
+ if content.has::<dyn Layout>()
+ && !content.is::<RectNode>()
+ && !content.is::<SquareNode>()
+ && !content.is::<EllipseNode>()
+ && !content.is::<CircleNode>()
+ && !content.is::<ImageNode>()
+ && !applicable(content, styles)
+ {
return Ok((content.clone(), styles));
}
@@ -464,18 +468,19 @@ struct ParBuilder<'a>(BehavedBuilder<'a>);
impl<'a> ParBuilder<'a> {
fn accept(&mut self, content: &'a Content, styles: StyleChain<'a>) -> bool {
if content.is::<SpaceNode>()
- || content.is::<LinebreakNode>()
+ || content.is::<TextNode>()
|| content.is::<HNode>()
|| content.is::<SmartQuoteNode>()
- || content.is::<TextNode>()
- || content.is::<FormulaNode>()
- || content.has::<dyn Inline>()
+ || content.is::<LinebreakNode>()
+ || content.is::<BoxNode>()
+ || content.is::<RepeatNode>()
+ || content.to::<FormulaNode>().map_or(false, |node| !node.block)
{
self.0.push(content.clone(), styles);
return true;
}
- if content.has::<dyn LayoutMath>() {
+ if !content.is::<FormulaNode>() && content.has::<dyn LayoutMath>() {
let formula = FormulaNode { body: content.clone(), block: false }.pack();
self.0.push(formula, styles);
return true;
diff --git a/library/src/layout/par.rs b/library/src/layout/par.rs
index 21551268..b712d8b1 100644
--- a/library/src/layout/par.rs
+++ b/library/src/layout/par.rs
@@ -500,12 +500,14 @@ fn collect<'a>(
.0
.items()
.find_map(|child| {
- if child.is::<TextNode>() || child.is::<SmartQuoteNode>() {
+ if child.with::<dyn Behave>().map_or(false, |behaved| {
+ behaved.behaviour() == Behaviour::Ignorant
+ }) {
+ None
+ } else if child.is::<TextNode>() || child.is::<SmartQuoteNode>() {
Some(true)
- } else if child.has::<dyn Inline>() {
- Some(false)
} else {
- None
+ Some(false)
}
})
.unwrap_or_default()
@@ -558,11 +560,9 @@ fn collect<'a>(
} else if let Some(&node) = child.to::<HNode>() {
full.push(SPACING_REPLACE);
Segment::Spacing(node.amount)
- } else if child.has::<dyn Inline>() {
+ } else {
full.push(NODE_REPLACE);
Segment::Inline(child)
- } else {
- panic!("unexpected par child: {child:?}");
};
if let Some(last) = full.chars().last() {
diff --git a/library/src/layout/repeat.rs b/library/src/layout/repeat.rs
index 06806fb0..10cd1d25 100644
--- a/library/src/layout/repeat.rs
+++ b/library/src/layout/repeat.rs
@@ -26,7 +26,7 @@ use crate::prelude::*;
/// ## Category
/// layout
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
pub struct RepeatNode(pub Content);
@@ -54,5 +54,3 @@ impl Layout for RepeatNode {
self.0.layout(vt, styles, regions)
}
}
-
-impl Inline for RepeatNode {}
diff --git a/library/src/layout/stack.rs b/library/src/layout/stack.rs
index 5c1a471c..35a0ff6f 100644
--- a/library/src/layout/stack.rs
+++ b/library/src/layout/stack.rs
@@ -169,7 +169,7 @@ enum StackItem {
/// Fractional spacing between other items.
Fractional(Fr),
/// A frame for a layouted block.
- Frame(Frame, Align),
+ Frame(Frame, Axes<Align>),
}
impl<'a> StackLayouter<'a> {
@@ -239,7 +239,7 @@ impl<'a> StackLayouter<'a> {
styles.get(AlignNode::ALIGNS)
};
- let align = aligns.get(self.axis).resolve(styles);
+ let aligns = aligns.resolve(styles);
let fragment = block.layout(vt, styles, self.regions)?;
let len = fragment.len();
for (i, frame) in fragment.into_iter().enumerate() {
@@ -257,7 +257,7 @@ impl<'a> StackLayouter<'a> {
self.used.main += gen.main;
self.used.cross.set_max(gen.cross);
- self.items.push(StackItem::Frame(frame, align));
+ self.items.push(StackItem::Frame(frame, aligns));
if i + 1 < len {
self.finish_region();
@@ -291,24 +291,30 @@ impl<'a> StackLayouter<'a> {
match item {
StackItem::Absolute(v) => cursor += v,
StackItem::Fractional(v) => cursor += v.share(self.fr, remaining),
- StackItem::Frame(frame, align) => {
+ StackItem::Frame(frame, aligns) => {
if self.dir.is_positive() {
- ruler = ruler.max(align);
+ ruler = ruler.max(aligns.get(self.axis));
} else {
- ruler = ruler.min(align);
+ ruler = ruler.min(aligns.get(self.axis));
}
- // Align along the block axis.
+ // Align along the main axis.
let parent = size.get(self.axis);
let child = frame.size().get(self.axis);
- let block = ruler.position(parent - self.used.main)
+ let main = ruler.position(parent - self.used.main)
+ if self.dir.is_positive() {
cursor
} else {
self.used.main - child - cursor
};
- let pos = Gen::new(Abs::zero(), block).to_point(self.axis);
+ // Align along the cross axis.
+ let other = self.axis.other();
+ let cross = aligns
+ .get(other)
+ .position(size.get(other) - frame.size().get(other));
+
+ let pos = Gen::new(cross, main).to_point(self.axis);
cursor += child;
output.push_frame(pos, frame);
}
diff --git a/library/src/layout/transform.rs b/library/src/layout/transform.rs
index 1c9dfce5..5977e90b 100644
--- a/library/src/layout/transform.rs
+++ b/library/src/layout/transform.rs
@@ -39,7 +39,7 @@ use crate::prelude::*;
/// ## Category
/// layout
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
pub struct MoveNode {
/// The offset by which to move the content.
@@ -75,18 +75,15 @@ impl Layout for MoveNode {
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
- let mut fragment = self.body.layout(vt, styles, regions)?;
- for frame in &mut fragment {
- let delta = self.delta.resolve(styles);
- let delta = delta.zip(regions.base()).map(|(d, s)| d.relative_to(s));
- frame.translate(delta.to_point());
- }
- Ok(fragment)
+ let pod = Regions::one(regions.base(), Axes::splat(false));
+ let mut frame = self.body.layout(vt, styles, pod)?.into_frame();
+ let delta = self.delta.resolve(styles);
+ let delta = delta.zip(regions.base()).map(|(d, s)| d.relative_to(s));
+ frame.translate(delta.to_point());
+ Ok(Fragment::frame(frame))
}
}
-impl Inline for MoveNode {}
-
/// # Rotate
/// Rotate content with affecting layout.
///
@@ -116,7 +113,7 @@ impl Inline for MoveNode {}
/// ## Category
/// layout
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
pub struct RotateNode {
/// The angle by which to rotate the node.
@@ -169,21 +166,18 @@ impl Layout for RotateNode {
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
- let mut fragment = self.body.layout(vt, styles, regions)?;
- for frame in &mut fragment {
- let origin = styles.get(Self::ORIGIN).unwrap_or(Align::CENTER_HORIZON);
- let Axes { x, y } = origin.zip(frame.size()).map(|(o, s)| o.position(s));
- let transform = Transform::translate(x, y)
- .pre_concat(Transform::rotate(self.angle))
- .pre_concat(Transform::translate(-x, -y));
- frame.transform(transform);
- }
- Ok(fragment)
+ let pod = Regions::one(regions.base(), Axes::splat(false));
+ let mut frame = self.body.layout(vt, styles, pod)?.into_frame();
+ let origin = styles.get(Self::ORIGIN).unwrap_or(Align::CENTER_HORIZON);
+ let Axes { x, y } = origin.zip(frame.size()).map(|(o, s)| o.position(s));
+ let ts = Transform::translate(x, y)
+ .pre_concat(Transform::rotate(self.angle))
+ .pre_concat(Transform::translate(-x, -y));
+ frame.transform(ts);
+ Ok(Fragment::frame(frame))
}
}
-impl Inline for RotateNode {}
-
/// # Scale
/// Scale content without affecting layout.
///
@@ -214,7 +208,7 @@ impl Inline for RotateNode {}
/// ## Category
/// layout
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
pub struct ScaleNode {
/// Scaling factor.
@@ -262,17 +256,14 @@ impl Layout for ScaleNode {
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
- let mut fragment = self.body.layout(vt, styles, regions)?;
- for frame in &mut fragment {
- let origin = styles.get(Self::ORIGIN).unwrap_or(Align::CENTER_HORIZON);
- let Axes { x, y } = origin.zip(frame.size()).map(|(o, s)| o.position(s));
- let transform = Transform::translate(x, y)
- .pre_concat(Transform::scale(self.factor.x, self.factor.y))
- .pre_concat(Transform::translate(-x, -y));
- frame.transform(transform);
- }
- Ok(fragment)
+ let pod = Regions::one(regions.base(), Axes::splat(false));
+ let mut frame = self.body.layout(vt, styles, pod)?.into_frame();
+ let origin = styles.get(Self::ORIGIN).unwrap_or(Align::CENTER_HORIZON);
+ let Axes { x, y } = origin.zip(frame.size()).map(|(o, s)| o.position(s));
+ let transform = Transform::translate(x, y)
+ .pre_concat(Transform::scale(self.factor.x, self.factor.y))
+ .pre_concat(Transform::translate(-x, -y));
+ frame.transform(transform);
+ Ok(Fragment::frame(frame))
}
}
-
-impl Inline for ScaleNode {}
diff --git a/library/src/math/mod.rs b/library/src/math/mod.rs
index 105940c7..85bf56ca 100644
--- a/library/src/math/mod.rs
+++ b/library/src/math/mod.rs
@@ -141,7 +141,7 @@ pub fn module() -> Module {
/// ## Category
/// math
#[func]
-#[capable(Show, Finalize, Layout, Inline, LayoutMath)]
+#[capable(Show, Finalize, Layout, LayoutMath)]
#[derive(Debug, Clone, Hash)]
pub struct FormulaNode {
/// Whether the formula is displayed as a separate block.
@@ -229,8 +229,6 @@ impl Layout for FormulaNode {
}
}
-impl Inline for FormulaNode {}
-
#[capability]
pub trait LayoutMath {
fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()>;
diff --git a/library/src/prelude.rs b/library/src/prelude.rs
index 98ec1ccb..5bb1d08a 100644
--- a/library/src/prelude.rs
+++ b/library/src/prelude.rs
@@ -28,6 +28,6 @@ pub use typst::util::{format_eco, EcoString};
pub use typst::World;
#[doc(no_inline)]
-pub use crate::layout::{Fragment, Inline, Layout, Regions};
+pub use crate::layout::{Fragment, Layout, Regions};
#[doc(no_inline)]
pub use crate::shared::{Behave, Behaviour, ContentExt, StyleMapExt};
diff --git a/library/src/visualize/image.rs b/library/src/visualize/image.rs
index 330f1d04..3a6eb3b0 100644
--- a/library/src/visualize/image.rs
+++ b/library/src/visualize/image.rs
@@ -32,9 +32,13 @@ use crate::prelude::*;
/// ## Category
/// visualize
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
-pub struct ImageNode(pub Image);
+pub struct ImageNode {
+ pub image: Image,
+ pub width: Smart<Rel<Length>>,
+ pub height: Smart<Rel<Length>>,
+}
#[node]
impl ImageNode {
@@ -57,10 +61,9 @@ impl ImageNode {
};
let image = Image::new(buffer, format).at(span)?;
- let width = args.named("width")?;
- let height = args.named("height")?;
-
- Ok(ImageNode(image).pack().boxed(Axes::new(width, height)))
+ let width = args.named("width")?.unwrap_or_default();
+ let height = args.named("height")?.unwrap_or_default();
+ Ok(ImageNode { image, width, height }.pack())
}
}
@@ -71,22 +74,28 @@ impl Layout for ImageNode {
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
- let pxw = self.0.width() as f64;
- let pxh = self.0.height() as f64;
- let px_ratio = pxw / pxh;
+ let sizing = Axes::new(self.width, self.height);
+ let region = sizing
+ .zip(regions.base())
+ .map(|(s, r)| s.map(|v| v.resolve(styles).relative_to(r)))
+ .unwrap_or(regions.base());
+
+ let expand = sizing.as_ref().map(Smart::is_custom) | regions.expand;
+ let region_ratio = region.x / region.y;
// Find out whether the image is wider or taller than the target size.
- let Regions { size: first, expand, .. } = regions;
- let region_ratio = first.x / first.y;
+ let pxw = self.image.width() as f64;
+ let pxh = self.image.height() as f64;
+ let px_ratio = pxw / pxh;
let wide = px_ratio > region_ratio;
// The space into which the image will be placed according to its fit.
let target = if expand.x && expand.y {
- first
- } else if expand.x || (!expand.y && wide && first.x.is_finite()) {
- Size::new(first.x, first.y.min(first.x.safe_div(px_ratio)))
- } else if first.y.is_finite() {
- Size::new(first.x.min(first.y * px_ratio), first.y)
+ region
+ } else if expand.x || (!expand.y && wide && region.x.is_finite()) {
+ Size::new(region.x, region.y.min(region.x.safe_div(px_ratio)))
+ } else if region.y.is_finite() {
+ Size::new(region.x.min(region.y * px_ratio), region.y)
} else {
Size::new(Abs::pt(pxw), Abs::pt(pxh))
};
@@ -108,7 +117,7 @@ impl Layout for ImageNode {
// the frame to the target size, center aligning the image in the
// process.
let mut frame = Frame::new(fitted);
- frame.push(Point::zero(), Element::Image(self.0.clone(), fitted));
+ frame.push(Point::zero(), Element::Image(self.image.clone(), fitted));
frame.resize(target, Align::CENTER_HORIZON);
// Create a clipping group if only part of the image should be visible.
@@ -123,8 +132,6 @@ impl Layout for ImageNode {
}
}
-impl Inline for ImageNode {}
-
/// How an image should adjust itself to a given area.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ImageFit {
diff --git a/library/src/visualize/line.rs b/library/src/visualize/line.rs
index 28910a26..890373ee 100644
--- a/library/src/visualize/line.rs
+++ b/library/src/visualize/line.rs
@@ -28,7 +28,7 @@ use crate::prelude::*;
/// ## Category
/// visualize
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
pub struct LineNode {
/// Where the line starts.
@@ -61,7 +61,7 @@ impl LineNode {
Some(end) => end.zip(start).map(|(to, from)| to - from),
None => {
let length =
- args.named::<Rel<Length>>("length")?.unwrap_or(Abs::cm(1.0).into());
+ args.named::<Rel<Length>>("length")?.unwrap_or(Abs::pt(30.0).into());
let angle = args.named::<Angle>("angle")?.unwrap_or_default();
let x = angle.cos() * length;
@@ -106,5 +106,3 @@ impl Layout for LineNode {
Ok(Fragment::frame(frame))
}
}
-
-impl Inline for LineNode {}
diff --git a/library/src/visualize/shape.rs b/library/src/visualize/shape.rs
index 6f70b6c1..81309f93 100644
--- a/library/src/visualize/shape.rs
+++ b/library/src/visualize/shape.rs
@@ -33,9 +33,13 @@ use crate::prelude::*;
/// ## Category
/// visualize
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
-pub struct RectNode(pub Option<Content>);
+pub struct RectNode {
+ pub body: Option<Content>,
+ pub width: Smart<Rel<Length>>,
+ pub height: Smart<Rel<Length>>,
+}
#[node]
impl RectNode {
@@ -155,14 +159,15 @@ impl RectNode {
pub const OUTSET: Sides<Option<Rel<Length>>> = Sides::splat(Rel::zero());
fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
- let width = args.named("width")?;
- let height = args.named("height")?;
- Ok(Self(args.eat()?).pack().boxed(Axes::new(width, height)))
+ let width = args.named("width")?.unwrap_or_default();
+ let height = args.named("height")?.unwrap_or_default();
+ let body = args.eat()?;
+ Ok(Self { body, width, height }.pack())
}
fn field(&self, name: &str) -> Option<Value> {
match name {
- "body" => match &self.0 {
+ "body" => match &self.body {
Some(body) => Some(Value::Content(body.clone())),
None => Some(Value::None),
},
@@ -181,7 +186,8 @@ impl Layout for RectNode {
layout(
vt,
ShapeKind::Rect,
- &self.0,
+ &self.body,
+ Axes::new(self.width, self.height),
styles.get(Self::FILL),
styles.get(Self::STROKE),
styles.get(Self::INSET),
@@ -193,8 +199,6 @@ impl Layout for RectNode {
}
}
-impl Inline for RectNode {}
-
/// # Square
/// A square with optional content.
///
@@ -237,9 +241,13 @@ impl Inline for RectNode {}
/// ## Category
/// visualize
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
-pub struct SquareNode(pub Option<Content>);
+pub struct SquareNode {
+ pub body: Option<Content>,
+ pub width: Smart<Rel<Length>>,
+ pub height: Smart<Rel<Length>>,
+}
#[node]
impl SquareNode {
@@ -270,22 +278,24 @@ impl SquareNode {
pub const OUTSET: Sides<Option<Rel<Length>>> = Sides::splat(Rel::zero());
fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
- let size = args.named::<Length>("size")?.map(Rel::from);
+ let size = args.named::<Smart<Length>>("size")?.map(|s| s.map(Rel::from));
let width = match size {
None => args.named("width")?,
size => size,
- };
-
+ }
+ .unwrap_or_default();
let height = match size {
None => args.named("height")?,
size => size,
- };
- Ok(Self(args.eat()?).pack().boxed(Axes::new(width, height)))
+ }
+ .unwrap_or_default();
+ let body = args.eat()?;
+ Ok(Self { body, width, height }.pack())
}
fn field(&self, name: &str) -> Option<Value> {
match name {
- "body" => match &self.0 {
+ "body" => match &self.body {
Some(body) => Some(Value::Content(body.clone())),
None => Some(Value::None),
},
@@ -304,7 +314,8 @@ impl Layout for SquareNode {
layout(
vt,
ShapeKind::Square,
- &self.0,
+ &self.body,
+ Axes::new(self.width, self.height),
styles.get(Self::FILL),
styles.get(Self::STROKE),
styles.get(Self::INSET),
@@ -316,8 +327,6 @@ impl Layout for SquareNode {
}
}
-impl Inline for SquareNode {}
-
/// # Ellipse
/// An ellipse with optional content.
///
@@ -350,9 +359,13 @@ impl Inline for SquareNode {}
/// ## Category
/// visualize
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
-pub struct EllipseNode(pub Option<Content>);
+pub struct EllipseNode {
+ pub body: Option<Content>,
+ pub width: Smart<Rel<Length>>,
+ pub height: Smart<Rel<Length>>,
+}
#[node]
impl EllipseNode {
@@ -378,14 +391,15 @@ impl EllipseNode {
pub const OUTSET: Sides<Option<Rel<Length>>> = Sides::splat(Rel::zero());
fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
- let width = args.named("width")?;
- let height = args.named("height")?;
- Ok(Self(args.eat()?).pack().boxed(Axes::new(width, height)))
+ let width = args.named("width")?.unwrap_or_default();
+ let height = args.named("height")?.unwrap_or_default();
+ let body = args.eat()?;
+ Ok(Self { body, width, height }.pack())
}
fn field(&self, name: &str) -> Option<Value> {
match name {
- "body" => match &self.0 {
+ "body" => match &self.body {
Some(body) => Some(Value::Content(body.clone())),
None => Some(Value::None),
},
@@ -404,7 +418,8 @@ impl Layout for EllipseNode {
layout(
vt,
ShapeKind::Ellipse,
- &self.0,
+ &self.body,
+ Axes::new(self.width, self.height),
styles.get(Self::FILL),
styles.get(Self::STROKE).map(Sides::splat),
styles.get(Self::INSET),
@@ -416,8 +431,6 @@ impl Layout for EllipseNode {
}
}
-impl Inline for EllipseNode {}
-
/// # Circle
/// A circle with optional content.
///
@@ -458,9 +471,13 @@ impl Inline for EllipseNode {}
/// ## Category
/// visualize
#[func]
-#[capable(Layout, Inline)]
+#[capable(Layout)]
#[derive(Debug, Hash)]
-pub struct CircleNode(pub Option<Content>);
+pub struct CircleNode {
+ pub body: Option<Content>,
+ pub width: Smart<Rel<Length>>,
+ pub height: Smart<Rel<Length>>,
+}
#[node]
impl CircleNode {
@@ -486,22 +503,26 @@ impl CircleNode {
pub const OUTSET: Sides<Option<Rel<Length>>> = Sides::splat(Rel::zero());
fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
- let size = args.named::<Length>("radius")?.map(|r| 2.0 * Rel::from(r));
+ let size = args
+ .named::<Smart<Length>>("radius")?
+ .map(|s| s.map(|r| 2.0 * Rel::from(r)));
let width = match size {
None => args.named("width")?,
size => size,
- };
-
+ }
+ .unwrap_or_default();
let height = match size {
None => args.named("height")?,
size => size,
- };
- Ok(Self(args.eat()?).pack().boxed(Axes::new(width, height)))
+ }
+ .unwrap_or_default();
+ let body = args.eat()?;
+ Ok(Self { body, width, height }.pack())
}
fn field(&self, name: &str) -> Option<Value> {
match name {
- "body" => match &self.0 {
+ "body" => match &self.body {
Some(body) => Some(Value::Content(body.clone())),
None => Some(Value::None),
},
@@ -520,7 +541,8 @@ impl Layout for CircleNode {
layout(
vt,
ShapeKind::Circle,
- &self.0,
+ &self.body,
+ Axes::new(self.width, self.height),
styles.get(Self::FILL),
styles.get(Self::STROKE).map(Sides::splat),
styles.get(Self::INSET),
@@ -532,13 +554,12 @@ impl Layout for CircleNode {
}
}
-impl Inline for CircleNode {}
-
/// Layout a shape.
fn layout(
vt: &mut Vt,
kind: ShapeKind,
body: &Option<Content>,
+ sizing: Axes<Smart<Rel<Length>>>,
fill: Option<Paint>,
stroke: Smart<Sides<Option<PartialStroke<Abs>>>>,
mut inset: Sides<Rel<Abs>>,
@@ -547,29 +568,28 @@ fn layout(
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
+ let resolved = sizing
+ .zip(regions.base())
+ .map(|(s, r)| s.map(|v| v.resolve(styles).relative_to(r)));
+
let mut frame;
if let Some(child) = body {
+ let region = resolved.unwrap_or(regions.base());
+
if kind.is_round() {
inset = inset.map(|side| side + Ratio::new(0.5 - SQRT_2 / 4.0));
}
// Pad the child.
let child = child.clone().padded(inset.map(|side| side.map(Length::from)));
- let pod = Regions::one(regions.size, regions.expand);
+ let expand = sizing.as_ref().map(Smart::is_custom);
+ let pod = Regions::one(region, expand);
frame = child.layout(vt, styles, pod)?.into_frame();
// Relayout with full expansion into square region to make sure
// the result is really a square or circle.
if kind.is_quadratic() {
- let length = if regions.expand.x || regions.expand.y {
- let target = regions.expand.select(regions.size, Size::zero());
- target.x.max(target.y)
- } else {
- let size = frame.size();
- let desired = size.x.max(size.y);
- desired.min(regions.size.x).min(regions.size.y)
- };
-
+ let length = frame.size().max_by_side().min(region.min_by_side());
let size = Size::splat(length);
let pod = Regions::one(size, Axes::splat(true));
frame = child.layout(vt, styles, pod)?.into_frame();
@@ -577,20 +597,11 @@ fn layout(
} else {
// The default size that a shape takes on if it has no child and
// enough space.
- let mut size = Size::new(Abs::pt(45.0), Abs::pt(30.0)).min(regions.size);
-
+ let default = Size::new(Abs::pt(45.0), Abs::pt(30.0));
+ let mut size = resolved.unwrap_or(default.min(regions.base()));
if kind.is_quadratic() {
- let length = if regions.expand.x || regions.expand.y {
- let target = regions.expand.select(regions.size, Size::zero());
- target.x.max(target.y)
- } else {
- size.x.min(size.y)
- };
- size = Size::splat(length);
- } else {
- size = regions.expand.select(regions.size, size);
+ size = Size::splat(size.min_by_side());
}
-
frame = Frame::new(size);
}