Skip to main content

meo_canvas/
lib.rs

1//! Draw a picture by describing it, not by issuing commands.
2//!
3//! ```
4//! use meo_canvas::{
5//!     Column, Image, Row, Styled, Text, all, hex_rgb, px, scene::ObjectFit,
6//! };
7//!
8//! let card = Row::new()
9//!     .gap(px(16.0))
10//!     .padding(all(px(24.0)))
11//!     .background_color(hex_rgb(0x10_10_14))
12//!     .children([
13//!         Image::path("avatar.png")
14//!             .size(px(64.0), px(64.0))
15//!             .object_fit(ObjectFit::Cover),
16//!         Column::new().children([
17//!             Text::new("Ukasyah").font_size(24.0).bold(),
18//!             Text::new("Bandung").color(hex_rgb(0x88_88_90)),
19//!         ]),
20//!     ]);
21//!
22//! let (scene, _diagnostics) = card.into_scene(360.0, 112.0)?;
23//! # Ok::<(), meo_canvas_scene::SceneError>(())
24//! ```
25//!
26//! Properties are named on the node, flat, as CSS names them and as the
27//! JavaScript surface's props spell them. That is the path this crate is
28//! taught in: the setters come from [`Styled`], which every node implements,
29//! so the import is one trait rather than a type per node.
30//!
31//! A node carries a constructor, its properties, and its children. The method
32//! set never grows per node: a new property is a new entry in one table, not a
33//! method on seven node types. Each node's essential argument is a constructor
34//! parameter -- [`Text::new`] takes the content, [`Image::path`] the source,
35//! [`Path::d`] the data -- so it cannot be forgotten.
36//!
37//! # One flat style
38//!
39//! [`Style`] is one type, not four. Authoring is flat because CSS is flat: a
40//! reader never has to know which group `gap` lives in versus
41//! `background_color`. The scene keeps them grouped because the codec needs
42//! them grouped, and [`Style::into_parts`] splits at the moment the tree
43//! becomes a scene.
44//!
45//! The names and the behaviour are CSS's. [`Style::color`] is the inherited
46//! text colour and [`Style::background_color`] is the fill; the two sit
47//! adjacent and mean different things, which is CSS's trap and not one invented
48//! here. Keeping it is what lets a design be ported without translation.
49//!
50//! # A style as a value, for the base a design reuses
51//!
52//! The flat setters name one property at a time, which is the wrong shape for
53//! a base that many nodes share. [`Style`] carries the same setters as
54//! `const fn`s, so that base is a `const`, and
55//! [`with_style`](Element::with_style) layers it onto a node:
56//!
57//! ```
58//! use meo_canvas::{ColorValue, Row, Style, Styled, all, hex_rgb, px};
59//!
60//! const CARD: Style = Style::new().padding(all(px(24.0))).gap(px(16.0));
61//!
62//! let dark = Row::new().with_style(
63//!     CARD.background_color(ColorValue::Rgba(hex_rgb(0x10_10_14))),
64//! );
65//! let light = Row::new()
66//!     .with_style(CARD)
67//!     .background_color(hex_rgb(0x1c_1c_22));
68//! ```
69//!
70//! `with_style` merges: what the style names wins, what it leaves absent the
71//! node keeps. So the two idioms compose in either order, and neither erases
72//! the other -- `light` above is a card that is also a row, and would be
73//! whichever way round those two lines were written.
74//!
75//! A `const` is substituted at each use, so every `CARD` is a fresh value a
76//! `self`-taking setter may consume. No clone and no lifetime. A property
77//! holding a `String` or a `Vec` cannot be `const`, because assigning one drops
78//! what it replaces; a function returning a `Style` serves the same purpose
79//! there.
80//!
81//! Every field is public, so a property with no setter is still reachable:
82//!
83//! ```
84//! use meo_canvas::{Style, px};
85//!
86//! let golden = Style {
87//!     aspect_ratio: Some(1.618),
88//!     ..Style::new().gap(px(8.0))
89//! };
90//! ```
91//!
92//! # Chains and literals
93//!
94//! A tree is chained and a bag of options is a literal, and the difference is
95//! not a matter of taste.
96//!
97//! A node's children nest, and each carries a style of its own, so the shape of
98//! the call has to be the shape of the picture -- `Row::new().children([..])`
99//! reads as the row it describes where the same tree written as a literal
100//! reads as bookkeeping. [`Style`] chains for a second reason: the properties
101//! are optional and independent, so a chain names the handful a caller set
102//! rather than defaulting the sixty they did not.
103//!
104//! Options are struct literals closed with `..Default::default()`. A literal
105//! shows every value the caller chose in one place, and there is no ordering
106//! between options and no invalid intermediate state for a builder to prevent.
107//!
108//! `Style` takes both, which is why its fields are public and why it is not
109//! `#[non_exhaustive]`: the chain covers the properties with setters, and the
110//! literal reaches the ones without. The rest pattern is what keeps such a
111//! literal compiling when a field is added.
112//!
113//! # What this crate deliberately excludes
114//!
115//! No Skia and no taffy in any signature, and neither as a direct dependency.
116//! Both live behind `meo-canvas-core`. A caller who upgrades either one does so
117//! on that crate's schedule, and a caller who reads this crate's documentation
118//! never has to learn two other vocabularies to place a rectangle.
119//!
120//! No async runtime, and no HTTP client unless you ask for one. An
121//! [`ImageSource::Url`](scene::ImageSource) is [`Error::UnresolvedSource`] by
122//! default, and the `net` feature makes it a request instead -- the client
123//! beneath is blocking by construction, so enabling it puts no runtime in any
124//! consumer. [`HttpOptions`](scene::HttpOptions) sets headers per source, so a
125//! page pulling from two origins sends each one only what belongs to it.
126//!
127//! **Off by default is the same reach at a different price.** The JavaScript
128//! surface fetches without a flag because its addon ships the client prebuilt;
129//! here the consumer compiles it, and the flag lets whoever pays for the
130//! dependency decide. Most never do: a scene built from bytes or paths names no
131//! URL.
132//!
133//! No mutable drawing context. There is no `move_to`/`line_to` state machine
134//! here -- that API already exists, in `meo-skia-canvas`, and reproducing it
135//! would give the workspace two answers to the same question.
136
137// No source in this workspace writes `unsafe`, and this makes adding one a
138// deliberate decision rather than a line that passes review. Integration tests
139// are separate crates and not covered; their one `unsafe` is the
140// `GlobalAlloc` that measures `codec::decode`'s reservation.
141#![forbid(unsafe_code)]
142pub mod chart;
143pub mod element;
144pub mod root;
145pub mod style;
146pub mod unit;
147
148pub use element::{
149    Box, Column, Each, Element, Grid, Image, IntoElements, Path, Row, Text,
150    each,
151};
152/// The animation helpers, as a module rather than a curated list.
153///
154/// **A list would be a second surface free to drift from the first**: a
155/// helper in the core and absent here, with nothing to say so.
156/// Re-exporting the module cannot omit one. The cost is that it publishes
157/// whatever the module grows, which holds because nothing inside the
158/// renderer uses `animate` -- anything added to it is added for callers.
159///
160/// # Examples
161///
162/// ```
163/// use meo_canvas::animate::{easing::Easing, spring::Spring};
164///
165/// assert!((Easing::OutCubic.at(0.5) - 0.875).abs() < f64::EPSILON);
166/// assert!(Spring::default().at(0.2).unwrap_or(0.0) > 0.0);
167/// ```
168pub use meo_canvas_core::animate;
169pub use meo_canvas_core::{
170    EncodeOptions, Error, FetchFailure, ImageFormat as Format, ImageWarning,
171    PreparedEncode, RenderedCanvas, Renderer,
172};
173pub use meo_canvas_scene::style::{
174    PaintOrder,
175    effect::FillRule,
176    layout::{
177        Align, BoxSizing, Direction, Display, FlexDirection, FlexWrap,
178        GridAutoFlow, GridPlacement, Justify, JustifyItems, JustifySelf,
179        LegacyPosition, Overflow, OverflowPosition, PositionType, SelfPosition,
180        TrackSize,
181    },
182    paint::{
183        BackgroundRepeat, BlendMode, BorderStyle, Color, ColorValue,
184        GradientKind, ObjectFit,
185    },
186    text::{
187        FontStyle, FontVariant, FontWeight, LineHeight, TextAlign,
188        TextDecoration, VerticalAlign,
189    },
190};
191/// The style keywords, at the crate root.
192///
193/// `Justify::Center` and its siblings are authoring vocabulary — a caller
194/// names one every time they write a container — so they sit beside the
195/// node constructors rather than under [`scene`]. The scene module keeps
196/// them too, along with everything a caller assembling a `Scene` by hand
197/// would need.
198pub use meo_canvas_scene::surface::{ColorSpace, ColorType, OnImageError};
199pub use root::{BuildError, Canvas, PageInfo, Root, SequenceError};
200pub use style::{Style, Styled};
201pub use unit::{
202    DefaultZero, IntoCorners, IntoSides, all, auto, bottom, corners,
203    corners_all, fr, fraction, hex, hex_rgb, hex_rgba, left, pct, px, rgb,
204    rgba, right, sides, size_auto, top, track, xy,
205};
206
207/// The scene vocabulary, re-exported so callers need one dependency rather than
208/// two.
209pub mod scene {
210    /// Reading and writing a scene as bytes: what turns the scene
211    /// [`Root::into_scene`](crate::Root::into_scene) returns into
212    /// something to write to disk, send over the wire or render more
213    /// than once.
214    pub use meo_canvas_scene::codec;
215    pub use meo_canvas_scene::{
216        Corners, Dimension, Length, Node, NodeId, NodeKind, Point, Rect, Scene,
217        SceneError, Sides, Size,
218        node::{HttpOptions, ImageSource, LineCap, LineJoin, PathPaint},
219        style::{
220            PaintOrder,
221            effect::{
222                BoxShadow, Effects, FillRule, Mask, MaskShape, TextShadow,
223                Transform,
224            },
225            layout::{
226                Align, BoxSizing, Direction, Display, FlexDirection, FlexWrap,
227                GridAutoFlow, GridPlacement, Justify, JustifyItems,
228                JustifySelf, LayoutStyle, LegacyPosition, Overflow,
229                OverflowPosition, PositionType, SelfPosition, TrackSize,
230            },
231            paint::{
232                BackgroundImage, BackgroundRepeat, BackgroundSize, BlendMode,
233                BorderStyle, Color, ColorValue, Gradient, GradientGeometry,
234                GradientKind, GradientStop, LinearDirection, ObjectFit,
235                PaintStyle,
236            },
237            text::{
238                DEFAULT_ELLIPSIS, FontStyle, FontVariant, FontWeight,
239                LineHeight, ParagraphStyle, Spacing, TextAlign, TextDecoration,
240                TextStroke, TextStyle, VerticalAlign,
241            },
242        },
243    };
244}
245
246/// The repository README's Rust examples, run as doctests since nothing else
247/// checks them; `#[cfg(doctest)]` keeps this out of the rendered docs.
248/// rustdoc runs only unlabelled and `rust` fences, so the `ts` fences that
249/// `generate-doc-examples.mjs` typechecks are left alone.
250#[cfg(doctest)]
251#[doc = include_str!("../../../README.md")]
252pub struct RepositoryReadme;