euv-ui 0.47.0

Cross-platform UI component library and 17-scheme design system for the euv framework with pixel-consistent rendering across Web, Android, iOS, iPadOS, macOS, Windows, and Linux.
Documentation
use super::*;

/// Returns `true` when pre-lowercased `haystack` contains the pre-lowercased `needle_lower` byte slice.
///
/// # Arguments
///
/// - `&[u8]` - Pre-lowercased haystack bytes (valid UTF-8 segments optionally separated by `0xFF`).
/// - `&[u8]` - Pre-lowercased UTF-8 needle bytes.
///
/// # Returns
///
/// - `bool` - `true` when `needle_lower` occurs contiguously inside `haystack`.
#[must_use]
pub(crate) fn contains_ascii_lowered_needle(haystack: &[u8], needle_lower: &[u8]) -> bool {
    let n_len: usize = needle_lower.len();
    if n_len == 0 {
        return true;
    }
    if n_len > haystack.len() {
        return false;
    }
    let first: u8 = needle_lower[0];
    let tail: &[u8] = &needle_lower[1..];
    let limit: usize = haystack.len() - n_len;
    let mut pos: usize = 0;
    while pos <= limit {
        if haystack[pos] == first && haystack[pos + 1..pos + n_len] == *tail {
            return true;
        }
        pos += 1;
    }
    false
}

/// Returns `true` when `haystack` contains `needle` using zero-allocation ASCII case-insensitive matching.
///
/// # Arguments
///
/// - `&str` - Source UTF-8 haystack text.
/// - `&str` - UTF-8 search query substring.
///
/// # Returns
///
/// - `bool` - `true` when `needle` occurs inside `haystack` ignoring ASCII letter case.
#[must_use]
pub(crate) fn contains_ascii_ignore_case(haystack: &str, needle: &str) -> bool {
    let h: &[u8] = haystack.as_bytes();
    let n: &[u8] = needle.as_bytes();
    let n_len: usize = n.len();
    if n_len == 0 {
        return true;
    }
    if n_len > h.len() {
        return false;
    }
    let first: u8 = n[0].to_ascii_lowercase();
    let tail: &[u8] = &n[1..];
    let limit: usize = h.len() - n_len;
    let mut pos: usize = 0;
    while pos <= limit {
        if h[pos].to_ascii_lowercase() == first
            && h[pos + 1..pos + n_len].eq_ignore_ascii_case(tail)
        {
            return true;
        }
        pos += 1;
    }
    false
}

/// Computes dynamic per-column natural widths and total width for `EuvDataTable` so cells render without ellipsis truncation.
///
/// # Arguments
///
/// - `&[String]` - Table column header labels.
/// - `&[Vec<String>]` - Table row cell matrix.
///
/// # Returns
///
/// - `(Vec<f32>, f32)` - Per-column widths in logical pixels and their sum.
#[must_use]
pub(crate) fn compute_data_table_column_widths(
    headers: &[String],
    rows: &[Vec<String>],
) -> (Vec<f32>, f32) {
    let mut col_count: usize = headers.len();
    for row in rows.iter() {
        if row.len() > col_count {
            col_count = row.len();
        }
    }
    if col_count == 0 {
        return (Vec::new(), 0.0);
    }
    let mut widths: Vec<f32> = Vec::with_capacity(col_count);
    let mut total: f32 = 0.0;
    for ci in 0..col_count {
        let mut max_w: f32 = headers
            .get(ci)
            .map(|h: &String| estimate_data_cell_width(h.as_str(), 12.0, true))
            .unwrap_or(0.0);
        for row in rows.iter() {
            if let Some(cell) = row.get(ci) {
                let cw: f32 = estimate_data_cell_width(cell.as_str(), 13.0, false);
                if cw > max_w {
                    max_w = cw;
                }
            }
        }
        let col_w: f32 = (max_w + 38.0).clamp(96.0, 460.0);
        widths.push(col_w);
        total += col_w;
    }
    (widths, total)
}

/// Estimates single-line horizontal width of a `EuvDataTable` cell string in logical pixels.
///
/// # Arguments
///
/// - `&str` - Cell text content.
/// - `f32` - Font size in logical pixels.
/// - `bool` - Whether bold/semi-bold weight is used.
///
/// # Returns
///
/// - `f32` - Estimated single-line width in logical pixels.
#[must_use]
fn estimate_data_cell_width(text: &str, font_size: f32, is_bold: bool) -> f32 {
    let weight_scale: f32 = if is_bold { 1.08 } else { 1.0 };
    let mut best_w: f32 = 0.0;
    for line in text.split('\n') {
        let mut w: f32 = 0.0;
        for ch in line.chars() {
            let factor: f32 = if !ch.is_ascii() {
                1.15
            } else if matches!(
                ch,
                'i' | 'l' | 'I' | '1' | '.' | ',' | ':' | ';' | '|' | '!' | '\'' | ' '
            ) {
                0.38
            } else if ch.is_ascii_uppercase() || matches!(ch, 'w' | 'm' | '@' | '%' | '#' | '&') {
                0.76
            } else {
                0.60
            };
            w += font_size * factor * weight_scale;
        }
        if w > best_w {
            best_w = w;
        }
    }
    best_w
}

/// Parses an optional numeric or currency/percentage string into a finite `f64` for `EuvDataTable` sorting.
///
/// # Arguments
///
/// - `&str` - Raw cell text.
///
/// # Returns
///
/// - `Option<f64>` - Parsed finite numeric value when the cell represents a number.
#[must_use]
fn parse_sortable_number(raw: &str) -> Option<f64> {
    let trimmed: &str = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    let stripped: &str = trimmed
        .strip_prefix('$')
        .unwrap_or(trimmed)
        .strip_suffix('%')
        .unwrap_or(trimmed.strip_prefix('$').unwrap_or(trimmed))
        .trim();
    if stripped.is_empty() {
        return None;
    }
    let parsed: Option<f64> = if stripped.contains(',') {
        let cleaned: String = stripped.replace(',', "");
        cleaned.parse::<f64>().ok()
    } else {
        stripped.parse::<f64>().ok()
    };
    parsed.filter(|v: &f64| v.is_finite())
}

/// Compares two `EuvDataTable` cell strings using numeric-aware, case-insensitive ordering.
///
/// # Arguments
///
/// - `&str` - First cell text.
/// - `&str` - Second cell text.
///
/// # Returns
///
/// - `Ordering` - Deterministic ordering between the two cells.
#[must_use]
pub(crate) fn compare_data_table_cells(a: &str, b: &str) -> Ordering {
    if let (Some(na), Some(nb)) = (parse_sortable_number(a), parse_sortable_number(b)) {
        let num_ord: Ordering = na.total_cmp(&nb);
        if num_ord != Ordering::Equal {
            return num_ord;
        }
    }
    if a.is_ascii() && b.is_ascii() {
        for (ba, bb) in a.bytes().zip(b.bytes()) {
            let ord: Ordering = ba.to_ascii_lowercase().cmp(&bb.to_ascii_lowercase());
            if ord != Ordering::Equal {
                return ord;
            }
        }
        let len_ord: Ordering = a.len().cmp(&b.len());
        if len_ord != Ordering::Equal {
            return len_ord;
        }
        return a.cmp(b);
    }
    let la: String = a.to_lowercase();
    let lb: String = b.to_lowercase();
    let ord: Ordering = la.cmp(&lb);
    if ord != Ordering::Equal {
        return ord;
    }
    a.cmp(b)
}

/// Maps `EuvTone` to the matching contrast-guaranteed `SurfaceRole`.
///
/// # Arguments
///
/// - `EuvTone` - Semantic component tone.
///
/// # Returns
///
/// - `SurfaceRole` - Corresponding surface role for `ThemePalette::surface`.
#[must_use]
pub(crate) fn tone_to_surface_role(tone: EuvTone) -> SurfaceRole {
    match tone {
        EuvTone::Neutral => SurfaceRole::Secondary,
        EuvTone::Primary => SurfaceRole::Primary,
        EuvTone::Success => SurfaceRole::Success,
        EuvTone::Warning => SurfaceRole::Warning,
        EuvTone::Destructive => SurfaceRole::Destructive,
    }
}