1use std::fmt;
2
3use crate::checked_value::impl_checked_value;
4use crate::{
5 CssLength, CssValue, CssVariableReference, FiniteF64, InvalidCssNumber, number::try_finite,
6 serialization::CssWriteTo,
7};
8
9#[derive(Clone, Copy, Debug, PartialEq)]
25#[non_exhaustive]
26pub enum CssDimension {
27 Length(CssLength),
29 Percent(FiniteF64),
31 Zero,
33}
34
35macro_rules! dimension_constructor {
40 ($(#[$meta:meta])* $name:ident, $try_name:ident, $variant:ident, $unit:literal) => {
41 $(#[$meta])*
42 #[track_caller]
48 pub const fn $name(v: f64) -> Self {
49 match Self::$try_name(v) {
50 Ok(value) => value,
51 Err(_) => panic!(concat!("CSS ", $unit, " value must be finite")),
52 }
53 }
54
55 #[doc = concat!("Attempt to construct a finite `", $unit, "` dimension.")]
56 pub const fn $try_name(v: f64) -> Result<Self, InvalidCssNumber> {
61 match try_finite(v, $unit) {
62 Ok(value) => Ok(Self::Length(CssLength::$variant(value))),
63 Err(error) => Err(error),
64 }
65 }
66 };
67}
68
69impl CssDimension {
70 dimension_constructor!(px, try_px, Px, "px");
72 dimension_constructor!(em, try_em, Em, "em");
74 dimension_constructor!(rem, try_rem, Rem, "rem");
76 dimension_constructor!(vw, try_vw, Vw, "vw");
78 dimension_constructor!(vh, try_vh, Vh, "vh");
80 dimension_constructor!(vmin, try_vmin, Vmin, "vmin");
82 dimension_constructor!(vmax, try_vmax, Vmax, "vmax");
84 dimension_constructor!(ch, try_ch, Ch, "ch");
86 dimension_constructor!(dvw, try_dvw, Dvw, "dvw");
88 dimension_constructor!(dvh, try_dvh, Dvh, "dvh");
90 dimension_constructor!(svw, try_svw, Svw, "svw");
92 dimension_constructor!(svh, try_svh, Svh, "svh");
94 dimension_constructor!(lvw, try_lvw, Lvw, "lvw");
96 dimension_constructor!(lvh, try_lvh, Lvh, "lvh");
98 dimension_constructor!(cqw, try_cqw, Cqw, "cqw");
100 dimension_constructor!(cqh, try_cqh, Cqh, "cqh");
102
103 #[track_caller]
110 pub const fn pct(v: f64) -> Self {
111 match Self::try_pct(v) {
112 Ok(value) => value,
113 Err(_) => panic!("CSS % value must be finite"),
114 }
115 }
116
117 pub const fn try_pct(v: f64) -> Result<Self, InvalidCssNumber> {
123 match try_finite(v, "%") {
124 Ok(value) => Ok(Self::Percent(value)),
125 Err(error) => Err(error),
126 }
127 }
128}
129
130impl CssWriteTo for CssDimension {
131 fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
132 match self {
133 Self::Length(l) => l.css_fmt(w),
134 Self::Percent(v) => write!(w, "{v}%"),
135 Self::Zero => w.write_str("0px"),
136 }
137 }
138}
139
140impl From<CssDimension> for CssValue {
141 fn from(dim: CssDimension) -> Self {
142 match dim {
143 CssDimension::Length(l) => Self::Length(l),
144 CssDimension::Percent(v) => Self::Percent(v),
145 CssDimension::Zero => Self::Zero,
146 }
147 }
148}
149
150impl From<CssLength> for CssDimension {
151 fn from(l: CssLength) -> Self {
152 Self::Length(l)
153 }
154}
155
156#[derive(Clone, Debug, PartialEq)]
161#[non_exhaustive]
162pub enum LengthPercentageAuto {
163 LengthPercentage(CssDimension),
165 Calculation(CssDimensionExpr),
167 Auto,
169}
170
171impl From<CssDimension> for LengthPercentageAuto {
172 fn from(value: CssDimension) -> Self {
173 Self::LengthPercentage(value)
174 }
175}
176
177impl From<CssDimensionExpr> for LengthPercentageAuto {
178 fn from(value: CssDimensionExpr) -> Self {
179 Self::Calculation(value)
180 }
181}
182
183impl CssWriteTo for LengthPercentageAuto {
184 fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
185 match self {
186 Self::LengthPercentage(value) => value.css_fmt(w),
187 Self::Calculation(value) => value.css_fmt(w),
188 Self::Auto => w.write_str("auto"),
189 }
190 }
191}
192
193#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
195#[non_exhaustive]
196pub enum CssEnvironmentVariable {
197 SafeAreaInsetTop,
199 SafeAreaInsetRight,
201 SafeAreaInsetBottom,
203 SafeAreaInsetLeft,
205 SafeAreaMaxInsetTop,
207 SafeAreaMaxInsetRight,
209 SafeAreaMaxInsetBottom,
211 SafeAreaMaxInsetLeft,
213}
214
215impl CssEnvironmentVariable {
216 const fn as_str(self) -> &'static str {
217 match self {
218 Self::SafeAreaInsetTop => "safe-area-inset-top",
219 Self::SafeAreaInsetRight => "safe-area-inset-right",
220 Self::SafeAreaInsetBottom => "safe-area-inset-bottom",
221 Self::SafeAreaInsetLeft => "safe-area-inset-left",
222 Self::SafeAreaMaxInsetTop => "safe-area-max-inset-top",
223 Self::SafeAreaMaxInsetRight => "safe-area-max-inset-right",
224 Self::SafeAreaMaxInsetBottom => "safe-area-max-inset-bottom",
225 Self::SafeAreaMaxInsetLeft => "safe-area-max-inset-left",
226 }
227 }
228}
229
230#[derive(Clone, Debug, PartialEq)]
236pub struct CssDimensionExpr(DimensionExpr);
237
238#[derive(Clone, Debug, PartialEq)]
239enum DimensionExpr {
240 Simple(CssDimension),
241 Variable(CssVariableReference<CssDimension>),
242 Add(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
243 Subtract(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
244 Min(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
245 Max(Box<CssDimensionExpr>, Box<CssDimensionExpr>),
246 Clamp {
247 min: Box<CssDimensionExpr>,
248 preferred: Box<CssDimensionExpr>,
249 max: Box<CssDimensionExpr>,
250 },
251 Env(CssEnvironmentVariable),
252}
253
254impl CssDimensionExpr {
255 fn calc_fmt<W: fmt::Write>(&self, w: &mut W, nested: bool) -> fmt::Result {
256 match &self.0 {
257 DimensionExpr::Simple(value) => value.css_fmt(w),
258 DimensionExpr::Variable(value) => value.css_fmt(w),
259 DimensionExpr::Add(lhs, rhs) | DimensionExpr::Subtract(lhs, rhs) => {
260 if nested {
261 w.write_char('(')?;
262 }
263 lhs.calc_fmt(w, true)?;
264 if matches!(&self.0, DimensionExpr::Add(_, _)) {
265 w.write_str(" + ")?;
266 } else {
267 w.write_str(" - ")?;
268 }
269 rhs.calc_fmt(w, true)?;
270 if nested {
271 w.write_char(')')?;
272 }
273 Ok(())
274 }
275 DimensionExpr::Min(_, _)
276 | DimensionExpr::Max(_, _)
277 | DimensionExpr::Clamp { .. }
278 | DimensionExpr::Env(_) => self.css_fmt(w),
279 }
280 }
281
282 fn css_fmt_as_top_level_calculation<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
289 if matches!(
290 &self.0,
291 DimensionExpr::Simple(_) | DimensionExpr::Variable(_) | DimensionExpr::Env(_)
292 ) {
293 w.write_str("calc(")?;
294 self.calc_fmt(w, false)?;
295 w.write_char(')')
296 } else {
297 self.css_fmt(w)
298 }
299 }
300}
301
302impl CssWriteTo for CssDimensionExpr {
303 fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
304 match &self.0 {
305 DimensionExpr::Simple(value) => value.css_fmt(w),
306 DimensionExpr::Variable(value) => value.css_fmt(w),
307 DimensionExpr::Add(_, _) | DimensionExpr::Subtract(_, _) => {
308 w.write_str("calc(")?;
309 self.calc_fmt(w, false)?;
310 w.write_char(')')
311 }
312 DimensionExpr::Min(lhs, rhs) => {
313 w.write_str("min(")?;
314 lhs.css_fmt(w)?;
315 w.write_str(", ")?;
316 rhs.css_fmt(w)?;
317 w.write_char(')')
318 }
319 DimensionExpr::Max(lhs, rhs) => {
320 w.write_str("max(")?;
321 lhs.css_fmt(w)?;
322 w.write_str(", ")?;
323 rhs.css_fmt(w)?;
324 w.write_char(')')
325 }
326 DimensionExpr::Clamp {
327 min,
328 preferred,
329 max,
330 } => {
331 w.write_str("clamp(")?;
332 min.css_fmt(w)?;
333 w.write_str(", ")?;
334 preferred.css_fmt(w)?;
335 w.write_str(", ")?;
336 max.css_fmt(w)?;
337 w.write_char(')')
338 }
339 DimensionExpr::Env(variable) => write!(w, "env({})", variable.as_str()),
340 }
341 }
342}
343
344impl From<CssDimension> for CssDimensionExpr {
345 fn from(dim: CssDimension) -> Self {
346 Self(DimensionExpr::Simple(dim))
347 }
348}
349
350impl From<CssLength> for CssDimensionExpr {
351 fn from(length: CssLength) -> Self {
352 Self::from(CssDimension::Length(length))
353 }
354}
355
356impl From<CssVariableReference<CssDimension>> for CssDimensionExpr {
357 fn from(variable: CssVariableReference<CssDimension>) -> Self {
358 Self(DimensionExpr::Variable(variable))
359 }
360}
361
362#[derive(Clone, Debug, PartialEq)]
370pub struct LengthPercentageCalculation(CssDimensionExpr);
371
372impl LengthPercentageCalculation {
373 pub fn new(expression: impl Into<CssDimensionExpr>) -> Self {
376 Self(expression.into())
377 }
378}
379
380impl CssWriteTo for LengthPercentageCalculation {
381 fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
382 self.0.css_fmt_as_top_level_calculation(w)
383 }
384}
385
386impl From<CssDimension> for String {
387 fn from(dim: CssDimension) -> Self {
388 let mut s = Self::new();
389 dim.write_to(&mut s);
390 s
391 }
392}
393
394impl From<CssDimension> for std::borrow::Cow<'static, str> {
395 fn from(dim: CssDimension) -> Self {
396 Self::Owned(String::from(dim))
397 }
398}
399
400impl From<CssDimensionExpr> for String {
401 fn from(expr: CssDimensionExpr) -> Self {
402 let mut s = Self::new();
403 expr.write_to(&mut s);
404 s
405 }
406}
407
408impl From<CssDimensionExpr> for std::borrow::Cow<'static, str> {
409 fn from(expr: CssDimensionExpr) -> Self {
410 Self::Owned(String::from(expr))
411 }
412}
413
414impl std::ops::Neg for CssDimension {
415 type Output = Self;
416
417 fn neg(self) -> Self {
419 match self {
420 Self::Length(l) => Self::Length(-l),
421 Self::Percent(v) => Self::Percent(-v),
422 Self::Zero => Self::Zero,
423 }
424 }
425}
426
427fn same_unit(a: &CssLength, b: &CssLength) -> bool {
431 std::mem::discriminant(a) == std::mem::discriminant(b)
432}
433
434impl std::ops::Add for CssDimension {
435 type Output = CssDimensionExpr;
436
437 fn add(self, rhs: Self) -> CssDimensionExpr {
444 match (self, rhs) {
445 (Self::Zero, other) | (other, Self::Zero) => CssDimensionExpr::from(other),
446 (Self::Length(a), Self::Length(b)) if same_unit(&a, &b) => {
447 CssDimensionExpr::from(Self::Length(a.map_value(|v| v + b.value())))
448 }
449 (Self::Percent(a), Self::Percent(b)) => {
450 CssDimensionExpr::from(Self::Percent(FiniteF64::new(a.get() + b.get())))
451 }
452 (a, b) => CssDimensionExpr(DimensionExpr::Add(Box::new(a.into()), Box::new(b.into()))),
453 }
454 }
455}
456
457impl std::ops::Sub for CssDimension {
458 type Output = CssDimensionExpr;
459
460 fn sub(self, rhs: Self) -> CssDimensionExpr {
467 match (self, rhs) {
468 (lhs, Self::Zero) => CssDimensionExpr::from(lhs),
469 (Self::Zero, rhs) => CssDimensionExpr::from(-rhs),
470 (Self::Length(a), Self::Length(b)) if same_unit(&a, &b) => {
471 CssDimensionExpr::from(Self::Length(a.map_value(|v| v - b.value())))
472 }
473 (Self::Percent(a), Self::Percent(b)) => {
474 CssDimensionExpr::from(Self::Percent(FiniteF64::new(a.get() - b.get())))
475 }
476 (a, b) => CssDimensionExpr(DimensionExpr::Subtract(
477 Box::new(a.into()),
478 Box::new(b.into()),
479 )),
480 }
481 }
482}
483
484impl std::ops::Add<CssDimension> for CssDimensionExpr {
485 type Output = CssDimensionExpr;
486
487 fn add(self, rhs: CssDimension) -> CssDimensionExpr {
488 self + CssDimensionExpr::from(rhs)
489 }
490}
491
492impl std::ops::Sub<CssDimension> for CssDimensionExpr {
493 type Output = CssDimensionExpr;
494
495 fn sub(self, rhs: CssDimension) -> CssDimensionExpr {
496 self - CssDimensionExpr::from(rhs)
497 }
498}
499
500impl std::ops::Add for CssDimensionExpr {
501 type Output = CssDimensionExpr;
502
503 fn add(self, rhs: Self) -> Self {
504 match (self.0, rhs.0) {
505 (DimensionExpr::Simple(lhs), DimensionExpr::Simple(rhs)) => lhs + rhs,
506 (lhs, rhs) => Self(DimensionExpr::Add(Box::new(Self(lhs)), Box::new(Self(rhs)))),
507 }
508 }
509}
510
511impl std::ops::Sub for CssDimensionExpr {
512 type Output = CssDimensionExpr;
513
514 fn sub(self, rhs: Self) -> Self {
515 match (self.0, rhs.0) {
516 (DimensionExpr::Simple(lhs), DimensionExpr::Simple(rhs)) => lhs - rhs,
517 (lhs, rhs) => Self(DimensionExpr::Subtract(
518 Box::new(Self(lhs)),
519 Box::new(Self(rhs)),
520 )),
521 }
522 }
523}
524
525macro_rules! dim_fn {
526 ($(#[$meta:meta])* $fn_name:ident, $try_fn_name:ident, $unit_str:literal) => {
527 $(#[$meta])*
528 #[track_caller]
534 pub fn $fn_name(v: impl Into<f64>) -> CssDimension {
535 CssDimension::$fn_name(v.into())
536 }
537
538 #[doc = concat!("Attempt to create a finite CSS `", $unit_str, "` value.")]
539 pub fn $try_fn_name(v: impl Into<f64>) -> Result<CssDimension, InvalidCssNumber> {
544 CssDimension::$try_fn_name(v.into())
545 }
546 };
547}
548
549dim_fn!(px, try_px, "px");
551dim_fn!(em, try_em, "em");
553dim_fn!(
554 #[allow(clippy::module_name_repetitions)]
555 rem,
557 try_rem,
558 "rem"
559);
560dim_fn!(vw, try_vw, "vw");
562dim_fn!(vh, try_vh, "vh");
564dim_fn!(vmin, try_vmin, "vmin");
566dim_fn!(vmax, try_vmax, "vmax");
568dim_fn!(ch, try_ch, "ch");
570dim_fn!(dvw, try_dvw, "dvw");
573dim_fn!(dvh, try_dvh, "dvh");
576dim_fn!(svw, try_svw, "svw");
579dim_fn!(svh, try_svh, "svh");
582dim_fn!(lvw, try_lvw, "lvw");
585dim_fn!(lvh, try_lvh, "lvh");
588dim_fn!(cqw, try_cqw, "cqw");
590dim_fn!(cqh, try_cqh, "cqh");
592
593pub fn pct(v: impl Into<f64>) -> CssDimension {
599 CssDimension::pct(v.into())
600}
601
602pub fn try_pct(v: impl Into<f64>) -> Result<CssDimension, InvalidCssNumber> {
608 CssDimension::try_pct(v.into())
609}
610
611pub fn css_min(
615 lhs: impl Into<CssDimensionExpr>,
616 rhs: impl Into<CssDimensionExpr>,
617) -> CssDimensionExpr {
618 let lhs = lhs.into();
619 let rhs = rhs.into();
620 CssDimensionExpr(DimensionExpr::Min(Box::new(lhs), Box::new(rhs)))
621}
622
623pub fn css_max(
625 lhs: impl Into<CssDimensionExpr>,
626 rhs: impl Into<CssDimensionExpr>,
627) -> CssDimensionExpr {
628 let lhs = lhs.into();
629 let rhs = rhs.into();
630 CssDimensionExpr(DimensionExpr::Max(Box::new(lhs), Box::new(rhs)))
631}
632
633pub fn css_clamp(
635 min: impl Into<CssDimensionExpr>,
636 preferred: impl Into<CssDimensionExpr>,
637 max: impl Into<CssDimensionExpr>,
638) -> CssDimensionExpr {
639 let min = min.into();
640 let preferred = preferred.into();
641 let max = max.into();
642 CssDimensionExpr(DimensionExpr::Clamp {
643 min: Box::new(min),
644 preferred: Box::new(preferred),
645 max: Box::new(max),
646 })
647}
648
649pub fn css_env(variable: CssEnvironmentVariable) -> CssDimensionExpr {
651 CssDimensionExpr(DimensionExpr::Env(variable))
652}
653
654impl_checked_value!(
655 CssDimension,
656 LengthPercentageAuto,
657 CssDimensionExpr,
658 LengthPercentageCalculation,
659);