icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! The run variant a snapshot belongs to: the theme, window size and scale factor a test runs
//! in, each present only when the test varies it.

use std::fmt;

use iced_core::theme;
use icedwright_types::Size as LogicalSize;
use icedwright_types::units::{Logical, ScaleFactor};

use crate::config::HarnessConfig;
use crate::harness::TestProgram;
use crate::testing::matrix::{Size, Theme};

/// The name a theme has in snapshot file names.
#[must_use]
pub fn theme_name(theme: Theme) -> &'static str {
    match theme {
        Theme::Light => "light",
        Theme::Dark => "dark",
    }
}

/// The name a window size has in snapshot file names: `phone`, or `w1024h700` for a custom
/// size.
#[must_use]
pub fn size_name(size: Size) -> String {
    match size {
        Size::Phone => "phone".to_owned(),
        Size::Tablet => "tablet".to_owned(),
        Size::Desktop => "desktop".to_owned(),
        Size::Custom(width, height) => format!("w{width}h{height}"),
    }
}

/// The name a scale factor has in snapshot file names: `1x`, `1.25x`, `2x`.
#[must_use]
pub fn scale_name(scale: ScaleFactor) -> String {
    format!("{}x", scale.get())
}

/// The combination of axes a test runs in. A dimension the test does not vary is `None`
/// and is left out of file names, so a test with no variant writes plain `reader.png`.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[must_use]
pub struct Variant {
    theme: Option<Theme>,
    size: Option<Size>,
    scale: Option<ScaleFactor>,
}

impl Variant {
    /// No dimension varied.
    pub fn new() -> Self {
        Self::default()
    }

    /// Varies the theme.
    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Varies the window size.
    pub fn size(mut self, size: Size) -> Self {
        self.size = Some(size);
        self
    }

    /// Varies the scale factor.
    pub fn scale(mut self, scale: ScaleFactor) -> Self {
        self.scale = Some(scale);
        self
    }

    /// The theme, if varied.
    #[must_use]
    pub fn theme_axis(&self) -> Option<Theme> {
        self.theme
    }

    /// The window size, if varied.
    #[must_use]
    pub fn size_axis(&self) -> Option<Size> {
        self.size
    }

    /// The scale factor, if varied.
    #[must_use]
    pub fn scale_axis(&self) -> Option<ScaleFactor> {
        self.scale
    }

    /// Whether no dimension is varied.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.theme.is_none() && self.size.is_none() && self.scale.is_none()
    }

    /// Writes the variant into a configuration: system theme, window size and scale factor,
    /// and the variant itself, which snapshots read back from the harness. The same as
    /// [`HarnessConfig::variant`].
    pub fn apply<P: TestProgram>(self, config: HarnessConfig<P>) -> HarnessConfig<P> {
        config.variant(self)
    }

    pub(crate) fn configure(
        &self,
        system_theme: &mut theme::Mode,
        size: &mut Option<Logical<LogicalSize>>,
        scale: &mut ScaleFactor,
    ) {
        if let Some(axis) = self.theme {
            *system_theme = axis.into();
        }
        if let Some(axis) = self.size {
            *size = Some(axis.into());
        }
        if let Some(axis) = self.scale {
            *scale = axis;
        }
    }

    /// The part of a semantic snapshot's name: the window size, which changes what a
    /// responsive app shows, and the theme only when `per_theme` is on.
    #[must_use]
    pub fn semantic_suffix(&self, per_theme: bool) -> String {
        let theme = self
            .theme
            .filter(|_| per_theme)
            .map(|t| theme_name(t).to_owned());
        let size = self.size.map(size_name);
        [theme, size]
            .into_iter()
            .flatten()
            .collect::<Vec<_>>()
            .join("-")
    }

    /// The snapshot file stem for `name`: `name@dark-desktop-2x`, or `name` with no variant.
    #[must_use]
    pub fn file_stem(&self, name: &str) -> String {
        if self.is_empty() {
            return name.to_owned();
        }
        format!("{name}@{self}")
    }
}

/// `dark-desktop-2x`: theme, size and scale, each only when varied.
impl fmt::Display for Variant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let parts = [
            self.theme.map(|t| theme_name(t).to_owned()),
            self.size.map(size_name),
            self.scale.map(scale_name),
        ];
        let joined: Vec<String> = parts.into_iter().flatten().collect();
        f.write_str(&joined.join("-"))
    }
}