Compare commits

...
Author SHA1 Message Date
shinyobjectz 7c492adfda skills: raea-skills main 8efd329 (#138: raea show --playable in cli.md)
tools/skills.sh check, strict, with a raea built at main 9ce8f53466: every reference and guide copy matches.
2026-11-28 14:48:14 -08:00
shaneandshinyobjectz 9ce8f53466 raea show GAME.tsx --playable, and a playable's page shown as itself (PA16) (#265)
--playable exports the game's preview (native.ts: raea playable --networks preview, in a folder of its own) and shows
that page, titled from it; the raea app plays it in a phone, sandboxed (raea-feed #124). raea show takes a
NAME-preview.html as it is too. The help line, the manual and the conformance tests say so.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 14:32:03 -08:00
shaneandshinyobjectz 28af820668 PA13, PA14: raea playable, and playables in the public engine (#264)
* PA13, PA14: raea playable, and playables in the public engine

Playables move from the private tree into the public engine (Shane 11-28: "public totally part of the engine"):
sdk/playable (raea/playable for authors, the browser host, check.ts, parity.ts, tony.ts), examples/playables and
docs/playables.feature, with raea/playable and @raea/playable back in sdk/tsconfig.base.json.

`raea playable GAME.tsx -o DIR` (apps/playable) replaces the Bun pipeline (playable.sh, bundle.ts, lint.ts, walk.ts,
alias.ts). It lints the source, renders each composition through `raea run` for its shapes and 3D kinds, bundles the
game and the host once with raea's own bundler, and writes each network's page or ZIP against its 5 MB cap.
engine/bundle gains `minify`, `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, .bin as a
Uint8Array) and package-folder aliases (`three/=DIR`). brick-rush writes all nine targets in 7 s (1,384 KB a page);
mobile-ads' tiles and gates export; all play in WebKit, the Google and TikTok packages included.

check.ts lets a network's own page tags through; parity.ts draws in WebKit (chrome.ts is gone), 6.8/255 on
brick-rush frame 300. The craft guide motion/playable.md is `raea guide playable`. bench/live-3d skips brick-rush with
its real reason (PA18).

* tools/layers.toml: raea-app-playable in apps (PA13)

* Fonts travel with a playable, and an end card in a brand's type

An imported .ttf, .otf, .woff or .woff2 (and .jpeg) is its path in a native render (runtime/bundle rewrite.rs,
engine/bundle script.rs) and a data URL in a playable (inline.rs), so an @font-face names the same file either way.
<EndCard> takes font, color and button. Made for the real-brand playables in mobile-ads (ACANA, OLIPOP, HelloFresh),
which carry their brands' own type; the guide and docs/playables.feature say how.

* The preview page tells raea's review its ad events (PA16)

Inside a frame, the preview network posts {raeaPlayable: kind} to its parent on install and end, so the review can show
them beside the game.

* PA16 status: the review plays playables (raea-platform #99), on a host of their own

* The preview page tells the review when it's ready, seen or hidden, and the first touch (PA16)

Beside install and end, the preview build inside a frame posts ready (the game started), viewable and hidden (its page
shown or put away) and touch (the player took over from the game's own hand), so the review and the desktop show them.

* PA16 status: built in cloud (raea-platform #99, #101) and desktop (raea-feed #124), and raea show --playable

* raea playable says what the source can't have even when the game won't render for the lint

A fetch or a URL often stops the walk's render too, and the lint answered with the render's end ("lint.ts ended with
exit 1") and dropped the refusals it had found. Now the source's refusals are the answer, and a render that fails
for another reason is named by its error line.

* PA16 status: play.raea.io is live, checked with the ACANA export

* skills: raea-skills main ae81d0f (#135 notes hook, #136 and #137 the playable guide and raea playable in cli.md)

tools/skills.sh gen with a raea built at this branch and the feed app at main: every reference and guide copy matches it.

* raea-cli: export-game and playable dispatched in a line each, as the verbs around them, so the crate stays at the size gate's 2000 lines

* dupes: the playable's copies folded into what they copied

spec is raea-runtime-bundle's own (now pub), inline.rs's base64 is the base64 crate as raea's other crates use it,
the store and card JSON are json!, and the bundle FFI reads minify and inline as it reads z3 and stamps. tools/dupes.sh:
293 exact, 57 near, as allowed.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 13:53:48 -08:00
shaneandshinyobjectz ea5640de8f raea show --fyi/--group; notes reach closed sessions through raea's hook (#263)
* raea show --fyi and --group; the inbox hook says seen

Shane 11-28: "some things I'm not approving, I'm just acknowledging"; "the agent can go 'let me add a label here'".
raea show --fyi sends a show only to be looked at (the person says Got it, never approves or sends notes); --group
"Title: what it is" FILE... lays the files out in groups, each titled and said in a plain line. Both go to the app's
host as ShowBody.intent and .groups (raea-feed host/show.ts), which hands them to the review (raea-platform
harness/board.ts). The inbox hook says a {kind: seen} line as "seen on item ...", and when every new line is one,
tells the agent there's nothing to do rather than to take it up.

* Notes reach closed sessions: raea's hook hands them over when the session starts again

Shane 11-28: "raea installs a hook in Claude Code and Codex so your notes are delivered when the session next starts".
What the person sends from raea to a session whose terminal has closed waits in its inbox (~/.raea/inbox); the hook
now reads it at SessionStart (a resumed session takes it up first, told it waited while the session was closed) and at
UserPromptSubmit, as well as after a tool and as a turn ends. raea skills install adds SessionStart and
UserPromptSubmit for Claude Code, and Stop, SessionStart and UserPromptSubmit for Codex.

Tested: raea-app-check-inbox (4, a SessionStart hand-over once) and the installer's test in a standalone crate. The
hook.rs change isn't compiled here: raea-app-check needs ~12 GB to build and the disk has 3.5 GB free.

* The inbox tests share one scratch folder helper (dupes: the new test copied the first one's setup)

* The inbox's all-seen check written so it isn't a copy of a closure in fingerprint-use (dupes)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 11:29:49 -08:00
shaneandshinyobjectz 3ac738884c skills: 0.1.12's references (raea-skills #134) (#259)
The goal job kind, MakeGoal, a job's previews, and ~/.raea/machine-id and target, generated at main 096f87d1 with raea
built from it: tools/skills.sh check passes.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 14:08:38 -08:00
shaneandshinyobjectz 096f87d153 A canvas draws a picture from its file: drawImage of a /media/ src (raea #253) (#258)
#255 gave new Image() in a composition its size, so the issue's 3D cards got a canvas the right size, but drawing the
screenshot on it painted nothing: the canvas host decoded only data: URLs (systems/canvas draw.rs decode). A picture
that isn't inline is now read from its file, found by the same roots a canvas's videos are (the page host's
page_path, so /media/x is the project's file; a plain or file:// path without one), its type by its name (png, jpeg,
webp, gif, bmp, svg). A src that isn't there, or isn't a picture, still draws nothing.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 13:23:57 -08:00
shaneandshinyobjectz 845f7438d5 Small caps synthesised, flex lines with a 1/64 px tolerance, and a table's stray text in anonymous cells (#257)
Three layout misses 0.1.11 shipped, each from its issue's own repro.

Times, Helvetica: most system faces) the text drew in normal case. blitz-dom now checks the face a text's lower-case
letters are drawn in for an smcp GSUB feature (once per face, layout/small_caps.rs) and, where it has none, draws each
run of lower-case letters as their capitals at 70% of the font size, as Chrome synthesises them.

gaps come out a few ulps over 658.8 px, so the third item wrapped (rows of 2, 2, 1). Chrome lays out in 1/64 px units
and keeps them on one line. Taffy 0.15.0 is vendored with a line that overflows by less than 1/64 px still fitting,
greedy and balanced wrapping alike.

element around its text had no cells and drew nothing, not even its background. The table's runs of other children
(text, blocks, inline elements) are now wrapped in an anonymous block that the table lays out as an anonymous row
holding one anonymous cell, as css-tables-3 wraps them: the element is laid out shrink-to-fit around its text.

The regression tests (systems/page/tests/layout_0112.rs) lay out each repro; all four fail on main and pass here.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 13:23:52 -08:00
120 changed files with 32516 additions and 57 deletions

No files matched your search

Generated
+14 -2
View File
@@ -13956,6 +13956,18 @@ dependencies = [
"winit",
]
[[package]]
name = "raea-app-playable"
version = "0.1.0"
dependencies = [
"dunce",
"raea-io-home",
"raea-runtime-bundle",
"regex",
"serde_json",
"zip",
]
[[package]]
name = "raea-app-registry"
version = "0.1.0"
@@ -14240,6 +14252,7 @@ name = "raea-bundle"
version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"dunce",
"lightningcss",
"oxc",
@@ -14292,6 +14305,7 @@ dependencies = [
"raea-app-media",
"raea-app-notes",
"raea-app-play",
"raea-app-playable",
"raea-app-scene",
"raea-app-solid",
"raea-app-sound",
@@ -20427,8 +20441,6 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
dependencies = [
"serde",
"slotmap",
+5
View File
@@ -239,6 +239,7 @@ members = [
"apps/capcut",
"apps/layers",
"apps/play",
"apps/playable",
"tools/sdk-props",
"tools/hands-audit",
]
@@ -407,6 +408,10 @@ vello_encoding = { path = "vendor/vello_encoding" }
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
# equivalent yet (linebender/vello blends the encoded values).
vello_shaders = { path = "vendor/vello_shaders" }
# taffy 0.15.0 (Blitz's, Bevy UI's, rune-taffy's) with a flex line whose items overflow its container by less than
# Chrome's layout unit, 1/64 px, kept on one line: f32 rounding wrapped items that add up to the container's width
# (changes marked "raea:", raea #252). Back to upstream once Taffy breaks flex lines with a tolerance.
taffy = { path = "vendor/taffy" }
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
firewheel = { path = "vendor/firewheel" }
firewheel-core = { path = "vendor/firewheel-core" }
+44 -3
View File
@@ -55,6 +55,11 @@ fn said(l: &Value) -> String {
"result" => format!("a result{on}: {text}"),
"correction" => format!("a correction{on}: {text}"),
"sign" => format!("a sign-off{on} (ask {})", l["ask"]),
// a show only to be looked at (raea show --fyi), looked at: Got it, with a word or none
"seen" => {
let word = text.strip_prefix("Seen").unwrap_or(&text).trim_start_matches(':').trim();
if word.is_empty() { format!("seen{on}") } else { format!("seen{on}: {word}") }
}
k => format!("{}{on}: {text}", if k.is_empty() { "something" } else { k }),
};
format!("- {what}")
@@ -68,6 +73,17 @@ pub fn told(agent: &str, v: &Value) -> Option<String> {
return None;
}
let list = lines.iter().map(said).collect::<Vec<_>>().join("\n");
// only Got it on what was shown to look at: nothing to take up
if !lines.iter().any(|l| l["kind"] != "seen") {
return Some(format!("raea: the person has looked at what you showed them (your inbox, ~/.raea/inbox/{inbox}.jsonl):\n{list}\nNothing to do about it; carry on."));
}
// a session started again (resumed) after the person wrote to it while it was closed (Shane 11-28: "notes reach
// closed sessions"): what waited is handed over before anything else
if v["hook_event_name"].as_str() == Some("SessionStart") {
return Some(format!(
"raea: while this session was closed, the person sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up first, before anything else. Answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
));
}
Some(format!(
"raea: the person just sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up now, before going on: it may change what you're doing. What you say next shows under your session in their feed; answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
))
@@ -78,11 +94,17 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
let d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
/// an empty inbox folder of the test's own
fn scratch(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("raea-inbox-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
let d = scratch("once");
let f = d.join("claude-code-abcd1234.jsonl");
std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"no").unwrap();
let first = unread(&d, "claude-code-abcd1234");
@@ -97,6 +119,25 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn seen_is_said_as_seen_and_asks_nothing() {
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen"})), "- seen on item i-2 \"Lobby\"");
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen: lovely"})), "- seen on item i-2 \"Lobby\": lovely");
}
#[test]
fn what_waited_while_it_was_closed_is_handed_over_as_it_starts_again() {
let d = scratch("start");
std::fs::write(d.join("claude-code-5e55a0ff.jsonl"), "{\"kind\":\"edits\",\"item\":\"i-9\",\"title\":\"Cut\",\"text\":\"tighter open\"}\n").unwrap();
// SAFETY: tests in this crate don't read RAEA_INBOX_DIR concurrently
unsafe { std::env::set_var("RAEA_INBOX_DIR", &d) };
let start = told("claude", &json!({"hook_event_name": "SessionStart", "source": "resume", "session_id": "5e55a0ff-1"})).unwrap();
assert!(start.starts_with("raea: while this session was closed") && start.contains("- edits on item i-9 \"Cut\":\ntighter open"), "{start}");
assert_eq!(told("claude", &json!({"hook_event_name": "UserPromptSubmit", "session_id": "5e55a0ff-1"})), None, "handed over once");
unsafe { std::env::remove_var("RAEA_INBOX_DIR") };
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_inbox_is_named_as_raea_show_names_it() {
assert_eq!(name("claude", &json!({"session_id": "15cd6bb0-8829-466f-a28a-bbca3d35be92"})).as_deref(), Some("claude-code-15cd6bb0"));
+7 -1
View File
@@ -148,7 +148,13 @@ pub fn hook(args: &[String]) -> R<String> {
let event = v["hook_event_name"].as_str().unwrap_or("");
// what the person sent from the raea app since the last look (inbox.rs): handed over after any tool, and a turn about
// to end goes on to take it up
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop" | "SessionStart" | "UserPromptSubmit") { crate::inbox::told(agent, &v) } else { None };
// a session starting again, or the person writing to it in its terminal: what they sent from raea while it was
// closed or idle goes in as context first (Claude Code's and Codex's SessionStart and UserPromptSubmit read
// hookSpecificOutput.additionalContext)
if matches!(event, "SessionStart" | "UserPromptSubmit") {
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
}
if event == "Stop" {
// what the person sent, and a `make` job that isn't done (docs/make.feature MK2): either keeps the turn going
let reasons: Vec<String> = [sent, raea_app_check_make::stop(&v)].into_iter().flatten().collect();
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "raea-app-playable"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea playable`: a raea game exported as a playable ad, one page or ZIP per ad network (docs/playables.feature)"
[dependencies]
dunce = "1"
# the game and sdk/playable's host bundled into one page by raea's own bundler (Rolldown, in process)
raea-runtime-bundle = { path = "../../runtime/bundle" }
# where raea's files are: an install's share/raea, else this checkout
raea-io-home = { path = "../../io/home" }
regex = "1"
serde_json = "1"
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
+102
View File
@@ -0,0 +1,102 @@
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
mod lint;
mod pages;
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
pub(crate) use raea_runtime_bundle::spec;
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
let mut d = game.parent();
while let Some(dir) = d {
if dir.join("node_modules/three/package.json").is_file() {
return Ok(dir.to_path_buf());
}
d = dir.parent();
}
["sdk/playable", "sdk/r3f"]
.iter()
.map(|p| home.join(p))
.find(|d| d.join("node_modules/three/package.json").is_file())
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
}
/// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path) -> R<String> {
let host = home.join("sdk/playable/src/host/main.tsx");
if !host.is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display()));
}
let three = three_dir(game, home)?;
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
let alias = format!("three/={}", three.display());
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out);
js
}
pub fn cli(args: &[String]) -> R<String> {
let game = args.get(1).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
let game = dunce::canonicalize(game).map_err(|e| format!("{game}: {e}"))?;
let out = PathBuf::from(flag(args, "-o").ok_or(format!("-o DIR is required: {USAGE}"))?);
let networks: Vec<&str> = flag(args, "--networks").map(|n| n.split(',').filter(|s| !s.is_empty()).collect()).unwrap_or_else(|| pages::NETWORKS.to_vec());
if let Some(bad) = networks.iter().find(|n| !pages::NETWORKS.contains(n)) {
return Err(format!("raea playable: no network {bad} (one of {})", pages::NETWORKS.join(", ")));
}
let orientation = flag(args, "--orientation").unwrap_or("both");
if !["portrait", "landscape", "both"].contains(&orientation) {
return Err("--orientation is portrait, landscape or both".into());
}
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
let mut report = Vec::new();
let found = lint::lint(&game)?;
report.push(format!("3D kinds: {}", if found.kinds.is_empty() { "none".into() } else { found.kinds.join(", ") }));
for c in &found.comps {
let shape = if c.height > c.width { "portrait" } else { "landscape" };
report.push(format!("composition {}: {}x{} {shape}, {} fps, {:.0} s", c.id, c.width, c.height, c.fps, c.frames as f64 / c.fps.max(1.0)));
}
report.extend(found.notes.iter().map(|n| format!("note: {n}")));
if !found.refusals.is_empty() {
// the reasons first: the CLI marks an error's first line REFUSED
let mut why = found.refusals.clone();
why.extend(report);
return Err(why.join("\n"));
}
let js = bundle(&game, &raea_io_home::home())?;
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut over = false;
for net in networks {
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
let w = pages::write(net, &name, &script, &out, orientation)?;
let ok = w.bytes <= pages::CAP;
over |= !ok;
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
}
if over {
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
return Err(report.join("\n"));
}
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
Ok(report.join("\n"))
}
+104
View File
@@ -0,0 +1,104 @@
//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files
//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts,
//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw.
use super::R;
use serde_json::Value;
use std::path::Path;
/// One composition the game registers
pub struct Comp {
pub id: String,
pub width: u32,
pub height: u32,
pub fps: f64,
pub frames: u64,
}
/// What the lint found: refusals stop the export, notes don't
pub struct Found {
pub comps: Vec<Comp>,
pub kinds: Vec<String>,
pub notes: Vec<String>,
pub refusals: Vec<String>,
}
const SOURCE_RULES: &[(&str, &str)] = &[
(r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"),
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
];
/// The game's source and its compositions, judged
pub fn lint(game: &Path) -> R<Found> {
let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
let mut refusals = Vec::new();
let mut notes = Vec::new();
// a URL the SVG namespace names is a name, not a request
let src_no_ns = src.replace("http://www.w3.org", "");
for (re, why) in SOURCE_RULES {
if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
refusals.push(why.to_string());
}
}
if !src.contains("raea/playable") {
notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
}
let walked = match walk(game) {
Ok(w) => w,
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
Err(e) => return Err(e),
};
let comps: Vec<Comp> = walked["comps"]
.as_array()
.into_iter()
.flatten()
.map(|c| Comp {
id: c["id"].as_str().unwrap_or("").into(),
width: c["width"].as_u64().unwrap_or(0) as u32,
height: c["height"].as_u64().unwrap_or(0) as u32,
fps: c["fps"].as_f64().unwrap_or(30.0),
frames: c["frames"].as_u64().unwrap_or(0),
})
.collect();
let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
if comps.is_empty() {
refusals.push("no composition registered (registerRoot)".into());
}
if comps.len() == 1 {
notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
}
for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
}
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
}
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
/// out of this one; its answer is the JSON it prints
fn walk(game: &Path) -> R<Value> {
let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
if !walk.is_file() {
return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
}
let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
let entry = work.join("lint.ts");
std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
let _ = std::fs::remove_dir_all(&work);
let run = run?;
let out = String::from_utf8_lossy(&run.stdout);
if !run.status.success() {
let err = String::from_utf8_lossy(&run.stderr);
let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
// the line that names the error, else the last one ("… ended with exit 1" says nothing)
let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
return Err(format!("the game didn't render for the lint: {why}"));
}
let at = out.find('{').ok_or("the lint's walk printed no answer")?;
serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
}
+100
View File
@@ -0,0 +1,100 @@
//! Each network's package around the one script (docs/playables.feature, the Background's table): the page every
//! network gets, with that network's own tags, as one HTML file or a ZIP, checked against its cap.
use super::R;
use std::io::Write;
use std::path::{Path, PathBuf};
pub const NETWORKS: &[&str] = &["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff", "preview"];
/// Every network's cap, 5 MB (TikTok's counted zipped, which is what's written)
pub const CAP: u64 = 5 * 1024 * 1024;
/// What one network got: the file and its size
pub struct Written {
pub network: String,
pub file: PathBuf,
pub bytes: u64,
}
/// The settings a page starts with, as the globals the host reads (sdk/playable network.ts, host/main.tsx): the network,
/// the store links, the end card's words
pub fn preamble(network: &str, store: &str, card: &str) -> String {
format!("var __RAEA_NETWORK__={},__RAEA_STORE__={store},__RAEA_PLAYABLE__={card};", serde_json::to_string(network).unwrap_or_default())
}
/// The page: the network's head and body tags, then the script (a page's inline script ends at the first "</script")
pub fn page(title: &str, head: &str, body: &str, script: &str) -> String {
let title = title.replace('&', "&amp;").replace('<', "&lt;");
format!(
"<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n<title>{title}</title>\n{head}\n</head>\n<body>\n{body}\n<script>\n{}\n</script>\n</body>\n</html>\n",
script.replace("</script", "<\\/script")
)
}
fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
let f = std::fs::File::create(file).map_err(|e| format!("{}: {e}", file.display()))?;
let mut w = zip::ZipWriter::new(f);
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
for (name, text) in entries {
w.start_file(name.as_str(), o).map_err(|e| e.to_string())?;
w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
}
w.finish().map_err(|e| e.to_string())?;
Ok(())
}
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
let html = |head: &str, body: &str| page(name, head, body, script);
let file = match network {
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
"google" => {
let o = if orientation == "both" { "portrait,landscape" } else { orientation };
let head = format!("<meta name=\"ad.orientation\" content=\"{o}\">\n<script type=\"text/javascript\" src=\"https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js\"></script>");
let f = out.join(format!("{name}-google.zip"));
zip(&f, &[("index.html".into(), html(&head, ""))])?;
f
}
// a ZIP with index.html and config.json; TikTok's playable SDK before the game's script (TikTok Ads help)
"tiktok" => {
let o = match orientation {
"portrait" => 1,
"landscape" => 2,
_ => 0,
};
let body = "<script src=\"https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js\"></script>";
let f = out.join(format!("{name}-tiktok.zip"));
zip(&f, &[("index.html".into(), html("", body)), ("config.json".into(), format!("{{\"playable_orientation\": {o}}}\n"))])?;
f
}
// a ZIP holding a folder and a page of the same name
"mintegral" => {
let f = out.join(format!("{name}-mintegral.zip"));
zip(&f, &[(format!("{name}/{name}.html"), html("", ""))])?;
f
}
// one HTML file, everything inlined; MRAID is injected by the network's webview (Meta: data URIs only)
"applovin" | "unity" | "meta" | "moloco" | "liftoff" | "preview" => {
let f = out.join(format!("{name}-{network}.html"));
std::fs::write(&f, html("", "")).map_err(|e| format!("{}: {e}", f.display()))?;
f
}
other => return Err(format!("raea playable: no network {other} (one of {})", NETWORKS.join(", "))),
};
let bytes = std::fs::metadata(&file).map(|m| m.len()).unwrap_or(0);
Ok(Written { network: network.into(), file, bytes })
}
#[cfg(test)]
mod tests {
#[test]
fn a_script_cannot_end_its_page_early() {
let p = super::page("t", "", "", "a('</script>')");
assert_eq!(p.matches("</script").count(), 1, "{p}");
}
#[test]
fn the_preamble_names_the_network_as_a_string() {
assert_eq!(super::preamble("applovin", "{}", "{}"), "var __RAEA_NETWORK__=\"applovin\",__RAEA_STORE__={},__RAEA_PLAYABLE__={};");
}
}
+9 -3
View File
@@ -21,8 +21,10 @@ struct Hook {
fn hooks(agent: &str) -> R<Vec<Hook>> {
let h = |event, matcher, secs| Hook { event, matcher, secs };
Ok(match agent {
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30)],
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
// SessionStart and UserPromptSubmit: notes sent from raea while the session was closed or idle reach it when it
// starts again or is next written to (Shane 11-28: "notes reach closed sessions")
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
"gemini" => vec![h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
"kimi" => vec![h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
@@ -124,7 +126,8 @@ mod tests {
let c = d.join("claude/settings.json");
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().unwrap();
let [pre, post, stop, start, prompt] = <[Hook; 5]>::try_from(hooks("claude").unwrap()).ok().unwrap();
assert!(add_json(&c, "claude", &start).unwrap() && add_json(&c, "claude", &prompt).unwrap() && !add_json(&c, "claude", &start).unwrap());
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
assert!(add_json(&c, "claude", &post).unwrap() && !add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook is widened to every tool, once");
assert!(add_json(&c, "claude", &stop).unwrap() && !add_json(&c, "claude", &stop).unwrap());
@@ -133,6 +136,9 @@ mod tests {
assert_eq!((v["hooks"]["PostToolUse"][0]["matcher"].as_str(), v["hooks"]["PostToolUse"][1]["matcher"].as_str()), (Some("Bash"), Some("*")));
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["SessionStart"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(hooks("codex").unwrap().iter().map(|h| h.event).collect::<Vec<_>>(), ["PreToolUse", "PostToolUse", "Stop", "SessionStart", "UserPromptSubmit"]);
let g = d.join("gemini/settings.json");
let [before, _] = <[Hook; 2]>::try_from(hooks("gemini").unwrap()).ok().unwrap();
assert!(add_json(&g, "gemini", &before).unwrap());
+1 -1
View File
@@ -16,7 +16,7 @@ mkdir -p "$OUT"
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
expected() { case $1 in
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
examples/playables/brick-rush.tsx) echo "a playable: it needs the playable host's raea_playable (sdk/playable)" ;;
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
esac; }
SAME=0 DIFF=0 ERR=0 SKIP=0
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea app"
summary: "Run, check headless and package a desktop app written as one TSX file on @raea/ui."
order: 7
order: 8
sources: ["engine/cli/src/cli.rs", "engine/rune/src/main.rs"]
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea bundle"
summary: "Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone."
order: 6
order: 7
sources: ["engine/cli/src/cli.rs", "runtime/bundle/src/lib.rs"]
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea export"
summary: "The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them."
order: 5
order: 6
sources: ["engine/cli/src/cli.rs"]
---
+1
View File
@@ -35,6 +35,7 @@ Render, play and package what you wrote.
| [`raea render`](render.md) | Render a composition to an MP4, a PNG or a folder of frames, on the GPU and headless. |
| [`raea play`](play.md) | Play a game live in a window, or headless with scripted keys, snapshots and a timing report. |
| [`raea export-game`](export-game.md) | Package a game as a program of its own: a Mac app or a command-line program. |
| [`raea playable`](playable.md) | Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad. |
| [`raea export`](export.md) | The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them. |
| [`raea bundle`](bundle.md) | Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone. |
| [`raea app`](app.md) | Run, check headless and package a desktop app written as one TSX file on @raea/ui. |
+48
View File
@@ -0,0 +1,48 @@
---
title: "raea playable"
summary: "Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad."
order: 5
sources: ["apps/playable/src/lib.rs"]
---
`raea playable` turns a raea game into a playable ad: a short game served in place of a video ad inside other apps,
ending on a card that opens the store. The same file renders with `raea render` as the video ad, because a game that
nobody touches plays itself. Each network gets the page or ZIP it takes, with its own start, pause and store calls,
checked against its 5 MB cap. Nothing in the page loads anything: pictures, sounds and the 3D renderer travel inside it.
```sh
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
raea playable game.tsx -o out/playable --networks applovin,google,preview --cta "Play free"
```
Before it bundles, the export refuses what a playable can't have: files read from disk at render time (`staticFile`;
import the file instead), URLs and network calls, modules that need the native engine, `<Video>` and `<Audio>`, and 3D
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
project (`raea add [email protected]`).
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## Usage
```sh
raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
## Flags
| Flag | Takes | What it does |
| --- | --- | --- |
| `--android` | `URL` | The Google Play page the store tap opens on Android. |
| `--cta` | `TEXT` | The button's words on the host's own end card, `Play now` by default. A game's `<EndCard cta>` sets its own. |
| `--ios` | `URL` | The App Store page the store tap opens on iPhone and iPad. |
| `--networks` | `LIST` | The networks to write, split by commas: `applovin`, `unity`, `google`, `meta`, `moloco`, `mintegral`, `tiktok`, `liftoff`, `preview`. All of them by default. |
| `--orientation` | `portrait\|landscape\|both` | What Google's `ad.orientation` tag and TikTok's `config.json` are told; `both` by default. The game plays whichever of its compositions is nearest the screen's shape either way. |
| `--title` | `TEXT` | The title on the host's own end card, shown at the last frame when the game never shows an `<EndCard>`. |
| `-o` | `DIR` | The folder the pages and ZIPs go in, named GAME-NETWORK.html or .zip. |
<!-- generated:end -->
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea run"
summary: "Run a TypeScript program on the engine, headless, and print what it prints."
order: 8
order: 9
sources: ["engine/cli/src/cli.rs"]
---
+1 -1
View File
@@ -51,7 +51,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage
```sh
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
```
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
+244
View File
@@ -0,0 +1,244 @@
@spec
Feature: raea games as playable ads, exported for every ad network from the TSX that renders the video ad
Shane, 2026-10-29: "lets build a playables feature and explore how we can optimize or help raea agents build for
playables specifically as well as explore the export options included with it". A playable ad is a 15-60 second
mini-game served in place of a video ad, inside other apps' WebViews; it ends on a card that opens the store. Bevy
stays the engine for games (docs/web-export.md is raea's own web build); a playable is an export of a game, drawn by
a light web renderer on the same scene contract, because Bevy's renderer doesn't fit an ad (PA0b). The code is
sdk/playable (raea/playable for authors, the browser host, the export tools); the example is
examples/playables/brick-rush.tsx.
Background:
Given the networks that take advertiser playables in 2026, read from each network's own spec on 10-29
| network | package | cap | install call | also |
| AppLovin | one HTML, all inlined (base64/122) | 5 MB | mraid.open(url) | MRAID 2.0; timer starts at the first touch |
| Unity Ads | one index.html, inlined, minified | 5 MB | mraid.open(url) | MRAID 3.0 injected by the webview; start on ready + viewable, pause when not; both orientations |
| Google | ZIP, index.html, at most 512 files | 5 MB | ExitApi.exit() | exitapi.js and <meta name="ad.orientation"> in the head; billed per engagement |
| Meta | one HTML with data URIs, or ZIP | 5 MB | FbPlayableAd.onCTAClick() | no mraid.js; ZIP at most 100 files (blogs that say 2 MB are out of date) |
| Moloco | one HTML with data URIs, no ZIP | 5 MB | FbPlayableAd.onCTAClick() | mraid.js banned |
| Mintegral | ZIP: a folder and a page of one name | 5 MB | window.install() | gameReady() when loaded, gameStart from the network, gameEnd() when over |
| TikTok | ZIP, index.html + config.json | 5 MB zipped | window.openAppStore() | their playable-sdk.js before the game's script; {"playable_orientation": 0/1/2}; no mraid.js |
| Liftoff | one HTML, or ZIP with one folder | 5 MB | Liftoff.open() | relative paths only |
And every network refuses a network request, a redirect without a tap, and sound before the first touch
And ironSource's own network closed on 2026-04-30 (its traffic is Unity LevelPlay's)
Rule: Settled questions
Scenario: PA0a. What a raea playable is
Given a game written as any raea game is: React TSX, its state a pure fold of input (useGameState), its 3D the
SDK's components (which render data-3d elements, the contract the native engine reads)
Then the same file renders with `raea render` as the video ad (no one touches it, so it plays itself) and exports
with `raea playable` as a playable for each network
And it imports raea/playable for the store: <EndCard show={over}> when the game is over, <InstallButton> anywhere,
or install() from a tap; outside an export install() does nothing
And it registers a portrait and a landscape composition when it can (the host plays the one nearest the screen;
a single one is letterboxed, and Unity, AppLovin, Moloco and Mintegral want both)
Scenario: PA0b. Bevy's renderer stays out of ads; a light web renderer draws them (measured 10-29)
Given brick-rush's scene (24 cuboids, paddle, ball, a shadowed directional light) in plain Bevy 0.20 for
wasm32 (opt-level z, fat LTO, wasm-opt -Oz), next to the three.js export of the same game
| build | wasm | one HTML (base64) | zipped |
| Bevy, default features | 23.3 MB | 31.3 MB | 7.4 MB |
| Bevy, the features raea-render turns on | 21.5 MB | 28.7 MB | 6.9 MB |
| Bevy, only what the scene needs (WebGL2) | 12.3 MB | 16.5 MB | 3.7 MB |
| Bevy, only what the scene needs (WebGPU) | 10.8 MB | 14.6 MB | 3.1 MB |
| Bevy logic only (App, ECS, Transform; no renderer) | 0.55 MB | 0.74 MB | 0.2 MB |
| sdk/playable: React + three.js + the game | - | 0.79 MB | 0.22 MB |
And stored gzipped inside the page (DecompressionStream, in every WebView since 2023) the stripped WebGL2 build
is 4.99 MB as base64: under 5 MB with nothing left for raea's own crates, the game or its assets (brotli: 3.4 MB,
but older WebViews can't decompress brotli)
And first frame served from localhost: Bevy 1.9 s, three.js 0.66 s; at 4x CPU throttle 3.2 s and 1.5 s
Then the renderer (wgpu, naga, bevy_pbr) is about 95% of Bevy on the web: logic alone is small
And the industry does the same: Unity Playworks (ex-Luna) never ships Unity's WebGL build; it converts the game's
C# to JavaScript and runs it on its own ~650 KB playable engine; PlayCanvas's engine is ~1.2 MB
And so a playable is drawn by a light WebGL2 renderer on raea's scene contract, its look held to the native
engine's by a parity check (PA9), its shading moving toward Bevy's own (PA10, PA11); Bevy's logic may come along
as wasm (PA12); Bevy wasm stays the path for raea's uncapped web export (docs/web-export.md)
And WebGPU is on by default in iOS 26's WKWebView and reported in Android WebView, but a playable targets WebGL2
for reach
Rule: Built 10-29
@done
Scenario: PA1. The browser host
Then sdk/playable/src/host/main.tsx mounts the registered composition nearest the screen's shape on a stage
scaled uniformly into the screen, steps a Clock 1/fps at a time off requestAnimationFrame with the person's
input recorded per frame as live entries (input.ts: keys, the primary pointer, every finger, in composition
px), and draws the page's data-3d parts with three.js under the page (scene.ts), the page's background behind
the 3D becoming its clear colour
And it starts when the network says the ad is viewable, pauses while it isn't, stops stepping when the game's
EndCard shows, and at the composition's last frame shows its own EndCard
And the status: brick-rush plays in headless mobile Chrome in portrait and landscape; a drag moves the paddle; three
misses show "So close!"; a tap on the card fires end then install (tools/check.ts, PLAY_SECONDS=25)
@done
Scenario: PA2. Each network's start, pause, store and end calls
Then sdk/playable/src/network.ts is built with the network's name (__RAEA_NETWORK__) and the store links, and maps
whenReady, install and end onto the table in the Background (MRAID's ready/viewableChange; Mintegral's
gameReady, gameStart, gameEnd; the store call per network; preview does nothing)
@done
Scenario: PA3. raea/playable for authors
Then install(), end(), <EndCard> (the whole card opens the store; end() when it first shows) and <InstallButton>,
plain page elements, so a native render draws them as the playable does
@done
Scenario: PA4. The lint: what a playable can't have, refused before it is bundled
Then `raea playable` (apps/playable lint.rs, with sdk/playable/src/export/walk.ts run by `raea run`) renders each
composition at 12 frames through its length and refuses a 3D kind the host doesn't draw (PLAYABLE_KINDS in
host/kinds.ts), staticFile, URLs, fetch/XHR/WebSocket, modules that need
the native engine, and <Video>/<Audio> until PA6; it notes a missing raea/playable import and a single
orientation
@done
Scenario: PA5. One export, every network's package
Then `raea playable GAME.tsx -o DIR [--networks ...] [--ios URL] [--android URL] [--title T] [--cta T]
[--orientation O]` lints, bundles one minified script (PA13) and writes each network's page or ZIP, its settings
in a preamble before the script, checked against its cap
And the status: brick-rush exports for all nine targets (eight networks and preview) at 916 KB per HTML and 292 KB
per ZIP (786 and 218 before PA10's tone-mapping table)
@done
Scenario: PA7. A playable played as a phone shows it
Then sdk/playable/tools/check.ts PAGE.html OUT [WxH] opens it at a phone's size with touch (WebKit since PA7b),
drags across it, saves screenshots, reads the console and the ad events back, and fails on an exception or a
network request; CPU_THROTTLE=4 for a slow phone, PLAY_SECONDS to play to the end and tap the card
Rule: Made viable again 11-28
The 11-06 public-first squash took raea/playable and @raea/playable out of the public sdk/tsconfig.base.json (as it
did raea/body and raea/gen), so every export failed at the lint with "Cannot find module 'raea/playable'"
@done
Scenario: PA4b. The tools resolve the SDK's names themselves
Then sdk/playable/tools/alias.ts resolves raea, raea/<module> and @raea/<package> from sdk/tsconfig.base.json's
paths as engine/bundle's script.rs does, plus raea/playable and @raea/playable/*, as a Bun plugin for the bundle
And the lint's walk (tools/walk.ts) runs bundled after the game instead of imported by Bun's runtime, whose own
tsconfig paths ("raea/*") catch raea/playable before any plugin
And a game's own components in a project with no SDK tsconfig bundle as they render (mobile-ads' gates did not)
And the status 11-28: brick-rush exports for all nine targets (1,431 KB per HTML, 471 KB per ZIP); mobile-ads'
tiles (1,393 KB) and gates (1,395 KB) export for AppLovin, Google and preview
@done
Scenario: PA7b. The check plays in WebKit
Given iOS ad WebViews are WebKit, and raea doesn't test in Chrome (Shane 11-15)
Then tools/check.ts plays the page in Playwright's WebKit (playwright-core 1.64.1, the app's version) at a phone's
size with real pointer input held over frames, fails on an exception, a network request, an empty page, or an
end-card tap with no install event; parity.ts draws its still in WebKit too, and tools/chrome.ts is gone
And a network's own page tags (Google's exitapi.js, TikTok's playable-sdk.js) are stopped but not failed: the ad
view serves them
And the status 11-28: brick-rush, tiles and gates play to their end cards, events ["end","install"], no requests
Rule: Next
Scenario: PA6. Sound in a playable
Given networks keep sound off until the first touch and most players never turn it on
Then raea/tone's instruments and the export's generated foley (TokenSynth, SAO) play through Web Audio from data
URLs after input.onFirstTouch, inside the size budget
Scenario: PA8. Fonts inlined
Given brick-rush's page asks for Inter, which a phone doesn't have (it fell back to a serif in the first check)
Then the export inlines the subset of each font the page uses, as the native render draws it
@done @needs:PA1
Scenario: PA9. The playable is held to the native render
Then a parity check renders the same composition frame with `raea render` and in the playable host (headless
Chrome, scripted input none, so both play themselves), and compares the 3D's colours where both drew a part
And it fails when they drift past a bar, so the light renderer can't quietly lose the look
And the status: sdk/playable/tools/parity.ts GAME.tsx COMPOSITION FRAME OUT [BAR] renders the frame with `raea render
--frame`, opens a preview build at the composition's size with #still=FRAME&comp=ID (the host draws that one frame
and stops), and compares the pixels the native frame drew over its background: coverage, mean colours, brightness
and mean difference (0-255), exiting 1 over BAR (default 16); native.png, playable.png and diff.png are kept
@done @needs:PA9
Scenario: PA10. The lighting conversion
Given the SDK's 3D layer hands lights to the renderer in its own units (r3f intensities converted from Bevy's lux,
lumens and cd/m²) and Bevy draws with its camera exposure and TonyMcMapface tone mapping
Then the host converts them so PA9's colours match
And the status: host/scene.ts turns the SDK's intensities back into Bevy's units (lux 8000, lumens 9e5 over 4π,
ambient 400 × π) times Bevy's camera exposure (1 / (1.2 · 2^9.7)); host/tonemap.ts draws the 3D into a half-float
target and maps it through TonyMcMapface, Bevy's own 48³ table (tools/tony.ts reads bevy_core_pipeline's ktx2)
resampled to 32³ sRGB bytes (98 KB; the 48³ table scored 5.3 for 311 KB more), sampled as tonemapping.wesl does;
where nothing was drawn it stays transparent over the page's own background
And the numbers on brick-rush (mean difference / 255, brightness): portrait frame 90 went from 50.2 and 0.688x
(three.js's units, no exposure) to 5.4 and 0.992x; landscape frame 300 is 9.1 and 0.971x. three.js's built-in
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
the shading itself (the bricks' side faces a touch darker), PA11's job
@needs:PA9
Scenario: PA11. Bevy's own shading in the light renderer
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
export time, and the light renderer draws with them instead of three.js's own materials
And the 10-29 trial: Bevy 0.20's shaders are WESL, composed by bevy_shader with wesl 0.6 (defs as feature flags,
Int/UInt defs in a virtual `constants` package, `bevy_pbr/bevy_core_pipeline` folded to `bevy_core_pipeline`). A
standalone program doing the same over the registry sources, then naga 30 (validate, GLSL ES 3.00 for WebGL),
with WebGL2's defs (WEBGL2, NO_ARRAY_TEXTURES_SUPPORT, NO_CUBE_ARRAY_TEXTURES_SUPPORT, SIXTEEN_BYTE_ALIGNMENT,
AVAILABLE_STORAGE_BUFFER_BINDINGS=0, MAX_CASCADES_PER_LIGHT=1, PER_OBJECT_BUFFER_BATCH_SIZE=93 for the 176-byte
Mesh in 16 KB) and the mesh pipeline's for a plain forward StandardMaterial mesh with TonyMcMapface in the shader:
| shader | GLSL ES 3.00 | gzip | in Chrome's WebGL2 |
| bevy_pbr::render::pbr frag | 1,703 lines, 88 KB | 16 KB | compiles (29 ms) |
| bevy_pbr::render::mesh vert | 175 lines, 6.8 KB | 1.7 KB| compiles; the pair links (551 ms) |
| bevy_pbr::prepass (shadows) | 150 lines, 5.5 KB, vertex | | translated, not linked yet |
And what that leaves: nothing has been drawn with them. The program binds 7 textures (4 material maps, the point
and directional shadow maps, the Tony LUT) and 11 uniform blocks the host would fill as Bevy's render world does:
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
Scenario: PA12. Bevy systems in a playable
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b)
Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the
playable, its world drawn by the light renderer
@done
Scenario: PA13. `raea playable`
Then the export is a raea CLI verb (apps/playable) on raea's own bundler, in process: engine/bundle gained
`minify` (Rolldown's minifier), `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, a .bin as a
Uint8Array) and package-folder aliases (`--alias three/=DIR`, three.js from the project's node_modules, else
raea's own)
And the lint's walk runs as `raea run` in a process of its own; tools/playable.sh, bundle.ts, lint.ts, walk.ts,
alias.ts and chrome.ts are gone, and Bun is needed only for check.ts, parity.ts and tony.ts
And the status 11-28: brick-rush writes all nine targets in 7 s (1,384 KB per HTML, 464 KB per ZIP), mobile-ads'
tiles (1,345 KB) and gates (1,347 KB) export, and all play in WebKit, the Google and TikTok packages included;
a game with staticFile is refused with the reason first
And fonts travel as pictures do: an imported .ttf, .otf, .woff or .woff2 is its path in a native render and a data
URL in a playable, named in an @font-face; <EndCard> takes font, color and button for a brand's own card
Scenario: PA14. Agents writing playables
Then the raea skill says how a playable is shaped (hook, a hand until the first touch, a fail moment, the end card
within 30-60 s, both orientations), what the lint refuses, and how to check one (tools/check.ts)
And the guide is sdk/guides/craft/motion/playable.md (`raea guide playable`, copied into the skill's motion/), and
SKILL.md routes "a playable ad" to it
Scenario: PA15. A 2D playable carries no three.js
Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D
Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page)
Scenario: PA16. Playables in the review (raea cloud and the desktop)
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
in raea cloud and in desktop v3, and a playable is one HTML page that loads nothing
Then a "playable" kind is drawn by that player: the preview page in a sandboxed iframe (allow-scripts only) inside
a phone frame, portrait and landscape, restarted from the stage's own button
And the host's ad events (ready, viewable, end, install) show beside it, so a reviewer sees the store tap fire
And each network's package, its size against the cap, is a download under it, and pins and notes work as on a video
And `raea show GAME.tsx --playable` exports the preview and shows it as that kind (`raea show PAGE.html` for a page
already exported); host/show.ts refuses .html today
# Status 11-28: built. Cloud: raea-platform #99 (merged into #97's oux-audit-1128) and #101: the playable kind
# (a delivered .html), its 9:16 card, the phone either way up with Restart, the events (ready, viewable,
# hidden, first touch, end card, store opened), and the network packages folded under it as downloads, red
# past 5 MB. Shane 11-28: the page plays on a domain of its own: play.raea.io, live 11-28 (#105, #106:
# PLAY_HOST, harness/play.ts: sandbox allow-scripts, 'wasm-unsafe-eval', network off, no-transform, framed by
# app.raea.cloud, api.raea.cloud and the desktop's local port). Checked live: the ACANA export uploaded, played
# from play.raea.io in a sandboxed frame in WebKit, ready and touch posted, the bytes as exported.
# Desktop: raea-feed #124: `raea show PAGE.html` posts a play item with a page, /host/playable serves it under
# the same policy, Playable.tsx draws it with pins. `raea show GAME.tsx --playable` exports the preview first
# (engine/cli show.ts, native.ts). Checked: the real ACANA export served under the policy runs clean in WebKit.
Scenario: PA17. Video ad and playable side by side
Then one shown game is both: its `raea render` (the video ad, played by its own hand) and its playable, one
project in the review, so a creative test brief gets both formats from one file
Scenario: PA18. brick-rush plays live in the native engine
Given bench/live-3d/corpus.sh skips brick-rush: under RAEA_LIVE3D_CHECK it panics on frame 1, because the fast
rows (runtime/scene/src/live.rs) carry the sun's rotation and the full rows don't
Then the fast and full rows agree on a light's transform, and brick-rush plays live and leaves the corpus's skips
+2
View File
@@ -20,6 +20,8 @@ rolldown = "=1.2.12"
# CSS imports and CSS modules (A2): @imports inlined, nesting and newer syntax lowered for Stylo
lightningcss = { version = "=1.0.0-alpha.72", features = ["bundler"] }
anyhow = "1"
# imported files carried in a playable's script as data (inline.rs)
base64 = "0.22"
# the Z3 compile (z3.rs, a live bundle's TSX): oxc as Rolldown 1.2.12 uses it
oxc = { version = "=0.152.0", features = ["transformer", "codegen", "semantic", "ast_visit"] }
tokio = { version = "1", features = ["rt-multi-thread"] }
+72
View File
@@ -0,0 +1,72 @@
//! A bundle that carries its files (docs/playables.feature PA13): a picture, sound or model a module imports becomes a
//! data URL in the script, and a `.bin` table its bytes, so the one page loads nothing (an ad network refuses a page
//! that makes a request). Ahead of the script resolver, which otherwise hands media back as their paths.
use rolldown_common::ModuleType;
use rolldown_plugin::{HookLoadArgs, HookLoadOutput, HookLoadReturn, HookUsage, Plugin, SharedLoadPluginContext};
use std::borrow::Cow;
use std::path::Path;
/// The files carried, by extension, with their media type
const TYPES: &[(&str, &str)] = &[
("png", "image/png"),
("jpg", "image/jpeg"),
("jpeg", "image/jpeg"),
("webp", "image/webp"),
("gif", "image/gif"),
("svg", "image/svg+xml"),
("mp3", "audio/mpeg"),
("m4a", "audio/mp4"),
("ogg", "audio/ogg"),
("wav", "audio/wav"),
("glb", "model/gltf-binary"),
("woff2", "font/woff2"),
("woff", "font/woff"),
("ttf", "font/ttf"),
("otf", "font/otf"),
];
#[derive(Debug)]
pub struct Inline;
/// Standard base64, padded (the base64 crate, as raea's other crates use it)
pub fn base64(bytes: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(bytes)
}
impl Plugin for Inline {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("raea:inline")
}
fn register_hook_usage(&self) -> HookUsage {
HookUsage::Load
}
async fn load(&self, _ctx: SharedLoadPluginContext, args: &HookLoadArgs<'_>) -> HookLoadReturn {
let path = args.id.split(['?', '#']).next().unwrap_or(args.id);
let Some(ext) = Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase) else { return Ok(None) };
let code = if ext == "bin" {
let b = std::fs::read(path)?;
format!("export default Uint8Array.from(atob({:?}), (c) => c.charCodeAt(0));\n", base64(&b))
} else if let Some((_, mime)) = TYPES.iter().find(|(e, _)| *e == ext) {
let b = std::fs::read(path)?;
format!("export default {:?};\n", format!("data:{mime};base64,{}", base64(&b)))
} else {
return Ok(None);
};
Ok(Some(HookLoadOutput { code: code.into(), module_type: Some(ModuleType::Js), ..Default::default() }))
}
}
#[cfg(test)]
mod tests {
#[test]
fn base64_pads_as_the_standard_does() {
assert_eq!(super::base64(b""), "");
assert_eq!(super::base64(b"f"), "Zg==");
assert_eq!(super::base64(b"fo"), "Zm8=");
assert_eq!(super::base64(b"foo"), "Zm9v");
assert_eq!(super::base64(b"foobar"), "Zm9vYmFy");
}
}
+12 -2
View File
@@ -16,6 +16,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
pub mod edit;
pub mod inline;
pub mod script;
pub mod stamp;
pub mod z3;
@@ -41,6 +42,10 @@ pub struct Options {
pub edit: Option<edit::Edit>,
/// each element the edit's own files write stamped with its place in the code (stamp.rs; the app's editor asks)
pub stamps: bool,
/// minified (a playable's page, which ad networks cap at 5 MB)
pub minify: bool,
/// imported pictures, sounds, models and .bin tables carried in the script (inline.rs), not named by path
pub inline: bool,
}
/// `entry` bundled into one browser script and its CSS.
@@ -61,6 +66,7 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
// no `//#region <path>` before each module: its path names the work folder (raea-motion-b<pid>), so every
// process's bundle differed and the incremental bake saw every function change (lightspeed T3)
experimental: Some(ExperimentalOptions { attach_debug_info: Some(AttachDebugInfo::None), ..Default::default() }),
minify: o.minify.then_some(rolldown_common::RawMinifyOptions::Bool(true)),
..Default::default()
};
let stamps = if o.stamps {
@@ -84,6 +90,9 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
s.spawn(move || {
rt.block_on(async move {
let mut plugins = vec![Pluginable::new_shared(css)];
if o.inline {
plugins.push(Pluginable::new_shared(inline::Inline));
}
if let Some(s) = stamps {
plugins.push(Pluginable::new_shared(s));
}
@@ -320,7 +329,7 @@ pub mod ffi {
1
}
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool}); returns JSON, {"js","css"} or {"error"}, to
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool, "minify": bool, "inline": bool}); returns JSON, {"js","css"} or {"error"}, to
/// be freed with raea_bundle_free
///
/// # Safety
@@ -344,7 +353,8 @@ pub mod ffi {
js: path(&e["js"]),
work: std::path::absolute(&entry).ok().and_then(|p| p.parent().map(|d| d.to_path_buf())).unwrap_or_default(),
});
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false) };
let (minify, inline) = (opts["minify"].as_bool().unwrap_or(false), opts["inline"].as_bool().unwrap_or(false));
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false), minify, inline };
match super::bundle_with(std::path::Path::new(&entry), o) {
Ok(b) => serde_json::json!({"js": b.js, "css": b.css}),
Err(e) => serde_json::json!({"error": e}),
+14 -4
View File
@@ -23,7 +23,8 @@ pub struct Script {
pub motion: PathBuf,
/// sdk/shell/src/index.ts
pub shell: PathBuf,
/// `--alias SPEC=PATH`
/// `--alias SPEC=PATH`; a SPEC ending in `/` (`three/=DIR`) is a package and every subpath of it, resolved from DIR
/// (a folder whose node_modules holds it) wherever it's imported, so the bundle has one copy
pub aliases: HashMap<String, PathBuf>,
/// `--node-stub a,b`
pub stubs: Vec<String>,
@@ -36,8 +37,9 @@ const NODE: &[&str] = &[
];
const STUB: &str = "\0raea-node-stub:";
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models.
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models and fonts
/// (an @font-face's url(), so a playable can carry the same font: inline.rs).
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
#[derive(Debug)]
@@ -46,7 +48,12 @@ pub struct ScriptResolve(pub Script);
impl ScriptResolve {
/// `spec` as the engine's node_modules resolves it (Rolldown's resolver, from a file in sdk/react/js)
async fn from_engine(&self, ctx: &PluginContext, spec: &str) -> anyhow::Result<Option<HookResolveIdOutput>> {
let importer = self.0.js.join("_raea.js");
self.from_dir(ctx, spec, &self.0.js).await
}
/// `spec` as `dir`'s node_modules resolves it
async fn from_dir(&self, ctx: &PluginContext, spec: &str, dir: &Path) -> anyhow::Result<Option<HookResolveIdOutput>> {
let importer = dir.join("_raea.js");
let opts = rolldown_plugin::PluginContextResolveOptions { skip_self: true, ..Default::default() };
match ctx.resolve(spec, Some(&importer.to_string_lossy()), Some(opts)).await? {
Ok(r) => Ok(Some(HookResolveIdOutput::from_id(r.id.as_str()))),
@@ -84,6 +91,9 @@ impl Plugin for ScriptResolve {
if let Some(p) = s.aliases.get(spec) {
return Ok(path_id(p));
}
if let Some((_, dir)) = s.aliases.iter().find(|(k, _)| k.strip_suffix('/').is_some_and(|pkg| spec == pkg || spec.starts_with(k.as_str()))) {
return self.from_dir(ctx, spec, dir).await;
}
match spec {
"bun:test" | "vitest" | "@jest/globals" => return Ok(path_id(&s.js.join("shims/test.ts"))),
"@raea/shell" => return Ok(path_id(&s.shell)),
+2 -2
View File
@@ -133,7 +133,7 @@ import { version } from "react";
aliases: [("~lib".to_string(), d.join("lib/aliased.ts"))].into_iter().collect(),
stubs: vec!["fs".into()],
};
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false };
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false, ..Default::default() };
let b = raea_bundle::bundle_with(&d.join("work/entry.ts"), o).expect("bundles");
for want in ["MOTION_INDEX", "MOTION_ECS", "MOTION_PRELUDE", "TEST_SHIM:", "ZLIB_SHIM", "ALIASED", "ENGINE_REACT", "isn't available in raea's V8", "\"ON\""] {
assert!(b.js.contains(want), "{want} in the bundle: {}", b.js);
@@ -141,7 +141,7 @@ import { version } from "react";
assert!(!b.js.contains("OTHER_REACT"), "one React: the engine's");
// a Node built-in raea doesn't carry, not listed as a stub: the bundle fails, naming it
w("work/bad.ts", "import { createServer } from \"http\";\nconsole.log(createServer);\n");
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false }).expect_err("http isn't carried");
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false, ..Default::default() }).expect_err("http isn't carried");
assert!(e.contains("\"http\" is a Node built-in") && e.contains("--node-stub http"), "{e}");
let _ = std::fs::remove_dir_all(&d);
}
+2
View File
@@ -85,6 +85,8 @@ raea-app-media = { path = "../../apps/media" }
# `raea app run|check|bundle` and `raea rune` on either target (docs/targets.feature T0b)
raea-app-targets = { path = "../../apps/targets" }
raea-app-game = { path = "../../apps/game" }
# `raea playable`: a game as a playable ad for each network (docs/playables.feature PA13)
raea-app-playable = { path = "../../apps/playable" }
raea-app-capcut = { path = "../../apps/capcut" }
raea-app-layers = { path = "../../apps/layers" }
raea-app-play = { path = "../../apps/play", features = ["ml"] }
+72
View File
@@ -110,3 +110,75 @@ describe("labelsIn", () => {
expect(() => labelsIn('{"text":"a"}', "l.json")).toThrow(/--labels l.json is a list of labels/);
});
});
// Shane 11-28: "some things I'm not approving, I'm just acknowledging"; "the agent can go 'let me add a label here'".
// --fyi and --group go to the host (apps/app host/show.ts ShowBody.intent, .groups), which hands them to the review.
describe("raea show --fyi and --group", () => {
const run = (args: string[]) => {
const ops: [string, Record<string, unknown>][] = [];
const ask = (op: string, b: Record<string, unknown>) => {
ops.push([op, b]);
if (op === "harness") return { name: "Claude Code", pid: 7 };
return { kind: "item", id: "i-1", type: "look", title: "Lobby", project: "shop", workspace: "Work", inbox: "/inbox.jsonl" };
};
const out = showVerb(ask, args, "/work/shop", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
return { out, body: ops.find(([op]) => op === "show")?.[1] };
};
test("--fyi sends a look-only show, and says nothing waits on it", () => {
const { out, body } = run(["lobby.png", "--fyi"]);
expect(body).toMatchObject({ intent: "fyi", files: ["/work/shop/lobby.png"] });
expect(out).toContain(`{"kind":"seen"}`);
expect(run(["lobby.png"]).body?.intent).toBeUndefined();
});
test("each --group holds the files after it, titled before the colon and said after it", () => {
const { body } = run(["--group", "Day: sun through the doors", "a.png", "b.png", "--group", "Night", "c.png", "--title", "Lobby"]);
expect(body?.files).toEqual(["/work/shop/a.png", "/work/shop/b.png", "/work/shop/c.png"]);
expect(body?.groups).toEqual([
{ title: "Day", says: "sun through the doors", files: ["/work/shop/a.png", "/work/shop/b.png"] },
{ title: "Night", files: ["/work/shop/c.png"] },
]);
expect(run(["a.png"]).body?.groups).toBeUndefined();
});
test("a group with no files, or --fyi on a question, is refused", () => {
expect(() => run(["a.png", "--group", "Empty"])).toThrow(/has no files/);
expect(() => run(["--group", ": no title", "a.png"])).toThrow(/is a title/);
expect(() => run(["--question", "Which?", "--choice", "A", "--choice", "B", "--fyi"])).toThrow(/--fyi/);
});
});
// --playable exports a game's preview (native.ts playable: raea playable --networks preview) and shows that page, which
// the app plays in a phone (apps/app host/playable.ts, docs/playables.feature PA16)
describe("raea show --playable", () => {
const run = (args: string[]) => {
const ops: [string, Record<string, unknown>][] = [];
const ask = (op: string, b: Record<string, unknown>) => {
ops.push([op, b]);
if (op === "harness") return { name: "Claude Code", pid: 7 };
if (op === "playable") return { page: "/tmp/raea-playable-x/acana-preview.html" };
return { kind: "item", id: "i-1", type: "play", title: "Acana", project: "ads", workspace: "Work", inbox: "/inbox.jsonl" };
};
showVerb(ask, args, "/work/ads", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
return { exported: ops.find(([op]) => op === "playable")?.[1], body: ops.find(([op]) => op === "show")?.[1] };
};
test("the game is exported, and its preview page is what's shown, titled from it", () => {
const { exported, body } = run(["compositions/acana.tsx", "--playable"]);
expect(exported).toMatchObject({ file: "/work/ads/compositions/acana.tsx" });
expect(body).toMatchObject({ files: ["/tmp/raea-playable-x/acana-preview.html"], title: "Acana" });
expect(run(["acana.tsx", "--playable", "--title", "ACANA catch"]).body?.title).toBe("ACANA catch");
});
test("it takes one game's .tsx and nothing else", () => {
expect(() => run(["a.tsx", "b.tsx", "--playable"])).toThrow(/one game's \.tsx/);
expect(() => run(["cut.mp4", "--playable"])).toThrow(/one game's \.tsx/);
});
test("without it a .tsx is shown as it is", () => {
const { exported, body } = run(["picker.tsx"]);
expect(exported).toBeUndefined();
expect(body?.files).toEqual(["/work/ads/picker.tsx"]);
});
});
+5 -5
View File
@@ -134,7 +134,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
let usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
@@ -147,7 +147,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, raea_app_make::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_denoise_bench::USAGE));
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
@@ -228,9 +228,9 @@ pub fn run(args: &[String]) -> R<String> {
// `export capcut EDIT.tsx` (a CapCut draft) and `render ... -o OUT.mov --alpha` (a transparent movie): apps/capcut
if let Some(done) = raea_app_capcut::cli(args, |a| raea_app_sound::render(a).unwrap_or_else(|| raea_runtime_export::render(a))) { return done; }
// `export-game EDIT.tsx -o OUT`: the game as a program of its own (game.rs, sdk/react/docs/game-export.md)
if args.first().map(String::as_str) == Some("export-game") {
return raea_app_game::export(args);
}
if args[0] == "export-game" { return raea_app_game::export(args); }
// `playable GAME.tsx -o DIR`: the game as a playable ad, a page or ZIP per network (apps/playable, docs/playables.feature)
if args[0] == "playable" { return raea_app_playable::cli(args); }
// `add PKG... [--dev] | remove NAME... | install [--offline] [--in DIR]`: npm packages for the project (its
// package.json and raea.lock, a pnpm-style node_modules from one verified store; install scripts never run), which
// a composition, an app screen or a legacy-app panel imports (io/npm)
+14
View File
@@ -416,6 +416,8 @@ const host: Host = (op, a) => {
return library(a);
case "show":
return show(a);
case "playable":
return playable(a as { file: string });
case "clothes":
return clothesHost(raea, cwd, process.env, a);
case "bug":
@@ -445,3 +447,15 @@ const r = await raeaHandler(host, engine)(args, { cwd, fs });
process.stdout.write(r.stdout);
process.stderr.write(r.stderr);
process.exitCode = r.exitCode;
/** `raea show GAME.tsx --playable` (show.ts): the game's preview page, exported by `raea playable` into a folder of its
* own (the show copies it into the app's media) */
function playable(a: { file: string }): { page: string } {
const out = mkdtempSync(`${tmpdir()}/raea-playable-`);
const r = spawnSync(raea, ["playable", a.file, "-o", out, "--networks", "preview"], { encoding: "utf8" });
if (r.status !== 0) throw new Error(`raea playable refused ${basename(a.file)}: ${`${r.stdout ?? ""}${r.stderr ?? ""}`.trim().slice(0, 1200)}`);
const page = readdirSync(out).find((f) => f.endsWith("-preview.html"));
if (!page) throw new Error(`raea playable made no preview page for ${basename(a.file)}`);
return { page: `${out}/${page}` };
}
+38 -7
View File
@@ -23,10 +23,18 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
It lands in the person's feed with a notice and the window stays where they are; --open brings the window up on it
(only when they're waiting on it).
FILE: stills (several make a storyboard), a video, a sound, a NAME.script.ts or .md, or a .tsx (an interactive
artifact; one of the project's compositions opens in its editor). P: Workspace/id (ids as raea workspace --json
artifact; one of the project's compositions opens in its editor), or a playable ad's .html (raea playable's
NAME-preview.html: it plays in a phone, sandboxed). --playable takes a game's .tsx, exports its preview with
\`raea playable\` and shows that page. P: Workspace/id (ids as raea workspace --json
lists them), a folder in the project, or a Copy reference from the app; a title only when it's the only one and
this folder isn't in another project. Else the one this folder is in. Who's showing it: --as NAME [--role ROLE]
[--inbox NAME], else your harness's.
raea show FILE... --fyi
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
raea show FILE... --despite CHECK "why"
A render that still holds an error (raea findings --open lists them) isn't shown: fix it and render again, or say
why it goes anyway, once per check; the person reads the why on the item. One let through at the render (raea render
@@ -50,8 +58,8 @@ raea show FILE... --replaces ITEM --done ID...
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
`;
const WITH_VALUE = new Set(["--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open"]);
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open", "--fyi", "--playable"]);
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
* walks up its parents): any harness, not only the ones that mark their shells. */
@@ -84,6 +92,8 @@ const hash = (s: string) => {
return h.toString(36);
};
const marking = (args: string[]) => args.includes("--working") || args.includes("--done");
export function parseShow(args: string[], cwd: string) {
const one = (name: string) => {
const i = args.lastIndexOf(name);
@@ -95,7 +105,19 @@ export function parseShow(args: string[], cwd: string) {
if (unknown) throw new Error(`no ${unknown} here\n${SHOW_USAGE}`);
const abs = (f: string) => fromCwd(cwd, f);
// --despite takes two: the check, then why
const files = args.filter((a, i) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite").map(abs);
const isFile = (a: string, i: number) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite";
const files = args.filter(isFile).map(abs);
// the groups in order: each --group "Title: what it is" holds the files after it, up to the next --group
const groups: { title: string; says?: string; files: string[] }[] = [];
args.forEach((a, i) => {
if (a === "--group" && args[i + 1] !== undefined) {
const [title, ...rest] = args[i + 1].split(":");
if (!title.trim()) throw new Error(`--group "${args[i + 1]}" is a title, then what it is after a colon: --group "Night: practicals only"\n${SHOW_USAGE}`);
groups.push({ title: title.trim(), ...(rest.join(":").trim() ? { says: rest.join(":").trim() } : {}), files: [] });
} else if (groups.length && isFile(a, i)) groups.at(-1)!.files.push(abs(a));
});
const empty = groups.find((g) => !g.files.length);
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
const despite = args.flatMap((a, i) => {
if (a !== "--despite") return [];
const [check, why] = [args[i + 1], args[i + 2]];
@@ -134,7 +156,8 @@ export function parseShow(args: string[], cwd: string) {
if ((labels.length || args.includes("--labels")) && (!files.length || questions || asked.length)) throw new Error(`labels go on the files you show: raea show FILE --label "PLACE TAG"\n${SHOW_USAGE}`);
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
return { labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
}
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
@@ -189,7 +212,13 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
if (a.done.length && !a.replaces) throw new Error(`--done with files settles comments on the item they replace: add --replaces ITEM\n${SHOW_USAGE}`);
if (a.labelsFile !== undefined && !listed) throw new Error(`--labels ${a.labelsFile}: its labels weren't read (raea's own handler reads the file)`);
const labels = a.labels.length ? a.labels : listed;
const r = ask("show", { ...(labels?.length ? { labels } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
// --playable: the game's preview exported (raea playable --networks preview) and that page shown (docs/playables.feature PA16)
if (a.playable) {
if (a.files.length !== 1 || !/\.tsx$/.test(a.files[0]) || a.question || a.questions) throw new Error(`--playable shows one game's .tsx as its playable: raea show GAME.tsx --playable\n${SHOW_USAGE}`);
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
@@ -213,7 +242,9 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
...settled,
`What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
a.fyi
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
"",
].join("\n");
}
+1 -1
View File
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}");
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
assert!(help.contains(usage), "{usage}");
}
}
+115
View File
@@ -0,0 +1,115 @@
// record: playable-brick-rush
// A playable ad's shape in raea (docs/playables.feature): a hand shows the move until the first touch, the player drags
// the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions
// (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no
// one touches it: the paddle follows the ball, and the same file is the video ad.
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { Sphere } from "raea/3d";
import { LinearRgba, Srgba } from "raea/color";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { AmbientLight, DirectionalLight } from "raea/light";
import { Transform } from "raea/transform";
import { Camera3d } from "raea/camera";
import { EndCard } from "raea/playable";
const FPS = 30;
const COLS = 6, ROWS = 4, LIVES = 3;
const W = 6, TOP = 6; // field: x in [-W/2, W/2], y from 0 (paddle) to TOP
const FOV = 0.733; // radians, vertical
const COLORS = ["#ef476f", "#f78c6b", "#06d6a0", "#118ab2"];
interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" }
const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" };
const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5];
/** The camera's distance that fits the whole field on a screen of this aspect */
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);
/** A pointer's x on screen, in field units at the paddle's depth */
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
if (!input.pointer) return undefined;
const d = distance(width / height);
const halfH = Math.tan(FOV / 2) * d;
return ((input.pointer.x / width) * 2 - 1) * halfH * (width / height);
}
const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
if (s.over) return s;
const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
const want = touched ? fieldX(input, width, height) ?? s.px : s.bx; // before the first touch, the paddle plays itself
const px = Math.max(-W / 2 + 0.7, Math.min(W / 2 - 0.7, s.px + Math.max(-0.35, Math.min(0.35, want - s.px))));
let { bx, by, vx, vy, hit, missed, lives } = s;
bx += vx; by += vy;
if (bx < -W / 2 + 0.12 || bx > W / 2 - 0.12) vx = -vx;
if (by > TOP) vy = -Math.abs(vy);
if (by < 0.15 && by > -0.2 && vy < 0 && Math.abs(bx - px) < 0.8) { vy = Math.abs(vy); vx += (bx - px) * 0.05; hit = frame; }
if (by < -1.2) { lives -= 1; missed = frame; bx = px; by = 0.6; vx = 0.06; vy = 0.1; }
const alive = s.alive.slice(), broke = s.broke.slice();
for (let i = 0; i < alive.length; i++) {
if (!alive[i]) continue;
const [x, y] = brickPos(i);
if (Math.abs(bx - x) < W / COLS / 2 && Math.abs(by - y) < 0.22) { alive[i] = false; broke[i] = frame; vy = -vy; break; }
}
const over = !alive.some(Boolean) ? "won" : lives <= 0 ? "lost" : "";
return { px, bx, by, vx, vy, alive, broke, hit, missed, lives, touched, over };
};
const steps = new Map<string, ReturnType<typeof stepFor>>();
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;
function BrickRush() {
const { width, height } = useVideoConfig();
const g = useGameState(INITIAL, stepOf(width, height));
const now = useCurrentFrame();
const last = g.broke.reduce((m, b) => Math.max(m, b), -99);
const kick = Math.max(0, 1 - (now - last) / 8);
const shake = kick * kick * 0.08 * Math.sin(now * 2.7);
const squash = Math.max(0, 1 - (now - g.hit) / 6);
const flash = Math.max(0, 1 - (now - g.missed) / 12);
const d = distance(width / height);
const s = width / 1080; // page sizes scale with the composition
return (
<AbsoluteFill style={{ background: `rgb(${16 + 90 * flash}, 20, 34)` }}>
<Camera3d transform={Transform.fromXyz(shake, TOP / 2 + shake, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
<AmbientLight brightness={180} />
<DirectionalLight transform={Transform.fromXyz(2, 8, 6).lookingAt([0, 0, 0])} illuminance={9600} shadow_maps_enabled />
<Mesh3d transform={Transform.fromXyz(g.px, 0, 0).withScale([1 + 0.25 * squash, 1 - 0.35 * squash, 1])} name="paddle">
<Cuboid half_size={[0.7, 0.1, 0.2]} />
<StandardMaterial base_color="#f0ebd8" perceptual_roughness={0.4} />
</Mesh3d>
<Mesh3d transform={Transform.fromXyz(g.bx, g.by, 0)} name="ball">
<Sphere radius={0.14} />
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.6)} />
</Mesh3d>
{g.alive.map((on, i) => {
const [x, y] = brickPos(i);
const t = (now - g.broke[i]) / 10;
if (!on && t > 1) return null;
const pop = on ? 1 : 1 + 0.6 * t;
return (
<Mesh3d key={i} transform={Transform.fromXyz(x, y, on ? 0 : t * 0.8).withScale([pop, on ? 1 : 1 - t, on ? 1 : 1 - t])} name={`brick-${i}`}>
<Cuboid half_size={[(W / COLS - 0.08) / 2, 0.2, 0.2]} />
<StandardMaterial base_color={on ? COLORS[Math.floor(i / COLS)] : "#ffffff"} perceptual_roughness={0.5} />
</Mesh3d>
);
})}
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
{"♥".repeat(Math.max(0, g.lives))}
</div>
{!g.touched ? (
<div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
{`👆 Drag to play`}
</div>
) : null}
<EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
</AbsoluteFill>
);
}
registerRoot(() => (
<>
<Composition id="brick-rush-portrait" component={BrickRush} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 45} />
<Composition id="brick-rush-landscape" component={BrickRush} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 45} />
</>
));
+8 -2
View File
@@ -24,12 +24,13 @@ pub fn bundle_module(ts: &Path, out: &Path, body: &str) -> R<()> {
/// A path as an entry's import specifier. On Windows a canonical path is a verbatim one (\\?\C:\...), which Rolldown
/// can't resolve as an import (`raea run` on windows-latest, PT20); dunce drops the prefix where the plain path means the
/// same file, and changes nothing elsewhere.
fn spec(p: &Path) -> String {
pub fn spec(p: &Path) -> String {
dunce::simplified(p).display().to_string()
}
/// `entry` (TypeScript source) bundled into `out` by raea-bundle's library (engine/bundle/src/script.rs's resolution); `extra`
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b).
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b), and --minify 1 and --inline 1 (a page that
/// carries its files: engine/bundle inline.rs).
pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
let out = &std::path::absolute(out).map_err(|e| format!("{}: {e}", out.display()))?;
let work = std::env::temp_dir().join(format!("raea-cli-e{}-{:?}", std::process::id(), std::thread::current().id()));
@@ -41,6 +42,7 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
// in process by raea-bundle's library: the engine's resolution (engine/bundle/src/script.rs) and the flags
{
let (mut defines, mut aliases, mut stubs) = (serde_json::Map::new(), serde_json::Map::new(), Vec::new());
let (mut minify, mut inline) = (false, false);
let mut it = extra.iter();
while let Some(flag) = it.next() {
let Some(v) = it.next() else { break };
@@ -56,6 +58,8 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
}
}
"--node-stub" => stubs.extend(v.split(',').filter(|s| !s.is_empty()).map(|s| Value::from(s))),
"--minify" => minify = *v != "0",
"--inline" => inline = *v != "0",
_ => {}
}
}
@@ -64,6 +68,8 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
"script": {"js": js, "motion": root.join("sdk/raea/src"), "shell": root.join("sdk/shell/src/index.ts"),
"aliases": aliases, "stubs": stubs},
"defines": defines,
"minify": minify,
"inline": inline,
});
let r = inproc::bundle(&work.join("entry.ts"), opts);
let _ = std::fs::remove_dir_all(&work);
+3 -1
View File
@@ -35,7 +35,9 @@ pub fn drop_tsconfigs(dir: &Path, depth: usize) {
}
}
pub const MEDIA_EXTS: [&str; 12] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
/// Files an edit imports as their path, as engine/bundle's script.rs MEDIA: media, models, and fonts (an @font-face's
/// url(), which a playable carries as a data URL)
pub const MEDIA_EXTS: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
/// The edit's source with its imports pointed at the bundle's copy of the SDK (its package name, a subpath such as /3d,
/// or a relative path into raea/motion/src), and media imported as modules turned into their paths (spec: "Media
+89
View File
@@ -0,0 +1,89 @@
# Playable ads: raea/playable and `raea playable`
A playable ad is a short game served in place of a video ad inside other apps (AppLovin, Unity, Google, Meta,
Moloco, Mintegral, TikTok, Liftoff). It ends on a card that opens the store. In raea it is a game written the usual
way (`games`), and the same file is both ads: `raea render` makes the video ad, because nobody touches it and it plays
itself, and `raea playable` makes the playable for each network.
## The shape
- **It plays itself until the first touch.** Before anyone touches it, the step plays (a hand, a ghost finger, the
computer making the best move each second). The first touch hands control over, and the hand goes. This is also
what the video ad shows.
- **The move is clear in two seconds.** One gesture: drag, tap a group, swipe a lane. Show it with the hand, not
words. A line of instructions is the rut.
- **A fail moment comes early.** Somewhere between 10 and 30 seconds the player nearly wins or just loses ("So
close!", a tower one short). That is what sends people to the store.
- **The card comes within 30 to 60 seconds.** End on `<EndCard>` when the game is over, won or lost, and never later
than the composition's last frame (the host shows its own card there).
- **Both orientations.** Register a portrait composition (1080x1920) and a landscape one (1920x1080) from the same
game. The host plays the one nearest the screen's shape; with one only, the other is letterboxed. Unity, AppLovin,
Moloco and Mintegral want both.
- **Words stay big.** A phone shows the composition scaled down: titles at 80 px and more, nothing under 36 px at
1080 wide.
## The store
```tsx
import { EndCard, InstallButton, install } from "raea/playable";
<EndCard show={g.over !== ""} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle="Can you clear the wall?" cta="Try again" />
```
- `<EndCard show>` covers the game, and a tap anywhere on it opens the store (`end()` is called when it first shows).
`title`, `subtitle`, `icon` (an imported picture), `cta`, `background`, `font`, `color` and `button` set it; what
you put inside it (a logo, a product) goes between the words and the button.
- `<InstallButton>` is a button anywhere in the game; `install()` opens the store from your own tap handler.
- Outside an export (a render, a preview) they draw but do nothing. The store links come from the export's `--ios` and
`--android`.
## Input
- Read the pointer and touches from the frame's input as in any game: `input.pointer` (`x`, `y` in composition px,
`down`) and `input.touches`. Keys work too, for testing in a browser.
- The host samples input once a frame. A tap shorter than a frame can be missed, so act on the press (`down` becoming
true), not on a quick down-and-up within one frame.
## What a playable can't have
`raea playable` refuses these before it bundles:
- `staticFile()`. Import the file instead (`import icon from "./icon.png"`), and the export carries it in the page.
- Any URL, `fetch`, XHR or WebSocket. Networks refuse a page that makes a request.
- Modules that need the native engine: raea/native, raea/ml, raea/character, raea/physics, raea/media,
raea/matchmove and raea/modelling.
- `<Video>` and `<Audio>`, until sound comes to playables.
- 3D outside what the host draws: meshes (box, sphere, plane, cylinder, cone, torus, capsule, circle, ring), the
standard, physical and basic materials, perspective and orthographic cameras, the five light kinds, fog, tone
mapping, shadows and anti-aliasing. Models, splats and water stay in the video ad.
A font is carried the same way: import it (`import arvo from "./Arvo-Bold.ttf"`) and name it in an `@font-face` in a
`<style>`, ``src: url(${arvo})``. A font named but not imported isn't there on a phone, which draws its own sans-serif.
`<EndCard>` takes `font`, `color` and `button` (a style for its button), so a brand's card is in the brand's type.
## Export and check
```sh
raea add [email protected] # once per project: the playable's 3D renderer
raea render game.tsx -o out/video-ad.mp4 # the video ad
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
```
It prints each network's file and its size against the 5 MB cap; a page is usually 1.3 to 1.5 MB, most of it
three.js. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
`--orientation` sets what Google and TikTok are told.
Play the `preview` page yourself before handing it over: open it at a phone's size, drag, lose, and tap the card. In
raea's own checkout, `bun sdk/playable/tools/check.ts PAGE.html OUT` plays it in WebKit, as an iPhone's ad view does,
and fails on an error, a request, or a card that opens nothing.
## How it fails
| What you see | Why | What to change |
|---|---|---|
| nothing moves until it's touched | the step only reads input | let the step play itself when nobody has touched it |
| the hand keeps playing after a touch | `touched` isn't kept in the state | set it in the step on the first press, and stop the hand from then |
| a tap does nothing | the press lasted less than a frame, or the step waits for the release | act on `down` |
| the page is refused for a request | a URL or `staticFile` in the source, or a font from the web | import the file; take the URL out |
| it's letterboxed on a phone | one orientation registered | register the other shape |
| the video ad shows the end card early | the self-play loses too fast | tune the self-play so it nearly wins |
+13
View File
@@ -0,0 +1,13 @@
src/host/tony.bin is the tone-mapping table Tony McMapface, resampled by tools/tony.ts from Bevy's copy of it.
Tony McMapface
Copyright (c) 2023 Tomasz Stachowiak
https://github.com/h3r2tic/tony-mc-mapface
Licensed under MIT.
Bevy's copy: bevy_core_pipeline's tonemapping/luts/tony_mc_mapface.ktx2
https://github.com/bevyengine/bevy
Licensed under MIT OR Apache-2.0.
host/tonemap.ts samples it as Bevy's tonemapping shader does. The rest of raea/playable is raea's own, under the
repository's licence.
+66
View File
@@ -0,0 +1,66 @@
{
"lockfileVersion": 2,
"configVersion": 1,
"workspaces": {
"": {
"name": "@raea/playable",
"dependencies": {
"react": "file:../raea/node_modules/react",
"react-dom": "file:../raea/node_modules/react-dom",
"scheduler": "file:../raea/node_modules/scheduler",
"three": "0.180.0",
},
"devDependencies": {
"@types/bun": "1.4.3",
"@types/react-dom": "19.2.0",
"@types/three": "0.180.0",
"playwright-core": "1.64.1",
},
},
},
"packages": {
"@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],
"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],
"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],
"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-brtBs0MnE9SMx7px208g39lRmC5uHZs96caOJfTjFcYSLHNamvaSMfJNagChVNkup2SdtOxKX1FDBkRSJe1ZAg=="],
"@types/stats.js": ["@types/[email protected]", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="],
"@types/three": ["@types/[email protected]", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": "*", "@webgpu/types": "*", "fflate": "~0.8.2", "meshoptimizer": "~0.22.0" } }, "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg=="],
"@types/webxr": ["@types/[email protected]", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="],
"@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA=="],
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"fflate": ["[email protected]", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],
"meshoptimizer": ["[email protected]", "", {}, "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg=="],
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],
"react": ["react@file:../raea/node_modules/react", {}],
"react-dom": ["react-dom@file:../raea/node_modules/react-dom", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }],
"scheduler": ["scheduler@file:../raea/node_modules/scheduler", {}],
"three": ["[email protected]", "", {}, "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="],
"undici-types": ["[email protected]", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="],
"@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
"react-dom/scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
}
}
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@raea/playable",
"license": "FSL-1.1-ALv2",
"private": true,
"version": "0.1.0",
"description": "raea games as playable ads: the install call and end card authors use (raea/playable), and the browser host a playable export runs the game in (a fixed-step clock, touch input, the 3D drawn by three.js), docs/playables.feature.",
"type": "module",
"main": "src/index.ts",
"exports": {
".": "./src/index.ts",
"./host": "./src/host/main.tsx"
},
"//": "React is the SDK's own copy (sdk/raea), linked, so a game and the host share one React",
"dependencies": {
"react": "file:../raea/node_modules/react",
"react-dom": "file:../raea/node_modules/react-dom",
"scheduler": "file:../raea/node_modules/scheduler",
"three": "0.180.0"
},
"devDependencies": {
"@types/bun": "1.4.3",
"@types/react-dom": "19.2.0",
"@types/three": "0.180.0",
"playwright-core": "1.64.1"
}
}
+89
View File
@@ -0,0 +1,89 @@
// The two pieces of page every playable has: a button that opens the store, and the end card shown when the game is
// over. Plain page elements, so a raea render draws them as the playable does.
import { useEffect, type CSSProperties, type ReactNode } from "react";
import { end, install } from "./network";
export interface InstallButtonProps {
children?: ReactNode;
style?: CSSProperties;
}
const BUTTON: CSSProperties = {
border: "none",
borderRadius: 999,
padding: "0.7em 1.6em",
fontFamily: "Inter, system-ui, sans-serif",
fontWeight: 800,
fontSize: 40,
color: "#101422",
background: "#ffd166",
boxShadow: "0 6px 0 rgba(0,0,0,0.25)",
cursor: "pointer",
};
/** Opens the store when tapped (install()). */
export function InstallButton({ children = "Install", style }: InstallButtonProps) {
return (
<button
type="button"
onPointerUp={(e) => {
e.stopPropagation();
install();
}}
style={{ ...BUTTON, ...style }}
>
{children}
</button>
);
}
export interface EndCardProps {
/** shown once the game is over (a state the game's fold reaches); end() is called when it first shows */
show: boolean;
title?: string;
subtitle?: string;
/** the app's icon: an imported picture (`import icon from "./icon.png"`), which the export carries in the page */
icon?: string;
cta?: string;
background?: string;
/** the card's type (a brand's font, carried by importing it in an @font-face), Inter by default */
font?: string;
/** the text's colour, white by default */
color?: string;
/** the button's look over the default yellow pill: a brand's colours and type */
button?: CSSProperties;
children?: ReactNode;
}
/** The card the playable ends on: the whole card opens the store when tapped, as networks expect. */
export function EndCard({ show, title, subtitle, icon, cta = "Play now", background = "rgba(10, 12, 24, 0.82)", font = "Inter, system-ui, sans-serif", color = "#ffffff", button, children }: EndCardProps) {
useEffect(() => {
if (show) end();
}, [show]);
if (!show) return null;
return (
<div
onPointerUp={() => install()}
style={{
position: "absolute",
inset: 0,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 28,
background,
color,
fontFamily: font,
textAlign: "center",
cursor: "pointer",
}}
>
{icon ? <img src={icon} alt="" style={{ width: 180, height: 180, borderRadius: 40 }} /> : null}
{title ? <div style={{ fontSize: 64, fontWeight: 900, lineHeight: 1.05, padding: "0 40px" }}>{title}</div> : null}
{subtitle ? <div style={{ fontSize: 34, opacity: 0.8, padding: "0 40px" }}>{subtitle}</div> : null}
{children}
<InstallButton style={button}>{cta}</InstallButton>
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
// `raea playable`'s lint, the part that renders (docs/playables.feature PA4): run by `raea run` on an entry that imports
// the game first, so its compositions are registered. Each composition is rendered at 12 frames through its length,
// and every 3D kind it draws is held to what the playable host draws (kinds.ts). Returns its shapes and the kinds.
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { Clock, getCompositions } from "raea";
import { PLAYABLE_KINDS } from "../host/kinds";
export default function walk() {
const kinds: Record<string, number> = {};
const comps = getCompositions().map((c) => {
const step = Math.max(1, Math.floor(c.durationInFrames / 12));
for (let f = 0; f < c.durationInFrames; f += step) {
const html = renderToStaticMarkup(
createElement(Clock, { frame: f, fps: c.fps, width: c.width, height: c.height, durationInFrames: c.durationInFrames }, createElement(c.component, c.defaultProps)),
);
for (const m of html.matchAll(/data-3d="([A-Za-z0-9]+)"/g)) kinds[m[1]] = (kinds[m[1]] ?? 0) + 1;
}
return { id: c.id, width: c.width, height: c.height, fps: c.fps, frames: c.durationInFrames };
});
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)) };
}
+5
View File
@@ -0,0 +1,5 @@
// raw tables, carried in the page by `raea playable` (engine/bundle inline.rs: a .bin import is a Uint8Array)
declare module "*.bin" {
const bytes: Uint8Array;
export default bytes;
}
+69
View File
@@ -0,0 +1,69 @@
// A person's input as raea's FrameInput, in composition px: keys held, the primary pointer and every finger down.
// The stage is the composition scaled uniformly into the screen, so each point is mapped back through its box.
import type { FrameInput } from "raea";
/** window.addEventListener typed by the event's name (bun's globals type the bare addEventListener loosely) */
function on<K extends keyof WindowEventMap>(type: K, f: (e: WindowEventMap[K]) => void) {
window.addEventListener(type, f);
}
export class Input {
private keys = new Set<string>();
private pointer?: { x: number; y: number; down: boolean };
private touches = new Map<number, { x: number; y: number }>();
/** set on the first touch, click or key: networks keep sound off until then */
touched = false;
private firstTouch: (() => void)[] = [];
constructor(private stage: HTMLElement, private size: () => { width: number; height: number }) {
const at = (e: PointerEvent) => {
const r = this.stage.getBoundingClientRect();
const { width, height } = this.size();
return { x: ((e.clientX - r.left) / r.width) * width, y: ((e.clientY - r.top) / r.height) * height };
};
const first = () => {
if (this.touched) return;
this.touched = true;
for (const f of this.firstTouch) f();
};
on("pointerdown", (e) => {
first();
const p = at(e);
this.pointer = { ...p, down: true };
this.touches.set(e.pointerId, p);
});
on("pointermove", (e) => {
const p = at(e);
if (e.isPrimary) this.pointer = { ...p, down: this.pointer?.down ?? false };
if (this.touches.has(e.pointerId)) this.touches.set(e.pointerId, p);
});
const up = (e: PointerEvent) => {
if (e.isPrimary && this.pointer) this.pointer = { ...this.pointer, down: false };
this.touches.delete(e.pointerId);
};
on("pointerup", up);
on("pointercancel", up);
on("keydown", (e) => {
first();
this.keys.add(e.key);
});
on("keyup", (e) => this.keys.delete(e.key));
on("blur", () => this.keys.clear());
}
/** Runs `f` on the first touch, click or key */
onFirstTouch(f: () => void) {
if (this.touched) f();
else this.firstTouch.push(f);
}
/** This frame's input, marked live (a person is playing: raea/games' fold reads it so) */
now(): FrameInput & { live: true } {
return {
keys: [...this.keys],
...(this.pointer ? { pointer: { ...this.pointer } } : {}),
...(this.touches.size ? { touches: [...this.touches].map(([id, p]) => ({ id, ...p })) } : {}),
live: true,
};
}
}
+12
View File
@@ -0,0 +1,12 @@
// The 3D kinds a playable's host draws (scene.ts, through sdk/r3f/src/three), apart from the renderer so the export's
// lint reads them without three.js (`raea playable`, docs/playables.feature PA4).
/** The kinds a playable draws; the export's lint refuses any other */
export const PLAYABLE_KINDS: ReadonlySet<string> = new Set([
"Canvas3D", "Group", "Mesh",
"Box", "Sphere", "Plane", "Cylinder", "Cone", "Torus", "Capsule", "Circle", "Ring",
"MeshStandardMaterial", "MeshPhysicalMaterial", "MeshBasicMaterial",
"PerspectiveCamera", "OrthographicCamera",
"AmbientLight", "DirectionalLight", "PointLight", "SpotLight", "HemisphereLight",
"Fog", "ToneMapping", "Shadows", "AntiAliasing",
]);
+168
View File
@@ -0,0 +1,168 @@
// The browser host a playable export runs a raea game in (docs/playables.feature PA1): the game's registered
// composition (the one nearest the screen's shape, so a portrait and a landscape one can both ship) put on a stage
// scaled uniformly into the screen, a Clock stepped 1/fps at a time off requestAnimationFrame with the person's input
// recorded per frame, and its 3D drawn by three.js under the page. It starts when the network says the ad is
// viewable, pauses while it isn't, and ends on the game's own EndCard or, at the composition's last frame, on one of
// its own.
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import * as THREE from "three";
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
import { EndCard } from "../cards";
import { network, onAdEvent, whenReady } from "../network";
import { Input } from "./input";
import { Scene3d } from "./scene";
import { UNDER, backgroundUnder3d } from "@raea/r3f/three/page";
import { Tonemap } from "./tonemap";
declare const __RAEA_PLAYABLE__: { title?: string; cta?: string } | undefined;
const config = typeof __RAEA_PLAYABLE__ === "object" && __RAEA_PLAYABLE__ ? __RAEA_PLAYABLE__ : {};
function pick(comps: RegisteredComposition[]): RegisteredComposition {
const screen = innerWidth / Math.max(1, innerHeight);
return comps.reduce((a, b) => (Math.abs(Math.log((b.width / b.height) / screen)) < Math.abs(Math.log((a.width / a.height) / screen)) ? b : a));
}
/** The 3D is drawn under the page, so the page elements holding it are cleared and the innermost solid background
* among them becomes the 3D's clear colour, as the native engine shows the page's background behind the 3D. */
function boot() {
const comps = getCompositions();
if (!comps.length) throw new Error("raea playable: the game registered no composition (registerRoot)");
// a still (tools/parity.ts): one composition at one frame, no one playing, as `raea render --frame` draws it
const still = network === "preview" ? new URLSearchParams(location.hash.slice(1)) : undefined;
const fixed = still?.has("still") ? comps.find((c) => c.id === still.get("comp")) ?? comps[0] : undefined;
let comp = fixed ?? pick(comps);
document.head.insertAdjacentHTML("beforeend", `<style>html,body{margin:0;height:100%;overflow:hidden;background:#000;touch-action:none;user-select:none;-webkit-user-select:none}[${UNDER}]{background:transparent!important}#raea-stage{position:absolute;transform-origin:0 0;overflow:hidden}#raea-stage>canvas,#raea-page{position:absolute;inset:0;width:100%;height:100%}</style>`);
const stage = document.createElement("div");
stage.id = "raea-stage";
const canvas = document.createElement("canvas");
const page = document.createElement("div");
page.id = "raea-page";
stage.append(canvas, page);
document.body.append(stage);
// the 3D is tone-mapped by its own pass (antialiased in its target) and left transparent where nothing was drawn
const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const tonemap = new Tonemap(renderer);
const scene = new Scene3d();
const layout = () => {
if (comps.length > 1 && !fixed) comp = pick(comps);
const s = Math.min(innerWidth / comp.width, innerHeight / comp.height);
Object.assign(stage.style, {
width: `${comp.width}px`,
height: `${comp.height}px`,
left: `${(innerWidth - comp.width * s) / 2}px`,
top: `${(innerHeight - comp.height * s) / 2}px`,
transform: `scale(${s})`,
});
// the canvas is drawn at the screen's pixels, not the composition's
renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * s);
renderer.setSize(comp.width, comp.height, false);
tonemap.resize();
scene.fit(comp.width, comp.height);
};
layout();
addEventListener("resize", layout);
const input = new Input(stage, () => comp);
const root = createRoot(page);
const timeline: InputTimeline = {};
let frame = 0;
let timedOut = false;
let running = false;
let visible = true;
let last = 0;
let acc = 0;
let over = false;
let shown = false;
let firstDrawn = false;
// the ad events so far, for tools/check.ts to read back
const events: string[] = ((globalThis as { __raeaAdEvents?: string[] }).__raeaAdEvents = []);
// the preview page inside raea's review (a sandboxed frame) tells the review each event, which shows them beside it
const tell = (kind: string) => {
if (network === "preview" && window.parent !== window) window.parent.postMessage({ raeaPlayable: kind }, "*");
};
onAdEvent((e) => {
events.push(e.kind);
if (e.kind === "end") over = true;
tell(e.kind);
});
// the player took over from the game's own hand
input.onFirstTouch(() => tell("touch"));
const draw = () => {
const C = comp.component;
flushSync(() =>
root.render(
<Clock frame={frame} fps={comp.fps} width={comp.width} height={comp.height} durationInFrames={comp.durationInFrames} input={timeline} defaultProps={comp.defaultProps}>
<C {...comp.defaultProps} />
<EndCard show={timedOut} title={config.title} cta={config.cta} />
</Clock>,
),
);
scene.sync(page, frame / comp.fps);
const clear = backgroundUnder3d(page);
// the page's own background colour behind the 3D, untouched by the tone curve as natively
stage.style.background = clear ?? "#000000";
canvas.style.visibility = scene.any ? "visible" : "hidden";
if (scene.any) tonemap.render(scene.scene, scene.camera);
// a preview build says when its first frame was drawn (tools/check.ts reads it: startup on a slow phone)
if (!firstDrawn && network === "preview") console.info(`raea playable: first frame at ${Math.round(performance.now())} ms`);
firstDrawn = true;
};
const tick = (now: number) => {
requestAnimationFrame(tick);
if (!running || !visible) {
last = now;
return;
}
const step = 1000 / comp.fps;
acc += Math.min(250, now - last);
last = now;
let stepped = false;
// the game stops stepping once it is over (its EndCard showed, or time ran out): the card stays on the last frame
while (acc >= step && !over) {
acc -= step;
timeline[frame] = input.now();
if (frame + 1 >= comp.durationInFrames) {
timedOut = true;
break;
}
frame++;
stepped = true;
}
if (stepped || (timedOut && !shown)) {
shown = timedOut;
draw();
}
};
if (fixed) {
frame = Math.min(Number(still!.get("still")), comp.durationInFrames - 1);
draw();
(globalThis as { __raeaStill?: boolean }).__raeaStill = true;
return;
}
draw();
whenReady(
() => {
running = true;
last = performance.now();
tell("ready");
},
(on) => {
if (on !== visible) tell(on ? "viewable" : "hidden");
visible = on;
},
);
requestAnimationFrame(tick);
}
if (document.readyState === "loading") addEventListener("DOMContentLoaded", boot);
else boot();
+5
View File
@@ -0,0 +1,5 @@
// The page's 3D drawn by three.js: raea's three.js host (sdk/r3f/src/three, shared with <Raea> in React Three Fiber),
// held to what a playable may carry: a kind outside PLAYABLE_KINDS (kinds.ts) is refused by the export's lint
// (`raea playable`, docs/playables.feature PA4).
export { Scene3d } from "@raea/r3f/three/scene";
export { PLAYABLE_KINDS } from "./kinds";
+65
View File
@@ -0,0 +1,65 @@
// Bevy's tone mapping in the playable (docs/playables.feature PA10): the 3D drawn into a half-float target with no
// tone curve, then one full-screen pass maps it through TonyMcMapface (Bevy's default, tools/tony.ts's table) and
// encodes sRGB, as bevy_core_pipeline's tonemapping.wesl does. Where nothing was drawn it stays transparent, so the
// page's background shows through as it does under the native engine's 3D.
import * as THREE from "three";
import tony from "./tony.bin";
const N = Math.round(Math.cbrt(tony.length / 3));
const FRAG = /* glsl */ `
precision highp float;
precision highp sampler3D;
uniform sampler2D scene;
uniform sampler3D lut;
in vec2 vUv;
out vec4 color;
void main() {
vec4 c = texture(scene, vUv);
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0));
vec3 uv = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
// the table holds sRGB-encoded bytes, already the screen's values
color = vec4(texture(lut, clamp(uv, 0.0, 1.0)).rgb * c.a, c.a);
}`;
const VERT = /* glsl */ `
in vec3 position;
in vec2 uv;
out vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
export class Tonemap {
private target: THREE.WebGLRenderTarget;
private quad: THREE.Mesh;
private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
constructor(private renderer: THREE.WebGLRenderer) {
renderer.toneMapping = THREE.NoToneMapping;
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
this.target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4, colorSpace: THREE.LinearSRGBColorSpace });
const rgba = new Uint8Array(N * N * N * 4);
for (let i = 0; i < N * N * N; i++) rgba.set([tony[i * 3], tony[i * 3 + 1], tony[i * 3 + 2], 255], i * 4);
const lut = new THREE.Data3DTexture(rgba, N, N, N);
lut.minFilter = lut.magFilter = THREE.LinearFilter;
lut.unpackAlignment = 1;
lut.needsUpdate = true;
const material = new THREE.RawShaderMaterial({ glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: FRAG, uniforms: { scene: { value: this.target.texture }, lut: { value: lut } }, transparent: true, premultipliedAlpha: true, blending: THREE.NoBlending, depthTest: false, depthWrite: false });
this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
}
/** The target sized to the canvas's drawing buffer */
resize() {
const s = this.renderer.getDrawingBufferSize(new THREE.Vector2());
this.target.setSize(s.x, s.y);
}
render(scene: THREE.Scene, camera: THREE.Camera) {
const r = this.renderer;
r.setRenderTarget(this.target);
r.setClearColor(0x000000, 0);
r.clear();
r.render(scene, camera);
r.setRenderTarget(null);
r.render(this.quad, this.camera);
}
}
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
// raea/playable: what a game written for a playable ad uses (docs/playables.feature PA3). The same TSX renders as a
// video ad with `raea render` (where install() does nothing) and exports as a playable with `raea playable`.
export { install, end, isEnded, network, storeUrl, onAdEvent, type Network, type StoreLinks } from "./network";
export { EndCard, InstallButton, type EndCardProps, type InstallButtonProps } from "./cards";
+138
View File
@@ -0,0 +1,138 @@
// The ad network a playable export is built for, and the three things every network wants from it in its own words:
// when the ad may start (and must pause), how the store opens, and that the game ended (docs/playables.feature PA2).
// The export names the network at build time (__RAEA_NETWORK__); a game's own code only calls install() and end().
export type Network = "applovin" | "unity" | "google" | "meta" | "moloco" | "mintegral" | "tiktok" | "liftoff" | "preview";
export interface StoreLinks {
ios?: string;
android?: string;
}
declare const __RAEA_NETWORK__: Network | undefined;
declare const __RAEA_STORE__: StoreLinks | undefined;
interface Mraid {
getState(): string;
isViewable(): boolean;
addEventListener(event: string, f: (...a: unknown[]) => void): void;
open(url?: string): void;
}
type Win = typeof globalThis & {
mraid?: Mraid;
ExitApi?: { exit(): void };
FbPlayableAd?: { onCTAClick(): void };
Liftoff?: { open(): void };
install?: () => void;
openAppStore?: () => void;
gameReady?: () => void;
gameEnd?: () => void;
gameStart?: () => void;
gameClose?: () => void;
};
const w = globalThis as Win;
/** The network this build is for: "preview" outside an export (a raea render, a browser tab) */
export const network: Network = typeof __RAEA_NETWORK__ === "string" ? __RAEA_NETWORK__ : "preview";
const store: StoreLinks = typeof __RAEA_STORE__ === "object" && __RAEA_STORE__ ? __RAEA_STORE__ : {};
const MRAID: readonly Network[] = ["applovin", "unity", "liftoff"];
/** The store link for this device: iOS's on iPhone/iPad, Android's otherwise */
export function storeUrl(): string | undefined {
const ua = typeof navigator === "undefined" ? "" : navigator.userAgent;
const ios = /iPhone|iPad|iPod|Macintosh/.test(ua) && !/Android/.test(ua);
return (ios ? store.ios : store.android) ?? store.android ?? store.ios;
}
const listeners: ((e: { kind: "install" | "end" }) => void)[] = [];
/** Called on install() and end(), for the preview page's log and tests */
export function onAdEvent(f: (e: { kind: "install" | "end" }) => void): void {
listeners.push(f);
}
let ended = false;
/** Open the store, the network's way. Call it only from a player's tap (every network rejects an automatic redirect). */
export function install(): void {
for (const f of listeners) f({ kind: "install" });
if (!ended) end();
const url = storeUrl();
switch (network) {
case "applovin":
case "unity":
if (w.mraid) w.mraid.open(url);
return;
case "liftoff":
if (w.Liftoff) w.Liftoff.open();
else w.mraid?.open();
return;
case "google":
w.ExitApi?.exit();
return;
case "meta":
case "moloco":
w.FbPlayableAd?.onCTAClick();
return;
case "mintegral":
w.install?.();
return;
case "tiktok":
w.openAppStore?.();
return;
case "preview":
return;
}
}
/** The game is over (won, lost or out of time): Mintegral's gameEnd; the host shows the end card. Called once. */
export function end(): void {
if (ended) return;
ended = true;
for (const f of listeners) f({ kind: "end" });
if (network === "mintegral") w.gameEnd?.();
}
/** Whether end() was called */
export function isEnded(): boolean {
return ended;
}
/** Calls `start` once the ad may begin, then `visible(false|true)` as it is hidden and shown again (Unity, AppLovin:
* start only after MRAID's ready and while viewable, pause while not). Mintegral is told the game is ready and
* starts it with its own gameStart. */
export function whenReady(start: () => void, visible: (on: boolean) => void): void {
let started = false;
const go = () => {
if (started) return;
started = true;
start();
};
if (MRAID.includes(network) && w.mraid) {
const m = w.mraid;
const onReady = () => {
m.addEventListener("viewableChange", (on) => {
if (on) go();
visible(!!on);
});
if (m.isViewable()) go();
};
if (m.getState() === "loading") m.addEventListener("ready", onReady);
else onReady();
return;
}
if (network === "mintegral") {
w.gameStart = go;
w.gameClose = () => visible(false);
w.gameReady?.();
// Mintegral's preview tool calls gameStart; a page opened by hand starts on its own
if (!w.gameReady) go();
return;
}
if (typeof document !== "undefined") {
document.addEventListener("visibilitychange", () => visible(document.visibilityState === "visible"));
}
go();
}
+76
View File
@@ -0,0 +1,76 @@
// A playable played in headless WebKit, as an iPhone's ad WebView would show it (docs/playables.feature PA7): the page
// opened at a phone's size, a drag held long enough for the host's per-frame input to see it, its console,
// exceptions and any network request it tried read back, and screenshots saved.
// `bun tools/check.ts PAGE.html OUT_DIR [WxH]`; exits 1 on a page error, a request, or a page that never drew.
// PLAY_SECONDS=N plays on, then taps the end card (and the check fails if no install event came back).
// WebKit, not Chrome: iOS ad WebViews are WebKit, and raea doesn't test in Chrome.
import { mkdirSync } from "node:fs";
import { resolve } from "node:path";
import { webkit } from "playwright-core";
const [page, outDir, size = "390x844"] = process.argv.slice(2);
if (!page || !outDir) throw new Error("usage: bun tools/check.ts PAGE.html OUT_DIR [WxH]");
const [W, H] = size.split("x").map(Number);
mkdirSync(outDir, { recursive: true });
const browser = await webkit.launch();
const ctx = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: 2, hasTouch: true, isMobile: true });
const p = await ctx.newPage();
const logs: string[] = [];
const problems: string[] = [];
p.on("console", (m) => logs.push(`${m.type()}: ${m.text()}`));
p.on("pageerror", (e) => problems.push(`exception: ${e.message}`));
// the scripts a network's own page tags load, which its ad view serves (apps/playable pages.rs): Google's exit API and
// TikTok's playable SDK. They're stopped here like any request, but they aren't the game's.
const NETWORK_TAGS = ["https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js", "https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js"];
await ctx.route("**/*", (r) => {
const u = r.request().url();
if (u.startsWith("file:") || u.startsWith("data:") || u.startsWith("blob:")) return r.continue();
if (!NETWORK_TAGS.includes(u)) problems.push(`network request: ${u}`);
return r.abort();
});
await p.goto(page.startsWith("http") ? page : `file://${resolve(page)}`);
await p.waitForTimeout(1500);
const shot = (name: string) => p.screenshot({ path: resolve(outDir, `${name}.png`) });
// real input: WebKit makes the pointer events the host reads (host/input.ts), each press held over several frames
// (the host samples input once a frame, so a press shorter than a frame is lost)
const press = async (type: "down" | "move" | "up", x: number, y: number) => {
await p.mouse.move(x, y);
if (type === "down") await p.mouse.down();
if (type === "up") await p.mouse.up();
};
await shot("0-start");
await press("down", W * 0.3, H * 0.75);
for (let i = 0; i <= 10; i++) {
await press("move", W * (0.3 + 0.04 * i), H * 0.75);
await p.waitForTimeout(80);
}
await press("up", W * 0.7, H * 0.75);
await shot("1-played");
await p.waitForTimeout(2500);
await shot("2-later");
const more = Number(process.env.PLAY_SECONDS ?? 0);
if (more > 0) {
await p.waitForTimeout(more * 1000);
await shot("3-end");
await press("down", W / 2, H / 2);
await p.waitForTimeout(150);
await press("up", W / 2, H / 2);
await p.waitForTimeout(300);
}
const state = (await p.evaluate(() => ({
canvas: !!document.querySelector("#raea-stage canvas"),
parts: document.querySelectorAll("[data-3d]").length,
page: document.querySelector("#raea-page")?.childElementCount ?? 0,
events: (globalThis as { __raeaAdEvents?: unknown[] }).__raeaAdEvents ?? [],
}))) as { canvas: boolean; parts: number; page: number; events: unknown[] };
console.log(`page: ${JSON.stringify(state)}`);
if (!state.page && !state.parts) problems.push("nothing drew: the game's page is empty");
if (more > 0 && !JSON.stringify(state.events).includes("install")) problems.push("the end card was tapped but no install event came back");
for (const l of logs) console.log(l);
for (const pr of problems) console.log(`PROBLEM: ${pr}`);
await browser.close();
process.exit(problems.length ? 1 : 0);
+72
View File
@@ -0,0 +1,72 @@
// A playable held to the native render (docs/playables.feature PA9): one composition frame drawn by `raea render` and
// by the playable host (a preview build opened at the composition's size, no one playing, so both play themselves),
// compared where the native frame drew something over its background. The playable is drawn in WebKit, as an
// iPhone's ad view draws it (raea doesn't test in Chrome).
// `bun tools/parity.ts GAME.tsx COMPOSITION FRAME OUT_DIR [BAR]` prints the numbers, writes native.png, playable.png
// and diff.png, and exits 1 when the mean colour difference over the drawn pixels is over BAR (0-255, default 16).
import { mkdirSync } from "node:fs";
import { resolve } from "node:path";
import { webkit } from "playwright-core";
const [game, comp, at, outArg, barArg = "16"] = process.argv.slice(2);
if (!game || !comp || !at || !outArg) throw new Error("usage: bun tools/parity.ts GAME.tsx COMPOSITION FRAME OUT_DIR [BAR]");
const out = resolve(outArg);
mkdirSync(out, { recursive: true });
const name = game.split("/").pop()!.replace(/\.tsx$/, "");
const run = async (cmd: string[]) => {
const p = Bun.spawn(cmd, { stdout: "pipe", stderr: "pipe" });
const [o, e] = [await new Response(p.stdout).text(), await new Response(p.stderr).text()];
if ((await p.exited) !== 0) throw new Error(`${cmd.join(" ")} failed:\n${o}\n${e}`);
return o;
};
// the native frame, and the composition's size from the registry the playable reads
await run(["raea", "render", resolve(game), "-o", `${out}/native.png`, "--composition", comp, "--frame", at]);
await run(["raea", "playable", resolve(game), "-o", out, "--networks", "preview"]);
const size = (await run(["ffprobe", "-v", "error", "-select_streams", "v", "-show_entries", "stream=width,height", "-of", "csv=p=0", `${out}/native.png`])).trim();
const [W, H] = size.split(",").map(Number);
const browser = await webkit.launch();
const p = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });
const problems: string[] = [];
p.on("pageerror", (e) => problems.push(`exception: ${e.message}`));
await p.route("**/*", (r) => {
const u = r.request().url();
if (/^(file|data|blob):/.test(u)) return r.continue();
problems.push(`network request: ${u}`);
return r.abort();
});
await p.goto(`file://${out}/${name}-preview.html#still=${at}&comp=${comp}`);
await p.waitForFunction(() => (globalThis as { __raeaStill?: unknown }).__raeaStill, null, { timeout: 10_000 }).catch(() => problems.push("the still never drew"));
await p.screenshot({ path: `${out}/playable.png` });
await browser.close();
const raw = async (png: string) => new Uint8Array(await new Response(Bun.spawn(["ffmpeg", "-v", "error", "-i", png, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { stdout: "pipe" }).stdout).arrayBuffer());
const [a, b] = [await raw(`${out}/native.png`), await raw(`${out}/playable.png`)];
if (a.length !== b.length) throw new Error(`parity: sizes differ (${a.length} vs ${b.length} bytes)`);
await run(["ffmpeg", "-v", "error", "-y", "-i", `${out}/native.png`, "-i", `${out}/playable.png`, "-filter_complex", "blend=all_mode=difference", `${out}/diff.png`]);
// the drawn pixels: those of the native frame away from its background (the corner's colour)
const bg = [a[0], a[1], a[2]];
let n = 0, diff = 0, covered = 0;
const sumA = [0, 0, 0], sumB = [0, 0, 0];
for (let i = 0; i < a.length; i += 3) {
if (Math.abs(a[i] - bg[0]) + Math.abs(a[i + 1] - bg[1]) + Math.abs(a[i + 2] - bg[2]) < 24) continue;
n++;
for (let k = 0; k < 3; k++) {
diff += Math.abs(a[i + k] - b[i + k]) / 3;
sumA[k] += a[i + k];
sumB[k] += b[i + k];
}
if (Math.abs(b[i] - bg[0]) + Math.abs(b[i + 1] - bg[1]) + Math.abs(b[i + 2] - bg[2]) >= 24) covered++;
}
const hex = (s: number[]) => "#" + s.map((v) => Math.round(v / n).toString(16).padStart(2, "0")).join("");
const luma = (s: number[]) => 0.2126 * s[0] + 0.7152 * s[1] + 0.0722 * s[2];
const mean = diff / Math.max(1, n);
const bar = Number(barArg);
console.log(`${comp} frame ${at}: ${n} drawn pixels (${((100 * n) / (a.length / 3)).toFixed(1)}% of the frame), the playable covers ${((100 * covered) / Math.max(1, n)).toFixed(1)}% of them`);
console.log(`mean colour native ${hex(sumA)} playable ${hex(sumB)}, brightness ${(luma(sumB) / luma(sumA)).toFixed(3)}x`);
console.log(`mean difference ${mean.toFixed(1)} / 255 (bar ${bar}): ${mean <= bar ? "ok" : "OVER"}`);
for (const p of problems) console.log(`PROBLEM: ${p}`);
process.exit(mean <= bar && !problems.length ? 0 : 1);
+56
View File
@@ -0,0 +1,56 @@
// Bevy's TonyMcMapface tone-mapping table for the playable host (docs/playables.feature PA10): bevy_core_pipeline's
// tony_mc_mapface.ktx2 (48³, E5B9G9R9 floats, zstd; MIT, Tomasz Stachowiak) resampled to N³ and stored as sRGB-encoded
// RGB bytes, which host/tonemap.ts samples as Bevy's tonemapping.wesl does.
// `bun tools/tony.ts N OUT.bin` (N = 48 keeps Bevy's own size).
import { readdirSync } from "node:fs";
import { homedir } from "node:os";
const [nArg = "32", out = "src/host/tony.bin"] = process.argv.slice(2);
const N = Number(nArg);
const reg = `${homedir()}/.cargo/registry/src`;
const src = readdirSync(reg).map((d) => `${reg}/${d}/bevy_core_pipeline-0.20.0/src/tonemapping/luts/tony_mc_mapface.ktx2`).find((f) => Bun.file(f).size > 0);
if (!src) throw new Error("tony: bevy_core_pipeline 0.20.0 isn't in ~/.cargo/registry (build raea once)");
const ktx = new DataView(await Bun.file(src).arrayBuffer());
const u32 = (o: number) => ktx.getUint32(o, true);
const [format, D, superc] = [u32(12), u32(20), u32(44)];
if (format !== 123 || D !== 48 || superc !== 2) throw new Error(`tony: expected 48³ E5B9G9R9 with zstd, got format ${format}, ${D}³, supercompression ${superc}`);
// the one level's index: offset and length (u64s, small enough for a Number)
const off = Number(ktx.getBigUint64(80, true)), len = Number(ktx.getBigUint64(88, true));
const data = Bun.zstdDecompressSync(new Uint8Array(ktx.buffer, off, len));
const px = new DataView(data.buffer, data.byteOffset, data.byteLength);
/** E5B9G9R9: three 9-bit mantissas over one shared 5-bit exponent (bias 15) */
function texel(x: number, y: number, z: number): [number, number, number] {
const v = px.getUint32(((z * D + y) * D + x) * 4, true);
const s = 2 ** ((v >>> 27) - 15 - 9);
return [(v & 511) * s, ((v >>> 9) & 511) * s, ((v >>> 18) & 511) * s];
}
/** the table at p in [0, 1]³, trilinear as the GPU's sampler reads it (texel centres at (i + 0.5) / D) */
function sample(p: [number, number, number]): number[] {
const f = p.map((c) => Math.min(D - 1, Math.max(0, c * D - 0.5)));
const i0 = f.map(Math.floor), t = f.map((c, k) => c - i0[k]);
const i1 = i0.map((c) => Math.min(D - 1, c + 1));
const out = [0, 0, 0];
for (let corner = 0; corner < 8; corner++) {
const pick = [corner & 1, (corner >> 1) & 1, (corner >> 2) & 1];
const w = pick.reduce((m, b, k) => m * (b ? t[k] : 1 - t[k]), 1);
const c = texel(pick[0] ? i1[0] : i0[0], pick[1] ? i1[1] : i0[1], pick[2] ? i1[2] : i0[2]);
for (let k = 0; k < 3; k++) out[k] += w * c[k];
}
return out;
}
const srgb = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
// Bevy reads the table at uv = e * (D - 1) / D + 0.5 / D for e = x / (x + 1) in [0, 1]: texel i holds e = i / (D - 1).
// The new table keeps that layout at its own size, so the host samples it the same way with N for D.
const at = (e: number) => e * (D - 1) / D + 0.5 / D;
const bytes = new Uint8Array(N * N * N * 3);
for (let z = 0; z < N; z++)
for (let y = 0; y < N; y++)
for (let x = 0; x < N; x++) {
const c = sample([at(x / (N - 1)), at(y / (N - 1)), at(z / (N - 1))]);
const o = ((z * N + y) * N + x) * 3;
for (let k = 0; k < 3; k++) bytes[o + k] = Math.round(255 * srgb(Math.min(1, Math.max(0, c[k]))));
}
await Bun.write(out, bytes);
console.log(`tony: ${N}³ from ${D}³, ${bytes.length} bytes to ${out}`);
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["bun"] } }
+3
View File
@@ -51,6 +51,7 @@
"raea/blender/shot": ["./blender/src/shot.tsx"],
"raea/godot": ["./godot/src/index.ts"],
"raea/godot/shot": ["./godot/src/shot.tsx"],
"raea/playable": ["./playable/src/index.ts"],
"raea/pick": ["./render/src/pick.ts"],
"raea/playtest": ["./app/src/playtest.ts"],
"raea/ragdoll": ["./character/src/ragdoll.ts"],
@@ -112,6 +113,8 @@
"@raea/ui/canvas": ["./ui/src/canvas.ts"],
"@raea/physics": ["./physics/src/index.ts"],
"@raea/physics/*": ["./physics/src/*"],
"@raea/playable": ["./playable/src/index.ts"],
"@raea/playable/*": ["./playable/src/*"],
"@raea/web": ["./web/src/index.tsx"],
"@raea/web/*": ["./web/src/*"],
"@raea/room": ["./room/src/index.ts"],
+1 -1
Submodule skills updated: 98de983bca...8efd329239.
+2 -1
View File
@@ -165,7 +165,8 @@ impl Ctx<'_> {
if let Some(p) = self.images.get(src) {
return Some(p.clone());
}
let (mime, bytes) = raea_io_net::data_url(src)?;
// inline (data:), else the picture's file (a page's /media/: the host's roots, as its videos)
let (mime, bytes) = raea_io_net::data_url(src).or_else(|| crate::image_file(src))?;
let mime = mime.as_str();
let img = if mime == "image/svg+xml" {
let size = crate::svg::natural_size(&bytes, self.opt)?;
+52 -7
View File
@@ -84,8 +84,8 @@ impl Replay {
}
}
/// Where a canvas's videos' files are, for a host that draws canvases (raea-page's Blitz page: the page's roots); until
/// one is given a video's src is read as a file path.
/// Where a canvas's videos' and pictures' files are, for a host that draws canvases (raea-page's Blitz page: the page's
/// roots, so a /media/ src is the project's file); until one is given a src is read as a file path.
pub fn videos(find: fn(&str) -> Option<std::path::PathBuf>) {
*VIDEO_PATHS.write().unwrap() = Some(find);
}
@@ -140,9 +140,34 @@ pub(crate) fn page_options() -> usvg::Options<'static> {
db.map_or_else(usvg::Options::default, |db| page_fonts(&db))
}
/// Where a video's src is as a file, for its frames drawn on a canvas (`videos`).
/// Where a video's or a picture's src is as a file, for drawing it on a canvas (`videos`).
static VIDEO_PATHS: std::sync::RwLock<Option<fn(&str) -> Option<std::path::PathBuf>>> = std::sync::RwLock::new(None);
/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too).
fn media_file(src: &str) -> Option<std::path::PathBuf> {
match *VIDEO_PATHS.read().unwrap() {
Some(f) => f(src),
None => Some(std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src))),
}
}
/// A picture that isn't inline, read from its file, with its type by its name: drawImage of an <img> or new Image()
/// whose src is the project's /media/ file (raea #253: the card's screenshot drew nothing, as only data: URLs were
/// decoded).
pub(crate) fn image_file(src: &str) -> Option<(String, Vec<u8>)> {
let path = media_file(src)?;
let mime = match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"webp" => "image/webp",
"gif" => "image/gif",
"bmp" => "image/bmp",
"svg" => "image/svg+xml",
_ => return None,
};
Some((mime.to_string(), std::fs::read(path).ok()?))
}
/// A video's frame at `t`, as a pixmap: opened and decoded on the CPU when it's asked for (a histogram reads one frame
/// per seek), the last few kept.
fn video_frame(src: &str, t: f64) -> Option<sk::Pixmap> {
@@ -150,10 +175,7 @@ fn video_frame(src: &str, t: f64) -> Option<sk::Pixmap> {
if let Some((.., pm)) = FRAMES.lock().unwrap().iter().find(|(s, b, _)| s == src && *b == t.to_bits()) {
return Some(pm.clone());
}
let path = match *VIDEO_PATHS.read().unwrap() {
Some(f) => f(src)?,
None => std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src)),
};
let path = media_file(src)?;
let frame = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(&path).ok()?.frame_at(t).ok())?;
let mut pm = sk::Pixmap::new(frame.width, frame.height)?;
for (i, px) in pm.pixels_mut().iter_mut().enumerate() {
@@ -209,6 +231,29 @@ mod tests {
assert_eq!(at(2, 2).alpha(), 0);
}
#[test]
fn a_picture_from_a_file_is_drawn() {
// raea #253: drawImage of a picture whose src is a file (a page's /media/, found by the host's roots) drew nothing
let dir = std::env::temp_dir().join(format!("raea-canvas-pic-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut pic = sk::Pixmap::new(3, 2).unwrap();
pic.fill(sk::Color::from_rgba8(0, 0, 210, 255));
let file = dir.join("shot.png");
pic.save_png(&file).unwrap();
let opt = usvg::Options::default();
let mut pm = sk::Pixmap::new(10, 10).unwrap();
let mut cx = Ctx { opt: &opt, images: HashMap::new() };
let st = serde_json::json!({"ts": [1, 0, 0, 1, 0, 0], "alpha": 1, "comp": "source-over", "clip": [], "shadow": null, "smooth": false});
let src = file.to_string_lossy().to_string();
cx.op(&mut pm, &serde_json::json!(["image", src, null, null, null, null, 2, 2, 6, 4, st]));
assert_eq!(pm.pixel(4, 4).unwrap().demultiply().blue(), 210, "the picture is drawn");
assert_eq!(pm.pixel(1, 1).unwrap().alpha(), 0, "only where it was asked to go");
// a file that isn't a picture, or isn't there, draws nothing and doesn't panic
cx.op(&mut pm, &serde_json::json!(["image", dir.join("none.png").to_string_lossy(), null, null, null, null, 0, 0, 10, 10, st]));
assert_eq!(pm.pixel(1, 1).unwrap().alpha(), 0);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn image_under_a_scale() {
// Excalidraw's way: a 4x4 picture drawn at 2x size under a 0.5 transform covers 4x4 pixels at (2, 2)
+92
View File
@@ -0,0 +1,92 @@
//! Three of 0.1.11's layout misses, each laid out from its issue's own repro: `font-variant: small-caps` drew in normal
//! case (#249), a flex row whose items fit but for f32 rounding wrapped (#252), and a `display: table` element around
//! its text drew nothing at all (#254).
use bevy::math::UVec2;
use blitz_dom::BaseDocument;
use raea_sys_page::{Page, config};
fn laid_out(body: &str) -> BaseDocument {
let html = format!("<!doctype html><html><body style=\"margin:0\">{body}</body></html>");
let mut doc = blitz_html::HtmlDocument::from_html(&html, config(Page { size: UVec2::new(700, 400), scale: 1.0 })).into_inner();
doc.resolve(0.0);
doc
}
/// The border box of the element with `id`: x, y, width, height.
fn rect(doc: &BaseDocument, id: &str) -> (f64, f64, f64, f64) {
let node = doc.query_selector(&format!("#{id}")).unwrap().unwrap_or_else(|| panic!("no #{id}"));
let r = doc.get_client_bounding_rect(node).unwrap_or_else(|| panic!("#{id} has no box"));
(r.x, r.y, r.width, r.height)
}
/// #249: small capitals in a face without an `smcp` feature (Georgia) are synthesised as Chrome does: each lower-case
/// letter drawn as its capital at 70% of the font size. So the line is as wide as those capitals written out at 28 px,
/// and narrower than the text in full capitals.
#[test]
fn small_caps_are_synthesised_capitals_at_70_percent() {
let doc = laid_out(
r#"<div style="font-size: 40px; font-family: Georgia, serif">
<span id="caps" style="font-variant: small-caps">Compliance Audit</span><br>
<span id="spelled">C<span style="font-size: 28px">OMPLIANCE</span> A<span style="font-size: 28px">UDIT</span></span><br>
<span id="plain">Compliance Audit</span><br>
<span id="upper">COMPLIANCE AUDIT</span>
</div>"#,
);
let width = |id| rect(&doc, id).2;
let (caps, spelled, plain, upper) = (width("caps"), width("spelled"), width("plain"), width("upper"));
assert!((caps - spelled).abs() < 0.5, "small caps {caps} px wide, the capitals written out at 28 px {spelled}");
assert!(caps < upper - 20.0, "small caps {caps} px wide, full capitals {upper}");
assert!((caps - plain).abs() > 5.0, "small caps {caps} px wide, the text in normal case {plain}: drawn as it is");
}
/// #252: three 183.6 px items and two 54 px gaps add up to the 658.8 px container in exact arithmetic, a few ulps over
/// it in f32. Chrome lays out in 1/64 px units and keeps them on one line: rows of 3 and 2, not 2, 2 and 1.
#[test]
fn a_flex_row_that_fits_but_for_rounding_stays_one_row() {
let (w, size, cols) = (1080.0_f64, 0.17, 3.0);
let items: String = (0..5).map(|i| format!(r#"<div id="i{i}" style="width: {}px; height: 60px"></div>"#, size * w)).collect();
let doc = laid_out(&format!(
r#"<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: {}px {}px; width: {}px">{items}</div>"#,
0.04 * w,
0.05 * w,
(cols * size + (cols - 1.0) * 0.05) * w
));
let y = |i: usize| rect(&doc, &format!("i{i}")).1;
assert_eq!((y(1), y(2)), (y(0), y(0)), "the first three items share a row");
assert!(y(3) > y(0) && y(4) == y(3), "the last two share the second row: {:?}", (0..5).map(y).collect::<Vec<_>>());
}
/// #254: a `display: table` element holding only text is laid out as Chrome lays it out, its text in an anonymous row
/// and cell: a block as wide as its text (shrink-to-fit), with the next block below it.
#[test]
fn a_table_around_its_text_is_as_wide_as_its_text() {
let doc = laid_out(
r#"<div style="font-size: 30px">
<div id="table" style="display: table; background: #FFD43B">Line one as a table</div>
<div id="next">Line two, block</div>
<span id="text">Line one as a table</span>
</div>"#,
);
let (tx, ty, tw, th) = rect(&doc, "table");
let text = rect(&doc, "text");
let next = rect(&doc, "next");
assert!(th > 30.0, "the table is a line tall: {th}");
assert!((tw - text.2).abs() < 0.5, "the table is {tw} px wide, its text {}", text.2);
assert_eq!((tx, ty), (0.0, 0.0));
assert!((next.1 - (ty + th)).abs() < 0.5, "the next block starts below the table: {} against {}", next.1, ty + th);
}
/// #254, the rest of css-tables-3's wrapping: a table's stray text beside a row of its own gets an anonymous row of its
/// own above it, and a table of rows alone builds no anonymous box (its cells as before).
#[test]
fn stray_text_beside_a_row_gets_a_row_of_its_own() {
let doc = laid_out(
r#"<div id="t" style="display: table; font-size: 20px">loose
<div style="display: table-row"><div id="cell" style="display: table-cell">in a cell</div></div></div>
<table id="plain"><tr><td id="td">a</td></tr></table>"#,
);
let cell = rect(&doc, "cell");
assert!(cell.1 >= 20.0, "the cell is in the second row, below the loose text: {cell:?}");
let td = rect(&doc, "td");
assert!(td.2 > 0.0 && td.3 > 0.0, "a plain table's cell keeps its box: {td:?}");
}
+1
View File
@@ -231,6 +231,7 @@ raea-app-game = "apps"
raea-app-capcut = "apps"
raea-app-layers = "apps"
raea-app-play = "apps"
raea-app-playable = "apps"
raea-page-host = "runtime"
raea-rune-host = "runtime"
raea-rune-page = "runtime"
+1 -1
View File
@@ -25,7 +25,7 @@ const verbs: Verb[] = JSON.parse(run(["help", "--json"])).verbs
// the index's groups, in the order a reader meets them; every verb is in one
const GROUPS: [string, string, string[]][] = [
["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "export", "bundle", "app", "run"]],
["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "playable", "export", "bundle", "app", "run"]],
["Projects", "The workspace, its projects and what a project holds.", ["init", "workspace", "project", "spec", "component", "part", "add", "brand", "library", "index"]],
["Check", "What's wrong before anyone watches it.", ["check", "judge", "make", "fingerprint", "findings", "scene", "light", "bench", "world", "solid", "next", "doctor", "hook", "traces"]],
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],
+2 -1
View File
@@ -13,7 +13,8 @@ use style::{
};
/// Query fontique for the fonts matching `font_styles` (family list and attributes).
fn query_for_font_styles<'a>(
/// raea: small_caps.rs asks it for the face it checks for `smcp` (#249)
pub(crate) fn query_for_font_styles<'a>(
font_ctx: &'a mut FontContext,
font_styles: &'a FontStyles,
) -> parley::fontique::Query<'a> {
+60 -2
View File
@@ -573,7 +573,9 @@ fn collect_layout_children_with_wrap(
}
DisplayInside::Table => {
let (table_context, tlayout_children) = build_table_context(doc, container_node_id);
let wrapped = wrap_table_strays(doc, container_node_id, out);
let (table_context, tlayout_children) =
build_table_context(doc, container_node_id, wrapped);
#[allow(clippy::arc_with_non_send_sync)]
let data = SpecialElementData::TableRoot(Arc::new(table_context));
doc.nodes[container_node_id]
@@ -802,6 +804,49 @@ fn flush_pseudo_elements(doc: &mut BaseDocument, node_id: NodeId) {
}
}
/// raea: a table's children with each run of children that are no table box (text, a block or inline element, a
/// table inside it) wrapped in an anonymous block, which table.rs lays out as an anonymous row holding one anonymous
/// cell (css-tables-3 § 3.3, as Chrome does). Blitz dropped them, so a `display: table` element around its text (a
/// shrink-wrapped line) drew nothing, not even its background (#254). None when there is no such run (no text but
/// whitespace), so a table of rows builds no anonymous block. The blocks are `out`'s to free on reconstruction.
fn wrap_table_strays(
doc: &mut BaseDocument,
table_id: NodeId,
out: &mut LayoutChildren,
) -> Option<Vec<NodeId>> {
fn is_stray(node: &Node) -> bool {
match node.data.kind() {
NodeKind::Text => true,
NodeKind::Element => node.primary_styles().is_some_and(|style| {
let display = style.clone_display();
matches!(display.outside(), DisplayOutside::Block | DisplayOutside::Inline)
&& display.inside() != DisplayInside::Contents
&& !style.clone_position().is_absolutely_positioned()
}),
_ => false,
}
}
let children = doc.nodes[table_id].children.clone();
let any = children.iter().any(|&id| {
let node = &doc.nodes[id];
is_stray(node) && !node.is_whitespace_node()
});
if !any {
return None;
}
let mut runs = LayoutChildren::default();
for id in children {
match doc.nodes[id].data.kind() {
NodeKind::Comment => {}
_ if is_stray(&doc.nodes[id]) => runs.push_wrapped(table_id, id, doc),
_ => runs.push(id, doc),
}
}
runs.maybe_push_anon_block(doc);
out.anonymous_blocks.extend(runs.anonymous_blocks.iter().copied());
Some(runs.children.into_iter().collect())
}
/// Handles the cases where there are text nodes or inline nodes that need to be wrapped in an anonymous block node
fn collect_complex_layout_children(
doc: &mut BaseDocument,
@@ -1085,6 +1130,10 @@ pub(crate) fn build_inline_layout_into(
..Default::default()
});
// raea: which of its elements' text gets synthesised small capitals, asked of the fonts before the builder holds
// them (#249)
let small_caps = super::small_caps::synthesized(nodes, inline_context_root_node_id, font_ctx);
// Create a parley tree builder
let mut builder = layout_ctx.tree_builder(font_ctx, scale, true, &parley_style);
if let Some(style) = root_node_style.as_deref() {
@@ -1124,6 +1173,7 @@ pub(crate) fn build_inline_layout_into(
};
// The marker is a separate box, so words in the content don't continue from it.
let mut text_transformer = TextTransformer::default();
text_transformer.small_caps = small_caps;
text_transformer.word_break(&builder);
// raea: the root's bidi override around its content (stylo_to_parley::bidi_controls)
@@ -1395,10 +1445,18 @@ pub(crate) fn build_inline_layout_into(
s.clone_white_space_collapse() != stylo_to_parley::stylo::WhiteSpaceCollapse::Collapse
});
let bidi = if keeps_newlines { std::mem::take(&mut text_transformer.bidi) } else { Vec::new() };
// raea: the font size its synthesised small capitals scale, when they're its parent's (#249)
let small_caps = node
.parent
.filter(|p| text_transformer.small_caps.contains(p))
.and_then(|p| nodes[p].primary_styles().map(|s| s.get_font().font_size.used_size.0.px()));
let text =
text_transformer.transform(&data.content, parent_text_transform, builder);
let start = builder.text().len();
builder.push_text(&bidi_newlines(text, &bidi));
match small_caps {
Some(font_size) => super::small_caps::push(builder, &bidi_newlines(text, &bidi), font_size),
None => builder.push_text(&bidi_newlines(text, &bidi)),
}
text_transformer.texts.push((node_id, start, builder.text().len()));
if keeps_newlines {
text_transformer.bidi = bidi;
+2
View File
@@ -28,6 +28,8 @@ pub(crate) mod inline;
pub(crate) mod list;
pub(crate) mod paint_tree;
pub(crate) mod replaced;
// raea: synthesised small capitals (#249)
pub(crate) mod small_caps;
pub(crate) mod table;
pub(crate) mod text_transform;
#[cfg(feature = "writing-mode")]
+143
View File
@@ -0,0 +1,143 @@
//! raea: `font-variant: small-caps` as Chrome draws it (#249). A face with an `smcp` feature gets it
//! (stylo_to_parley::font_variant_caps); for a face without one (Georgia, Times, Helvetica: most system faces) Chrome
//! synthesises the small capitals, each lower-case letter drawn as its capital at 70% of the font size (Blink's
//! kSmallCapsFontSizeMultiplier). Blitz only asked for the feature, so such text drew in normal case, with no warning.
use std::cell::RefCell;
use std::collections::HashMap;
use blitz_traits::node_id::NodeId;
use parley::fontique::{QueryFont, QueryStatus};
use parley::{FontContext, StyleProperty, TreeBuilder};
use skrifa::MetadataProvider as _;
use skrifa::raw::TableProvider as _;
use style::properties::style_structs::Font as FontStyles;
use crate::font_metrics::query_for_font_styles;
use crate::node::TextBrush;
use crate::stylo_to_parley::stylo::FontVariantCaps;
/// The size of a synthesised small capital, as a fraction of the font size (Blink's)
pub(crate) const SCALE: f32 = 0.7;
thread_local! {
/// whether a face (its blob's id and index in it) has an `smcp` feature, read once
static SMCP: RefCell<HashMap<(u64, u32), bool>> = RefCell::new(HashMap::new());
}
/// The elements whose text under `root` (an inline layout's root) is drawn in synthesised small capitals: each text
/// node's parent (its DOM parent, which an anonymous block wrapping the text isn't) whose font-variant-caps is
/// small-caps, in a face whose lower-case letters have no `smcp` feature.
pub(crate) fn synthesized(nodes: &crate::NodeTree, root: NodeId, fcx: &mut FontContext) -> Vec<NodeId> {
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(id) = stack.pop() {
let node = &nodes[id];
if node.is_text_node() {
let Some(parent) = node.parent.filter(|p| !out.contains(p)) else { continue };
let Some(style) = nodes[parent].primary_styles() else { continue };
let font = style.get_font();
if font.font_variant_caps == FontVariantCaps::SmallCaps && !has_smcp(fcx, font) {
out.push(parent);
}
continue;
}
stack.extend(node.children.iter().copied());
stack.extend(node.before());
stack.extend(node.after());
}
out
}
/// Whether the face `font` draws a lower-case `a` in has an `smcp` feature (true when no face has the letter: then
/// there is nothing to synthesise).
fn has_smcp(fcx: &mut FontContext, font: &FontStyles) -> bool {
let mut query = query_for_font_styles(fcx, font);
let mut face = None;
query.matches_with(|q: &QueryFont| {
let maps = skrifa::FontRef::from_index(q.blob.as_ref(), q.index).is_ok_and(|f| f.charmap().map('a').is_some());
if !maps {
return QueryStatus::Continue;
}
face = Some((q.blob.clone(), q.index));
QueryStatus::Stop
});
let Some((blob, index)) = face else { return true };
SMCP.with(|seen| *seen.borrow_mut().entry((blob.id(), index)).or_insert_with(|| has_feature(blob.as_ref(), index, b"smcp")))
}
/// Whether the face at `index` in `data` lists the GSUB feature `tag`.
pub(crate) fn has_feature(data: &[u8], index: u32, tag: &[u8; 4]) -> bool {
let tag = skrifa::Tag::new(tag);
let Ok(font) = skrifa::FontRef::from_index(data, index) else { return false };
let Ok(list) = font.gsub().and_then(|gsub| gsub.feature_list()) else { return false };
list.feature_records().iter().any(|record| record.feature_tag() == tag)
}
/// A lower-case letter a synthesised small capital replaces: one with a capital of its own.
fn is_small(c: char) -> bool {
c.is_lowercase() && !c.to_uppercase().eq(std::iter::once(c))
}
/// `text` pushed with each run of lower-case letters as their capitals at SCALE of `font_size` (px), the rest as it is.
pub(crate) fn push(builder: &mut TreeBuilder<TextBrush>, text: &str, font_size: f32) {
let mut rest = text;
while let Some(first) = rest.chars().next() {
let small = is_small(first);
let end = rest.char_indices().find(|&(_, c)| is_small(c) != small).map_or(rest.len(), |(i, _)| i);
let (run, tail) = rest.split_at(end);
if small {
builder.push_style_modification_span(&[StyleProperty::FontSize(font_size * SCALE)]);
builder.push_text(&run.to_uppercase());
builder.pop_style_span();
} else {
builder.push_text(run);
}
rest = tail;
}
}
#[cfg(test)]
mod tests {
use super::*;
use parley::{LayoutContext, TextStyle};
/// Each glyph run's text and font size, for `text` pushed as small capitals at 40 px.
fn runs(text: &str) -> Vec<(String, f32)> {
let mut font_ctx = FontContext::new();
let mut layout_ctx: LayoutContext<TextBrush> = LayoutContext::new();
let style = TextStyle { font_size: 40.0, ..TextStyle::default() };
let mut builder = layout_ctx.tree_builder(&mut font_ctx, 1.0, true, &style);
push(&mut builder, text, 40.0);
let mut layout = parley::Layout::new();
let built = builder.build_into(&mut layout);
layout.break_all_lines(None);
let mut out = Vec::new();
for line in layout.lines() {
for item in line.items() {
if let parley::PositionedLayoutItem::GlyphRun(run) = item {
out.push((built[run.run().text_range()].to_string(), run.run().font_size()));
}
}
}
out
}
#[test]
fn lower_case_letters_are_capitals_at_70_percent() {
let want = [("C", 40.0), ("OMPLIANCE", 28.0), (" A", 40.0), ("UDIT", 28.0)];
let want: Vec<(String, f32)> = want.iter().map(|(t, s)| (t.to_string(), *s)).collect();
assert_eq!(runs("Compliance Audit"), want);
}
#[test]
fn capitals_digits_and_spaces_keep_their_size() {
assert_eq!(runs("A1 B"), vec![("A1 B".to_string(), 40.0)]);
}
#[test]
fn a_letter_without_a_capital_of_its_own_keeps_its_size() {
// U+0138 kra is lower-case and has no capital
assert!(!is_small('ĸ') && is_small('a') && !is_small('A') && !is_small('1'));
}
}
+19 -4
View File
@@ -208,9 +208,12 @@ fn percent_plus_length(
dim.into()
}
/// raea: `wrapped` is the table's children with each run of children that are no table box (its text, a block or
/// an inline element) in an anonymous block (construct.rs `wrap_table_strays`, #254); None when it has no such run
pub(crate) fn build_table_context(
doc: &mut BaseDocument,
table_root_node_id: NodeId,
wrapped: Option<Vec<NodeId>>,
) -> (TableContext, Vec<NodeId>) {
let mut cells: Vec<TableCell> = Vec::new();
let mut oof_children: Vec<(NodeId, taffy::Position)> = Vec::new();
@@ -221,7 +224,8 @@ pub(crate) fn build_table_context(
let wm = table_wm(doc, table_root_node_id);
let root_node = &mut doc.nodes[table_root_node_id];
let children = std::mem::take(&mut root_node.children);
let dom_children = std::mem::take(&mut root_node.children);
let children = wrapped.unwrap_or_else(|| dom_children.to_vec());
let Some(stylo_styles) = root_node.primary_styles() else {
panic!("Ignoring table because it has no styles");
@@ -469,7 +473,7 @@ pub(crate) fn build_table_context(
.chain(oof_children.iter().map(|(node_id, _)| *node_id))
.collect();
let root_node = &mut doc.nodes[table_root_node_id];
root_node.children = children;
root_node.children = dom_children;
(
TableContext {
@@ -582,7 +586,9 @@ fn collect_table_cells(
) {
let node = &mut doc.nodes[node_id];
if !node.is_element() {
// raea: an anonymous block here is one construct.rs wrapped a run of the table's stray children in (#254)
let anonymous = node.is_anonymous();
if !node.is_element() && !anonymous {
return;
}
@@ -605,7 +611,16 @@ fn collect_table_cells(
return;
}
match display.inside() {
// raea: it is an anonymous row holding one anonymous cell, as css-tables-3 § 3.3 wraps such a run (#254)
let inside = if anonymous {
*row += 1;
cursor.start_row();
rows.push(TableRow { node_id, group: None, height: None, is_constrained: false });
DisplayInside::TableCell
} else {
display.inside()
};
match inside {
DisplayInside::TableRowGroup
| DisplayInside::TableHeaderGroup
| DisplayInside::TableFooterGroup
+2
View File
@@ -117,6 +117,8 @@ pub(crate) struct TextTransformer {
pub(crate) bidi: Vec<(&'static str, &'static str)>,
/// raea: each text node's bytes in the builder's text, as pushed (TextLayout::text_nodes)
pub(crate) texts: Vec<(blitz_traits::node_id::NodeId, usize, usize)>,
/// raea: the elements whose own text is drawn in synthesised small capitals (layout/small_caps.rs, #249)
pub(crate) small_caps: Vec<blitz_traits::node_id::NodeId>,
}
impl TextTransformer {
+168
View File
@@ -0,0 +1,168 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.71"
name = "taffy"
version = "0.15.0"
authors = [
"Alice Cecile <[email protected]>",
"Johnathan Kelley <[email protected]>",
"Nico Burns <[email protected]>",
]
build = false
include = [
"src/**/*",
"examples/**/*",
"Cargo.toml",
"README.md",
]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "A flexible UI layout library "
readme = "README.md"
keywords = [
"cross-platform",
"layout",
"flexbox",
"css-grid",
"grid",
]
categories = ["gui"]
license = "MIT"
repository = "https://github.com/DioxusLabs/taffy"
[package.metadata.docs.rs]
all-features = true
cargo-args = [
"-Zunstable-options",
"-Zrustdoc-scrape-examples",
]
rustdoc-args = [
"--cfg",
"docsrs",
]
[features]
alloc = []
block_layout = []
calc = []
content_size = []
debug = ["std"]
default = [
"std",
"taffy_tree",
"flexbox",
"flexbox_balance",
"grid",
"block_layout",
"float_layout",
"calc",
"content_size",
"detailed_layout_info",
]
detailed_layout_info = []
flexbox = []
flexbox_balance = ["flexbox"]
float_layout = []
grid = ["dep:smallvec"]
parse = ["dep:cssparser"]
parse_faster = [
"parse",
"cssparser/fast_match_byte",
]
profile = ["std"]
serde = [
"dep:serde",
"serde/alloc",
]
std = [
"serde?/std",
"slotmap?/std",
]
strict_provenance = []
taffy_tree = ["dep:slotmap"]
[lib]
name = "taffy"
path = "src/lib.rs"
[[example]]
name = "basic"
path = "examples/basic.rs"
doc-scrape-examples = true
[[example]]
name = "custom_tree_owned_partial"
path = "examples/custom_tree_owned_partial.rs"
[[example]]
name = "custom_tree_owned_unsafe"
path = "examples/custom_tree_owned_unsafe.rs"
[[example]]
name = "custom_tree_vec"
path = "examples/custom_tree_vec.rs"
[[example]]
name = "flexbox_gap"
path = "examples/flexbox_gap.rs"
[[example]]
name = "grid_holy_grail"
path = "examples/grid_holy_grail.rs"
[[example]]
name = "measure"
path = "examples/measure.rs"
[[example]]
name = "nested"
path = "examples/nested.rs"
[dependencies.cssparser]
version = "0.37.0"
optional = true
default-features = false
[dependencies.document-features]
version = "0.2.7"
optional = true
[dependencies.serde]
version = "1.0"
features = ["serde_derive"]
optional = true
default-features = false
[dependencies.slotmap]
version = "1.0.6"
optional = true
default-features = false
[dependencies.smallvec]
version = "1.13"
optional = true
default-features = false
[dev-dependencies.roxmltree]
version = "0.21.1"
[dev-dependencies.serde_json]
version = "1.0.93"
[profile.release]
lto = true
panic = "abort"
+124
View File
@@ -0,0 +1,124 @@
[package]
name = "taffy"
version = "0.15.0"
authors = [
"Alice Cecile <[email protected]>",
"Johnathan Kelley <[email protected]>",
"Nico Burns <[email protected]>",
]
edition = "2021"
rust-version = "1.71"
include = ["src/**/*", "examples/**/*", "Cargo.toml", "README.md"]
description = "A flexible UI layout library "
repository = "https://github.com/DioxusLabs/taffy"
keywords = ["cross-platform", "layout", "flexbox", "css-grid", "grid"]
categories = ["gui"]
license = "MIT"
[dependencies]
document-features = { version = "0.2.7", optional = true }
serde = { version = "1.0", default-features = false, optional = true, features = ["serde_derive"] }
slotmap = { version = "1.0.6", default-features = false, optional = true }
smallvec = { version = "1.13", default-features = false, optional = true }
cssparser = { version = "0.37.0", default-features = false, optional = true }
[package.metadata.docs.rs]
# To test all the documentation related features, run:
# RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc -Zunstable-options -Zrustdoc-scrape-examples --all-features --no-deps --open
all-features = true
# see https://doc.rust-lang.org/nightly/rustdoc/scraped-examples.html
cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]
rustdoc-args = ["--cfg", "docsrs"]
[features]
default = [
"std",
"taffy_tree",
"flexbox",
"flexbox_balance",
"grid",
"block_layout",
"float_layout",
"calc",
"content_size",
"detailed_layout_info",
]
#! ## Feature Flags
#!
#! ### Algorithms
## Enables the Block layout algorithm. See [`compute_block_layout`](crate::compute_block_layout).
block_layout = []
## Enables the Float layout algorithm. This is a sub-feature of block layout.
float_layout = []
## Enables the Flexbox layout algorithm. See [`compute_flexbox_layout`](crate::compute_flexbox_layout).
flexbox = []
## Enables support for `flex-wrap: balance` and `flex-line-count` from [CSS Flexbox Level 2](https://drafts.csswg.org/css-flexbox-2/)
flexbox_balance = ["flexbox"]
## Enables the CSS Grid layout algorithm. See [`compute_grid_layout`](crate::compute_grid_layout).
grid = ["dep:smallvec"]
## Enables calc() values for all layout algorithms
calc = []
## Causes all algorithms to compute and output a content size for each node
content_size = []
## Causes algorithms to stores detailed information of the nodes in TaffyTree, with only CSS Grid supporting this.
detailed_layout_info = []
## Use strict provenance APIs for pointer manipulation. Using this feature requires Rust 1.84 or higher.
strict_provenance = []
#! ### Taffy Tree
## Enable the built-in Taffy node tree. See [`TaffyTree`](crate::TaffyTree).
taffy_tree = ["dep:slotmap"]
#! ### Other
## Add [`serde`] derives to Style structs
serde = ["dep:serde", "serde/alloc"]
## Implement `FromStr` trait for Taffy style types
parse = ["dep:cssparser"]
## Enable the `parse` feature with proc-macro dependent optimisations
parse_faster = ["parse", "cssparser/fast_match_byte"]
## Allow Taffy to depend on the [`Rust Standard Library`](std)
std = ["serde?/std", "slotmap?/std"]
## Deprecated no-op: Taffy always depends on the `alloc` library. Retained so that existing `features = ["alloc"]` configurations keep compiling.
alloc = []
## Internal feature for debugging
debug = ["std"]
## Internal feature for profiling
profile = ["std"]
[dev-dependencies]
serde_json = "1.0.93"
roxmltree = "0.21.1"
taffy_test_helpers = { path = "tests/common"}
# Enable default features for tests and examples
taffy = { path = ".", features = ["parse"] }
[profile.release]
lto = true
panic = 'abort'
[[bench]]
name = "dummy_benchmark"
path = "benches/dummy_benchmark.rs"
harness = false
[[example]]
name = "basic"
# This causes all the examples to be scraped for documentation, not just the basic example
doc-scrape-examples = true
[workspace]
members = [
"scripts/gentest",
"scripts/getchrome",
"scripts/format-fixtures",
"scripts/import-yoga-tests",
"tests/common",
]
# The Parley example and benches are excluded from the workspace as their dependencies require a newer
# Rust version than Taffy's MSRV
exclude = ["examples/parley", "benches"]
+139
View File
@@ -0,0 +1,139 @@
<!-- markdownlint-disable-next-line MD041 -->
<p>
<picture>
<img src="assets/logo.svg" alt="Taffy" height="70">
</picture>
</p>
[![GitHub CI](https://github.com/DioxusLabs/taffy/actions/workflows/ci.yml/badge.svg)](https://github.com/DioxusLabs/taffy/actions/workflows/ci.yml)
[![crates.io](https://img.shields.io/crates/v/taffy.svg)](https://crates.io/crates/taffy)
[![docs.rs](https://img.shields.io/docsrs/taffy)](https://docs.rs/taffy)
![Crates.io MSRV](https://img.shields.io/crates/msrv/taffy)
Taffy is a flexible, high-performance, cross-platform UI layout library written in [Rust](https://www.rust-lang.org).
It currently implements the CSS **Block**, **Flexbox** and **CSS Grid** layout algorithms. Support for other paradigms is planned. For more information on this and other future development plans see the [roadmap issue](https://github.com/DioxusLabs/taffy/issues/345).
This crate is a collaborative, cross-team project, and is designed to be used as a dependency for other UI and GUI libraries.
Right now, it powers:
- [Servo](https://github.com/servo/servo): an alternative web browser
- [Blitz](https://github.com/DioxusLabs/blitz): a radically modular web engine
- [Bevy](https://bevyengine.org/): an ergonomic, ECS-first Rust game engine
- [Takumi](https://github.com/kane50613/takumi): Renders your React components to images
- [iocraft](https://github.com/ccbrown/iocraft): crafting beautiful interfaces for the terminal
- [Slint](https://github.com/slint-ui/slint): a declarative GUI toolkit for building native user interfaces
- The [Lapce](https://lapce.dev/) text editor via the [Floem](https://github.com/lapce/floem) UI framework
- The [Zed](https://zed.dev/) text editor via the [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui) UI framework
## Usage
```rust
use taffy::prelude::*;
// First create an instance of TaffyTree
let mut tree : TaffyTree<()> = TaffyTree::new();
// Create a tree of nodes using `TaffyTree.new_leaf` and `TaffyTree.new_with_children`.
// These functions both return a node id which can be used to refer to that node
// The Style struct is used to specify styling information
let header_node = tree
.new_leaf(
Style {
size: Size { width: length(800.0), height: length(100.0) },
..Default::default()
},
).unwrap();
let body_node = tree
.new_leaf(
Style {
size: Size { width: length(800.0), height: auto() },
flex_grow: 1.0,
..Default::default()
},
).unwrap();
let root_node = tree
.new_with_children(
Style {
flex_direction: FlexDirection::Column,
size: Size { width: length(800.0), height: length(600.0) },
..Default::default()
},
&[header_node, body_node],
)
.unwrap();
// Call compute_layout on the root of your tree to run the layout algorithm
tree.compute_layout(root_node, Size::MAX_CONTENT).unwrap();
// Inspect the computed layout using `TaffyTree.layout`
assert_eq!(tree.layout(root_node).unwrap().size.width, 800.0);
assert_eq!(tree.layout(root_node).unwrap().size.height, 600.0);
assert_eq!(tree.layout(header_node).unwrap().size.width, 800.0);
assert_eq!(tree.layout(header_node).unwrap().size.height, 100.0);
assert_eq!(tree.layout(body_node).unwrap().size.width, 800.0);
assert_eq!(tree.layout(body_node).unwrap().size.height, 500.0); // This value was not set explicitly, but was computed by Taffy
```
## Bindings to other languages
- Python via [stretchable](https://github.com/mortencombat/stretchable)
- [WIP C bindings](https://github.com/DioxusLabs/taffy/pull/404)
- [WIP WASM bindings](https://github.com/DioxusLabs/taffy/pull/394)
## Learning Resources
Taffy implements the Flexbox and CSS Grid specifications faithfully, so documentation designed for the web should translate cleanly to Taffy's implementation. For reference documentation on individual style properties we recommend the MDN documentation (for example [this page](https://developer.mozilla.org/en-US/docs/Web/CSS/width) on the `width` property). Such pages can usually be found by searching for "MDN property-name" using a search engine.
If you are interested in guide-level documentation on CSS layout, then we recommend the following resources:
### Flexbox
- [Flexbox Froggy](https://flexboxfroggy.com/). This is an interactive tutorial/game that allows you to learn the essential parts of Flexbox in a fun engaging way.
- [A Complete Guide To Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different Flexbox properties and how they work.
### CSS Grid
- [CSS Grid Garden](https://cssgridgarden.com/). This is an interactive tutorial/game that allows you to learn the essential parts of CSS Grid in a fun engaging way.
- [A Complete Guide To CSS Grid](https://css-tricks.com/snippets/css/complete-guide-grid/) by CSS Tricks. This is detailed guide with illustrations and comprehensive written explanation of the different CSS Grid properties and how they work.
## Benchmarks (vs. [Yoga](https://github.com/facebook/yoga))
- Run on a 2021 MacBook Pro with M1 Pro processor using [criterion](https://github.com/bheisler/criterion.rs)
- The benchmarks measure layout computation only. They do not measure tree creation.
- Yoga benchmarks were run via the [yoga](https://github.com/bschwind/yoga-rs) crate (Rust bindings), version 0.5.0
- Most popular websites seem to have between 3,000 and 10,000 nodes (although they also require text layout, which neither yoga nor taffy implement).
Note that the table below contains multiple different units (seconds vs. milliseconds vs. microseconds)
| Benchmark | Node Count | Depth | Yoga ([v3.2.1]) | Taffy ([e747f6e]) |
| --- | --- | --- | --- | --- |
| yoga 'huge nested' | 1,000 | 3 | 328.24 µs | 250.23 µs |
| yoga 'huge nested' | 10,000 | 4 | 3.2892 ms | 2.6947 ms |
| yoga 'huge nested' | 100,000 | 5 | 41.686 ms | 32.871 ms |
| big trees (wide) | 1,000 | 2 | 468.66 µs | 471.14 µs |
| big trees (wide) | 10,000 | 2 | 4.8667 ms | 4.8032 ms |
| big trees (wide) | 100,000 | 2 | 63.304 ms | 58.111 ms |
| absolutely positioned leaves | 1,000 | 2 | 408.51 µs | 259.91 µs |
| absolutely positioned leaves | 10,000 | 2 | 4.3898 ms | 2.7890 ms |
| absolutely positioned leaves | 100,000 | 2 | 56.490 ms | 41.270 ms |
| big trees (deep, random size) | 4,000 | 12 | 1.7937 ms | 1.8160 ms |
| big trees (deep, random size) | 10,000 | 14 | 4.4436 ms | 4.5843 ms |
| big trees (deep, random size) | 100,000 | 17 | 63.555 ms | 69.952 ms |
| big trees (deep, auto size) | 4,000 | 12 | 32.872 ms | 4.7357 ms |
| big trees (deep, auto size) | 10,000 | 14 | 103.19 ms | 11.894 ms |
| big trees (deep, auto size) | 100,000 | 17 | 2.3502 s | 164.24 ms |
| super deep | 150 | 50 | 61.132 ms | 179.02 µs |
| super deep | 300 | 100 | did not finish (>9min) | 366.89 µs |
[v3.2.1]: https://github.com/facebook/yoga/commit/042f5013152eb81c1552dec945b88f7b95ca350f
[e747f6e]: https://github.com/DioxusLabs/taffy/commit/e747f6e5b94e7b0586d807aeb681b48f9a005f04
## Contributions
[Contributions welcome](https://github.com/DioxusLabs/taffy/blob/main/CONTRIBUTING.md):
if you'd like to use, improve or build `taffy`, feel free to join the conversation, open an [issue](https://github.com/DioxusLabs/taffy/issues) or submit a [PR](https://github.com/DioxusLabs/taffy/pulls).
If you have questions about how to use `taffy`, open a [discussion](https://github.com/DioxusLabs/taffy/discussions) so we can answer your questions in a way that others can find.
+1824
View File
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
//! Generic CSS alignment code that is shared between both the Flexbox and CSS Grid algorithms.
use crate::style::{AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignmentSafety};
/// Resolve the `safe`/`unsafe` overflow-position fallback for a self-level alignment value
/// (used by `align-self` / `justify-self`-style sites and by absolutely-positioned items in
/// flex/grid). If the alignment subject overflows its alignment container and the requested
/// alignment is `safe`, fall back to logical `Start` per CSS Box Alignment
/// <https://www.w3.org/TR/css-align-3/#overflow-values>. Otherwise drop the safety modifier
/// and return the bare keyword.
#[inline]
pub(crate) fn resolve_self_alignment_safety(alignment: AlignItems, overflows: bool) -> AlignItemsKeyword {
if matches!(alignment.safety, AlignmentSafety::Safe) && overflows {
AlignItemsKeyword::Start
} else {
alignment.keyword
}
}
/// Resolve any spec-defined fallbacks for the given [`AlignContent`] value, returning the
/// bare position keyword the alignment math should use.
///
/// In addition to the spec at <https://www.w3.org/TR/css-align-3/> this implementation follows
/// the resolution of <https://github.com/w3c/csswg-drafts/issues/10154>.
///
/// `normal` behaves differently in each layout mode, so callers must resolve
/// [`AlignContentKeyword::Normal`] to the keyword it behaves as before calling this function
/// (if it is not resolved then it is treated as `stretch`).
pub(crate) fn apply_alignment_fallback(
free_space: f32,
num_items: usize,
alignment_mode: AlignContent,
) -> AlignContentKeyword {
debug_assert!(
alignment_mode.keyword != AlignContentKeyword::Normal,
"normal must be resolved before computing content alignment"
);
let mut keyword = match alignment_mode.keyword {
AlignContentKeyword::Normal => AlignContentKeyword::Stretch,
keyword => keyword,
};
let mut is_safe = matches!(alignment_mode.safety, AlignmentSafety::Safe);
// 1. If there is only a single item being aligned or the items overflow the container, the
// distributed alignment keywords (`stretch`, `space-*`) fall back to a positional keyword
// and gain implicit `safe` semantics so step 2 can flip them to `Start` on overflow.
// https://www.w3.org/TR/css-align-3/#distribution-values
if num_items <= 1 || free_space <= 0.0 {
(keyword, is_safe) = match keyword {
AlignContentKeyword::Stretch | AlignContentKeyword::SpaceBetween => (AlignContentKeyword::FlexStart, true),
AlignContentKeyword::SpaceAround | AlignContentKeyword::SpaceEvenly => (AlignContentKeyword::Center, true),
other => (other, is_safe),
};
}
// 2. Safe alignment falls back to `Start` whenever the alignment subject would overflow the
// alignment container.
if free_space <= 0.0 && is_safe {
keyword = AlignContentKeyword::Start;
}
keyword
}
/// Generic alignment function that is used:
/// - For both align-content and justify-content alignment
/// - For both the Flexbox and CSS Grid algorithms
///
/// CSS Grid does not apply gaps as part of alignment, so the gap parameter should
/// always be set to zero for CSS Grid.
pub(crate) fn compute_alignment_offset(
free_space: f32,
num_items: usize,
gap: f32,
alignment_mode: AlignContentKeyword,
layout_is_flex_reversed: bool,
is_first: bool,
) -> f32 {
if is_first {
match alignment_mode {
AlignContentKeyword::Start => 0.0,
AlignContentKeyword::FlexStart => {
if layout_is_flex_reversed {
free_space
} else {
0.0
}
}
AlignContentKeyword::End => free_space,
AlignContentKeyword::FlexEnd => {
if layout_is_flex_reversed {
0.0
} else {
free_space
}
}
AlignContentKeyword::Center => free_space / 2.0,
AlignContentKeyword::Normal | AlignContentKeyword::Stretch => 0.0,
AlignContentKeyword::SpaceBetween => 0.0,
AlignContentKeyword::SpaceAround => {
if free_space >= 0.0 {
(free_space / num_items as f32) / 2.0
} else {
free_space / 2.0
}
}
AlignContentKeyword::SpaceEvenly => {
if free_space >= 0.0 {
free_space / (num_items + 1) as f32
} else {
free_space / 2.0
}
}
}
} else {
let free_space = free_space.max(0.0);
gap + match alignment_mode {
AlignContentKeyword::Start
| AlignContentKeyword::FlexStart
| AlignContentKeyword::End
| AlignContentKeyword::FlexEnd
| AlignContentKeyword::Center
| AlignContentKeyword::Normal
| AlignContentKeyword::Stretch => 0.0,
AlignContentKeyword::SpaceBetween => free_space / (num_items - 1) as f32,
AlignContentKeyword::SpaceAround => free_space / num_items as f32,
AlignContentKeyword::SpaceEvenly => free_space / (num_items + 1) as f32,
}
}
}
+6
View File
@@ -0,0 +1,6 @@
//! Generic code that is shared between multiple layout algorithms
pub(crate) mod alignment;
pub(crate) mod sizing_keyword;
#[cfg(feature = "content_size")]
pub(crate) mod scrollable_overflow;
+62
View File
@@ -0,0 +1,62 @@
//! Generic CSS scrollable overflow code that is shared between all CSS algorithms.
use crate::geometry::{Point, Rect, Size};
use crate::style::{Contain, Overflow};
use crate::util::sys::{f32_max, f32_min};
#[inline(always)]
/// Determine the rectangle that a given node contributes to its parent's scrollable overflow
/// rectangle.
///
/// `location` is the position of the node's border box measured from the parent's scroll origin
/// (logical start edge): callers pass coordinates that are mirrored for RTL. The node's own
/// `scrollable_overflow_rect` propagates to the parent only where the node's overflow allows it
/// to escape: a scroll container (`Hidden`/`Scroll` in either axis) clips both axes and
/// contributes only its border box, while for non-scroll-containers `Clip` clips just its own
/// axis and `Visible` propagates.
///
/// Boxes positioned wholly in the unreachable scrollable overflow region (entirely before the
/// scroll origin in either axis) must be clipped by a scroll container and are excluded from its
/// scrollable overflow region (<https://www.w3.org/TR/css-overflow-3/#scrollable>). This
/// exclusion only applies when the parent is a scroll container: boxes with `overflow: visible`
/// have no unreachable region of their own, so all of their content contributes.
///
/// A box whose containment contains its scrollable overflow (layout or paint containment)
/// contributes only its border box, regardless of its overflow style.
pub(crate) fn compute_scrollable_overflow_contribution(
location: Point<f32>,
size: Size<f32>,
scrollable_overflow_rect: Rect<f32>,
overflow: Point<Overflow>,
contain: Contain,
parent_is_scroll_container: bool,
) -> Rect<f32> {
let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
let overflow_is_contained = contain.contains_scrollable_overflow();
let propagates = Point {
x: !is_scroll_container && !overflow_is_contained && overflow.x == Overflow::Visible,
y: !is_scroll_container && !overflow_is_contained && overflow.y == Overflow::Visible,
};
let end_extent = Size {
width: if propagates.x { f32_max(size.width, scrollable_overflow_rect.right) } else { size.width },
height: if propagates.y { f32_max(size.height, scrollable_overflow_rect.bottom) } else { size.height },
};
if end_extent.width <= 0.0 || end_extent.height <= 0.0 {
return Rect::ZERO;
}
let start_extent = Point {
x: if propagates.x { f32_min(0.0, scrollable_overflow_rect.left) } else { 0.0 },
y: if propagates.y { f32_min(0.0, scrollable_overflow_rect.top) } else { 0.0 },
};
let contribution = Rect {
left: location.x + start_extent.x,
right: location.x + end_extent.width,
top: location.y + start_extent.y,
bottom: location.y + end_extent.height,
};
let is_wholly_unreachable = contribution.right <= 0.0 || contribution.bottom <= 0.0;
if parent_is_scroll_container && is_wholly_unreachable {
Rect::ZERO
} else {
contribution
}
}
+162
View File
@@ -0,0 +1,162 @@
//! Shared resolution logic for sizing keywords (`min-content`, `max-content`, `fit-content`,
//! `fit-content(...)`, and `stretch`) on the `width`/`height` style properties
use crate::geometry::{AbsoluteAxis, Line, Rect, Size};
use crate::style::AvailableSpace;
use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, NodeId, SizingMode};
use crate::util::sys::f32_max;
use crate::{CompactLength, Dimension};
/// How a sizing keyword resolves to a used size
pub(crate) enum SizingKeywordResolution {
/// The size is the result of measuring the item under the given available space constraint
Measure(AvailableSpace),
/// The size resolves to an exact value without measuring the item
Exact(f32),
}
/// Resolve an item's size style in one axis if it is a sizing keyword (`min-content`,
/// `max-content`, `fit-content`, `fit-content(...)`, or `stretch`).
///
/// - `stretch_size` is the size the item would take if stretched to fill the available space
/// (available space minus margins). Used by `fit-content` and `stretch`.
/// - `percent_resolution_basis` is the size that percentages resolve against in this axis.
/// Used by `fit-content(<percentage>)`.
///
/// Returns `None` if the size style is not a sizing keyword, or if it cannot
/// be resolved in the current context (in which case it behaves as `auto`).
#[inline]
pub(crate) fn resolve_sizing_keyword(
style: Dimension,
stretch_size: Option<f32>,
percent_resolution_basis: Option<f32>,
calc_resolver: impl Fn(*const (), f32) -> f32,
) -> Option<SizingKeywordResolution> {
#[cfg(not(feature = "calc"))]
let _ = &calc_resolver;
match style.tag() {
CompactLength::MIN_CONTENT_TAG => Some(SizingKeywordResolution::Measure(AvailableSpace::MinContent)),
CompactLength::MAX_CONTENT_TAG => Some(SizingKeywordResolution::Measure(AvailableSpace::MaxContent)),
CompactLength::FIT_CONTENT_PX_TAG => {
Some(SizingKeywordResolution::Measure(AvailableSpace::Definite(style.value())))
}
CompactLength::FIT_CONTENT_PERCENT_TAG => percent_resolution_basis
.map(|basis| SizingKeywordResolution::Measure(AvailableSpace::Definite(basis * style.value()))),
CompactLength::FIT_CONTENT_KEYWORD_TAG => {
stretch_size.map(|size| SizingKeywordResolution::Measure(AvailableSpace::Definite(size)))
}
#[cfg(feature = "calc")]
_ if style.is_fit_content_calc() => percent_resolution_basis.map(|basis| {
SizingKeywordResolution::Measure(AvailableSpace::Definite(calc_resolver(style.calc_value(), basis)))
}),
CompactLength::STRETCH_TAG => stretch_size.map(SizingKeywordResolution::Exact),
_ => None,
}
}
/// Resolve the sizing keywords (`min-content`, `max-content`, `fit-content`, `fit-content(...)`,
/// and `stretch`) on the size styles of an absolutely positioned item, filling in the
/// corresponding `known_dimensions` axes.
///
/// - `area_size` is the size of the item's containing block (which insets and percentages
/// resolve against).
/// - The stretch size in each axis is the containing block minus the item's insets and margins
/// in that axis.
#[allow(clippy::too_many_arguments)]
pub(crate) fn resolve_absolute_sizing_keywords(
tree: &mut impl LayoutPartialTree,
node: NodeId,
known_dimensions: &mut Size<Option<f32>>,
size_style: Size<Dimension>,
area_size: Size<f32>,
inset: Rect<Option<f32>>,
margin: Rect<Option<f32>>,
sizing_mode: SizingMode,
) {
let stretch_size = Size {
width: f32_max(
area_size.width
- inset.left.unwrap_or(0.0)
- inset.right.unwrap_or(0.0)
- margin.left.unwrap_or(0.0)
- margin.right.unwrap_or(0.0),
0.0,
),
height: f32_max(
area_size.height
- inset.top.unwrap_or(0.0)
- inset.bottom.unwrap_or(0.0)
- margin.top.unwrap_or(0.0)
- margin.bottom.unwrap_or(0.0),
0.0,
),
};
let keyword_width = if known_dimensions.width.is_none() {
resolve_sizing_keyword(size_style.width, Some(stretch_size.width), Some(area_size.width), |val, basis| {
tree.calc(val, basis)
})
} else {
None
};
let keyword_height = if known_dimensions.height.is_none() {
resolve_sizing_keyword(size_style.height, Some(stretch_size.height), Some(area_size.height), |val, basis| {
tree.calc(val, basis)
})
} else {
None
};
match (keyword_width, keyword_height) {
// If both axes need to be measured then resolve them with a single measure call
(
Some(SizingKeywordResolution::Measure(available_width)),
Some(SizingKeywordResolution::Measure(available_height)),
) => {
let measured_size = tree.measure_child_size_both(
node,
Size::NONE,
area_size.map(Some),
Size { width: available_width, height: available_height },
sizing_mode,
Line::FALSE,
);
*known_dimensions = measured_size.map(Some);
}
(keyword_width, keyword_height) => {
if let Some(resolution) = keyword_width {
known_dimensions.width = Some(match resolution {
SizingKeywordResolution::Exact(width) => width,
SizingKeywordResolution::Measure(available_width) => tree.measure_child_size(
node,
*known_dimensions,
area_size.map(Some),
Size { width: available_width, height: AvailableSpace::Definite(stretch_size.height) },
sizing_mode,
AbsoluteAxis::Horizontal,
Line::FALSE,
),
});
}
if let Some(resolution) = keyword_height {
known_dimensions.height = Some(match resolution {
SizingKeywordResolution::Exact(height) => height,
SizingKeywordResolution::Measure(available_height) => tree.measure_child_size(
node,
*known_dimensions,
area_size.map(Some),
Size {
width: known_dimensions
.width
.map(AvailableSpace::Definite)
.unwrap_or(AvailableSpace::Definite(stretch_size.width)),
height: available_height,
},
sizing_mode,
AbsoluteAxis::Vertical,
Line::FALSE,
),
});
}
}
}
}
File diff suppressed because it is too large. Load diff
+797
View File
@@ -0,0 +1,797 @@
//! Computes the position of floats in a block formatting context
//!
//! Here are the precise rules that govern the behavior of floats:
//!
//! 1. The left outer edge of a left-floating box may not be to the left of the left edge of its containing block. An analogous rule
//! holds for right-floating elements.
//! 2. If the current box is left-floating, and there are any left-floating boxes generated by elements earlier in the source document,
//! then for each such earlier box, either the left outer edge of the current box must be to the right of the right outer edge of the earlier box,
//! or its top must be lower than the bottom of the earlier box. Analogous rules hold for right-floating boxes.
//! 3. The right outer edge of a left-floating box may not be to the right of the left outer edge of any right-floating box that is next to it.
//! Analogous rules hold for right-floating elements.
//! 4. A floating box's outer top may not be higher than the top of its containing block. When the float occurs between two collapsing margins,
//! the float is positioned as if it had an otherwise empty anonymous block parent taking part in the flow. The position of such a parent is defined
//! by the rules in the section on margin collapsing.
//! 5. The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.
//! 6. The outer top of an element's floating box may not be higher than the top of any line-box containing a box generated by
//! an element earlier in the source document.
//! 7. A left-floating box that has another left-floating box to its left may not have its right outer edge to the right of its containing block's
//! right edge. (Loosely: a left float may not stick out at the right edge, unless it is already as far to the left as possible.) An analogous rule
//! holds for right-floating elements.
//! 8. A floating box must be placed as high as possible.
//! 9. A left-floating box must be put as far to the left as possible, a right-floating box as far to the right as possible. A higher position is
//! preferred over one that is further to the left/right.
//!
//! But in CSS 2.2, if, within the block formatting context, there is an in-flow negative vertical margin such that the float's position is above the position it would be at were all such negative margins set to zero, the position of the float is undefined.
//!
//! <https://www.w3.org/TR/CSS22/visuren.html#floats>
use core::ops::Range;
use crate::{debug::debug_log, sys::Vec, AvailableSpace, Clear, Direction, FloatDirection, Point, Size};
/// Tolerance used when checking whether a box fits in a horizontal space, to absorb `f32`
/// rounding errors (e.g. percentage widths and margins that sum to exactly 100% may otherwise
/// exceed the container width and spuriously wrap)
pub(crate) const FIT_TOLERANCE: f32 = 0.001;
/// An empty "slot" that avoids floats that is suitable for non-floated content
/// to be laid out into
#[derive(Debug, Clone, Copy, Default)]
pub struct ContentSlot {
/// The id of the segment that the slot starts in
pub segment_id: Option<usize>,
/// The x position of the start of the slot
pub x: f32,
/// The y position of the start of the slot
pub y: f32,
/// The width of the slot
pub width: f32,
/// The height of the slot
pub height: f32,
}
/// An empty "slot" that avoids floats that is suitable for a box that establishes
/// an independent formatting context (and therefore must not overlap floats) to be
/// laid out into. Unlike [`ContentSlot`], this accounts for the box's own margins,
/// which are resolved against the containing block's edges (not float edges) and
/// may therefore overlap floats.
#[derive(Debug, Clone, Copy, Default)]
pub struct BfcSlot {
/// The id of the segment that the slot starts in
pub segment_id: Option<usize>,
/// The x position of the start of the slot (border box edge)
pub x: f32,
/// The y position of the start of the slot
pub y: f32,
/// The space available for the box's border box: the space between float edges
/// and the margin-inset containing block edges. The box fits in the slot if its
/// border box width does not exceed this.
pub border_width: f32,
/// The width that an auto width resolves to (before applying min/max constraints and
/// the negative-margin lower bound). This differs from `border_width` in that the
/// trailing margin is subtracted (except for any part of it that overlaps a float).
pub stretch_width: f32,
}
/// A floated box
#[derive(Debug, Clone, Default)]
pub struct PlacedFloatedBox {
/// A user defined ID for the box
// id: u64,
/// The width of the box
pub width: f32,
/// The height of the box
pub height: f32,
/// Horizontal distance from the edge of the container that the box is floated towards
/// (distance from the left for left floats, from the right for right floats)
pub x_inset: f32,
/// Vertical distance from top edge of the container
pub y: f32,
}
/// A non-overlapping horizontal segment of the Block Formatting Context container
#[derive(Debug, Clone)]
struct Segment {
/// The vertical start and end points of the segment
y: Range<f32>,
/// Left inset in slot 0. Right inset in slot 1.
insets: [f32; 2],
/// Whether a float actually occupies the left (slot 0) / right (slot 1) inset.
/// The insets of a segment created for a float are seeded with the float's containing
/// block insets on both sides, so a non-zero inset alone does not imply a float.
has_float: [bool; 2],
}
impl Segment {
/// Whether the segment can fit the passed floated box (in the horizontal axis)
///
/// See [`float_fits_horizontally`] for the details of the fit rules.
fn fits_float_width(
&self,
floated_box: Size<f32>,
direction: FloatDirection,
bfc_width: f32,
cb_insets: [f32; 2],
) -> bool {
float_fits_horizontally(floated_box.width, direction, bfc_width, self.insets, cb_insets)
}
}
/// Whether a floated box of the given width fits horizontally given the float insets
/// (`float_insets`) and containing block insets (`cb_insets`) that apply to it.
///
/// A float is normally placed at the further-in of the float edge and the containing block
/// edge on the side it is floated towards (its "lead" side). From that position it must:
///
/// - not overlap any float on the opposite ("trail") side (CSS2 §9.5.1 rule 3), and
/// - not extend past the containing block's trail edge if there is a float on its lead
/// side (CSS2 §9.5.1 rule 7: a float may only stick out of its containing block if it
/// is already as far towards its float direction as possible).
///
/// Note that a float which is not constrained by other floats *may* overflow its
/// containing block's trail edge (rules 1 and 7).
fn float_fits_horizontally(
width: f32,
direction: FloatDirection,
bfc_width: f32,
float_insets: [f32; 2],
cb_insets: [f32; 2],
) -> bool {
let lead = direction as usize;
let trail = 1 - lead;
let x_inset = float_insets[lead].max(cb_insets[lead]);
let fits_opposite_floats =
float_insets[trail] == 0.0 || x_inset + width <= bfc_width - float_insets[trail] + FIT_TOLERANCE;
let fits_containing_block =
float_insets[lead] == 0.0 || x_inset + width <= bfc_width - cb_insets[trail] + FIT_TOLERANCE;
fits_opposite_floats && fits_containing_block
}
/// Helper type for placing a single floated box
///
/// Given a pinned starting y position, this type helps determine if there is any x position
/// such that there is sufficient horizontal space for the box accross it's entire height.
#[derive(Debug, Clone)]
struct FloatFitter {
/// The overall width of the Block Formatting Context
bfc_width: f32,
/// The total height of the set of segments currently being considered
slot_height: f64,
/// The union of the float insets of the set of segments currently being considered
float_insets: [f32; 2],
/// The insets of the box's containing block from the edges of the Block Formatting Context
cb_insets: [f32; 2],
}
impl FloatFitter {
/// Create a new `FloatFitter`
fn new(bfc_width: f32, slot_height: f32, cb_insets: [f32; 2]) -> Self {
Self { bfc_width, slot_height: slot_height as f64, float_insets: [0.0, 0.0], cb_insets }
}
// Horizontal fitting
/// Union the insets of another segment. This is a "max" of the insets on each side.
fn union_insets(&mut self, insets: [f32; 2]) {
self.float_insets[0] = self.float_insets[0].max(insets[0]);
self.float_insets[1] = self.float_insets[1].max(insets[1]);
}
/// The inset from the edge of the BFC (on the side the box is floated towards) that the
/// box would be placed at given the currently accounted for insets
fn placed_inset(&self, direction: FloatDirection) -> f32 {
let lead = direction as usize;
self.float_insets[lead].max(self.cb_insets[lead])
}
/// Given the currently accounted for insets, check whether there is an x position
/// such that the box fits horizontally.
///
/// See [`float_fits_horizontally`] for the details of the fit rules.
fn fits_horiontally(&self, width: f32, direction: FloatDirection) -> bool {
float_fits_horizontally(width, direction, self.bfc_width, self.float_insets, self.cb_insets)
}
// Vertical fitting
/// Add the height of another segment.
fn add_height(&mut self, height: f32) {
self.slot_height += height as f64;
}
/// Given the currently accounted for height, check whether the box fits vertically
fn fits_vertically(&mut self, height: f32) -> bool {
self.slot_height >= height as f64
}
}
/// A context for placing floated boxes
#[derive(Debug, Clone)]
pub struct FloatContext {
/// The available space constraint that applies to the root Block Formatting Context
/// for which this `FloatContext` manages floats.
available_width: f32,
/// Whether the float context contains any floats
has_floats: bool,
/// A list of left-floated boxes within the context
left_floats: Vec<PlacedFloatedBox>,
/// A list of right-floated boxes within the context
right_floats: Vec<PlacedFloatedBox>,
/// A list of non-overlapping horizontal "segments" within the context.
/// Each segment has the same available width for it's entire height.
segments: Vec<Segment>,
/// A closed-open range indicating which segment the last placed float
/// was placed(on each side).
last_placed_floats: [Range<usize>; 2],
/// The bottom (y + height) of the lowest float placed on each side, including
/// zero-sized floats (which occupy no segment). Left in slot 0, right in slot 1.
clear_bottoms: [Option<f32>; 2],
/// The topmost y position allowed for a new float (CSS2 float rule 5), including
/// the tops of zero-sized floats (which occupy no segment)
float_ceiling: Option<f32>,
// Left hwm in slot 0. Right hwm in slot 1.
// high_water_marks: [usize; 2],
// left_float_high_water_mark: usize,
// right_float_high_water_mark: usize,
}
impl Default for FloatContext {
fn default() -> Self {
Self {
available_width: 0.0,
has_floats: false,
left_floats: Vec::new(),
right_floats: Vec::new(),
segments: Vec::new(),
last_placed_floats: [0..0, 0..0], // high_water_marks: [0, 0],
clear_bottoms: [None, None],
float_ceiling: None,
}
}
}
impl FloatContext {
/// Create a new empty `FloatContext`
pub fn new() -> Self {
Default::default()
}
/// Whether the float context contains any floats
#[inline(always)]
pub fn has_floats(&self) -> bool {
self.has_floats
}
/// Whether the float context contains any floats that extend to or below min_y
#[inline(always)]
pub fn has_active_floats(&self, min_y: f32) -> bool {
self.has_floats && self.segments.last().map(|seg| seg.y.end).unwrap_or(0.0) > min_y
}
/// Set the width of the `FloatContext`
pub fn set_width(&mut self, available_width: f32) {
self.available_width = available_width;
}
/// Returns a slice of placed left floats
pub fn left_floats(&self) -> &[PlacedFloatedBox] {
&self.left_floats
}
/// Returns a slice of placed right floats
pub fn right_floats(&self) -> &[PlacedFloatedBox] {
&self.right_floats
}
/// Divide a segment into two segments so that a new float can be placed and have it's
/// vertical start and end at exact segment boundaries
fn subdivide_segment(&mut self, idx: usize, divide_at_y: f32) {
let old_segment = &mut self.segments[idx];
let new_segment =
Segment { insets: old_segment.insets, has_float: old_segment.has_float, y: divide_at_y..old_segment.y.end };
if !old_segment.y.contains(&divide_at_y) || old_segment.y.start == divide_at_y {
debug_log!("old_segment", dbg:&mut *old_segment);
debug_log!("divide_at_y", dbg:divide_at_y);
assert!(old_segment.y.contains(&divide_at_y) && old_segment.y.start != divide_at_y);
}
old_segment.y.end = divide_at_y;
self.segments.splice((idx + 1)..(idx + 1), core::iter::once(new_segment));
}
/// Update the last placed float start and end values
fn update_last_placed_float(&mut self, direction: FloatDirection, placement: Range<usize>) {
let slot = direction as usize;
self.last_placed_floats[slot].start = self.last_placed_floats[slot].start.max(placement.start);
self.last_placed_floats[slot].end = self.last_placed_floats[slot].end.max(placement.end);
}
/// Position a floated box with the context, returning the (x, y) coordinates
pub fn place_floated_box(
&mut self,
floated_box: Size<f32>,
min_y: f32,
containing_block_insets: [f32; 2],
direction: FloatDirection,
clear: Clear,
) -> Point<f32> {
self.has_floats = true;
let placed_floated_box =
self.place_floated_box_inner(floated_box, min_y, containing_block_insets, direction, clear);
let slot = direction as usize;
let bottom = placed_floated_box.y + placed_floated_box.height;
self.clear_bottoms[slot] = Some(self.clear_bottoms[slot].map_or(bottom, |b| b.max(bottom)));
let y = placed_floated_box.y;
self.float_ceiling = Some(self.float_ceiling.map_or(y, |ceiling| ceiling.max(y)));
let x_inset = placed_floated_box.x_inset;
let y = placed_floated_box.y;
match direction {
FloatDirection::Left => {
self.left_floats.push(placed_floated_box);
Point { x: x_inset, y }
}
FloatDirection::Right => {
self.right_floats.push(placed_floated_box);
Point { x: self.available_width - x_inset - floated_box.width, y }
}
}
}
/// Inner implementation of float placement, split into a separate function so that it can early-return
fn place_floated_box_inner(
&mut self,
floated_box: Size<f32>,
min_y: f32,
containing_block_insets: [f32; 2],
direction: FloatDirection,
clear: Clear,
) -> PlacedFloatedBox {
let slot = direction as usize;
// Floats (including zero-sized floats) that occupy no segment still constrain the
// position of later boxes: rule 5 (a float may not be higher than the top of any
// earlier float) and `clear` (which clears past the bottom of floats on the
// relevant side, regardless of their width)
let min_y = min_y
.max(self.float_ceiling.unwrap_or(f32::NEG_INFINITY))
.max(self.cleared_threshold(clear).unwrap_or(f32::NEG_INFINITY));
// Ensure that float:
// - Starts at or after the last placed float in either direction (CSS2 float rule 5:
// "The outer top of a floating box may not be higher than the outer top of any block
// or floated box generated by an element earlier in the source document")
// - Respects "clear"
let float_start = self.last_placed_floats[0].start.max(self.last_placed_floats[1].start);
let hwm = match clear {
Clear::Left => {
let left_end = self.last_placed_floats[0].end;
float_start.max(left_end + 1)
}
Clear::Right => {
let right_end = self.last_placed_floats[1].end;
float_start.max(right_end + 1)
}
Clear::Both => {
let left_end = self.last_placed_floats[0].end;
let right_end = self.last_placed_floats[1].end;
left_end.max(right_end) + 1
}
Clear::None => float_start,
};
// Ensure that float is placed in a segment at or below "min_y"
// (ensuring that it is placed at or below min_y within it's segment happens below)
let start_idx = self
.segments
.get(hwm..)
.and_then(|segments| segments.iter().position(|segment| segment.y.end > min_y).map(|idx| idx + hwm));
let mut start_idx = start_idx.unwrap_or(self.segments.len());
let mut start_y = min_y;
let mut end_idx = start_idx;
// let mut end_y = min_y;
// Loop over remaining segments, trying to place the float in a position
// that has space to accomodate it.
let (start, mut end, placed_inset) = 'outer: loop {
// Start segment does not exist:
//
// This means no existing segment can accomodate the float so we must create a new
// segment below all existing segments. A new segment will always have space for
// the float, so we can exit the loop at this point.
let Some(start_segment) = self.segments.get(start_idx) else {
break (None, None, containing_block_insets[slot]);
};
// Candidate start segment doesn't have (horizontal) space for the float:
// => retry with the next segment
if !start_segment.fits_float_width(floated_box, direction, self.available_width, containing_block_insets) {
start_idx += 1;
end_idx = end_idx.max(start_idx);
continue;
}
start_y = start_y.max(start_segment.y.start);
let available_height = start_segment.y.end - start_y;
let mut fitter = FloatFitter::new(self.available_width, available_height, containing_block_insets);
fitter.union_insets(start_segment.insets);
// Pinning the start segment, loop over segments starting with the start segment
// to find the end segment:
// - The selected segment range must have enough height to contain the float
// - All of the segments in the range must have enough horizontal width to contain the float
// TODO: must ensure that width is in the correct place.
loop {
// End segment does not exist:
//
// This means no existing segment can accomodate the float so we must create a new
// segment below all existing segments
let Some(end_segment) = self.segments.get(end_idx) else {
let inset = fitter.placed_inset(direction);
break 'outer (Some(start_idx), None, inset);
};
// Check horizontal fit
//
// If it does not fit horizontally then it will never fit in this position, so
// continue the outer loop to find and check a new position
fitter.union_insets(end_segment.insets);
if !fitter.fits_horiontally(floated_box.width, direction) {
start_idx += 1;
end_idx = end_idx.max(start_idx);
continue 'outer;
}
// Check vertical fit
//
// If it does not (yet) fit vertically then continue the inner loop to add another
// segment to the range of segments we are placing the float in
if end_idx != start_idx {
fitter.add_height(end_segment.y.end - end_segment.y.start);
}
if !fitter.fits_vertically(floated_box.height) {
end_idx += 1;
continue;
}
let inset = fitter.placed_inset(direction);
break 'outer (Some(start_idx), Some(end_idx), inset);
}
};
// Short-circuit for zero-height boxes. Zero-width boxes are still recorded in segments:
// their edge acts as an obstacle that boxes establishing an independent formatting
// context may not be placed to the outside of (e.g. via a negative margin).
if floated_box.height == 0.0 {
// TODO: need to update last_placed_float?
return PlacedFloatedBox {
width: floated_box.width,
height: floated_box.height,
y: start_y,
x_inset: placed_inset,
};
}
// Handle case where floated box is placed after all existing segments
if start.is_none() {
let last_y_end = self.segments.last().map(|seg| seg.y.end).unwrap_or(0.0);
if start_y > last_y_end {
self.segments.push(Segment { y: last_y_end..start_y, insets: [0.0, 0.0], has_float: [false; 2] });
}
let start_y = last_y_end.max(start_y);
let mut insets = containing_block_insets;
insets[slot] += floated_box.width;
let mut has_float = [false; 2];
has_float[slot] = true;
self.segments.push(Segment { y: start_y..(start_y + floated_box.height), insets, has_float });
// Update last_placed_float
let start_idx = self.segments.len() - 1;
let end_idx = start_idx + 1;
self.update_last_placed_float(direction, start_idx..end_idx);
return PlacedFloatedBox {
width: floated_box.width,
height: floated_box.height,
y: start_y,
x_inset: containing_block_insets[slot],
};
}
// Else unwrap the index of the segment that the start of the floating box is placed in
let mut start_idx = start.unwrap();
// If the floated box doesn't start at the exact same y-offset as the segment it starts in, then
// subdivide that segment into two segments at the y-offset that the floated box starts at, and increment
// `start_idx` so that the floating box is placed in the second of the two segments.
if start_y != self.segments[start_idx].y.start {
self.subdivide_segment(start_idx, start_y);
start_idx += 1;
if let Some(end_idx) = end.as_mut() {
*end_idx += 1;
}
}
let end_idx = match end {
None => {
let last_y_end = self.segments.last().map(|seg| seg.y.end).unwrap_or(0.0);
if min_y > last_y_end {
self.segments.push(Segment { y: last_y_end..min_y, insets: [0.0, 0.0], has_float: [false; 2] });
}
self.segments.len() - 1
}
Some(mut end_idx) => {
let end_y = start_y + floated_box.height;
// Due to floating point imprecision, `end_y` may coincide with (or fall before)
// the start of the end segment even though the sum of the candidate segment
// heights was computed as sufficient. In that case the float effectively ends at
// the boundary of the previous segment, so walk back to the segment that actually
// contains `end_y`.
while end_idx > start_idx && end_y <= self.segments[end_idx].y.start {
end_idx -= 1;
}
// Only subdivide if `end_y` falls strictly within the segment. If it lands on
// (or, due to floating point imprecision, beyond) a segment boundary then no
// subdivision is needed.
if self.segments[end_idx].y.start < end_y && end_y < self.segments[end_idx].y.end {
self.subdivide_segment(end_idx, end_y);
}
end_idx
}
};
// Update inset for the range of segments that the float is placed in
let placed_inset_plus_width = placed_inset + floated_box.width;
for segment in &mut self.segments[start_idx..=end_idx] {
segment.insets[slot] = placed_inset_plus_width;
segment.has_float[slot] = true;
}
// Update last_placed_float
self.update_last_placed_float(direction, start_idx..(end_idx + 1));
PlacedFloatedBox { width: floated_box.width, height: floated_box.height, y: start_y, x_inset: placed_inset }
}
/// Get the end segment of the last float on side(s) specified by the clear parameter (if any)
///
/// Returns `None` if no float has been placed on the relevant side(s)
fn cleared_segment(&self, clear: Clear) -> Option<usize> {
let left_end = self.last_placed_floats[0].end;
let right_end = self.last_placed_floats[1].end;
match clear {
Clear::Left if left_end > 0 => Some(left_end),
Clear::Right if right_end > 0 => Some(right_end),
Clear::Both if left_end > 0 || right_end > 0 => Some(left_end.max(right_end)),
_ => None,
}
}
/// Get the bottom of lowest relevant float for the specific clear property
pub fn cleared_threshold(&self, clear: Clear) -> Option<f32> {
match clear {
Clear::Left => self.clear_bottoms[0],
Clear::Right => self.clear_bottoms[1],
Clear::Both => match self.clear_bottoms {
[Some(l), Some(r)] => Some(l.max(r)),
[l, r] => l.or(r),
},
Clear::None => None,
}
}
/// Search for a space suitable for laying out non-floated content into
pub fn find_content_slot(
&self,
min_y: f32,
containing_block_insets: [f32; 2],
clear: Clear,
after: Option<usize>,
) -> ContentSlot {
if !self.has_active_floats(min_y) {
return ContentSlot {
segment_id: None,
x: containing_block_insets[0],
y: min_y,
width: self.available_width - containing_block_insets[0] - containing_block_insets[1],
height: f32::INFINITY,
};
}
// Clearance clears past the bottom of floats on the relevant side, including
// zero-sized floats which occupy no segment
let min_y = min_y.max(self.cleared_threshold(clear).unwrap_or(f32::NEG_INFINITY));
// The min starting segment index
let at_least = after.map(|idx| idx + 1).unwrap_or(0);
let hwm = at_least.max(self.cleared_segment(clear).map(|idx| idx + 1).unwrap_or(0));
let start_idx = self
.segments
.get(hwm..)
.and_then(|segments| segments.iter().position(|segment| segment.y.end > min_y).map(|idx| idx + hwm));
let start_idx = start_idx.unwrap_or(self.segments.len());
let segment = self.segments.get(start_idx);
match segment {
Some(segment) => {
let inset_left = segment.insets[0].max(containing_block_insets[0]);
let inset_right = segment.insets[1].max(containing_block_insets[1]);
ContentSlot {
segment_id: Some(start_idx),
x: inset_left,
y: segment.y.start.max(min_y),
width: self.available_width - inset_left - inset_right,
height: f32::INFINITY,
}
}
None => ContentSlot {
segment_id: None,
x: containing_block_insets[0],
y: min_y,
width: self.available_width - containing_block_insets[0] - containing_block_insets[1],
height: f32::INFINITY,
},
}
}
/// Search for a space suitable for laying out a box that establishes an independent
/// formatting context (whose border box must not overlap floats).
///
/// The box's margins are resolved against the containing block's content edges. When there
/// are floats beside the box:
///
/// - The leading margin (in flow direction) positions the border box's leading edge, but
/// may be partially or fully "absorbed" by a float on the leading side (the border edge
/// is the further-in of the float edge and the margin-inset containing block edge), and
/// a negative leading margin does not move the border edge past the float edge. When no
/// float intrudes on the leading side the margin applies as usual, and a negative margin
/// may move the border edge outside the containing block.
/// - The trailing margin is subtracted from the width an auto width resolves to (except
/// for any part of it that overlaps a float on the trailing side). When a float intrudes
/// on the trailing side, the trailing margin does not affect whether a box of a given
/// width fits in the slot: the trailing margin may overflow the containing block edge.
/// When no float intrudes on the trailing side the margin applies as usual, and a
/// negative margin lets the border box extend outside the containing block.
///
/// When there are no floats beside the box, its (possibly negative) margins apply as usual.
pub fn find_bfc_slot(
&self,
min_y: f32,
containing_block_insets: [f32; 2],
margins: [f32; 2],
direction: Direction,
clear: Clear,
after: Option<usize>,
) -> BfcSlot {
let margin_insets = [containing_block_insets[0] + margins[0], containing_block_insets[1] + margins[1]];
let no_float_width = self.available_width - margin_insets[0] - margin_insets[1];
let no_float_slot = BfcSlot {
segment_id: None,
x: margin_insets[0],
y: min_y,
border_width: no_float_width,
stretch_width: no_float_width,
};
if !self.has_active_floats(min_y) {
return no_float_slot;
}
// Clearance clears past the bottom of floats on the relevant side, including
// zero-sized floats which occupy no segment
let min_y = min_y.max(self.cleared_threshold(clear).unwrap_or(f32::NEG_INFINITY));
// The min starting segment index
let at_least = after.map(|idx| idx + 1).unwrap_or(0);
let hwm = at_least.max(self.cleared_segment(clear).map(|idx| idx + 1).unwrap_or(0));
let start_idx = self
.segments
.get(hwm..)
.and_then(|segments| segments.iter().position(|segment| segment.y.end > min_y).map(|idx| idx + hwm));
let start_idx = start_idx.unwrap_or(self.segments.len());
match self.segments.get(start_idx) {
Some(segment) => {
let lead = match direction {
Direction::Ltr => 0,
Direction::Rtl => 1,
};
let trail = 1 - lead;
let has_lead_float = segment.has_float[lead];
let has_trail_float = segment.has_float[trail];
let mut fit_insets = [0.0; 2];
let mut stretch_insets = [0.0; 2];
fit_insets[lead] =
if has_lead_float { segment.insets[lead].max(margin_insets[lead]) } else { margin_insets[lead] };
stretch_insets[lead] = fit_insets[lead];
fit_insets[trail] = if has_trail_float {
segment.insets[trail].max(containing_block_insets[trail])
} else {
// A positive trailing margin may overflow the containing block edge (it does
// not affect fit), but a negative one widens the space for the border box
margin_insets[trail].min(containing_block_insets[trail])
};
stretch_insets[trail] = if has_trail_float {
segment.insets[trail].max(margin_insets[trail])
} else {
margin_insets[trail]
};
BfcSlot {
segment_id: Some(start_idx),
x: fit_insets[0],
y: segment.y.start.max(min_y),
border_width: self.available_width - fit_insets[0] - fit_insets[1],
stretch_width: self.available_width - stretch_insets[0] - stretch_insets[1],
}
}
// Below all floats
None => BfcSlot {
y: self.segments.last().map(|segment| segment.y.end).unwrap_or(min_y).max(min_y),
..no_float_slot
},
}
}
}
/// Context for computing the intrinsic width contribution of a set of floats
pub struct FloatIntrinsicWidthCalculator {
/// The available width of the container
available_width: AvailableSpace,
/// The running sums of the widths of adjacent uncleared floats on each side (left, right)
side_sums: [f32; 2],
/// The running total intrinsic width contribution
contribution: f32,
/// The widest single float (the floats' min-content contribution)
widest: f32,
}
impl FloatIntrinsicWidthCalculator {
/// Create a new `FloatIntrinsicWidthCalculator`
pub fn new(available_width: AvailableSpace) -> Self {
Self { available_width, side_sums: [0.0; 2], contribution: 0.0, widest: 0.0 }
}
/// Add a float to the computation
pub fn add_float(&mut self, width: f32, direction: FloatDirection, clear: Clear) {
match self.available_width {
// Definite available width means the container is being fit-content sized
// (e.g. it is itself a float being shrink-to-fit sized). The floats' max-content
// contribution (widths summed) is clamped by the available width in `result`.
AvailableSpace::Definite(_) | AvailableSpace::MaxContent => {
// A float that clears a side is placed below the floats on that side, so its
// width does not accumulate with theirs.
if matches!(clear, Clear::Left | Clear::Both) {
self.side_sums[0] = 0.0;
}
if matches!(clear, Clear::Right | Clear::Both) {
self.side_sums[1] = 0.0;
}
self.side_sums[direction as usize] += width;
self.contribution = self.contribution.max(self.side_sums[0] + self.side_sums[1]);
}
AvailableSpace::MinContent => self.contribution = self.contribution.max(width),
};
self.widest = self.widest.max(width);
}
/// Get the computed float contribution to intrinsic width
pub fn result(&self) -> f32 {
match self.available_width {
// Fit-content sizing: clamp the max-content contribution between the available
// width and the min-content contribution (floats narrow by wrapping onto new
// bands, but never below the widest single float).
AvailableSpace::Definite(available_width) => self.contribution.min(available_width).max(self.widest),
_ => self.contribution,
}
}
}
+536
View File
@@ -0,0 +1,536 @@
//! Alignment of tracks and final positioning of items
use super::types::GridTrack;
use crate::compute::common::alignment::{
apply_alignment_fallback, compute_alignment_offset, resolve_self_alignment_safety,
};
use crate::geometry::{InBothAbsAxis, Line, Point, Rect, Size};
use crate::style::{
AlignContent, AlignItems, AlignItemsKeyword, AlignSelf, AvailableSpace, CoreStyle, GridItemStyle, Overflow,
Position,
};
use crate::tree::{Layout, LayoutPartialTreeExt, NodeId, OofCandidates, SizingMode};
use crate::util::sys::f32_max;
use crate::util::{MaybeMath, MaybeResolve, ResolveOrZero};
#[cfg(feature = "content_size")]
use crate::compute::common::scrollable_overflow::compute_scrollable_overflow_contribution;
use crate::compute::common::sizing_keyword::{resolve_sizing_keyword, SizingKeywordResolution};
use crate::{AbsoluteAxis, BoxSizing, Direction, LayoutGridContainer};
/// Align the grid tracks within the grid according to the align-content (rows) or
/// justify-content (columns) property. This only does anything if the size of the
/// grid is not equal to the size of the grid container in the axis being aligned.
pub(super) fn align_tracks(
grid_container_content_box_size: f32,
padding: Line<f32>,
border: Line<f32>,
tracks: &mut [GridTrack],
track_alignment_style: AlignContent,
axis_is_reversed: bool,
) {
let used_size: f32 = tracks.iter().map(|track| track.base_size).sum();
let free_space = grid_container_content_box_size - used_size;
let origin = padding.start + border.start;
// Count the number of non-collapsed tracks (not counting gutters)
let num_tracks = tracks.iter().skip(1).step_by(2).filter(|track| !track.is_collapsed).count();
// Grid layout treats gaps as full tracks rather than applying them at alignment so we
// simply pass zero here. Grid layout is never reversed.
let gap = 0.0;
let layout_is_reversed = false;
let track_alignment = apply_alignment_fallback(free_space, num_tracks, track_alignment_style);
let track_alignment = if axis_is_reversed { track_alignment.reversed() } else { track_alignment };
// If every track is collapsed then no track receives the alignment offset below, but the
// grid's lines should still be aligned within the container (e.g. at the inline-start edge
// for RTL), so apply the offset to the origin instead.
let empty_grid_offset = if num_tracks == 0 {
compute_alignment_offset(free_space, num_tracks, gap, track_alignment, layout_is_reversed, true)
} else {
0.0
};
// Compute offsets. Tracks are stored in logical order; when the axis is reversed (RTL)
// physical offsets are assigned right-to-left by iterating the tracks in reverse.
let mut total_offset = origin + empty_grid_offset;
let mut seen_non_collapsed_track = false;
let mut position_track = |i: usize, track: &mut GridTrack| {
// Odd tracks are gutters (but slices are zero-indexed, so odd tracks have even indices)
let is_gutter = i % 2 == 0;
let is_non_collapsed_track = !is_gutter && !track.is_collapsed;
// Alignment offsets should be applied only to non-collapsed tracks.
let is_first = is_non_collapsed_track && !seen_non_collapsed_track;
let offset = if is_non_collapsed_track {
compute_alignment_offset(free_space, num_tracks, gap, track_alignment, layout_is_reversed, is_first)
} else {
0.0
};
track.offset = total_offset + offset;
total_offset = total_offset + offset + track.base_size;
if is_non_collapsed_track {
seen_non_collapsed_track = true;
}
};
if axis_is_reversed {
tracks.iter_mut().rev().enumerate().for_each(|(i, track)| position_track(i, track));
} else {
tracks.iter_mut().enumerate().for_each(|(i, track)| position_track(i, track));
}
}
/// Align and size a grid item into it's final position
#[allow(clippy::too_many_arguments)]
pub(super) fn align_and_position_item(
tree: &mut impl LayoutGridContainer,
node: NodeId,
order: u32,
grid_area: Rect<f32>,
// Percentage basis for the item's styles. Grid passes the grid area size; grid lanes (css-grid-3) items
// have the container's content box as their containing block in the stacking axis.
containing_block_size: Size<f32>,
container_alignment_styles: InBothAbsAxis<AlignItems>,
baseline_shim: f32,
direction: Direction,
container_border_box_width: f32,
container_border: Rect<f32>,
#[cfg(feature = "content_size")] container_is_scroll_container: bool,
bubbled_candidates: &mut OofCandidates,
) -> (Rect<f32>, f32, f32) {
let grid_area_size = Size { width: grid_area.right - grid_area.left, height: grid_area.bottom - grid_area.top };
let style = tree.get_grid_child_style(node);
let overflow = style.overflow();
#[cfg(feature = "content_size")]
let contain = style.contain();
let scrollbar_width = style.scrollbar_width();
let aspect_ratio = style.aspect_ratio();
let is_replaced = style.is_replaced();
// Fall back to the container's justify-items/align-items if unset (`None`), and then resolve
// writing-mode-relative self-start/self-end keywords against the item's own direction.
// The horizontal axis is the inline axis (Taffy only supports horizontal-tb); the vertical
// (block) axis resolves them to plain start/end.
let item_direction = style.direction();
let justify_self = style.justify_self().unwrap_or(container_alignment_styles.horizontal).resolve_self_relative(
item_direction,
direction,
true,
);
let align_self = style.align_self().unwrap_or(container_alignment_styles.vertical).resolve_self_relative(
item_direction,
direction,
false,
);
let position = style.position();
let inset_horizontal = style
.inset()
.horizontal_components()
.map(|size| size.resolve_to_option(containing_block_size.width, |val, basis| tree.calc(val, basis)));
let inset_vertical = style
.inset()
.vertical_components()
.map(|size| size.resolve_to_option(containing_block_size.height, |val, basis| tree.calc(val, basis)));
let padding = style
.padding()
.map(|p| p.resolve_or_zero(Some(containing_block_size.width), |val, basis| tree.calc(val, basis)));
let border = style
.border()
.map(|p| p.resolve_or_zero(Some(containing_block_size.width), |val, basis| tree.calc(val, basis)));
let padding_border_size = (padding + border).sum_axes();
let box_sizing_adjustment =
if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
let size_style = style.size();
let inherent_size = size_style
.maybe_resolve(containing_block_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let min_size = style
.min_size()
.maybe_resolve(containing_block_size, |val, basis| tree.calc(val, basis))
.maybe_add(box_sizing_adjustment)
.or(padding_border_size.map(Some))
.maybe_max(padding_border_size)
.maybe_apply_aspect_ratio(aspect_ratio);
let max_size = style
.max_size()
.maybe_resolve(containing_block_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
// Resolve `normal` alignment (the default if alignment is set on neither the parent or the node itself)
// Note: if the child has a preferred aspect ratio but neither width or height are set, then the width is stretched
// and the then height is calculated from the width according the aspect ratio
// Replaced elements are not stretched: they are sized as for `start`.
// See: https://www.w3.org/TR/css-grid-1/#grid-item-sizing
let alignment_styles = InBothAbsAxis {
horizontal: match justify_self.keyword {
AlignItemsKeyword::Normal => {
if inherent_size.width.is_some() || size_style.width.is_sizing_keyword() || is_replaced {
AlignSelf::START
} else {
AlignSelf::STRETCH
}
}
_ => justify_self,
},
vertical: match align_self.keyword {
AlignItemsKeyword::Normal => {
if inherent_size.height.is_some()
|| size_style.height.is_sizing_keyword()
|| aspect_ratio.is_some()
|| is_replaced
{
AlignSelf::START
} else {
AlignSelf::STRETCH
}
}
_ => align_self,
},
};
// Note: This is not a bug. It is part of the CSS spec that both horizontal and vertical margins
// resolve against the WIDTH of the grid area.
let margin = style
.margin()
.map(|margin| margin.resolve_to_option(containing_block_size.width, |val, basis| tree.calc(val, basis)));
drop(style);
let grid_area_minus_item_margins_size = Size {
width: grid_area_size.width.maybe_sub(margin.left).maybe_sub(margin.right).max(0.0),
height: (grid_area_size.height.maybe_sub(margin.top).maybe_sub(margin.bottom) - baseline_shim).max(0.0),
};
// A size that is a sizing keyword (min-content, max-content, fit-content,
// fit-content(...), stretch) either resolves to an exact size or is resolved
// by measuring the item under the corresponding available space constraint
let keyword_width = inherent_size.width.is_none().then(|| {
resolve_sizing_keyword(
size_style.width,
Some(grid_area_minus_item_margins_size.width),
Some(containing_block_size.width),
|val, basis| tree.calc(val, basis),
)
});
let keyword_height = inherent_size.height.is_none().then(|| {
resolve_sizing_keyword(
size_style.height,
Some(grid_area_minus_item_margins_size.height),
Some(containing_block_size.height),
|val, basis| tree.calc(val, basis),
)
});
// If both axes need to be measured then resolve them with a single measure call
let keyword_measured_size: Size<Option<f32>> = match (&keyword_width, &keyword_height) {
(
Some(Some(SizingKeywordResolution::Measure(available_width))),
Some(Some(SizingKeywordResolution::Measure(available_height))),
) if !position.is_out_of_flow() => tree
.measure_child_size_both(
node,
Size::NONE,
containing_block_size.map(Option::Some),
Size { width: *available_width, height: *available_height },
SizingMode::InherentSize,
Line::FALSE,
)
.map(Option::Some),
_ => Size::NONE,
};
// If node is absolutely positioned and width is not set explicitly, then deduce it
// from left, right and container_content_box if both are set.
let width = inherent_size.width.or_else(|| {
// Apply width derived from both the left and right properties of an absolutely
// positioned element being set
if position.is_out_of_flow() {
if let (Some(left), Some(right)) = (inset_horizontal.start, inset_horizontal.end) {
return Some(f32_max(grid_area_minus_item_margins_size.width - left - right, 0.0));
}
}
if let Some(Some(resolution)) = keyword_width {
return Some(match resolution {
SizingKeywordResolution::Exact(width) => width,
SizingKeywordResolution::Measure(available_width) => keyword_measured_size.width.unwrap_or_else(|| {
tree.measure_child_size(
node,
Size::NONE,
containing_block_size.map(Option::Some),
Size {
width: available_width,
height: AvailableSpace::Definite(grid_area_minus_item_margins_size.height),
},
SizingMode::InherentSize,
AbsoluteAxis::Horizontal,
Line::FALSE,
)
}),
});
}
// Apply width based on stretch alignment if:
// - Alignment style is "stretch"
// - The node is not absolutely positioned
// - The node does not have auto margins in this axis.
if margin.left.is_some()
&& margin.right.is_some()
&& alignment_styles.horizontal == AlignSelf::STRETCH
&& !position.is_out_of_flow()
{
return Some(grid_area_minus_item_margins_size.width);
}
None
});
// Reapply aspect ratio after stretch and absolute position width adjustments
let Size { width, height } = Size { width, height: inherent_size.height }.maybe_apply_aspect_ratio(aspect_ratio);
let height = height.or_else(|| {
if position.is_out_of_flow() {
if let (Some(top), Some(bottom)) = (inset_vertical.start, inset_vertical.end) {
return Some(f32_max(grid_area_minus_item_margins_size.height - top - bottom, 0.0));
}
}
if let Some(Some(resolution)) = keyword_height {
return Some(match resolution {
SizingKeywordResolution::Exact(height) => height,
SizingKeywordResolution::Measure(available_height) => {
keyword_measured_size.height.unwrap_or_else(|| {
tree.measure_child_size(
node,
Size { width, height: None },
containing_block_size.map(Option::Some),
Size {
width: width
.map(AvailableSpace::Definite)
.unwrap_or(AvailableSpace::Definite(grid_area_minus_item_margins_size.width)),
height: available_height,
},
SizingMode::InherentSize,
AbsoluteAxis::Vertical,
Line::FALSE,
)
})
}
});
}
// Apply height based on stretch alignment if:
// - Alignment style is "stretch"
// - The node is not absolutely positioned
// - The node does not have auto margins in this axis.
if margin.top.is_some()
&& margin.bottom.is_some()
&& alignment_styles.vertical == AlignSelf::STRETCH
&& !position.is_out_of_flow()
{
return Some(grid_area_minus_item_margins_size.height);
}
None
});
// Reapply aspect ratio after stretch and absolute position height adjustments
let Size { width, height } = Size { width, height }.maybe_apply_aspect_ratio(aspect_ratio);
// Clamp size by min and max width/height
let Size { width, height } = Size { width, height }.maybe_clamp(min_size, max_size);
// Layout node
let size = if position.is_out_of_flow() && (width.is_none() || height.is_none()) {
tree.measure_child_size_both(
node,
Size { width, height },
containing_block_size.map(Option::Some),
grid_area_minus_item_margins_size.map(AvailableSpace::Definite),
SizingMode::InherentSize,
Line::FALSE,
)
.map(Some)
} else {
Size { width, height }
};
let mut layout_output = tree.perform_child_layout(
node,
size,
containing_block_size.map(Option::Some),
grid_area_minus_item_margins_size.map(AvailableSpace::Definite),
SizingMode::InherentSize,
Line::FALSE,
);
// Resolve final size
let Size { width, height } = size.unwrap_or(layout_output.size).maybe_clamp(min_size, max_size);
let (x, x_margin) = align_item_within_area(
Line { start: grid_area.left, end: grid_area.right },
alignment_styles.horizontal,
width,
position,
inset_horizontal,
margin.horizontal_components(),
0.0,
direction,
);
let (y, y_margin) = align_item_within_area(
Line { start: grid_area.top, end: grid_area.bottom },
alignment_styles.vertical,
height,
position,
inset_vertical,
margin.vertical_components(),
baseline_shim,
Direction::Ltr,
);
let scrollbar_size = Size {
width: if overflow.y == Overflow::Scroll { scrollbar_width } else { 0.0 },
height: if overflow.x == Overflow::Scroll { scrollbar_width } else { 0.0 },
};
let resolved_margin = Rect { left: x_margin.start, right: x_margin.end, top: y_margin.start, bottom: y_margin.end };
// Bubble out-of-flow candidates from the item's subtree, translating anchors from
// item-relative to container-relative coordinates
let mut item_candidates = layout_output.oof_candidates.take();
if !item_candidates.is_empty() {
item_candidates.translate(Point { x, y });
bubbled_candidates.append(&mut item_candidates);
}
tree.set_unrounded_layout(
node,
&Layout {
order,
location: Point { x, y },
size: Size { width, height },
#[cfg(feature = "content_size")]
scrollable_overflow_rect: layout_output.scrollable_overflow_rect,
scrollbar_size,
padding,
border,
margin: resolved_margin,
},
);
#[cfg(feature = "content_size")]
let contribution = {
// Contributions to the container's scrollable overflow rect are measured from the
// container's padding-box origin (mirrored for RTL), matching the scrollable overflow region.
let contribution_location = if direction.is_rtl() {
Point { x: container_border_box_width - (x + width) - container_border.right, y: y - container_border.top }
} else {
Point { x: x - container_border.left, y: y - container_border.top }
};
compute_scrollable_overflow_contribution(
contribution_location,
Size { width, height },
layout_output.scrollable_overflow_rect,
overflow,
contain,
container_is_scroll_container,
)
};
#[cfg(not(feature = "content_size"))]
let contribution = Rect::ZERO;
(contribution, y, height)
}
/// Align and size a grid item along a single axis
#[allow(clippy::too_many_arguments)]
pub(super) fn align_item_within_area(
grid_area: Line<f32>,
alignment_style: AlignSelf,
resolved_size: f32,
position: Position,
inset: Line<Option<f32>>,
margin: Line<Option<f32>>,
baseline_shim: f32,
direction: Direction,
) -> (f32, Line<f32>) {
// Calculate grid area dimension in the axis
let non_auto_margin = Line { start: margin.start.unwrap_or(0.0) + baseline_shim, end: margin.end.unwrap_or(0.0) };
let grid_area_size = f32_max(grid_area.end - grid_area.start, 0.0);
let free_space = f32_max(grid_area_size - resolved_size - non_auto_margin.sum(), 0.0);
// Expand auto margins to fill available space
let auto_margin_count = margin.start.is_none() as u8 + margin.end.is_none() as u8;
let auto_margin_size = if auto_margin_count > 0 { free_space / auto_margin_count as f32 } else { 0.0 };
let resolved_margin = Line {
start: margin.start.unwrap_or(auto_margin_size) + baseline_shim,
end: margin.end.unwrap_or(auto_margin_size),
};
let overflows = resolved_size + non_auto_margin.sum() > grid_area_size;
let alignment_keyword = resolve_self_alignment_safety(alignment_style, overflows);
// Compute offset in the axis
let alignment_based_offset = match alignment_keyword {
// TODO: Add support for baseline alignment. For now we treat it as "start".
AlignItemsKeyword::Start
| AlignItemsKeyword::FlexStart
| AlignItemsKeyword::Baseline
| AlignItemsKeyword::Stretch => {
if direction.is_rtl() {
grid_area_size - resolved_size - resolved_margin.end
} else {
resolved_margin.start
}
}
AlignItemsKeyword::End | AlignItemsKeyword::FlexEnd => {
if direction.is_rtl() {
resolved_margin.start
} else {
grid_area_size - resolved_size - resolved_margin.end
}
}
AlignItemsKeyword::Center => {
(grid_area_size - resolved_size + resolved_margin.start - resolved_margin.end) / 2.0
}
// Normal is resolved, and SelfStart/SelfEnd are resolved to Start/End against
// the item's own direction, in `align_and_position_item`.
AlignItemsKeyword::Normal | AlignItemsKeyword::SelfStart | AlignItemsKeyword::SelfEnd => unreachable!(),
};
let offset_within_area = if position.is_out_of_flow() {
match (inset.start, inset.end) {
(Some(start), Some(end)) => {
if direction.is_rtl() {
grid_area_size - end - resolved_size - non_auto_margin.end
} else {
start + non_auto_margin.start
}
}
(Some(start), None) => start + non_auto_margin.start,
(None, Some(end)) => grid_area_size - end - resolved_size - non_auto_margin.end,
(None, None) => alignment_based_offset,
}
} else {
alignment_based_offset
};
let mut start = grid_area.start + offset_within_area;
if position == Position::Relative {
let relative_inset = if direction.is_rtl() {
inset.end.map(|pos| -pos).or(inset.start)
} else {
inset.start.or(inset.end.map(|pos| -pos))
};
start += relative_inset.unwrap_or(0.0);
}
(start, resolved_margin)
}
+833
View File
@@ -0,0 +1,833 @@
//! Helper functions for initialising GridTrack's from styles
//! This mainly consists of evaluating GridAutoTracks
use super::types::{GridTrack, GridTrackKind, TrackCounts};
use crate::geometry::AbsoluteAxis;
use crate::style::{LengthPercentage, RepetitionCount, TrackSizingFunction};
use crate::style_helpers::TaffyAuto;
use crate::util::sys::{ceil, floor, Vec};
use crate::util::MaybeMath;
use crate::util::ResolveOrZero;
use core::cmp::min;
use super::MAX_GRID_TRACKS;
use crate::{GenericGridTemplateComponent, GenericRepetition, GridContainerStyle};
/// The auto-repeat fit strategy to use
pub(crate) enum AutoRepeatStrategy {
/// If the grid container has a definite size or max size in the relevant axis:
/// - then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow the content
/// box of its grid container.
MaxRepetitionsThatDoNotOverflow,
/// Otherwise, if the grid container has a definite min size in the relevant axis:
/// - then the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement
MinRepetitionsThatDoOverflow,
}
/// Compute the number of rows and columns in the explicit grid
pub(crate) fn compute_explicit_grid_size_in_axis(
style: &impl GridContainerStyle,
auto_fit_container_size: Option<f32>,
auto_fit_strategy: AutoRepeatStrategy,
resolve_calc_value: impl Fn(*const (), f32) -> f32,
axis: AbsoluteAxis,
) -> (u16, u16) {
let template = match axis {
AbsoluteAxis::Horizontal => style.grid_template_columns(),
AbsoluteAxis::Vertical => style.grid_template_rows(),
};
let Some(template) = template else {
return (0, 0);
};
// If template contains no tracks, then there are trivially zero explicit tracks
let track_count = template.len();
if track_count == 0 {
return (0, 0);
}
// If there are any repetitions that contains no tracks, then the whole definition should be considered invalid
// and we default to no explicit tracks
let template_has_repetitions_with_zero_tracks = template.clone().any(|track_def| match track_def {
GenericGridTemplateComponent::Single(_) => false,
GenericGridTemplateComponent::Repeat(repeat) => repeat.track_count() == 0,
});
if template_has_repetitions_with_zero_tracks {
return (0, 0);
}
// Compute that number of track generated by single track definition and repetitions with a fixed repetition count
// (clamping to the maximum track limit to prevent arithmetic overflow)
let non_auto_repeating_track_count = template
.clone()
.fold(0u32, |track_count, track_def| {
let additional_tracks = match track_def {
GenericGridTemplateComponent::Single(_) => 1u32,
GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
RepetitionCount::Count(count) => count as u32 * repeat.track_count() as u32,
RepetitionCount::AutoFit | RepetitionCount::AutoFill => 0,
},
};
track_count.saturating_add(additional_tracks)
})
.min(MAX_GRID_TRACKS as u32) as u16;
let auto_repetition_count: u16 = template.clone().filter(|track_def| track_def.is_auto_repetition()).count() as u16;
let all_track_defs_have_fixed_component = template.clone().all(|track_def| match track_def {
GenericGridTemplateComponent::Single(sizing_function) => sizing_function.has_fixed_component(),
GenericGridTemplateComponent::Repeat(repeat) => {
repeat.tracks().all(|sizing_function| sizing_function.has_fixed_component())
}
});
let template_is_valid =
auto_repetition_count == 0 || (auto_repetition_count == 1 && all_track_defs_have_fixed_component);
// If the template is invalid because it contains multiple auto-repetition definitions or it combines an auto-repetition
// definition with non-fixed-size track sizing functions, then disregard it entirely and default to zero explicit tracks
if !template_is_valid {
return (0, 0);
}
// If there are no repetitions, then the number of explicit tracks is simply equal to the lengths of the track definition
// vector (as each item in the Vec represents one track).
if auto_repetition_count == 0 {
return (0, non_auto_repeating_track_count);
}
let mut auto_repeat_insertion_point = 0u32;
let repetition_definition = template
.clone()
.find_map(|def| match def {
GenericGridTemplateComponent::Single(_) => {
auto_repeat_insertion_point = auto_repeat_insertion_point.saturating_add(1);
None
}
GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
RepetitionCount::Count(count) => {
auto_repeat_insertion_point =
auto_repeat_insertion_point.saturating_add(count as u32 * repeat.track_count() as u32);
None
}
RepetitionCount::AutoFit | RepetitionCount::AutoFill => Some(repeat),
},
})
.unwrap();
let repetition_definition_iter = repetition_definition.tracks();
let repetition_track_count = repetition_definition_iter.len().min(u16::MAX as usize) as u16;
// Determine the number of repetitions
let num_repetitions: u32 = match auto_fit_container_size {
None => 1,
Some(inner_container_size) => {
let parent_size = Some(inner_container_size);
/// ...treating each track as its max track sizing function if that is definite or as its minimum track sizing function
/// otherwise, flooring the max track sizing function by the min track sizing function if both are definite
fn track_definite_value(
sizing_function: TrackSizingFunction,
parent_size: Option<f32>,
calc_resolver: impl Fn(*const (), f32) -> f32,
) -> f32 {
let max_size = sizing_function.max.definite_value(parent_size, &calc_resolver);
let min_size = sizing_function.min.definite_value(parent_size, &calc_resolver);
max_size.map(|max| max.maybe_max(min_size)).or(min_size).unwrap()
}
let non_repeating_track_used_space: f32 = template
.clone()
.map(|track_def| match track_def {
GenericGridTemplateComponent::Single(sizing_function) => {
track_definite_value(sizing_function, parent_size, &resolve_calc_value)
}
GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
RepetitionCount::Count(count) => {
let sum = repeat
.tracks()
.map(|sizing_function| {
track_definite_value(sizing_function, parent_size, &resolve_calc_value)
})
.sum::<f32>();
sum * (count as f32)
}
RepetitionCount::AutoFit | RepetitionCount::AutoFill => 0.0,
},
})
.sum();
let gap_size = style.gap().get_abs(axis).resolve_or_zero(Some(inner_container_size), &resolve_calc_value);
// Compute the amount of space that a single repetition of the repeated track list takes
let per_repetition_track_used_space: f32 = repetition_definition_iter
.map(|sizing_function| track_definite_value(sizing_function, parent_size, &resolve_calc_value))
.sum::<f32>();
// We special case the first repetition here because the number of gaps in the first repetition
// depends on the number of non-repeating tracks in the template
let first_repetition_and_non_repeating_tracks_used_space = non_repeating_track_used_space
+ per_repetition_track_used_space
+ ((non_auto_repeating_track_count as u32 + repetition_track_count as u32).saturating_sub(1) as f32
* gap_size);
// If a single repetition already overflows the container then we return 1 as the repetition count
// (the number of repetitions is floored at 1)
if first_repetition_and_non_repeating_tracks_used_space > inner_container_size {
1u32
} else {
let per_repetition_gap_used_space = (repetition_track_count as f32) * gap_size;
let per_repetition_used_space = per_repetition_track_used_space + per_repetition_gap_used_space;
let num_repetition_that_fit = (inner_container_size
- first_repetition_and_non_repeating_tracks_used_space)
/ per_repetition_used_space;
// If the container size is a preferred or maximum size:
// Then we return the maximum number of repetitions that fit into the container without overflowing.
// If the container size is a minimum size:
// - Then we return the minimum number of repetitions required to overflow the size.
//
// In all cases we add the additional repetition that was already accounted for in the special-case computation above
// Note: as-casts from f32 to u32 saturate, so a huge or infinite number of repetitions
// (e.g. due to zero-sized tracks) resolves to u32::MAX and is clamped below
match auto_fit_strategy {
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow => {
(floor(num_repetition_that_fit) as u32).saturating_add(1)
}
AutoRepeatStrategy::MinRepetitionsThatDoOverflow => {
(ceil(num_repetition_that_fit) as u32).saturating_add(1)
}
}
}
}
};
// Clamp the number of repetitions based on the auto-repeat's insertion point so that tracks
// before it are preserved and tracks after it are truncated in source order.
// https://www.w3.org/TR/css-grid-1/#overlarge-grids
let remaining_tracks = (MAX_GRID_TRACKS as u32).saturating_sub(auto_repeat_insertion_point);
let num_repetitions = if remaining_tracks == 0 {
0
} else {
let max_repetitions = (remaining_tracks + repetition_track_count as u32 - 1) / repetition_track_count as u32;
num_repetitions.clamp(1, max_repetitions) as u16
};
let grid_template_track_count = min(
non_auto_repeating_track_count as u32 + (repetition_track_count as u32 * num_repetitions as u32),
MAX_GRID_TRACKS as u32,
) as u16;
(num_repetitions, grid_template_track_count)
}
/// Resolve the track sizing functions of explicit tracks, automatically created tracks, and gutters
/// given a set of track counts and all of the relevant styles
pub(super) fn initialize_grid_tracks(
tracks: &mut Vec<GridTrack>,
counts: TrackCounts,
style: &impl GridContainerStyle,
axis: AbsoluteAxis,
auto_repetition_count: u16,
track_has_items: impl Fn(usize) -> bool,
) {
// Extract styles
let track_template;
let auto_tracks;
let gap;
match axis {
AbsoluteAxis::Horizontal => {
track_template = style.grid_template_columns();
auto_tracks = style.grid_auto_columns();
gap = style.gap().width;
}
AbsoluteAxis::Vertical => {
track_template = style.grid_template_rows();
auto_tracks = style.grid_auto_rows();
gap = style.gap().height;
}
};
// Clear vector (in case this is a re-layout), reserve space for all tracks ahead of time to reduce allocations,
// and push the initial gutter
tracks.clear();
tracks.reserve((counts.len() * 2) + 1);
tracks.push(GridTrack::gutter(gap));
let auto_track_count = auto_tracks.len();
// Create negative implicit tracks
if counts.negative_implicit > 0 {
if auto_track_count == 0 {
let iter = core::iter::repeat(TrackSizingFunction::AUTO);
create_implicit_tracks(tracks, counts.negative_implicit, iter, gap)
} else {
let offset = auto_track_count - (counts.negative_implicit as usize % auto_track_count);
let iter = auto_tracks.clone().cycle().skip(offset);
create_implicit_tracks(tracks, counts.negative_implicit, iter, gap)
}
}
let mut current_track_index = (counts.negative_implicit) as usize;
// The maximum index up to which explicit tracks may be created. The explicit track count is clamped
// to MAX_GRID_TRACKS, so track creation from the template must be truncated to match.
let explicit_track_limit = (counts.negative_implicit + counts.explicit) as usize;
// Create explicit tracks
// An explicit check against the count (rather than just relying on track_template being empty) is required here
// because a count of zero can result from the track_template being invalid, in which case it should be ignored.
if counts.explicit > 0 {
if let Some(track_template) = track_template {
track_template.for_each(|track_sizing_function| {
match track_sizing_function {
GenericGridTemplateComponent::Single(sizing_function) => {
if current_track_index < explicit_track_limit {
tracks.push(GridTrack::new(
sizing_function.min_sizing_function(),
sizing_function.max_sizing_function(),
));
tracks.push(GridTrack::gutter(gap));
current_track_index += 1;
}
}
GenericGridTemplateComponent::Repeat(repeat) => match repeat.count() {
RepetitionCount::Count(count) => {
let repeated_track_count = (repeat.track_count() as usize * count as usize)
.min(explicit_track_limit - current_track_index);
let track_iter = repeat.tracks();
let track_iter = track_iter.cycle().take(repeated_track_count);
track_iter.for_each(|sizing_function| {
tracks.push(GridTrack::new(
sizing_function.min_sizing_function(),
sizing_function.max_sizing_function(),
));
tracks.push(GridTrack::gutter(gap));
current_track_index += 1;
});
}
RepetitionCount::AutoFit | RepetitionCount::AutoFill => {
let auto_repeated_track_count = (repeat.track_count() as usize
* auto_repetition_count as usize)
.min(explicit_track_limit - current_track_index);
let iter = repeat.tracks().cycle();
for track_def in iter.take(auto_repeated_track_count) {
let mut track =
GridTrack::new(track_def.min_sizing_function(), track_def.max_sizing_function());
let mut gutter = GridTrack::gutter(gap);
// Auto-fit tracks that don't contain should be collapsed.
if repeat.count() == RepetitionCount::AutoFit && !track_has_items(current_track_index) {
track.collapse();
gutter.collapse();
}
tracks.push(track);
tracks.push(gutter);
current_track_index += 1;
}
// Is this auto-repeat at the very end of the track list?
let is_last = current_track_index == counts.len();
// When collapsing auto-fit tracks (in the loop just above), we collapse the gutter after collapsed
// tracks but not the gutter before. This is correct so long as there is another non-collapsed track
// somewhere in the track list after the collapsed track.
//
// However, if the auto-fit repeat is at the very end of the track list, then there will be no such track.
// In this case we need to iterate backwards through the track list until we find a non-collapsed track and
// collapse the gutter just after that track.
//
// As all of the other tracks and gutters we find along the way will already be collapsed, we simplify the
// implementation to collapsing all tracks and gutters until we find the first non-collapsed track.
if repeat.count() == RepetitionCount::AutoFit && is_last {
for previous_track in tracks.iter_mut().rev() {
if previous_track.kind == GridTrackKind::Track && !previous_track.is_collapsed {
break;
}
previous_track.collapse();
}
}
}
},
}
});
}
}
let grid_area_tracks = (counts.negative_implicit + counts.explicit) - current_track_index as u16;
// Create positive implicit tracks
if auto_track_count == 0 {
let iter = core::iter::repeat(TrackSizingFunction::AUTO);
create_implicit_tracks(tracks, counts.positive_implicit + grid_area_tracks, iter, gap)
} else {
let iter = auto_tracks.clone().cycle();
create_implicit_tracks(tracks, counts.positive_implicit + grid_area_tracks, iter, gap)
}
// Mark first and last grid lines as collapsed
tracks.first_mut().unwrap().collapse();
tracks.last_mut().unwrap().collapse();
}
/// Utility function for repeating logic of creating implicit tracks
fn create_implicit_tracks(
tracks: &mut Vec<GridTrack>,
count: u16,
mut auto_tracks_iter: impl Iterator<Item = TrackSizingFunction>,
gap: LengthPercentage,
) {
for _ in 0..count {
let track_def = auto_tracks_iter.next().unwrap();
tracks.push(GridTrack::new(track_def.min_sizing_function(), track_def.max_sizing_function()));
tracks.push(GridTrack::gutter(gap));
}
}
#[cfg(test)]
mod test {
use super::compute_explicit_grid_size_in_axis;
use super::initialize_grid_tracks;
use crate::compute::grid::explicit_grid::AutoRepeatStrategy;
use crate::compute::grid::types::GridTrackKind;
use crate::compute::grid::types::TrackCounts;
use crate::compute::grid::util::*;
use crate::geometry::AbsoluteAxis;
use crate::prelude::*;
use crate::sys::DefaultCheapStr;
#[test]
fn explicit_grid_sizing_no_repeats() {
let grid_style = (600.0, 600.0, 2, 4).into_grid();
let preferred_size = grid_style.size.map(|s| s.into_option());
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 2);
assert_eq!(row_count, 4);
assert_eq!(auto_col_reps, 0);
assert_eq!(auto_row_reps, 0);
}
#[test]
fn explicit_grid_sizing_auto_fill_exact_fit() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
size: Size { width: length(120.0), height: length(80.0) },
grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
..Default::default()
};
let preferred_size = grid_style.size.map(|s| s.into_option());
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 3);
assert_eq!(row_count, 4);
assert_eq!(auto_col_reps, 3);
assert_eq!(auto_row_reps, 4);
}
#[test]
fn explicit_grid_sizing_auto_fill_non_exact_fit() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
size: Size { width: length(140.0), height: length(90.0) },
grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
..Default::default()
};
let preferred_size = grid_style.size.map(|s| s.into_option());
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 3);
assert_eq!(row_count, 4);
assert_eq!(auto_col_reps, 3);
assert_eq!(auto_row_reps, 4);
}
#[test]
fn explicit_grid_sizing_auto_fill_min_size_exact_fit() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
min_size: Size { width: length(120.0), height: length(80.0) },
grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
..Default::default()
};
let inner_container_size = Size { width: Some(120.0), height: Some(80.0) };
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
inner_container_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
inner_container_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 3);
assert_eq!(row_count, 4);
assert_eq!(auto_col_reps, 3);
assert_eq!(auto_row_reps, 4);
}
#[test]
fn explicit_grid_sizing_auto_fill_min_size_non_exact_fit() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
min_size: Size { width: length(140.0), height: length(90.0) },
grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
..Default::default()
};
let inner_container_size = Size { width: Some(140.0), height: Some(90.0) };
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
inner_container_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
inner_container_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 4);
assert_eq!(row_count, 5);
assert_eq!(auto_col_reps, 4);
assert_eq!(auto_row_reps, 5);
}
#[test]
fn explicit_grid_sizing_auto_fill_multiple_repeated_tracks() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
size: Size { width: length(140.0), height: length(100.0) },
grid_template_columns: vec![repeat(AutoFill, vec![length(40.0), length(20.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0), length(10.0)])],
..Default::default()
};
let preferred_size = grid_style.size.map(|s| s.into_option());
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 4); // 2 repetitions * 2 repeated tracks = 4 tracks in total
assert_eq!(row_count, 6); // 3 repetitions * 2 repeated tracks = 4 tracks in total
assert_eq!(auto_col_reps, 2);
assert_eq!(auto_row_reps, 3);
}
#[test]
fn explicit_grid_sizing_auto_fill_gap() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
size: Size { width: length(140.0), height: length(100.0) },
grid_template_columns: vec![repeat(AutoFill, vec![length(40.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
gap: length(20.0),
..Default::default()
};
let preferred_size = grid_style.size.map(|s| s.into_option());
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 2); // 2 tracks + 1 gap
assert_eq!(row_count, 3); // 3 tracks + 2 gaps
assert_eq!(auto_col_reps, 2);
assert_eq!(auto_row_reps, 3);
}
#[test]
fn explicit_grid_sizing_no_defined_size() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
grid_template_columns: vec![repeat(AutoFill, vec![length(40.0), percent(0.5), length(20.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
gap: length(20.0),
..Default::default()
};
let preferred_size = grid_style.size.map(|s| s.into_option());
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 3);
assert_eq!(row_count, 1);
assert_eq!(auto_col_reps, 1);
assert_eq!(auto_row_reps, 1);
}
#[test]
fn explicit_grid_sizing_mix_repeated_and_non_repeated() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
size: Size { width: length(140.0), height: length(100.0) },
grid_template_columns: vec![length(20.0), repeat(AutoFill, vec![length(40.0)])],
grid_template_rows: vec![length(40.0), repeat(AutoFill, vec![length(20.0)])],
gap: length(20.0),
..Default::default()
};
let preferred_size = grid_style.size.map(|s| s.into_option());
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
preferred_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 3); // 3 tracks + 2 gaps
assert_eq!(row_count, 2); // 2 tracks + 1 gap
assert_eq!(auto_col_reps, 2);
assert_eq!(auto_row_reps, 1);
}
#[test]
fn explicit_grid_sizing_mix_with_padding() {
use RepetitionCount::AutoFill;
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
size: Size { width: length(120.0), height: length(120.0) },
padding: Rect { left: length(10.0), right: length(10.0), top: length(20.0), bottom: length(20.0) },
grid_template_columns: vec![repeat(AutoFill, vec![length(20.0)])],
grid_template_rows: vec![repeat(AutoFill, vec![length(20.0)])],
..Default::default()
};
let inner_container_size = Size { width: Some(100.0), height: Some(80.0) };
let (auto_col_reps, col_count) = compute_explicit_grid_size_in_axis(
&grid_style,
inner_container_size.get_abs(AbsoluteAxis::Horizontal),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
let (auto_row_reps, row_count) = compute_explicit_grid_size_in_axis(
&grid_style,
inner_container_size.get_abs(AbsoluteAxis::Vertical),
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Vertical,
);
assert_eq!(col_count, 5); // 40px horizontal padding
assert_eq!(row_count, 4); // 20px vertical padding
assert_eq!(auto_col_reps, 5);
assert_eq!(auto_row_reps, 4);
}
#[test]
fn auto_repeat_clamping_preserves_template_source_order() {
use RepetitionCount::{AutoFill, Count};
let auto_repeat_first: Style<DefaultCheapStr> = Style {
display: Display::Grid,
grid_template_columns: vec![repeat(AutoFill, vec![length(2.0)]), repeat(Count(10_000), vec![length(37.0)])],
..Default::default()
};
let (repetitions, track_count) = compute_explicit_grid_size_in_axis(
&auto_repeat_first,
None,
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
assert_eq!((repetitions, track_count), (1, 10_000));
let mut tracks = Vec::new();
initialize_grid_tracks(
&mut tracks,
TrackCounts::from_raw(0, track_count, 0),
&auto_repeat_first,
AbsoluteAxis::Horizontal,
repetitions,
|_| false,
);
assert_eq!(tracks[1].min_track_sizing_function, MinTrackSizingFunction::from_length(2.0));
assert_eq!(tracks[3].min_track_sizing_function, MinTrackSizingFunction::from_length(37.0));
let auto_repeat_last: Style<DefaultCheapStr> = Style {
display: Display::Grid,
grid_template_columns: vec![repeat(Count(10_000), vec![length(37.0)]), repeat(AutoFill, vec![length(2.0)])],
..Default::default()
};
let (repetitions, track_count) = compute_explicit_grid_size_in_axis(
&auto_repeat_last,
None,
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
assert_eq!((repetitions, track_count), (0, 10_000));
}
#[test]
fn explicit_track_count_accumulation_saturates() {
use RepetitionCount::{AutoFill, Count};
let repeated_tracks = vec![length(1.0); 32_769];
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
grid_template_columns: vec![
repeat(Count(u16::MAX), repeated_tracks.clone()),
repeat(Count(u16::MAX), repeated_tracks),
repeat(AutoFill, vec![length(1.0)]),
],
..Default::default()
};
let result = compute_explicit_grid_size_in_axis(
&grid_style,
None,
AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
|_, _| 42.42,
AbsoluteAxis::Horizontal,
);
assert_eq!(result, (0, 10_000));
}
#[test]
fn test_initialize_grid_tracks() {
let minpx0 = MinTrackSizingFunction::from_length(0.0);
let minpx20 = MinTrackSizingFunction::from_length(20.0);
let minpx100 = MinTrackSizingFunction::from_length(100.0);
let maxpx0 = MaxTrackSizingFunction::from_length(0.0);
let maxpx20 = MaxTrackSizingFunction::from_length(20.0);
let maxpx100 = MaxTrackSizingFunction::from_length(100.0);
// Setup test
let grid_style: Style<DefaultCheapStr> = Style {
display: Display::Grid,
gap: length(20.0),
grid_template_columns: vec![length(100.0), minmax(length(100.0), fr(2.0)), fr(1.0)],
grid_auto_columns: vec![auto(), length(100.0)],
..Default::default()
};
let track_counts = TrackCounts {
negative_implicit: 3,
explicit: grid_style.grid_template_columns.len() as u16,
positive_implicit: 3,
};
// Call function
let mut tracks = Vec::new();
initialize_grid_tracks(&mut tracks, track_counts, &grid_style, AbsoluteAxis::Horizontal, 0, |_| false);
// Assertions
let expected = vec![
// Gutter
(GridTrackKind::Gutter, minpx0, maxpx0),
// Negative implicit tracks
(GridTrackKind::Track, minpx100, maxpx100),
(GridTrackKind::Gutter, minpx20, maxpx20),
(GridTrackKind::Track, auto(), auto()),
(GridTrackKind::Gutter, minpx20, maxpx20),
(GridTrackKind::Track, minpx100, maxpx100),
(GridTrackKind::Gutter, minpx20, maxpx20),
// Explicit tracks
(GridTrackKind::Track, minpx100, maxpx100),
(GridTrackKind::Gutter, minpx20, maxpx20),
(GridTrackKind::Track, minpx100, MaxTrackSizingFunction::from_fr(2.0)), // Note: separate min-max functions
(GridTrackKind::Gutter, minpx20, maxpx20),
(GridTrackKind::Track, auto(), MaxTrackSizingFunction::from_fr(1.0)), // Note: min sizing function of flex sizing functions is AUTO
(GridTrackKind::Gutter, minpx20, maxpx20),
// Positive implicit tracks
(GridTrackKind::Track, auto(), auto()),
(GridTrackKind::Gutter, minpx20, maxpx20),
(GridTrackKind::Track, minpx100, maxpx100),
(GridTrackKind::Gutter, minpx20, maxpx20),
(GridTrackKind::Track, auto(), auto()),
(GridTrackKind::Gutter, minpx0, maxpx0),
];
assert_eq!(tracks.len(), expected.len(), "Number of tracks doesn't match");
for (idx, (actual, (kind, min, max))) in tracks.into_iter().zip(expected).enumerate() {
assert_eq!(actual.kind, kind, "Track {idx} (0-based index)");
assert_eq!(actual.min_track_sizing_function, min, "Track {idx} (0-based index)");
assert_eq!(actual.max_track_sizing_function, max, "Track {idx} (0-based index)");
}
}
}
+249
View File
@@ -0,0 +1,249 @@
//! This module is not required for spec compliance, but is used as a performance optimisation
//! to reduce the number of allocations required when creating a grid.
use crate::geometry::Line;
use crate::style::{GenericGridPlacement, OriginZeroGridPlacement};
use core::cmp::{max, min};
use super::types::TrackCounts;
use super::{ItemPlacement, OriginZeroLine, MAX_OZ_LINE, MIN_OZ_LINE};
/// Estimate the number of rows and columns in the grid
/// This is used as a performance optimisation to pre-size vectors and reduce allocations. It also forms a necessary step
/// in the auto-placement
/// - The estimates for the explicit and negative implicit track counts are exact.
/// - However, the estimates for the positive explicit track count is a lower bound as auto-placement can affect this
/// in ways which are impossible to predict until the auto-placement algorithm is run.
///
/// Note that this function internally mixes use of grid track numbers and grid line numbers
pub(crate) fn compute_grid_size_estimate(
explicit_col_count: u16,
explicit_row_count: u16,
placements: &[ItemPlacement],
) -> (TrackCounts, TrackCounts) {
// Iterate over children, producing an estimate of the min and max grid lines (in origin-zero coordinates where)
// along with the span of each item
let (col_min, col_max, col_max_span, row_min, row_max, row_max_span) = get_known_child_positions(placements);
// Compute *track* count estimates for each axis from:
// - The explicit track counts
// - The origin-zero coordinate min and max grid line variables
let negative_implicit_inline_tracks = col_min.implied_negative_implicit_tracks();
let explicit_inline_tracks = explicit_col_count;
let mut positive_implicit_inline_tracks = col_max.implied_positive_implicit_tracks(explicit_col_count);
let negative_implicit_block_tracks = row_min.implied_negative_implicit_tracks();
let explicit_block_tracks = explicit_row_count;
let mut positive_implicit_block_tracks = row_max.implied_positive_implicit_tracks(explicit_row_count);
// In each axis, adjust positive track estimate if any items have a span that does not fit within
// the total number of tracks in the estimate
let tot_inline_tracks = negative_implicit_inline_tracks + explicit_inline_tracks + positive_implicit_inline_tracks;
if tot_inline_tracks < col_max_span {
positive_implicit_inline_tracks = col_max_span - explicit_inline_tracks - negative_implicit_inline_tracks;
}
let tot_block_tracks = negative_implicit_block_tracks + explicit_block_tracks + positive_implicit_block_tracks;
if tot_block_tracks < row_max_span {
positive_implicit_block_tracks = row_max_span - explicit_block_tracks - negative_implicit_block_tracks;
}
let column_counts =
TrackCounts::from_raw(negative_implicit_inline_tracks, explicit_inline_tracks, positive_implicit_inline_tracks);
let row_counts =
TrackCounts::from_raw(negative_implicit_block_tracks, explicit_block_tracks, positive_implicit_block_tracks);
(column_counts, row_counts)
}
/// Iterate over the children's `grid-row`/`grid-column` styles (named lines resolved), producing an estimate of the
/// min and max grid *lines* along with the span of each item
///
/// Min and max grid lines are returned in origin-zero coordinates)
/// The span is measured in tracks spanned
fn get_known_child_positions(
placements: &[ItemPlacement],
) -> (OriginZeroLine, OriginZeroLine, u16, OriginZeroLine, OriginZeroLine, u16) {
let (mut col_min, mut col_max, mut col_max_span) = (OriginZeroLine(0), OriginZeroLine(0), 0);
let (mut row_min, mut row_max, mut row_max_span) = (OriginZeroLine(0), OriginZeroLine(0), 0);
placements.iter().for_each(|placement| {
// Note: that the children reference the lines in between (and around) the tracks not tracks themselves,
// and thus we must subtract 1 to get an accurate estimate of the number of tracks
let (child_col_min, child_col_max, child_col_span) = child_min_line_max_line_span(placement.horizontal);
let (child_row_min, child_row_max, child_row_span) = child_min_line_max_line_span(placement.vertical);
col_min = min(col_min, child_col_min);
col_max = max(col_max, child_col_max);
col_max_span = max(col_max_span, child_col_span);
row_min = min(row_min, child_row_min);
row_max = max(row_max, child_row_max);
row_max_span = max(row_max_span, child_row_span);
});
(col_min, col_max, col_max_span, row_min, row_max, row_max_span)
}
/// Helper function for `compute_grid_size_estimate`
/// Produces a conservative estimate of the greatest and smallest grid lines used by a single grid item
///
/// Values are returned in origin-zero coordinates
#[inline]
fn child_min_line_max_line_span(oz_line: Line<OriginZeroGridPlacement>) -> (OriginZeroLine, OriginZeroLine, u16) {
use GenericGridPlacement::*;
// 8.3.1. Grid Placement Conflict Handling
// A. If the placement for a grid item contains two lines, and the start line is further end-ward than the end line, swap the two lines.
// B. If the start line is equal to the end line, remove the end line.
// C. If the placement contains two spans, remove the one contributed by the end grid-placement property.
// D. If the placement contains only a span for a named line, replace it with a span of 1.
let min = match (oz_line.start, oz_line.end) {
// Both tracks specified
(Line(track1), Line(track2)) => {
// See rules A and B above
if track1 == track2 {
track1
} else {
min(track1, track2)
}
}
// Start track specified
(Line(track), Auto) => track,
(Line(track), Span(_)) => track,
// End track specified
// An auto start with a definite end resolves to a span of 1 ending at that line
(Auto, Line(track)) => track - 1,
(Span(span), Line(track)) => track - span,
// Only spans or autos
// We ignore spans here by returning 0 which never effect the estimate as these are accounted for separately
(Auto | Span(_), Auto | Span(_)) => OriginZeroLine(0),
};
let max = match (oz_line.start, oz_line.end) {
// Both tracks specified
(Line(track1), Line(track2)) => {
// See rules A and B above
if track1 == track2 {
track1 + 1
} else {
max(track1, track2)
}
}
// Start track specified
(Line(track), Auto) => track + 1,
(Line(track), Span(span)) => track + span,
// End track specified
(Auto, Line(track)) => track,
(Span(_), Line(track)) => track,
// Only spans or autos
// We ignore spans here by returning 0 which never effect the estimate as these are accounted for separately
(Auto | Span(_), Auto | Span(_)) => OriginZeroLine(0),
};
// Calculate span only for indefinitely placed items as we don't need for other items (whose required space will
// be taken into account by min and max)
let span = match (oz_line.start, oz_line.end) {
(Auto | Span(_), Auto | Span(_)) => oz_line.indefinite_span(),
_ => 1,
};
// Clamp the min and max lines into the limited grid so that the estimated implicit track counts
// stay within the maximum track limit (https://www.w3.org/TR/css-grid-1/#overlarge-grids).
// This matches the clamping of the actual item placements performed during placement.
let clamped_min = OriginZeroLine(min.0.max(MIN_OZ_LINE));
let clamped_max = OriginZeroLine(max.0.min(MAX_OZ_LINE));
(clamped_min, clamped_max, span)
}
#[allow(clippy::bool_assert_comparison)]
#[cfg(test)]
mod tests {
mod test_child_min_max_line {
use super::super::child_min_line_max_line_span;
use super::super::OriginZeroLine;
use crate::geometry::Line;
use crate::style::GridPlacement;
use crate::style_helpers::*;
#[test]
fn child_min_max_line_auto() {
let (min_col, max_col, span) = child_min_line_max_line_span(
Line::<GridPlacement<String>> { start: line(5), end: span(6) }.into_origin_zero_ignoring_named(6),
);
assert_eq!(min_col, OriginZeroLine(4));
assert_eq!(max_col, OriginZeroLine(10));
assert_eq!(span, 1);
}
#[test]
fn child_min_max_line_negative_track() {
let (min_col, max_col, span) = child_min_line_max_line_span(
Line::<GridPlacement<String>> { start: line(-5), end: span(3) }.into_origin_zero_ignoring_named(6),
);
assert_eq!(min_col, OriginZeroLine(2));
assert_eq!(max_col, OriginZeroLine(5));
assert_eq!(span, 1);
}
}
mod test_initial_grid_sizing {
use super::super::{compute_grid_size_estimate, TrackCounts};
use crate::compute::grid::util::test_helpers::*;
use crate::compute::grid::NamedLineResolver;
use crate::style_helpers::*;
use crate::Style;
fn estimate(
explicit_col_count: u16,
explicit_row_count: u16,
child_styles: &[Style],
) -> (TrackCounts, TrackCounts) {
let mut name_resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
name_resolver.set_explicit_column_count(explicit_col_count);
name_resolver.set_explicit_row_count(explicit_row_count);
let placements =
resolve_named_lines(child_styles.iter(), &name_resolver, explicit_col_count, explicit_row_count);
compute_grid_size_estimate(explicit_col_count, explicit_row_count, &placements)
}
#[test]
fn explicit_grid_sizing_with_children() {
let explicit_col_count = 6;
let explicit_row_count = 8;
let child_styles = [
(line(1), span(2), line(2), auto()).into_grid_child(),
(line(-4), auto(), line(-2), auto()).into_grid_child(),
];
let (inline, block) = estimate(explicit_col_count, explicit_row_count, &child_styles);
assert_eq!(inline.negative_implicit, 0);
assert_eq!(inline.explicit, explicit_col_count);
assert_eq!(inline.positive_implicit, 0);
assert_eq!(block.negative_implicit, 0);
assert_eq!(block.explicit, explicit_row_count);
assert_eq!(block.positive_implicit, 0);
}
#[test]
fn negative_implicit_grid_sizing() {
let explicit_col_count = 4;
let explicit_row_count = 4;
let child_styles = [
(line(-6), span(2), line(-8), auto()).into_grid_child(),
(line(4), auto(), line(3), auto()).into_grid_child(),
];
let (inline, block) = estimate(explicit_col_count, explicit_row_count, &child_styles);
assert_eq!(inline.negative_implicit, 1);
assert_eq!(inline.explicit, explicit_col_count);
assert_eq!(inline.positive_implicit, 0);
assert_eq!(block.negative_implicit, 3);
assert_eq!(block.explicit, explicit_row_count);
assert_eq!(block.positive_implicit, 0);
}
}
}
File diff suppressed because it is too large. Load diff
+638
View File
@@ -0,0 +1,638 @@
//! Implements placing items in the grid and resolving the implicit grid.
//! <https://www.w3.org/TR/css-grid-1/#placement>
use super::types::{CellOccupancyMatrix, CellOccupancyState, GridItem};
use super::{OriginZeroLine, MAX_OZ_LINE, MIN_OZ_LINE};
use crate::geometry::Line;
use crate::geometry::{AbsoluteAxis, InBothAbsAxis};
use crate::style::{GridAutoFlow, OriginZeroGridPlacement};
#[inline]
/// Advances the cursor by one track.
fn advance_position(position: OriginZeroLine) -> OriginZeroLine {
OriginZeroLine(position.0.saturating_add(1))
}
#[inline]
/// Resolves an indefinite span starting at `position`.
fn resolve_indefinite_grid_span(position: OriginZeroLine, span: u16) -> Line<OriginZeroLine> {
let position = position.0 as i32;
let span = span as i32;
let line = |value: i32| OriginZeroLine(value.clamp(i16::MIN as i32, i16::MAX as i32) as i16);
Line { start: line(position), end: line(position + span) }
}
/// A grid item's `grid-row`/`grid-column` styles with named lines resolved, in origin-zero coordinates
pub(super) type ItemPlacement = InBothAbsAxis<Line<OriginZeroGridPlacement>>;
/// 8.5. Grid Item Placement Algorithm
/// Place items into the grid, generating new rows/column into the implicit grid as required
///
/// `items` and `placements` are parallel slices in document order: `placements[i]` holds the `grid-row`/`grid-column`
/// styles of `items[i]`, with named lines already resolved. The placement passes run over these (small) values rather
/// than re-reading the children's styles.
///
/// [Specification](https://www.w3.org/TR/css-grid-2/#auto-placement-algo)
pub(super) fn place_grid_items(
cell_occupancy_matrix: &mut CellOccupancyMatrix,
items: &mut [GridItem],
placements: &[ItemPlacement],
grid_auto_flow: GridAutoFlow,
) {
debug_assert_eq!(items.len(), placements.len());
let primary_axis = grid_auto_flow.primary_axis();
let secondary_axis = primary_axis.other_axis();
// 1. Place children with definite positions
for (item, &placement) in items.iter_mut().zip(placements.iter()) {
if !(placement.horizontal.is_definite() && placement.vertical.is_definite()) {
continue;
}
#[cfg(test)]
println!("Definite Item {}\n==============", item.source_order);
let (row_span, col_span) = place_definite_grid_item(placement, primary_axis);
record_grid_placement(
cell_occupancy_matrix,
item,
primary_axis,
row_span,
col_span,
CellOccupancyState::DefinitelyPlaced,
);
}
// 2. Place remaining children with definite secondary axis positions
for (item, &placement) in items.iter_mut().zip(placements.iter()) {
if !(placement.get(secondary_axis).is_definite() && !placement.get(primary_axis).is_definite()) {
continue;
}
#[cfg(test)]
println!("Definite Secondary Item {}\n==============", item.source_order);
let (primary_span, secondary_span) =
place_definite_secondary_axis_item(&*cell_occupancy_matrix, placement, grid_auto_flow);
record_grid_placement(
cell_occupancy_matrix,
item,
primary_axis,
primary_span,
secondary_span,
CellOccupancyState::AutoPlaced,
);
}
// 3. Determine the number of columns in the implicit grid
// By the time we get to this point in the execution, this is actually already accounted for:
//
// 3.1 Start with the columns from the explicit grid
// => Handled by grid size estimate which is used to pre-size the GridOccupancyMatrix
//
// 3.2 Among all the items with a definite column position (explicitly positioned items, items positioned in the previous step,
// and items not yet positioned but with a definite column) add columns to the beginning and end of the implicit grid as necessary
// to accommodate those items.
// => Handled by expand_to_fit_range which expands the GridOccupancyMatrix as necessary
// -> Called by mark_area_as
// -> Called by record_grid_placement
//
// 3.3 If the largest column span among all the items without a definite column position is larger than the width of
// the implicit grid, add columns to the end of the implicit grid to accommodate that column span.
// => Handled by grid size estimate which is used to pre-size the GridOccupancyMatrix
// 4. Position the remaining grid items
// (which either have definite position only in the secondary axis or indefinite positions in both axis)
let primary_axis = grid_auto_flow.primary_axis();
let secondary_axis = primary_axis.other_axis();
let primary_axis_grid_start_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_start_line();
let secondary_axis_grid_start_line = cell_occupancy_matrix.track_counts(secondary_axis).implicit_start_line();
let grid_start_position = (primary_axis_grid_start_line, secondary_axis_grid_start_line);
let mut grid_position = grid_start_position;
for (item, &placement) in items.iter_mut().zip(placements.iter()) {
if placement.get(secondary_axis).is_definite() {
continue;
}
#[cfg(test)]
println!("\nAuto Item {}\n==============", item.source_order);
// Compute placement
let (primary_span, secondary_span) =
place_indefinitely_positioned_item(&*cell_occupancy_matrix, placement, grid_auto_flow, grid_position);
// Record item
record_grid_placement(
cell_occupancy_matrix,
item,
primary_axis,
primary_span,
secondary_span,
CellOccupancyState::AutoPlaced,
);
// If using the "dense" placement algorithm then reset the grid position back to grid_start_position ready for the next item
// Otherwise set it to the position of the current item so that the next item it placed after it.
grid_position = match grid_auto_flow.is_dense() {
true => grid_start_position,
false => (primary_span.end, secondary_span.start),
};
}
}
/// 8.5. Grid Item Placement Algorithm
/// Place a single definitely placed item into the grid
fn place_definite_grid_item(
placement: ItemPlacement,
primary_axis: AbsoluteAxis,
) -> (Line<OriginZeroLine>, Line<OriginZeroLine>) {
// Resolve spans to tracks
let primary_span = placement.get(primary_axis).resolve_definite_grid_lines();
let secondary_span = placement.get(primary_axis.other_axis()).resolve_definite_grid_lines();
(primary_span, secondary_span)
}
/// 8.5. Grid Item Placement Algorithm
/// Step 2. Place remaining children with definite secondary axis positions
fn place_definite_secondary_axis_item(
cell_occupancy_matrix: &CellOccupancyMatrix,
placement: ItemPlacement,
auto_flow: GridAutoFlow,
) -> (Line<OriginZeroLine>, Line<OriginZeroLine>) {
let primary_axis = auto_flow.primary_axis();
let secondary_axis = primary_axis.other_axis();
let primary_axis_grid_start_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_start_line();
let secondary_axis_placement = placement.get(secondary_axis).resolve_definite_grid_lines();
let starting_position = match auto_flow.is_dense() {
true => primary_axis_grid_start_line,
false => cell_occupancy_matrix
.auto_placement_cursor(primary_axis, secondary_axis_placement.start)
.unwrap_or(primary_axis_grid_start_line),
};
let primary_axis_span = placement.get(primary_axis).indefinite_span();
let mut position: OriginZeroLine = starting_position;
loop {
let primary_axis_placement = resolve_indefinite_grid_span(position, primary_axis_span);
let collision = cell_occupancy_matrix.line_area_collision_jump(
primary_axis,
primary_axis_placement,
secondary_axis_placement,
);
match collision {
None => return (primary_axis_placement, secondary_axis_placement),
Some(next_position) => position = next_position,
}
}
}
/// 8.5. Grid Item Placement Algorithm
/// Step 4. Position the remaining grid items.
fn place_indefinitely_positioned_item(
cell_occupancy_matrix: &CellOccupancyMatrix,
placement: ItemPlacement,
auto_flow: GridAutoFlow,
grid_position: (OriginZeroLine, OriginZeroLine),
) -> (Line<OriginZeroLine>, Line<OriginZeroLine>) {
let primary_axis = auto_flow.primary_axis();
let secondary_axis = primary_axis.other_axis();
let primary_placement_style = placement.get(primary_axis);
let secondary_placement_style = placement.get(secondary_axis);
let secondary_span = secondary_placement_style.indefinite_span();
let has_definite_primary_axis_position = primary_placement_style.is_definite();
let primary_axis_grid_start_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_start_line();
let primary_axis_grid_end_line = cell_occupancy_matrix.track_counts(primary_axis).implicit_end_line();
let secondary_axis_grid_start_line = cell_occupancy_matrix.track_counts(secondary_axis).implicit_start_line();
let (mut primary_idx, mut secondary_idx) = grid_position;
if has_definite_primary_axis_position {
let primary_span = primary_placement_style.resolve_definite_grid_lines();
// Compute secondary axis starting position for search
secondary_idx = match auto_flow.is_dense() {
// If auto-flow is dense then we always search from the first track
true => secondary_axis_grid_start_line,
false => {
if primary_span.start < primary_idx {
advance_position(secondary_idx)
} else {
secondary_idx
}
}
};
// Item has fixed primary axis position: so we simply increment the secondary axis position
// until we find a space that the item fits in
loop {
let secondary_span = resolve_indefinite_grid_span(secondary_idx, secondary_span);
// If area is occupied, jump the index past the collision and try again
let collision =
cell_occupancy_matrix.line_area_collision_jump(secondary_axis, secondary_span, primary_span);
if let Some(next_position) = collision {
secondary_idx = next_position;
continue;
}
// Once we find a free space, return that position
return (primary_span, secondary_span);
}
} else {
let primary_span = primary_placement_style.indefinite_span();
// Whether the item spans every track in the primary axis. Such an item can only be
// placed at the primary axis grid start, in a stripe of entirely unoccupied tracks.
let spans_all_primary_tracks = primary_span as usize >= cell_occupancy_matrix.track_counts(primary_axis).len();
// Item does not have any fixed axis, so we search along the primary axis until we hit the end of the already
// existent tracks, and then we reset the primary axis back to zero and increment the secondary axis index.
// We continue in this vein until we find a space that the item fits in.
loop {
let primary_span = resolve_indefinite_grid_span(primary_idx, primary_span);
let secondary_span = resolve_indefinite_grid_span(secondary_idx, secondary_span);
// If the primary index is out of bounds, then increment the secondary index and reset the primary
// index back to the start of the grid
let primary_out_of_bounds = primary_span.end > primary_axis_grid_end_line;
if primary_out_of_bounds {
// If the span is out of bounds even at the search start position then it can never fit,
// as searching only ever moves the span further away from the start of the grid. Bail out
// and let `record_grid_placement` clamp the placement into the limited grid
if primary_idx == primary_axis_grid_start_line {
return (primary_span, secondary_span);
}
secondary_idx = advance_position(secondary_idx);
primary_idx = primary_axis_grid_start_line;
continue;
}
// If the item spans every primary axis track, it fits if and only if all of the
// secondary axis tracks it spans are entirely unoccupied. Jump the secondary index
// past any non-empty tracks in the spanned stripe.
if spans_all_primary_tracks {
match cell_occupancy_matrix.occupied_track_jump(secondary_axis, secondary_span) {
Some(next_position) => {
secondary_idx = next_position;
primary_idx = primary_axis_grid_start_line;
continue;
}
None => return (primary_span, secondary_span),
}
}
// If area is occupied, jump the primary index past the collision and try again
let collision = cell_occupancy_matrix.line_area_collision_jump(primary_axis, primary_span, secondary_span);
if let Some(next_position) = collision {
primary_idx = next_position;
continue;
}
// Once we find a free space that's in bounds, return that position
return (primary_span, secondary_span);
}
}
}
/// Clamp a placement into the limited grid, preserving a span of at least 1 track.
/// Items placed outside of the limited grid are clamped into it.
///
/// See: <https://www.w3.org/TR/css-grid-1/#overlarge-grids>
fn clamp_span_to_limited_grid(span: Line<OriginZeroLine>) -> Line<OriginZeroLine> {
let start = span.start.0.clamp(MIN_OZ_LINE, MAX_OZ_LINE - 1);
let end = span.end.0.clamp(start + 1, MAX_OZ_LINE);
Line { start: OriginZeroLine(start), end: OriginZeroLine(end) }
}
/// Record the grid item's placement in both the CellOccupancyMatrix and the item itself
/// once a definite placement has been determined
fn record_grid_placement(
cell_occupancy_matrix: &mut CellOccupancyMatrix,
item: &mut GridItem,
primary_axis: AbsoluteAxis,
primary_span: Line<OriginZeroLine>,
secondary_span: Line<OriginZeroLine>,
placement_type: CellOccupancyState,
) {
#[cfg(test)]
println!("BEFORE placement:");
#[cfg(test)]
println!("{cell_occupancy_matrix:?}");
// Clamp placements into the limited grid to prevent arithmetic overflow when growing the
// implicit grid (https://www.w3.org/TR/css-grid-1/#overlarge-grids)
let primary_span = clamp_span_to_limited_grid(primary_span);
let secondary_span = clamp_span_to_limited_grid(secondary_span);
// Mark area of grid as occupied
cell_occupancy_matrix.mark_area_as(primary_axis, primary_span, secondary_span, placement_type);
// Record placement on the item
let (col_span, row_span) = match primary_axis {
AbsoluteAxis::Horizontal => (primary_span, secondary_span),
AbsoluteAxis::Vertical => (secondary_span, primary_span),
};
item.column = col_span;
item.row = row_span;
#[cfg(test)]
println!("AFTER placement:");
#[cfg(test)]
println!("{cell_occupancy_matrix:?}");
#[cfg(test)]
println!("\n");
}
#[cfg(test)]
mod tests {
use super::*;
mod test_placement_algorithm {
use crate::compute::grid::implicit_grid::compute_grid_size_estimate;
use crate::compute::grid::types::TrackCounts;
use crate::compute::grid::util::test_helpers::{grid_items, resolve_named_lines};
use crate::compute::grid::util::*;
use crate::compute::grid::CellOccupancyMatrix;
use crate::compute::grid::NamedLineResolver;
use crate::compute::grid::OriginZeroLine;
use crate::prelude::*;
use crate::style::GridAutoFlow;
use super::super::place_grid_items;
type ExpectedPlacement = (i16, i16, i16, i16);
fn placement_test_runner(
explicit_col_count: u16,
explicit_row_count: u16,
children: Vec<(usize, Style, ExpectedPlacement)>,
expected_col_counts: TrackCounts,
expected_row_counts: TrackCounts,
flow: GridAutoFlow,
) {
// Setup test
let mut name_resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
name_resolver.set_explicit_column_count(explicit_col_count);
name_resolver.set_explicit_row_count(explicit_row_count);
let mut items = grid_items(children.iter().map(|(index, style, _)| (*index, style)));
let placements = resolve_named_lines(
children.iter().map(|(_, style, _)| style),
&name_resolver,
explicit_col_count,
explicit_row_count,
);
let estimated_sizes = compute_grid_size_estimate(explicit_col_count, explicit_row_count, &placements);
let mut cell_occupancy_matrix =
CellOccupancyMatrix::with_track_counts(estimated_sizes.0, estimated_sizes.1);
// Run placement algorithm
place_grid_items(&mut cell_occupancy_matrix, &mut items, &placements, flow);
// Assert that each item has been placed in the right location (items are in the same order as children)
assert_eq!(items.len(), children.len());
for (idx, ((id, _style, expected_placement), item)) in children.iter().zip(items.iter()).enumerate() {
assert_eq!(item.node, NodeId::from(*id));
let actual_placement = (item.column.start, item.column.end, item.row.start, item.row.end);
assert_eq!(actual_placement, (*expected_placement).into_oz(), "Item {idx} (0-indexed)");
}
// Assert that the correct number of implicit rows have been generated
let actual_row_counts = *cell_occupancy_matrix.track_counts(crate::compute::grid::AbsoluteAxis::Vertical);
assert_eq!(actual_row_counts, expected_row_counts, "row track counts");
let actual_col_counts = *cell_occupancy_matrix.track_counts(crate::compute::grid::AbsoluteAxis::Horizontal);
assert_eq!(actual_col_counts, expected_col_counts, "column track counts");
}
#[test]
fn test_only_fixed_placement() {
let flow = GridAutoFlow::Row;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
vec![
// node, style (grid coords), expected_placement (oz coords)
(1, (line(1), auto(), line(1), auto()).into_grid_child(), (0, 1, 0, 1)),
(2, (line(-4), auto(), line(-3), auto()).into_grid_child(), (-1, 0, 0, 1)),
(3, (line(-3), auto(), line(-4), auto()).into_grid_child(), (0, 1, -1, 0)),
(4, (line(3), span(2), line(5), auto()).into_grid_child(), (2, 4, 4, 5)),
]
};
let expected_cols = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 2 };
let expected_rows = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 3 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_placement_spanning_origin() {
let flow = GridAutoFlow::Row;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
vec![
// node, style (grid coords), expected_placement (oz coords)
(1, (line(-1), line(-1), line(-1), line(-1)).into_grid_child(), (2, 3, 2, 3)),
(2, (line(-1), span(2), line(-1), span(2)).into_grid_child(), (2, 4, 2, 4)),
(3, (line(-4), line(-4), line(-4), line(-4)).into_grid_child(), (-1, 0, -1, 0)),
(4, (line(-4), span(2), line(-4), span(2)).into_grid_child(), (-1, 1, -1, 1)),
]
};
let expected_cols = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 2 };
let expected_rows = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 2 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_only_auto_placement_row_flow() {
let flow = GridAutoFlow::Row;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
let auto_child = (auto(), auto(), auto(), auto()).into_grid_child();
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(1, auto_child.clone(), (0, 1, 0, 1)),
(2, auto_child.clone(), (1, 2, 0, 1)),
(3, auto_child.clone(), (0, 1, 1, 2)),
(4, auto_child.clone(), (1, 2, 1, 2)),
(5, auto_child.clone(), (0, 1, 2, 3)),
(6, auto_child.clone(), (1, 2, 2, 3)),
(7, auto_child.clone(), (0, 1, 3, 4)),
(8, auto_child.clone(), (1, 2, 3, 4)),
]
};
let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 2 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_only_auto_placement_column_flow() {
let flow = GridAutoFlow::Column;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
let auto_child = (auto(), auto(), auto(), auto()).into_grid_child();
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(1, auto_child.clone(), (0, 1, 0, 1)),
(2, auto_child.clone(), (0, 1, 1, 2)),
(3, auto_child.clone(), (1, 2, 0, 1)),
(4, auto_child.clone(), (1, 2, 1, 2)),
(5, auto_child.clone(), (2, 3, 0, 1)),
(6, auto_child.clone(), (2, 3, 1, 2)),
(7, auto_child.clone(), (3, 4, 0, 1)),
(8, auto_child.clone(), (3, 4, 1, 2)),
]
};
let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 2 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_oversized_item() {
let flow = GridAutoFlow::Row;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(1, (span(5), auto(), auto(), auto()).into_grid_child(), (0, 5, 0, 1)),
]
};
let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 3 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_fixed_in_secondary_axis() {
let flow = GridAutoFlow::Row;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(1, (span(2), auto(), line(1), auto()).into_grid_child(), (0, 2, 0, 1)),
(2, (auto(), auto(), line(2), auto()).into_grid_child(), (0, 1, 1, 2)),
(3, (auto(), auto(), line(1), auto()).into_grid_child(), (2, 3, 0, 1)),
(4, (auto(), auto(), line(4), auto()).into_grid_child(), (0, 1, 3, 4)),
]
};
let expected_cols = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 1 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 2 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_definite_in_secondary_axis_with_fully_definite_negative() {
let flow = GridAutoFlow::Row;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(2, (auto(), auto(), line(2), auto()).into_grid_child(), (0, 1, 1, 2)),
(1, (line(-4), auto(), line(2), auto()).into_grid_child(), (-1, 0, 1, 2)),
(3, (auto(), auto(), line(1), auto()).into_grid_child(), (-1, 0, 0, 1)),
]
};
let expected_cols = TrackCounts { negative_implicit: 1, explicit: 2, positive_implicit: 0 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_dense_packing_algorithm() {
let flow = GridAutoFlow::RowDense;
let explicit_col_count = 4;
let explicit_row_count = 4;
let children = {
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(1, (line(2), auto(), line(1), auto()).into_grid_child(), (1, 2, 0, 1)), // Definitely positioned in column 2
(2, (span(2), auto(), auto(), auto()).into_grid_child(), (2, 4, 0, 1)), // Spans 2 columns, so positioned after item 1
(3, (auto(), auto(), auto(), auto()).into_grid_child(), (0, 1, 0, 1)), // Spans 1 column, so should be positioned before item 1
]
};
let expected_cols = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_sparse_packing_algorithm() {
let flow = GridAutoFlow::Row;
let explicit_col_count = 4;
let explicit_row_count = 4;
let children = {
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(1, (auto(), span(3), auto(), auto()).into_grid_child(), (0, 3, 0, 1)), // Width 3
(2, (auto(), span(3), auto(), auto()).into_grid_child(), (0, 3, 1, 2)), // Width 3 (wraps to next row)
(3, (auto(), span(1), auto(), auto()).into_grid_child(), (3, 4, 1, 2)), // Width 1 (uses second row as we're already on it)
]
};
let expected_cols = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 4, positive_implicit: 0 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_auto_placement_in_negative_tracks() {
let flow = GridAutoFlow::RowDense;
let explicit_col_count = 2;
let explicit_row_count = 2;
let children = {
vec![
// output order, node, style (grid coords), expected_placement (oz coords)
(1, (line(-5), auto(), line(1), auto()).into_grid_child(), (-2, -1, 0, 1)), // Row 1. Definitely positioned in column -2
(2, (auto(), auto(), line(2), auto()).into_grid_child(), (-2, -1, 1, 2)), // Row 2. Auto positioned in column -2
(3, (auto(), auto(), auto(), auto()).into_grid_child(), (-1, 0, 0, 1)), // Row 1. Auto positioned in column -1
]
};
let expected_cols = TrackCounts { negative_implicit: 2, explicit: 2, positive_implicit: 0 };
let expected_rows = TrackCounts { negative_implicit: 0, explicit: 2, positive_implicit: 0 };
placement_test_runner(explicit_col_count, explicit_row_count, children, expected_cols, expected_rows, flow);
}
#[test]
fn test_overlarge_placement_is_clamped() {
let explicit_col_count = 9_000;
let explicit_row_count = 0;
let style = (line(-19_005), auto(), auto(), auto()).into_grid_child();
let children = [(0usize, style)];
let mut name_resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
name_resolver.set_explicit_column_count(explicit_col_count);
name_resolver.set_explicit_row_count(explicit_row_count);
let mut items = grid_items(children.iter().map(|(index, style)| (*index, style)));
let placements = resolve_named_lines(
children.iter().map(|(_, style)| style),
&name_resolver,
explicit_col_count,
explicit_row_count,
);
let estimated_sizes = compute_grid_size_estimate(explicit_col_count, explicit_row_count, &placements);
let mut cell_occupancy_matrix =
CellOccupancyMatrix::with_track_counts(estimated_sizes.0, estimated_sizes.1);
place_grid_items(&mut cell_occupancy_matrix, &mut items, &placements, GridAutoFlow::Row);
assert_eq!(items[0].column, Line { start: OriginZeroLine(-10_000), end: OriginZeroLine(-9_999) });
}
}
#[test]
fn auto_placement_cursor_saturates_at_integer_bounds() {
assert_eq!(advance_position(OriginZeroLine(i16::MAX)), OriginZeroLine(i16::MAX));
}
#[test]
fn indefinite_spans_saturate_at_integer_bounds() {
assert_eq!(
resolve_indefinite_grid_span(OriginZeroLine(i16::MAX), 1),
Line { start: OriginZeroLine(i16::MAX), end: OriginZeroLine(i16::MAX) }
);
}
}
File diff suppressed because it is too large. Load diff
+608
View File
@@ -0,0 +1,608 @@
//! Contains CellOccupancyMatrix used to track occupied cells during grid placement
use super::TrackCounts;
use crate::compute::grid::OriginZeroLine;
use crate::geometry::AbsoluteAxis;
use crate::geometry::Line;
use crate::util::sys::{new_vec_with_capacity, Vec};
use core::cmp::{max, min};
use core::fmt::Debug;
use core::ops::Range;
use smallvec::SmallVec;
/// The occupancy state of a single grid cell
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub(crate) enum CellOccupancyState {
#[default]
/// Indicates that a grid cell is unoccupied
Unoccupied,
/// Indicates that a grid cell is occupied by a definitely placed item
DefinitelyPlaced,
/// Indicates that a grid cell is occupied by an item that was placed by the auto placement algorithm
AutoPlaced,
}
/// A run of occupied cells within a single track. The range is in OriginZero line coordinates
/// along the track (so for a row track, the range spans column lines and vice versa).
#[derive(Debug, Clone, PartialEq, Eq)]
struct OccupiedInterval {
/// The range of cells covered by this interval (start line..end line in OriginZero coordinates)
range: Range<i16>,
/// The occupancy state of every cell within this interval
state: CellOccupancyState,
}
impl OccupiedInterval {
/// Whether this interval overlaps the given range
fn overlaps(&self, range: &Range<i16>) -> bool {
self.range.start < range.end && self.range.end > range.start
}
}
/// The occupied cells of a single track, stored as a sorted list of disjoint intervals in
/// OriginZero line coordinates. Gaps between intervals are unoccupied. Touching intervals
/// with the same state are merged.
#[derive(Debug, Clone, Default)]
struct TrackIntervals {
/// The sorted, disjoint list of occupied intervals within the track
intervals: SmallVec<[OccupiedInterval; 2]>,
/// The furthest end line of an auto-placed item starting in this secondary-axis track
auto_placement_cursor: Option<OriginZeroLine>,
}
impl TrackIntervals {
/// Whether the track contains any occupied cells
fn is_empty(&self) -> bool {
self.intervals.is_empty()
}
/// The occupancy state of the cell whose start line is at `coordinate`
fn state_at(&self, coordinate: i16) -> CellOccupancyState {
self.intervals
.iter()
.find(|interval| interval.range.start <= coordinate && coordinate < interval.range.end)
.map(|interval| interval.state)
.unwrap_or(CellOccupancyState::Unoccupied)
}
/// Set the cells covered by `range` to `state`, overwriting the state of any already-occupied
/// cells within the range (matching the overwrite semantics of a dense matrix of cells)
fn paint(&mut self, range: Range<i16>, state: CellOccupancyState) {
if range.start >= range.end {
return;
}
// Fast path: the painted range lies entirely after all existing intervals
// (the common case, as placement queries and inserts mostly advance forwards)
match self.intervals.last_mut() {
None => {
self.intervals.push(OccupiedInterval { range, state });
return;
}
Some(last) if last.range.end <= range.start => {
if last.state == state && last.range.end == range.start {
last.range.end = range.end;
} else {
self.intervals.push(OccupiedInterval { range, state });
}
return;
}
_ => {}
}
let mut result: SmallVec<[OccupiedInterval; 2]> = SmallVec::new();
// Intervals (or partial intervals) entirely before the painted range
for interval in &self.intervals {
if interval.range.end <= range.start {
result.push(interval.clone());
} else if interval.range.start < range.start {
result.push(OccupiedInterval { range: interval.range.start..range.start, state: interval.state });
}
}
// The painted range, merged with the preceding interval if it touches and has the same state
match result.last_mut() {
Some(last) if last.state == state && last.range.end == range.start => last.range.end = range.end,
_ => result.push(OccupiedInterval { range: range.clone(), state }),
}
// Intervals (or partial intervals) entirely after the painted range
for interval in &self.intervals {
let trimmed = if interval.range.start >= range.end {
interval.clone()
} else if interval.range.end > range.end {
OccupiedInterval { range: range.end..interval.range.end, state: interval.state }
} else {
continue;
};
match result.last_mut() {
Some(last) if last.state == trimmed.state && last.range.end == trimmed.range.start => {
last.range.end = trimmed.range.end
}
_ => result.push(trimmed),
}
}
self.intervals = result;
}
/// Find the extent of the occupied interval which an auto-placement search along the track
/// would collide with last: the end of the last overlapping interval. Returns the extremal
/// occupied cell of that interval (which may lie outside `range`: every search position
/// before the returned extent also collides with the interval), or `None` if the range is
/// entirely unoccupied.
fn collision_extent(&self, range: &Range<i16>) -> Option<i16> {
let interval = self
.intervals
.iter()
.rev()
.take_while(|interval| interval.range.end > range.start)
.find(|interval| interval.overlaps(range))?;
Some(interval.range.end - 1)
}
}
/// A dynamically sized matrix (2d grid) which tracks the occupancy of each grid cell during auto-placement.
/// It also keeps tabs on how many tracks there are and which tracks are implicit and which are explicit.
///
/// Occupancy is stored sparsely as per-track interval lists (in both orientations), so memory usage
/// is proportional to the number of placed items rather than the total number of grid cells.
pub(crate) struct CellOccupancyMatrix {
/// The counts of implicit and explicit columns
columns: TrackCounts,
/// The counts of implicit and explicit rows
rows: TrackCounts,
/// For each row track: the occupied intervals within that row (in column coordinates)
row_intervals: Vec<TrackIntervals>,
/// For each column track: the occupied intervals within that column (in row coordinates)
column_intervals: Vec<TrackIntervals>,
}
/// Debug impl that represents the matrix in a compact 2d text format
impl Debug for CellOccupancyMatrix {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(
f,
"Rows: neg_implicit={} explicit={} pos_implicit={}",
self.rows.negative_implicit, self.rows.explicit, self.rows.positive_implicit
)?;
writeln!(
f,
"Cols: neg_implicit={} explicit={} pos_implicit={}",
self.columns.negative_implicit, self.columns.explicit, self.columns.positive_implicit
)?;
if self.rows.len() > 100 || self.columns.len() > 100 {
writeln!(f, "State: (not printed: more than 100 tracks)")?;
return Ok(());
}
writeln!(f, "State:")?;
for row in &self.row_intervals {
for column_index in 0..self.columns.len() {
let coordinate = self.columns.track_to_prev_oz_line(column_index as u16);
let letter = match row.state_at(coordinate.0) {
CellOccupancyState::Unoccupied => '_',
CellOccupancyState::DefinitelyPlaced => 'D',
CellOccupancyState::AutoPlaced => 'A',
};
write!(f, "{letter}")?;
}
writeln!(f)?;
}
Ok(())
}
}
impl CellOccupancyMatrix {
/// Create a CellOccupancyMatrix given a set of provisional track counts. The grid can expand as needed to fit more tracks,
/// the provisional track counts represent a best effort attempt to avoid the extra allocations this requires.
pub fn with_track_counts(columns: TrackCounts, rows: TrackCounts) -> Self {
let mut row_intervals = new_vec_with_capacity(rows.len());
row_intervals.resize(rows.len(), TrackIntervals::default());
let mut column_intervals = new_vec_with_capacity(columns.len());
column_intervals.resize(columns.len(), TrackIntervals::default());
Self { rows, columns, row_intervals, column_intervals }
}
/// The per-track interval lists for tracks in the specified axis. Each row track's intervals
/// are in column coordinates and vice versa.
fn track_lists(&self, track_axis: AbsoluteAxis) -> &[TrackIntervals] {
match track_axis {
AbsoluteAxis::Horizontal => &self.column_intervals,
AbsoluteAxis::Vertical => &self.row_intervals,
}
}
/// Expands the grid (potentially in all 4 directions) in order to ensure that the specified
/// spans (in OriginZero coordinates) fit within the tracked tracks
fn expand_to_fit_range(&mut self, row_span: Line<OriginZeroLine>, col_span: Line<OriginZeroLine>) {
// Calculate number of rows and columns missing to accommodate ranges (if any)
let req_negative_rows = max(-(self.rows.negative_implicit as i16) - row_span.start.0, 0);
let req_positive_rows = max(row_span.end.0 - self.rows.implicit_end_line().0, 0);
let req_negative_cols = max(-(self.columns.negative_implicit as i16) - col_span.start.0, 0);
let req_positive_cols = max(col_span.end.0 - self.columns.implicit_end_line().0, 0);
// Add empty tracks to the front and/or back of the per-track interval lists.
// Interval contents are stored in OriginZero coordinates, so they do not need to shift.
if req_negative_rows > 0 {
self.row_intervals
.splice(0..0, core::iter::repeat_with(TrackIntervals::default).take(req_negative_rows as usize));
}
if req_positive_rows > 0 {
let new_len = self.row_intervals.len() + req_positive_rows as usize;
self.row_intervals.resize(new_len, TrackIntervals::default());
}
if req_negative_cols > 0 {
self.column_intervals
.splice(0..0, core::iter::repeat_with(TrackIntervals::default).take(req_negative_cols as usize));
}
if req_positive_cols > 0 {
let new_len = self.column_intervals.len() + req_positive_cols as usize;
self.column_intervals.resize(new_len, TrackIntervals::default());
}
self.rows.negative_implicit += req_negative_rows as u16;
self.rows.positive_implicit += req_positive_rows as u16;
self.columns.negative_implicit += req_negative_cols as u16;
self.columns.positive_implicit += req_positive_cols as u16;
}
/// Mark an area of the matrix as occupied, expanding the allocated space as necessary to accommodate the passed area.
pub fn mark_area_as(
&mut self,
primary_axis: AbsoluteAxis,
primary_span: Line<OriginZeroLine>,
secondary_span: Line<OriginZeroLine>,
value: CellOccupancyState,
) {
let (row_span, column_span) = match primary_axis {
AbsoluteAxis::Horizontal => (secondary_span, primary_span),
AbsoluteAxis::Vertical => (primary_span, secondary_span),
};
self.expand_to_fit_range(row_span, column_span);
if value == CellOccupancyState::AutoPlaced
&& primary_span.start < primary_span.end
&& secondary_span.start < secondary_span.end
{
self.advance_auto_placement_cursor(primary_axis, secondary_span.start, primary_span.end);
}
let row_range = self.rows.oz_line_range_to_track_range(row_span);
let col_range = self.columns.oz_line_range_to_track_range(column_span);
for row_index in row_range {
self.row_intervals[row_index as usize].paint(column_span.start.0..column_span.end.0, value);
}
for column_index in col_range {
self.column_intervals[column_index as usize].paint(row_span.start.0..row_span.end.0, value);
}
}
/// Determines whether a grid area specified by the bounding grid lines in OriginZero coordinates
/// is entirely unnocupied. Returns true if all grid cells within the grid area are unnocupied, else false.
#[cfg(test)]
pub fn line_area_is_unoccupied(
&self,
primary_axis: AbsoluteAxis,
primary_span: Line<OriginZeroLine>,
secondary_span: Line<OriginZeroLine>,
) -> bool {
self.line_area_collision_jump(primary_axis, primary_span, secondary_span).is_none()
}
/// Checks the specified area for occupied cells (`primary_span` and `secondary_span` are
/// bounding grid lines in OriginZero coordinates). Returns `None` if the area is entirely
/// unoccupied. Otherwise returns the next search position (in OriginZero coordinates, along
/// `primary_axis`) that is not guaranteed to collide with the occupied cells found in the
/// area. This allows the auto-placement search cursor to jump past collisions rather than
/// advancing one track at a time.
pub fn line_area_collision_jump(
&self,
primary_axis: AbsoluteAxis,
primary_span: Line<OriginZeroLine>,
secondary_span: Line<OriginZeroLine>,
) -> Option<OriginZeroLine> {
let track_lists = self.track_lists(primary_axis.other_axis());
let secondary_counts = self.track_counts(primary_axis.other_axis());
let secondary_range = secondary_counts.oz_line_range_to_track_range(secondary_span);
// Out of bounds cells are considered unoccupied, so clamp the secondary range to the
// tracks which actually exist
let secondary_start = max(secondary_range.start, 0);
let secondary_end = min(secondary_range.end, track_lists.len() as i16);
let primary_range = primary_span.start.0..primary_span.end.0;
let mut extent: Option<i16> = None;
for secondary_index in secondary_start..secondary_end {
let Some(cell) = track_lists[secondary_index as usize].collision_extent(&primary_range) else {
continue;
};
extent = Some(match extent {
None => cell,
Some(best) => max(best, cell),
});
}
extent.map(|cell| OriginZeroLine(cell + 1))
}
/// Given a span of tracks in `axis` (in OriginZero coordinates), returns the next search
/// position past all non-empty tracks within the span, or `None` if all tracks within the
/// span are entirely unoccupied. Used to place items which span every track in the other
/// axis (such items can only fit in a stripe of entirely unoccupied tracks).
pub fn occupied_track_jump(&self, axis: AbsoluteAxis, span: Line<OriginZeroLine>) -> Option<OriginZeroLine> {
let counts = self.track_counts(axis);
let track_lists = self.track_lists(axis);
let range = counts.oz_line_range_to_track_range(span);
let start = max(range.start, 0);
let end = min(range.end, track_lists.len() as i16);
let found = (start..end).rev().find(|&index| !track_lists[index as usize].is_empty());
found.map(|track_index| {
let line = counts.track_to_prev_oz_line(track_index as u16);
line + 1
})
}
/// Determines whether the specified row contains any items
pub fn row_is_occupied(&self, row_index: usize) -> bool {
self.track_lists(AbsoluteAxis::Vertical).get(row_index).is_some_and(|track| !track.is_empty())
}
/// Determines whether the specified column contains any items
pub fn column_is_occupied(&self, column_index: usize) -> bool {
self.track_lists(AbsoluteAxis::Horizontal).get(column_index).is_some_and(|track| !track.is_empty())
}
/// Returns the track counts of this CellOccunpancyMatrix in the relevant axis
pub fn track_counts(&self, track_type: AbsoluteAxis) -> &TrackCounts {
match track_type {
AbsoluteAxis::Horizontal => &self.columns,
AbsoluteAxis::Vertical => &self.rows,
}
}
/// The sparse placement cursor for items starting in the given secondary-axis track.
pub fn auto_placement_cursor(&self, track_type: AbsoluteAxis, start_at: OriginZeroLine) -> Option<OriginZeroLine> {
let track_counts = self.track_counts(track_type.other_axis());
let track_computed_index = track_counts.oz_line_to_next_track(start_at);
let track_lists = self.track_lists(track_type.other_axis());
if track_computed_index < 0 || track_computed_index >= track_lists.len() as i16 {
// Index out of bounds: no tracks to search
return None;
}
track_lists[track_computed_index as usize].auto_placement_cursor
}
/// Advances the sparse placement cursor to at least `primary_end`.
/// The secondary-axis track must already exist in the matrix.
fn advance_auto_placement_cursor(
&mut self,
primary_axis: AbsoluteAxis,
secondary_start: OriginZeroLine,
primary_end: OriginZeroLine,
) {
let track_index = self.track_counts(primary_axis.other_axis()).oz_line_to_next_track(secondary_start) as usize;
let tracks = match primary_axis {
AbsoluteAxis::Horizontal => &mut self.row_intervals,
AbsoluteAxis::Vertical => &mut self.column_intervals,
};
let cursor = &mut tracks[track_index].auto_placement_cursor;
*cursor = max(*cursor, Some(primary_end));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn interval(range: Range<i16>, state: CellOccupancyState) -> OccupiedInterval {
OccupiedInterval { range, state }
}
mod track_intervals {
use super::*;
use CellOccupancyState::{AutoPlaced, DefinitelyPlaced};
#[test]
fn paint_merges_touching_same_state_intervals() {
let mut track = TrackIntervals::default();
track.paint(0..2, AutoPlaced);
track.paint(4..6, AutoPlaced);
track.paint(2..4, AutoPlaced);
assert_eq!(track.intervals.as_slice(), &[interval(0..6, AutoPlaced)]);
}
#[test]
fn paint_does_not_merge_different_states() {
let mut track = TrackIntervals::default();
track.paint(0..2, AutoPlaced);
track.paint(2..4, DefinitelyPlaced);
assert_eq!(track.intervals.as_slice(), &[interval(0..2, AutoPlaced), interval(2..4, DefinitelyPlaced)]);
}
#[test]
fn paint_overwrites_overlapped_cells() {
let mut track = TrackIntervals::default();
track.paint(0..6, AutoPlaced);
track.paint(2..4, DefinitelyPlaced);
assert_eq!(
track.intervals.as_slice(),
&[interval(0..2, AutoPlaced), interval(2..4, DefinitelyPlaced), interval(4..6, AutoPlaced)]
);
// Painting over everything replaces all intervals
track.paint(-1..7, AutoPlaced);
assert_eq!(track.intervals.as_slice(), &[interval(-1..7, AutoPlaced)]);
}
#[test]
fn paint_overwrites_multiple_intervals() {
let mut track = TrackIntervals::default();
track.paint(0..2, AutoPlaced);
track.paint(3..5, DefinitelyPlaced);
track.paint(6..8, AutoPlaced);
track.paint(1..7, DefinitelyPlaced);
assert_eq!(
track.intervals.as_slice(),
&[interval(0..1, AutoPlaced), interval(1..7, DefinitelyPlaced), interval(7..8, AutoPlaced)]
);
}
#[test]
fn collision_extent_finds_extremal_occupied_cell() {
let mut track = TrackIntervals::default();
track.paint(2..4, AutoPlaced);
track.paint(6..8, DefinitelyPlaced);
// The last cell of the last overlapping interval
assert_eq!(track.collision_extent(&(0..10)), Some(7));
assert_eq!(track.collision_extent(&(0..7)), Some(7));
assert_eq!(track.collision_extent(&(0..6)), Some(3));
assert_eq!(track.collision_extent(&(4..6)), None);
}
#[test]
fn state_at_distinguishes_occupied_intervals_and_gaps() {
let mut track = TrackIntervals::default();
track.paint(0..2, DefinitelyPlaced);
track.paint(2..4, AutoPlaced);
track.paint(6..8, AutoPlaced);
track.paint(8..9, DefinitelyPlaced);
assert_eq!(track.state_at(0), DefinitelyPlaced);
assert_eq!(track.state_at(3), AutoPlaced);
assert_eq!(track.state_at(5), CellOccupancyState::Unoccupied);
assert_eq!(track.state_at(7), AutoPlaced);
assert_eq!(track.state_at(8), DefinitelyPlaced);
}
#[test]
fn definitely_placed_overwrite_hides_auto_placed_cells() {
let mut track = TrackIntervals::default();
track.paint(0..4, CellOccupancyState::AutoPlaced);
track.paint(2..4, CellOccupancyState::DefinitelyPlaced);
assert_eq!(track.state_at(1), CellOccupancyState::AutoPlaced);
assert_eq!(track.state_at(2), CellOccupancyState::DefinitelyPlaced);
assert_eq!(track.state_at(3), CellOccupancyState::DefinitelyPlaced);
}
}
mod cell_occupancy_matrix {
use super::*;
use crate::geometry::AbsoluteAxis::{Horizontal, Vertical};
use CellOccupancyState::AutoPlaced;
fn line(start: i16, end: i16) -> Line<OriginZeroLine> {
Line { start: OriginZeroLine(start), end: OriginZeroLine(end) }
}
#[test]
fn negative_expansion_preserves_occupancy() {
let mut matrix =
CellOccupancyMatrix::with_track_counts(TrackCounts::from_raw(0, 2, 0), TrackCounts::from_raw(0, 2, 0));
matrix.mark_area_as(Horizontal, line(0, 1), line(0, 1), AutoPlaced);
// Expand by marking an area in negative tracks
matrix.mark_area_as(Horizontal, line(-2, -1), line(-1, 0), AutoPlaced);
assert_eq!(*matrix.track_counts(Horizontal), TrackCounts::from_raw(2, 2, 0));
assert_eq!(*matrix.track_counts(Vertical), TrackCounts::from_raw(1, 2, 0));
// Original cell still occupied at the same OriginZero coordinates
assert!(!matrix.line_area_is_unoccupied(Horizontal, line(0, 1), line(0, 1)));
assert!(!matrix.line_area_is_unoccupied(Horizontal, line(-2, -1), line(-1, 0)));
assert!(matrix.line_area_is_unoccupied(Horizontal, line(-1, 0), line(0, 1)));
// Matrix-index based queries account for the shifted origin
assert!(matrix.column_is_occupied(0)); // OriginZero column -2
assert!(!matrix.column_is_occupied(1)); // OriginZero column -1
assert!(matrix.column_is_occupied(2)); // OriginZero column 0
assert!(matrix.row_is_occupied(0)); // OriginZero row -1
assert!(matrix.row_is_occupied(1)); // OriginZero row 0
assert!(!matrix.row_is_occupied(2)); // OriginZero row 1
}
#[test]
fn auto_placed_item_only_advances_cursor_in_first_secondary_track() {
for axis in [Horizontal, Vertical] {
let mut matrix = CellOccupancyMatrix::with_track_counts(
TrackCounts::from_raw(0, 4, 0),
TrackCounts::from_raw(0, 4, 0),
);
matrix.mark_area_as(axis, line(1, 3), line(1, 4), AutoPlaced);
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(1)), Some(OriginZeroLine(3)));
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(2)), None);
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(3)), None);
assert!(!matrix.line_area_is_unoccupied(axis, line(1, 3), line(2, 4)));
}
}
#[test]
fn cursors_survive_interval_merging_and_grid_expansion() {
for axis in [Horizontal, Vertical] {
let mut matrix = CellOccupancyMatrix::with_track_counts(
TrackCounts::from_raw(0, 4, 0),
TrackCounts::from_raw(0, 4, 0),
);
matrix.mark_area_as(axis, line(2, 4), line(1, 2), AutoPlaced);
matrix.mark_area_as(axis, line(4, 8), line(0, 2), AutoPlaced);
matrix.mark_area_as(axis, line(8, 10), line(1, 2), CellOccupancyState::DefinitelyPlaced);
matrix.mark_area_as(axis, line(-3, -1), line(-2, -1), AutoPlaced);
matrix.mark_area_as(axis, line(12, 14), line(7, 8), AutoPlaced);
matrix.mark_area_as(axis, line(0, 1), line(1, 2), AutoPlaced);
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(1)), Some(OriginZeroLine(4)));
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(0)), Some(OriginZeroLine(8)));
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(-2)), Some(OriginZeroLine(-1)));
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(7)), Some(OriginZeroLine(14)));
for track in [-3, -1, 2, 8] {
assert_eq!(matrix.auto_placement_cursor(axis, OriginZeroLine(track)), None);
}
}
}
#[test]
fn alternating_spans_merge_occupancy_and_skip_the_occupied_prefix() {
for axis in [Horizontal, Vertical] {
let mut matrix = CellOccupancyMatrix::with_track_counts(
TrackCounts::from_raw(0, 0, 0),
TrackCounts::from_raw(0, 0, 0),
);
for i in 0..128 {
matrix.mark_area_as(axis, line(i, i + 1), line(i % 2, 2), AutoPlaced);
}
let track = &matrix.track_lists(axis.other_axis())[1];
assert_eq!(track.intervals.as_slice(), &[interval(0..128, AutoPlaced)]);
assert!(!track.intervals.spilled());
assert_eq!(matrix.line_area_collision_jump(axis, line(0, 1), line(1, 2)), Some(OriginZeroLine(128)));
}
}
#[test]
fn collision_jump_returns_next_search_position() {
let mut matrix =
CellOccupancyMatrix::with_track_counts(TrackCounts::from_raw(0, 4, 0), TrackCounts::from_raw(0, 4, 0));
matrix.mark_area_as(Horizontal, line(1, 3), line(0, 1), AutoPlaced);
// Jump past the end of the last colliding interval
assert_eq!(matrix.line_area_collision_jump(Horizontal, line(0, 2), line(0, 1)), Some(OriginZeroLine(3)));
assert_eq!(matrix.line_area_collision_jump(Horizontal, line(0, 4), line(0, 1)), Some(OriginZeroLine(3)));
// No collision in a different row
assert_eq!(matrix.line_area_collision_jump(Horizontal, line(0, 4), line(1, 2)), None);
}
#[test]
fn occupied_track_jump_skips_non_empty_tracks() {
let mut matrix =
CellOccupancyMatrix::with_track_counts(TrackCounts::from_raw(0, 4, 0), TrackCounts::from_raw(0, 4, 0));
matrix.mark_area_as(Horizontal, line(0, 1), line(1, 2), AutoPlaced);
// Vertical (row) tracks: row 1 is occupied
assert_eq!(matrix.occupied_track_jump(Vertical, line(0, 4)), Some(OriginZeroLine(2)));
assert_eq!(matrix.occupied_track_jump(Vertical, line(2, 4)), None);
}
}
}
+184
View File
@@ -0,0 +1,184 @@
//! Taffy uses two coordinate systems to refer to grid lines (the gaps/gutters between rows/columns):
use super::super::types::TrackCounts;
use crate::geometry::Line;
use core::cmp::{max, Ordering};
use core::ops::{Add, AddAssign, Sub};
/// The maximum number of tracks in each direction from the start of the explicit grid (line 0 in
/// OriginZero coordinates), and the maximum span of a single grid item. This limits the grid to
/// `2 * MAX_GRID_TRACKS` total tracks in each axis (including explicit tracks, which count against
/// the positive limit). Grids larger than this limit are clamped.
///
/// See: <https://www.w3.org/TR/css-grid-1/#overlarge-grids>
pub(crate) const MAX_GRID_TRACKS: u16 = 10_000;
/// The lowest valid grid line in OriginZero coordinates
pub(crate) const MIN_OZ_LINE: i16 = -(MAX_GRID_TRACKS as i16);
/// The highest valid grid line in OriginZero coordinates
pub(crate) const MAX_OZ_LINE: i16 = MAX_GRID_TRACKS as i16;
/// Represents a grid line position in "CSS Grid Line" coordinates
///
/// "CSS Grid Line" coordinates are those used in grid-row/grid-column in the CSS grid spec:
/// - The line at left hand (or top) edge of the explicit grid is line 1
/// (and counts up from there)
/// - The line at the right hand (or bottom) edge of the explicit grid is -1
/// (and counts down from there)
/// - 0 is not a valid index
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(transparent)]
pub struct GridLine(i16);
impl From<i16> for GridLine {
fn from(value: i16) -> Self {
Self(value)
}
}
impl GridLine {
/// Returns the underlying i16
pub fn as_i16(self) -> i16 {
self.0
}
/// Convert into OriginZero coordinates using the specified explicit track count.
///
/// The result is clamped into the limited grid `[-MAX_GRID_TRACKS, MAX_GRID_TRACKS]`
pub(crate) fn into_origin_zero_line(self, explicit_track_count: u16) -> OriginZeroLine {
let explicit_line_count = explicit_track_count as i32 + 1;
let oz_line = match self.0.cmp(&0) {
Ordering::Greater => self.0 as i32 - 1,
Ordering::Less => self.0 as i32 + explicit_line_count,
Ordering::Equal => panic!("Grid line of zero is invalid"),
};
OriginZeroLine::clamped(oz_line)
}
}
/// Represents a grid line position in "OriginZero" coordinates
///
/// "OriginZero" coordinates are a normalized form:
/// - The line at left hand (or top) edge of the explicit grid is line 0
/// - The next line to the right (or down) is 1, and so on
/// - The next line to the left (or up) is -1, and so on
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct OriginZeroLine(pub i16);
// Add and Sub with Self
impl Add<OriginZeroLine> for OriginZeroLine {
type Output = Self;
fn add(self, rhs: OriginZeroLine) -> Self::Output {
OriginZeroLine(self.0 + rhs.0)
}
}
impl Sub<OriginZeroLine> for OriginZeroLine {
type Output = Self;
fn sub(self, rhs: OriginZeroLine) -> Self::Output {
OriginZeroLine(self.0 - rhs.0)
}
}
// Add and Sub with u16
impl Add<u16> for OriginZeroLine {
type Output = Self;
fn add(self, rhs: u16) -> Self::Output {
OriginZeroLine(self.0 + rhs as i16)
}
}
impl AddAssign<u16> for OriginZeroLine {
fn add_assign(&mut self, rhs: u16) {
self.0 += rhs as i16;
}
}
impl Sub<u16> for OriginZeroLine {
type Output = Self;
fn sub(self, rhs: u16) -> Self::Output {
OriginZeroLine(self.0 - rhs as i16)
}
}
impl OriginZeroLine {
/// Create an `OriginZeroLine`, clamping the line into the limited grid `[-MAX_GRID_TRACKS, MAX_GRID_TRACKS]`
pub(crate) fn clamped(line: i32) -> Self {
OriginZeroLine(line.clamp(MIN_OZ_LINE as i32, MAX_OZ_LINE as i32) as i16)
}
/// Convert into "CSS Grid Line" coordinates using the specified explicit track count.
///
/// The inverse of [`GridLine::into_origin_zero_line`]
pub(crate) fn into_grid_line(self, explicit_track_count: u16) -> GridLine {
let explicit_line_count = explicit_track_count + 1;
if self.0 >= 0 {
GridLine(self.0 + 1)
} else {
GridLine(self.0 - explicit_line_count as i16)
}
}
/// Converts a grid line in OriginZero coordinates into the index of that same grid line in the GridTrackVec.
pub(crate) fn into_track_vec_index(self, track_counts: TrackCounts) -> usize {
self.try_into_track_vec_index(track_counts).unwrap_or_else(|| {
if self.0 > 0 {
panic!("OriginZero grid line cannot be more than the number of positive grid lines");
} else {
panic!("OriginZero grid line cannot be less than the number of negative grid lines");
}
})
}
/// Converts a grid line in OriginZero coordinates into the index of that same grid line in the GridTrackVec.
///
/// This fallible version is used for the placement of absolutely positioned grid items:
///
/// If a grid-placement property refers to a non-existent line either by explicitly specifying such a line or by
/// spanning outside of the existing implicit grid, it is instead treated as specifying auto (instead of creating
/// new implicit grid lines).
///
/// The infallible version above if used when placing regular in-flow grid items.
pub(crate) fn try_into_track_vec_index(self, track_counts: TrackCounts) -> Option<usize> {
// OriginZero grid line cannot be less than the number of negative grid lines
if self.0 < -(track_counts.negative_implicit as i16) {
return None;
};
// OriginZero grid line cannot be more than the number of positive grid lines
if self.0 > (track_counts.explicit + track_counts.positive_implicit) as i16 {
return None;
};
Some(2 * ((self.0 + track_counts.negative_implicit as i16) as usize))
}
/// The minimum number of negative implicit track there must be if a grid item starts at this line.
pub(crate) fn implied_negative_implicit_tracks(self) -> u16 {
if self.0 < 0 {
self.0.unsigned_abs()
} else {
0
}
}
/// The minimum number of positive implicit track there must be if a grid item end at this line.
pub(crate) fn implied_positive_implicit_tracks(self, explicit_track_count: u16) -> u16 {
if self.0 > explicit_track_count as i16 {
self.0 as u16 - explicit_track_count
} else {
0
}
}
}
impl Line<OriginZeroLine> {
/// The number of tracks between the start and end lines
#[inline(always)]
pub(crate) fn span(self) -> u16 {
max(self.end.0 - self.start.0, 0) as u16
}
}
/// A trait for the different coordinates used to define grid lines.
pub trait GridCoordinate: Copy {}
impl GridCoordinate for GridLine {}
impl GridCoordinate for OriginZeroLine {}
+817
View File
@@ -0,0 +1,817 @@
//! Contains GridItem used to represent a single grid item during layout
use super::GridTrack;
use crate::compute::common::sizing_keyword::{resolve_sizing_keyword, SizingKeywordResolution};
use crate::compute::grid::OriginZeroLine;
use crate::geometry::AbstractAxis;
use crate::geometry::{Line, Point, Rect, Size};
use crate::style::{AlignItems, AlignSelf, AvailableSpace, Dimension, LengthPercentageAuto, Overflow};
use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, NodeId, OofCandidates, SizingMode};
use crate::util::sys::f32_max;
use crate::util::{MaybeMath, MaybeResolve, ResolveOrZero};
use crate::{AlignItemsKeyword, BoxSizing, GridItemStyle, LengthPercentage};
use core::ops::Range;
/// The known_dimensions computed for a grid item for a given grid area size
#[derive(Debug, Clone, Copy)]
pub(in super::super) struct KnownDimensionsCacheEntry {
/// The grid area size that `known_dimensions` was computed for
grid_area_size: Size<Option<f32>>,
/// The cached known_dimensions
known_dimensions: Size<Option<f32>>,
}
/// Represents a single grid item
#[derive(Debug)]
pub(in super::super) struct GridItem {
/// The id of the node that this item represents
pub node: NodeId,
/// The index of the item in the children array
pub source_order: u16,
/// The item's definite row-start and row-end, as resolved by the placement algorithm
/// (in origin-zero coordinates). Set by the placement algorithm.
pub row: Line<OriginZeroLine>,
/// The items definite column-start and column-end, as resolved by the placement algorithm
/// (in origin-zero coordinates). Set by the placement algorithm.
pub column: Line<OriginZeroLine>,
/// Is it a compressible replaced element?
/// https://drafts.csswg.org/css-sizing-3/#min-content-zero
pub is_compressible_replaced: bool,
/// Whether the item is a replaced element. Such items are not stretched by `normal` alignment.
pub is_replaced: bool,
/// The item's overflow style
pub overflow: Point<Overflow>,
/// The item's box_sizing style
pub box_sizing: BoxSizing,
/// The item's size style
pub size: Size<Dimension>,
/// The item's min_size style
pub min_size: Size<LengthPercentageAuto>,
/// The item's max_size style
pub max_size: Size<LengthPercentageAuto>,
/// The item's aspect_ratio style
pub aspect_ratio: Option<f32>,
/// The item's padding style
pub padding: Rect<LengthPercentage>,
/// The item's border style
pub border: Rect<LengthPercentage>,
/// The item's margin style
pub margin: Rect<LengthPercentageAuto>,
/// The item's align_self property, or the parent's align_items property if it is `None`
pub align_self: AlignSelf,
/// The item's justify_self property, or the parent's justify_items property if it is `None`
pub justify_self: AlignSelf,
/// The items first baseline (horizontal)
pub baseline: Option<f32>,
/// Shim for baseline alignment that acts like an extra top margin
/// TODO: Support last baseline and vertical text baselines
pub baseline_shim: f32,
/// The item's definite row-start and row-end (same as `row` field, except in a different coordinate system)
/// (as indexes into the Vec<GridTrack> stored in a grid's AbstractAxisTracks)
pub row_indexes: Line<u16>,
/// The items definite column-start and column-end (same as `column` field, except in a different coordinate system)
/// (as indexes into the Vec<GridTrack> stored in a grid's AbstractAxisTracks)
pub column_indexes: Line<u16>,
/// Whether the item crosses a flexible row
pub crosses_flexible_row: bool,
/// Whether the item crosses a flexible column
pub crosses_flexible_column: bool,
/// Whether the item crosses a intrinsic row
pub crosses_intrinsic_row: bool,
/// Whether the item crosses a intrinsic column
pub crosses_intrinsic_column: bool,
// Caches for intrinsic size computation. These caches are only valid for a single run of the track-sizing algorithm.
/// Cache for the known_dimensions input to intrinsic sizing computation
pub grid_area_size_cache: Option<Size<Option<f32>>>,
/// Cache for the known_dimensions passed to the child when computing its intrinsic contributions, stored along with
/// the grid area size it was computed for. Must be cleared whenever `baseline_shim` changes.
pub known_dimensions_cache: Option<KnownDimensionsCacheEntry>,
/// Cache for the min-content size
pub min_content_contribution_cache: Size<Option<f32>>,
/// Cache for the minimum contribution
pub minimum_contribution_cache: Size<Option<f32>>,
/// Cache for the max-content size
pub max_content_contribution_cache: Size<Option<f32>>,
/// Final y position. Used to compute baseline alignment for the container.
pub y_position: f32,
/// Final height. Used to compute baseline alignment for the container.
pub height: f32,
/// Out-of-flow candidates bubbled out of this item's subtree (anchors relative to the
/// container's border box)
pub oof_candidates: OofCandidates,
}
impl GridItem {
/// Create a new item from its style. Its placement (`row`/`column`) is filled in by the placement algorithm.
pub fn new_with_style_and_order<S: GridItemStyle>(
node: NodeId,
style: S,
parent_align_items: AlignItems,
parent_justify_items: AlignItems,
source_order: u16,
) -> Self {
const UNPLACED: Line<OriginZeroLine> = Line { start: OriginZeroLine(0), end: OriginZeroLine(0) };
GridItem {
node,
source_order,
row: UNPLACED,
column: UNPLACED,
is_compressible_replaced: style.is_compressible_replaced(),
is_replaced: style.is_replaced(),
overflow: style.overflow(),
box_sizing: style.box_sizing(),
size: style.size(),
min_size: style.min_size(),
max_size: style.max_size(),
aspect_ratio: style.aspect_ratio(),
padding: style.padding(),
border: style.border(),
margin: style.margin(),
align_self: style.align_self().unwrap_or(parent_align_items),
justify_self: style.justify_self().unwrap_or(parent_justify_items),
baseline: None,
baseline_shim: 0.0,
row_indexes: Line { start: 0, end: 0 }, // Properly initialised later
column_indexes: Line { start: 0, end: 0 }, // Properly initialised later
crosses_flexible_row: false, // Properly initialised later
crosses_flexible_column: false, // Properly initialised later
crosses_intrinsic_row: false, // Properly initialised later
crosses_intrinsic_column: false, // Properly initialised later
grid_area_size_cache: None,
min_content_contribution_cache: Size::NONE,
max_content_contribution_cache: Size::NONE,
known_dimensions_cache: None,
minimum_contribution_cache: Size::NONE,
y_position: 0.0,
height: 0.0,
oof_candidates: OofCandidates::NONE,
}
}
/// Whether the item has an auto margin in the block axis
#[inline(always)]
pub fn has_auto_block_margin(&self) -> bool {
self.margin.top.is_auto() || self.margin.bottom.is_auto()
}
/// Whether the item's block size depends on the size of its row(s), creating a cyclic
/// dependency with baseline alignment (which affects row sizing). Per
/// <https://www.w3.org/TR/css-grid-1/#row-align> such items do not participate in baseline
/// alignment and are aligned using their fallback alignment instead.
#[inline(always)]
pub fn has_cyclic_block_size_dependency(&self) -> bool {
self.size.height.0.uses_percentage() && (self.crosses_intrinsic_row || self.crosses_flexible_row)
}
/// Returns true if the item participates in baseline alignment: it has `align-self: baseline`
/// and neither of its block-axis margins are `auto`.
/// See <https://www.w3.org/TR/css-align-3/#baseline-align-self>
#[inline(always)]
pub fn participates_in_baseline_alignment(&self) -> bool {
self.align_self.keyword == AlignItemsKeyword::Baseline
&& !self.has_auto_block_margin()
&& !self.has_cyclic_block_size_dependency()
}
/// This item's placement in the specified axis in OriginZero coordinates
pub fn placement(&self, axis: AbstractAxis) -> Line<OriginZeroLine> {
match axis {
AbstractAxis::Block => self.row,
AbstractAxis::Inline => self.column,
}
}
/// This item's placement in the specified axis as GridTrackVec indices
pub fn placement_indexes(&self, axis: AbstractAxis) -> Line<u16> {
match axis {
AbstractAxis::Block => self.row_indexes,
AbstractAxis::Inline => self.column_indexes,
}
}
/// Returns a range which can be used as an index into the GridTrackVec in the specified axis
/// which will produce a sub-slice of covering all the tracks and lines that this item spans
/// excluding the lines that bound it.
pub fn track_range_excluding_lines(&self, axis: AbstractAxis) -> Range<usize> {
let indexes = self.placement_indexes(axis);
(indexes.start as usize + 1)..(indexes.end as usize)
}
/// Whether any track spanned by this item in the specified axis satisfies `predicate`
pub fn spans_track_matching(
&self,
axis: AbstractAxis,
axis_tracks: &[GridTrack],
predicate: impl Fn(&GridTrack) -> bool,
) -> bool {
axis_tracks[self.track_range_excluding_lines(axis)].iter().any(predicate)
}
/// Returns the number of tracks that this item spans in the specified axis
pub fn span(&self, axis: AbstractAxis) -> u16 {
match axis {
AbstractAxis::Block => self.row.span(),
AbstractAxis::Inline => self.column.span(),
}
}
/// Returns the pre-computed value indicating whether the grid item crosses a flexible track in
/// the specified axis
pub fn crosses_flexible_track(&self, axis: AbstractAxis) -> bool {
match axis {
AbstractAxis::Inline => self.crosses_flexible_column,
AbstractAxis::Block => self.crosses_flexible_row,
}
}
/// Returns the pre-computed value indicating whether the grid item crosses an intrinsic track in
/// the specified axis
pub fn crosses_intrinsic_track(&self, axis: AbstractAxis) -> bool {
match axis {
AbstractAxis::Inline => self.crosses_intrinsic_column,
AbstractAxis::Block => self.crosses_intrinsic_row,
}
}
/// For an item spanning multiple tracks, the upper limit used to calculate its limited min-/max-content contribution is the
/// sum of the fixed max track sizing functions of any tracks it spans, and is applied if it only spans such tracks.
pub fn spanned_track_limit(
&mut self,
axis: AbstractAxis,
axis_tracks: &[GridTrack],
axis_parent_size: Option<f32>,
resolve_calc_value: &dyn Fn(*const (), f32) -> f32,
) -> Option<f32> {
let spanned_tracks = &axis_tracks[self.track_range_excluding_lines(axis)];
let tracks_all_fixed = spanned_tracks.iter().all(|track| {
track.max_track_sizing_function.definite_limit(axis_parent_size, resolve_calc_value).is_some()
});
if tracks_all_fixed {
let limit: f32 = spanned_tracks
.iter()
.map(|track| {
track.max_track_sizing_function.definite_limit(axis_parent_size, resolve_calc_value).unwrap()
})
.sum();
Some(limit)
} else {
None
}
}
/// Similar to the spanned_track_limit, but excludes FitContent arguments from the limit.
/// Used to clamp the automatic minimum contributions of an item
pub fn spanned_fixed_track_limit(
&mut self,
axis: AbstractAxis,
axis_tracks: &[GridTrack],
axis_parent_size: Option<f32>,
resolve_calc_value: &dyn Fn(*const (), f32) -> f32,
) -> Option<f32> {
let spanned_tracks = &axis_tracks[self.track_range_excluding_lines(axis)];
let tracks_all_fixed = spanned_tracks.iter().all(|track| {
track.max_track_sizing_function.definite_value(axis_parent_size, resolve_calc_value).is_some()
});
if tracks_all_fixed {
let limit: f32 = spanned_tracks
.iter()
.map(|track| {
track.max_track_sizing_function.definite_value(axis_parent_size, resolve_calc_value).unwrap()
})
.sum();
Some(limit)
} else {
None
}
}
/// Retrieve the known_dimensions for the given grid area size from the cache or compute them.
/// The min-content and max-content contributions of an item are both computed from the same known_dimensions.
#[inline(always)]
fn known_dimensions_cached(
&mut self,
tree: &mut impl LayoutPartialTree,
grid_area_size: Size<Option<f32>>,
) -> Size<Option<f32>> {
if let Some(entry) = self.known_dimensions_cache {
if entry.grid_area_size == grid_area_size {
return entry.known_dimensions;
}
}
let known_dimensions = self.known_dimensions(tree, grid_area_size);
self.known_dimensions_cache = Some(KnownDimensionsCacheEntry { grid_area_size, known_dimensions });
known_dimensions
}
/// Whether the given self-alignment stretches the item: `stretch`, or `normal` unless the item is replaced
#[inline(always)]
fn is_stretch_aligned(&self, alignment: AlignSelf) -> bool {
match alignment.keyword {
AlignItemsKeyword::Stretch => true,
AlignItemsKeyword::Normal => !self.is_replaced,
_ => false,
}
}
/// Compute the known_dimensions to be passed to the child sizing functions
/// The key thing that is being done here is applying stretch alignment, which is necessary to
/// allow percentage sizes further down the tree to resolve properly in some cases
fn known_dimensions(
&self,
tree: &mut impl LayoutPartialTree,
grid_area_size: Size<Option<f32>>,
) -> Size<Option<f32>> {
let margins = self.margins_axis_sums_with_baseline_shims(grid_area_size.width, tree);
let aspect_ratio = self.aspect_ratio;
// CSS resolves percentage padding and border against the inline size of the containing
// block. For a grid item under intrinsic measurement, that inline-size basis is the grid
// area's width when it is definite.
// Spec:
// https://www.w3.org/TR/css-grid-1/#item-margins
// https://www.w3.org/TR/CSS22/box.html#padding-properties
let padding = self.padding.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
let border = self.border.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
let padding_border_size = (padding + border).sum_axes();
let box_sizing_adjustment =
if self.box_sizing == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
let inherent_size = self
.size
.maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let min_size = self
.min_size
.maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment)
// The size of the item is floored by its padding and border
.or(padding_border_size.map(Some))
.maybe_max(padding_border_size);
let max_size = self
.max_size
.maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let grid_area_minus_item_margins_size = grid_area_size.maybe_sub(margins).maybe_max(Size::ZERO);
// If node is absolutely positioned and width is not set explicitly, then deduce it
// from left, right and container_content_box if both are set.
let width = inherent_size.width.or_else(|| {
// A width that is a sizing keyword is not auto, so it does not stretch. The stretch
// keyword resolves to an exact width; the others resolve during content measurement.
if self.size.width.is_sizing_keyword() {
return match resolve_sizing_keyword(
self.size.width,
grid_area_minus_item_margins_size.width,
grid_area_size.width,
|val, basis| tree.calc(val, basis),
) {
Some(SizingKeywordResolution::Exact(width)) => Some(width),
_ => None,
};
}
// Apply width based on stretch alignment if:
// - Alignment style is "stretch" or "normal". Note that "normal" is treated as "stretch"
// here regardless of whether the item has a preferred size or aspect ratio in this axis,
// which differs from the rule used when the item is finally aligned (see `align_and_position_item`).
// Replaced elements are not stretched by "normal".
// - The node is not absolutely positioned
// - The node does not have auto margins in this axis.
if !self.margin.left.is_auto() && !self.margin.right.is_auto() && self.is_stretch_aligned(self.justify_self)
{
return grid_area_minus_item_margins_size.width;
}
None
});
// Reapply aspect ratio after stretch and absolute position width adjustments
let Size { width, height } =
Size { width, height: inherent_size.height }.maybe_apply_aspect_ratio(aspect_ratio);
let height = height.or_else(|| {
// A height that is a sizing keyword is not auto, so it does not stretch. The stretch
// keyword resolves to an exact height; the others resolve during content measurement.
if self.size.height.is_sizing_keyword() {
return match resolve_sizing_keyword(
self.size.height,
grid_area_minus_item_margins_size.height,
grid_area_size.height,
|val, basis| tree.calc(val, basis),
) {
Some(SizingKeywordResolution::Exact(height)) => Some(height),
_ => None,
};
}
// Apply height based on stretch alignment if:
// - Alignment style is "stretch" or "normal" (see the note on width above)
// - The node is not absolutely positioned
// - The node does not have auto margins in this axis.
if !self.margin.top.is_auto() && !self.margin.bottom.is_auto() && self.is_stretch_aligned(self.align_self) {
return grid_area_minus_item_margins_size.height;
}
None
});
// Reapply aspect ratio after stretch and absolute position height adjustments
let Size { width, height } = Size { width, height }.maybe_apply_aspect_ratio(aspect_ratio);
// Clamp size by min and max width/height
let Size { width, height } = Size { width, height }.maybe_clamp(min_size, max_size);
Size { width, height }
}
/// Returns the grid area's size in the specified axis when every spanned track has a definite fixed size.
///
/// During intrinsic sizing, percentages on grid items resolve against the size of the grid area,
/// not the grid container. If the spanned tracks in an axis are not all definite yet, the grid
/// area is still indefinite in that axis and percentage-dependent values must stay unresolved here.
///
/// Spec:
/// https://www.w3.org/TR/css-grid-1/#grid-item-sizing
/// https://www.w3.org/TR/css-grid-1/#algo-overview
///
/// Compute the available_space to be passed to the child sizing functions
/// These are estimates based on either the max track sizing function or the provisional base size in the opposite
/// axis to the one currently being sized.
/// https://www.w3.org/TR/css-grid-1/#algo-overview
pub fn grid_area_size(
&self,
axis: AbstractAxis,
axis_tracks: &[GridTrack],
other_axis_tracks: &[GridTrack],
available_space: Size<Option<f32>>,
get_track_size_estimate: impl Fn(&GridTrack, Option<f32>) -> Option<f32>,
resolve_calc_value: &impl Fn(*const (), f32) -> f32,
) -> Size<Option<f32>> {
let mut size = Size::NONE;
size.set(
axis,
axis_tracks[self.track_range_excluding_lines(axis)]
.iter()
.map(|track| {
let min_size = track
.min_track_sizing_function
.definite_value(available_space.get(axis), resolve_calc_value)?;
let max_size = track
.max_track_sizing_function
.definite_value(available_space.get(axis), resolve_calc_value)?;
if min_size == max_size {
Some(track.base_size)
} else {
None
}
})
.sum::<Option<f32>>(),
);
size.set(
axis.other(),
other_axis_tracks[self.track_range_excluding_lines(axis.other())]
.iter()
.map(|track| {
get_track_size_estimate(track, available_space.get(axis.other()))
.map(|size| size + track.content_alignment_adjustment)
})
.sum::<Option<f32>>(),
);
size
}
/// Retrieve the available_space from the cache or compute them using the passed parameters
pub fn grid_area_size_cached(
&mut self,
axis: AbstractAxis,
axis_tracks: &[GridTrack],
other_axis_tracks: &[GridTrack],
available_space: Size<Option<f32>>,
get_track_size_estimate: impl Fn(&GridTrack, Option<f32>) -> Option<f32>,
resolve_calc_value: &impl Fn(*const (), f32) -> f32,
) -> Size<Option<f32>> {
self.grid_area_size_cache.unwrap_or_else(|| {
let grid_area_size = self.grid_area_size(
axis,
axis_tracks,
other_axis_tracks,
available_space,
get_track_size_estimate,
resolve_calc_value,
);
self.grid_area_size_cache = Some(grid_area_size);
grid_area_size
})
}
/// Compute the item's resolved margins for size contributions. Horizontal percentage margins always resolve
/// to zero if the container size is indefinite as otherwise this would introduce a cyclic dependency.
#[inline(always)]
pub fn margins_axis_sums_with_baseline_shims(
&self,
inner_node_width: Option<f32>,
tree: &impl LayoutPartialTree,
) -> Size<f32> {
Rect {
left: self.margin.left.resolve_or_zero(Some(0.0), |val, basis| tree.calc(val, basis)),
right: self.margin.right.resolve_or_zero(Some(0.0), |val, basis| tree.calc(val, basis)),
top: self.margin.top.resolve_or_zero(inner_node_width, |val, basis| tree.calc(val, basis))
+ self.baseline_shim,
bottom: self.margin.bottom.resolve_or_zero(inner_node_width, |val, basis| tree.calc(val, basis)),
}
.sum_axes()
}
/// Compute the item's min content contribution from the provided parameters
pub fn min_content_contribution(
&mut self,
axis: AbstractAxis,
tree: &mut impl LayoutPartialTree,
grid_area_size: Size<Option<f32>>,
available_space: Size<Option<f32>>,
) -> f32 {
let known_dimensions = self.known_dimensions_cached(tree, grid_area_size);
// If the item's size in the axis being measured is already known then that size is its contribution,
// and we can avoid calling into the child entirely.
if let Some(size) = known_dimensions.get(axis) {
return size;
}
// The child sees the grid area as its containing block during intrinsic measurement, so
// percentage box properties resolve against the grid area when that size is definite.
// Spec:
// https://www.w3.org/TR/css-grid-1/#grid-item-sizing
// https://www.w3.org/TR/css-grid-1/#algo-overview
tree.measure_child_size(
self.node,
known_dimensions,
grid_area_size,
self.keyword_adjusted_available_space(
grid_area_size,
self.available_space_minus_margins(grid_area_size, available_space, tree).map(|opt| match opt {
Some(size) => AvailableSpace::Definite(size),
None => AvailableSpace::MinContent,
}),
tree,
),
SizingMode::InherentSize,
axis.as_abs_naive(),
Line::FALSE,
)
}
/// Retrieve the item's min content contribution from the cache or compute it using the provided parameters
#[inline(always)]
pub fn min_content_contribution_cached(
&mut self,
axis: AbstractAxis,
tree: &mut impl LayoutPartialTree,
grid_area_size: Size<Option<f32>>,
available_space: Size<Option<f32>>,
) -> f32 {
self.min_content_contribution_cache.get(axis).unwrap_or_else(|| {
let size = self.min_content_contribution(axis, tree, grid_area_size, available_space);
self.min_content_contribution_cache.set(axis, Some(size));
size
})
}
/// Compute the item's max content contribution from the provided parameters
pub fn max_content_contribution(
&mut self,
axis: AbstractAxis,
tree: &mut impl LayoutPartialTree,
grid_area_size: Size<Option<f32>>,
available_space: Size<Option<f32>>,
) -> f32 {
let known_dimensions = self.known_dimensions_cached(tree, grid_area_size);
// If the item's size in the axis being measured is already known then that size is its contribution,
// and we can avoid calling into the child entirely.
if let Some(size) = known_dimensions.get(axis) {
return size;
}
// See the min-content path above. Max-content measurement uses the same containing-block
// basis so percentage-dependent item geometry is measured from the grid area rather than
// from the container.
tree.measure_child_size(
self.node,
known_dimensions,
grid_area_size,
self.keyword_adjusted_available_space(
grid_area_size,
self.available_space_minus_margins(grid_area_size, available_space, tree).map(|opt| match opt {
Some(size) => AvailableSpace::Definite(size),
None => AvailableSpace::MaxContent,
}),
tree,
),
SizingMode::InherentSize,
axis.as_abs_naive(),
Line::FALSE,
)
}
/// Subtract the item's margins (and baseline shim) from the definite axes of the space available
/// to the item's margin box, giving the available space that is passed to the item.
/// As when the item is laid out into its final position, margins resolve against the width
/// of the grid area and `auto` margins are treated as zero.
#[inline(always)]
fn available_space_minus_margins(
&self,
grid_area_size: Size<Option<f32>>,
available_space: Size<Option<f32>>,
tree: &impl LayoutPartialTree,
) -> Size<Option<f32>> {
if available_space.width.is_none() && available_space.height.is_none() {
return available_space;
}
let margin = self.margin.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
Size {
width: available_space.width.map(|width| f32_max(width - margin.horizontal_axis_sum(), 0.0)),
height: available_space
.height
.map(|height| f32_max(height - margin.vertical_axis_sum() - self.baseline_shim, 0.0)),
}
}
/// Override the available space in each axis whose size style is a sizing keyword that
/// measures the item under a specific available space constraint
/// (min-content, max-content, fit-content, fit-content(...))
fn keyword_adjusted_available_space(
&self,
grid_area_size: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
tree: &impl LayoutPartialTree,
) -> Size<AvailableSpace> {
if !self.size.width.is_sizing_keyword() && !self.size.height.is_sizing_keyword() {
return available_space;
}
let margins = self.margins_axis_sums_with_baseline_shims(grid_area_size.width, tree);
let mut adjusted = available_space;
for axis in [AbstractAxis::Inline, AbstractAxis::Block] {
let size_style = self.size.get(axis);
if !size_style.is_sizing_keyword() {
continue;
}
let stretch_size = grid_area_size.get(axis).maybe_sub(margins.get(axis)).maybe_max(0.0);
if let Some(SizingKeywordResolution::Measure(available)) =
resolve_sizing_keyword(size_style, stretch_size, grid_area_size.get(axis), |val, basis| {
tree.calc(val, basis)
})
{
adjusted.set(axis, available);
}
}
adjusted
}
/// Retrieve the item's max content contribution from the cache or compute it using the provided parameters
#[inline(always)]
pub fn max_content_contribution_cached(
&mut self,
axis: AbstractAxis,
tree: &mut impl LayoutPartialTree,
grid_area_size: Size<Option<f32>>,
available_space: Size<Option<f32>>,
) -> f32 {
self.max_content_contribution_cache.get(axis).unwrap_or_else(|| {
let size = self.max_content_contribution(axis, tree, grid_area_size, available_space);
self.max_content_contribution_cache.set(axis, Some(size));
size
})
}
/// The minimum contribution of an item is the smallest outer size it can have.
/// Specifically:
/// - If the item’s computed preferred size behaves as auto or depends on the size of its containing block in the relevant axis:
/// Its minimum contribution is the outer size that would result from assuming the item’s used minimum size as its preferred size;
/// - Else the item’s minimum contribution is its min-content contribution.
///
/// Because the minimum contribution often depends on the size of the item’s content, it is considered a type of intrinsic size contribution.
/// See: https://www.w3.org/TR/css-grid-1/#min-size-auto
pub fn minimum_contribution(
&mut self,
tree: &mut impl LayoutPartialTree,
axis: AbstractAxis,
axis_tracks: &[GridTrack],
grid_area_size: Size<Option<f32>>,
inner_node_size: Size<Option<f32>>,
) -> f32 {
let padding = self.padding.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
let border = self.border.resolve_or_zero(grid_area_size.width, |val, basis| tree.calc(val, basis));
let padding_border_size = (padding + border).sum_axes();
let box_sizing_adjustment =
if self.box_sizing == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
self.size
.maybe_resolve(grid_area_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(self.aspect_ratio)
.maybe_add(box_sizing_adjustment)
.get(axis)
.map(|size| {
// A definite preferred size is clamped by the minimum and maximum sizes. For a compressible replaced
// element, an indefinite percentage maximum size is resolved against zero.
let min_size = self.min_size.get(axis);
let max_size = self.max_size.get(axis);
if min_size.is_auto() && max_size.is_auto() {
return size;
}
let basis = grid_area_size.get(axis);
let max_size_basis = if self.is_compressible_replaced { basis.or(Some(0.0)) } else { basis };
let adjustment = box_sizing_adjustment.get(axis);
let min_size = min_size.maybe_resolve(basis, |val, basis| tree.calc(val, basis));
let max_size = max_size.maybe_resolve(max_size_basis, |val, basis| tree.calc(val, basis));
size.maybe_clamp(min_size.maybe_add(adjustment), max_size.maybe_add(adjustment))
})
.or_else(|| {
// A preferred size that is a sizing keyword other than `stretch` does not behave as auto,
// so the minimum contribution is the min-content contribution.
let size = self.size.get(axis);
(size.is_sizing_keyword() && !size.is_stretch())
.then(|| self.min_content_contribution_cached(axis, tree, grid_area_size, grid_area_size))
})
.or_else(|| {
self.min_size
.maybe_resolve(grid_area_size.map(|size| size.unwrap_or(0.0)), |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(self.aspect_ratio)
.maybe_add(box_sizing_adjustment)
.get(axis)
})
.or_else(|| self.overflow.get(axis).maybe_into_automatic_min_size())
.unwrap_or_else(|| {
// Automatic minimum size. See https://www.w3.org/TR/css-grid-1/#min-size-auto
// To provide a more reasonable default minimum size for grid items, the used value of its automatic minimum size
// in a given axis is the content-based minimum size if all of the following are true:
let item_axis_tracks = &axis_tracks[self.track_range_excluding_lines(axis)];
// it is not a scroll container (handled above)
// it spans at least one track in that axis whose min track sizing function is auto
let spans_auto_min_track = item_axis_tracks
.iter()
.any(|track| track.min_track_sizing_function.behaves_as_auto(inner_node_size.get(axis)));
// if it spans more than one track in that axis, none of those tracks are flexible
let only_span_one_track = item_axis_tracks.len() == 1;
let use_content_based_minimum = spans_auto_min_track
&& (only_span_one_track
|| !item_axis_tracks.iter().any(|track| track.max_track_sizing_function.is_fr()));
// Otherwise, the automatic minimum size is zero, as usual.
if use_content_based_minimum {
let mut minimum_contribution =
self.min_content_contribution_cached(axis, tree, grid_area_size, grid_area_size);
// If the item is a compressible replaced element, and has a definite preferred size or maximum size in the
// relevant axis, the size suggestion is capped by those sizes; for this purpose, any indefinite percentages
// in these sizes are resolved against zero (and considered definite).
if self.is_compressible_replaced {
let size = self.size.get(axis).maybe_resolve(Some(0.0), |val, basis| tree.calc(val, basis));
let max_size =
self.max_size.get(axis).maybe_resolve(Some(0.0), |val, basis| tree.calc(val, basis));
minimum_contribution = minimum_contribution.maybe_min(size).maybe_min(max_size);
}
// The content-based minimum size is additionally clamped by the sum of any fixed max track sizing
// functions of the tracks the item spans. Note that this clamp does not apply to explicitly specified
// preferred or minimum sizes, and that the argument to fit-content() does not clamp the content-based
// minimum size in the same way as a fixed max track sizing function. The clamp is a stretch fit into
// the limit, so it does not shrink the item below its padding + border.
let limit =
self.spanned_fixed_track_limit(axis, axis_tracks, inner_node_size.get(axis), &|val, basis| {
tree.resolve_calc_value(val, basis)
});
minimum_contribution.maybe_min(limit.map(|limit| f32_max(limit, padding_border_size.get(axis))))
} else {
0.0
}
})
}
/// Retrieve the item's minimum contribution from the cache or compute it using the provided parameters
#[inline(always)]
pub fn minimum_contribution_cached(
&mut self,
tree: &mut impl LayoutPartialTree,
axis: AbstractAxis,
axis_tracks: &[GridTrack],
grid_area_size: Size<Option<f32>>,
inner_node_size: Size<Option<f32>>,
) -> f32 {
self.minimum_contribution_cache.get(axis).unwrap_or_else(|| {
let size = self.minimum_contribution(tree, axis, axis_tracks, grid_area_size, inner_node_size);
self.minimum_contribution_cache.set(axis, Some(size));
size
})
}
}
+169
View File
@@ -0,0 +1,169 @@
//! Contains GridTrack used to represent a single grid track (row/column) during layout
use crate::{
prelude::TaffyZero,
style::{LengthPercentage, MaxTrackSizingFunction, MinTrackSizingFunction},
util::sys::f32_min,
};
/// Whether a GridTrack represents an actual track or a gutter.
#[derive(Copy, Clone, Debug, PartialEq)]
pub(in super::super) enum GridTrackKind {
/// Track is an actual track
Track,
/// Track is a gutter (aka grid line) (aka gap)
Gutter, // { name: Option<u16> },
}
/// Internal sizing information for a single grid track (row/column)
/// Gutters between tracks are sized similarly to actual tracks, so they
/// are also represented by this struct
#[derive(Debug, Clone)]
pub(in super::super) struct GridTrack {
#[allow(dead_code)] // Used in tests + may be useful in future
/// Whether the track is a full track, a gutter, or a placeholder that has not yet been initialised
pub kind: GridTrackKind,
/// Whether the track is a collapsed track/gutter. Collapsed tracks are effectively treated as if
/// they don't exist for the purposes of grid sizing. Gutters between collapsed tracks are also collapsed.
pub is_collapsed: bool,
/// The minimum track sizing function of the track
pub min_track_sizing_function: MinTrackSizingFunction,
/// The maximum track sizing function of the track
pub max_track_sizing_function: MaxTrackSizingFunction,
/// The distance of the start of the track from the start of the grid container
pub offset: f32,
/// The size (width/height as applicable) of the track
pub base_size: f32,
/// A temporary scratch value when sizing tracks
/// Note: can be infinity
pub growth_limit: f32,
/// A temporary scratch value when sizing tracks. Is used as an additional amount to add to the
/// estimate for the available space in the opposite axis when content sizing items
pub content_alignment_adjustment: f32,
/// A temporary scratch value when "distributing space" to avoid clobbering planned increase variable
pub item_incurred_increase: f32,
/// A temporary scratch value when "distributing space" to avoid clobbering the main variable
pub base_size_planned_increase: f32,
/// A temporary scratch value when "distributing space" to avoid clobbering the main variable
pub growth_limit_planned_increase: f32,
/// A temporary scratch value when "distributing space"
/// See: https://www.w3.org/TR/css3-grid-layout/#infinitely-growable
pub infinitely_growable: bool,
/// The resolved `fit-content()` limit of the max track sizing function (infinity if it is not `fit-content()`
/// or the limit cannot be resolved). Resolved once per track sizing pass by `resolve_fit_content_limit`.
pub fit_content_limit: f32,
}
impl GridTrack {
/// GridTrack constructor with all configuration parameters for the other constructors exposed
const fn new_with_kind(
kind: GridTrackKind,
min_track_sizing_function: MinTrackSizingFunction,
max_track_sizing_function: MaxTrackSizingFunction,
) -> GridTrack {
GridTrack {
kind,
is_collapsed: false,
min_track_sizing_function,
max_track_sizing_function,
offset: 0.0,
base_size: 0.0,
growth_limit: 0.0,
content_alignment_adjustment: 0.0,
item_incurred_increase: 0.0,
base_size_planned_increase: 0.0,
growth_limit_planned_increase: 0.0,
infinitely_growable: false,
fit_content_limit: f32::INFINITY,
}
}
/// Create new GridTrack representing an actual track (not a gutter)
pub const fn new(
min_track_sizing_function: MinTrackSizingFunction,
max_track_sizing_function: MaxTrackSizingFunction,
) -> GridTrack {
Self::new_with_kind(GridTrackKind::Track, min_track_sizing_function, max_track_sizing_function)
}
/// Create a new GridTrack representing a gutter
pub fn gutter(size: LengthPercentage) -> GridTrack {
Self::new_with_kind(
GridTrackKind::Gutter,
MinTrackSizingFunction::from(size),
MaxTrackSizingFunction::from(size),
)
}
/// Mark a GridTrack as collapsed. Also sets both of the track's sizing functions
/// to fixed zero-sized sizing functions.
pub fn collapse(&mut self) {
self.is_collapsed = true;
self.min_track_sizing_function = MinTrackSizingFunction::ZERO;
self.max_track_sizing_function = MaxTrackSizingFunction::ZERO;
self.fit_content_limit = f32::INFINITY;
}
#[inline(always)]
/// Returns true if the track is flexible (has a Flex MaxTrackSizingFunction), else false.
pub fn is_flexible(&self) -> bool {
self.max_track_sizing_function.is_fr()
}
#[inline(always)]
/// Returns true if the track is flexible (has a Flex MaxTrackSizingFunction), else false.
pub fn uses_percentage(&self) -> bool {
self.min_track_sizing_function.uses_percentage() || self.max_track_sizing_function.uses_percentage()
}
#[inline(always)]
/// Returns true if the track has an intrinsic min and or max sizing function
pub fn has_intrinsic_sizing_function(&self) -> bool {
self.min_track_sizing_function.is_intrinsic() || self.max_track_sizing_function.is_intrinsic()
}
/// Cache the `fit-content()` limit of the max track sizing function (if any), resolved against the
/// container's inner size in this axis. Percentage and calc() limits resolve to infinity if that size is
/// indefinite, as do tracks which are not `fit-content()`.
#[inline]
pub fn resolve_fit_content_limit(
&mut self,
axis_inner_node_size: Option<f32>,
calc_resolver: impl Fn(*const (), f32) -> f32,
) {
self.fit_content_limit = self
.max_track_sizing_function
.fit_content_limit(axis_inner_node_size, calc_resolver)
.unwrap_or(f32::INFINITY);
}
#[inline(always)]
/// Returns the resolved `fit-content()` limit of the track (infinity if the track is not `fit-content()`)
pub fn fit_content_limit(&self) -> f32 {
self.fit_content_limit
}
#[inline]
/// Returns the track's growth limit, capped by its `fit-content()` limit (if any)
pub fn fit_content_limited_growth_limit(&self) -> f32 {
f32_min(self.growth_limit, self.fit_content_limit)
}
#[inline]
/// Returns the track's flex factor if it is a flex track, else 0.
pub fn flex_factor(&self) -> f32 {
if self.max_track_sizing_function.is_fr() {
self.max_track_sizing_function.0.value()
} else {
0.0
}
}
}
+102
View File
@@ -0,0 +1,102 @@
//! Contains TrackCounts used to keep track of the number of tracks in the explicit and implicit grids.
//! Also contains coordinate conversion functions which depend on those counts
//!
//! Taffy uses two coordinate systems to refer to grid lines (the gaps/gutters between rows/columns):
//!
//! "CSS Grid Line" coordinates are those used in grid-row/grid-column in the CSS grid spec:
//! - 0 is not a valid index
//! - The line at left hand (or top) edge of the explicit grid is line 1
//! (and counts up from there)
//! - The line at the right hand (or bottom) edge of the explicit grid in -1
//! (and counts down from there)
//!
//! "OriginZero" coordinates are a normalized form:
//! - The line at left hand (or top) edge of the explicit grid is line 0
//! - The next line to the right (or down) is 1, and so on
//! - The next line to the left (or up) is -1, and so on
//!
//! Taffy also uses two coordinate systems to refer to grid tracks (rows/columns):
//!
//! Both of these systems represent the entire implicit grid, not just the explicit grid.
//!
//! "CellOccupancyMatrix track indices":
//! - These are indexes into the CellOccupancyMatrix
//! - The CellOccupancyMatrix stores only tracks
//! - 0 is the leftmost track of the implicit grid, and indexes count up there
//!
//! "GridTrackVec track indices":
//! - The GridTrackVecs store both lines and tracks, so:
//! - even indices (0, 2, 4, etc) represent lines
//! - odd indices (1, 3, 5, etc) represent tracks
//! - These is always an odd number of
//! - Index 1 is the leftmost track of the implicit grid. Index 3 is the second leftmost track, etc.
//! - Index 0 is the leftmost grid line. Index 2 is the second leftmost line, etc.
//!
use crate::{compute::grid::OriginZeroLine, geometry::Line};
use core::ops::Range;
/// Stores the number of tracks in a given dimension.
/// Stores separately the number of tracks in the implicit and explicit grids
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub(crate) struct TrackCounts {
/// The number of track in the implicit grid before the explicit grid
pub negative_implicit: u16,
/// The number of tracks in the explicit grid
pub explicit: u16,
/// The number of tracks in the implicit grid after the explicit grid
pub positive_implicit: u16,
}
impl TrackCounts {
/// Create a TrackCounts instance from raw track count numbers
pub const fn from_raw(negative_implicit: u16, explicit: u16, positive_implicit: u16) -> Self {
Self { negative_implicit, explicit, positive_implicit }
}
/// Count the total number of tracks in the axis
pub const fn len(&self) -> usize {
(self.negative_implicit + self.explicit + self.positive_implicit) as usize
}
/// The OriginZeroLine representing the start of the implicit grid
pub const fn implicit_start_line(&self) -> OriginZeroLine {
OriginZeroLine(-(self.negative_implicit as i16))
}
/// The OriginZeroLine representing the end of the implicit grid
pub const fn implicit_end_line(&self) -> OriginZeroLine {
OriginZeroLine((self.explicit + self.positive_implicit) as i16)
}
}
/// Conversion functions between OriginZero coordinates and CellOccupancyMatrix track indexes
#[allow(dead_code)]
impl TrackCounts {
/// Converts a grid line in OriginZero coordinates into the track immediately
/// following that grid line as an index into the CellOccupancyMatrix.
pub const fn oz_line_to_next_track(&self, index: OriginZeroLine) -> i16 {
index.0 + (self.negative_implicit as i16)
}
/// Converts start and end grid lines in OriginZero coordinates into a range of tracks
/// as indexes into the CellOccupancyMatrix
pub const fn oz_line_range_to_track_range(&self, input: Line<OriginZeroLine>) -> Range<i16> {
let start = self.oz_line_to_next_track(input.start);
let end = self.oz_line_to_next_track(input.end); // Don't subtract 1 as output range is exclusive
start..end
}
/// Converts a track as an index into the CellOccupancyMatrix into the grid line immediately
/// preceding that track in OriginZero coordinates.
pub const fn track_to_prev_oz_line(&self, index: u16) -> OriginZeroLine {
OriginZeroLine((index as i16) - (self.negative_implicit as i16))
}
/// Converts a range of tracks as indexes into the CellOccupancyMatrix into
/// start and end grid lines in OriginZero coordinates
pub const fn track_range_to_oz_line_range(&self, input: Range<i16>) -> Line<OriginZeroLine> {
let start = self.track_to_prev_oz_line(input.start as u16);
let end = self.track_to_prev_oz_line(input.end as u16); // Don't add 1 as input range is exclusive
Line { start, end }
}
}
+19
View File
@@ -0,0 +1,19 @@
//! Structs and enums that are used within the grid module
mod cell_occupancy;
mod coordinates;
mod grid_item;
mod grid_track;
mod grid_track_counts;
mod named;
// Publish only locally in the grid module
pub(super) use cell_occupancy::{CellOccupancyMatrix, CellOccupancyState};
pub(crate) use coordinates::{GridCoordinate, GridLine, OriginZeroLine, MAX_GRID_TRACKS, MAX_OZ_LINE, MIN_OZ_LINE};
pub(super) use grid_item::GridItem;
pub(super) use grid_track::GridTrack;
pub(super) use grid_track_counts::TrackCounts;
pub(super) use named::{GridAreasMap, NamedLineResolver};
pub use named::{GridLineNames, GridLineNamesIter};
#[allow(unused_imports)]
pub(super) use grid_track::GridTrackKind;
+998
View File
@@ -0,0 +1,998 @@
//! Code for resolving name grid lines and areas
use crate::{
CheapCloneStr, GenericGridTemplateComponent, GenericRepetition as _, GridAreaAxis, GridAreaEnd, GridContainerStyle,
GridPlacement, Line, NonNamedGridPlacement, RepetitionCount,
};
use core::{borrow::Borrow, cmp::Ordering, fmt::Debug};
use super::{GridLine, OriginZeroLine, MAX_GRID_TRACKS};
use crate::geometry::AbsoluteAxis;
use crate::sys::DefaultCheapStr;
use crate::sys::{Map, Vec};
use smallvec::{smallvec, SmallVec};
/// Wrap an `AsRef<str>` type with a type which implements Hash by first
/// deferring to the underlying `&str`'s implementation of Hash.
#[derive(Debug, Clone)]
pub(crate) struct StrHasher<T: CheapCloneStr>(pub T);
impl<T: CheapCloneStr> PartialOrd for StrHasher<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T: CheapCloneStr> Ord for StrHasher<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.0.as_ref().cmp(other.0.as_ref())
}
}
impl<T: CheapCloneStr> PartialEq for StrHasher<T> {
fn eq(&self, other: &Self) -> bool {
other.0.as_ref() == self.0.as_ref()
}
}
impl<T: CheapCloneStr> Eq for StrHasher<T> {}
#[cfg(feature = "std")]
impl<T: CheapCloneStr> std::hash::Hash for StrHasher<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.as_ref().hash(state)
}
}
impl<T: CheapCloneStr> Borrow<str> for StrHasher<T> {
fn borrow(&self) -> &str {
self.0.as_ref()
}
}
/// The one-indexed line positions of a single grid line name. Inline capacity of 4 keeps the
/// type the same size as `Vec<u32>` (24 bytes) while avoiding a heap allocation for names
/// mapping to at most 4 lines (the common case)
pub(crate) type LinePositions = SmallVec<[u32; 4]>;
/// Map from a grid line name to its one-indexed line positions
type NamedGridLinesMap<S> = Map<StrHasher<S>, LinePositions>;
/// The one-indexed positions of the first line that starts and the first line that ends a named grid area in
/// each axis, i.e. the first line named `<area-name>-start`/`<area-name>-end` (explicitly or by
/// `grid-template-areas`). A value of 0 means that there is no such line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct AreaLines {
/// The first line that starts the area in the row axis
row_start: u32,
/// The first line that ends the area in the row axis
row_end: u32,
/// The first line that starts the area in the column axis
column_start: u32,
/// The first line that ends the area in the column axis
column_end: u32,
}
impl AreaLines {
/// The line for the passed edge of the area (if there is one)
fn line(&self, axis: GridAreaAxis, end: GridAreaEnd) -> Option<&u32> {
let line = match (axis, end) {
(GridAreaAxis::Row, GridAreaEnd::Start) => &self.row_start,
(GridAreaAxis::Row, GridAreaEnd::End) => &self.row_end,
(GridAreaAxis::Column, GridAreaEnd::Start) => &self.column_start,
(GridAreaAxis::Column, GridAreaEnd::End) => &self.column_end,
};
Some(line).filter(|line| **line != 0)
}
/// The line for the passed edge of the area (0 if there is none)
fn line_mut(&mut self, axis: GridAreaAxis, end: GridAreaEnd) -> &mut u32 {
match (axis, end) {
(GridAreaAxis::Row, GridAreaEnd::Start) => &mut self.row_start,
(GridAreaAxis::Row, GridAreaEnd::End) => &mut self.row_end,
(GridAreaAxis::Column, GridAreaEnd::Start) => &mut self.column_start,
(GridAreaAxis::Column, GridAreaEnd::End) => &mut self.column_end,
}
}
}
/// Map from the name of a grid area to the lines of its edges.
///
/// This is how the `<area-name>-start` and `<area-name>-end` line names that `grid-template-areas` implicitly
/// generates are represented: storing them as line names would require allocating a string for each of them.
pub(crate) type GridAreasMap<S> = Map<StrHasher<S>, AreaLines>;
/// Split a line name of the form `<area-name>-start` or `<area-name>-end` into the area name and the edge
fn split_area_edge_name(name: &str) -> Option<(&str, GridAreaEnd)> {
if let Some(area_name) = name.strip_suffix("-start") {
Some((area_name, GridAreaEnd::Start))
} else if let Some(area_name) = name.strip_suffix("-end") {
Some((area_name, GridAreaEnd::End))
} else {
None
}
}
/// Resolver for named placements in one grid axis
struct NamedLineResolverAxis<'a, S: CheapCloneStr> {
/// Named lines and their one-indexed positions
lines: &'a NamedGridLinesMap<S>,
/// The edges of named grid areas (in both axes)
areas: &'a GridAreasMap<S>,
/// The axis being resolved
axis: GridAreaAxis,
/// Number of explicit tracks in this axis
explicit_track_count: u16,
}
/// Resolver that takes grid lines names and area names as input and can then be used to
/// resolve line names of grid placement properties into line numbers.
pub(crate) struct NamedLineResolver<S: CheapCloneStr> {
/// Map of row line names to line numbers. Each line name may correspond to multiple lines
/// so we store a `SmallVec`
row_lines: NamedGridLinesMap<S>,
/// Map of column line names to line numbers. Each line name may correspond to multiple lines
/// so we store a `SmallVec`
column_lines: NamedGridLinesMap<S>,
/// Map of area names to the lines of the area's edges
areas: GridAreasMap<S>,
/// Number of columns implied by grid area definitions
area_column_count: u16,
/// Number of rows implied by grid area definitions
area_row_count: u16,
/// The number of explicit columns in the grid. This is an *input* to the `NamedLineResolver` and is
/// used when computing the fallback line when a non-existent named line is specified.
explicit_column_count: u16,
/// The number of explicit rows in the grid. This is an *input* to the `NamedLineResolver` and is
/// used when computing the fallback line when a non-existent named line is specified.
explicit_row_count: u16,
/// The (1-indexed line number, name) pairs of every column line named in the track template,
/// in source order (excludes the implicit names generated by `grid-template-areas`)
column_line_name_pairs: Vec<(u32, S)>,
/// The (1-indexed line number, name) pairs of every row line named in the track template,
/// in source order (excludes the implicit names generated by `grid-template-areas`)
row_line_name_pairs: Vec<(u32, S)>,
}
/// Utility function to create or update an entry in a line name map
///
/// `areas` must already contain the edges of the areas defined by `grid-template-areas`
fn upsert_line_name_map<S: CheapCloneStr>(
map: &mut NamedGridLinesMap<S>,
areas: &mut GridAreasMap<S>,
axis: GridAreaAxis,
key: S,
value: u32,
) {
// A line named `foo-start` or `foo-end` is also an edge of the (implicitly) named area `foo`. Record it as such
// if it is the first such line. If `foo` is also an area defined by `grid-template-areas`, then the line which
// that area generated also has this name.
let mut area_line = 0;
if let Some((area_name, end)) = split_area_edge_name(key.as_ref()) {
// The key is only created if the area is not already in the map
if !areas.contains_key(area_name) {
areas.insert(StrHasher(S::from(area_name)), AreaLines::default());
}
let edge = areas.get_mut(area_name).unwrap().line_mut(axis, end);
area_line = *edge;
*edge = if *edge == 0 { value } else { (*edge).min(value) };
}
map.entry(StrHasher(key)).and_modify(|lines| lines.push(value)).or_insert_with(|| {
// Until this entry is created, the only line that can have been recorded for this edge is the area's own
if area_line == 0 {
smallvec![value]
} else {
smallvec![area_line, value]
}
});
}
impl<S: CheapCloneStr> NamedLineResolverAxis<'_, S> {
/// The line for the passed edge of the named grid area in this axis (if there is one)
fn area_line(&self, area_name: &str, end: GridAreaEnd) -> Option<&u32> {
self.areas.get(area_name)?.line(self.axis, end)
}
/// Resolve named lines and spans into numeric placements
fn resolve_line_names(&self, line: &Line<GridPlacement<S>>) -> Line<NonNamedGridPlacement> {
let start_holder;
let start_line_resolved = if let GridPlacement::NamedLine(name, idx) = &line.start {
start_holder = GridPlacement::Line(self.find_named_line(name, *idx, GridAreaEnd::Start));
&start_holder
} else {
&line.start
};
let end_holder;
let end_line_resolved = if let GridPlacement::NamedLine(name, idx) = &line.end {
end_holder = GridPlacement::Line(self.find_named_line(name, *idx, GridAreaEnd::End));
&end_holder
} else {
&line.end
};
// If both the *-start and *-end values of its grid-placement properties specify a line, its grid span is implicit.
// If it has an explicit span value, its grid span is explicit.
// Otherwise, its grid span is automatic:
// - if it is subgridded in that axis, its grid span is determined from its <line-name-list>;
// - otherwise its grid span is 1.
//
// <https://drafts.csswg.org/css-grid-2/#grid-span>
match (&start_line_resolved, &end_line_resolved) {
(GridPlacement::Line(start_line), GridPlacement::NamedSpan(name, idx)) if start_line.as_i16() != 0 => {
let after_start_line = start_line.into_origin_zero_line(self.explicit_track_count) + 1;
let end_line =
self.nth_line_forwards(self.lines_named(name.as_ref()), after_start_line, (*idx).max(1) as i32);
Line {
start: NonNamedGridPlacement::Line(*start_line),
end: NonNamedGridPlacement::Line(end_line.into_grid_line(self.explicit_track_count)),
}
}
(GridPlacement::NamedSpan(name, idx), GridPlacement::Line(end_line)) if end_line.as_i16() != 0 => {
let before_end_line = end_line.into_origin_zero_line(self.explicit_track_count) - 1;
let start_line =
self.nth_line_backwards(self.lines_named(name.as_ref()), before_end_line, (*idx).max(1) as i32);
Line {
start: NonNamedGridPlacement::Line(start_line.into_grid_line(self.explicit_track_count)),
end: NonNamedGridPlacement::Line(*end_line),
}
}
(start, end) => Line {
start: match start {
GridPlacement::Auto => NonNamedGridPlacement::Auto,
GridPlacement::Line(grid_line) => NonNamedGridPlacement::Line(*grid_line),
GridPlacement::Span(span) => NonNamedGridPlacement::Span(*span),
GridPlacement::NamedSpan(_, _) => NonNamedGridPlacement::Span(1),
_ => unreachable!(),
},
end: match end {
GridPlacement::Auto => NonNamedGridPlacement::Auto,
GridPlacement::Line(grid_line) => NonNamedGridPlacement::Line(*grid_line),
GridPlacement::Span(span) => NonNamedGridPlacement::Span(*span),
GridPlacement::NamedSpan(_, _) => NonNamedGridPlacement::Span(1),
_ => unreachable!(),
},
},
}
}
/// Resolve the grid line for a named grid line (`<custom-ident>` or `<integer> <custom-ident>`).
/// An index of 0 is used to represent "no index specified".
///
/// <https://drafts.csswg.org/css-grid-2/#line-placement>
fn find_named_line(&self, name: &S, idx: i16, end: GridAreaEnd) -> GridLine {
let name = name.as_ref();
// A `<custom-ident>` on its own first attempts to match the edge of a named grid area:
// the first line named `<custom-ident>-start` (or `<custom-ident>-end` for an end line).
// Otherwise it is treated as if the integer 1 had been specified along with it.
if idx == 0 {
if let Some(first_line) = self.area_line(name, end) {
return OriginZeroLine::clamped(oz_line(*first_line)).into_grid_line(self.explicit_track_count);
}
}
let lines = self.lines_named(name);
let line = if idx >= 0 {
self.nth_line_forwards(lines, OriginZeroLine(0), (idx as i32).max(1))
} else {
self.nth_line_backwards(lines, self.last_explicit_line(), -(idx as i32))
};
line.into_grid_line(self.explicit_track_count)
}
/// The sorted line numbers of the lines with the passed name
///
/// A line generated by a grid area is included in the lines of its name if any line has been explicitly
/// given the same name. Otherwise it is found from the area's edges.
fn lines_named(&self, name: &str) -> &[u32] {
match self.lines.get(name) {
Some(lines) => lines.as_slice(),
None => split_area_edge_name(name)
.and_then(|(area_name, area_end)| self.area_line(area_name, area_end))
.map(core::slice::from_ref)
.unwrap_or(&[]),
}
}
/// The line at the end edge of the explicit grid
fn last_explicit_line(&self) -> OriginZeroLine {
OriginZeroLine(self.explicit_track_count as i16)
}
/// Find the `n`th line in `lines` (searching forwards) that is not before `first_line`.
///
/// If there are not enough such lines, then all implicit lines after the explicit grid are
/// assumed to be in `lines` for the purpose of counting
///
/// <https://drafts.csswg.org/css-grid-2/#grid-placement-int>
fn nth_line_forwards(&self, lines: &[u32], first_line: OriginZeroLine, n: i32) -> OriginZeroLine {
let first_line = first_line.0.max(0) as i32;
let lines = &lines[lines.partition_point(|line| oz_line(*line) < first_line)..];
let line = match lines.get(n as usize - 1) {
Some(line) => oz_line(*line),
None => first_line.max(self.last_explicit_line().0 as i32 + 1) + (n - lines.len() as i32) - 1,
};
OriginZeroLine::clamped(line)
}
/// Find the `n`th line in `lines` (searching backwards) that is not after `last_line`.
///
/// If there are not enough such lines, then all implicit lines before the explicit grid are
/// assumed to be in `lines` for the purpose of counting
///
/// <https://drafts.csswg.org/css-grid-2/#grid-placement-int>
fn nth_line_backwards(&self, lines: &[u32], last_line: OriginZeroLine, n: i32) -> OriginZeroLine {
let last_line = last_line.0.min(self.last_explicit_line().0) as i32;
let lines = &lines[..lines.partition_point(|line| oz_line(*line) <= last_line)];
let line = match lines.len().checked_sub(n as usize) {
Some(index) => oz_line(lines[index]),
None => last_line.min(-1) - (n - lines.len() as i32) + 1,
};
OriginZeroLine::clamped(line)
}
}
/// The named line maps store lines as 1-based "CSS Grid Line" numbers (which are always within the
/// explicit grid). Convert one to OriginZero coordinates.
fn oz_line(line: u32) -> i32 {
line as i32 - 1
}
impl<S: CheapCloneStr> NamedLineResolver<S> {
/// Create and initialise a new `NamedLineResolver`
pub(crate) fn new(
style: &impl GridContainerStyle<CustomIdent = S>,
column_auto_repetitions: u16,
row_auto_repetitions: u16,
) -> Self {
let mut column_lines: NamedGridLinesMap<S> = Map::new();
let mut row_lines: NamedGridLinesMap<S> = Map::new();
let mut areas: GridAreasMap<S> = Map::new();
let mut column_line_name_pairs: Vec<(u32, S)> = Vec::new();
let mut row_line_name_pairs: Vec<(u32, S)> = Vec::new();
// The size of the area template may be larger than the extents of the named areas
// due to unnamed (`.`) cells, so it is taken from the style rather than being derived
// from the areas themselves.
let area_column_count = style.grid_template_area_column_count();
let area_row_count = style.grid_template_area_row_count();
if let Some(area_iter) = style.grid_template_areas() {
for area in area_iter.into_iter() {
let lines = AreaLines {
row_start: area.row_start as u32,
row_end: area.row_end as u32,
column_start: area.column_start as u32,
column_end: area.column_end as u32,
};
areas.insert(StrHasher(area.name.clone()), lines);
}
}
let mut current_line = 0;
if let Some(mut column_tracks) = style.grid_template_columns() {
if let Some(column_line_names_iter) = style.grid_template_column_names() {
for line_names in column_line_names_iter {
current_line += 1;
for line_name in line_names.into_iter() {
column_line_name_pairs.push((current_line, line_name.clone()));
upsert_line_name_map(
&mut column_lines,
&mut areas,
GridAreaAxis::Column,
line_name.clone(),
current_line,
);
}
if let Some(GenericGridTemplateComponent::Repeat(repeat)) = column_tracks.next() {
let repeat_count = match repeat.count() {
RepetitionCount::Count(count) => count,
RepetitionCount::AutoFill | RepetitionCount::AutoFit => column_auto_repetitions,
};
// Line name sets are positional: set `i` names the `i`th line of each
// repetition, and the final line name set of each repetition collapses
// with the first line name set of the following one. An empty list means
// the repetition's lines are unnamed; any other length must be exactly
// `track_count + 1` (one set per line, including both edge lines).
let line_name_set_count = repeat.lines_names().len() as u32;
let lines_per_repetition = repeat.track_count() as u32;
assert!(
line_name_set_count == 0 || line_name_set_count == lines_per_repetition + 1,
"grid template repetition must have no line name sets or exactly track count + 1 of them ({} tracks but {} line name sets)",
lines_per_repetition,
line_name_set_count,
);
for _ in 0..repeat_count {
for (line, line_name_set) in (current_line..).zip(repeat.lines_names()) {
for line_name in line_name_set {
column_line_name_pairs.push((line, line_name.clone()));
upsert_line_name_map(
&mut column_lines,
&mut areas,
GridAreaAxis::Column,
line_name.clone(),
line,
);
}
}
current_line += lines_per_repetition;
// Names for lines beyond the maximum track limit are never resolvable:
// stop generating them (the explicit grid is clamped to MAX_GRID_TRACKS)
if current_line > MAX_GRID_TRACKS as u32 {
break;
}
}
// Last line name set collapses with following line name set
if repeat_count > 0 {
current_line = current_line.saturating_sub(1);
}
}
}
}
}
let mut current_line = 0;
if let Some(mut row_tracks) = style.grid_template_rows() {
if let Some(row_line_names_iter) = style.grid_template_row_names() {
for line_names in row_line_names_iter {
current_line += 1;
for line_name in line_names.into_iter() {
row_line_name_pairs.push((current_line, line_name.clone()));
upsert_line_name_map(
&mut row_lines,
&mut areas,
GridAreaAxis::Row,
line_name.clone(),
current_line,
);
}
if let Some(GenericGridTemplateComponent::Repeat(repeat)) = row_tracks.next() {
let repeat_count = match repeat.count() {
RepetitionCount::Count(count) => count,
RepetitionCount::AutoFill | RepetitionCount::AutoFit => row_auto_repetitions,
};
// Line name sets are positional: set `i` names the `i`th line of each
// repetition, and the final line name set of each repetition collapses
// with the first line name set of the following one. An empty list means
// the repetition's lines are unnamed; any other length must be exactly
// `track_count + 1` (one set per line, including both edge lines).
let line_name_set_count = repeat.lines_names().len() as u32;
let lines_per_repetition = repeat.track_count() as u32;
assert!(
line_name_set_count == 0 || line_name_set_count == lines_per_repetition + 1,
"grid template repetition must have no line name sets or exactly track count + 1 of them ({} tracks but {} line name sets)",
lines_per_repetition,
line_name_set_count,
);
for _ in 0..repeat_count {
for (line, line_name_set) in (current_line..).zip(repeat.lines_names()) {
for line_name in line_name_set {
row_line_name_pairs.push((line, line_name.clone()));
upsert_line_name_map(
&mut row_lines,
&mut areas,
GridAreaAxis::Row,
line_name.clone(),
line,
);
}
}
current_line += lines_per_repetition;
// Names for lines beyond the maximum track limit are never resolvable:
// stop generating them (the explicit grid is clamped to MAX_GRID_TRACKS)
if current_line > MAX_GRID_TRACKS as u32 {
break;
}
}
// Last line name set collapses with following line name set
if repeat_count > 0 {
current_line = current_line.saturating_sub(1);
}
}
}
}
}
// Sort and dedup lines for each column name
for lines in column_lines.values_mut() {
lines.sort_unstable();
lines.dedup();
}
// Sort and dedup lines for each row name
for lines in row_lines.values_mut() {
lines.sort_unstable();
lines.dedup();
}
Self {
area_column_count,
area_row_count,
explicit_column_count: 0, // Overwritten later
explicit_row_count: 0, // Overwritten later
row_lines,
column_lines,
areas,
column_line_name_pairs,
row_line_name_pairs,
}
}
/// Build the per-line name groups of the explicit grid in the passed axis as a
/// [`GridLineNames`], with `repeat()`s expanded. Only names given explicitly in the track
/// template are included; the implicit `<name>-start`/`<name>-end` names generated by
/// `grid-template-areas` are omitted (matching the resolved value of
/// `grid-template-rows`/`grid-template-columns` in browsers) but remain resolvable for
/// placement via [`GridLineNames::resolve_line_names`].
///
/// Line indices are relative to the explicit grid (line 0 = start of the first explicit track).
pub(crate) fn detailed_line_names(&self, axis: AbsoluteAxis) -> GridLineNames<S> {
let (pairs, explicit_track_count) = match axis {
AbsoluteAxis::Horizontal => (&self.column_line_name_pairs, self.explicit_column_count),
AbsoluteAxis::Vertical => (&self.row_line_name_pairs, self.explicit_row_count),
};
if pairs.is_empty() {
return GridLineNames::default();
}
// Stable sort by line number preserves the source order of names within each line
let mut sorted_pairs: Vec<&(u32, S)> = pairs.iter().collect();
sorted_pairs.sort_by_key(|(line, _)| *line);
let line_count = explicit_track_count as usize + 1;
let mut line_names = GridLineNames::with_capacity(sorted_pairs.len(), line_count + 1);
let mut pair_iter = sorted_pairs.into_iter().peekable();
for line in 1..=(line_count as u32) {
line_names.start_line();
while let Some(&&(pair_line, ref name)) = pair_iter.peek() {
if pair_line != line {
break;
}
pair_iter.next();
if !line_names.current_line_contains(name.as_ref()) {
line_names.push_name(name.clone());
}
}
}
line_names
}
/// Resolve named lines for both the `start` and `end` of a row-axis grid placement
#[inline(always)]
pub(crate) fn resolve_row_names(&self, line: &Line<GridPlacement<S>>) -> Line<NonNamedGridPlacement> {
self.resolve_line_names(line, GridAreaAxis::Row)
}
/// Resolve named lines for both the `start` and `end` of a column-axis grid placement
#[inline(always)]
pub(crate) fn resolve_column_names(&self, line: &Line<GridPlacement<S>>) -> Line<NonNamedGridPlacement> {
self.resolve_line_names(line, GridAreaAxis::Column)
}
/// Resolve named lines for both the `start` and `end` of a grid placement
#[inline(always)]
pub(crate) fn resolve_line_names(
&self,
line: &Line<GridPlacement<S>>,
axis: GridAreaAxis,
) -> Line<NonNamedGridPlacement> {
let (lines, explicit_track_count) = match axis {
GridAreaAxis::Row => (&self.row_lines, self.explicit_row_count),
GridAreaAxis::Column => (&self.column_lines, self.explicit_column_count),
};
NamedLineResolverAxis { lines, areas: &self.areas, axis, explicit_track_count }.resolve_line_names(line)
}
/// Move the row and column line-name maps into the detailed grid information, and return the grid area map
/// for the same purpose
pub(crate) fn populate_detailed_line_resolvers(
self,
rows: &mut GridLineNames<S>,
columns: &mut GridLineNames<S>,
) -> GridAreasMap<S> {
rows.resolver = self.row_lines;
columns.resolver = self.column_lines;
self.areas
}
/// Get the number of columns defined by the grid areas
pub(crate) fn area_column_count(&self) -> u16 {
self.area_column_count
}
/// Get the number of rows defined by the grid areas
pub(crate) fn area_row_count(&self) -> u16 {
self.area_row_count
}
/// Set the number of columns in the explicit grid
pub(crate) fn set_explicit_column_count(&mut self, count: u16) {
self.explicit_column_count = count;
}
/// Set the number of rows in the explicit grid
pub(crate) fn set_explicit_row_count(&mut self, count: u16) {
self.explicit_row_count = count;
}
}
impl<S: CheapCloneStr> Debug for NamedLineResolver<S> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "Grid Areas (row-start / column-start / row-end / column-end):")?;
for (name, area) in self.areas.iter() {
let AreaLines { row_start, column_start, row_end, column_end } = area;
writeln!(f, "{}: {row_start} / {column_start} / {row_end} / {column_end}", name.0.as_ref())?;
}
writeln!(f, "Grid Rows:")?;
for (name, lines) in self.row_lines.iter() {
write!(f, "{}: ", name.0.as_ref())?;
for line in lines {
write!(f, "{line} ")?;
}
writeln!(f)?;
}
writeln!(f, "Grid Columns:")?;
for (name, lines) in self.column_lines.iter() {
write!(f, "{}: ", name.0.as_ref())?;
for line in lines {
write!(f, "{line} ")?;
}
writeln!(f)?;
}
Ok(())
}
}
/// The names of each explicit grid line in a single axis, stored in CSR (compressed sparse
/// row) format: a single flat `Vec` of names plus a `Vec` of offsets into it (one more offset
/// than there are lines). The names of line `i` (0-indexed) are `names[offsets[i]..offsets[i + 1]]`.
///
/// Line indices here are relative to the explicit grid;
/// [`DetailedGridTracksInfo`](crate::DetailedGridTracksInfo) provides accessors with indices
/// relative to the full grid (including implicit tracks).
///
/// Iterate over per-line name groups with [`GridLineNames::iter`], or access a single line's
/// names with [`GridLineNames::line`]. A grid with no named lines is represented by two empty
/// `Vec`s (see [`GridLineNames::is_empty`]).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct GridLineNames<S: CheapCloneStr = DefaultCheapStr> {
/// The names of every grid line in the axis, concatenated in line order
names: Vec<S>,
/// Offsets into `names`: line `i`'s names are `names[offsets[i]..offsets[i + 1]]`.
/// Either empty (no named lines) or of length `line count + 1`.
offsets: Vec<u32>,
/// Named line lookup used to resolve arbitrary grid placements
resolver: NamedGridLinesMap<S>,
}
impl<S: CheapCloneStr> GridLineNames<S> {
/// Create an empty `GridLineNames` with pre-allocated capacity
pub(crate) fn with_capacity(name_capacity: usize, offset_capacity: usize) -> Self {
let mut offsets = Vec::with_capacity(offset_capacity);
offsets.push(0);
Self { names: Vec::with_capacity(name_capacity), offsets, resolver: Map::new() }
}
/// Start a new (initially empty) line
pub(crate) fn start_line(&mut self) {
self.offsets.push(self.names.len() as u32);
}
/// Append a name to the current (last) line
pub(crate) fn push_name(&mut self, name: S) {
self.names.push(name);
*self.offsets.last_mut().unwrap() = self.names.len() as u32;
}
/// Whether the current (last) line already contains the passed name
pub(crate) fn current_line_contains(&self, name: &str) -> bool {
self.line(self.line_count().wrapping_sub(1)).iter().any(|n| n.as_ref() == name)
}
/// Resolve named lines and spans using the retained line-name map and the passed grid area map
pub(crate) fn resolve_line_names(
&self,
line: &Line<GridPlacement<S>>,
areas: &GridAreasMap<S>,
axis: GridAreaAxis,
explicit_track_count: u16,
) -> Line<NonNamedGridPlacement> {
NamedLineResolverAxis { lines: &self.resolver, areas, axis, explicit_track_count }.resolve_line_names(line)
}
/// Whether the axis has any named lines at all
pub fn is_empty(&self) -> bool {
self.names.is_empty()
}
/// The number of grid lines represented (zero if the grid has no named lines)
pub fn line_count(&self) -> usize {
self.offsets.len().saturating_sub(1)
}
/// The names of the line with the passed 0-indexed line index.
/// Returns an empty slice if the line has no names or the index is out of range.
pub fn line(&self, line_index: usize) -> &[S] {
match (self.offsets.get(line_index), self.offsets.get(line_index + 1)) {
(Some(&start), Some(&end)) => &self.names[start as usize..end as usize],
_ => &[],
}
}
/// Iterate over the name group (`&[S]`) of each grid line in line order
pub fn iter(&self) -> GridLineNamesIter<'_, S> {
self.iter_padded(0, 0)
}
/// Iterate over the name group (`&[S]`) of each grid line in line order, additionally
/// yielding `leading_empty` empty groups before the stored lines and `trailing_empty`
/// empty groups after them (representing unnamed implicit grid lines)
pub(crate) fn iter_padded(&self, leading_empty: usize, trailing_empty: usize) -> GridLineNamesIter<'_, S> {
GridLineNamesIter { names: &self.names, offsets: self.offsets.windows(2), leading_empty, trailing_empty }
}
}
impl<'a, S: CheapCloneStr> IntoIterator for &'a GridLineNames<S> {
type Item = &'a [S];
type IntoIter = GridLineNamesIter<'a, S>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// Iterator over the per-line name groups of a [`GridLineNames`]. Yields one `&[S]` per grid
/// line (which is empty for unnamed lines)
#[derive(Debug, Clone)]
pub struct GridLineNamesIter<'a, S: CheapCloneStr> {
/// The flat name storage being iterated over
names: &'a [S],
/// Iterator over adjacent pairs of offsets into `names`
offsets: core::slice::Windows<'a, u32>,
/// Number of (unnamed, implicit) lines remaining before the stored lines
leading_empty: usize,
/// Number of (unnamed, implicit) lines remaining after the stored lines
trailing_empty: usize,
}
impl<'a, S: CheapCloneStr> Iterator for GridLineNamesIter<'a, S> {
type Item = &'a [S];
fn next(&mut self) -> Option<Self::Item> {
if self.leading_empty > 0 {
self.leading_empty -= 1;
return Some(&[]);
}
if let Some(window) = self.offsets.next() {
return Some(&self.names[window[0] as usize..window[1] as usize]);
}
if self.trailing_empty > 0 {
self.trailing_empty -= 1;
return Some(&[]);
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.leading_empty + self.offsets.len() + self.trailing_empty;
(len, Some(len))
}
}
impl<S: CheapCloneStr> ExactSizeIterator for GridLineNamesIter<'_, S> {}
#[cfg(test)]
mod tests {
use super::super::{MAX_OZ_LINE, MIN_OZ_LINE};
use super::*;
use crate::style::GenericGridPlacement;
use crate::sys::DefaultCheapStr;
use crate::GridTemplateAreas;
use crate::Style;
use crate::{GridTemplateArea, NonNamedGridPlacement};
fn resolver(explicit_track_count: u16) -> NamedLineResolver<DefaultCheapStr> {
let mut resolver = NamedLineResolver::new(&Style::DEFAULT, 0, 0);
resolver.set_explicit_column_count(explicit_track_count);
resolver
}
fn resolved_start_line(
resolver: &NamedLineResolver<DefaultCheapStr>,
placement: GridPlacement<DefaultCheapStr>,
) -> i16 {
let resolved = resolver.resolve_column_names(&Line { start: placement, end: GridPlacement::Auto });
match resolved.start {
GenericGridPlacement::Line(line) => line.as_i16(),
_ => panic!("expected a resolved line"),
}
}
#[test]
fn extreme_missing_named_line_indices_do_not_overflow() {
// Lines are clamped to the limits of the grid, in the same way as `GridLine::into_origin_zero_line`
let resolver = resolver(10_000);
assert_eq!(
resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("missing"), i16::MAX)),
OriginZeroLine(MAX_OZ_LINE).into_grid_line(10_000).as_i16()
);
assert_eq!(
resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("missing"), i16::MIN)),
OriginZeroLine(MIN_OZ_LINE).into_grid_line(10_000).as_i16()
);
}
#[test]
fn large_named_span_does_not_wrap_negative() {
let resolver = resolver(10_000);
let resolved = resolver.resolve_column_names(&Line {
start: GridPlacement::Line(GridLine::from(1)),
end: GridPlacement::NamedSpan(DefaultCheapStr::from("missing"), u16::MAX),
});
match resolved.end {
GenericGridPlacement::Line(line) => assert_eq!(line, OriginZeroLine(MAX_OZ_LINE).into_grid_line(10_000)),
_ => panic!("expected a resolved line"),
}
}
#[test]
fn area_lines_saturate_when_converted_to_grid_lines() {
let style = Style {
grid_template_areas: Some(GridTemplateAreas {
areas: vec![GridTemplateArea {
name: DefaultCheapStr::from("area"),
row_start: 1,
row_end: 2,
column_start: u16::MAX,
column_end: u16::MAX,
}],
row_count: 1,
column_count: u16::MAX,
}),
..Style::DEFAULT
};
let resolver = NamedLineResolver::new(&style, 0, 0);
assert_eq!(
resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("area-start"), 1)),
OriginZeroLine(MAX_OZ_LINE).into_grid_line(0).as_i16()
);
assert_eq!(
resolved_start_line(&resolver, GridPlacement::NamedLine(DefaultCheapStr::from("area"), 0)),
OriginZeroLine(MAX_OZ_LINE).into_grid_line(0).as_i16()
);
}
/// A resolver for a grid with 4 explicit columns, the passed names for each of the 5 column lines, and a
/// single grid area named "area" which spans columns 2 and 3 (lines 2 to 4)
fn area_resolver(column_line_names: [&[&str]; 5]) -> NamedLineResolver<DefaultCheapStr> {
let style = Style {
grid_template_column_names: column_line_names
.iter()
.map(|names| names.iter().map(|name| DefaultCheapStr::from(*name)).collect())
.collect(),
grid_template_areas: Some(GridTemplateAreas {
areas: vec![GridTemplateArea {
name: DefaultCheapStr::from("area"),
row_start: 1,
row_end: 2,
column_start: 2,
column_end: 4,
}],
row_count: 1,
column_count: 4,
}),
..Style::DEFAULT
};
let mut resolver = NamedLineResolver::new(&style, 0, 0);
resolver.set_explicit_column_count(4);
resolver.set_explicit_row_count(1);
resolver
}
fn named_line(name: &str, index: i16) -> GridPlacement<DefaultCheapStr> {
GridPlacement::NamedLine(DefaultCheapStr::from(name), index)
}
fn resolved_end_line(
resolver: &NamedLineResolver<DefaultCheapStr>,
placement: GridPlacement<DefaultCheapStr>,
) -> i16 {
let resolved = resolver.resolve_column_names(&Line { start: GridPlacement::Auto, end: placement });
match resolved.end {
GenericGridPlacement::Line(line) => line.as_i16(),
_ => panic!("expected a resolved line"),
}
}
#[test]
fn bare_ident_resolves_to_area_edge() {
let resolver = area_resolver([&[], &[], &[], &[], &[]]);
assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 2);
assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
let rows = resolver.resolve_row_names(&Line { start: named_line("area", 0), end: named_line("area", 0) });
assert_eq!(rows.start, NonNamedGridPlacement::Line(GridLine::from(1)));
assert_eq!(rows.end, NonNamedGridPlacement::Line(GridLine::from(2)));
}
#[test]
fn bare_ident_resolves_to_edge_of_implicitly_named_area() {
let resolver = area_resolver([&[], &["foo-start"], &["foo-start"], &["foo-end"], &["foo-end"]]);
assert_eq!(resolved_start_line(&resolver, named_line("foo", 0)), 2);
assert_eq!(resolved_end_line(&resolver, named_line("foo", 0)), 4);
}
#[test]
fn area_edges_are_lines_named_with_start_and_end_suffixes() {
let resolver = area_resolver([&[], &[], &[], &[], &[]]);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 0)), 2);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 2);
assert_eq!(resolved_start_line(&resolver, named_line("area-end", 1)), 4);
assert_eq!(resolved_start_line(&resolver, named_line("area-end", -1)), 4);
// There is only one such line, so the second is the first implicit line after the grid
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 6);
}
#[test]
fn area_edges_are_merged_with_explicitly_named_lines() {
// The area's start edge is line 2 and its end edge is line 4
let resolver = area_resolver([&["area-start"], &[], &["area-start"], &["area-end"], &["area-end"]]);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 1);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 2);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 3)), 3);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", -1)), 3);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 4)), 6);
// The area's end edge has the same line number as an explicitly named line
assert_eq!(resolved_start_line(&resolver, named_line("area-end", 1)), 4);
assert_eq!(resolved_start_line(&resolver, named_line("area-end", 2)), 5);
assert_eq!(resolved_start_line(&resolver, named_line("area-end", 3)), 6);
// A bare ident matches the first line of the edge
assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 1);
assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
let span = resolver.resolve_column_names(&Line {
start: GridPlacement::Line(GridLine::from(1)),
end: GridPlacement::NamedSpan(DefaultCheapStr::from("area-start"), 2),
});
assert_eq!(span.end, NonNamedGridPlacement::Line(GridLine::from(3)));
}
#[test]
fn area_edges_are_only_matched_by_bare_idents() {
let resolver = area_resolver([&[], &[], &[], &[], &[]]);
// There are no lines named "area", so these resolve to implicit lines after the grid
assert_eq!(resolved_start_line(&resolver, named_line("area", 1)), 6);
assert_eq!(resolved_start_line(&resolver, named_line("area", 2)), 7);
let span = resolver.resolve_column_names(&Line {
start: GridPlacement::Line(GridLine::from(1)),
end: GridPlacement::NamedSpan(DefaultCheapStr::from("area"), 0),
});
assert_eq!(span.end, NonNamedGridPlacement::Line(GridLine::from(6)));
}
#[test]
fn area_edge_is_the_first_line_with_the_edge_name() {
// Explicit lines named after the area's edges which come after the area's generated lines (lines 2 and
// 4) don't replace them
let resolver = area_resolver([&[], &[], &["area-start"], &[], &["area-end"]]);
assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 2);
assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 2);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 3);
assert_eq!(resolved_start_line(&resolver, named_line("area-end", 2)), 5);
// An explicit line with the same number as the generated line is the same line
let resolver = area_resolver([&[], &["area-start"], &[], &["area-end"], &[]]);
assert_eq!(resolved_start_line(&resolver, named_line("area", 0)), 2);
assert_eq!(resolved_end_line(&resolver, named_line("area", 0)), 4);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 1)), 2);
assert_eq!(resolved_start_line(&resolver, named_line("area-start", 2)), 6);
assert_eq!(resolved_start_line(&resolver, named_line("area-end", 2)), 6);
}
}
+6
View File
@@ -0,0 +1,6 @@
//! Utility functions used within the grid module
#[cfg(test)]
pub(super) mod test_helpers;
#[cfg(test)]
pub(super) use test_helpers::{CreateChildTestNode, CreateExpectedPlacement, CreateParentTestNode};
+78
View File
@@ -0,0 +1,78 @@
//! Helpers for use in unit tests within the grid module
use super::super::types::{GridItem, NamedLineResolver};
use super::super::{ItemPlacement, OriginZeroLine};
use crate::geometry::InBothAbsAxis;
use crate::prelude::*;
use crate::style::{Dimension, GridPlacement, Style};
use crate::util::sys::Vec;
/// Create a `GridItem` (with start alignment) for each `(index, style)` pair, as `compute_grid_layout` does
/// for the in-flow children of a grid container
pub(crate) fn grid_items<'a>(children: impl Iterator<Item = (usize, &'a Style)>) -> Vec<GridItem> {
children
.map(|(index, style)| {
GridItem::new_with_style_and_order(
NodeId::from(index),
style,
AlignSelf::START,
AlignSelf::START,
index as u16,
)
})
.collect()
}
/// Resolve the named lines in the `grid-row`/`grid-column` styles of the given child styles (and convert them to
/// origin-zero coordinates), as `compute_grid_layout` does before estimating the grid size and placing items
pub(crate) fn resolve_named_lines<'a>(
child_styles: impl Iterator<Item = &'a Style>,
name_resolver: &NamedLineResolver<String>,
explicit_col_count: u16,
explicit_row_count: u16,
) -> Vec<ItemPlacement> {
child_styles
.map(|style| InBothAbsAxis {
horizontal: name_resolver.resolve_column_names(&style.grid_column).into_origin_zero(explicit_col_count),
vertical: name_resolver.resolve_row_names(&style.grid_row).into_origin_zero(explicit_row_count),
})
.collect()
}
pub(crate) trait CreateParentTestNode {
fn into_grid(self) -> Style;
}
impl CreateParentTestNode for (f32, f32, i32, i32) {
fn into_grid(self) -> Style {
Style {
display: Display::Grid,
size: Size { width: Dimension::from_length(self.0), height: Dimension::from_length(self.1) },
grid_template_columns: vec![fr(1f32); self.2 as usize],
grid_template_rows: vec![fr(1f32); self.3 as usize],
..Default::default()
}
}
}
pub(crate) trait CreateChildTestNode {
fn into_grid_child(self) -> Style;
}
impl CreateChildTestNode
for (GridPlacement<String>, GridPlacement<String>, GridPlacement<String>, GridPlacement<String>)
{
fn into_grid_child(self) -> Style<String> {
Style {
display: Display::Grid,
grid_column: Line { start: self.0, end: self.1 },
grid_row: Line { start: self.2, end: self.3 },
..Default::default()
}
}
}
pub(crate) trait CreateExpectedPlacement {
fn into_oz(self) -> (OriginZeroLine, OriginZeroLine, OriginZeroLine, OriginZeroLine);
}
impl CreateExpectedPlacement for (i16, i16, i16, i16) {
fn into_oz(self) -> (OriginZeroLine, OriginZeroLine, OriginZeroLine, OriginZeroLine) {
(OriginZeroLine(self.0), OriginZeroLine(self.1), OriginZeroLine(self.2), OriginZeroLine(self.3))
}
}
+188
View File
@@ -0,0 +1,188 @@
//! Computes size using styles and measure functions
#[cfg(feature = "content_size")]
use crate::geometry::Rect;
use crate::geometry::Size;
use crate::style::{AvailableSpace, Overflow};
use crate::tree::{Baselines, CollapsibleMarginSet, RunMode};
use crate::tree::{LayoutInput, LayoutOutput, SizingMode};
use crate::util::debug::debug_log;
use crate::util::sys::f32_max;
use crate::util::MaybeMath;
use crate::util::{MaybeResolve, ResolveOrZero};
use crate::{BoxSizing, CoreStyle};
use core::unreachable;
/// Compute the size of a leaf node (node with no children)
///
/// A definite `inputs.available_space` is treated as the space available to the node's border box:
/// the caller is expected to have already subtracted the node's margins from it.
pub fn compute_leaf_layout<MeasureFunction>(
inputs: LayoutInput,
style: &impl CoreStyle,
resolve_calc_value: impl Fn(*const (), f32) -> f32,
measure_function: MeasureFunction,
) -> LayoutOutput
where
MeasureFunction: FnOnce(Size<Option<f32>>, Size<AvailableSpace>) -> Size<f32>,
{
let LayoutInput { known_dimensions, parent_size, available_space, sizing_mode, run_mode, .. } = inputs;
// Note: both horizontal and vertical percentage padding/borders are resolved against the container's inline size (i.e. width).
// This is not a bug, but is how CSS is specified (see: https://developer.mozilla.org/en-US/docs/Web/CSS/padding#values)
let padding = style.padding().resolve_or_zero(parent_size.width, &resolve_calc_value);
let border = style.border().resolve_or_zero(parent_size.width, &resolve_calc_value);
let padding_border = padding + border;
let pb_sum = padding_border.sum_axes();
let box_sizing_adjustment = if style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
// Resolve node's preferred/min/max sizes (width/heights) against the available space (percentages resolve to pixel values)
// For ContentSize mode, we pretend that the node has no size styles as these should be ignored.
let (node_size, node_min_size, node_max_size, aspect_ratio) = match sizing_mode {
SizingMode::ContentSize => {
let node_size = known_dimensions;
let node_min_size = Size::NONE;
let node_max_size = Size::NONE;
(node_size, node_min_size, node_max_size, None)
}
SizingMode::InherentSize => {
let aspect_ratio = style.aspect_ratio();
let style_size = style
.size()
.maybe_resolve(parent_size, &resolve_calc_value)
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let style_min_size = style
.min_size()
.maybe_resolve(parent_size, &resolve_calc_value)
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let style_max_size =
style.max_size().maybe_resolve(parent_size, &resolve_calc_value).maybe_add(box_sizing_adjustment);
let node_size = known_dimensions.or(style_size);
(node_size, style_min_size, style_max_size, aspect_ratio)
}
};
// Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
// However, the axis are switched (transposed) because a node that scrolls vertically needs
// *horizontal* space to be reserved for a scrollbar
let scrollbar_gutter = style.overflow().transpose().map(|overflow| match overflow {
Overflow::Scroll => style.scrollbar_width(),
_ => 0.0,
});
// TODO: make side configurable based on the `direction` property
let mut content_box_inset = padding_border;
content_box_inset.right += scrollbar_gutter.x;
content_box_inset.bottom += scrollbar_gutter.y;
let has_styles_preventing_being_collapsed_through = !style.is_block()
|| style.overflow().x.is_scroll_container()
|| style.overflow().y.is_scroll_container()
|| style.position().is_out_of_flow()
|| style.contain().establishes_independent_formatting_context()
|| padding.top > 0.0
|| padding.bottom > 0.0
|| border.top > 0.0
|| border.bottom > 0.0
|| matches!(node_size.height, Some(h) if h > 0.0)
|| matches!(node_min_size.height, Some(h) if h > 0.0);
debug_log!("LEAF");
debug_log!("node_size", dbg:node_size);
debug_log!("min_size ", dbg:node_min_size);
debug_log!("max_size ", dbg:node_max_size);
// Return early if both width and height are known
if run_mode == RunMode::ComputeSize && has_styles_preventing_being_collapsed_through {
if let Size { width: Some(width), height: Some(height) } = node_size {
let size = Size { width, height }
.maybe_clamp(node_min_size, node_max_size)
.maybe_max(padding_border.sum_axes().map(Some));
return LayoutOutput {
size,
#[cfg(feature = "content_size")]
scrollable_overflow_rect: Rect::ZERO,
baselines: Baselines::NONE,
top_margin: CollapsibleMarginSet::ZERO,
bottom_margin: CollapsibleMarginSet::ZERO,
margins_can_collapse_through: false,
oof_candidates: crate::tree::OofCandidates::NONE,
oof_positioning_area: None,
};
};
}
// Compute available space
let available_space = Size {
width: known_dimensions
.width
.map(AvailableSpace::from)
.unwrap_or(available_space.width)
.maybe_set(known_dimensions.width)
.maybe_set(node_size.width)
.map_definite_value(|size| {
size.maybe_clamp(node_min_size.width, node_max_size.width) - content_box_inset.horizontal_axis_sum()
}),
height: known_dimensions
.height
.map(AvailableSpace::from)
.unwrap_or(available_space.height)
.maybe_set(known_dimensions.height)
.maybe_set(node_size.height)
.map_definite_value(|size| {
size.maybe_clamp(node_min_size.height, node_max_size.height) - content_box_inset.vertical_axis_sum()
}),
};
// Measure node
let measured_size = measure_function(
match run_mode {
RunMode::ComputeSize => known_dimensions,
RunMode::PerformLayout => Size::NONE,
RunMode::PerformHiddenLayout => unreachable!(),
},
available_space,
);
let clamped_size = known_dimensions
.or(node_size)
.unwrap_or(measured_size + content_box_inset.sum_axes())
.maybe_clamp(node_min_size, node_max_size);
let size = Size {
width: clamped_size.width,
height: f32_max(clamped_size.height, aspect_ratio.map(|ratio| clamped_size.width / ratio).unwrap_or(0.0)),
};
let size = size.maybe_max(padding_border.sum_axes().map(Some));
// A scroll container's own padding at the end of the content is part of its scrollable
// overflow region, so it is included in the overflow rect. Boxes that are not scroll
// containers do not extend their overflow region by their own padding.
#[cfg(feature = "content_size")]
let scrollable_overflow_rect = {
let is_scroll_container = style.overflow().x.is_scroll_container() || style.overflow().y.is_scroll_container();
let is_rtl = style.direction().is_rtl();
let start_padding = if is_rtl { padding.right } else { padding.left };
let end_padding = if is_rtl { padding.left } else { padding.right };
Rect {
left: 0.0,
right: start_padding + measured_size.width + if is_scroll_container { end_padding } else { 0.0 },
top: 0.0,
bottom: padding.top + measured_size.height + if is_scroll_container { padding.bottom } else { 0.0 },
}
};
LayoutOutput {
size,
#[cfg(feature = "content_size")]
scrollable_overflow_rect,
baselines: Baselines::NONE,
top_margin: CollapsibleMarginSet::ZERO,
bottom_margin: CollapsibleMarginSet::ZERO,
margins_can_collapse_through: !has_styles_preventing_being_collapsed_through
&& size.height == 0.0
&& measured_size.height == 0.0,
oof_candidates: crate::tree::OofCandidates::NONE,
oof_positioning_area: None,
}
}
+516
View File
@@ -0,0 +1,516 @@
//! Low-level access to the layout algorithms themselves. For a higher-level API, see the [`TaffyTree`](crate::TaffyTree) struct.
//!
//! ### Layout functions
//!
//! The layout functions all take an [`&mut impl LayoutPartialTree`](crate::LayoutPartialTree) parameter, which represents a single container node and it's direct children.
//!
//! | Function | Purpose |
//! | --- | --- |
//! | [`compute_flexbox_layout`] | Layout a Flexbox container and it's direct children |
//! | [`compute_grid_layout`] | Layout a CSS Grid container and it's direct children |
//! | [`compute_block_layout`] | Layout a Block container and it's direct children |
//! | [`compute_leaf_layout`] | Applies common properties like padding/border/aspect-ratio to a node before deferring to a passed closure to determine it's size. Can be applied to nodes like text or image nodes. |
//! | [`compute_root_layout`] | Layout the root node of a tree (regardless of it's layout mode). This function is typically called once to begin a layout run. | |
//! | [`compute_hidden_layout`] | Mark a node as hidden during layout (like `Display::None`) |
//! | [`compute_cached_layout`] | Attempts to find a cached layout for the specified node and layout inputs. Uses the provided closure to compute the layout (and then stores the result in the cache) if no cached layout is found. |
//!
//! ### Other functions
//!
//! | Function | Requires | Purpose |
//! | --- | --- | --- |
//! | [`round_layout`] | [`RoundTree`] | Round a tree of float-valued layouts to integer pixels |
//! | [`print_tree`](crate::print_tree) | [`PrintTree`](crate::PrintTree) | Print a debug representation of a node tree and it's computed layout |
//!
pub(crate) mod common;
pub(crate) mod leaf;
pub(crate) mod oof;
#[cfg(feature = "block_layout")]
pub(crate) mod block;
#[cfg(feature = "float_layout")]
pub(crate) mod float;
#[cfg(feature = "flexbox")]
pub(crate) mod flexbox;
#[cfg(feature = "grid")]
pub(crate) mod grid;
pub use leaf::compute_leaf_layout;
pub use oof::{compute_oof_layout, compute_oof_layout_for_area, resolve_static_offset, OofLayoutResult};
#[cfg(feature = "block_layout")]
pub use self::block::{compute_block_align_content_offset, compute_block_layout, BlockContext, BlockFormattingContext};
#[cfg(feature = "flexbox")]
pub use self::flexbox::compute_flexbox_layout;
#[cfg(feature = "grid")]
pub use self::grid::compute_grid_layout;
#[cfg(feature = "float_layout")]
pub use self::float::{BfcSlot, ContentSlot, FloatContext, FloatIntrinsicWidthCalculator};
use crate::geometry::{Line, Point, Size};
use crate::style::{AvailableSpace, ContainingBlockClaims, CoreStyle, Overflow, Position};
use crate::tree::{
AxisStaticAlign, AxisStaticEdge, AxisStaticPosition, Layout, LayoutInput, LayoutOutput, LayoutPartialTree,
LayoutPartialTreeExt, NodeId, OofCandidate, OofCandidates, RequestedAxis, RoundTree, RunMode, SizingMode,
};
use crate::util::debug::{debug_log, debug_log_node, debug_pop_node, debug_push_node};
use crate::util::sys::{round, Vec};
use crate::util::ResolveOrZero;
use crate::{CacheTree, MaybeMath, MaybeResolve};
/// Compute layout for the root node in the tree
///
/// The root's containing block is the initial containing block (ICB), which has the dimensions of the
/// viewport (`available_space`) and is anchored at the canvas origin. The root's `position` and `inset`
/// styles are resolved against it:
///
/// - A `position: absolute`/`fixed` root is laid out by the out-of-flow positioning routine used for
/// every other out-of-flow box (insets, shrink-to-fit sizing, auto margins, ...), with its static
/// position at the ICB origin. This requires a definite `available_space` in both axes: otherwise there
/// is no ICB to resolve against and the root is laid out as if it were in flow.
/// - A `position: relative` root is laid out in flow and then offset by its insets.
pub fn compute_root_layout(
tree: &mut (impl crate::tree::LayoutContainingBlock + CacheTree),
root: NodeId,
available_space: Size<AvailableSpace>,
) {
let style = tree.get_core_container_style(root);
let position = style.position();
let direction = style.direction();
drop(style);
let icb_size = available_space.into_options();
let oof_root_area = match (position.is_out_of_flow(), icb_size.width, icb_size.height) {
(true, Some(width), Some(height)) => Some(Size { width, height }),
_ => None,
};
// When the root's layout is served from the cache its layout algorithm does not run, so the
// hoisted children it recorded on a previous run (including those added by the root
// positioning pass below) are still in place and must not be re-added.
let mut root_is_cached = false;
let (layout, candidates) = if let Some(area_size) = oof_root_area {
// The static position of the root places its margin box at the origin of the ICB
let (start, end) = if direction.is_rtl() { (area_size.width, area_size.width) } else { (0.0, 0.0) };
let candidate = OofCandidate {
node: root,
order: 0,
position,
static_position: Point {
x: AxisStaticPosition {
area: Line { start, end },
align: AxisStaticAlign::from_keyword(if direction.is_rtl() {
AxisStaticEdge::End
} else {
AxisStaticEdge::Start
}),
},
y: AxisStaticPosition::from_edge(0.0, AxisStaticEdge::Start),
},
};
let oof::OofBoxLayout { layout, surfaced, .. } = oof::layout_oof_box(
tree,
candidate,
area_size,
Point::ZERO,
direction,
// The initial containing block is not a scroll container
Point { x: Overflow::Visible, y: Overflow::Visible },
#[cfg(feature = "grid")]
None,
|tree, inputs| root_is_cached = tree.cache_get(root, inputs).is_some(),
);
(layout, surfaced)
} else {
compute_in_flow_root_layout(tree, root, available_space, &mut root_is_cached)
};
// Final positioning pass for out-of-flow boxes with no nearer containing block: the initial
// containing block is the containing block for `position: fixed` boxes and for
// `position: absolute` boxes with no positioned ancestor.
if !candidates.is_empty() {
let overflow = tree.get_core_container_style(root).overflow();
// The initial containing block has the dimensions of the viewport (the available space) and is
// anchored at the canvas origin. In an axis where the available space is indefinite, fall back
// to the root's padding box.
let area_inset = layout.border
+ crate::geometry::Rect {
left: 0.0,
right: layout.scrollbar_size.width,
top: 0.0,
bottom: layout.scrollbar_size.height,
};
let root_padding_box_size =
layout.size - Size { width: area_inset.horizontal_axis_sum(), height: area_inset.vertical_axis_sum() };
let (area_width, area_x) = match icb_size.width {
Some(width) => ((width - layout.scrollbar_size.width).max(0.0), -layout.location.x),
None => (root_padding_box_size.width, area_inset.left),
};
let (area_height, area_y) = match icb_size.height {
Some(height) => ((height - layout.scrollbar_size.height).max(0.0), -layout.location.y),
None => (root_padding_box_size.height, area_inset.top),
};
let area_size = Size { width: area_width, height: area_height };
let area_offset = Point { x: area_x, y: area_y };
let mut hoisted: Vec<NodeId> = Vec::new();
let mut unclaimed = OofCandidates::new();
oof::perform_oof_layout(
tree,
root,
candidates.as_slice(),
area_size,
area_offset,
direction,
// The root is the initial containing block and claims all remaining candidates
ContainingBlockClaims::ALL,
overflow,
&mut hoisted,
&mut unclaimed,
);
debug_assert!(unclaimed.is_empty(), "the root positioning pass must claim all remaining candidates");
if !root_is_cached {
tree.add_hoisted_children(root, &hoisted);
}
}
}
/// Lay out an in-flow (or `position: relative`) root node against the available space, store its layout
/// and return it along with the out-of-flow candidates bubbled up from its subtree.
#[inline(always)]
fn compute_in_flow_root_layout(
tree: &mut (impl crate::tree::LayoutContainingBlock + CacheTree),
root: NodeId,
available_space: Size<AvailableSpace>,
root_is_cached: &mut bool,
) -> (Layout, OofCandidates) {
let mut known_dimensions = Size::NONE;
// The available space passed to the root excludes the root's margins
let root_available_space = {
let style = tree.get_core_container_style(root);
let margin =
style.margin().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
available_space.maybe_sub(margin.sum_axes()).maybe_max(Size::ZERO)
};
#[cfg(feature = "block_layout")]
{
use crate::BoxSizing;
let parent_size = available_space.into_options();
let style = tree.get_core_container_style(root);
if style.is_block() {
// Pull these out earlier to avoid borrowing issues
let aspect_ratio = style.aspect_ratio();
let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
let padding_border_size = (padding + border).sum_axes();
let box_sizing_adjustment =
if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
let min_size = style
.min_size()
.maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let max_size = style
.max_size()
.maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let clamped_style_size = style
.size()
.maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment)
.maybe_clamp(min_size, max_size);
// If both min and max in a given axis are set and max <= min then this determines the size in that axis
let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
(Some(min), Some(max)) if max <= min => Some(min),
_ => None,
});
// Block nodes automatically stretch fit their width to fit available space if available space is definite
let available_space_based_size = Size { width: root_available_space.width.into_option(), height: None };
let styled_based_known_dimensions = known_dimensions
.or(min_max_definite_size)
.or(clamped_style_size)
.or(available_space_based_size)
.maybe_max(padding_border_size);
known_dimensions = styled_based_known_dimensions;
}
}
let inputs = LayoutInput {
known_dimensions,
known_dimensions_are_definite: Size { width: true, height: true },
parent_size: available_space.into_options(),
available_space: root_available_space,
sizing_mode: SizingMode::InherentSize,
axis: RequestedAxis::Both,
run_mode: RunMode::PerformLayout,
vertical_margins_are_collapsible: Line::FALSE,
};
*root_is_cached = tree.cache_get(root, &inputs).is_some();
// Recursively compute node layout
let mut output = tree.compute_child_layout(root, inputs);
let style = tree.get_core_container_style(root);
let padding =
style.padding().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
let border =
style.border().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
let margin =
style.margin().resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis));
let scrollbar_size = Size {
width: if style.overflow().y == Overflow::Scroll { style.scrollbar_width() } else { 0.0 },
height: if style.overflow().x == Overflow::Scroll { style.scrollbar_width() } else { 0.0 },
};
let is_rtl = style.direction().is_rtl();
// The root's margin box is placed at the origin of the initial containing block
let mut location = Point {
x: match (is_rtl, available_space.width.into_option()) {
(true, Some(available_width)) => available_width - output.size.width - margin.right,
_ => margin.left,
},
y: margin.top,
};
// A relatively positioned root is offset by its insets (resolved against the initial containing block)
if style.position() == Position::Relative {
let icb_size = available_space.into_options();
let inset = style.inset();
let left = inset.left.maybe_resolve(icb_size.width, |val, basis| tree.calc(val, basis));
let right = inset.right.maybe_resolve(icb_size.width, |val, basis| tree.calc(val, basis));
let top = inset.top.maybe_resolve(icb_size.height, |val, basis| tree.calc(val, basis));
let bottom = inset.bottom.maybe_resolve(icb_size.height, |val, basis| tree.calc(val, basis));
location.x += if is_rtl {
right.map(|right| -right).or(left).unwrap_or(0.0)
} else {
left.or(right.map(|right| -right)).unwrap_or(0.0)
};
location.y += top.or(bottom.map(|bottom| -bottom)).unwrap_or(0.0);
}
drop(style);
let layout = Layout {
order: 0,
location,
size: output.size,
#[cfg(feature = "content_size")]
scrollable_overflow_rect: output.scrollable_overflow_rect,
scrollbar_size,
padding,
border,
// TODO: support auto margins for root node?
margin,
};
tree.set_unrounded_layout(root, &layout);
(layout, output.oof_candidates.take())
}
/// Attempts to find a cached layout for the specified node and layout inputs.
///
/// Uses the provided closure to compute the layout (and then stores the result in the cache) if no cached layout is found.
#[inline(always)]
pub fn compute_cached_layout<Tree: CacheTree + ?Sized, ComputeFunction>(
tree: &mut Tree,
node: NodeId,
inputs: LayoutInput,
compute_uncached: ComputeFunction,
) -> LayoutOutput
where
ComputeFunction: FnOnce(&mut Tree, NodeId, LayoutInput) -> LayoutOutput,
{
debug_push_node!(node);
// First we check if we have a cached result for the given input
let cache_entry = tree.cache_get(node, &inputs);
if let Some(cached_size_and_baselines) = cache_entry {
debug_log_node!(inputs);
debug_log!("RESULT (CACHED)", dbg:cached_size_and_baselines.size);
debug_pop_node!();
return cached_size_and_baselines;
}
debug_log_node!(inputs);
let computed_size_and_baselines = compute_uncached(tree, node, inputs);
// Cache result
tree.cache_store(node, &inputs, computed_size_and_baselines.clone());
debug_log!("RESULT", dbg:computed_size_and_baselines.size);
debug_pop_node!();
computed_size_and_baselines
}
/// Rounds the calculated layout to exact pixel values
///
/// In order to ensure that no gaps in the layout are introduced we:
/// - Always round based on the cumulative x/y coordinates (relative to the viewport) rather than
/// parent-relative coordinates
/// - Compute width/height by first rounding the top/bottom/left/right and then computing the difference
/// rather than rounding the width/height directly
///
/// See <https://github.com/facebook/yoga/commit/aa5b296ac78f7a22e1aeaf4891243c6bb76488e2> for more context
///
/// In order to prevent innacuracies caused by rounding already-rounded values, we read from `unrounded_layout`
/// and write to `final_layout`.
pub fn round_layout(tree: &mut impl RoundTree, node_id: NodeId) {
return round_layout_inner(tree, node_id, 0.0, 0.0);
/// Recursive function to apply rounding to all descendents
fn round_layout_inner(tree: &mut impl RoundTree, node_id: NodeId, cumulative_x: f32, cumulative_y: f32) {
let unrounded_layout = tree.get_unrounded_layout(node_id);
let mut layout = unrounded_layout;
let parent_x = cumulative_x;
let parent_y = cumulative_y;
let cumulative_x = cumulative_x + unrounded_layout.location.x;
let cumulative_y = cumulative_y + unrounded_layout.location.y;
layout.location.x = round(cumulative_x) - round(parent_x);
layout.location.y = round(cumulative_y) - round(parent_y);
layout.size.width = round(cumulative_x + unrounded_layout.size.width) - round(cumulative_x);
layout.size.height = round(cumulative_y + unrounded_layout.size.height) - round(cumulative_y);
layout.scrollbar_size.width = round(unrounded_layout.scrollbar_size.width);
layout.scrollbar_size.height = round(unrounded_layout.scrollbar_size.height);
layout.border.left = round(cumulative_x + unrounded_layout.border.left) - round(cumulative_x);
layout.border.right = round(cumulative_x + unrounded_layout.size.width)
- round(cumulative_x + unrounded_layout.size.width - unrounded_layout.border.right);
layout.border.top = round(cumulative_y + unrounded_layout.border.top) - round(cumulative_y);
layout.border.bottom = round(cumulative_y + unrounded_layout.size.height)
- round(cumulative_y + unrounded_layout.size.height - unrounded_layout.border.bottom);
layout.padding.left = round(cumulative_x + unrounded_layout.padding.left) - round(cumulative_x);
layout.padding.right = round(cumulative_x + unrounded_layout.size.width)
- round(cumulative_x + unrounded_layout.size.width - unrounded_layout.padding.right);
layout.padding.top = round(cumulative_y + unrounded_layout.padding.top) - round(cumulative_y);
layout.padding.bottom = round(cumulative_y + unrounded_layout.size.height)
- round(cumulative_y + unrounded_layout.size.height - unrounded_layout.padding.bottom);
#[cfg(feature = "content_size")]
round_scrollable_overflow_rect(
&mut layout,
unrounded_layout.scrollable_overflow_rect,
cumulative_x,
cumulative_y,
);
tree.set_final_layout(node_id, &layout);
// Recurse into in-flow children. Out-of-flow (absolute/fixed) children are skipped here:
// they are instead visited via their containing block's hoisted child list below, which
// ensures each node is visited exactly once and that its cumulative offset is accumulated
// relative to its containing block (which its `location` is relative to).
let child_count = tree.child_count(node_id);
for index in 0..child_count {
let child = tree.get_child_id(node_id, index);
if !tree.is_out_of_flow(child) {
round_layout_inner(tree, child, cumulative_x, cumulative_y);
}
}
// Recurse into out-of-flow boxes for which this node is the containing block
let hoisted_count = tree.hoisted_child_count(node_id);
for index in 0..hoisted_count {
let child = tree.get_hoisted_child_id(node_id, index);
round_layout_inner(tree, child, cumulative_x, cumulative_y);
}
}
#[cfg(feature = "content_size")]
#[inline(always)]
/// Round the scrollable overflow rect.
/// This is split into a separate function to make it easier to feature flag.
fn round_scrollable_overflow_rect(
layout: &mut Layout,
unrounded_rect: crate::geometry::Rect<f32>,
cumulative_x: f32,
cumulative_y: f32,
) {
layout.scrollable_overflow_rect.left = round(cumulative_x + unrounded_rect.left) - round(cumulative_x);
layout.scrollable_overflow_rect.right = round(cumulative_x + unrounded_rect.right) - round(cumulative_x);
layout.scrollable_overflow_rect.top = round(cumulative_y + unrounded_rect.top) - round(cumulative_y);
layout.scrollable_overflow_rect.bottom = round(cumulative_y + unrounded_rect.bottom) - round(cumulative_y);
}
}
/// Creates a layout for this node and its children, recursively.
/// Each hidden node has zero size and is placed at the origin
pub fn compute_hidden_layout(tree: &mut (impl LayoutPartialTree + CacheTree), node: NodeId) -> LayoutOutput {
// Clear cache and set zeroed-out layout for the node
tree.cache_clear(node);
tree.set_unrounded_layout(node, &Layout::with_order(0));
// Perform hidden layout on all children
for index in 0..tree.child_count(node) {
let child_id = tree.get_child_id(node, index);
tree.compute_child_layout(child_id, LayoutInput::HIDDEN);
}
LayoutOutput::HIDDEN
}
/// A module for unified re-exports of detailed layout info structs, used by low level API
pub mod detailed_info {
#[cfg(feature = "grid")]
pub use super::grid::{
DetailedGridInfo, DetailedGridItemsInfo, DetailedGridTracksInfo, GridLineNames, GridLineNamesIter,
};
}
#[cfg(test)]
mod tests {
use super::compute_hidden_layout;
use crate::geometry::{Point, Size};
use crate::style::{Display, Style};
use crate::TaffyTree;
#[test]
fn hidden_layout_should_hide_recursively() {
let mut taffy: TaffyTree<()> = TaffyTree::new();
let style: Style = Style { display: Display::Flex, size: Size::from_lengths(50.0, 50.0), ..Default::default() };
let grandchild_00 = taffy.new_leaf(style.clone()).unwrap();
let grandchild_01 = taffy.new_leaf(style.clone()).unwrap();
let child_00 = taffy.new_with_children(style.clone(), &[grandchild_00, grandchild_01]).unwrap();
let grandchild_02 = taffy.new_leaf(style.clone()).unwrap();
let child_01 = taffy.new_with_children(style.clone(), &[grandchild_02]).unwrap();
let root = taffy
.new_with_children(
Style { display: Display::None, size: Size::from_lengths(50.0, 50.0), ..Default::default() },
&[child_00, child_01],
)
.unwrap();
compute_hidden_layout(&mut taffy.as_layout_tree(), root);
// Whatever size and display-mode the nodes had previously,
// all layouts should resolve to ZERO due to the root's DISPLAY::NONE
for node in [root, child_00, child_01, grandchild_00, grandchild_01, grandchild_02] {
let layout = taffy.layout(node).unwrap();
assert_eq!(layout.size, Size::zero());
assert_eq!(layout.location, Point::zero());
}
}
}
+912
View File
@@ -0,0 +1,912 @@
//! Shared positioning pass for out-of-flow (`position: absolute` / `position: fixed`) boxes.
//!
//! Layout algorithms do not lay out their out-of-flow children directly (unless they are the
//! child's containing block). Instead they emit [`OofCandidate`] records which bubble up the tree
//! via [`LayoutOutput::oof_candidates`](crate::LayoutOutput) until they reach the box's containing
//! block, which lays the box out using the routine in this module.
use crate::geometry::{Line, Point, Rect, Size};
use crate::style::{
AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace, ContainingBlockClaims, CoreStyle, OofItemStyle,
Overflow,
};
#[cfg(feature = "grid")]
use crate::tree::DetailedLayoutInfo;
use crate::tree::{
AxisStaticPosition, Layout, LayoutContainingBlock, LayoutInput, LayoutOutput, LayoutPartialTreeExt, NodeId,
OofCandidate, OofCandidates, OofPositioningArea, RequestedAxis, RunMode, SizingMode,
};
use crate::util::sys::{f32_max, Vec};
use crate::util::{MaybeMath, MaybeResolve, ResolveOrZero};
use crate::{AxisStaticEdge, BoxSizing, Direction};
#[cfg(feature = "content_size")]
use super::common::scrollable_overflow::compute_scrollable_overflow_contribution;
use super::common::sizing_keyword::resolve_absolute_sizing_keywords;
/// Resolve the final static offset of an out-of-flow box from its static position, given the
/// box's final size and resolved margins.
///
/// In each axis the box's margin box is aligned within the static-position area according to the
/// recorded alignment keyword. When the alignment is `safe` and the margin box overflows the
/// area, the fallback keyword is used instead (the `safe` overflow-position keyword from CSS
/// Box Alignment). The returned offset locates the box's border box and is relative to whatever
/// the static-position areas are relative to (the containing block's border box once a candidate
/// has bubbled to its containing block).
pub fn resolve_static_offset(
static_position: Point<AxisStaticPosition>,
final_size: Size<f32>,
resolved_margin: Rect<f32>,
) -> Point<f32> {
Point {
x: resolve_static_offset_axis(
static_position.x,
final_size.width,
Line { start: resolved_margin.left, end: resolved_margin.right },
),
y: resolve_static_offset_axis(
static_position.y,
final_size.height,
Line { start: resolved_margin.top, end: resolved_margin.bottom },
),
}
}
/// Single-axis version of [`resolve_static_offset`]
fn resolve_static_offset_axis(sp: AxisStaticPosition, size: f32, margin: Line<f32>) -> f32 {
let margin_box_size = size + margin.start + margin.end;
let overflows = matches!(sp.align.safety, AlignmentSafety::Safe) && margin_box_size > sp.area.end - sp.area.start;
let keyword = if overflows { sp.align.fallback } else { sp.align.keyword };
align_in_line(sp.area, margin_box_size, keyword) + margin.start
}
/// Position a box of `size` within `container` so that it is aligned to the given physical edge
fn align_in_line(container: Line<f32>, size: f32, edge: AxisStaticEdge) -> f32 {
match edge {
AxisStaticEdge::Start => container.start,
AxisStaticEdge::End => container.end - size,
AxisStaticEdge::Center => (container.start + container.end - size) / 2.0,
}
}
/// The self-alignment of an out-of-flow box in one axis, resolved relative to the writing mode
/// of its containing block (`Start` is the logical start edge of the containing block).
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum OofAlignment {
/// `normal` (or `auto`): stretch-fit sizing for non-replaced, non-table boxes; start alignment
Normal,
/// `stretch`: stretch-fit sizing; start alignment
Stretch,
/// Aligned to the logical start edge
Start,
/// Centered
Center,
/// Aligned to the logical end edge
End,
}
impl OofAlignment {
/// Convert an `align-self`/`justify-self` value for an out-of-flow box into a logical
/// alignment relative to the containing block's writing mode.
///
/// `alignment` must already have had `self-start`/`self-end` resolved against the containing
/// block's direction (see [`AlignSelf::resolve_self_relative`]).
fn from_resolved(alignment: AlignSelf) -> Self {
debug_assert!(
!matches!(alignment.keyword, AlignItemsKeyword::SelfStart | AlignItemsKeyword::SelfEnd),
"self-start/self-end must be resolved before computing out-of-flow alignment"
);
match alignment.keyword {
AlignItemsKeyword::Normal => Self::Normal,
AlignItemsKeyword::Stretch => Self::Stretch,
AlignItemsKeyword::Center => Self::Center,
AlignItemsKeyword::End | AlignItemsKeyword::FlexEnd | AlignItemsKeyword::SelfEnd => Self::End,
// The fallback alignment of `baseline` is `start`
AlignItemsKeyword::Start
| AlignItemsKeyword::FlexStart
| AlignItemsKeyword::SelfStart
| AlignItemsKeyword::Baseline => Self::Start,
}
}
/// The physical edge of the containing block the box's margin box is aligned to once its
/// size has been determined. `Normal` and `Stretch` behave as `Start`.
fn physical_edge(self, reversed: bool) -> AxisStaticEdge {
match (self, reversed) {
(Self::Center, _) => AxisStaticEdge::Center,
(Self::End, false) | (Self::Normal | Self::Stretch | Self::Start, true) => AxisStaticEdge::End,
(Self::End, true) | (Self::Normal | Self::Stretch | Self::Start, false) => AxisStaticEdge::Start,
}
}
}
/// The inputs to the absolute positioning layout model
/// (<https://www.w3.org/TR/css-position-3/#abspos-layout>) in a single axis. All coordinates
/// are physical (left-to-right / top-to-bottom) and relative to the start of the containing
/// block's inset-resolution area.
#[derive(Copy, Clone, Debug)]
struct OofAxis {
/// The size of the containing block in this axis
cb_size: f32,
/// The box's resolved inset properties (`None` = `auto`)
inset: Line<Option<f32>>,
/// The box's resolved margins (`None` = `auto`)
margin: Line<Option<f32>>,
/// The box's static position (relative to the containing block's inset-resolution area)
static_position: AxisStaticPosition,
/// The box's self-alignment in this axis
alignment: OofAlignment,
/// The overflow-position modifier of the box's self-alignment in this axis
safety: AlignmentSafety,
/// Whether this is the inline axis of the containing block
is_inline: bool,
/// Whether the logical start edge of the containing block is the physical end edge of this
/// axis (the inline axis of an RTL containing block)
reversed: bool,
/// Whether the containing block is a scroll container which scrolls in this axis
is_scroll_axis: bool,
}
impl OofAxis {
/// The physical edge corresponding to the logical start edge of the containing block
fn start_edge(&self) -> AxisStaticEdge {
if self.reversed {
AxisStaticEdge::End
} else {
AxisStaticEdge::Start
}
}
/// The physical edge corresponding to the logical end edge of the containing block
fn end_edge(&self) -> AxisStaticEdge {
if self.reversed {
AxisStaticEdge::Start
} else {
AxisStaticEdge::End
}
}
/// The inset-modified containing block (IMCB) in this axis
/// <https://www.w3.org/TR/css-position-3/#resolving-insets>
fn inset_modified_containing_block(&self) -> Line<f32> {
let (mut imcb, weaker_edge) = match (self.inset.start, self.inset.end) {
(Some(start), Some(end)) => (Line { start, end: self.cb_size - end }, self.end_edge()),
// A lone auto inset resolves to zero, and is the weaker inset
(Some(start), None) => (Line { start, end: self.cb_size }, AxisStaticEdge::End),
(None, Some(end)) => (Line { start: 0.0, end: self.cb_size - end }, AxisStaticEdge::Start),
// Both insets are auto: resolve them from the static position rectangle and the
// alignment within it
(None, None) => {
let sp = self.static_position;
let imcb = match sp.align.keyword {
AxisStaticEdge::Start => Line { start: sp.area.start, end: self.cb_size },
AxisStaticEdge::End => Line { start: 0.0, end: sp.area.end },
AxisStaticEdge::Center => {
// Center the IMCB on the static position rectangle's center, bounded by
// the nearer edge of the containing block
let center = (sp.area.start + sp.area.end) / 2.0;
let start_distance = center;
let end_distance = self.cb_size - center;
if start_distance.abs() <= end_distance.abs() {
Line { start: 0.0, end: 2.0 * start_distance }
} else {
Line { start: self.cb_size - 2.0 * end_distance, end: self.cb_size }
}
}
};
(imcb, self.end_edge())
}
};
// Overconstrained insets: the weaker inset is reduced to bring the IMCB size up to zero
// <https://www.w3.org/TR/css-position-3/#resolving-insets>
if imcb.end < imcb.start {
match weaker_edge {
AxisStaticEdge::Start => imcb.start = imcb.end,
_ => imcb.end = imcb.start,
}
}
imcb
}
/// The size of the IMCB in this axis: the space available to the box's margin box
fn inset_modified_containing_block_size(&self) -> f32 {
let imcb = self.inset_modified_containing_block();
imcb.end - imcb.start
}
/// The stretch-fit size of the box's border box: the IMCB minus the non-auto margins (auto
/// margins are treated as zero) <https://www.w3.org/TR/css-position-3/#abspos-auto-size>
fn stretch_fit_size(&self) -> f32 {
let non_auto_margin_sum = self.margin.start.unwrap_or(0.0) + self.margin.end.unwrap_or(0.0);
f32_max(self.inset_modified_containing_block_size() - non_auto_margin_sum, 0.0)
}
/// Whether an `auto` size in this axis is the stretch-fit size (rather than fit-content)
/// <https://www.w3.org/TR/css-position-3/#abspos-auto-size>
fn is_stretch_sized(&self, is_replaced: bool, is_table: bool) -> bool {
let no_auto_inset = self.inset.start.is_some() && self.inset.end.is_some();
no_auto_inset
&& match self.alignment {
OofAlignment::Stretch => true,
OofAlignment::Normal => !is_replaced && !is_table,
_ => false,
}
}
/// Resolve the box's auto margins given its final size
/// <https://www.w3.org/TR/css-position-3/#abspos-margins>
fn resolve_margins(&self, size: f32) -> Line<f32> {
let both_insets = self.inset.start.is_some() && self.inset.end.is_some();
let imcb = self.inset_modified_containing_block();
let free_space = imcb.end - imcb.start - size;
match (self.margin.start, self.margin.end) {
(Some(start), Some(end)) => Line { start, end },
// If either inset is auto then auto margins resolve to zero
_ if !both_insets => Line { start: self.margin.start.unwrap_or(0.0), end: self.margin.end.unwrap_or(0.0) },
(Some(start), None) => Line { start, end: free_space - start },
(None, Some(end)) => Line { start: free_space - end, end },
(None, None) => {
// In the inline axis, negative free space is absorbed entirely by the end margin
if free_space < 0.0 && self.is_inline {
if self.reversed {
Line { start: free_space, end: 0.0 }
} else {
Line { start: 0.0, end: free_space }
}
} else {
Line { start: free_space / 2.0, end: free_space / 2.0 }
}
}
}
}
/// Compute the physical start of the box's border box given its final size and margins
/// <https://www.w3.org/TR/css-position-3/#abspos-alignment>
fn position(&self, size: f32, margin: Line<f32>) -> f32 {
let imcb = self.inset_modified_containing_block();
match (self.inset.start, self.inset.end) {
// Both insets are auto: static alignment, with safe overflow relative to the IMCB
(None, None) => {
let sp = self.static_position;
let margin_box_size = size + margin.start + margin.end;
let offset = if sp.align.safety == AlignmentSafety::Safe && margin_box_size > imcb.end - imcb.start {
align_in_line(imcb, margin_box_size, self.start_edge())
} else {
align_in_line(sp.area, margin_box_size, sp.align.keyword)
};
offset + margin.start
}
// One auto inset: the margin box is aligned to the edge of the stronger inset
(Some(_), None) => imcb.start + margin.start,
(None, Some(_)) => imcb.end - size - margin.end,
(Some(_), Some(_)) => {
// Auto margins have already absorbed all of the free space
if self.margin.start.is_none() || self.margin.end.is_none() {
return imcb.start + margin.start;
}
let margin_box_size = size + margin.start + margin.end;
let imcb_size = imcb.end - imcb.start;
let edge = self.alignment.physical_edge(self.reversed);
let margin_box_start = match self.safety {
AlignmentSafety::Unsafe => align_in_line(imcb, margin_box_size, edge),
AlignmentSafety::Safe => {
let edge = if margin_box_size > imcb_size { self.start_edge() } else { edge };
align_in_line(imcb, margin_box_size, edge)
}
// Default overflow alignment for absolutely positioned boxes:
// <https://www.w3.org/TR/css-align-3/#auto-safety-position>
AlignmentSafety::Default => {
if margin_box_size <= imcb_size || self.alignment == OofAlignment::Normal {
// 1. Fits within the IMCB: align as specified
align_in_line(imcb, margin_box_size, edge)
} else {
// The overflow limit rect is the bounding rect of the IMCB and the
// containing block, extended to infinity in the scrollable direction
// of a scroll container
let mut limit = Line { start: imcb.start.min(0.0), end: f32_max(imcb.end, self.cb_size) };
if self.is_scroll_axis {
if self.reversed {
limit.start = f32::NEG_INFINITY;
} else {
limit.end = f32::INFINITY;
}
}
if margin_box_size <= limit.end - limit.start {
// 2. Fits within the overflow limit rect: cover the IMCB and align
// as specified as far as possible without overflowing the limit
let start = align_in_line(imcb, margin_box_size, edge);
f32_max(start.min(limit.end - margin_box_size), limit.start)
} else {
// 3. Start-align within the overflow limit rect
align_in_line(limit, margin_box_size, self.start_edge())
}
}
}
};
margin_box_start + margin.start
}
}
}
}
/// Run the out-of-flow positioning pass for `node_id` after its layout algorithm has produced
/// `output`: lay out the out-of-flow candidates in `output.oof_candidates` for which the node is
/// the containing block, record them as the node's hoisted children, and replace
/// `output.oof_candidates` with the unclaimed remainder (which bubble further up the tree).
/// The scrollable overflow contributed by the claimed boxes is merged into
/// `output.scrollable_overflow_rect`.
///
/// This should be called once per `RunMode::PerformLayout` container layout, after the layout
/// algorithm (block/flexbox/grid) has run, and *inside* any layout caching wrapper (such as
/// [`compute_cached_layout`](crate::compute_cached_layout)) so that cache hits do not re-run the
/// pass. It is a no-op when `output.oof_positioning_area` is `None` (leaf and size-only outputs).
///
/// Which candidates the node claims is determined by the node's style via
/// [`CoreStyle::is_containing_block`]. `position: fixed` boxes unclaimed by every ancestor are
/// claimed by the final root positioning pass in [`compute_root_layout`](crate::compute_root_layout).
pub fn compute_oof_layout(tree: &mut impl LayoutContainingBlock, node_id: NodeId, output: &mut LayoutOutput) {
let Some(area) = output.oof_positioning_area else { return };
let style = tree.get_core_container_style(node_id);
let direction = style.direction();
let claims = style.is_containing_block();
drop(style);
let candidates = output.oof_candidates.take();
let result = compute_oof_layout_for_area(tree, node_id, candidates.as_slice(), area, direction, claims);
// Always record the hoisted child list (even when empty) so that lists recorded by previous
// layout runs do not persist
tree.clear_hoisted_children(node_id);
tree.add_hoisted_children(node_id, &result.hoisted);
output.oof_candidates = result.unclaimed;
#[cfg(feature = "content_size")]
{
output.scrollable_overflow_rect = output.scrollable_overflow_rect.union(result.scrollable_overflow_rect);
}
}
/// The result of laying out out-of-flow candidates against an explicit positioning area.
pub struct OofLayoutResult {
/// Candidates claimed and laid out by this pass, in document order.
pub hoisted: Vec<NodeId>,
/// Candidates not claimed by this pass, which must continue bubbling.
pub unclaimed: OofCandidates,
/// Scrollable overflow contributed by the claimed candidates, relative to the positioning
/// area's origin.
pub scrollable_overflow_rect: Rect<f32>,
}
/// Lay out out-of-flow candidates against an explicit positioning area.
///
/// Unlike [`compute_oof_layout`], this function does not update the geometry owner's hoisted
/// children or merge overflow into a [`LayoutOutput`]. This is useful when the CSS containing
/// block does not have its own layout node and another node owns the resulting geometry.
///
/// `geometry_owner` supplies the layout tree operations, detailed layout information, and
/// scroll-container state used by the positioning pass. `direction` and `claims` describe the
/// actual CSS containing block.
pub fn compute_oof_layout_for_area(
tree: &mut impl LayoutContainingBlock,
geometry_owner: NodeId,
candidates: &[OofCandidate],
area: OofPositioningArea,
direction: Direction,
claims: ContainingBlockClaims,
) -> OofLayoutResult {
let overflow = tree.get_core_container_style(geometry_owner).overflow();
let mut hoisted = Vec::new();
let mut unclaimed = OofCandidates::new();
let scrollable_overflow_rect = perform_oof_layout(
tree,
geometry_owner,
candidates,
area.size,
area.offset,
direction,
claims,
overflow,
&mut hoisted,
&mut unclaimed,
);
OofLayoutResult { hoisted, unclaimed, scrollable_overflow_rect }
}
/// The result of laying out a single out-of-flow box with [`layout_oof_box`].
pub(crate) struct OofBoxLayout {
/// The box's final layout (its `location` is relative to the containing block's border box)
pub layout: Layout,
/// Out-of-flow candidates surfaced from within the box's subtree, with anchors relative to
/// the box's own border box
pub surfaced: OofCandidates,
/// The box's `overflow` style
#[cfg(feature = "content_size")]
pub overflow: Point<Overflow>,
/// The box's `contain` style
#[cfg(feature = "content_size")]
pub contain: crate::style::Contain,
}
/// Size and position a single out-of-flow box against its containing block, and store its layout.
///
/// - `area_size`/`area_offset` describe the inset-resolution area of the containing block
/// (border box minus borders and scrollbar gutters), relative to the containing block's border box.
/// - `container_overflow` is the `overflow` style of the containing block, which determines
/// whether overflowing boxes may be aligned into its scrollable overflow area.
/// - `grid_owner` is the node whose detailed layout info is consulted for grid placement: if it is
/// a grid container, the box is positioned relative to the grid area determined by its
/// grid-placement properties rather than the passed area.
/// - `before_layout` is called with the inputs of the final layout pass just before it runs, which
/// allows the caller to inspect the layout cache for the box.
#[inline(always)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn layout_oof_box<Tree: LayoutContainingBlock>(
tree: &mut Tree,
candidate: OofCandidate,
area_size: Size<f32>,
area_offset: Point<f32>,
direction: Direction,
container_overflow: Point<Overflow>,
#[cfg(feature = "grid")] grid_owner: Option<NodeId>,
before_layout: impl FnOnce(&mut Tree, &LayoutInput),
) -> OofBoxLayout {
let child_style = tree.get_oof_item_style(candidate.node);
// If the current node is a grid container then the box is positioned relative to the
// grid area determined by its grid-placement properties (which falls back to the passed
// area for `auto` placement)
#[cfg(feature = "grid")]
let (area_size, area_offset) = match grid_owner.map(|owner| tree.get_detailed_layout_info(owner)) {
Some(DetailedLayoutInfo::Grid(grid_info)) => {
let area_rect = Rect {
left: area_offset.x,
right: area_offset.x + area_size.width,
top: area_offset.y,
bottom: area_offset.y + area_size.height,
};
let grid_area = grid_info.resolve_absolute_grid_area(
child_style.grid_row(),
child_style.grid_column(),
direction,
area_rect,
);
(
Size { width: grid_area.right - grid_area.left, height: grid_area.bottom - grid_area.top },
Point { x: grid_area.left, y: grid_area.top },
)
}
_ => (area_size, area_offset),
};
let area_width = area_size.width;
let area_height = area_size.height;
let aspect_ratio = child_style.aspect_ratio();
let margin =
child_style.margin().map(|margin| margin.resolve_to_option(area_width, |val, basis| tree.calc(val, basis)));
let padding = child_style.padding().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
let border = child_style.border().resolve_or_zero(Some(area_width), |val, basis| tree.calc(val, basis));
let padding_border_sum = (padding + border).sum_axes();
let box_sizing_adjustment =
if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
// Resolve inset
let left = child_style.inset().left.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
let right = child_style.inset().right.maybe_resolve(area_width, |val, basis| tree.calc(val, basis));
let top = child_style.inset().top.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
let bottom = child_style.inset().bottom.maybe_resolve(area_height, |val, basis| tree.calc(val, basis));
// Compute known dimensions from min/max/inherent size styles
let size_style = child_style.size();
let style_size = size_style
.maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let mut min_size = child_style
.min_size()
.maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment)
.or(padding_border_sum.map(Some))
.maybe_max(padding_border_sum);
let max_size = child_style
.max_size()
.maybe_resolve(area_size, |val, basis| tree.calc(val, basis))
.maybe_apply_aspect_ratio(aspect_ratio)
.maybe_add(box_sizing_adjustment);
let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
let is_replaced = child_style.is_replaced();
let is_table = child_style.is_table();
let item_direction = child_style.direction();
// Taffy only supports the `horizontal-tb` writing mode, so only the inline axis can be reversed.
// `auto` (`None`) behaves as `normal` for absolutely positioned boxes: it does not defer to the
// `*-items` properties of the containing block.
let justify_self =
child_style.justify_self().unwrap_or(AlignSelf::NORMAL).resolve_self_relative(item_direction, direction, true);
let align_self =
child_style.align_self().unwrap_or(AlignSelf::NORMAL).resolve_self_relative(item_direction, direction, false);
let overflow = child_style.overflow();
let scrollbar_width = child_style.scrollbar_width();
#[cfg(feature = "content_size")]
let contain = child_style.contain();
drop(child_style);
// Static positions are relative to the containing block's border box: make them relative to
// the inset-resolution area
let static_position = Point {
x: AxisStaticPosition {
area: candidate.static_position.x.area.map(|v| v - area_offset.x),
align: candidate.static_position.x.align,
},
y: AxisStaticPosition {
area: candidate.static_position.y.area.map(|v| v - area_offset.y),
align: candidate.static_position.y.align,
},
};
let horizontal = OofAxis {
cb_size: area_width,
inset: Line { start: left, end: right },
margin: Line { start: margin.left, end: margin.right },
static_position: static_position.x,
alignment: OofAlignment::from_resolved(justify_self),
safety: justify_self.safety,
is_inline: true,
reversed: direction.is_rtl(),
is_scroll_axis: container_overflow.x.is_scroll_container(),
};
let vertical = OofAxis {
cb_size: area_height,
inset: Line { start: top, end: bottom },
margin: Line { start: margin.top, end: margin.bottom },
static_position: static_position.y,
alignment: OofAlignment::from_resolved(align_self),
safety: align_self.safety,
is_inline: false,
reversed: false,
is_scroll_axis: container_overflow.y.is_scroll_container(),
};
let stretch_fit_size = Size { width: horizontal.stretch_fit_size(), height: vertical.stretch_fit_size() };
// The space available to the box's border box is its stretch-fit size (the IMCB minus its
// non-auto margins). The available space for a table never exceeds that of the containing
// block (minus the margins) <https://www.w3.org/TR/css-tables-3/#abspos>
let mut available_space = stretch_fit_size;
if is_table {
let non_auto_margin = margin.map(|m| m.unwrap_or(0.0));
available_space = available_space.f32_min(Size {
width: f32_max(area_width - non_auto_margin.horizontal_axis_sum(), 0.0),
height: f32_max(area_height - non_auto_margin.vertical_axis_sum(), 0.0),
});
}
let available_space = available_space.maybe_clamp(min_size, max_size).map(AvailableSpace::Definite);
// Resolve any sizing keywords (min-content, max-content, fit-content, fit-content(...),
// stretch) in the size styles. An explicitly sized axis takes precedence over the
// automatic size below.
if size_style.width.is_sizing_keyword() || size_style.height.is_sizing_keyword() {
resolve_absolute_sizing_keywords(
tree,
candidate.node,
&mut known_dimensions,
size_style,
area_size,
Rect { left, right, top, bottom },
margin,
SizingMode::ContentSize,
);
known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
}
// Resolve automatic sizes <https://www.w3.org/TR/css-position-3/#abspos-auto-size>
//
// An auto size is the stretch-fit size (the IMCB minus margins) if the self-alignment in
// that axis is `stretch` (or `normal` for a non-replaced, non-table box) and neither inset is
// auto. Otherwise it is the fit-content size, which is measured below. Stretch-fit sizes are
// resolved first so that a size in the other axis can be transferred through the aspect ratio.
// The block axis is the ratio-dependent axis, so a stretched inline size is transferred
// through the aspect ratio rather than also stretching the block size. An explicit
// `stretch` in both axes stretches both and ignores the aspect ratio.
let stretch_width = known_dimensions.width.is_none() && horizontal.is_stretch_sized(is_replaced, is_table);
let stretch_height = known_dimensions.height.is_none() && vertical.is_stretch_sized(is_replaced, is_table);
let both_explicit_stretch =
horizontal.alignment == OofAlignment::Stretch && vertical.alignment == OofAlignment::Stretch;
let stretch_aspect_ratio =
if stretch_width && stretch_height && both_explicit_stretch { None } else { aspect_ratio };
if stretch_width {
if is_table {
// A table cannot be stretched smaller than its content: stretch-fit is a minimum
min_size.width = Some(f32_max(min_size.width.unwrap_or(0.0), stretch_fit_size.width));
} else {
known_dimensions.width = Some(stretch_fit_size.width);
known_dimensions =
known_dimensions.maybe_apply_aspect_ratio(stretch_aspect_ratio).maybe_clamp(min_size, max_size);
}
}
if known_dimensions.height.is_none() && stretch_height {
if is_table {
min_size.height = Some(f32_max(min_size.height.unwrap_or(0.0), stretch_fit_size.height));
} else {
known_dimensions.height = Some(stretch_fit_size.height);
known_dimensions =
known_dimensions.maybe_apply_aspect_ratio(stretch_aspect_ratio).maybe_clamp(min_size, max_size);
}
}
let final_size = match (known_dimensions.width, known_dimensions.height) {
(Some(width), Some(height)) => Size { width, height },
_ => {
let measured_size = tree.measure_child_size_both(
candidate.node,
known_dimensions,
area_size.map(Some),
available_space,
SizingMode::ContentSize,
Line::FALSE,
);
known_dimensions.unwrap_or(measured_size)
}
}
.maybe_clamp(min_size, max_size);
let layout_input = LayoutInput {
known_dimensions: final_size.map(Some),
known_dimensions_are_definite: Size { width: true, height: true },
parent_size: area_size.map(Some),
available_space,
sizing_mode: SizingMode::ContentSize,
axis: RequestedAxis::Both,
run_mode: RunMode::PerformLayout,
vertical_margins_are_collapsible: Line::FALSE,
};
before_layout(tree, &layout_input);
let mut layout_output = tree.compute_child_layout(candidate.node, layout_input);
// Resolve auto margins <https://www.w3.org/TR/css-position-3/#abspos-margins>
let horizontal_margin = horizontal.resolve_margins(final_size.width);
let vertical_margin = vertical.resolve_margins(final_size.height);
let resolved_margin = Rect {
left: horizontal_margin.start,
right: horizontal_margin.end,
top: vertical_margin.start,
bottom: vertical_margin.end,
};
// Align the margin box within the IMCB <https://www.w3.org/TR/css-position-3/#abspos-alignment>
let location = Point {
x: horizontal.position(final_size.width, horizontal_margin) + area_offset.x,
y: vertical.position(final_size.height, vertical_margin) + area_offset.y,
};
// Note: axis intentionally switched here as scrollbars take up space in the opposite axis
// to the axis in which scrolling is enabled.
let scrollbar_size = Size {
width: if overflow.y == Overflow::Scroll { scrollbar_width } else { 0.0 },
height: if overflow.x == Overflow::Scroll { scrollbar_width } else { 0.0 },
};
let layout = Layout {
order: candidate.order,
size: final_size,
#[cfg(feature = "content_size")]
scrollable_overflow_rect: layout_output.scrollable_overflow_rect,
scrollbar_size,
location,
padding,
border,
margin: resolved_margin,
};
tree.set_unrounded_layout(candidate.node, &layout);
OofBoxLayout {
layout,
surfaced: layout_output.oof_candidates.take(),
#[cfg(feature = "content_size")]
overflow,
#[cfg(feature = "content_size")]
contain,
}
}
/// Perform final layout on the out-of-flow candidates for which the current node is the
/// containing block, and collect the remainder into `unclaimed` for further bubbling.
///
/// - `node_id` is the current node. If its detailed layout info (as returned by
/// [`LayoutContainingBlock::get_detailed_layout_info`]) indicates that it is a grid container,
/// each claimed box is positioned relative to the grid area determined by its grid-placement
/// properties rather than the passed inset-resolution area.
/// - `candidates` is the merged, document-ordered list of candidates held by the current node
/// (direct out-of-flow children plus candidates bubbled from in-flow children). Anchors must be
/// relative to the current node's border box.
/// - `area_size`/`area_offset` describe the inset-resolution area of the current node
/// (border box minus borders and scrollbar gutters).
/// - `claims` describes which out-of-flow positions the current node acts as a containing block
/// for (see [`CoreStyle::is_containing_block`]). The final root positioning pass claims all.
/// - `container_overflow` is the `overflow` style of the containing block.
///
/// Laying out a claimed box may surface further candidates from within its subtree (e.g. a
/// `position: fixed` descendant of a `position: absolute` box). These are re-swept: claimed ones
/// are appended to the work list, unclaimed ones are added to `unclaimed`.
///
/// The ids of claimed boxes are appended to `hoisted` in order. Returns the scrollable overflow
/// contribution of the claimed boxes.
#[allow(clippy::too_many_arguments)]
pub(crate) fn perform_oof_layout(
tree: &mut impl LayoutContainingBlock,
node_id: NodeId,
candidates: &[OofCandidate],
area_size: Size<f32>,
area_offset: Point<f32>,
direction: Direction,
claims: ContainingBlockClaims,
container_overflow: Point<Overflow>,
hoisted: &mut Vec<NodeId>,
unclaimed: &mut OofCandidates,
) -> Rect<f32> {
#[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
let mut absolute_overflow_rect = Rect::ZERO;
if candidates.is_empty() {
return absolute_overflow_rect;
}
#[cfg(feature = "content_size")]
let is_scroll_container = container_overflow.x.is_scroll_container() || container_overflow.y.is_scroll_container();
// Split the candidate list into an initial work list of claimed candidates and the unclaimed
// remainder. Further claimed candidates surfaced while laying out a claimed box are appended
// to the work list (Blink-style re-sweep).
let mut worklist: Vec<OofCandidate> = Vec::new();
for candidate in candidates {
if claims.for_position(candidate.position) {
worklist.push(*candidate);
} else {
unclaimed.push(*candidate);
}
}
#[cfg(not(feature = "grid"))]
let _ = node_id;
let mut index = 0;
while index < worklist.len() {
let candidate = worklist[index];
index += 1;
hoisted.push(candidate.node);
let OofBoxLayout {
layout,
surfaced,
#[cfg(feature = "content_size")]
overflow,
#[cfg(feature = "content_size")]
contain,
} = layout_oof_box(
tree,
candidate,
area_size,
area_offset,
direction,
container_overflow,
#[cfg(feature = "grid")]
Some(node_id),
|_, _| {},
);
let location = layout.location;
let final_size = layout.size;
// Re-sweep any candidates surfaced from within the box's subtree, translating their
// anchors so they are relative to this node's border box
let mut surfaced = surfaced;
if !surfaced.is_empty() {
surfaced.translate(location);
for surfaced_candidate in surfaced.iter() {
if claims.for_position(surfaced_candidate.position) {
worklist.push(*surfaced_candidate);
} else {
unclaimed.push(*surfaced_candidate);
}
}
}
#[cfg(feature = "content_size")]
{
// Location is measured from the scroll origin (the inline-start edge: right side in RTL)
let relative_location = if direction.is_rtl() {
Point {
x: area_size.width - (location.x - area_offset.x) - final_size.width,
y: location.y - area_offset.y,
}
} else {
Point { x: location.x - area_offset.x, y: location.y - area_offset.y }
};
absolute_overflow_rect = absolute_overflow_rect.union(compute_scrollable_overflow_contribution(
relative_location,
final_size,
layout.scrollable_overflow_rect,
overflow,
contain,
is_scroll_container,
));
}
}
absolute_overflow_rect
}
#[cfg(test)]
mod tests {
use super::resolve_static_offset;
use crate::geometry::{Line, Point, Rect, Size};
use crate::style::AlignmentSafety;
use crate::tree::{AxisStaticAlign, AxisStaticEdge, AxisStaticPosition};
fn sp(
area: Line<f32>,
keyword: AxisStaticEdge,
safety: AlignmentSafety,
fallback: AxisStaticEdge,
) -> AxisStaticPosition {
AxisStaticPosition { area, align: AxisStaticAlign { keyword, safety, fallback } }
}
fn resolve_x(sp_x: AxisStaticPosition, width: f32, margin: Rect<f32>) -> f32 {
let position = Point { x: sp_x, y: AxisStaticPosition::from_edge(0.0, AxisStaticEdge::Start) };
resolve_static_offset(position, Size { width, height: 10.0 }, margin).x
}
const AREA: Line<f32> = Line { start: 10.0, end: 110.0 };
const NO_MARGIN: Rect<f32> = Rect { left: 0.0, right: 0.0, top: 0.0, bottom: 0.0 };
const MARGIN: Rect<f32> = Rect { left: 5.0, right: 15.0, top: 0.0, bottom: 0.0 };
#[test]
fn start_alignment() {
let sp_x = sp(AREA, AxisStaticEdge::Start, AlignmentSafety::Unsafe, AxisStaticEdge::Start);
assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 10.0);
assert_eq!(resolve_x(sp_x, 20.0, MARGIN), 15.0);
}
#[test]
fn end_alignment() {
let sp_x = sp(AREA, AxisStaticEdge::End, AlignmentSafety::Unsafe, AxisStaticEdge::End);
assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 90.0);
assert_eq!(resolve_x(sp_x, 20.0, MARGIN), 75.0);
}
#[test]
fn center_alignment() {
let sp_x = sp(AREA, AxisStaticEdge::Center, AlignmentSafety::Unsafe, AxisStaticEdge::Center);
assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 50.0);
// Center offsets by half the margin difference
assert_eq!(resolve_x(sp_x, 20.0, MARGIN), 45.0);
}
#[test]
fn safe_alignment_falls_back_only_on_overflow() {
let sp_x = sp(AREA, AxisStaticEdge::End, AlignmentSafety::Safe, AxisStaticEdge::Start);
// Fits: aligned to the end
assert_eq!(resolve_x(sp_x, 20.0, NO_MARGIN), 90.0);
// Margin box exactly fills the area: no fallback
assert_eq!(resolve_x(sp_x, 100.0, NO_MARGIN), 10.0);
// Margin box overflows the area: falls back to start
assert_eq!(resolve_x(sp_x, 120.0, NO_MARGIN), 10.0);
assert_eq!(resolve_x(sp_x, 90.0, MARGIN), 15.0);
}
#[test]
fn unsafe_alignment_never_falls_back() {
let sp_x = sp(AREA, AxisStaticEdge::End, AlignmentSafety::Unsafe, AxisStaticEdge::Start);
assert_eq!(resolve_x(sp_x, 120.0, NO_MARGIN), -10.0);
}
#[test]
fn degenerate_area() {
// A zero-extent area (static positions emitted by block layout) behaves as an anchor point
let anchor = AxisStaticPosition::from_edge(40.0, AxisStaticEdge::Start);
assert_eq!(resolve_x(anchor, 20.0, NO_MARGIN), 40.0);
let anchor_end = AxisStaticPosition::from_edge(40.0, AxisStaticEdge::End);
assert_eq!(resolve_x(anchor_end, 20.0, NO_MARGIN), 20.0);
}
}
+773
View File
@@ -0,0 +1,773 @@
//! Geometric primitives useful for layout
use crate::util::sys::f32_max;
use crate::CompactLength;
use crate::{style::Dimension, util::sys::f32_min};
use core::ops::{Add, Sub};
#[cfg(feature = "flexbox")]
use crate::style::FlexDirection;
/// The simple absolute horizontal and vertical axis
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum AbsoluteAxis {
/// The horizontal axis
Horizontal,
/// The vertical axis
Vertical,
}
impl AbsoluteAxis {
/// Returns the other variant of the enum
#[inline]
pub const fn other_axis(&self) -> Self {
match *self {
AbsoluteAxis::Horizontal => AbsoluteAxis::Vertical,
AbsoluteAxis::Vertical => AbsoluteAxis::Horizontal,
}
}
}
impl<T> Size<T> {
#[inline(always)]
/// Get either the width or height depending on the AbsoluteAxis passed in
pub fn get_abs(self, axis: AbsoluteAxis) -> T {
match axis {
AbsoluteAxis::Horizontal => self.width,
AbsoluteAxis::Vertical => self.height,
}
}
/// Swap the width and height components
#[inline(always)]
pub fn transpose(self) -> Size<T> {
Size { width: self.height, height: self.width }
}
}
impl<T: Add> Rect<T> {
#[inline(always)]
/// Get either the width or height depending on the AbsoluteAxis passed in
pub fn grid_axis_sum(self, axis: AbsoluteAxis) -> <T as Add>::Output {
match axis {
AbsoluteAxis::Horizontal => self.left + self.right,
AbsoluteAxis::Vertical => self.top + self.bottom,
}
}
}
/// The CSS abstract axis
/// <https://www.w3.org/TR/css-writing-modes-3/#abstract-axes>
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum AbstractAxis {
/// The axis in the inline dimension, i.e. the horizontal axis in horizontal writing modes and the vertical axis in vertical writing modes.
Inline,
/// The axis in the block dimension, i.e. the vertical axis in horizontal writing modes and the horizontal axis in vertical writing modes.
Block,
}
impl AbstractAxis {
/// Returns the other variant of the enum
#[inline]
pub const fn other(&self) -> AbstractAxis {
match *self {
AbstractAxis::Inline => AbstractAxis::Block,
AbstractAxis::Block => AbstractAxis::Inline,
}
}
/// Convert an `AbstractAxis` into an `AbsoluteAxis` naively assuming that the Inline axis is Horizontal
/// This is currently always true, but will change if Taffy ever implements the `writing_mode` property
#[inline]
pub const fn as_abs_naive(&self) -> AbsoluteAxis {
match self {
AbstractAxis::Inline => AbsoluteAxis::Horizontal,
AbstractAxis::Block => AbsoluteAxis::Vertical,
}
}
}
/// Container that holds an item in each absolute axis without specifying
/// what kind of item it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct InBothAbsAxis<T> {
/// The item in the horizontal axis
pub horizontal: T,
/// The item in the vertical axis
pub vertical: T,
}
impl<T: Copy> InBothAbsAxis<T> {
#[cfg(feature = "grid")]
/// Get the contained item based on the AbsoluteAxis passed
pub const fn get(&self, axis: AbsoluteAxis) -> T {
match axis {
AbsoluteAxis::Horizontal => self.horizontal,
AbsoluteAxis::Vertical => self.vertical,
}
}
}
/// An axis-aligned UI rectangle
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Rect<T> {
/// This can represent either the x-coordinate of the starting edge,
/// or the amount of padding on the starting side.
///
/// The starting edge is the left edge when working with LTR text,
/// and the right edge when working with RTL text.
pub left: T,
/// This can represent either the x-coordinate of the ending edge,
/// or the amount of padding on the ending side.
///
/// The ending edge is the right edge when working with LTR text,
/// and the left edge when working with RTL text.
pub right: T,
/// This can represent either the y-coordinate of the top edge,
/// or the amount of padding on the top side.
pub top: T,
/// This can represent either the y-coordinate of the bottom edge,
/// or the amount of padding on the bottom side.
pub bottom: T,
}
impl<U, T: Add<U>> Add<Rect<U>> for Rect<T> {
type Output = Rect<T::Output>;
fn add(self, rhs: Rect<U>) -> Self::Output {
Rect {
left: self.left + rhs.left,
right: self.right + rhs.right,
top: self.top + rhs.top,
bottom: self.bottom + rhs.bottom,
}
}
}
impl<T> Rect<T> {
/// Swap the horizontal and vertical sides (`left <-> top`, `right <-> bottom`)
#[inline(always)]
pub fn transpose(self) -> Rect<T> {
Rect { left: self.top, right: self.bottom, top: self.left, bottom: self.right }
}
/// Applies the function `f` to all four sides of the rect
///
/// When applied to the left and right sides, the width is used
/// as the second parameter of `f`.
/// When applied to the top or bottom sides, the height is used instead.
#[cfg(any(feature = "flexbox", feature = "block_layout"))]
#[inline(always)]
pub(crate) fn zip_size<R, F, U>(self, size: Size<U>, f: F) -> Rect<R>
where
F: Fn(T, U) -> R,
U: Copy,
{
Rect {
left: f(self.left, size.width),
right: f(self.right, size.width),
top: f(self.top, size.height),
bottom: f(self.bottom, size.height),
}
}
/// Applies the function `f` to the left, right, top, and bottom properties
///
/// This is used to transform a `Rect<T>` into a `Rect<R>`.
#[inline(always)]
pub fn map<R, F>(self, f: F) -> Rect<R>
where
F: Fn(T) -> R,
{
Rect { left: f(self.left), right: f(self.right), top: f(self.top), bottom: f(self.bottom) }
}
/// Returns a `Line<T>` representing the left and right properties of the Rect
pub fn horizontal_components(self) -> Line<T> {
Line { start: self.left, end: self.right }
}
/// Returns a `Line<T>` containing the top and bottom properties of the Rect
pub fn vertical_components(self) -> Line<T> {
Line { start: self.top, end: self.bottom }
}
}
impl<T, U> Rect<T>
where
T: Add<Output = U> + Copy + Clone,
{
/// The sum of [`Rect.start`](Rect) and [`Rect.end`](Rect)
///
/// This is typically used when computing total padding.
///
/// **NOTE:** this is *not* the width of the rectangle.
#[inline(always)]
pub fn horizontal_axis_sum(&self) -> U {
self.left + self.right
}
/// The sum of [`Rect.top`](Rect) and [`Rect.bottom`](Rect)
///
/// This is typically used when computing total padding.
///
/// **NOTE:** this is *not* the height of the rectangle.
#[inline(always)]
pub fn vertical_axis_sum(&self) -> U {
self.top + self.bottom
}
/// Both horizontal_axis_sum and vertical_axis_sum as a `Size<T>`
///
/// **NOTE:** this is *not* the width/height of the rectangle.
#[inline(always)]
#[allow(dead_code)] // Fixes spurious clippy warning: this function is used!
pub fn sum_axes(&self) -> Size<U> {
Size { width: self.horizontal_axis_sum(), height: self.vertical_axis_sum() }
}
/// The sum of the two fields of the [`Rect`] representing the main axis.
///
/// This is typically used when computing total padding.
///
/// If the [`FlexDirection`] is [`FlexDirection::Row`] or [`FlexDirection::RowReverse`], this is [`Rect::horizontal`].
/// Otherwise, this is [`Rect::vertical`].
#[cfg(feature = "flexbox")]
pub(crate) fn main_axis_sum(&self, direction: FlexDirection) -> U {
if direction.is_row() {
self.horizontal_axis_sum()
} else {
self.vertical_axis_sum()
}
}
/// The sum of the two fields of the [`Rect`] representing the cross axis.
///
/// If the [`FlexDirection`] is [`FlexDirection::Row`] or [`FlexDirection::RowReverse`], this is [`Rect::vertical`].
/// Otherwise, this is [`Rect::horizontal`].
#[cfg(feature = "flexbox")]
pub(crate) fn cross_axis_sum(&self, direction: FlexDirection) -> U {
if direction.is_row() {
self.vertical_axis_sum()
} else {
self.horizontal_axis_sum()
}
}
}
impl<T> Rect<T>
where
T: Copy + Clone,
{
/// The `start` or `top` value of the [`Rect`], from the perspective of the main layout axis
#[cfg(feature = "flexbox")]
pub(crate) const fn main_start(&self, direction: FlexDirection) -> T {
if direction.is_row() {
self.left
} else {
self.top
}
}
/// The `end` or `bottom` value of the [`Rect`], from the perspective of the main layout axis
#[cfg(feature = "flexbox")]
pub(crate) const fn main_end(&self, direction: FlexDirection) -> T {
if direction.is_row() {
self.right
} else {
self.bottom
}
}
/// The `start` or `top` value of the [`Rect`], from the perspective of the cross layout axis
#[cfg(feature = "flexbox")]
pub(crate) const fn cross_start(&self, direction: FlexDirection) -> T {
if direction.is_row() {
self.top
} else {
self.left
}
}
/// The `end` or `bottom` value of the [`Rect`], from the perspective of the main layout axis
#[cfg(feature = "flexbox")]
pub(crate) const fn cross_end(&self, direction: FlexDirection) -> T {
if direction.is_row() {
self.bottom
} else {
self.right
}
}
}
impl Rect<Option<f32>> {
/// A [`Rect`] with `None` as all parameters
pub const NONE: Rect<Option<f32>> = Self { left: None, right: None, top: None, bottom: None };
}
impl Rect<f32> {
/// Creates a new Rect with `0.0` as all parameters
pub const ZERO: Rect<f32> = Self { left: 0.0, right: 0.0, top: 0.0, bottom: 0.0 };
/// Creates a new Rect
#[must_use]
pub const fn new(start: f32, end: f32, top: f32, bottom: f32) -> Self {
Self { left: start, right: end, top, bottom }
}
/// Returns the smallest rectangle that contains both `self` and `other`, where the fields
/// of each `Rect` are interpreted as edge coordinates (`left`/`top` being the minimum
/// coordinates and `right`/`bottom` the maximum coordinates of the rectangle)
#[must_use]
pub fn union(self, other: Self) -> Self {
Self {
left: self.left.min(other.left),
right: self.right.max(other.right),
top: self.top.min(other.top),
bottom: self.bottom.max(other.bottom),
}
}
}
/// An abstract "line". Represents any type that has a start and an end
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Line<T> {
/// The start position of a line
pub start: T,
/// The end position of a line
pub end: T,
}
impl<T> Line<T> {
/// Applies the function `f` to both the width and height
///
/// This is used to transform a `Line<T>` into a `Line<R>`.
pub fn map<R, F>(self, f: F) -> Line<R>
where
F: Fn(T) -> R,
{
Line { start: f(self.start), end: f(self.end) }
}
}
impl Line<bool> {
/// A `Line<bool>` with both start and end set to `true`
pub const TRUE: Self = Line { start: true, end: true };
/// A `Line<bool>` with both start and end set to `false`
pub const FALSE: Self = Line { start: false, end: false };
}
impl<T: Add + Copy> Line<T> {
/// Adds the start and end values together and returns the result
pub fn sum(&self) -> <T as Add>::Output {
self.start + self.end
}
}
/// The width and height of a [`Rect`]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Size<T> {
/// The x extent of the rectangle
pub width: T,
/// The y extent of the rectangle
pub height: T,
}
// Generic Add impl for Size<T> + Size<U> where T + U has an Add impl
impl<U, T: Add<U>> Add<Size<U>> for Size<T> {
type Output = Size<<T as Add<U>>::Output>;
fn add(self, rhs: Size<U>) -> Self::Output {
Size { width: self.width + rhs.width, height: self.height + rhs.height }
}
}
// Generic Sub impl for Size<T> + Size<U> where T + U has an Sub impl
impl<U, T: Sub<U>> Sub<Size<U>> for Size<T> {
type Output = Size<<T as Sub<U>>::Output>;
fn sub(self, rhs: Size<U>) -> Self::Output {
Size { width: self.width - rhs.width, height: self.height - rhs.height }
}
}
// Note: we allow dead_code here as we want to provide a complete API of helpers that is symmetrical in all axes,
// but sometimes we only currently have a use for the helper in a single axis
#[allow(dead_code)]
impl<T> Size<T> {
/// Applies the function `f` to both the width and height
///
/// This is used to transform a `Size<T>` into a `Size<R>`.
pub fn map<R, F>(self, f: F) -> Size<R>
where
F: Fn(T) -> R,
{
Size { width: f(self.width), height: f(self.height) }
}
/// Applies the function `f` to the width
pub fn map_width<F>(self, f: F) -> Size<T>
where
F: Fn(T) -> T,
{
Size { width: f(self.width), height: self.height }
}
/// Applies the function `f` to the height
pub fn map_height<F>(self, f: F) -> Size<T>
where
F: Fn(T) -> T,
{
Size { width: self.width, height: f(self.height) }
}
/// Applies the function `f` to both the width and height
/// of this value and another passed value
pub fn zip_map<Other, Ret, Func>(self, other: Size<Other>, f: Func) -> Size<Ret>
where
Func: Fn(T, Other) -> Ret,
{
Size { width: f(self.width, other.width), height: f(self.height, other.height) }
}
/// Sets the extent of the main layout axis
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn set_main(&mut self, direction: FlexDirection, value: T) {
if direction.is_row() {
self.width = value
} else {
self.height = value
}
}
/// Sets the extent of the cross layout axis
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn set_cross(&mut self, direction: FlexDirection, value: T) {
if direction.is_row() {
self.height = value
} else {
self.width = value
}
}
/// Creates a new value of type Self with the main axis set to value provided
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn with_main(self, direction: FlexDirection, value: T) -> Self {
let mut new = self;
if direction.is_row() {
new.width = value
} else {
new.height = value
}
new
}
/// Creates a new value of type Self with the cross axis set to value provided
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn with_cross(self, direction: FlexDirection, value: T) -> Self {
let mut new = self;
if direction.is_row() {
new.height = value
} else {
new.width = value
}
new
}
/// Creates a new value of type Self with the main axis modified by the callback provided
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn map_main(self, direction: FlexDirection, mapper: impl FnOnce(T) -> T) -> Self {
let mut new = self;
if direction.is_row() {
new.width = mapper(new.width);
} else {
new.height = mapper(new.height);
}
new
}
/// Creates a new value of type Self with the cross axis modified by the callback provided
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn map_cross(self, direction: FlexDirection, mapper: impl FnOnce(T) -> T) -> Self {
let mut new = self;
if direction.is_row() {
new.height = mapper(new.height);
} else {
new.width = mapper(new.width);
}
new
}
/// Gets the extent of the main layout axis
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn main(self, direction: FlexDirection) -> T {
if direction.is_row() {
self.width
} else {
self.height
}
}
/// Gets the extent of the cross layout axis
///
/// Whether this is the width or height depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn cross(self, direction: FlexDirection) -> T {
if direction.is_row() {
self.height
} else {
self.width
}
}
/// Gets the extent of the specified layout axis
/// Whether this is the width or height depends on the `GridAxis` provided
#[cfg(feature = "grid")]
pub(crate) fn get(self, axis: AbstractAxis) -> T {
match axis {
AbstractAxis::Inline => self.width,
AbstractAxis::Block => self.height,
}
}
/// Sets the extent of the specified layout axis
/// Whether this is the width or height depends on the `GridAxis` provided
#[cfg(feature = "grid")]
pub(crate) fn set(&mut self, axis: AbstractAxis, value: T) {
match axis {
AbstractAxis::Inline => self.width = value,
AbstractAxis::Block => self.height = value,
}
}
/// Sets the extent of the specified layout axis
/// Whether this is the width or height depends on the `GridAxis` provided
#[cfg(feature = "grid")]
pub(crate) fn with(mut self, axis: AbstractAxis, value: T) -> Self {
match axis {
AbstractAxis::Inline => self.width = value,
AbstractAxis::Block => self.height = value,
}
self
}
}
impl Size<f32> {
/// A [`Size`] with zero width and height
pub const ZERO: Size<f32> = Self { width: 0.0, height: 0.0 };
/// Applies f32_max to each component separately
#[inline(always)]
pub fn f32_max(self, rhs: Size<f32>) -> Size<f32> {
Size { width: f32_max(self.width, rhs.width), height: f32_max(self.height, rhs.height) }
}
/// Applies f32_min to each component separately
#[inline(always)]
pub fn f32_min(self, rhs: Size<f32>) -> Size<f32> {
Size { width: f32_min(self.width, rhs.width), height: f32_min(self.height, rhs.height) }
}
/// Return true if both width and height are greater than 0 else false
#[inline(always)]
pub fn has_non_zero_area(self) -> bool {
self.width > 0.0 && self.height > 0.0
}
}
impl Size<Option<f32>> {
/// A [`Size`] with `None` width and height
pub const NONE: Size<Option<f32>> = Self { width: None, height: None };
/// A [`Size<Option<f32>>`] with `Some(width)` and `Some(height)` as parameters
#[must_use]
pub const fn new(width: f32, height: f32) -> Self {
Size { width: Some(width), height: Some(height) }
}
/// Creates a new [`Size<Option<f32>>`] with either the width or height set based on the provided `direction`
#[cfg(feature = "flexbox")]
pub const fn from_cross(direction: FlexDirection, value: Option<f32>) -> Self {
let mut new = Self::NONE;
if direction.is_row() {
new.height = value
} else {
new.width = value
}
new
}
/// Applies aspect_ratio (if one is supplied) to the Size:
/// - If width is `Some` but height is `None`, then height is computed from width and aspect_ratio
/// - If height is `Some` but width is `None`, then width is computed from height and aspect_ratio
///
/// If aspect_ratio is `None` then this function simply returns self.
pub fn maybe_apply_aspect_ratio(self, aspect_ratio: Option<f32>) -> Size<Option<f32>> {
match aspect_ratio {
Some(ratio) => match (self.width, self.height) {
(Some(width), None) => Size { width: Some(width), height: Some(width / ratio) },
(None, Some(height)) => Size { width: Some(height * ratio), height: Some(height) },
_ => self,
},
None => self,
}
}
}
impl<T> Size<Option<T>> {
/// Performs Option::unwrap_or on each component separately
pub fn unwrap_or(self, alt: Size<T>) -> Size<T> {
Size { width: self.width.unwrap_or(alt.width), height: self.height.unwrap_or(alt.height) }
}
/// Performs Option::or on each component separately
pub fn or(self, alt: Size<Option<T>>) -> Size<Option<T>> {
Size { width: self.width.or(alt.width), height: self.height.or(alt.height) }
}
/// Return true if both components are Some, else false.
#[inline(always)]
pub fn both_axis_defined(&self) -> bool {
self.width.is_some() && self.height.is_some()
}
}
impl Size<Dimension> {
/// Generates a [`Size<Dimension>`] using length values
#[must_use]
pub const fn from_lengths(width: f32, height: f32) -> Self {
Size { width: Dimension(CompactLength::length(width)), height: Dimension(CompactLength::length(height)) }
}
/// Generates a [`Size<Dimension>`] using percentage values
#[must_use]
pub const fn from_percent(width: f32, height: f32) -> Self {
Size { width: Dimension(CompactLength::percent(width)), height: Dimension(CompactLength::percent(height)) }
}
}
/// A 2-dimensional coordinate.
///
/// When used in association with a [`Rect`], represents the top-left corner.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Point<T> {
/// The x-coordinate
pub x: T,
/// The y-coordinate
pub y: T,
}
impl Point<f32> {
/// A [`Point`] with values (0,0), representing the origin
pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
}
impl Point<Option<f32>> {
/// A [`Point`] with values (None, None)
pub const NONE: Self = Self { x: None, y: None };
}
// Generic Add impl for Point<T> + Point<U> where T + U has an Add impl
impl<U, T: Add<U>> Add<Point<U>> for Point<T> {
type Output = Point<<T as Add<U>>::Output>;
fn add(self, rhs: Point<U>) -> Self::Output {
Point { x: self.x + rhs.x, y: self.y + rhs.y }
}
}
impl<T> Point<T> {
/// Applies the function `f` to both the x and y
///
/// This is used to transform a `Point<T>` into a `Point<R>`.
pub fn map<R, F>(self, f: F) -> Point<R>
where
F: Fn(T) -> R,
{
Point { x: f(self.x), y: f(self.y) }
}
/// Gets the extent of the specified layout axis
/// Whether this is the width or height depends on the `GridAxis` provided
#[cfg(feature = "grid")]
pub fn get(self, axis: AbstractAxis) -> T {
match axis {
AbstractAxis::Inline => self.x,
AbstractAxis::Block => self.y,
}
}
/// Swap x and y components
pub fn transpose(self) -> Point<T> {
Point { x: self.y, y: self.x }
}
/// Sets the extent of the specified layout axis
/// Whether this is the width or height depends on the `GridAxis` provided
#[cfg(feature = "grid")]
pub fn set(&mut self, axis: AbstractAxis, value: T) {
match axis {
AbstractAxis::Inline => self.x = value,
AbstractAxis::Block => self.y = value,
}
}
/// Gets the component in the main layout axis
///
/// Whether this is the x or y depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn main(self, direction: FlexDirection) -> T {
if direction.is_row() {
self.x
} else {
self.y
}
}
/// Gets the component in the cross layout axis
///
/// Whether this is the x or y depends on the `direction` provided
#[cfg(feature = "flexbox")]
pub(crate) fn cross(self, direction: FlexDirection) -> T {
if direction.is_row() {
self.y
} else {
self.x
}
}
}
impl<T> From<Point<T>> for Size<T> {
fn from(value: Point<T>) -> Self {
Size { width: value.x, height: value.y }
}
}
/// Generic struct which holds a "min" value and a "max" value
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MinMax<Min, Max> {
/// The value representing the minimum
pub min: Min,
/// The value representing the maximum
pub max: Max,
}
+133
View File
@@ -0,0 +1,133 @@
//! # Taffy
//!
//! Taffy is a flexible, high-performance library for **UI layout**.
//! It currently implements the Flexbox, Grid and Block layout algorithms from the CSS specification. Support for other paradigms is planned.
//! For more information on this and other future development plans see the [roadmap issue](https://github.com/DioxusLabs/taffy/issues/345).
//!
//! ## Architecture
//!
//! Taffy is based on a tree of "UI nodes" similar to the tree of DOM nodes that one finds in web-based UI. Each node has:
//! - A [`Style`] struct which holds a set of CSS styles which function as the primary input to the layout computations.
//! - A [`Layout`] struct containing a position (x/y) and a size (width/height) which function as the output of the layout computations.
//! - Optionally:
//! - A `Vec` set of child nodes
//! - "Context": arbitrary user-defined data (which you can access when using a "measure function" to integrate Taffy with other kinds of layout such as text layout)
//!
//! Usage of Taffy consists of constructing a tree of UI nodes (with associated styles, children and context), then calling function(s)
//! from Taffy to translate those styles, parent-child relationships and measure functions into a size and position in 2d space for each node
//! in the tree.
//!
//! ## High-level API vs. Low-level API
//!
//! Taffy has two APIs: a high-level API that is simpler and easier to get started with, and a low-level API that is more flexible gives greater control.
//! We would generally recommend the high-level API for users using Taffy standalone and the low-level API for users wanting to embed Taffy as part of
//! a wider layout system or as part of a UI framework that already has it's own node/widget tree representation.
//!
//! ### High-level API
//!
//! The high-level API consists of the [`TaffyTree`] struct which contains a tree implementation and provides methods that allow you to construct
//! a tree of UI nodes. Once constructed, you can call the [`compute_layout_with_measure`](crate::TaffyTree::compute_layout_with_measure) method to compute the layout (passing in a "measure function" closure which is used to compute the size of leaf nodes), and then access
//! the layout of each node using the [`layout`](crate::TaffyTree::layout) method.
//!
//! When using the high-level API, Taffy will take care of node storage, caching and dispatching to the correct layout algorithm for a given node for you.
//! See the [`TaffyTree`] struct for more details on this API.
//!
//! Examples which show usage of the high-level API include:
//!
//! - [basic](https://github.com/DioxusLabs/taffy/blob/main/examples/basic.rs)
//! - [flexbox_gap](https://github.com/DioxusLabs/taffy/blob/main/examples/flexbox_gap.rs)
//! - [grid_holy_grail](https://github.com/DioxusLabs/taffy/blob/main/examples/grid_holy_grail.rs)
//! - [measure](https://github.com/DioxusLabs/taffy/blob/main/examples/measure.rs)
//! - [parley](https://github.com/DioxusLabs/taffy/blob/main/examples/parley/src/main.rs)
//!
//! In particular, the "measure" example shows how to integrate Taffy layout with other layout modalities such as text or image layout when using the high level API.
//!
//! ### Low-level API
//!
//! The low-level API consists of a [set of traits](crate::tree::traits) (notably the [`LayoutPartialTree`] trait) which define an interface behind which you must implement your own
//! tree implementation, and a [set of functions](crate::compute) such as [`compute_flexbox_layout`] and [`compute_grid_layout`] which implement the layout algorithms (for a single node at a time), and are designed to be flexible
//! and easy to integrate into a wider layout or UI system.
//!
//! When using this API, you must handle node storage, caching, and dispatching to the correct layout algorithm for a given node yourself.
//! See the [`crate::tree::traits`] module for more details on this API.
//!
//! Examples which show usage of the low-level API are:
//!
//! - [custom_tree_vec](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_vec.rs) which implements a custom Taffy tree using a `Vec` as an arena with NodeId's being index's into the Vec.
//! - [custom_tree_owned_partial](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_partial.rs) which implements a custom Taffy tree using directly owned children with NodeId's being index's into vec on parent node.
//! - [custom_tree_owned_unsafe](https://github.com/DioxusLabs/taffy/blob/main/examples/custom_tree_owned_unsafe.rs) which implements a custom Taffy tree using directly owned children with NodeId's being pointers.
// document the feature flags for the crate by extracting the comments from Cargo.toml
#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
// annotate items with their required features (gated by docsrs flag as this requires the nightly toolchain)
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(unsafe_code)]
#![warn(missing_docs)]
#![warn(clippy::missing_docs_in_private_items)]
// Disable "unused_x" warnings when default features aren't enabled.
#![cfg_attr(not(feature = "default"), allow(dead_code))]
#![cfg_attr(not(feature = "default"), allow(unused_imports))]
#![cfg_attr(not(feature = "default"), allow(unused_variables))]
#![cfg_attr(not(feature = "default"), allow(unused_mut))]
// We always need std for the tests
// See <https://github.com/la10736/rstest/issues/149#issuecomment-1156402989>
#[cfg(all(test, not(feature = "std")))]
#[macro_use]
extern crate std;
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg_attr(feature = "serde", macro_use)]
#[cfg(feature = "serde")]
extern crate serde;
pub mod compute;
pub mod geometry;
pub mod prelude;
pub mod style;
pub mod style_helpers;
pub mod tree;
#[macro_use]
pub mod util;
mod readme_doctest {
#![doc = include_str!("../README.md")]
}
#[cfg(feature = "flexbox")]
#[doc(inline)]
pub use crate::compute::compute_flexbox_layout;
#[cfg(feature = "grid")]
#[doc(inline)]
pub use crate::compute::compute_grid_layout;
pub use crate::compute::detailed_info::*;
#[cfg(feature = "block_layout")]
#[doc(inline)]
pub use crate::compute::{compute_block_align_content_offset, compute_block_layout};
#[doc(inline)]
pub use crate::compute::{
compute_cached_layout, compute_hidden_layout, compute_leaf_layout, compute_oof_layout, compute_oof_layout_for_area,
compute_root_layout, resolve_static_offset, round_layout, OofLayoutResult,
};
#[doc(inline)]
pub use crate::style::Style;
#[doc(inline)]
pub use crate::tree::traits::*;
#[cfg(feature = "taffy_tree")]
#[doc(inline)]
pub use crate::tree::TaffyTree;
#[cfg(feature = "std")]
#[doc(inline)]
pub use crate::util::print_tree;
#[cfg(feature = "parse")]
pub use parse::{ParseError, ParseResult};
pub use crate::compute::*;
pub use crate::geometry::*;
pub use crate::style::*;
pub use crate::tree::*;
pub use crate::util::*;
+31
View File
@@ -0,0 +1,31 @@
//! Commonly used types
pub use crate::{
geometry::{Line, Rect, Size},
style::{
AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace,
BoxSizing, CompactLength, Dimension, Display, JustifyContent, JustifyItems, JustifySelf, LengthPercentage,
LengthPercentageAuto, Position, Style,
},
style_helpers::{
auto, fit_content, length, max_content, min_content, percent, zero, FromFr, FromLength, FromPercent, TaffyAuto,
TaffyFitContent, TaffyMaxContent, TaffyMinContent, TaffyZero,
},
tree::{Layout, LayoutPartialTree, NodeId, PrintTree, RoundTree, TraversePartialTree, TraverseTree},
};
#[cfg(feature = "flexbox")]
pub use crate::style::{FlexDirection, FlexWrap};
#[cfg(feature = "grid")]
pub use crate::style::{
GridAutoFlow, GridPlacement, GridTemplateComponent, MaxTrackSizingFunction, MinTrackSizingFunction,
RepetitionCount, TrackSizingFunction,
};
#[cfg(feature = "grid")]
pub use crate::style_helpers::{
evenly_sized_tracks, flex, fr, line, minmax, repeat, span, TaffyGridLine, TaffyGridSpan,
};
#[cfg(feature = "taffy_tree")]
pub use crate::TaffyTree;
+979
View File
@@ -0,0 +1,979 @@
//! Style types for controlling alignment.
//!
//! The public alignment types ([`AlignItems`], [`AlignContent`], and their aliases) are
//! structs with two orthogonal fields: a *position* keyword
//! ([`AlignItemsKeyword`] / [`AlignContentKeyword`]) and an *overflow-position*
//! modifier ([`AlignmentSafety`]). The pre-existing CSS spellings — `Start`, `End`,
//! `FlexStart`, `FlexEnd`, `Center`, `Stretch`, `SpaceBetween`, …, `SafeStart`,
//! `SafeEnd`, `SafeFlexStart`, `SafeFlexEnd`, `SafeCenter` — are exposed as associated
//! constants on the structs, so call sites read identically to the previous enum form.
#[cfg(feature = "parse")]
use crate::util::parse::{CssParseResult, FromCss, Parser, Token};
use crate::style::Direction;
/// The position-keyword half of [`AlignItems`] (and its aliases `AlignSelf`,
/// `JustifyItems`, `JustifySelf`).
///
/// Compute paths match on this enum directly so every match is exhaustive and
/// requires no `Safe*` siblings.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)]
pub enum AlignItemsKeyword {
/// The layout mode's default alignment: usually `Stretch`, but `Start` in some cases.
#[default]
Normal,
/// Items are packed toward the start of the axis.
Start,
/// Items are packed toward the end of the axis.
End,
/// Items are packed towards the flex-relative start of the axis.
///
/// For flex containers with flex_direction RowReverse or ColumnReverse this is
/// equivalent to End. In all other cases it is equivalent to Start.
FlexStart,
/// Items are packed towards the flex-relative end of the axis.
///
/// For flex containers with flex_direction RowReverse or ColumnReverse this is
/// equivalent to Start. In all other cases it is equivalent to End.
FlexEnd,
/// Items are packed toward the start of the axis as determined by the item's own
/// writing mode/direction (rather than the container's).
///
/// Equivalent to Start when the item's `direction` matches the container's, and
/// to End when they differ (in the inline axis).
SelfStart,
/// Items are packed toward the end of the axis as determined by the item's own
/// writing mode/direction (rather than the container's).
///
/// Equivalent to End when the item's `direction` matches the container's, and
/// to Start when they differ (in the inline axis).
SelfEnd,
/// Items are packed along the center of the cross axis.
Center,
/// Items are aligned such as their baselines align.
Baseline,
/// Stretch to fill the container.
Stretch,
}
/// The position-keyword half of [`AlignContent`] (and its alias `JustifyContent`).
///
/// Compute paths match on this enum directly so every match is exhaustive and
/// requires no `Safe*` siblings.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)]
pub enum AlignContentKeyword {
/// The layout mode's default alignment: `Stretch` for flex and grid containers, `Start`
/// for block containers.
#[default]
Normal,
/// Items are packed toward the start of the axis.
Start,
/// Items are packed toward the end of the axis.
End,
/// Items are packed towards the flex-relative start of the axis.
FlexStart,
/// Items are packed towards the flex-relative end of the axis.
FlexEnd,
/// Items are centered around the middle of the axis.
Center,
/// Items are stretched to fill the container.
Stretch,
/// The first and last items are aligned flush with the edges of the container
/// (no gap). The gap between items is distributed evenly.
SpaceBetween,
/// The gap between the first and last items is exactly THE SAME as the gap
/// between items. The gaps are distributed evenly.
SpaceEvenly,
/// The gap between the first and last items is exactly HALF the gap between
/// items. The gaps are distributed evenly in proportion to these ratios.
SpaceAround,
}
impl AlignContentKeyword {
/// Returns the reversed keyword for RTL (right-to-left) contexts: `Start`↔`End`,
/// `FlexStart`↔`FlexEnd`. `Stretch` maps to `End` to preserve the layout
/// algorithms' historical handling. `Normal`, `Center` and the distribution keywords
/// (`SpaceBetween`, `SpaceEvenly`, `SpaceAround`) are unaffected because their
/// visual placement is direction-symmetric.
pub(crate) fn reversed(self) -> Self {
match self {
Self::Start => Self::End,
Self::End => Self::Start,
Self::FlexStart => Self::FlexEnd,
Self::FlexEnd => Self::FlexStart,
Self::Stretch => Self::End,
Self::Normal | Self::Center | Self::SpaceBetween | Self::SpaceEvenly | Self::SpaceAround => self,
}
}
}
/// The overflow-position modifier per [CSS Box Alignment §4.3][css-align-overflow].
///
/// `Safe` falls back to start-edge alignment when the alignment subject would
/// overflow the alignment container, so the start of the content stays visible.
/// `Unsafe` keeps the requested alignment even when that causes overflow at the
/// start edge. `Default` (no overflow-position keyword specified) behaves as
/// `Unsafe`, except for absolutely positioned boxes whose alignment is instead
/// adjusted to minimize overflow per [CSS Box Alignment §4.4.1.2][css-align-abspos].
///
/// CSS only defines `safe` / `unsafe` against the position values `start`, `end`,
/// `flex-start`, `flex-end`, `center`. The struct shape does not enforce that
/// constraint at the type level — the parser rejects invalid combinations, and
/// the compute pass treats `Safe` paired with a non-position keyword (`Stretch`,
/// `Baseline`, `Space*`) the same as `Unsafe`.
///
/// [css-align-overflow]: https://www.w3.org/TR/css-align-3/#overflow-values
/// [css-align-abspos]: https://www.w3.org/TR/css-align-3/#auto-safety-position
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)]
pub enum AlignmentSafety {
/// No overflow-position keyword specified. Behaves as `Unsafe`, except for absolutely
/// positioned boxes, whose alignment is adjusted to minimize overflow of their
/// containing block.
#[default]
Default,
/// Keeps the requested alignment even when the subject overflows the alignment
/// container at the start edge.
Unsafe,
/// Falls back to the start edge when the subject would overflow, to avoid data
/// loss.
Safe,
}
/// Used to control how child nodes are aligned.
/// For Flexbox it controls alignment in the cross axis.
/// For Grid it controls alignment in the block axis.
///
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub struct AlignItems {
/// Position keyword.
pub keyword: AlignItemsKeyword,
/// Overflow-position modifier (`safe` / `unsafe`).
pub safety: AlignmentSafety,
}
impl AlignItems {
/// The layout mode's default alignment. See [`AlignItemsKeyword::Normal`].
pub const NORMAL: Self = Self { keyword: AlignItemsKeyword::Normal, safety: AlignmentSafety::Default };
/// Items are packed toward the start of the axis.
pub const START: Self = Self { keyword: AlignItemsKeyword::Start, safety: AlignmentSafety::Default };
/// Items are packed toward the end of the axis.
pub const END: Self = Self { keyword: AlignItemsKeyword::End, safety: AlignmentSafety::Default };
/// Items are packed towards the flex-relative start of the axis.
pub const FLEX_START: Self = Self { keyword: AlignItemsKeyword::FlexStart, safety: AlignmentSafety::Default };
/// Items are packed towards the flex-relative end of the axis.
pub const FLEX_END: Self = Self { keyword: AlignItemsKeyword::FlexEnd, safety: AlignmentSafety::Default };
/// Items are packed toward the start of the axis as determined by the item's own direction.
pub const SELF_START: Self = Self { keyword: AlignItemsKeyword::SelfStart, safety: AlignmentSafety::Default };
/// Items are packed toward the end of the axis as determined by the item's own direction.
pub const SELF_END: Self = Self { keyword: AlignItemsKeyword::SelfEnd, safety: AlignmentSafety::Default };
/// Items are packed along the center of the cross axis.
pub const CENTER: Self = Self { keyword: AlignItemsKeyword::Center, safety: AlignmentSafety::Default };
/// Items are aligned such as their baselines align.
pub const BASELINE: Self = Self { keyword: AlignItemsKeyword::Baseline, safety: AlignmentSafety::Default };
/// Stretch to fill the container.
pub const STRETCH: Self = Self { keyword: AlignItemsKeyword::Stretch, safety: AlignmentSafety::Default };
/// Like [`AlignItems::START`], but falls back to [`AlignItems::START`] when the
/// alignment subject overflows the alignment container, to avoid data loss.
pub const SAFE_START: Self = Self { keyword: AlignItemsKeyword::Start, safety: AlignmentSafety::Safe };
/// Like [`AlignItems::END`], but falls back to [`AlignItems::START`] when the
/// alignment subject overflows the alignment container, to avoid data loss.
pub const SAFE_END: Self = Self { keyword: AlignItemsKeyword::End, safety: AlignmentSafety::Safe };
/// Like [`AlignItems::FLEX_START`], but falls back to [`AlignItems::START`] when the
/// alignment subject overflows the alignment container, to avoid data loss.
pub const SAFE_FLEX_START: Self = Self { keyword: AlignItemsKeyword::FlexStart, safety: AlignmentSafety::Safe };
/// Like [`AlignItems::FLEX_END`], but falls back to [`AlignItems::START`] when the
/// alignment subject overflows the alignment container, to avoid data loss.
pub const SAFE_FLEX_END: Self = Self { keyword: AlignItemsKeyword::FlexEnd, safety: AlignmentSafety::Safe };
/// Like [`AlignItems::CENTER`], but falls back to [`AlignItems::START`] when the
/// alignment subject overflows the alignment container, to avoid data loss.
pub const SAFE_CENTER: Self = Self { keyword: AlignItemsKeyword::Center, safety: AlignmentSafety::Safe };
/// Like [`AlignItems::SELF_START`], but falls back to [`AlignItems::START`] when the
/// alignment subject overflows the alignment container, to avoid data loss.
pub const SAFE_SELF_START: Self = Self { keyword: AlignItemsKeyword::SelfStart, safety: AlignmentSafety::Safe };
/// Like [`AlignItems::SELF_END`], but falls back to [`AlignItems::START`] when the
/// alignment subject overflows the alignment container, to avoid data loss.
pub const SAFE_SELF_END: Self = Self { keyword: AlignItemsKeyword::SelfEnd, safety: AlignmentSafety::Safe };
/// Returns `true` iff this carries the `safe` overflow-position modifier.
#[inline]
pub const fn is_safe(self) -> bool {
matches!(self.safety, AlignmentSafety::Safe)
}
/// Returns this alignment with the given overflow-position modifier.
#[inline]
pub const fn with_safety(self, safety: AlignmentSafety) -> Self {
Self { keyword: self.keyword, safety }
}
/// Returns the underlying position keyword, discarding the safety modifier.
#[inline]
pub const fn keyword(self) -> AlignItemsKeyword {
self.keyword
}
/// Returns true if the keyword is `Stretch` or `Normal` (ignoring any overflow-position
/// modifier).
#[inline(always)]
pub const fn is_stretch_or_normal(self) -> bool {
matches!(self.keyword, AlignItemsKeyword::Stretch | AlignItemsKeyword::Normal)
}
/// Resolve the writing-mode-relative `SelfStart`/`SelfEnd` keywords to `Start`/`End`
/// based on the item's own `direction` per CSS Box Alignment §5.2
/// <https://www.w3.org/TR/css-align-3/#self-alignment>. All other keywords are
/// returned unchanged.
///
/// The `Start`/`End` keywords used by the compute paths are relative to the
/// *container's* writing mode/direction, so in the inline axis `SelfStart` resolves
/// to `Start` when the item's direction matches the container's and to `End` when it
/// differs. Taffy only supports the `horizontal-tb` writing mode, so in the block
/// axis `SelfStart`/`SelfEnd` always resolve to `Start`/`End` respectively.
#[inline]
pub fn resolve_self_relative(
self,
item_direction: Direction,
container_direction: Direction,
axis_is_inline: bool,
) -> Self {
let flip = axis_is_inline && item_direction != container_direction;
let keyword = match self.keyword {
AlignItemsKeyword::SelfStart => {
if flip {
AlignItemsKeyword::End
} else {
AlignItemsKeyword::Start
}
}
AlignItemsKeyword::SelfEnd => {
if flip {
AlignItemsKeyword::Start
} else {
AlignItemsKeyword::End
}
}
other => other,
};
Self { keyword, safety: self.safety }
}
}
#[cfg(feature = "parse")]
impl FromCss for AlignItems {
fn from_css<'i>(input: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
let first = input.expect_ident()?.clone();
cssparser::match_ignore_ascii_case! { &*first,
"safe" => {
let pos = input.expect_ident()?.clone();
cssparser::match_ignore_ascii_case! { &*pos,
"start" => Ok(Self::SAFE_START),
"end" => Ok(Self::SAFE_END),
"flex-start" => Ok(Self::SAFE_FLEX_START),
"flex-end" => Ok(Self::SAFE_FLEX_END),
"self-start" => Ok(Self::SAFE_SELF_START),
"self-end" => Ok(Self::SAFE_SELF_END),
"center" => Ok(Self::SAFE_CENTER),
_ => Err(input.new_unexpected_token_error(Token::Ident(pos))),
}
},
"unsafe" => {
let pos = input.expect_ident()?.clone();
let keyword = cssparser::match_ignore_ascii_case! { &*pos,
"start" => AlignItemsKeyword::Start,
"end" => AlignItemsKeyword::End,
"flex-start" => AlignItemsKeyword::FlexStart,
"flex-end" => AlignItemsKeyword::FlexEnd,
"self-start" => AlignItemsKeyword::SelfStart,
"self-end" => AlignItemsKeyword::SelfEnd,
"center" => AlignItemsKeyword::Center,
_ => return Err(input.new_unexpected_token_error(Token::Ident(pos))),
};
Ok(Self { keyword, safety: AlignmentSafety::Unsafe })
},
"normal" => Ok(Self::NORMAL),
"start" => Ok(Self::START),
"end" => Ok(Self::END),
"flex-start" => Ok(Self::FLEX_START),
"flex-end" => Ok(Self::FLEX_END),
"self-start" => Ok(Self::SELF_START),
"self-end" => Ok(Self::SELF_END),
"center" => Ok(Self::CENTER),
"baseline" => Ok(Self::BASELINE),
"stretch" => Ok(Self::STRETCH),
_ => Err(input.new_unexpected_token_error(Token::Ident(first))),
}
}
}
#[cfg(feature = "parse")]
crate::util::parse::from_str_from_css!(AlignItems);
/// Used to control how child nodes are aligned.
/// Does not apply to Flexbox, and will be ignored if specified on a flex container.
/// For Grid it controls alignment in the inline axis.
///
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
pub type JustifyItems = AlignItems;
/// Controls alignment of an individual node.
///
/// Overrides the parent Node's `AlignItems` property.
/// For Flexbox it controls alignment in the cross axis.
/// For Grid it controls alignment in the block axis.
///
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
pub type AlignSelf = AlignItems;
/// Controls alignment of an individual node.
///
/// Overrides the parent Node's `JustifyItems` property.
/// Does not apply to Flexbox, and will be ignored if specified on a flex child.
/// For Grid it controls alignment in the inline axis.
///
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
pub type JustifySelf = AlignItems;
/// Sets the distribution of space between and around content items.
/// For Flexbox it controls alignment in the cross axis.
/// For Grid it controls alignment in the block axis.
///
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub struct AlignContent {
/// Position keyword.
pub keyword: AlignContentKeyword,
/// Overflow-position modifier (`safe` / `unsafe`).
pub safety: AlignmentSafety,
}
impl AlignContent {
/// The layout mode's default alignment. See [`AlignContentKeyword::Normal`].
pub const NORMAL: Self = Self { keyword: AlignContentKeyword::Normal, safety: AlignmentSafety::Default };
/// Items are packed toward the start of the axis.
pub const START: Self = Self { keyword: AlignContentKeyword::Start, safety: AlignmentSafety::Default };
/// Items are packed toward the end of the axis.
pub const END: Self = Self { keyword: AlignContentKeyword::End, safety: AlignmentSafety::Default };
/// Items are packed towards the flex-relative start of the axis.
pub const FLEX_START: Self = Self { keyword: AlignContentKeyword::FlexStart, safety: AlignmentSafety::Default };
/// Items are packed towards the flex-relative end of the axis.
pub const FLEX_END: Self = Self { keyword: AlignContentKeyword::FlexEnd, safety: AlignmentSafety::Default };
/// Items are centered around the middle of the axis.
pub const CENTER: Self = Self { keyword: AlignContentKeyword::Center, safety: AlignmentSafety::Default };
/// Items are stretched to fill the container.
pub const STRETCH: Self = Self { keyword: AlignContentKeyword::Stretch, safety: AlignmentSafety::Default };
/// The first and last items are aligned flush with the edges of the container.
pub const SPACE_BETWEEN: Self =
Self { keyword: AlignContentKeyword::SpaceBetween, safety: AlignmentSafety::Default };
/// The gap between the first and last items equals the gap between items.
pub const SPACE_EVENLY: Self = Self { keyword: AlignContentKeyword::SpaceEvenly, safety: AlignmentSafety::Default };
/// The gap between the first and last items is half the gap between items.
pub const SPACE_AROUND: Self = Self { keyword: AlignContentKeyword::SpaceAround, safety: AlignmentSafety::Default };
/// Like [`AlignContent::START`], but falls back to [`AlignContent::START`] when the
/// content overflows the alignment container, to avoid data loss.
pub const SAFE_START: Self = Self { keyword: AlignContentKeyword::Start, safety: AlignmentSafety::Safe };
/// Like [`AlignContent::END`], but falls back to [`AlignContent::START`] when the
/// content overflows the alignment container, to avoid data loss.
pub const SAFE_END: Self = Self { keyword: AlignContentKeyword::End, safety: AlignmentSafety::Safe };
/// Like [`AlignContent::FLEX_START`], but falls back to [`AlignContent::START`] when
/// the content overflows the alignment container, to avoid data loss.
pub const SAFE_FLEX_START: Self = Self { keyword: AlignContentKeyword::FlexStart, safety: AlignmentSafety::Safe };
/// Like [`AlignContent::FLEX_END`], but falls back to [`AlignContent::START`] when the
/// content overflows the alignment container, to avoid data loss.
pub const SAFE_FLEX_END: Self = Self { keyword: AlignContentKeyword::FlexEnd, safety: AlignmentSafety::Safe };
/// Like [`AlignContent::CENTER`], but falls back to [`AlignContent::START`] when the
/// content overflows the alignment container, to avoid data loss.
pub const SAFE_CENTER: Self = Self { keyword: AlignContentKeyword::Center, safety: AlignmentSafety::Safe };
/// Returns `true` iff this carries the `safe` overflow-position modifier.
#[inline]
pub const fn is_safe(self) -> bool {
matches!(self.safety, AlignmentSafety::Safe)
}
/// Returns this alignment with the given overflow-position modifier.
#[inline]
pub const fn with_safety(self, safety: AlignmentSafety) -> Self {
Self { keyword: self.keyword, safety }
}
/// Returns the underlying position keyword, discarding the safety modifier.
#[inline]
pub const fn keyword(self) -> AlignContentKeyword {
self.keyword
}
}
#[cfg(feature = "parse")]
impl FromCss for AlignContent {
fn from_css<'i>(input: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
let first = input.expect_ident()?.clone();
cssparser::match_ignore_ascii_case! { &*first,
"safe" => {
let pos = input.expect_ident()?.clone();
cssparser::match_ignore_ascii_case! { &*pos,
"start" => Ok(Self::SAFE_START),
"end" => Ok(Self::SAFE_END),
"flex-start" => Ok(Self::SAFE_FLEX_START),
"flex-end" => Ok(Self::SAFE_FLEX_END),
"center" => Ok(Self::SAFE_CENTER),
_ => Err(input.new_unexpected_token_error(Token::Ident(pos))),
}
},
"unsafe" => {
let pos = input.expect_ident()?.clone();
let keyword = cssparser::match_ignore_ascii_case! { &*pos,
"start" => AlignContentKeyword::Start,
"end" => AlignContentKeyword::End,
"flex-start" => AlignContentKeyword::FlexStart,
"flex-end" => AlignContentKeyword::FlexEnd,
"center" => AlignContentKeyword::Center,
_ => return Err(input.new_unexpected_token_error(Token::Ident(pos))),
};
Ok(Self { keyword, safety: AlignmentSafety::Unsafe })
},
"normal" => Ok(Self::NORMAL),
"start" => Ok(Self::START),
"end" => Ok(Self::END),
"flex-start" => Ok(Self::FLEX_START),
"flex-end" => Ok(Self::FLEX_END),
"center" => Ok(Self::CENTER),
"stretch" => Ok(Self::STRETCH),
"space-between" => Ok(Self::SPACE_BETWEEN),
"space-evenly" => Ok(Self::SPACE_EVENLY),
"space-around" => Ok(Self::SPACE_AROUND),
_ => Err(input.new_unexpected_token_error(Token::Ident(first))),
}
}
}
#[cfg(feature = "parse")]
crate::util::parse::from_str_from_css!(AlignContent);
/// Sets the distribution of space between and around content items.
/// For Flexbox it controls alignment in the main axis.
/// For Grid it controls alignment in the inline axis.
///
/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
pub type JustifyContent = AlignContent;
// ---------------------------------------------------------------------------
// Serde — custom impls preserve the pre-struct wire format (single tag string
// per public spelling) so consumers reading data serialized before the refactor
// continue to deserialize correctly.
// ---------------------------------------------------------------------------
/// Canonical tag-string set accepted by [`AlignItems`] serde deserialization, used in
/// `unknown_variant` errors. Mirrors the spellings produced by `Serialize`.
#[cfg(feature = "serde")]
const ALIGN_ITEMS_NAMES: &[&str] = &[
"Normal",
"Start",
"End",
"FlexStart",
"FlexEnd",
"SelfStart",
"SelfEnd",
"Center",
"Baseline",
"Stretch",
"SafeStart",
"SafeEnd",
"SafeFlexStart",
"SafeFlexEnd",
"SafeSelfStart",
"SafeSelfEnd",
"SafeCenter",
"UnsafeStart",
"UnsafeEnd",
"UnsafeFlexStart",
"UnsafeFlexEnd",
"UnsafeSelfStart",
"UnsafeSelfEnd",
"UnsafeCenter",
];
#[cfg(feature = "serde")]
impl serde::Serialize for AlignItems {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let name = match (self.keyword, self.safety) {
(AlignItemsKeyword::Start, AlignmentSafety::Default) => "Start",
(AlignItemsKeyword::End, AlignmentSafety::Default) => "End",
(AlignItemsKeyword::FlexStart, AlignmentSafety::Default) => "FlexStart",
(AlignItemsKeyword::FlexEnd, AlignmentSafety::Default) => "FlexEnd",
(AlignItemsKeyword::SelfStart, AlignmentSafety::Default) => "SelfStart",
(AlignItemsKeyword::SelfEnd, AlignmentSafety::Default) => "SelfEnd",
(AlignItemsKeyword::Center, AlignmentSafety::Default) => "Center",
(AlignItemsKeyword::Start, AlignmentSafety::Unsafe) => "UnsafeStart",
(AlignItemsKeyword::End, AlignmentSafety::Unsafe) => "UnsafeEnd",
(AlignItemsKeyword::FlexStart, AlignmentSafety::Unsafe) => "UnsafeFlexStart",
(AlignItemsKeyword::FlexEnd, AlignmentSafety::Unsafe) => "UnsafeFlexEnd",
(AlignItemsKeyword::SelfStart, AlignmentSafety::Unsafe) => "UnsafeSelfStart",
(AlignItemsKeyword::SelfEnd, AlignmentSafety::Unsafe) => "UnsafeSelfEnd",
(AlignItemsKeyword::Center, AlignmentSafety::Unsafe) => "UnsafeCenter",
(AlignItemsKeyword::Normal, _) => "Normal",
(AlignItemsKeyword::Baseline, _) => "Baseline",
(AlignItemsKeyword::Stretch, _) => "Stretch",
(AlignItemsKeyword::Start, AlignmentSafety::Safe) => "SafeStart",
(AlignItemsKeyword::End, AlignmentSafety::Safe) => "SafeEnd",
(AlignItemsKeyword::FlexStart, AlignmentSafety::Safe) => "SafeFlexStart",
(AlignItemsKeyword::FlexEnd, AlignmentSafety::Safe) => "SafeFlexEnd",
(AlignItemsKeyword::SelfStart, AlignmentSafety::Safe) => "SafeSelfStart",
(AlignItemsKeyword::SelfEnd, AlignmentSafety::Safe) => "SafeSelfEnd",
(AlignItemsKeyword::Center, AlignmentSafety::Safe) => "SafeCenter",
};
serializer.serialize_str(name)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for AlignItems {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct AlignItemsVisitor;
impl<'de> serde::de::Visitor<'de> for AlignItemsVisitor {
type Value = AlignItems;
fn expecting(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
fmt.write_str("an AlignItems variant tag string")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
Ok(match v {
"Normal" => AlignItems::NORMAL,
"Start" => AlignItems::START,
"End" => AlignItems::END,
"FlexStart" => AlignItems::FLEX_START,
"FlexEnd" => AlignItems::FLEX_END,
"SelfStart" => AlignItems::SELF_START,
"SelfEnd" => AlignItems::SELF_END,
"Center" => AlignItems::CENTER,
"Baseline" => AlignItems::BASELINE,
"Stretch" => AlignItems::STRETCH,
"SafeStart" => AlignItems::SAFE_START,
"SafeEnd" => AlignItems::SAFE_END,
"SafeFlexStart" => AlignItems::SAFE_FLEX_START,
"SafeFlexEnd" => AlignItems::SAFE_FLEX_END,
"SafeSelfStart" => AlignItems::SAFE_SELF_START,
"SafeSelfEnd" => AlignItems::SAFE_SELF_END,
"SafeCenter" => AlignItems::SAFE_CENTER,
"UnsafeStart" => AlignItems::START.with_safety(AlignmentSafety::Unsafe),
"UnsafeEnd" => AlignItems::END.with_safety(AlignmentSafety::Unsafe),
"UnsafeFlexStart" => AlignItems::FLEX_START.with_safety(AlignmentSafety::Unsafe),
"UnsafeFlexEnd" => AlignItems::FLEX_END.with_safety(AlignmentSafety::Unsafe),
"UnsafeSelfStart" => AlignItems::SELF_START.with_safety(AlignmentSafety::Unsafe),
"UnsafeSelfEnd" => AlignItems::SELF_END.with_safety(AlignmentSafety::Unsafe),
"UnsafeCenter" => AlignItems::CENTER.with_safety(AlignmentSafety::Unsafe),
other => return Err(E::unknown_variant(other, ALIGN_ITEMS_NAMES)),
})
}
}
deserializer.deserialize_str(AlignItemsVisitor)
}
}
/// Canonical tag-string set accepted by [`AlignContent`] serde deserialization, used in
/// `unknown_variant` errors. Mirrors the spellings produced by `Serialize`.
#[cfg(feature = "serde")]
const ALIGN_CONTENT_NAMES: &[&str] = &[
"Normal",
"Start",
"End",
"FlexStart",
"FlexEnd",
"Center",
"Stretch",
"SpaceBetween",
"SpaceEvenly",
"SpaceAround",
"SafeStart",
"SafeEnd",
"SafeFlexStart",
"SafeFlexEnd",
"SafeCenter",
"UnsafeStart",
"UnsafeEnd",
"UnsafeFlexStart",
"UnsafeFlexEnd",
"UnsafeCenter",
];
#[cfg(feature = "serde")]
impl serde::Serialize for AlignContent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let name = match (self.keyword, self.safety) {
(AlignContentKeyword::Start, AlignmentSafety::Default) => "Start",
(AlignContentKeyword::End, AlignmentSafety::Default) => "End",
(AlignContentKeyword::FlexStart, AlignmentSafety::Default) => "FlexStart",
(AlignContentKeyword::FlexEnd, AlignmentSafety::Default) => "FlexEnd",
(AlignContentKeyword::Center, AlignmentSafety::Default) => "Center",
(AlignContentKeyword::Start, AlignmentSafety::Unsafe) => "UnsafeStart",
(AlignContentKeyword::End, AlignmentSafety::Unsafe) => "UnsafeEnd",
(AlignContentKeyword::FlexStart, AlignmentSafety::Unsafe) => "UnsafeFlexStart",
(AlignContentKeyword::FlexEnd, AlignmentSafety::Unsafe) => "UnsafeFlexEnd",
(AlignContentKeyword::Center, AlignmentSafety::Unsafe) => "UnsafeCenter",
(AlignContentKeyword::Normal, _) => "Normal",
(AlignContentKeyword::Stretch, _) => "Stretch",
(AlignContentKeyword::SpaceBetween, _) => "SpaceBetween",
(AlignContentKeyword::SpaceEvenly, _) => "SpaceEvenly",
(AlignContentKeyword::SpaceAround, _) => "SpaceAround",
(AlignContentKeyword::Start, AlignmentSafety::Safe) => "SafeStart",
(AlignContentKeyword::End, AlignmentSafety::Safe) => "SafeEnd",
(AlignContentKeyword::FlexStart, AlignmentSafety::Safe) => "SafeFlexStart",
(AlignContentKeyword::FlexEnd, AlignmentSafety::Safe) => "SafeFlexEnd",
(AlignContentKeyword::Center, AlignmentSafety::Safe) => "SafeCenter",
};
serializer.serialize_str(name)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for AlignContent {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct AlignContentVisitor;
impl<'de> serde::de::Visitor<'de> for AlignContentVisitor {
type Value = AlignContent;
fn expecting(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
fmt.write_str("an AlignContent variant tag string")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
Ok(match v {
"Normal" => AlignContent::NORMAL,
"Start" => AlignContent::START,
"End" => AlignContent::END,
"FlexStart" => AlignContent::FLEX_START,
"FlexEnd" => AlignContent::FLEX_END,
"Center" => AlignContent::CENTER,
"Stretch" => AlignContent::STRETCH,
"SpaceBetween" => AlignContent::SPACE_BETWEEN,
"SpaceEvenly" => AlignContent::SPACE_EVENLY,
"SpaceAround" => AlignContent::SPACE_AROUND,
"SafeStart" => AlignContent::SAFE_START,
"SafeEnd" => AlignContent::SAFE_END,
"SafeFlexStart" => AlignContent::SAFE_FLEX_START,
"SafeFlexEnd" => AlignContent::SAFE_FLEX_END,
"SafeCenter" => AlignContent::SAFE_CENTER,
"UnsafeStart" => AlignContent::START.with_safety(AlignmentSafety::Unsafe),
"UnsafeEnd" => AlignContent::END.with_safety(AlignmentSafety::Unsafe),
"UnsafeFlexStart" => AlignContent::FLEX_START.with_safety(AlignmentSafety::Unsafe),
"UnsafeFlexEnd" => AlignContent::FLEX_END.with_safety(AlignmentSafety::Unsafe),
"UnsafeCenter" => AlignContent::CENTER.with_safety(AlignmentSafety::Unsafe),
other => return Err(E::unknown_variant(other, ALIGN_CONTENT_NAMES)),
})
}
}
deserializer.deserialize_str(AlignContentVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::mem::size_of;
// Size budget — struct = 1B keyword + 1B safety, no niche packing.
// Pre-refactor each was a single-byte enum; spec §V13 caps regression at +2B.
#[test]
fn align_types_within_size_budget() {
assert!(size_of::<AlignItems>() <= 2, "AlignItems grew to {}", size_of::<AlignItems>());
assert!(size_of::<AlignContent>() <= 2, "AlignContent grew to {}", size_of::<AlignContent>());
assert!(size_of::<Option<AlignItems>>() <= 3);
}
#[test]
fn align_items_is_safe() {
assert!(AlignItems::SAFE_START.is_safe());
assert!(AlignItems::SAFE_END.is_safe());
assert!(AlignItems::SAFE_FLEX_START.is_safe());
assert!(AlignItems::SAFE_FLEX_END.is_safe());
assert!(AlignItems::SAFE_CENTER.is_safe());
assert!(!AlignItems::START.is_safe());
assert!(!AlignItems::END.is_safe());
assert!(!AlignItems::FLEX_START.is_safe());
assert!(!AlignItems::FLEX_END.is_safe());
assert!(!AlignItems::CENTER.is_safe());
assert!(!AlignItems::BASELINE.is_safe());
assert!(!AlignItems::STRETCH.is_safe());
assert!(AlignItems::SAFE_SELF_START.is_safe());
assert!(AlignItems::SAFE_SELF_END.is_safe());
assert!(!AlignItems::SELF_START.is_safe());
assert!(!AlignItems::SELF_END.is_safe());
assert!(!AlignItems::NORMAL.is_safe());
}
#[test]
fn align_items_keyword_strips_safe() {
assert_eq!(AlignItems::SAFE_START.keyword(), AlignItemsKeyword::Start);
assert_eq!(AlignItems::SAFE_END.keyword(), AlignItemsKeyword::End);
assert_eq!(AlignItems::SAFE_FLEX_START.keyword(), AlignItemsKeyword::FlexStart);
assert_eq!(AlignItems::SAFE_FLEX_END.keyword(), AlignItemsKeyword::FlexEnd);
assert_eq!(AlignItems::SAFE_CENTER.keyword(), AlignItemsKeyword::Center);
assert_eq!(AlignItems::SAFE_SELF_START.keyword(), AlignItemsKeyword::SelfStart);
assert_eq!(AlignItems::SAFE_SELF_END.keyword(), AlignItemsKeyword::SelfEnd);
}
#[test]
fn align_items_keyword_passthrough() {
assert_eq!(AlignItems::START.keyword(), AlignItemsKeyword::Start);
assert_eq!(AlignItems::STRETCH.keyword(), AlignItemsKeyword::Stretch);
assert_eq!(AlignItems::BASELINE.keyword(), AlignItemsKeyword::Baseline);
assert_eq!(AlignItems::FLEX_START.keyword(), AlignItemsKeyword::FlexStart);
assert_eq!(AlignItems::NORMAL.keyword(), AlignItemsKeyword::Normal);
}
#[test]
fn align_items_default_is_normal() {
assert_eq!(AlignItems::default(), AlignItems::NORMAL);
assert_eq!(AlignItemsKeyword::default(), AlignItemsKeyword::Normal);
assert_eq!(AlignmentSafety::default(), AlignmentSafety::Default);
}
#[test]
fn resolve_self_relative_inline_axis() {
use Direction::{Ltr, Rtl};
// Same direction: self-start == start, self-end == end
assert_eq!(AlignItems::SELF_START.resolve_self_relative(Ltr, Ltr, true), AlignItems::START);
assert_eq!(AlignItems::SELF_END.resolve_self_relative(Ltr, Ltr, true), AlignItems::END);
assert_eq!(AlignItems::SELF_START.resolve_self_relative(Rtl, Rtl, true), AlignItems::START);
assert_eq!(AlignItems::SELF_END.resolve_self_relative(Rtl, Rtl, true), AlignItems::END);
// Opposite direction: self-start == end, self-end == start
assert_eq!(AlignItems::SELF_START.resolve_self_relative(Ltr, Rtl, true), AlignItems::END);
assert_eq!(AlignItems::SELF_END.resolve_self_relative(Ltr, Rtl, true), AlignItems::START);
assert_eq!(AlignItems::SELF_START.resolve_self_relative(Rtl, Ltr, true), AlignItems::END);
assert_eq!(AlignItems::SELF_END.resolve_self_relative(Rtl, Ltr, true), AlignItems::START);
// Safety modifier is preserved
assert_eq!(AlignItems::SAFE_SELF_START.resolve_self_relative(Ltr, Rtl, true), AlignItems::SAFE_END);
// Other keywords are unchanged
assert_eq!(AlignItems::START.resolve_self_relative(Ltr, Rtl, true), AlignItems::START);
assert_eq!(AlignItems::FLEX_END.resolve_self_relative(Ltr, Rtl, true), AlignItems::FLEX_END);
assert_eq!(AlignItems::NORMAL.resolve_self_relative(Ltr, Rtl, true), AlignItems::NORMAL);
}
#[test]
fn resolve_self_relative_block_axis() {
use Direction::{Ltr, Rtl};
// In the block axis (horizontal-tb only) direction never flips self-start/self-end
assert_eq!(AlignItems::SELF_START.resolve_self_relative(Ltr, Rtl, false), AlignItems::START);
assert_eq!(AlignItems::SELF_END.resolve_self_relative(Rtl, Ltr, false), AlignItems::END);
}
#[test]
fn align_content_is_safe() {
assert!(AlignContent::SAFE_START.is_safe());
assert!(AlignContent::SAFE_CENTER.is_safe());
assert!(!AlignContent::SPACE_BETWEEN.is_safe());
assert!(!AlignContent::STRETCH.is_safe());
assert!(!AlignContent::NORMAL.is_safe());
}
#[test]
fn align_content_keyword_strips_safe() {
assert_eq!(AlignContent::SAFE_START.keyword(), AlignContentKeyword::Start);
assert_eq!(AlignContent::SAFE_FLEX_END.keyword(), AlignContentKeyword::FlexEnd);
assert_eq!(AlignContent::SAFE_CENTER.keyword(), AlignContentKeyword::Center);
assert_eq!(AlignContent::SPACE_BETWEEN.keyword(), AlignContentKeyword::SpaceBetween);
assert_eq!(AlignContent::NORMAL.keyword(), AlignContentKeyword::Normal);
assert_eq!(JustifyContent::NORMAL, AlignContent::NORMAL);
}
#[test]
fn align_content_keyword_reversed_swaps_start_end() {
assert_eq!(AlignContentKeyword::Start.reversed(), AlignContentKeyword::End);
assert_eq!(AlignContentKeyword::End.reversed(), AlignContentKeyword::Start);
assert_eq!(AlignContentKeyword::FlexStart.reversed(), AlignContentKeyword::FlexEnd);
assert_eq!(AlignContentKeyword::FlexEnd.reversed(), AlignContentKeyword::FlexStart);
// Stretch reverses to End — preserves pre-refactor behaviour.
assert_eq!(AlignContentKeyword::Stretch.reversed(), AlignContentKeyword::End);
assert_eq!(AlignContentKeyword::Normal.reversed(), AlignContentKeyword::Normal);
assert_eq!(AlignContentKeyword::Center.reversed(), AlignContentKeyword::Center);
assert_eq!(AlignContentKeyword::SpaceBetween.reversed(), AlignContentKeyword::SpaceBetween);
assert_eq!(AlignContentKeyword::SpaceEvenly.reversed(), AlignContentKeyword::SpaceEvenly);
assert_eq!(AlignContentKeyword::SpaceAround.reversed(), AlignContentKeyword::SpaceAround);
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_items_plain() {
assert_eq!("start".parse::<AlignItems>().unwrap(), AlignItems::START);
assert_eq!("end".parse::<AlignItems>().unwrap(), AlignItems::END);
assert_eq!("flex-start".parse::<AlignItems>().unwrap(), AlignItems::FLEX_START);
assert_eq!("flex-end".parse::<AlignItems>().unwrap(), AlignItems::FLEX_END);
assert_eq!("center".parse::<AlignItems>().unwrap(), AlignItems::CENTER);
assert_eq!("self-start".parse::<AlignItems>().unwrap(), AlignItems::SELF_START);
assert_eq!("self-end".parse::<AlignItems>().unwrap(), AlignItems::SELF_END);
assert_eq!("baseline".parse::<AlignItems>().unwrap(), AlignItems::BASELINE);
assert_eq!("stretch".parse::<AlignItems>().unwrap(), AlignItems::STRETCH);
}
#[test]
fn align_content_default_is_normal() {
assert_eq!(AlignContent::default(), AlignContent::NORMAL);
assert_eq!(JustifyContent::default(), JustifyContent::NORMAL);
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_items_normal() {
assert_eq!("normal".parse::<AlignItems>().unwrap(), AlignItems::NORMAL);
assert_eq!("NORMAL".parse::<AlignItems>().unwrap(), AlignItems::NORMAL);
assert_eq!(AlignItems::NORMAL.safety, AlignmentSafety::Default);
// `auto` is not an `AlignItems` keyword: it is represented by `None` on the `*-self` styles
assert!("auto".parse::<AlignSelf>().is_err());
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_items_safe() {
assert_eq!("safe start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_START);
assert_eq!("safe end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_END);
assert_eq!("safe flex-start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_FLEX_START);
assert_eq!("safe flex-end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_FLEX_END);
assert_eq!("safe self-start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_SELF_START);
assert_eq!("safe self-end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_SELF_END);
assert_eq!("safe center".parse::<AlignItems>().unwrap(), AlignItems::SAFE_CENTER);
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_items_safe_case_insensitive() {
assert_eq!("SAFE Start".parse::<AlignItems>().unwrap(), AlignItems::SAFE_START);
assert_eq!("Safe FLEX-end".parse::<AlignItems>().unwrap(), AlignItems::SAFE_FLEX_END);
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_items_unsafe() {
let unsafe_ = |keyword| AlignItems { keyword, safety: AlignmentSafety::Unsafe };
assert_eq!("unsafe start".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::Start));
assert_eq!("unsafe end".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::End));
assert_eq!("unsafe self-start".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::SelfStart));
assert_eq!("unsafe self-end".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::SelfEnd));
assert_eq!("unsafe center".parse::<AlignItems>().unwrap(), unsafe_(AlignItemsKeyword::Center));
// The bare keyword carries no overflow-position modifier
assert_eq!(AlignItems::START.safety, AlignmentSafety::Default);
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_items_rejects_invalid_safe_combos() {
assert!("safe stretch".parse::<AlignItems>().is_err());
assert!("safe baseline".parse::<AlignItems>().is_err());
assert!("safe space-between".parse::<AlignItems>().is_err());
assert!("safe".parse::<AlignItems>().is_err());
assert!("safe garbage".parse::<AlignItems>().is_err());
assert!("unsafe stretch".parse::<AlignItems>().is_err());
assert!("unsafe baseline".parse::<AlignItems>().is_err());
assert!("safe normal".parse::<AlignItems>().is_err());
assert!("safe auto".parse::<AlignItems>().is_err());
assert!("unsafe normal".parse::<AlignItems>().is_err());
assert!("unsafe auto".parse::<AlignItems>().is_err());
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_content_plain() {
assert_eq!("normal".parse::<AlignContent>().unwrap(), AlignContent::NORMAL);
assert_eq!("Normal".parse::<JustifyContent>().unwrap(), JustifyContent::NORMAL);
assert_eq!(AlignContent::NORMAL.safety, AlignmentSafety::Default);
assert_eq!("start".parse::<AlignContent>().unwrap(), AlignContent::START);
assert_eq!("space-between".parse::<AlignContent>().unwrap(), AlignContent::SPACE_BETWEEN);
assert_eq!("space-evenly".parse::<AlignContent>().unwrap(), AlignContent::SPACE_EVENLY);
assert_eq!("space-around".parse::<AlignContent>().unwrap(), AlignContent::SPACE_AROUND);
assert_eq!("stretch".parse::<AlignContent>().unwrap(), AlignContent::STRETCH);
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_content_safe() {
assert_eq!("safe start".parse::<AlignContent>().unwrap(), AlignContent::SAFE_START);
assert_eq!("safe end".parse::<AlignContent>().unwrap(), AlignContent::SAFE_END);
assert_eq!("safe flex-start".parse::<AlignContent>().unwrap(), AlignContent::SAFE_FLEX_START);
assert_eq!("safe flex-end".parse::<AlignContent>().unwrap(), AlignContent::SAFE_FLEX_END);
assert_eq!("safe center".parse::<AlignContent>().unwrap(), AlignContent::SAFE_CENTER);
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_content_unsafe() {
let unsafe_ = |keyword| AlignContent { keyword, safety: AlignmentSafety::Unsafe };
assert_eq!("unsafe start".parse::<AlignContent>().unwrap(), unsafe_(AlignContentKeyword::Start));
assert_eq!("unsafe flex-end".parse::<AlignContent>().unwrap(), unsafe_(AlignContentKeyword::FlexEnd));
}
#[cfg(feature = "parse")]
#[test]
fn parse_align_content_rejects_invalid_safe_combos() {
assert!("safe stretch".parse::<AlignContent>().is_err());
assert!("safe space-between".parse::<AlignContent>().is_err());
assert!("safe space-evenly".parse::<AlignContent>().is_err());
assert!("safe space-around".parse::<AlignContent>().is_err());
assert!("safe".parse::<AlignContent>().is_err());
assert!("unsafe stretch".parse::<AlignContent>().is_err());
assert!("unsafe space-between".parse::<AlignContent>().is_err());
assert!("safe normal".parse::<AlignContent>().is_err());
assert!("unsafe normal".parse::<AlignContent>().is_err());
assert!("auto".parse::<AlignContent>().is_err());
}
#[cfg(feature = "serde")]
#[test]
fn serde_align_items_round_trip() {
let cases = [
(AlignItems::NORMAL, "\"Normal\""),
(AlignItems::START, "\"Start\""),
(AlignItems::END, "\"End\""),
(AlignItems::FLEX_START, "\"FlexStart\""),
(AlignItems::FLEX_END, "\"FlexEnd\""),
(AlignItems::CENTER, "\"Center\""),
(AlignItems::BASELINE, "\"Baseline\""),
(AlignItems::STRETCH, "\"Stretch\""),
(AlignItems::SAFE_START, "\"SafeStart\""),
(AlignItems::SAFE_END, "\"SafeEnd\""),
(AlignItems::SAFE_FLEX_START, "\"SafeFlexStart\""),
(AlignItems::SAFE_FLEX_END, "\"SafeFlexEnd\""),
(AlignItems::SAFE_CENTER, "\"SafeCenter\""),
(AlignItems::SELF_START, "\"SelfStart\""),
(AlignItems::SELF_END, "\"SelfEnd\""),
(AlignItems::SAFE_SELF_START, "\"SafeSelfStart\""),
(AlignItems::SAFE_SELF_END, "\"SafeSelfEnd\""),
];
for (value, expected) in cases {
let serialized = serde_json::to_string(&value).unwrap();
assert_eq!(serialized, expected, "serialize {:?}", value);
let deserialized: AlignItems = serde_json::from_str(expected).unwrap();
assert_eq!(deserialized, value, "round-trip {:?}", value);
}
assert!(serde_json::from_str::<AlignItems>("\"NotAVariant\"").is_err());
}
#[cfg(feature = "serde")]
#[test]
fn serde_align_content_round_trip() {
let cases = [
(AlignContent::NORMAL, "\"Normal\""),
(AlignContent::START, "\"Start\""),
(AlignContent::END, "\"End\""),
(AlignContent::FLEX_START, "\"FlexStart\""),
(AlignContent::FLEX_END, "\"FlexEnd\""),
(AlignContent::CENTER, "\"Center\""),
(AlignContent::STRETCH, "\"Stretch\""),
(AlignContent::SPACE_BETWEEN, "\"SpaceBetween\""),
(AlignContent::SPACE_EVENLY, "\"SpaceEvenly\""),
(AlignContent::SPACE_AROUND, "\"SpaceAround\""),
(AlignContent::SAFE_START, "\"SafeStart\""),
(AlignContent::SAFE_END, "\"SafeEnd\""),
(AlignContent::SAFE_FLEX_START, "\"SafeFlexStart\""),
(AlignContent::SAFE_FLEX_END, "\"SafeFlexEnd\""),
(AlignContent::SAFE_CENTER, "\"SafeCenter\""),
];
for (value, expected) in cases {
let serialized = serde_json::to_string(&value).unwrap();
assert_eq!(serialized, expected, "serialize {:?}", value);
let deserialized: AlignContent = serde_json::from_str(expected).unwrap();
assert_eq!(deserialized, value, "round-trip {:?}", value);
}
assert!(serde_json::from_str::<AlignContent>("\"NotAVariant\"").is_err());
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Style type for representing available space as a sizing constraint
use crate::{
prelude::{FromLength, TaffyMaxContent, TaffyMinContent, TaffyZero},
sys::abs,
Size,
};
#[cfg(feature = "parse")]
use crate::util::parse::{from_str_from_css, CssParseResult, FromCss, Parser, Token};
/// The amount of space available to a node in a given axis
/// <https://www.w3.org/TR/css-sizing-3/#available>
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum AvailableSpace {
/// The amount of space available is the specified number of pixels
Definite(f32),
/// The amount of space available is indefinite and the node should be laid out under a min-content constraint
MinContent,
/// The amount of space available is indefinite and the node should be laid out under a max-content constraint
MaxContent,
}
impl TaffyZero for AvailableSpace {
const ZERO: Self = Self::Definite(0.0);
}
impl TaffyMaxContent for AvailableSpace {
const MAX_CONTENT: Self = Self::MaxContent;
}
impl TaffyMinContent for AvailableSpace {
const MIN_CONTENT: Self = Self::MinContent;
}
impl FromLength for AvailableSpace {
fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::Definite(value.into() as f32)
}
}
#[cfg(feature = "parse")]
impl FromCss for AvailableSpace {
fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
match parser.next()?.clone() {
Token::Number { value, .. } if value >= 0.0 => Ok(Self::Definite(value)),
Token::Dimension { value, .. } if value >= 0.0 => Ok(Self::Definite(value)),
Token::Ident(ident) if ident == "max-content" => Ok(Self::MaxContent),
Token::Ident(ident) if ident == "min-content" => Ok(Self::MinContent),
token => Err(parser.new_unexpected_token_error(token))?,
}
}
}
#[cfg(feature = "parse")]
from_str_from_css!(AvailableSpace);
impl AvailableSpace {
/// Returns true for definite values, else false
pub const fn is_definite(self) -> bool {
matches!(self, AvailableSpace::Definite(_))
}
/// Convert to Option
/// Definite values become Some(value). Constraints become None.
pub const fn into_option(self) -> Option<f32> {
match self {
AvailableSpace::Definite(value) => Some(value),
_ => None,
}
}
/// Return the definite value or a default value
pub fn unwrap_or(self, default: f32) -> f32 {
self.into_option().unwrap_or(default)
}
/// Return the definite value. Panic is the value is not definite.
#[track_caller]
pub fn unwrap(self) -> f32 {
self.into_option().unwrap()
}
/// Return self if definite or a default value
pub fn or(self, default: AvailableSpace) -> AvailableSpace {
match self {
AvailableSpace::Definite(_) => self,
_ => default,
}
}
/// Return self if definite or a the result of the default value callback
pub fn or_else(self, default_cb: impl FnOnce() -> AvailableSpace) -> AvailableSpace {
match self {
AvailableSpace::Definite(_) => self,
_ => default_cb(),
}
}
/// Return the definite value or the result of the default value callback
pub fn unwrap_or_else(self, default_cb: impl FnOnce() -> f32) -> f32 {
self.into_option().unwrap_or_else(default_cb)
}
/// If passed value is Some then return AvailableSpace::Definite containing that value, else return self
pub fn maybe_set(self, value: Option<f32>) -> AvailableSpace {
match value {
Some(value) => AvailableSpace::Definite(value),
None => self,
}
}
/// If passed value is Some then return AvailableSpace::Definite containing that value, else return self
pub fn map_definite_value(self, map_function: impl FnOnce(f32) -> f32) -> AvailableSpace {
match self {
AvailableSpace::Definite(value) => AvailableSpace::Definite(map_function(value)),
_ => self,
}
}
/// Compute free_space given the passed used_space
pub fn compute_free_space(&self, used_space: f32) -> f32 {
match self {
AvailableSpace::MaxContent => f32::INFINITY,
AvailableSpace::MinContent => 0.0,
AvailableSpace::Definite(available_space) => available_space - used_space,
}
}
/// Compare equality with another AvailableSpace, treating definite values
/// that are within f32::EPSILON of each other as equal
pub fn is_roughly_equal(self, other: AvailableSpace) -> bool {
use AvailableSpace::*;
match (self, other) {
(Definite(a), Definite(b)) => abs(a - b) < f32::EPSILON,
(MinContent, MinContent) => true,
(MaxContent, MaxContent) => true,
_ => false,
}
}
}
impl From<f32> for AvailableSpace {
fn from(value: f32) -> Self {
Self::Definite(value)
}
}
impl From<Option<f32>> for AvailableSpace {
fn from(option: Option<f32>) -> Self {
match option {
Some(value) => Self::Definite(value),
None => Self::MaxContent,
}
}
}
impl Size<AvailableSpace> {
/// Convert `Size<AvailableSpace>` into `Size<Option<f32>>`
pub fn into_options(self) -> Size<Option<f32>> {
Size { width: self.width.into_option(), height: self.height.into_option() }
}
/// If passed value is Some then return AvailableSpace::Definite containing that value, else return self
pub fn maybe_set(self, value: Size<Option<f32>>) -> Size<AvailableSpace> {
Size { width: self.width.maybe_set(value.width), height: self.height.maybe_set(value.height) }
}
}
+95
View File
@@ -0,0 +1,95 @@
//! Style types for Block layout
use crate::style::{AlignContent, AlignItems, AlignSelf};
use crate::{CoreStyle, Style};
/// The set of styles required for a Block layout container
pub trait BlockContainerStyle: CoreStyle {
/// Defines which row in the grid the item should start and end at
#[inline(always)]
fn text_align(&self) -> TextAlign {
Style::<Self::CustomIdent>::DEFAULT.text_align
}
/// How children of this block container are aligned in the block (cross) axis
#[inline(always)]
fn align_content(&self) -> AlignContent {
Style::<Self::CustomIdent>::DEFAULT.align_content
}
/// The default inline-axis alignment of this block container's children (`justify-items`).
/// Out-of-flow children with `justify-self: auto` are aligned within their static-position
/// rectangle according to this value.
#[inline(always)]
fn justify_items(&self) -> AlignItems {
Style::<Self::CustomIdent>::DEFAULT.justify_items
}
}
/// The set of styles required for a Block layout item (child of a Block container)
pub trait BlockItemStyle: CoreStyle {
/// Whether the item is a table. Table children are handled specially in block layout.
#[inline(always)]
fn is_table(&self) -> bool {
false
}
/// How an out-of-flow (absolutely positioned) child is aligned in the block axis of its
/// static-position rectangle (`align-self`). `None` corresponds to `normal`/`auto`.
#[inline(always)]
fn align_self(&self) -> Option<AlignSelf> {
None
}
/// How an out-of-flow (absolutely positioned) child is aligned in the inline axis of its
/// static-position rectangle (`justify-self`). `None` corresponds to `normal`/`auto`.
#[inline(always)]
fn justify_self(&self) -> Option<AlignSelf> {
None
}
/// The `align-content` of the item (if it is itself a block container). A non-`normal`
/// value makes the item establish an independent formatting context, so that it is laid
/// out next to (rather than underneath) floats and does not collapse margins with its
/// parent (<https://www.w3.org/TR/css-align-3/#distribution-block>).
#[inline(always)]
fn align_content(&self) -> AlignContent {
AlignContent::NORMAL
}
/// Whether the item is a floated
#[cfg(feature = "float_layout")]
#[inline(always)]
fn float(&self) -> super::Float {
super::Float::None
}
/// Whether the item is a floated
#[cfg(feature = "float_layout")]
#[inline(always)]
fn clear(&self) -> super::Clear {
super::Clear::None
}
}
/// Used by block layout to implement the legacy behaviour of `<center>` and `<div align="left | right | center">`
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum TextAlign {
/// No special legacy text align behaviour.
#[default]
Auto,
/// Corresponds to `-webkit-left` or `-moz-left` in browsers
LegacyLeft,
/// Corresponds to `-webkit-right` or `-moz-right` in browsers
LegacyRight,
/// Corresponds to `-webkit-center` or `-moz-center` in browsers
LegacyCenter,
}
#[cfg(feature = "parse")]
crate::util::parse::impl_parse_for_keyword_enum!(TextAlign,
"auto" => Auto,
"-webkit-left" => LegacyLeft,
"-webkit-right" => LegacyRight,
"-webkit-center" => LegacyCenter,
);
+793
View File
@@ -0,0 +1,793 @@
//! A tagged-pointer abstraction that allows size styles in Taffy to be represented
//! in just 64 bits. Wrapped by types in the `super::dimension` and `super::grid` modules.
use super::LengthPercentage;
use crate::style_helpers::{
FromFr, FromLength, FromPercent, TaffyAuto, TaffyFitContent, TaffyMaxContent, TaffyMinContent, TaffyZero,
};
/// Note: these two functions are copied directly from the std (core) library. But by duplicating them
/// here we can reduce MSRV from 1.84 all the way down to 1.65 while retaining const constructors and
/// strict pointer provenance
mod compat {
#![allow(unsafe_code)]
#![allow(unknown_lints)]
#![allow(unnecessary_transmutes)]
/// Raw transmutation from `f32` to `u32`.
pub const fn f32_to_bits(val: f32) -> u32 {
// SAFETY: `u32` is a plain old datatype so we can always transmute to it.
unsafe { core::mem::transmute(val) }
}
/// Raw transmutation from `u32` to `f32`.
pub const fn f32_from_bits(v: u32) -> f32 {
// SAFETY: `u32` is a plain old datatype so we can always transmute from it.
unsafe { core::mem::transmute(v) }
}
/// Tag a pointer preserving provenance (requires Rust 1.84)
#[inline(always)]
#[cfg(all(target_pointer_width = "64", feature = "strict_provenance"))]
pub fn tag_ptr(ptr: *const (), tag: usize) -> *const () {
ptr.map_addr(|a| a | tag)
}
/// Tag a pointer exposing provenance (works back to Rust 1.0)
#[inline(always)]
#[cfg(all(target_pointer_width = "64", not(feature = "strict_provenance")))]
pub fn tag_ptr(ptr: *const (), tag: usize) -> *const () {
(ptr as usize | tag) as *const ()
}
/// Clear the tag bits of a pointer preserving provenance (requires Rust 1.84)
#[inline(always)]
#[cfg(all(target_pointer_width = "64", feature = "strict_provenance"))]
pub fn untag_ptr(ptr: *const (), mask: usize) -> *const () {
ptr.map_addr(|a| a & !mask)
}
/// Clear the tag bits of a pointer exposing provenance (works back to Rust 1.0)
#[inline(always)]
#[cfg(all(target_pointer_width = "64", not(feature = "strict_provenance")))]
pub fn untag_ptr(ptr: *const (), mask: usize) -> *const () {
(ptr as usize & !mask) as *const ()
}
}
#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
std::compile_error!("Taffy only supports targets with a pointer width of 32 or 64 bits");
/// CompactLengthInner implementation for 64 bit platforms
#[cfg(target_pointer_width = "64")]
mod inner {
use super::compat::{f32_from_bits, f32_to_bits, tag_ptr, untag_ptr};
/// The low byte (8 bits)
const TAG_MASK: usize = 0b11111111;
/// The low 3 bits
const CALC_TAG_MASK: usize = 0b111;
/// On 64 bit platforms the tag, value and pointer are packed into a single 64 bit pointer
///
/// The tagged pointer always has a tag and may contain an f32 value or a pointer
/// (or neither) depending on the variant indicated by the tag.
#[derive(Copy, Clone, Debug, PartialEq)]
pub(super) struct CompactLengthInner {
/// The tagged pointer
tagged_ptr: *const (),
}
impl CompactLengthInner {
/// Construct a `CompactLengthInner` from a tag and pointer
#[inline(always)]
pub(super) fn from_ptr(ptr: *const (), tag: usize) -> Self {
let tagged_ptr = tag_ptr(ptr, tag);
Self { tagged_ptr }
}
/// Construct a `CompactLengthInner` from a tag and numeric value
#[inline(always)]
pub(super) const fn from_val(val: f32, tag: usize) -> Self {
let tagged_ptr = (((f32_to_bits(val) as usize) << 32) | tag) as *const ();
Self { tagged_ptr }
}
/// Construct a `CompactLengthInner` from only a tag
#[inline(always)]
pub(super) const fn from_tag(tag: usize) -> Self {
let tagged_ptr = tag as *const ();
Self { tagged_ptr }
}
/// Get the calc tag (low 3 bits)
#[inline(always)]
#[cfg(feature = "calc")]
pub(super) fn calc_tag(self) -> usize {
(self.tagged_ptr as usize) & CALC_TAG_MASK
}
/// Get the general tag (low 8 bits)
#[inline(always)]
pub(super) fn tag(self) -> usize {
(self.tagged_ptr as usize) & TAG_MASK
}
/// Get the pointer value (with the tag bits cleared)
#[inline(always)]
pub(super) fn ptr(self) -> *const () {
untag_ptr(self.tagged_ptr, CALC_TAG_MASK)
}
/// Get the numeric value
#[inline(always)]
pub(super) fn value(self) -> f32 {
f32_from_bits((self.tagged_ptr as usize >> 32) as u32)
}
/// Get the serialized value.
#[inline(always)]
#[cfg(feature = "serde")]
pub(super) fn serialized(self) -> u64 {
(self.tagged_ptr as usize as u64).rotate_left(32)
}
/// Derialized from a value.
#[inline(always)]
#[cfg(feature = "serde")]
pub(super) fn from_serialized(value: u64) -> Self {
Self { tagged_ptr: value.rotate_right(32) as usize as *const () }
}
}
}
/// CompactLengthInner implementation for 32 bit platforms
#[cfg(target_pointer_width = "32")]
mod inner {
use super::compat::{f32_from_bits, f32_to_bits};
/// On 32 bit platforms the tag is stored separately.
/// Either an f32 value or a pointer (or neither) are packed into the ptr field
/// depending on the variant indicated by the tag
#[derive(Copy, Clone, Debug, PartialEq)]
pub(super) struct CompactLengthInner {
/// The tag indicating what kind of value we are storing
tag: usize,
/// The pointer of numeric value
ptr: *const (),
}
impl CompactLengthInner {
/// Construct a `CompactLengthInner` from a tag and pointer
#[inline(always)]
pub(super) fn from_ptr(ptr: *const (), tag: usize) -> Self {
Self { ptr, tag }
}
/// Construct a `CompactLengthInner` from a tag and numeric value
#[inline(always)]
pub(super) const fn from_val(val: f32, tag: usize) -> Self {
Self { ptr: f32_to_bits(val) as usize as *const (), tag }
}
/// Construct a `CompactLengthInner` from only a tag
#[inline(always)]
pub(super) const fn from_tag(tag: usize) -> Self {
Self { ptr: 0 as *const (), tag }
}
/// Get the calc tag (low 3 bits)
#[inline(always)]
#[cfg(feature = "calc")]
pub(super) fn calc_tag(self) -> usize {
self.tag
}
/// Get the general tag (low 8 bits)
#[inline(always)]
pub(super) fn tag(self) -> usize {
self.tag
}
/// Get the pointer value
#[inline(always)]
pub(super) fn ptr(self) -> *const () {
self.ptr
}
/// Get the numeric value
#[inline(always)]
pub(super) fn value(self) -> f32 {
f32_from_bits(self.ptr as u32)
}
/// Get the serialized value.
#[inline(always)]
#[cfg(feature = "serde")]
pub(super) fn serialized(self) -> u64 {
(self.tag as u64) << 32 | (self.ptr as u64)
}
/// Derialized from a value.
#[inline(always)]
#[cfg(feature = "serde")]
pub(super) fn from_serialized(value: u64) -> Self {
Self { tag: (value >> 32) as usize, ptr: (value & 0xFFFFFFFF) as usize as *const () }
}
}
}
use inner::CompactLengthInner;
/// A representation of a length as a compact 64-bit tagged pointer
#[derive(Copy, Clone, PartialEq, Debug)]
#[repr(transparent)]
pub struct CompactLength(CompactLengthInner);
/// Tag layout
///
/// Tags are 8 bits. The low 3 bits are shared with pointer variants (such as `calc()`), which require
/// an 8-byte aligned pointer and so always have those bits clear. They are assigned as follows:
///
/// - Bit 0 (`NON_POINTER_BIT`): set for every variant that is *not* a pointer. Pointer variants
/// (`calc()`) have this bit clear, so `is_plain_calc()` is a single bit test.
/// - Bit 1 (`KEYWORD_BIT`): set for every variant that is *not* a plain length, percentage or calc()
/// value (i.e. everything that cannot be resolved to a length given only a percentage basis).
/// - Bit 2 (`PERCENTAGE_BIT`): set for every variant whose resolved value depends on a percentage basis,
/// including all `calc()` variants. `uses_percentage()` is a single bit test.
///
/// Pointer variants are distinguished by bit 1: `calc()` is `0b100` and `fit-content(calc())` is `0b110`.
/// Any pointer variant's `tag()` includes address bits 3..7, so pointer variants must be tested with low-bit
/// masks (`is_plain_calc()`, `is_fit_content_calc()`, `has_calc()`) rather than as `match` arms.
///
/// Within the keyword class, bit 3 (`SIZING_KEYWORD_BIT`) is set for the CSS sizing keywords
/// (`min-content`, `max-content`, `fit-content`, `fit-content()`, `stretch`) and clear for `auto`,
/// `fr` and `content`. The remaining high bits distinguish variants within a class.
impl CompactLength {
/// Bit set for all non-pointer (i.e. not `calc()`) tags
pub const NON_POINTER_BIT: usize = 0b0001;
/// Bit set for all tags that are not a plain length, percentage or calc() value
pub const KEYWORD_BIT: usize = 0b0010;
/// Bit set for all tags whose value depends on a percentage basis (including `calc()`)
pub const PERCENTAGE_BIT: usize = 0b0100;
/// Bit set (in addition to `KEYWORD_BIT`) for all CSS sizing keyword tags
pub const SIZING_KEYWORD_BIT: usize = 0b1000;
/// The tag indicating a calc() value
#[cfg(feature = "calc")]
pub const CALC_TAG: usize = 0b0000_0100;
/// The tag indicating a fit-content() value with a calc() limit
#[cfg(feature = "calc")]
pub const FIT_CONTENT_CALC_TAG: usize = 0b0000_0110;
/// The tag indicating a length value
pub const LENGTH_TAG: usize = 0b0000_0001;
/// The tag indicating a percentage value
pub const PERCENT_TAG: usize = 0b0000_0101;
/// The tag indicating an auto value
pub const AUTO_TAG: usize = 0b0000_0011;
/// The tag indicating an fr value
pub const FR_TAG: usize = 0b0001_0011;
/// The tag indicating a content keyword value
pub const CONTENT_TAG: usize = 0b0010_0011;
/// The tag indicating a min-content value
pub const MIN_CONTENT_TAG: usize = 0b0000_1011;
/// The tag indicating a max-content value
pub const MAX_CONTENT_TAG: usize = 0b0001_1011;
/// The tag indicating a fit-content value with px limit
pub const FIT_CONTENT_PX_TAG: usize = 0b0010_1011;
/// The tag indicating a plain fit-content keyword value (no limit)
pub const FIT_CONTENT_KEYWORD_TAG: usize = 0b0011_1011;
/// The tag indicating a stretch keyword value
pub const STRETCH_TAG: usize = 0b0100_1011;
/// The tag indicating a fit-content value with percent limit
pub const FIT_CONTENT_PERCENT_TAG: usize = 0b0000_1111;
}
impl CompactLength {
/// An absolute length in some abstract units. Users of Taffy may define what they correspond
/// to in their application (pixels, logical pixels, mm, etc) as they see fit.
#[inline(always)]
pub const fn length(val: f32) -> Self {
Self(CompactLengthInner::from_val(val, Self::LENGTH_TAG))
}
/// A percentage length relative to the size of the containing block.
///
/// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
#[inline(always)]
pub const fn percent(val: f32) -> Self {
Self(CompactLengthInner::from_val(val, Self::PERCENT_TAG))
}
/// A `calc()` value. The value passed here is treated as an opaque handle to
/// the actual calc representation and may be a pointer, index, etc.
///
/// The low 3 bits are used as a tag value and will be returned as 0.
#[inline]
#[cfg(feature = "calc")]
pub fn calc(ptr: *const ()) -> Self {
assert_ne!(ptr as u64, 0);
assert_eq!(ptr as u64 & 0b111, 0);
Self(CompactLengthInner::from_ptr(ptr, Self::CALC_TAG))
}
/// A `fit-content(calc())` value. The value passed here is treated as an opaque handle to
/// the actual calc representation of the limit and may be a pointer, index, etc.
///
/// The low 3 bits are used as a tag value and will be returned as 0.
#[inline]
#[cfg(feature = "calc")]
pub fn fit_content_calc(ptr: *const ()) -> Self {
assert_ne!(ptr as u64, 0);
assert_eq!(ptr as u64 & 0b111, 0);
Self(CompactLengthInner::from_ptr(ptr, Self::FIT_CONTENT_CALC_TAG))
}
/// The dimension should be automatically computed according to algorithm-specific rules
/// regarding the default size of boxes.
#[inline(always)]
pub const fn auto() -> Self {
Self(CompactLengthInner::from_tag(Self::AUTO_TAG))
}
/// The dimension as a fraction of the total available grid space (`fr` units in CSS)
/// Specified value is the numerator of the fraction. Denominator is the sum of all fraction specified in that grid dimension
/// Spec: <https://www.w3.org/TR/css3-grid-layout/#fr-unit>
#[inline(always)]
pub const fn fr(val: f32) -> Self {
Self(CompactLengthInner::from_val(val, Self::FR_TAG))
}
/// The size should be the "min-content" size.
/// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
#[inline(always)]
pub const fn min_content() -> Self {
Self(CompactLengthInner::from_tag(Self::MIN_CONTENT_TAG))
}
/// The size should be the "max-content" size.
/// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
#[inline(always)]
pub const fn max_content() -> Self {
Self(CompactLengthInner::from_tag(Self::MAX_CONTENT_TAG))
}
/// The size should be computed according to the "fit content" formula:
/// `max(min_content, min(max_content, limit))`
/// where:
/// - `min_content` is the [min-content](Self::min_content) size
/// - `max_content` is the [max-content](Self::max_content) size
/// - `limit` is a LENGTH value passed to this function
///
/// The effect of this is that the item takes the size of `limit` clamped
/// by the min-content and max-content sizes.
#[inline(always)]
pub const fn fit_content_px(limit: f32) -> Self {
Self(CompactLengthInner::from_val(limit, Self::FIT_CONTENT_PX_TAG))
}
/// The size should be computed according to the "fit content" formula:
/// `max(min_content, min(max_content, limit))`
/// where:
/// - `min_content` is the [min-content](Self::min_content) size
/// - `max_content` is the [max-content](Self::max_content) size
/// - `limit` is a PERCENTAGE value passed to this function
///
/// The effect of this is that the item takes the size of `limit` clamped
/// by the min-content and max-content sizes.
#[inline(always)]
pub const fn fit_content_percent(limit: f32) -> Self {
Self(CompactLengthInner::from_val(limit, Self::FIT_CONTENT_PERCENT_TAG))
}
/// The size should be computed according to the "fit content" formula:
/// `max(min_content, min(max_content, stretch))`
/// where:
/// - `min_content` is the [min-content](Self::min_content) size
/// - `max_content` is the [max-content](Self::max_content) size
/// - `stretch` is the "stretch-fit" size (the size the box would take if it filled the available space)
#[inline(always)]
pub const fn fit_content_keyword() -> Self {
Self(CompactLengthInner::from_tag(Self::FIT_CONTENT_KEYWORD_TAG))
}
/// The size should be the "stretch-fit" size: the size the box would take
/// if it filled the available space
/// (<https://www.w3.org/TR/css-sizing-4/#stretch-fit-sizing>)
#[inline(always)]
pub const fn stretch() -> Self {
Self(CompactLengthInner::from_tag(Self::STRETCH_TAG))
}
/// The size should be an automatic size based on the box's content
/// (<https://www.w3.org/TR/css-flexbox-1/#valdef-flex-basis-content>)
///
/// This keyword is only valid for `flex-basis`. In any other context it behaves as [`auto`](Self::auto).
#[inline(always)]
pub const fn content() -> Self {
Self(CompactLengthInner::from_tag(Self::CONTENT_TAG))
}
/// Get the primary tag
#[inline(always)]
pub fn tag(self) -> usize {
self.0.tag()
}
/// Get the numeric value associated with the `CompactLength`
/// (e.g. the pixel value for a LENGTH variant)
#[inline(always)]
pub fn value(self) -> f32 {
self.0.value()
}
/// Get the calc pointer of the `CompactLength`
#[inline(always)]
#[cfg(feature = "calc")]
pub fn calc_value(self) -> *const () {
self.0.ptr()
}
/// Returns true if the value is a plain calc() value (not a fit-content(calc()) value)
#[inline(always)]
#[cfg(feature = "calc")]
pub fn is_plain_calc(self) -> bool {
self.0.calc_tag() & (Self::NON_POINTER_BIT | Self::KEYWORD_BIT) == 0
}
/// Returns true if the value is a fit-content() value with a calc() limit
#[inline(always)]
pub fn is_fit_content_calc(self) -> bool {
self.tag() & (Self::NON_POINTER_BIT | Self::KEYWORD_BIT) == Self::KEYWORD_BIT
}
/// Returns true if the value holds a calc() pointer: either a plain calc() value or a
/// fit-content() value with a calc() limit. `calc_value()` is valid for exactly these values.
#[inline(always)]
pub fn has_calc(self) -> bool {
self.tag() & Self::NON_POINTER_BIT == 0
}
/// Returns true if the value is 0 px
#[inline(always)]
pub fn is_zero(self) -> bool {
self.0 == Self::ZERO.0
}
/// Returns true if the value is a length or percentage value
#[inline(always)]
pub fn is_length_or_percentage(self) -> bool {
self.tag() & (Self::NON_POINTER_BIT | Self::KEYWORD_BIT) == Self::NON_POINTER_BIT
}
/// Returns true if the value is auto
#[inline(always)]
pub fn is_auto(self) -> bool {
self.tag() == Self::AUTO_TAG
}
/// Returns true if the value is the content keyword
#[inline(always)]
pub fn is_content(self) -> bool {
self.tag() == Self::CONTENT_TAG
}
/// Returns true if the value is min-content
#[inline(always)]
pub fn is_min_content(self) -> bool {
matches!(self.tag(), Self::MIN_CONTENT_TAG)
}
/// Returns true if the value is max-content
#[inline(always)]
pub fn is_max_content(self) -> bool {
matches!(self.tag(), Self::MAX_CONTENT_TAG)
}
/// Returns true if the value is a fit-content(...) value
#[inline(always)]
pub fn is_fit_content(self) -> bool {
matches!(self.tag(), Self::FIT_CONTENT_PX_TAG | Self::FIT_CONTENT_PERCENT_TAG) || self.is_fit_content_calc()
}
/// Returns true if the value is min-content, max-content, fit-content, fit-content(...), or stretch
#[inline(always)]
pub fn is_sizing_keyword(self) -> bool {
const MASK: usize =
CompactLength::NON_POINTER_BIT | CompactLength::KEYWORD_BIT | CompactLength::SIZING_KEYWORD_BIT;
self.tag() & MASK == MASK || self.is_fit_content_calc()
}
/// Returns true if the value is max-content or a fit-content(...) value
#[inline(always)]
pub fn is_max_or_fit_content(self) -> bool {
matches!(self.tag(), Self::MAX_CONTENT_TAG | Self::FIT_CONTENT_PX_TAG | Self::FIT_CONTENT_PERCENT_TAG)
|| self.is_fit_content_calc()
}
/// Returns true if the max track sizing function is `MaxContent`, `FitContent` or `Auto` else false.
/// "In all cases, treat auto and fit-content() as max-content, except where specified otherwise for fit-content()."
/// See: <https://www.w3.org/TR/css-grid-1/#algo-terms>
#[inline(always)]
pub fn is_max_content_alike(&self) -> bool {
matches!(
self.tag(),
CompactLength::AUTO_TAG
| CompactLength::MAX_CONTENT_TAG
| CompactLength::FIT_CONTENT_PX_TAG
| CompactLength::FIT_CONTENT_PERCENT_TAG
) || self.is_fit_content_calc()
}
/// Returns true if the min track sizing function is `MinContent` or `MaxContent`, else false.
#[inline(always)]
pub fn is_min_or_max_content(&self) -> bool {
matches!(self.tag(), Self::MIN_CONTENT_TAG | Self::MAX_CONTENT_TAG)
}
/// Returns true if the value is auto, min-content, max-content, or fit-content(...)
#[inline(always)]
pub fn is_intrinsic(self) -> bool {
matches!(
self.tag(),
Self::AUTO_TAG
| Self::MIN_CONTENT_TAG
| Self::MAX_CONTENT_TAG
| Self::FIT_CONTENT_PX_TAG
| Self::FIT_CONTENT_PERCENT_TAG
) || self.is_fit_content_calc()
}
/// Returns true if the value is and fr value
#[inline(always)]
pub fn is_fr(self) -> bool {
self.tag() == Self::FR_TAG
}
/// Whether the track sizing functions depends on the size of the parent node
#[inline(always)]
pub fn uses_percentage(self) -> bool {
self.tag() & Self::PERCENTAGE_BIT != 0
}
/// Resolve percentage values against the passed parent_size, returning Some(value)
/// Non-percentage values always return None.
#[inline(always)]
pub fn resolved_percentage_size(
self,
parent_size: f32,
calc_resolver: impl Fn(*const (), f32) -> f32,
) -> Option<f32> {
match self.tag() {
CompactLength::PERCENT_TAG => Some(self.value() * parent_size),
#[cfg(feature = "calc")]
_ if self.is_plain_calc() => Some(calc_resolver(self.0.ptr(), parent_size)),
_ => None,
}
}
}
impl TaffyZero for CompactLength {
const ZERO: Self = Self::length(0.0);
}
impl TaffyAuto for CompactLength {
const AUTO: Self = Self::auto();
}
impl TaffyMinContent for CompactLength {
const MIN_CONTENT: Self = Self::min_content();
}
impl TaffyMaxContent for CompactLength {
const MAX_CONTENT: Self = Self::max_content();
}
impl FromLength for CompactLength {
fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::length(value.into() as f32)
}
}
impl FromPercent for CompactLength {
fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::percent(value.into() as f32)
}
}
impl FromFr for CompactLength {
fn from_fr<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::fr(value.into() as f32)
}
}
impl TaffyFitContent for CompactLength {
fn fit_content(lp: LengthPercentage) -> Self {
let value = lp.0.value();
match lp.0.tag() {
Self::LENGTH_TAG => Self::fit_content_px(value),
Self::PERCENT_TAG => Self::fit_content_percent(value),
#[cfg(feature = "calc")]
_ if lp.0.is_plain_calc() => Self::fit_content_calc(lp.0.calc_value()),
_ => unreachable!(),
}
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for CompactLength {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
#[cfg(feature = "calc")]
{
if self.has_calc() {
Err(serde::ser::Error::custom("Cannot serialize Calc value"))
} else {
serializer.serialize_u64(self.0.serialized())
}
}
#[cfg(not(feature = "calc"))]
serializer.serialize_u64(self.0.serialized())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for CompactLength {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let bits: u64 = u64::deserialize(deserializer)?;
let value = Self(CompactLengthInner::from_serialized(bits));
// Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported.
// All of the accepted tags have `NON_POINTER_BIT` set, so a calc() tag can never pass validation.
if matches!(
value.tag(),
CompactLength::LENGTH_TAG
| CompactLength::PERCENT_TAG
| CompactLength::AUTO_TAG
| CompactLength::MIN_CONTENT_TAG
| CompactLength::MAX_CONTENT_TAG
| CompactLength::FIT_CONTENT_KEYWORD_TAG
| CompactLength::FIT_CONTENT_PX_TAG
| CompactLength::FIT_CONTENT_PERCENT_TAG
| CompactLength::STRETCH_TAG
| CompactLength::CONTENT_TAG
| CompactLength::FR_TAG
) {
Ok(value)
} else {
Err(serde::de::Error::custom("Cannot deserialize Calc value"))
}
}
}
#[cfg(test)]
mod tests {
use super::{CompactLength, CompactLengthInner};
impl CompactLength {
fn from_raw_tag(tag: usize) -> Self {
Self(CompactLengthInner::from_tag(tag))
}
}
const NON_PERCENTAGE_TAGS: &[usize] = &[
CompactLength::LENGTH_TAG,
CompactLength::AUTO_TAG,
CompactLength::FR_TAG,
CompactLength::MIN_CONTENT_TAG,
CompactLength::MAX_CONTENT_TAG,
CompactLength::FIT_CONTENT_PX_TAG,
CompactLength::FIT_CONTENT_KEYWORD_TAG,
CompactLength::STRETCH_TAG,
CompactLength::CONTENT_TAG,
];
const PERCENTAGE_TAGS: &[usize] = &[CompactLength::PERCENT_TAG, CompactLength::FIT_CONTENT_PERCENT_TAG];
#[test]
fn tags_are_unique_and_fit_in_a_byte() {
let mut all: Vec<usize> = NON_PERCENTAGE_TAGS.iter().chain(PERCENTAGE_TAGS).copied().collect();
#[cfg(feature = "calc")]
all.push(CompactLength::CALC_TAG);
#[cfg(feature = "calc")]
all.push(CompactLength::FIT_CONTENT_CALC_TAG);
assert!(all.iter().all(|tag| *tag <= 0xFF));
all.sort_unstable();
all.dedup();
assert_eq!(all.len(), NON_PERCENTAGE_TAGS.len() + PERCENTAGE_TAGS.len() + 2 * cfg!(feature = "calc") as usize);
}
#[test]
fn non_pointer_tags_have_non_pointer_bit_set() {
for tag in NON_PERCENTAGE_TAGS.iter().chain(PERCENTAGE_TAGS) {
assert_ne!(tag & CompactLength::NON_POINTER_BIT, 0, "tag {tag:#010b}");
}
#[cfg(feature = "calc")]
assert_eq!(CompactLength::CALC_TAG & CompactLength::NON_POINTER_BIT, 0);
}
#[test]
fn keyword_bits_match_predicates() {
let all = NON_PERCENTAGE_TAGS.iter().chain(PERCENTAGE_TAGS).map(|tag| CompactLength::from_raw_tag(*tag));
for value in all {
let tag = value.tag();
let is_plain = matches!(tag, CompactLength::LENGTH_TAG | CompactLength::PERCENT_TAG);
assert_eq!(tag & CompactLength::KEYWORD_BIT == 0, is_plain, "tag {tag:#010b}");
assert_eq!(value.is_length_or_percentage(), is_plain, "tag {tag:#010b}");
let is_sizing_keyword = matches!(
tag,
CompactLength::MIN_CONTENT_TAG
| CompactLength::MAX_CONTENT_TAG
| CompactLength::FIT_CONTENT_KEYWORD_TAG
| CompactLength::FIT_CONTENT_PX_TAG
| CompactLength::FIT_CONTENT_PERCENT_TAG
| CompactLength::STRETCH_TAG
);
assert_eq!(value.is_sizing_keyword(), is_sizing_keyword, "tag {tag:#010b}");
}
#[cfg(feature = "calc")]
{
assert_eq!(CompactLength::CALC_TAG & CompactLength::KEYWORD_BIT, 0);
assert_ne!(CompactLength::FIT_CONTENT_CALC_TAG & CompactLength::KEYWORD_BIT, 0);
assert_eq!(CompactLength::FIT_CONTENT_CALC_TAG & CompactLength::NON_POINTER_BIT, 0);
assert_ne!(CompactLength::FIT_CONTENT_CALC_TAG & CompactLength::PERCENTAGE_BIT, 0);
}
}
#[test]
fn percentage_bit_matches_uses_percentage() {
for tag in NON_PERCENTAGE_TAGS {
assert_eq!(tag & CompactLength::PERCENTAGE_BIT, 0, "tag {tag:#010b}");
}
for tag in PERCENTAGE_TAGS {
assert_ne!(tag & CompactLength::PERCENTAGE_BIT, 0, "tag {tag:#010b}");
}
#[cfg(feature = "calc")]
assert_ne!(CompactLength::CALC_TAG & CompactLength::PERCENTAGE_BIT, 0);
assert!(!CompactLength::length(10.0).uses_percentage());
assert!(!CompactLength::auto().uses_percentage());
assert!(!CompactLength::fr(1.0).uses_percentage());
assert!(!CompactLength::min_content().uses_percentage());
assert!(!CompactLength::max_content().uses_percentage());
assert!(!CompactLength::fit_content_px(10.0).uses_percentage());
assert!(!CompactLength::fit_content_keyword().uses_percentage());
assert!(!CompactLength::stretch().uses_percentage());
assert!(!CompactLength::content().uses_percentage());
assert!(CompactLength::percent(0.5).uses_percentage());
assert!(CompactLength::fit_content_percent(0.5).uses_percentage());
}
#[test]
#[cfg(feature = "calc")]
fn fit_content_calc_round_trips_pointer() {
let boxed = Box::new(0u64);
let ptr = &*boxed as *const u64 as *const ();
let value = CompactLength::fit_content_calc(ptr);
assert!(value.is_fit_content_calc());
assert!(value.has_calc());
assert!(!value.is_plain_calc());
assert!(value.is_fit_content());
assert!(value.is_sizing_keyword());
assert!(value.is_intrinsic());
assert!(value.is_max_or_fit_content());
assert!(value.is_max_content_alike());
assert!(value.uses_percentage());
assert!(!value.is_length_or_percentage());
assert_eq!(value.calc_value(), ptr);
let calc = CompactLength::calc(ptr);
assert!(calc.is_plain_calc());
assert!(calc.has_calc());
assert!(!calc.is_fit_content_calc());
assert!(!calc.is_fit_content());
assert!(!calc.is_sizing_keyword());
}
#[test]
fn calc_round_trips_pointer() {
let boxed = Box::new(42u64);
let ptr = &*boxed as *const u64 as *const ();
let value = CompactLength::calc(ptr);
assert!(value.is_plain_calc());
assert!(value.uses_percentage());
assert!(!value.is_length_or_percentage());
assert!(!value.is_auto());
assert!(!value.is_intrinsic());
assert_eq!(value.calc_value(), ptr);
}
}
+762
View File
@@ -0,0 +1,762 @@
//! Style types for representing lengths / sizes
use super::CompactLength;
use crate::geometry::Rect;
use crate::style_helpers::{FromLength, FromPercent, TaffyAuto, TaffyZero};
#[cfg(feature = "parse")]
use crate::util::parse::{from_str_from_css, CssParseResult, FromCss, Parser, Token};
/// A unit of linear measurement
///
/// This is commonly combined with [`Rect`], [`Point`](crate::geometry::Point) and [`Size<T>`](crate::geometry::Size).
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct LengthPercentage(pub(crate) CompactLength);
impl TaffyZero for LengthPercentage {
const ZERO: Self = Self(CompactLength::ZERO);
}
impl FromLength for LengthPercentage {
fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::length(value.into() as f32)
}
}
impl FromPercent for LengthPercentage {
fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::percent(value.into() as f32)
}
}
#[cfg(feature = "parse")]
impl FromCss for LengthPercentage {
fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
match parser.next()?.clone() {
Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
token => Err(parser.new_unexpected_token_error(token))?,
}
}
}
#[cfg(feature = "parse")]
from_str_from_css!(LengthPercentage);
impl LengthPercentage {
/// An absolute length in some abstract units. Users of Taffy may define what they correspond
/// to in their application (pixels, logical pixels, mm, etc) as they see fit.
#[inline(always)]
pub const fn length(val: f32) -> Self {
Self(CompactLength::length(val))
}
/// A percentage length relative to the size of the containing block.
///
/// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
#[inline(always)]
pub const fn percent(val: f32) -> Self {
Self(CompactLength::percent(val))
}
/// A `calc()` value. The value passed here is treated as an opaque handle to
/// the actual calc representation and may be a pointer, index, etc.
///
/// The low 3 bits are used as a tag value and will be returned as 0.
#[inline(always)]
#[cfg(feature = "calc")]
pub fn calc(ptr: *const ()) -> Self {
Self(CompactLength::calc(ptr))
}
/// Create a LengthPercentage from a raw `CompactLength`.
/// # Safety
/// CompactLength must represent a valid variant for LengthPercentage
#[allow(unsafe_code)]
pub const unsafe fn from_raw(val: CompactLength) -> Self {
Self(val)
}
/// Get the underlying `CompactLength` representation of the value
pub const fn into_raw(self) -> CompactLength {
self.0
}
/// Expand the compact representation into an [`ExpandedLengthPercentage`] enum.
///
/// This is useful when integrating with other libraries (e.g. for style inspection or
/// serialization) as it allows the value to be pattern-matched without having to work
/// with the raw [`CompactLength`] tagged-pointer representation directly.
pub fn expand(self) -> ExpandedLengthPercentage {
match self.0.tag() {
CompactLength::LENGTH_TAG => ExpandedLengthPercentage::Length(self.0.value()),
CompactLength::PERCENT_TAG => ExpandedLengthPercentage::Percent(self.0.value()),
#[cfg(feature = "calc")]
_ if self.0.is_plain_calc() => ExpandedLengthPercentage::Calc(self.0.calc_value()),
_ => unreachable!("LengthPercentage contains a value with an invalid tag"),
}
}
}
/// The expanded, non-compact representation of a [`LengthPercentage`].
///
/// Obtained via [`LengthPercentage::expand`]. Can be converted back into a [`LengthPercentage`]
/// using the [`From`] implementation.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ExpandedLengthPercentage {
/// An absolute length (see [`LengthPercentage::length`])
Length(f32),
/// A percentage length (see [`LengthPercentage::percent`])
Percent(f32),
/// A `calc()` value (see [`LengthPercentage::calc`]). The pointer is an opaque handle to the
/// calc representation, exactly as passed to the constructor.
#[cfg(feature = "calc")]
Calc(*const ()),
}
impl From<LengthPercentage> for ExpandedLengthPercentage {
fn from(value: LengthPercentage) -> Self {
value.expand()
}
}
impl From<ExpandedLengthPercentage> for LengthPercentage {
fn from(value: ExpandedLengthPercentage) -> Self {
match value {
ExpandedLengthPercentage::Length(val) => Self::length(val),
ExpandedLengthPercentage::Percent(val) => Self::percent(val),
#[cfg(feature = "calc")]
ExpandedLengthPercentage::Calc(ptr) => Self::calc(ptr),
}
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for LengthPercentage {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let inner = CompactLength::deserialize(deserializer)?;
// Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
if matches!(inner.tag(), CompactLength::LENGTH_TAG | CompactLength::PERCENT_TAG) {
Ok(Self(inner))
} else {
Err(serde::de::Error::custom("Invalid tag"))
}
}
}
/// A unit of linear measurement
///
/// This is commonly combined with [`Rect`], [`Point`](crate::geometry::Point) and [`Size<T>`](crate::geometry::Size).
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct LengthPercentageAuto(pub(crate) CompactLength);
impl TaffyZero for LengthPercentageAuto {
const ZERO: Self = Self(CompactLength::ZERO);
}
impl TaffyAuto for LengthPercentageAuto {
const AUTO: Self = Self(CompactLength::AUTO);
}
impl FromLength for LengthPercentageAuto {
fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::length(value.into() as f32)
}
}
impl FromPercent for LengthPercentageAuto {
fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::percent(value.into() as f32)
}
}
impl From<LengthPercentage> for LengthPercentageAuto {
fn from(input: LengthPercentage) -> Self {
Self(input.0)
}
}
#[cfg(feature = "parse")]
impl FromCss for LengthPercentageAuto {
fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
match parser.next()?.clone() {
Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
Token::Ident(ident) if ident == "auto" => Ok(Self::auto()),
token => Err(parser.new_unexpected_token_error(token))?,
}
}
}
#[cfg(feature = "parse")]
from_str_from_css!(LengthPercentageAuto);
impl LengthPercentageAuto {
/// An absolute length in some abstract units. Users of Taffy may define what they correspond
/// to in their application (pixels, logical pixels, mm, etc) as they see fit.
#[inline(always)]
pub const fn length(val: f32) -> Self {
Self(CompactLength::length(val))
}
/// A percentage length relative to the size of the containing block.
///
/// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
#[inline(always)]
pub const fn percent(val: f32) -> Self {
Self(CompactLength::percent(val))
}
/// The dimension should be automatically computed according to algorithm-specific rules
/// regarding the default size of boxes.
#[inline(always)]
pub const fn auto() -> Self {
Self(CompactLength::auto())
}
/// A `calc()` value. The value passed here is treated as an opaque handle to
/// the actual calc representation and may be a pointer, index, etc.
///
/// The low 3 bits are used as a tag value and will be returned as 0.
#[inline]
#[cfg(feature = "calc")]
pub fn calc(ptr: *const ()) -> Self {
Self(CompactLength::calc(ptr))
}
/// Create a LengthPercentageAuto from a raw `CompactLength`.
/// # Safety
/// CompactLength must represent a valid variant for LengthPercentageAuto
#[allow(unsafe_code)]
pub const unsafe fn from_raw(val: CompactLength) -> Self {
Self(val)
}
/// Get the underlying `CompactLength` representation of the value
pub const fn into_raw(self) -> CompactLength {
self.0
}
/// Returns:
/// - Some(length) for Length variants
/// - Some(resolved) using the provided context for Percent variants
/// - None for Auto variants
#[inline(always)]
pub fn resolve_to_option(self, context: f32, calc_resolver: impl Fn(*const (), f32) -> f32) -> Option<f32> {
match self.0.tag() {
CompactLength::LENGTH_TAG => Some(self.0.value()),
CompactLength::PERCENT_TAG => Some(context * self.0.value()),
CompactLength::AUTO_TAG => None,
#[cfg(feature = "calc")]
_ if self.0.is_plain_calc() => Some(calc_resolver(self.0.calc_value(), context)),
_ => unreachable!("LengthPercentageAuto values cannot be constructed with other tags"),
}
}
/// Returns true if value is LengthPercentageAuto::Auto
#[inline(always)]
pub fn is_auto(self) -> bool {
self.0.is_auto()
}
/// Expand the compact representation into an [`ExpandedLengthPercentageAuto`] enum.
///
/// This is useful when integrating with other libraries (e.g. for style inspection or
/// serialization) as it allows the value to be pattern-matched without having to work
/// with the raw [`CompactLength`] tagged-pointer representation directly.
pub fn expand(self) -> ExpandedLengthPercentageAuto {
match self.0.tag() {
CompactLength::LENGTH_TAG => ExpandedLengthPercentageAuto::Length(self.0.value()),
CompactLength::PERCENT_TAG => ExpandedLengthPercentageAuto::Percent(self.0.value()),
CompactLength::AUTO_TAG => ExpandedLengthPercentageAuto::Auto,
#[cfg(feature = "calc")]
_ if self.0.is_plain_calc() => ExpandedLengthPercentageAuto::Calc(self.0.calc_value()),
_ => unreachable!("LengthPercentageAuto contains a value with an invalid tag"),
}
}
}
/// The expanded, non-compact representation of a [`LengthPercentageAuto`].
///
/// Obtained via [`LengthPercentageAuto::expand`]. Can be converted back into a
/// [`LengthPercentageAuto`] using the [`From`] implementation.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ExpandedLengthPercentageAuto {
/// An absolute length (see [`LengthPercentageAuto::length`])
Length(f32),
/// A percentage length (see [`LengthPercentageAuto::percent`])
Percent(f32),
/// The automatic keyword (see [`LengthPercentageAuto::auto`])
Auto,
/// A `calc()` value (see [`LengthPercentageAuto::calc`]). The pointer is an opaque handle to
/// the calc representation, exactly as passed to the constructor.
#[cfg(feature = "calc")]
Calc(*const ()),
}
impl From<LengthPercentageAuto> for ExpandedLengthPercentageAuto {
fn from(value: LengthPercentageAuto) -> Self {
value.expand()
}
}
impl From<ExpandedLengthPercentageAuto> for LengthPercentageAuto {
fn from(value: ExpandedLengthPercentageAuto) -> Self {
match value {
ExpandedLengthPercentageAuto::Length(val) => Self::length(val),
ExpandedLengthPercentageAuto::Percent(val) => Self::percent(val),
ExpandedLengthPercentageAuto::Auto => Self::auto(),
#[cfg(feature = "calc")]
ExpandedLengthPercentageAuto::Calc(ptr) => Self::calc(ptr),
}
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for LengthPercentageAuto {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let inner = CompactLength::deserialize(deserializer)?;
// Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
if matches!(inner.tag(), CompactLength::LENGTH_TAG | CompactLength::PERCENT_TAG | CompactLength::AUTO_TAG) {
Ok(Self(inner))
} else {
Err(serde::de::Error::custom("Invalid tag"))
}
}
}
/// A unit of linear measurement
///
/// This is commonly combined with [`Rect`], [`Point`](crate::geometry::Point) and [`Size<T>`](crate::geometry::Size).
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Dimension(pub(crate) CompactLength);
impl TaffyZero for Dimension {
const ZERO: Self = Self(CompactLength::ZERO);
}
impl TaffyAuto for Dimension {
const AUTO: Self = Self(CompactLength::AUTO);
}
impl FromLength for Dimension {
fn from_length<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::length(value.into() as f32)
}
}
impl FromPercent for Dimension {
fn from_percent<Input: Into<f64> + Copy>(value: Input) -> Self {
Self::percent(value.into() as f32)
}
}
impl From<LengthPercentage> for Dimension {
fn from(input: LengthPercentage) -> Self {
Self(input.0)
}
}
impl From<LengthPercentageAuto> for Dimension {
fn from(input: LengthPercentageAuto) -> Self {
Self(input.0)
}
}
#[cfg(feature = "parse")]
impl FromCss for Dimension {
fn from_css<'i>(parser: &mut Parser<'i, '_>) -> CssParseResult<'i, Self> {
let token = parser.next()?.clone();
match token {
Token::Percentage { unit_value, .. } => Ok(Self::percent(unit_value)),
Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::length(value)),
Token::Ident(ref ident) => match ident.as_ref() {
"auto" => Ok(Self::auto()),
"min-content" => Ok(Self::min_content()),
"max-content" => Ok(Self::max_content()),
"fit-content" => Ok(Self::fit_content()),
"stretch" => Ok(Self::stretch()),
"content" => Ok(Self::content()),
_ => Err(parser.new_unexpected_token_error(token))?,
},
Token::Function(ref name) if name.as_ref() == "fit-content" => parser.parse_nested_block(|parser| {
let token = parser.next()?.clone();
match token {
Token::Percentage { unit_value, .. } => Ok(Self::fit_content_percent(unit_value)),
Token::Dimension { unit, value, .. } if unit == "px" => Ok(Self::fit_content_px(value)),
token => Err(parser.new_unexpected_token_error(token))?,
}
}),
token => Err(parser.new_unexpected_token_error(token))?,
}
}
}
#[cfg(feature = "parse")]
from_str_from_css!(Dimension);
impl Dimension {
/// An absolute length in some abstract units. Users of Taffy may define what they correspond
/// to in their application (pixels, logical pixels, mm, etc) as they see fit.
#[inline(always)]
pub const fn length(val: f32) -> Self {
Self(CompactLength::length(val))
}
/// A percentage length relative to the size of the containing block.
///
/// **NOTE: percentages are represented as a f32 value in the range [0.0, 1.0] NOT the range [0.0, 100.0]**
#[inline(always)]
pub const fn percent(val: f32) -> Self {
Self(CompactLength::percent(val))
}
/// The dimension should be automatically computed according to algorithm-specific rules
/// regarding the default size of boxes.
#[inline(always)]
pub const fn auto() -> Self {
Self(CompactLength::auto())
}
/// The size should be the "min-content" size.
/// This is the smallest size that can fit the item's contents with ALL soft line-wrapping opportunities taken
#[inline(always)]
pub const fn min_content() -> Self {
Self(CompactLength::min_content())
}
/// The size should be the "max-content" size.
/// This is the smallest size that can fit the item's contents with NO soft line-wrapping opportunities taken
#[inline(always)]
pub const fn max_content() -> Self {
Self(CompactLength::max_content())
}
/// The size should be computed according to the "fit content" formula:
/// `max(min_content, min(max_content, stretch))`
/// where `stretch` is the size the box would take if it filled the available space
#[inline(always)]
pub const fn fit_content() -> Self {
Self(CompactLength::fit_content_keyword())
}
/// The size should be computed according to the "fit content" formula:
/// `max(min_content, min(max_content, limit))`
/// where `limit` is a LENGTH value
#[inline(always)]
pub const fn fit_content_px(limit: f32) -> Self {
Self(CompactLength::fit_content_px(limit))
}
/// The size should be the "stretch-fit" size: the size the box would take
/// if it filled the available space
/// (<https://www.w3.org/TR/css-sizing-4/#stretch-fit-sizing>)
#[inline(always)]
pub const fn stretch() -> Self {
Self(CompactLength::stretch())
}
/// The size should be an automatic size based on the box's content
/// (<https://www.w3.org/TR/css-flexbox-1/#valdef-flex-basis-content>)
///
/// This keyword is only valid for `flex-basis`. In any other context it behaves as [`auto`](Self::auto).
#[inline(always)]
pub const fn content() -> Self {
Self(CompactLength::content())
}
/// The size should be computed according to the "fit content" formula:
/// `max(min_content, min(max_content, limit))`
/// where `limit` is a PERCENTAGE value
#[inline(always)]
pub const fn fit_content_percent(limit: f32) -> Self {
Self(CompactLength::fit_content_percent(limit))
}
/// A `calc()` value. The value passed here is treated as an opaque handle to
/// the actual calc representation and may be a pointer, index, etc.
///
/// The low 3 bits are used as a tag value and will be returned as 0.
#[inline]
#[cfg(feature = "calc")]
pub fn calc(ptr: *const ()) -> Self {
Self(CompactLength::calc(ptr))
}
/// A `fit-content()` value whose limit is a `calc()` value. The value passed here is treated as an opaque
/// handle to the actual calc representation and may be a pointer, index, etc.
///
/// The low 3 bits are used as a tag value and will be returned as 0.
#[inline]
#[cfg(feature = "calc")]
pub fn fit_content_calc(ptr: *const ()) -> Self {
Self(CompactLength::fit_content_calc(ptr))
}
/// Returns true if the value is a `fit-content()` value with a `calc()` limit
#[inline(always)]
pub fn is_fit_content_calc(self) -> bool {
self.0.is_fit_content_calc()
}
/// Get the calc() pointer (valid for `calc()` and `fit-content(calc())` values)
#[inline(always)]
#[cfg(feature = "calc")]
pub fn calc_value(self) -> *const () {
self.0.calc_value()
}
/// Create a LengthPercentageAuto from a raw `CompactLength`.
/// # Safety
/// CompactLength must represent a valid variant for LengthPercentageAuto
#[allow(unsafe_code)]
pub const unsafe fn from_raw(val: CompactLength) -> Self {
Self(val)
}
/// Get the underlying `CompactLength` representation of the value
pub const fn into_raw(self) -> CompactLength {
self.0
}
/// Get Length value if value is Length variant
#[cfg(feature = "grid")]
pub fn into_option(self) -> Option<f32> {
match self.0.tag() {
CompactLength::LENGTH_TAG => Some(self.0.value()),
_ => None,
}
}
/// Returns true if value is Auto
#[inline(always)]
pub fn is_auto(self) -> bool {
self.0.is_auto()
}
/// Returns true if value is min-content, max-content, fit-content, fit-content(...), or stretch
#[inline(always)]
pub fn is_sizing_keyword(self) -> bool {
self.0.is_sizing_keyword()
}
/// Returns true if value is the stretch keyword
#[inline(always)]
pub fn is_stretch(self) -> bool {
self.0.tag() == CompactLength::STRETCH_TAG
}
/// Returns true if value is the content keyword
#[inline(always)]
pub fn is_content(self) -> bool {
self.0.is_content()
}
/// Get the raw `CompactLength` tag
pub fn tag(self) -> usize {
self.0.tag()
}
/// Get the raw `CompactLength` value for non-calc variants that have a numeric parameter
pub fn value(self) -> f32 {
self.0.value()
}
/// Expand the compact representation into an [`ExpandedDimension`] enum.
///
/// This is useful when integrating with other libraries (e.g. for style inspection or
/// serialization) as it allows the value to be pattern-matched without having to work
/// with the raw [`CompactLength`] tagged-pointer representation directly.
pub fn expand(self) -> ExpandedDimension {
match self.0.tag() {
CompactLength::LENGTH_TAG => ExpandedDimension::Length(self.0.value()),
CompactLength::PERCENT_TAG => ExpandedDimension::Percent(self.0.value()),
CompactLength::AUTO_TAG => ExpandedDimension::Auto,
CompactLength::MIN_CONTENT_TAG => ExpandedDimension::MinContent,
CompactLength::MAX_CONTENT_TAG => ExpandedDimension::MaxContent,
CompactLength::FIT_CONTENT_PX_TAG => ExpandedDimension::FitContentPx(self.0.value()),
CompactLength::FIT_CONTENT_PERCENT_TAG => ExpandedDimension::FitContentPercent(self.0.value()),
CompactLength::FIT_CONTENT_KEYWORD_TAG => ExpandedDimension::FitContent,
#[cfg(feature = "calc")]
_ if self.0.is_fit_content_calc() => ExpandedDimension::FitContentCalc(self.0.calc_value()),
CompactLength::STRETCH_TAG => ExpandedDimension::Stretch,
CompactLength::CONTENT_TAG => ExpandedDimension::Content,
#[cfg(feature = "calc")]
_ if self.0.is_plain_calc() => ExpandedDimension::Calc(self.0.calc_value()),
_ => unreachable!("Dimension contains a value with an invalid tag"),
}
}
}
/// The expanded, non-compact representation of a [`Dimension`].
///
/// Obtained via [`Dimension::expand`]. Can be converted back into a [`Dimension`] using the
/// [`From`] implementation.
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ExpandedDimension {
/// An absolute length (see [`Dimension::length`])
Length(f32),
/// A percentage length (see [`Dimension::percent`])
Percent(f32),
/// The automatic keyword (see [`Dimension::auto`])
Auto,
/// The `min-content` keyword (see [`Dimension::min_content`])
MinContent,
/// The `max-content` keyword (see [`Dimension::max_content`])
MaxContent,
/// A `fit-content(...)` value with a length limit (see [`Dimension::fit_content_px`])
FitContentPx(f32),
/// A `fit-content(...)` value with a percentage limit (see [`Dimension::fit_content_percent`])
FitContentPercent(f32),
/// The size is the fit-content size with a `calc()` limit (an opaque handle to the calc representation)
#[cfg(feature = "calc")]
FitContentCalc(*const ()),
/// The `fit-content` keyword with no limit (see [`Dimension::fit_content`])
FitContent,
/// The `stretch` keyword (see [`Dimension::stretch`])
Stretch,
/// The `content` keyword (see [`Dimension::content`])
Content,
/// A `calc()` value (see [`Dimension::calc`]). The pointer is an opaque handle to the calc
/// representation, exactly as passed to the constructor.
#[cfg(feature = "calc")]
Calc(*const ()),
}
impl From<Dimension> for ExpandedDimension {
fn from(value: Dimension) -> Self {
value.expand()
}
}
impl From<ExpandedDimension> for Dimension {
fn from(value: ExpandedDimension) -> Self {
match value {
ExpandedDimension::Length(val) => Self::length(val),
ExpandedDimension::Percent(val) => Self::percent(val),
ExpandedDimension::Auto => Self::auto(),
ExpandedDimension::MinContent => Self::min_content(),
ExpandedDimension::MaxContent => Self::max_content(),
ExpandedDimension::FitContentPx(val) => Self::fit_content_px(val),
ExpandedDimension::FitContentPercent(val) => Self::fit_content_percent(val),
ExpandedDimension::FitContent => Self::fit_content(),
#[cfg(feature = "calc")]
ExpandedDimension::FitContentCalc(ptr) => Self::fit_content_calc(ptr),
ExpandedDimension::Stretch => Self::stretch(),
ExpandedDimension::Content => Self::content(),
#[cfg(feature = "calc")]
ExpandedDimension::Calc(ptr) => Self::calc(ptr),
}
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Dimension {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let inner = CompactLength::deserialize(deserializer)?;
// Note: validation intentionally excludes the CALC_TAG as deserializing calc() values is not supported
if matches!(
inner.tag(),
CompactLength::LENGTH_TAG
| CompactLength::PERCENT_TAG
| CompactLength::AUTO_TAG
| CompactLength::MIN_CONTENT_TAG
| CompactLength::MAX_CONTENT_TAG
| CompactLength::FIT_CONTENT_KEYWORD_TAG
| CompactLength::FIT_CONTENT_PX_TAG
| CompactLength::FIT_CONTENT_PERCENT_TAG
| CompactLength::STRETCH_TAG
| CompactLength::CONTENT_TAG
) {
Ok(Self(inner))
} else {
Err(serde::de::Error::custom("Invalid tag"))
}
}
}
impl Rect<Dimension> {
/// Create a new Rect with length values
#[must_use]
pub const fn from_length(start: f32, end: f32, top: f32, bottom: f32) -> Self {
Rect {
left: Dimension(CompactLength::length(start)),
right: Dimension(CompactLength::length(end)),
top: Dimension(CompactLength::length(top)),
bottom: Dimension(CompactLength::length(bottom)),
}
}
/// Create a new Rect with percentage values
#[must_use]
pub const fn from_percent(start: f32, end: f32, top: f32, bottom: f32) -> Self {
Rect {
left: Dimension(CompactLength::percent(start)),
right: Dimension(CompactLength::percent(end)),
top: Dimension(CompactLength::percent(top)),
bottom: Dimension(CompactLength::percent(bottom)),
}
}
}
#[cfg(test)]
mod expand_tests {
use super::*;
/// A helper that produces a valid `calc()` handle for tests: a non-null pointer whose low
/// three bits are zero (as required by `CompactLength::calc`).
#[cfg(feature = "calc")]
fn calc_handle() -> *const () {
#[allow(dead_code)]
#[repr(align(8))]
struct Aligned(u64);
static HANDLE: Aligned = Aligned(0);
&HANDLE as *const Aligned as *const ()
}
#[test]
fn length_percentage_round_trips() {
let cases = [LengthPercentage::length(12.0), LengthPercentage::percent(0.5), LengthPercentage::ZERO];
for value in cases {
assert_eq!(LengthPercentage::from(value.expand()), value);
assert_eq!(ExpandedLengthPercentage::from(value), value.expand());
}
assert_eq!(LengthPercentage::length(3.0).expand(), ExpandedLengthPercentage::Length(3.0));
assert_eq!(LengthPercentage::percent(0.25).expand(), ExpandedLengthPercentage::Percent(0.25));
}
#[test]
fn length_percentage_auto_round_trips() {
let cases =
[LengthPercentageAuto::length(12.0), LengthPercentageAuto::percent(0.5), LengthPercentageAuto::auto()];
for value in cases {
assert_eq!(LengthPercentageAuto::from(value.expand()), value);
}
assert_eq!(LengthPercentageAuto::auto().expand(), ExpandedLengthPercentageAuto::Auto);
}
#[test]
fn dimension_round_trips_all_keywords() {
let cases = [
Dimension::length(12.0),
Dimension::percent(0.5),
Dimension::auto(),
Dimension::min_content(),
Dimension::max_content(),
Dimension::fit_content_px(30.0),
Dimension::fit_content_percent(0.75),
Dimension::fit_content(),
Dimension::stretch(),
Dimension::content(),
];
for value in cases {
assert_eq!(Dimension::from(value.expand()), value);
}
assert_eq!(Dimension::fit_content_px(30.0).expand(), ExpandedDimension::FitContentPx(30.0));
assert_eq!(Dimension::content().expand(), ExpandedDimension::Content);
}
#[cfg(feature = "calc")]
#[test]
fn calc_round_trips() {
let handle = calc_handle();
assert_eq!(LengthPercentage::calc(handle).expand(), ExpandedLengthPercentage::Calc(handle));
assert_eq!(LengthPercentage::from(ExpandedLengthPercentage::Calc(handle)), LengthPercentage::calc(handle));
assert_eq!(Dimension::calc(handle).expand(), ExpandedDimension::Calc(handle));
assert_eq!(Dimension::fit_content_calc(handle).expand(), ExpandedDimension::FitContentCalc(handle));
assert_eq!(Dimension::from(ExpandedDimension::FitContentCalc(handle)), Dimension::fit_content_calc(handle));
assert_eq!(LengthPercentageAuto::calc(handle).expand(), ExpandedLengthPercentageAuto::Calc(handle));
}
}
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more