diff --git a/crates/engine/src/codegen.rs b/crates/engine/src/codegen.rs index 520728bc5..2a50e42ba 100644 --- a/crates/engine/src/codegen.rs +++ b/crates/engine/src/codegen.rs @@ -137,6 +137,12 @@ pub(crate) fn num(v: f64) -> String { } } +/// `v` without trailing zeros (6 decimals), for lengths that must convert back to the same pixels. +fn num6(v: f64) -> String { + let r = (v * 1_000_000.0).round() / 1_000_000.0; + if r.is_finite() && r != 0.0 { format!("{r}") } else { "0".into() } +} + /// `code` with every pixel length (`12px`) in rem of `root` pixels (`0.75rem`); names that end /// in "px", markup lines (layer text), string literals and comments are left alone. pub fn px_to_rem(code: &str, root: f64) -> String { @@ -202,7 +208,7 @@ fn lengths_to_rem(code: &str, root: f64) -> String { match number.parse::() { Ok(v) if free && v.is_finite() => { out.push_str(before); - out.push_str(&format!("{}rem", num(v / root))); + out.push_str(&format!("{}rem", num6(v / root))); } _ => { out.push_str(head); diff --git a/crates/engine/src/inspect_behaviour_tests.rs b/crates/engine/src/inspect_behaviour_tests.rs index c4bcc6be6..780aa19c6 100644 --- a/crates/engine/src/inspect_behaviour_tests.rs +++ b/crates/engine/src/inspect_behaviour_tests.rs @@ -340,6 +340,13 @@ fn rem_conversion_leaves_names_alone() { let f = crate::codegen::px_to_rem; // Lengths convert, names ending in "px" don't. assert_eq!(f("width: 32px; --gap-8px: 1; margin: -8px 0px;", 16.0), "width: 2rem; --gap-8px: 1; margin: -0.5rem 0rem;"); - assert_eq!(f("épx 1px px", 16.0), "épx 0.06rem px"); + assert_eq!(f("épx 1px px", 16.0), "épx 0.0625rem px"); assert_eq!(f("", 16.0), ""); } + +#[test] +fn rem_conversion_keeps_the_original_pixels() { + let f = crate::codegen::px_to_rem; + assert_eq!(f("padding: 3px;", 16.0), "padding: 0.1875rem;"); + assert_eq!(f("gap: 0.5px;", 16.0), "gap: 0.03125rem;"); +}