use super::format::{
TickDigits, format_compact_number, format_grouped_number, js_equals, js_math_round,
js_round_to_precision, tick_digits,
};
use super::model::{ChartBounds, ChartDomain, ChartSeries, ChartX};
use dioxus::prelude::*;
pub(crate) fn chart_domain(
values: impl IntoIterator<Item = Option<f64>>,
include_zero: bool,
) -> ChartDomain {
let mut min = f64::INFINITY;
let mut max = f64::NEG_INFINITY;
for value in values.into_iter().flatten() {
if !value.is_finite() {
continue;
}
min = min.min(value);
max = max.max(value);
}
if !min.is_finite() || !max.is_finite() {
return ChartDomain::new(0.0, 1.0);
}
if include_zero {
min = min.min(0.0);
max = max.max(0.0);
}
if js_equals(min, max) {
let base = if min == 0.0 { 1.0 } else { min };
let offset = f64::from_bits(1).max(base.abs() * 0.1);
min = (-f64::MAX).max(min - offset);
max = f64::MAX.min(max + offset);
}
ChartDomain::new(min, max)
}
pub(crate) fn resolve_domain(
values: impl IntoIterator<Item = Option<f64>>,
requested: Option<ChartBounds>,
include_zero: bool,
) -> ChartDomain {
let calculated = chart_domain(values, include_zero);
let requested = requested.unwrap_or_default();
ChartDomain::new(
requested.min.unwrap_or(calculated.min),
requested.max.unwrap_or(calculated.max),
)
}
pub(crate) fn scale_value(
value: f64,
domain: ChartDomain,
range_start: f64,
range_end: f64,
) -> f64 {
let size = domain.max - domain.min;
if !value.is_finite() || !domain.min.is_finite() || !domain.max.is_finite() || size == 0.0 {
return range_start;
}
let ratio = if size.is_finite() {
(value - domain.min) / size
} else {
(value / 2.0 - domain.min / 2.0) / (domain.max / 2.0 - domain.min / 2.0)
};
range_start + ratio * (range_end - range_start)
}
pub(crate) fn value_ratio(value: f64, domain: ChartDomain) -> f64 {
scale_value(value, domain, 0.0, 1.0).clamp(0.0, 1.0)
}
const DEFAULT_TICK_COUNT: usize = 5;
const MAXIMUM_TICK_COUNT: u32 = 4_096;
const TICK_MULTIPLIERS: [f64; 4] = [1.0, 2.0, 2.5, 5.0];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TickMode {
Inner,
Outer,
}
#[derive(Clone, Copy, Debug)]
struct TickCandidate {
aligned: bool,
first_index: f64,
intervals: f64,
last_index: f64,
penalty: f64,
step: f64,
}
fn resolve_tick_count(count: usize) -> u32 {
u32::try_from(count).map_or(MAXIMUM_TICK_COUNT, |count| {
count.clamp(2, MAXIMUM_TICK_COUNT)
})
}
fn tick_step(multiplier: f64, exponent: f64) -> f64 {
if exponent < 0.0 {
multiplier / 10f64.powf(-exponent)
} else {
multiplier * 10f64.powf(exponent)
}
}
fn is_tick_quotient_whole(quotient: f64) -> bool {
(quotient - js_math_round(quotient)).abs()
<= 1e-7_f64.min(1e-9_f64.max(quotient.abs() * 16.0 * f64::EPSILON))
}
fn floor_tick_quotient(quotient: f64) -> f64 {
if is_tick_quotient_whole(quotient) {
js_math_round(quotient)
} else {
quotient.floor()
}
}
fn ceil_tick_quotient(quotient: f64) -> f64 {
if is_tick_quotient_whole(quotient) {
js_math_round(quotient)
} else {
quotient.ceil()
}
}
fn tick_candidate(
min: f64,
max: f64,
multiplier: f64,
exponent: f64,
mode: TickMode,
) -> Option<TickCandidate> {
let step = tick_step(multiplier, exponent);
let low = min / step;
let high = max / step;
if !step.is_finite() || step <= 0.0 || !low.is_finite() || !high.is_finite() {
return None;
}
let (first_index, last_index) = match mode {
TickMode::Outer => (floor_tick_quotient(low), ceil_tick_quotient(high)),
TickMode::Inner => (ceil_tick_quotient(low), floor_tick_quotient(high)),
};
Some(TickCandidate {
aligned: is_tick_quotient_whole(low) && is_tick_quotient_whole(high),
first_index,
intervals: last_index - first_index,
last_index,
penalty: if js_equals(multiplier, 2.5) && exponent <= 0.0 {
1.0
} else {
0.0
},
step,
})
}
fn tick_candidates(min: f64, max: f64, target: f64, mode: TickMode) -> Vec<TickCandidate> {
let rough = (max - min) / target;
let exponent = rough.log10().floor();
if !rough.is_finite() || rough <= 0.0 || !exponent.is_finite() {
return Vec::new();
}
let mut candidates = Vec::new();
for offset in [-1.0, 0.0, 1.0] {
for multiplier in TICK_MULTIPLIERS {
if let Some(candidate) = tick_candidate(min, max, multiplier, exponent + offset, mode)
&& candidate.intervals >= 1.0
{
candidates.push(candidate);
}
}
}
candidates
}
fn compare_tick_keys(left: &[f64], right: &[f64]) -> f64 {
for (index, value) in left.iter().enumerate() {
let difference = value - right.get(index).copied().unwrap_or(0.0);
if difference.abs() > 1e-9 {
return difference;
}
}
0.0
}
fn tick_candidate_key(
candidate: &TickCandidate,
span: f64,
target: f64,
mode: TickMode,
) -> Vec<f64> {
let distance = (candidate.intervals - target).abs();
let acceptable =
candidate.intervals >= 1f64.max(target - 1.0) && candidate.intervals <= target + 1.0;
let extent = (candidate.intervals * candidate.step) / span;
let density = [
if acceptable { 0.0 } else { 1.0 },
if acceptable { 0.0 } else { distance },
];
match mode {
TickMode::Outer => vec![
density[0],
density[1],
candidate.penalty,
extent,
distance,
-candidate.step,
],
TickMode::Inner => vec![
density[0],
density[1],
if candidate.aligned { 0.0 } else { 1.0 },
candidate.penalty,
distance,
-extent,
-candidate.step,
],
}
}
fn select_tick_candidate(min: f64, max: f64, target: f64, mode: TickMode) -> Option<TickCandidate> {
let span = max - min;
let mut best: Option<(TickCandidate, Vec<f64>)> = None;
for candidate in tick_candidates(min, max, target, mode) {
let key = tick_candidate_key(&candidate, span, target, mode);
if best
.as_ref()
.is_none_or(|(_, best_key)| compare_tick_keys(&key, best_key) < 0.0)
{
best = Some((candidate, key));
}
}
best.map(|(candidate, _)| candidate)
}
fn is_usable_domain(domain: ChartDomain) -> bool {
let span = domain.max - domain.min;
domain.min.is_finite() && domain.max.is_finite() && span.is_finite() && span > 0.0
}
fn tick_precision(first: f64, last: f64, step: f64) -> usize {
let max_abs = first.abs().max(last.abs()).max(step);
let estimate = (max_abs / step).log10().ceil() + 2.0;
match estimate {
estimate if estimate >= 15.0 => 15,
estimate if estimate >= 14.0 => 14,
estimate if estimate >= 13.0 => 13,
_ => 12,
}
}
fn tick_value(raw: f64, step: f64, precision: usize) -> f64 {
let rounded = js_round_to_precision(raw, precision);
if rounded.is_finite() && (rounded - raw).abs() <= step * 1e-3 {
rounded
} else {
raw
}
}
pub(crate) fn nice_domain(domain: ChartDomain) -> ChartDomain {
nice_domain_with_count(domain, DEFAULT_TICK_COUNT)
}
pub(crate) fn nice_domain_with_count(domain: ChartDomain, count: usize) -> ChartDomain {
if !is_usable_domain(domain) {
return domain;
}
let target = f64::from(resolve_tick_count(count) - 1);
let Some(best) = select_tick_candidate(domain.min, domain.max, target, TickMode::Outer) else {
return domain;
};
let raw_min = best.first_index * best.step;
let raw_max = best.last_index * best.step;
let precision = tick_precision(raw_min, raw_max, best.step);
let nice_min = domain.min.min(tick_value(raw_min, best.step, precision));
let nice_max = domain.max.max(tick_value(raw_max, best.step, precision));
if nice_min.is_finite() && nice_max.is_finite() {
ChartDomain::new(nice_min, nice_max)
} else {
domain
}
}
pub(crate) fn axis_domain(
values: &[Option<f64>],
requested: Option<ChartBounds>,
include_zero: bool,
) -> ChartDomain {
let has_non_zero = values
.iter()
.flatten()
.any(|value| value.is_finite() && *value != 0.0);
let automatic = if has_non_zero {
chart_domain(values.iter().copied(), include_zero)
} else {
ChartDomain::new(0.0, 1.0)
};
let requested = requested.unwrap_or_default();
let requested_min = requested.min.filter(|value| value.is_finite());
let requested_max = requested.max.filter(|value| value.is_finite());
let merged = ChartDomain::new(
requested_min.unwrap_or(automatic.min),
requested_max.unwrap_or(automatic.max),
);
if (requested_min.is_some() && requested_max.is_some()) || merged.max <= merged.min {
return merged;
}
let nice = nice_domain(merged);
ChartDomain::new(
requested_min.unwrap_or(nice.min),
requested_max.unwrap_or(nice.max),
)
}
pub(crate) fn chart_ticks(domain: ChartDomain) -> Vec<f64> {
chart_ticks_with_count(domain, DEFAULT_TICK_COUNT)
}
pub(crate) fn chart_ticks_with_count(domain: ChartDomain, count: usize) -> Vec<f64> {
let safe_count = resolve_tick_count(count);
let bounds = vec![domain.min, domain.max];
if !is_usable_domain(domain) {
return bounds;
}
let target = f64::from(safe_count - 1);
let Some(best) = select_tick_candidate(domain.min, domain.max, target, TickMode::Inner) else {
return bounds;
};
let first = best.first_index * best.step;
let last = best.last_index * best.step;
let valid = first.is_finite()
&& last.is_finite()
&& best.intervals.is_finite()
&& best.intervals >= 1.0
&& best.intervals <= f64::from(safe_count) * 4.0;
if !valid {
return bounds;
}
let precision = tick_precision(first, last, best.step);
let boundary_tolerance = best.step * 1e-9;
let mut ticks: Vec<f64> = Vec::new();
let mut index = 0.0;
while index <= best.intervals {
let mut tick = tick_value(first + index * best.step, best.step, precision);
if !tick.is_finite() {
return bounds;
}
if tick < domain.min && domain.min - tick <= boundary_tolerance {
tick = domain.min;
}
if tick > domain.max && tick - domain.max <= boundary_tolerance {
tick = domain.max;
}
if tick < domain.min || tick > domain.max {
index += 1.0;
continue;
}
if ticks.last().is_some_and(|previous| tick <= *previous) {
return bounds;
}
ticks.push(tick);
index += 1.0;
}
if ticks.len() >= 2 { ticks } else { bounds }
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum TickFormatter {
Custom(Callback<f64, String>),
Standard(usize),
Compact(usize),
}
impl std::fmt::Debug for TickFormatter {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Custom(_) => formatter.write_str("Custom"),
Self::Standard(decimals) => formatter.debug_tuple("Standard").field(decimals).finish(),
Self::Compact(digits) => formatter.debug_tuple("Compact").field(digits).finish(),
}
}
}
const TICK_LABEL_LENGTH: usize = 5;
fn longest_label(labels: &[String]) -> usize {
labels
.iter()
.map(|label| label.chars().count())
.max()
.unwrap_or(0)
}
fn distinct_labels(labels: &[String]) -> usize {
labels
.iter()
.collect::<std::collections::HashSet<_>>()
.len()
}
impl TickFormatter {
pub(crate) fn new(ticks: &[f64], format_value: Option<&Callback<f64, String>>) -> Self {
if let Some(format) = format_value {
return Self::Custom(*format);
}
let values: Vec<f64> = ticks
.iter()
.copied()
.filter(|value| value.is_finite())
.collect();
let digits: Vec<TickDigits> = values.iter().map(|value| tick_digits(*value)).collect();
let decimals = digits
.iter()
.map(|digits| digits.decimals)
.max()
.unwrap_or(0);
let standard = Self::Standard(decimals);
let standard_labels: Vec<String> =
values.iter().map(|value| standard.format(*value)).collect();
let standard_length = longest_label(&standard_labels);
if standard_length <= TICK_LABEL_LENGTH {
return standard;
}
let significant = digits
.iter()
.map(|digits| digits.significant)
.max()
.unwrap_or(1)
.max(1);
let compact = Self::Compact(significant);
let compact_labels: Vec<String> =
values.iter().map(|value| compact.format(*value)).collect();
if longest_label(&compact_labels) < standard_length
&& distinct_labels(&compact_labels) == distinct_labels(&standard_labels)
{
compact
} else {
standard
}
}
pub(crate) fn format(self, value: f64) -> String {
match self {
Self::Custom(format) => format.call(value),
Self::Standard(decimals) => format_grouped_number(value, decimals),
Self::Compact(digits) => format_compact_number(value, digits),
}
}
}
pub(crate) fn format_ticks(
ticks: &[f64],
format_value: Option<&Callback<f64, String>>,
) -> Vec<String> {
let formatter = TickFormatter::new(ticks, format_value);
ticks.iter().map(|tick| formatter.format(*tick)).collect()
}
const LABEL_CHARACTER_WIDTH: f64 = 7.0;
const LABEL_NARROW_CHARACTER_WIDTH: f64 = 4.0;
const LABEL_WIDE_CHARACTER_WIDTH: f64 = 11.0;
const LABEL_GAP: f64 = 16.0;
const MAXIMUM_AXIS_PADDING: f64 = 240.0;
const COMBINING_RANGES: [(u32, u32); 7] = [
(0x0300, 0x036F),
(0x1AB0, 0x1AFF),
(0x1DC0, 0x1DFF),
(0x20D0, 0x20FF),
(0xFE00, 0xFE0F),
(0xFE20, 0xFE2F),
(0x1F3FB, 0x1F3FF),
];
const WIDE_RANGES: [(u32, u32); 11] = [
(0x1100, 0x115F),
(0x2329, 0x232A),
(0x2E80, 0xA4CF),
(0xAC00, 0xD7A3),
(0xF900, 0xFAFF),
(0xFE10, 0xFE19),
(0xFE30, 0xFE6F),
(0xFF00, 0xFF60),
(0xFFE0, 0xFFE6),
(0x1F300, 0x1FAFF),
(0x20000, 0x3FFFD),
];
fn in_ranges(code_point: u32, ranges: &[(u32, u32)]) -> bool {
ranges
.iter()
.any(|(start, end)| code_point >= *start && code_point <= *end)
}
fn character_width(character: char) -> f64 {
let code_point = u32::from(character);
if code_point == 0x200D || in_ranges(code_point, &COMBINING_RANGES) {
return 0.0;
}
if in_ranges(code_point, &WIDE_RANGES) {
return LABEL_WIDE_CHARACTER_WIDTH;
}
if matches!(character, 'M' | 'W' | '@' | '%' | '&' | '#') {
return 10.0;
}
if matches!(
character,
' ' | '.' | ',' | ':' | ';' | '!' | '|' | '\'' | 'i' | 'j' | 'l' | 'I'
) {
return LABEL_NARROW_CHARACTER_WIDTH;
}
LABEL_CHARACTER_WIDTH
}
fn utf16_length(label: &str) -> f64 {
#[allow(clippy::cast_precision_loss)]
let length = label.encode_utf16().count() as f64;
length
}
pub(crate) fn estimate_label_width(label: &str) -> f64 {
let width: f64 = label.chars().map(character_width).sum();
(utf16_length(label) * LABEL_CHARACTER_WIDTH).max(width)
}
pub(crate) fn axis_padding<S: AsRef<str>>(
labels: &[S],
minimum: f64,
font_size: Option<f64>,
) -> f64 {
let safe_minimum = minimum.max(0.0);
let widest = labels
.iter()
.map(|label| estimate_label_width(label.as_ref()))
.fold(0.0, f64::max);
MAXIMUM_AXIS_PADDING.min(safe_minimum.max(widest * label_font_scale(font_size) + LABEL_GAP))
}
pub(crate) fn estimate_chart_label_width(label: &str, font_size: f64) -> f64 {
estimate_label_width(label) * label_font_scale(Some(font_size))
}
fn label_font_scale(font_size: Option<f64>) -> f64 {
match font_size {
Some(size) if size.is_finite() && size > 0.0 => size / 11.0,
_ => 1.0,
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CategoryTick {
pub(crate) index: usize,
pub(crate) label: String,
pub(crate) position: f64,
}
impl CategoryTick {
pub(crate) const ANCHOR: &'static str = "middle";
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct CategoryTickOptions<'a> {
pub(crate) start: f64,
pub(crate) end: f64,
pub(crate) bounds: Option<(f64, f64)>,
pub(crate) font_size: Option<f64>,
pub(crate) maximum_font_size: Option<f64>,
pub(crate) positions: Option<&'a [f64]>,
}
impl<'a> CategoryTickOptions<'a> {
pub(crate) fn new(start: f64, end: f64) -> Self {
Self {
start,
end,
bounds: None,
font_size: None,
maximum_font_size: None,
positions: None,
}
}
pub(crate) fn positions(mut self, positions: &'a [f64]) -> Self {
self.positions = Some(positions);
self
}
pub(crate) fn bounds(mut self, start: f64, end: f64) -> Self {
self.bounds = Some((start, end));
self
}
pub(crate) fn font_size(mut self, font_size: f64) -> Self {
self.font_size = Some(font_size);
self
}
pub(crate) fn maximum_font_size(mut self, font_size: f64) -> Self {
self.maximum_font_size = Some(font_size);
self
}
}
const CATEGORY_LABEL_GAP: f64 = 8.0;
struct CategoryCandidate {
index: usize,
label: String,
position: f64,
width: f64,
}
fn fit_label(label: &str, maximum_width: f64) -> String {
if estimate_label_width(label) <= maximum_width {
return label.to_string();
}
let suffix = '…';
let mut result = String::new();
let mut width = estimate_label_width("…");
for character in label.chars() {
width += LABEL_CHARACTER_WIDTH.max(character_width(character));
if width > maximum_width {
break;
}
result.push(character);
}
result.push(suffix);
result
}
fn labels_collide(previous: &CategoryCandidate, next: &CategoryCandidate, gap: f64) -> bool {
next.position - next.width / 2.0 < previous.position + previous.width / 2.0 + gap
}
fn select_stride(candidates: &[CategoryCandidate], stride: usize, gap: f64) -> Option<Vec<usize>> {
let mut selected: Vec<usize> = Vec::new();
for index in (0..candidates.len()).step_by(stride) {
if let Some(&previous) = selected.last()
&& labels_collide(&candidates[previous], &candidates[index], gap)
{
return None;
}
selected.push(index);
}
let last = candidates.len().checked_sub(1)?;
if selected.last() == Some(&last) {
return Some(selected);
}
let collides_with_last =
|previous: usize| labels_collide(&candidates[previous], &candidates[last], gap);
while selected.len() > 1
&& selected
.last()
.is_some_and(|&previous| collides_with_last(previous))
{
selected.pop();
}
if selected
.last()
.is_some_and(|&previous| collides_with_last(previous))
{
return None;
}
selected.push(last);
Some(selected)
}
fn select_ticks(candidates: Vec<CategoryCandidate>, gap: f64) -> Vec<CategoryTick> {
let selected = (1..candidates.len())
.find_map(|stride| select_stride(&candidates, stride, gap))
.unwrap_or_else(|| {
if candidates.is_empty() {
Vec::new()
} else {
vec![0]
}
});
let mut candidates: Vec<Option<CategoryCandidate>> = candidates.into_iter().map(Some).collect();
selected
.into_iter()
.filter_map(|index| candidates.get_mut(index).and_then(Option::take))
.map(|candidate| CategoryTick {
index: candidate.index,
label: candidate.label,
position: candidate.position,
})
.collect()
}
fn place_label(position: f64, width: f64, bounds: Option<(f64, f64)>) -> f64 {
let Some((start, end)) = bounds else {
return position;
};
let half = width.min(end - start) / 2.0;
(end - half).min((start + half).max(position))
}
fn tick_positions(count: usize, end: f64, positions: Option<&[f64]>, start: f64) -> Vec<f64> {
if let Some(positions) = positions {
let valid = positions.len() == count
&& positions.iter().enumerate().all(|(index, position)| {
let previous = if index == 0 {
start
} else {
positions[index - 1]
};
position.is_finite()
&& *position >= start
&& *position <= end
&& *position >= previous
});
if valid {
return positions.to_vec();
}
}
(0..count)
.map(|index| {
#[allow(clippy::cast_precision_loss)]
let ratio = if count == 1 {
0.5
} else {
index as f64 / (count - 1) as f64
};
start + ratio * (end - start)
})
.collect()
}
pub(crate) fn category_ticks<S: AsRef<str>>(
labels: &[S],
options: CategoryTickOptions<'_>,
) -> Vec<CategoryTick> {
let CategoryTickOptions {
start,
end,
bounds,
font_size,
maximum_font_size,
positions,
} = options;
if labels.is_empty() || !start.is_finite() || !end.is_finite() || end < start {
return Vec::new();
}
let font_scale = label_font_scale(font_size);
let placement_scale = font_scale.max(label_font_scale(maximum_font_size.or(font_size)));
let gap = CATEGORY_LABEL_GAP;
let bounds = bounds.filter(|(bound_start, bound_end)| {
bound_start.is_finite() && bound_end.is_finite() && bound_end > bound_start
});
let resolved = tick_positions(labels.len(), end, positions, start);
let span = resolved.last().copied().unwrap_or(end) - resolved.first().copied().unwrap_or(start);
let axis_width = if labels.len() == 1 {
end - start
} else {
(span - gap) / 2.0
}
.max(0.0);
let maximum_width = match bounds {
Some((bound_start, bound_end)) => axis_width.min(bound_end - bound_start),
None => axis_width,
};
let candidates = labels
.iter()
.enumerate()
.map(|(index, label)| {
let fitted = fit_label(label.as_ref(), maximum_width / font_scale);
let width = estimate_label_width(&fitted) * font_scale;
CategoryCandidate {
index,
position: place_label(
resolved.get(index).copied().unwrap_or(start),
(width / font_scale) * placement_scale,
bounds,
),
label: fitted,
width,
}
})
.collect();
select_ticks(candidates, gap)
}
pub(crate) fn fitted_label(label: &str, end: f64) -> String {
category_ticks(&[label], CategoryTickOptions::new(0.0, end))
.into_iter()
.next()
.map_or_else(String::new, |tick| tick.label)
}
pub(crate) fn chart_categories(series: &[ChartSeries]) -> Vec<ChartX> {
let mut seen = std::collections::HashSet::new();
let mut categories = Vec::new();
for item in series {
for datum in &item.data {
if seen.insert(datum.x.key()) {
categories.push(datum.x.clone());
}
}
}
categories
}
pub(crate) fn align_series(series: &ChartSeries, categories: &[ChartX]) -> ChartSeries {
let mut indexed = std::collections::HashMap::new();
for datum in &series.data {
indexed.insert(datum.x.key(), datum);
}
ChartSeries {
id: series.id.clone(),
label: series.label.clone(),
tone: series.tone,
dash: series.dash,
data: categories
.iter()
.map(|category| {
indexed.get(&category.key()).map_or_else(
|| super::model::ChartDatum::missing(category.clone()),
|datum| (*datum).clone(),
)
})
.collect(),
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LabelContext {
Axis,
Detail,
}
pub(crate) fn category_label(
series: &[ChartSeries],
category: &ChartX,
format_category: Option<&Callback<ChartX, String>>,
context: LabelContext,
) -> String {
if context == LabelContext::Detail
&& let Some(format) = format_category
{
return format.call(category.clone());
}
for item in series {
if let Some(label) = item
.data
.iter()
.find(|datum| datum.x == *category)
.and_then(|datum| datum.x_label.clone())
{
return label;
}
}
match format_category {
Some(format) => format.call(category.clone()),
None => category.display(),
}
}
pub(crate) fn has_chart_data(series: &[ChartSeries]) -> bool {
series
.iter()
.any(|item| item.data.iter().any(|datum| datum.value().is_some()))
}
#[cfg(test)]
mod tests {
use super::{
CategoryTickOptions, ChartBounds, ChartDomain, TickFormatter, axis_domain, axis_padding,
category_ticks, chart_domain, chart_ticks, chart_ticks_with_count,
estimate_chart_label_width, estimate_label_width, fitted_label, format_ticks, nice_domain,
scale_value, value_ratio,
};
fn values(list: &[f64]) -> Vec<Option<f64>> {
list.iter().copied().map(Some).collect()
}
#[test]
fn domains_include_zero_and_widen_flat_data() {
assert_eq!(
chart_domain([Some(3.0), Some(8.0)], true),
ChartDomain::new(0.0, 8.0)
);
assert_eq!(
chart_domain([Some(3.0), Some(8.0)], false),
ChartDomain::new(3.0, 8.0)
);
assert_eq!(
chart_domain([Some(-4.0), Some(-1.0)], true),
ChartDomain::new(-4.0, 0.0)
);
let flat = chart_domain([Some(5.0)], false);
assert!((flat.min - 4.5).abs() < 1e-12 && (flat.max - 5.5).abs() < 1e-12);
assert_eq!(
chart_domain([Some(0.0)], false),
ChartDomain::new(-0.1, 0.1)
);
assert_eq!(chart_domain([], true), ChartDomain::new(0.0, 1.0));
assert_eq!(
chart_domain([None, Some(f64::NAN), Some(f64::INFINITY)], true),
ChartDomain::new(0.0, 1.0)
);
}
#[test]
fn scales_guard_invalid_input_and_overflow() {
let domain = ChartDomain::new(0.0, 10.0);
assert!((scale_value(5.0, domain, 0.0, 100.0) - 50.0).abs() < 1e-12);
assert!((scale_value(5.0, domain, 100.0, 0.0) - 50.0).abs() < 1e-12);
assert!((scale_value(f64::NAN, domain, 7.0, 100.0) - 7.0).abs() < 1e-12);
assert!((scale_value(1.0, ChartDomain::new(2.0, 2.0), 7.0, 100.0) - 7.0).abs() < 1e-12);
let extreme = ChartDomain::new(-f64::MAX, f64::MAX);
assert!((scale_value(0.0, extreme, 0.0, 1.0) - 0.5).abs() < 1e-12);
assert!((value_ratio(20.0, domain) - 1.0).abs() < 1e-12);
assert!(value_ratio(-5.0, domain).abs() < 1e-12);
}
#[test]
fn ticks_are_nice_and_fall_back_to_bounds() {
assert_eq!(
chart_ticks(ChartDomain::new(0.0, 100.0)),
vec![0.0, 25.0, 50.0, 75.0, 100.0]
);
assert_eq!(
chart_ticks(ChartDomain::new(0.0, 1.0)),
vec![0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
);
assert_eq!(
chart_ticks(ChartDomain::new(-3.0, 7.0)),
vec![-2.0, 0.0, 2.0, 4.0, 6.0]
);
assert_eq!(
chart_ticks(ChartDomain::new(0.1, 0.7)),
vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
);
assert_eq!(chart_ticks(ChartDomain::new(5.0, 5.0)), vec![5.0, 5.0]);
assert_eq!(chart_ticks(ChartDomain::new(f64::NAN, 1.0)).len(), 2);
assert_eq!(
chart_ticks(ChartDomain::new(-f64::MAX, f64::MAX)),
vec![-f64::MAX, f64::MAX]
);
assert_eq!(
chart_ticks_with_count(ChartDomain::new(0.0, 10.0), 0),
vec![0.0, 10.0]
);
}
#[test]
fn shared_tick_fixtures_stay_inside_exact_domains() {
let cases: [(ChartDomain, &[f64]); 10] = [
(
ChartDomain::new(1e15 + 0.4, 1e15 + 3.4),
&[
1e15 + 0.5,
1e15 + 1.0,
1e15 + 1.5,
1e15 + 2.0,
1e15 + 2.5,
1e15 + 3.0,
],
),
(
ChartDomain::new(-1e15 - 3.4, -1e15 - 0.4),
&[
-1e15 - 3.0,
-1e15 - 2.5,
-1e15 - 2.0,
-1e15 - 1.5,
-1e15 - 1.0,
-1e15 - 0.5,
],
),
(
ChartDomain::new(1e14 + 0.125, 1e14 + 1.125),
&[
100_000_000_000_000.2,
100_000_000_000_000.4,
100_000_000_000_000.61,
100_000_000_000_000.8,
100_000_000_000_001.0,
],
),
(
ChartDomain::new(-1e14 - 1.125, -1e14 - 0.125),
&[
-100_000_000_000_001.0,
-100_000_000_000_000.8,
-100_000_000_000_000.6,
-100_000_000_000_000.4,
-100_000_000_000_000.2,
],
),
(
ChartDomain::new(0.1 + 0.2, 0.6),
&[0.1 + 0.2, 0.4, 0.5, 0.6],
),
(
ChartDomain::new(-0.6, -(0.1 + 0.2)),
&[-0.6, -0.5, -0.4, -(0.1 + 0.2)],
),
(ChartDomain::new(0.1, 0.3), &[0.1, 0.15, 0.2, 0.25, 0.3]),
(ChartDomain::new(1e16, 1e16 + 2.0), &[1e16, 1e16 + 2.0]),
(ChartDomain::new(-1e16 - 2.0, -1e16), &[-1e16 - 2.0, -1e16]),
(ChartDomain::new(0.0, 1e-323), &[0.0, 1e-323]),
];
for (domain, expected) in cases {
let ticks = chart_ticks(domain);
assert_eq!(ticks, expected, "{domain:?}");
assert_eq!(
axis_domain(
&[Some(domain.min), Some(domain.max)],
Some(ChartBounds {
min: Some(domain.min),
max: Some(domain.max)
}),
false,
),
domain,
);
assert!(ticks.len() >= 2);
assert!(
ticks
.iter()
.all(|tick| tick.is_finite() && *tick >= domain.min && *tick <= domain.max)
);
assert!(
ticks
.iter()
.all(|tick| (0.0..=1.0).contains(&scale_value(*tick, domain, 0.0, 1.0)))
);
assert!(ticks.windows(2).all(|pair| pair[0] < pair[1]));
}
}
#[test]
fn ticks_stay_inside_signed_narrow_domains_at_numeric_precision_limits() {
for magnitude in [1e-300, 1e-100, 1.0, 1e10, 1e14, 1e15, 1e16, 1e100, 1e300] {
for sign in [-1.0, 1.0] {
for width in [1.0, 3.0, 17.0, 100.0] {
let min = sign * magnitude;
let domain = ChartDomain::new(min, min + magnitude * f64::EPSILON * width);
for count in [2, 5, 17] {
let ticks = chart_ticks_with_count(domain, count);
assert!(ticks.len() >= 2, "{domain:?}");
assert!(
ticks.iter().all(|tick| tick.is_finite()
&& *tick >= domain.min
&& *tick <= domain.max),
"{domain:?}: {ticks:?}"
);
assert!(
ticks.windows(2).all(|pair| pair[0] < pair[1]),
"{domain:?}: {ticks:?}"
);
}
}
}
}
}
#[test]
fn axis_domains_round_out_to_ticks() {
let cases: [(&[f64], bool, (f64, f64)); 9] = [
(
&[
82.0, 104.0, 97.0, 128.0, 146.0, 120.0, 168.0, 154.0, 201.0, 238.0,
],
false,
(50.0, 250.0),
),
(
&[0.0, 120.0, 205.0, 237.0, 217.0, 162.0, 148.0],
true,
(0.0, 250.0),
),
(&[12.0, 13.0, 14.0, 24.0, 27.0, 31.0], false, (10.0, 35.0)),
(&[128.0, 146.0, 274.0, 250.0], true, (0.0, 300.0)),
(
&[18_420.0, 9_870.0, 6_320.0, 4_210.0],
true,
(0.0, 20_000.0),
),
(&[18.0, 96.0, 218.0, 302.0, 11.0], true, (0.0, 400.0)),
(&[-40.0, 120.0], true, (-50.0, 150.0)),
(&[-238.0, -82.0], false, (-250.0, -50.0)),
(&[12.0, 18.0, 16.0], false, (12.0, 18.0)),
];
for (data, include_zero, (min, max)) in cases {
let domain = axis_domain(&values(data), None, include_zero);
let ticks = chart_ticks(domain);
assert_eq!(domain, ChartDomain::new(min, max), "{data:?}");
assert_eq!(ticks.first().copied(), Some(min), "{data:?}");
assert_eq!(ticks.last().copied(), Some(max), "{data:?}");
assert!((4..=6).contains(&ticks.len()), "{data:?}: {ticks:?}");
}
}
#[test]
fn axis_ticks_prefer_whole_steps_over_fractional_quarters() {
let ticks = |data: &[f64], include_zero: bool| {
chart_ticks(axis_domain(&values(data), None, include_zero))
};
assert_eq!(
ticks(&[0.0, 95.0], true),
vec![0.0, 25.0, 50.0, 75.0, 100.0]
);
assert_eq!(ticks(&[12.0, 18.0], false), vec![12.0, 14.0, 16.0, 18.0]);
assert_eq!(
ticks(&[0.0, 0.93], true),
vec![0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
);
assert_eq!(ticks(&[0.1, 0.3], false), vec![0.1, 0.15, 0.2, 0.25, 0.3]);
}
#[test]
fn axis_domains_keep_explicit_bounds_and_round_the_automatic_side() {
let data = values(&[82.0, 238.0]);
assert_eq!(
axis_domain(&data, Some(ChartBounds::min(0.0)), false),
ChartDomain::new(0.0, 250.0)
);
assert_eq!(
axis_domain(&data, Some(ChartBounds::max(240.0)), false),
ChartDomain::new(50.0, 240.0)
);
assert_eq!(
axis_domain(&data, Some(ChartBounds::new(7.0, 237.0)), false),
ChartDomain::new(7.0, 237.0)
);
assert_eq!(
axis_domain(
&data,
Some(ChartBounds::new(f64::NAN, f64::INFINITY)),
false
),
ChartDomain::new(50.0, 250.0)
);
}
#[test]
fn axis_domains_use_zero_to_one_without_readable_data() {
for data in [
Vec::new(),
vec![None, None],
values(&[0.0, 0.0, 0.0]),
values(&[f64::NAN, f64::INFINITY, f64::NEG_INFINITY]),
] {
let domain = axis_domain(&data, None, true);
assert_eq!(domain, ChartDomain::new(0.0, 1.0), "{data:?}");
assert_eq!(chart_ticks(domain), vec![0.0, 0.2, 0.4, 0.6, 0.8, 1.0]);
}
}
#[test]
fn axis_domains_stay_finite_for_single_values_and_extremes() {
assert_eq!(
axis_domain(&values(&[5.0]), None, true),
ChartDomain::new(0.0, 5.0)
);
assert_eq!(
axis_domain(&values(&[50.0]), None, false),
ChartDomain::new(45.0, 55.0)
);
assert_eq!(
axis_domain(&values(&[0.0, 9e15]), None, true),
ChartDomain::new(0.0, 1e16)
);
for data in [
vec![f64::MAX],
vec![-f64::MAX, f64::MAX],
vec![f64::from_bits(1)],
vec![1e-300, 2e-300],
vec![1e16, 1e16 + 2.0],
vec![1.5e308, 1.79e308],
] {
let domain = axis_domain(&values(&data), None, false);
let ticks = chart_ticks(domain);
let lowest = data.iter().copied().fold(f64::INFINITY, f64::min);
let highest = data.iter().copied().fold(f64::NEG_INFINITY, f64::max);
assert!(domain.min.is_finite() && domain.max.is_finite(), "{data:?}");
assert!(domain.min <= lowest && domain.max >= highest, "{data:?}");
assert!(ticks.iter().all(|tick| tick.is_finite()), "{data:?}");
assert!(ticks.windows(2).all(|pair| pair[0] < pair[1]), "{data:?}");
}
}
#[test]
fn nice_domains_return_unusable_domains_unchanged() {
for domain in [
ChartDomain::new(f64::NAN, 1.0),
ChartDomain::new(0.0, f64::INFINITY),
ChartDomain::new(5.0, 5.0),
ChartDomain::new(10.0, 1.0),
ChartDomain::new(-f64::MAX, f64::MAX),
] {
let nice = nice_domain(domain);
assert!(
nice.min.to_bits() == domain.min.to_bits()
&& nice.max.to_bits() == domain.max.to_bits(),
"{domain:?}"
);
}
assert_eq!(
nice_domain(ChartDomain::new(0.0, 238.0)),
ChartDomain::new(0.0, 250.0)
);
}
#[test]
fn generated_domains_and_ticks_stay_consistent_for_random_extents() {
let mut seed = 7_u64;
let mut random = || {
seed = (seed * 16_807) % 2_147_483_647;
f64::from(u32::try_from(seed).expect("Park–Miller seeds stay below 2^31"))
/ 2_147_483_647.0
};
for _ in 0..2_000 {
let scale = 10f64.powf((random() * 16.0 - 8.0).floor());
let first = (random() - 0.3) * 1_000.0 * scale;
let second = first + random() * 1_000.0 * scale + f64::EPSILON * first.abs() * 64.0;
let domain = axis_domain(&values(&[first, second]), None, false);
let ticks = chart_ticks(domain);
let step = ticks[1] - ticks[0];
assert!(domain.min <= first && domain.max >= second);
assert!((3..=7).contains(&ticks.len()), "{domain:?}: {ticks:?}");
assert!((ticks[0] - domain.min).abs() <= step.abs() * 1e-6);
assert!((ticks[ticks.len() - 1] - domain.max).abs() <= step.abs() * 1e-6);
assert!(
ticks
.iter()
.all(|tick| (tick / step - (tick / step).round()).abs() < 1e-6),
"{ticks:?}"
);
}
}
#[test]
fn tick_labels_group_and_switch_the_whole_axis_to_compact_notation() {
let labels = |ticks: &[f64]| format_ticks(ticks, None);
assert_eq!(
labels(&[0.0, 500.0, 1_000.0, 1_500.0]),
["0", "500", "1,000", "1,500"]
);
assert_eq!(
labels(&[0.0, 5_000.0, 10_000.0, 15_000.0, 20_000.0]),
["0", "5K", "10K", "15K", "20K"]
);
assert_eq!(
labels(&[0.0, 2_500.0, 5_000.0, 7_500.0, 10_000.0]),
["0", "2.5K", "5K", "7.5K", "10K"]
);
assert_eq!(labels(&[-20_000.0, 0.0, 20_000.0]), ["-20K", "0", "20K"]);
assert_eq!(labels(&[0.0, 0.25, 0.5]), ["0", "0.25", "0.5"]);
assert_eq!(
labels(&[1_000_000.0, 1_250_000.0, 1_500_000.0]),
["1M", "1.25M", "1.5M"]
);
assert_eq!(labels(&[0.0, 1e20]), ["0", "100,000,000T"]);
assert_eq!(labels(&[0.0, 1e-7, 2e-7]), ["0", "0.0000001", "0.0000002"]);
assert_eq!(labels(&[0.1 + 0.2, 0.6]), ["0.3", "0.6"]);
assert_eq!(
TickFormatter::new(&[f64::NAN, 1_000.0], None).format(1_000.0),
"1,000"
);
assert_eq!(labels(&[]), Vec::<String>::new());
}
#[test]
fn category_labels_are_centred_and_culled_only_on_collision() {
let labels = [
"Opening",
"New sales",
"Expansion",
"Refunds",
"Operating",
"Fees",
"Closing",
];
let band = 528.0 / 7.0;
let positions: Vec<f64> = labels
.iter()
.zip(0_u32..)
.map(|(_, index)| 88.0 + band * (f64::from(index) + 0.5))
.collect();
let ticks = category_ticks(
&labels,
CategoryTickOptions::new(88.0, 616.0)
.bounds(0.0, 640.0)
.positions(&positions),
);
assert_eq!(
ticks
.iter()
.map(|tick| tick.label.as_str())
.collect::<Vec<_>>(),
labels
);
assert_eq!(
ticks.iter().map(|tick| tick.position).collect::<Vec<_>>(),
positions
);
let boundaries: Vec<String> = (0..=10).map(|index| (index * 100).to_string()).collect();
let ticks = category_ticks(
&boundaries,
CategoryTickOptions::new(88.0, 616.0).bounds(0.0, 640.0),
);
assert_eq!(ticks.len(), boundaries.len());
}
#[test]
fn category_labels_move_inward_only_as_far_as_the_bounds_require() {
let ticks = category_ticks(
&["Mon", "September 30"],
CategoryTickOptions::new(8.0, 632.0).bounds(0.0, 640.0),
);
assert!((ticks[0].position - estimate_label_width("Mon") / 2.0).abs() < 1e-12);
assert!(
(ticks[1].position - (640.0 - estimate_label_width("September 30") / 2.0)).abs()
< 1e-12
);
let invalid = category_ticks(
&["Mon"],
CategoryTickOptions::new(0.0, 100.0).bounds(0.0, f64::NAN),
);
assert_eq!(invalid.len(), 1);
assert!((invalid[0].position - 50.0).abs() < 1e-12);
}
#[test]
fn category_labels_thin_to_an_even_stride_and_keep_the_last_one() {
let labels: Vec<String> = (1..=60).map(|day| format!("D{day:02}")).collect();
let indexes: Vec<usize> = category_ticks(&labels, CategoryTickOptions::new(0.0, 600.0))
.iter()
.map(|tick| tick.index)
.collect();
assert_eq!(indexes.first(), Some(&0));
assert_eq!(indexes.last(), Some(&59));
assert!(
indexes[..indexes.len() - 1]
.windows(2)
.all(|pair| pair[1] - pair[0] == 3)
);
let long: Vec<String> = (0..100_000).map(|index| format!("Label {index}")).collect();
let ticks = category_ticks(&long, CategoryTickOptions::new(0.0, 1_000.0));
assert_eq!(ticks.first().map(|tick| tick.index), Some(0));
assert!(ticks.len() > 1 && ticks.len() < 40);
}
#[test]
fn label_widths_and_padding_follow_lumen_core() {
assert!((estimate_label_width("Jan") - 21.0).abs() < 1e-12);
assert!((estimate_label_width("WWW") - 30.0).abs() < 1e-12);
assert!((estimate_label_width("ill") - 21.0).abs() < 1e-12);
assert!((estimate_label_width("😀") - 14.0).abs() < 1e-12);
assert!((estimate_chart_label_width("September 30", 22.0) - 168.0).abs() < 1e-12);
assert!((estimate_chart_label_width("Jan", f64::NAN) - 21.0).abs() < 1e-12);
assert!((axis_padding(&["100"], 52.0, None) - 52.0).abs() < 1e-12);
assert!((axis_padding(&["$1,000,000.00"], 44.0, None) - 107.0).abs() < 1e-12);
assert!((axis_padding(&["$ 0", "$ 3.000.000"], 0.0, Some(22.0)) - 170.0).abs() < 1e-12);
for font_size in [f64::NAN, f64::INFINITY, 0.0, -22.0] {
assert!(
(axis_padding(&["$ 0", "$ 3.000.000"], 0.0, Some(font_size)) - 93.0).abs() < 1e-12
);
}
let long = "x".repeat(100_000);
assert!((axis_padding(&[long.as_str()], 0.0, Some(22.0)) - 240.0).abs() < 1e-12);
assert!((axis_padding(&[long.as_str()], 44.0, None) - 240.0).abs() < 1e-12);
}
#[test]
fn category_ticks_skip_crowded_labels_and_truncate() {
let labels = ["January", "February", "March", "April", "May", "June"];
let ticks = category_ticks(&labels, CategoryTickOptions::new(0.0, 200.0));
assert_eq!(ticks.first().map(|tick| tick.index), Some(0));
assert!(ticks.len() < labels.len());
let single = category_ticks(&["Only"], CategoryTickOptions::new(0.0, 100.0));
assert!((single[0].position - 50.0).abs() < 1e-12);
assert_eq!(fitted_label("A very long category label", 40.0), "A ve…");
assert_eq!(
category_ticks(&["a"], CategoryTickOptions::new(10.0, 0.0)),
[]
);
let empty: [&str; 0] = [];
assert_eq!(
category_ticks(&empty, CategoryTickOptions::new(0.0, 10.0)),
[]
);
let long = "y".repeat(50_000);
assert!(fitted_label(&long, 100.0).chars().count() < 20);
}
}