Skip to main content

lichtung_plot/numeric/
unit.rs

1//! Units and the one authored-or-generated common explanation slot.
2
3use std::sync::Arc;
4
5use super::decimal::{NumericNotation, ResolvedFormat, ResolvedPrecision, TrailingZeros};
6use super::emission::append;
7use super::format::NumericFormat;
8use super::locale::validate_token;
9use super::prefixes::{selection::SelectedScale, NumericFactor};
10use crate::{Error, Result, Text, TextLayout, TextTheme};
11
12/// Whether unit/factor text repeats or occupies one required owner slot.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum NumericUnitPlacement {
15    /// Repeat the unit with each numeric label.
16    PerLabel,
17    /// Retain a common factor/unit explanation, without repeating it on labels.
18    Shared,
19}
20
21/// Literal scientific unit text; it never infers conversion from its spelling.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct NumericUnit {
24    text: String,
25    separator: String,
26    placement: NumericUnitPlacement,
27}
28
29impl NumericUnit {
30    /// Construct a unit, with one ordinary space as its default separator.
31    /// Content is validated when attached to a NumericFormat.
32    pub fn new(text: impl Into<String>, placement: NumericUnitPlacement) -> Self {
33        Self {
34            text: text.into(),
35            separator: " ".into(),
36            placement,
37        }
38    }
39    /// Replace the literal separator; an empty separator is valid.
40    #[must_use]
41    pub fn separator(mut self, value: impl Into<String>) -> Self {
42        self.separator = value.into();
43        self
44    }
45    /// Literal unit, which may be empty for factor-only explanations.
46    pub fn text(&self) -> &str {
47        &self.text
48    }
49    /// Literal separator.
50    pub fn get_separator(&self) -> &str {
51        &self.separator
52    }
53    /// Repeated or common placement.
54    pub const fn placement(&self) -> NumericUnitPlacement {
55        self.placement
56    }
57    pub(super) fn validate(&self) -> Result<()> {
58        validate_token(&self.text, true)?;
59        validate_token(&self.separator, true)
60    }
61    pub(super) fn try_copy(&self) -> Result<Self> {
62        Ok(Self {
63            text: crate::data::source::copy_source_string(&self.text)?,
64            separator: crate::data::source::copy_source_string(&self.separator)?,
65            placement: self.placement,
66        })
67    }
68}
69
70/// Instructions for one common explanation, retaining normal Text replacement.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct NumericExplanation(Arc<Text>);
73
74impl NumericExplanation {
75    pub(super) fn replace_callback(&self, current: Option<Text>, incoming: Text) -> Result<Text> {
76        let mut slot = self.0.try_copy()?;
77        if let Some(current) = current {
78            slot.replace_from(current)?;
79        }
80        slot.replace_from(incoming)?;
81        slot.resolve_source(String::new())
82    }
83    /// Generate content from the selected factor and shared unit.
84    pub fn automatic() -> Self {
85        Self(Arc::new(Text::UNSET))
86    }
87    /// Replace generated content with authored Text in the same slot.
88    pub fn text(value: impl Into<Text>) -> Self {
89        let mut slot = Text::UNSET;
90        slot.replace_from(value.into())
91            .expect("public Text always has a source");
92        Self(Arc::new(slot))
93    }
94    /// Select the complete local appearance, without changing content.
95    #[must_use]
96    pub fn style(mut self, value: TextTheme) -> Self {
97        Arc::make_mut(&mut self.0).edit_style(value);
98        self
99    }
100    /// Select the local layout, without changing content.
101    #[must_use]
102    pub fn layout(mut self, value: TextLayout) -> Self {
103        Arc::make_mut(&mut self.0).edit_layout(value);
104        self
105    }
106    /// Remove the local appearance while preserving authored/generated content and layout.
107    #[must_use]
108    pub fn clear_style(mut self) -> Self {
109        Arc::make_mut(&mut self.0).edit_clear_style();
110        self
111    }
112    /// Remove the local layout request while preserving content and appearance.
113    #[must_use]
114    pub fn clear_layout(mut self) -> Self {
115        Arc::make_mut(&mut self.0).edit_clear_layout();
116        self
117    }
118    fn resolve(&self, generated: String) -> Result<Option<Text>> {
119        let text = self.0.resolve_source(generated)?;
120        if !self.0.is_provided() && text.as_str().is_empty() {
121            return Ok(None);
122        }
123        text.required_source("numeric explanation")?;
124        Ok(Some(text))
125    }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub(super) struct UnitPolicy {
130    pub(super) unit: Option<NumericUnit>,
131    pub(super) explanation: NumericExplanation,
132}
133
134impl Default for UnitPolicy {
135    fn default() -> Self {
136        Self {
137            unit: None,
138            explanation: NumericExplanation::automatic(),
139        }
140    }
141}
142
143impl NumericFormat {
144    pub(super) fn numeric_explanation(&self, scales: &[SelectedScale]) -> Result<Option<Text>> {
145        let generated = if let Some(unit) = self
146            .units
147            .unit
148            .as_ref()
149            .filter(|unit| unit.placement == NumericUnitPlacement::Shared)
150        {
151            if scales.windows(2).any(|pair| pair[0] != pair[1]) {
152                return Err(Error::Data(
153                    "shared numeric unit requires one common factor and affix selection".into(),
154                ));
155            }
156            scales
157                .first()
158                .map_or_else(|| Ok(String::new()), |scale| common_text(scale, unit))?
159        } else {
160            String::new()
161        };
162        self.units.explanation.resolve(generated)
163    }
164    /// Set or clear literal unit text, validating its single-line tokens.
165    pub fn unit(mut self, value: Option<NumericUnit>) -> Result<Self> {
166        if let Some(unit) = &value {
167            unit.validate()?;
168        }
169        Arc::make_mut(&mut self.units).unit = value;
170        self.validate()?;
171        Ok(self)
172    }
173    /// Replace instructions/content for the one common explanation slot.
174    #[must_use]
175    pub fn explanation(mut self, value: NumericExplanation) -> Self {
176        Arc::make_mut(&mut self.units).explanation = value;
177        self
178    }
179
180    pub(super) fn decorate_scales(
181        &self,
182        scales: &[SelectedScale],
183    ) -> Result<(Vec<SelectedScale>, Option<Text>)> {
184        let Some(unit) = &self.units.unit else {
185            return Ok((
186                crate::data::source::collect_source(scales.iter().map(SelectedScale::try_copy))?,
187                self.units.explanation.resolve(String::new())?,
188            ));
189        };
190        if unit.placement == NumericUnitPlacement::Shared {
191            if scales.windows(2).any(|pair| pair[0] != pair[1]) {
192                return Err(Error::Data(
193                    "shared numeric unit requires one common factor and affix selection".into(),
194                ));
195            }
196            let generated = scales
197                .first()
198                .map_or_else(|| Ok(String::new()), |scale| common_text(scale, unit))?;
199            let bare = crate::data::source::collect_source(scales.iter().map(|scale| {
200                Ok(SelectedScale {
201                    divisor: scale.divisor.try_copy()?,
202                    prefix: String::new(),
203                    suffix: String::new(),
204                    si: scale.si,
205                })
206            }))?;
207            return Ok((bare, self.units.explanation.resolve(generated)?));
208        }
209        let decorated = crate::data::source::collect_source(scales.iter().map(|scale| {
210            let mut selected = scale.try_copy()?;
211            if let Some(si) = scale.si {
212                selected.suffix.clear();
213                if !unit.text.is_empty() {
214                    append(&mut selected.suffix, &unit.separator)?;
215                }
216                append(&mut selected.suffix, si.symbol())?;
217                append(&mut selected.suffix, &unit.text)?;
218            } else if !unit.text.is_empty() {
219                append(&mut selected.suffix, &unit.separator)?;
220                append(&mut selected.suffix, &unit.text)?;
221            }
222            Ok(selected)
223        }))?;
224        Ok((decorated, self.units.explanation.resolve(String::new())?))
225    }
226}
227
228fn common_text(scale: &SelectedScale, unit: &NumericUnit) -> Result<String> {
229    let mut text = String::new();
230    if let Some(si) = scale.si {
231        if !unit.text.is_empty() {
232            append(&mut text, si.symbol())?;
233            append(&mut text, &unit.text)?;
234            return Ok(text);
235        }
236    }
237    if !scale.prefix.is_empty() || (!scale.suffix.is_empty() && scale.si.is_none()) {
238        append(&mut text, &scale.prefix)?;
239        append(&mut text, &scale.suffix)?;
240    } else {
241        match &scale.divisor {
242            NumericFactor::PowerOfTen(exponent) if exponent != "0" => {
243                append(&mut text, "×10")?;
244                for scalar in exponent.chars() {
245                    append(
246                        &mut text,
247                        match scalar {
248                            '-' => "⁻",
249                            '0' => "⁰",
250                            '1' => "¹",
251                            '2' => "²",
252                            '3' => "³",
253                            '4' => "⁴",
254                            '5' => "⁵",
255                            '6' => "⁶",
256                            '7' => "⁷",
257                            '8' => "⁸",
258                            '9' => "⁹",
259                            _ => unreachable!("normalized factor exponent"),
260                        },
261                    )?;
262                }
263            }
264            NumericFactor::Value(value) if value.to_bits() != 1.0_f64.to_bits() => {
265                append(&mut text, "×")?;
266                let factor = super::decimal::format_finite(
267                    *value,
268                    &ResolvedFormat {
269                        notation: NumericNotation::General,
270                        precision: ResolvedPrecision::Significant(17),
271                        trailing_zeros: TrailingZeros::Trim,
272                        ..ResolvedFormat::default()
273                    },
274                )?;
275                append(&mut text, &factor)?;
276            }
277            _ => (),
278        }
279    }
280    if !unit.text.is_empty() {
281        if !text.is_empty() {
282            append(&mut text, &unit.separator)?;
283        }
284        append(&mut text, &unit.text)?;
285    }
286    Ok(text)
287}
288
289impl UnitPolicy {
290    pub(super) fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
291        round.observe_count(usize::from(self.unit.is_some()))?;
292        if let Some(unit) = &self.unit {
293            round.observe_string(&unit.text)?;
294            round.observe_string(&unit.separator)?;
295            round.observe_count(unit.placement as usize)?;
296        }
297        self.explanation.0.observe_feedback(round)
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use crate::{NumericPrecision, NumericPrefixes, NumericPromotion, NumericSelection, SiPrefix};
305
306    #[test]
307    fn shared_factors_retain_occurrences_units_and_one_deterministic_explanation() {
308        let millions =
309            NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(0))
310                .unwrap()
311                .prefixes(NumericPrefixes::factor(NumericFactor::PowerOfTen("6".into())).unwrap())
312                .unwrap()
313                .unit(Some(NumericUnit::new("", NumericUnitPlacement::Shared)))
314                .unwrap();
315        let set = millions
316            .format_set(&[1e6, 2e6, 3e6, 1e6], false, true)
317            .unwrap()
318            .unwrap();
319        assert_eq!(set.labels, ["1", "2", "3", "1"]);
320        assert_eq!(set.explanation.unwrap().as_str(), "×10⁶");
321        assert_eq!(set.scales.len(), set.members.len());
322        let whole = NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(1))
323            .unwrap()
324            .prefixes(
325                NumericPrefixes::si(NumericSelection::WholeSet, NumericPromotion::KeepThreshold)
326                    .unwrap(),
327            )
328            .unwrap()
329            .unit(Some(NumericUnit::new("m", NumericUnitPlacement::Shared)))
330            .unwrap();
331        let set = whole
332            .format_set(&[1250.0, 2500.0], false, true)
333            .unwrap()
334            .unwrap();
335        assert_eq!(set.labels, ["1.2", "2.5"]);
336        assert_eq!(set.explanation.unwrap().as_str(), "km");
337        let repeated = whole
338            .unit(Some(
339                NumericUnit::new("m", NumericUnitPlacement::PerLabel).separator("\u{202f}"),
340            ))
341            .unwrap();
342        assert_eq!(
343            repeated.format_singleton(1250.0, false).unwrap(),
344            "1.2\u{202f}km"
345        );
346        let mixed = repeated
347            .prefixes(
348                NumericPrefixes::si(NumericSelection::PerValue, NumericPromotion::KeepThreshold)
349                    .unwrap(),
350            )
351            .unwrap()
352            .unit(Some(NumericUnit::new("m", NumericUnitPlacement::Shared)))
353            .unwrap();
354        assert!(mixed.format_set(&[1.0, 1000.0], false, false).is_err());
355        let tiny = millions
356            .prefixes(
357                NumericPrefixes::si(
358                    NumericSelection::Fixed(SiPrefix::from_exponent(-6).unwrap()),
359                    NumericPromotion::KeepThreshold,
360                )
361                .unwrap(),
362            )
363            .unwrap();
364        assert_eq!(
365            tiny.format_set(&[0.0], false, true)
366                .unwrap()
367                .unwrap()
368                .explanation
369                .unwrap()
370                .as_str(),
371            "×10⁻⁶"
372        );
373    }
374}