use super::write::{Svg, TextStyle, text_width};
use super::{BASELINE_RATIO, INK, INK_SECONDARY, SMALL};
use crate::chart::{Rgb, Series};
use crate::excel::numfmt::{self, NumFmt};
pub(super) const LABEL_SIZE_PT: f32 = 8.0;
pub(super) const MAX_DATA_LABELS: usize = 600;
pub(super) const LABEL_OFFSET_PT: f32 = 3.0;
const DARK_LUMINANCE: f32 = 0.18;
const INK_ON_DARK: &str = "#ffffff";
const PERCENT_FORMAT: &str = "0%";
const SEPARATOR: &str = ", ";
pub(super) struct Label {
pub(super) at: (f32, f32),
pub(super) text: String,
pub(super) ink: &'static str,
}
pub(super) struct Labels {
labels: Vec<Label>,
}
impl Labels {
pub(super) fn new() -> Self {
Self { labels: Vec::new() }
}
pub(super) fn room(&self) -> bool {
self.labels.len() < MAX_DATA_LABELS
}
pub(super) fn add(&mut self, center: (f32, f32), text: String, ink: &'static str) {
if self.room() {
self.labels.push(Label {
at: (center.0, center.1 + LABEL_SIZE_PT * BASELINE_RATIO),
text,
ink,
});
}
}
pub(super) fn write(self, out: &mut Svg) {
for label in self.labels {
let style = TextStyle {
size: LABEL_SIZE_PT,
fill: label.ink,
..SMALL
};
out.text("data-label", label.at, style, &label.text);
}
}
}
pub(super) fn text(series: &Series, index: usize, value: f64, share: Option<f64>, date1904: bool) -> Option<String> {
let (show_value, show_percent) = series.labels.shown(index);
let mut parts = Vec::new();
if show_value && value.is_finite() {
let format = series
.labels
.format
.as_ref()
.or_else(|| series.values.as_ref().map(|values| &values.format))
.unwrap_or(&NumFmt::General);
parts.push(numfmt::format(value, format, date1904));
}
if show_percent && let Some(share) = share.filter(|share| share.is_finite()) {
parts.push(numfmt::format(share, &NumFmt::Code(PERCENT_FORMAT.into()), date1904));
}
let text = parts.join(SEPARATOR);
(!text.trim().is_empty()).then_some(text)
}
pub(super) fn size(text: &str) -> (f32, f32) {
(text_width(text, LABEL_SIZE_PT), LABEL_SIZE_PT)
}
pub(super) fn ink_on(color: Rgb) -> &'static str {
let channel = |value: u8| {
let value = f32::from(value) / 255.0;
if value <= 0.04045 {
value / 12.92
} else {
((value + 0.055) / 1.055).powf(2.4)
}
};
let luminance = 0.2126 * channel(color[0]) + 0.7152 * channel(color[1]) + 0.0722 * channel(color[2]);
if luminance < DARK_LUMINANCE { INK_ON_DARK } else { INK }
}
pub(super) const INK_OUTSIDE: &str = INK_SECONDARY;