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::{text::TextLayout, theme::TextTheme, Error, Result, Text};
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(crate) fn appearance_only(&self) -> Self {
76        Self(Arc::new(self.0.appearance_only()))
77    }
78
79    pub(crate) fn has_authored_content(&self) -> bool {
80        self.0.is_provided()
81    }
82
83    pub(crate) fn apply_appearance(&mut self, source: &Self) {
84        Arc::make_mut(&mut self.0).apply_appearance(source.0.as_ref().clone());
85    }
86
87    pub(super) fn replace_callback(&self, current: Option<Text>, incoming: Text) -> Result<Text> {
88        let mut slot = self.0.try_copy()?;
89        if let Some(current) = current {
90            slot.replace_from(current)?;
91        }
92        slot.replace_from(incoming)?;
93        slot.resolve_source(String::new())
94    }
95    /// Generate content from the selected factor and shared unit.
96    pub fn automatic() -> Self {
97        Self(Arc::new(Text::UNSET))
98    }
99    /// Replace generated content with authored Text in the same slot.
100    pub fn text(value: impl Into<Text>) -> Self {
101        let mut slot = Text::UNSET;
102        slot.replace_from(value.into())
103            .expect("public Text always has a source");
104        Self(Arc::new(slot))
105    }
106    /// Select the complete local appearance, without changing content.
107    #[must_use]
108    pub fn style(mut self, value: TextTheme) -> Self {
109        Arc::make_mut(&mut self.0).edit_style(value);
110        self
111    }
112    /// Select the local layout, without changing content.
113    #[must_use]
114    pub fn layout(mut self, value: TextLayout) -> Self {
115        Arc::make_mut(&mut self.0).edit_layout(value);
116        self
117    }
118    /// Remove the local appearance while preserving authored/generated content and layout.
119    #[must_use]
120    pub fn clear_style(mut self) -> Self {
121        Arc::make_mut(&mut self.0).edit_clear_style();
122        self
123    }
124    /// Remove the local layout request while preserving content and appearance.
125    #[must_use]
126    pub fn clear_layout(mut self) -> Self {
127        Arc::make_mut(&mut self.0).edit_clear_layout();
128        self
129    }
130    fn resolve(&self, generated: String) -> Result<Option<Text>> {
131        let text = self.0.resolve_source(generated)?;
132        if !self.0.is_provided() && text.as_str().is_empty() {
133            return Ok(None);
134        }
135        text.required_source("numeric explanation")?;
136        Ok(Some(text))
137    }
138}
139
140impl crate::recipe::codec::Codec for NumericExplanation {
141    fn schema(ctx: &mut crate::recipe::schema::Schema) -> serde_json::Value {
142        ctx.reference::<Text>()
143    }
144    fn encode(&self) -> toml_edit::Value {
145        self.0.encode()
146    }
147    fn decode(item: &toml_edit::Item, _: Option<Self>) -> Result<Self> {
148        Text::decode(item, None).map(|value| Self(Arc::new(value)))
149    }
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub(super) struct UnitPolicy {
154    pub(super) unit: Option<NumericUnit>,
155    pub(super) explanation: NumericExplanation,
156}
157
158impl Default for UnitPolicy {
159    fn default() -> Self {
160        Self {
161            unit: None,
162            explanation: NumericExplanation::automatic(),
163        }
164    }
165}
166
167impl NumericFormat {
168    pub(super) fn numeric_explanation(&self, scales: &[SelectedScale]) -> Result<Option<Text>> {
169        let generated = if let Some(unit) = self
170            .units
171            .unit
172            .as_ref()
173            .filter(|unit| unit.placement == NumericUnitPlacement::Shared)
174        {
175            if scales.windows(2).any(|pair| pair[0] != pair[1]) {
176                return Err(Error::Data(
177                    "shared numeric unit requires one common factor and affix selection".into(),
178                ));
179            }
180            scales
181                .first()
182                .map_or_else(|| Ok(String::new()), |scale| common_text(scale, unit))?
183        } else {
184            String::new()
185        };
186        self.units.explanation.resolve(generated)
187    }
188    /// Set or clear literal unit text, validating its single-line tokens.
189    pub fn unit(mut self, value: Option<NumericUnit>) -> Result<Self> {
190        if let Some(unit) = &value {
191            unit.validate()?;
192        }
193        Arc::make_mut(&mut self.units).unit = value;
194        self.validate()?;
195        Ok(self)
196    }
197    /// Replace instructions/content for the one common explanation slot.
198    #[must_use]
199    pub fn explanation(mut self, value: NumericExplanation) -> Self {
200        Arc::make_mut(&mut self.units).explanation = value;
201        self
202    }
203
204    pub(super) fn decorate_scales(
205        &self,
206        scales: &[SelectedScale],
207    ) -> Result<(Vec<SelectedScale>, Option<Text>)> {
208        let Some(unit) = &self.units.unit else {
209            return Ok((
210                crate::data::source::collect_source(scales.iter().map(SelectedScale::try_copy))?,
211                self.units.explanation.resolve(String::new())?,
212            ));
213        };
214        if unit.placement == NumericUnitPlacement::Shared {
215            if scales.windows(2).any(|pair| pair[0] != pair[1]) {
216                return Err(Error::Data(
217                    "shared numeric unit requires one common factor and affix selection".into(),
218                ));
219            }
220            let generated = scales
221                .first()
222                .map_or_else(|| Ok(String::new()), |scale| common_text(scale, unit))?;
223            let bare = crate::data::source::collect_source(scales.iter().map(|scale| {
224                Ok(SelectedScale {
225                    divisor: scale.divisor.try_copy()?,
226                    prefix: String::new(),
227                    suffix: String::new(),
228                    si: scale.si,
229                })
230            }))?;
231            return Ok((bare, self.units.explanation.resolve(generated)?));
232        }
233        let decorated = crate::data::source::collect_source(scales.iter().map(|scale| {
234            let mut selected = scale.try_copy()?;
235            if let Some(si) = scale.si {
236                selected.suffix.clear();
237                if !unit.text.is_empty() {
238                    append(&mut selected.suffix, &unit.separator)?;
239                }
240                append(&mut selected.suffix, si.symbol())?;
241                append(&mut selected.suffix, &unit.text)?;
242            } else if !unit.text.is_empty() {
243                append(&mut selected.suffix, &unit.separator)?;
244                append(&mut selected.suffix, &unit.text)?;
245            }
246            Ok(selected)
247        }))?;
248        Ok((decorated, self.units.explanation.resolve(String::new())?))
249    }
250}
251
252fn common_text(scale: &SelectedScale, unit: &NumericUnit) -> Result<String> {
253    let mut text = String::new();
254    if let Some(si) = scale.si {
255        if !unit.text.is_empty() {
256            append(&mut text, si.symbol())?;
257            append(&mut text, &unit.text)?;
258            return Ok(text);
259        }
260    }
261    if !scale.prefix.is_empty() || (!scale.suffix.is_empty() && scale.si.is_none()) {
262        append(&mut text, &scale.prefix)?;
263        append(&mut text, &scale.suffix)?;
264    } else {
265        match &scale.divisor {
266            NumericFactor::PowerOfTen(exponent) if exponent != "0" => {
267                append(&mut text, "×10")?;
268                for scalar in exponent.chars() {
269                    append(
270                        &mut text,
271                        match scalar {
272                            '-' => "⁻",
273                            '0' => "⁰",
274                            '1' => "¹",
275                            '2' => "²",
276                            '3' => "³",
277                            '4' => "⁴",
278                            '5' => "⁵",
279                            '6' => "⁶",
280                            '7' => "⁷",
281                            '8' => "⁸",
282                            '9' => "⁹",
283                            _ => unreachable!("normalized factor exponent"),
284                        },
285                    )?;
286                }
287            }
288            NumericFactor::Value(value) if value.to_bits() != 1.0_f64.to_bits() => {
289                append(&mut text, "×")?;
290                let factor = super::decimal::format_finite(
291                    *value,
292                    &ResolvedFormat {
293                        notation: NumericNotation::General,
294                        precision: ResolvedPrecision::Significant(17),
295                        trailing_zeros: TrailingZeros::Trim,
296                        ..ResolvedFormat::default()
297                    },
298                )?;
299                append(&mut text, &factor)?;
300            }
301            _ => (),
302        }
303    }
304    if !unit.text.is_empty() {
305        if !text.is_empty() {
306            append(&mut text, &unit.separator)?;
307        }
308        append(&mut text, &unit.text)?;
309    }
310    Ok(text)
311}
312
313impl UnitPolicy {
314    pub(super) fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
315        round.observe_count(usize::from(self.unit.is_some()))?;
316        if let Some(unit) = &self.unit {
317            round.observe_string(&unit.text)?;
318            round.observe_string(&unit.separator)?;
319            round.observe_count(unit.placement as usize)?;
320        }
321        self.explanation.0.observe_feedback(round)
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use crate::formatting::{
329        NumericPrecision, NumericPrefixes, NumericPromotion, NumericSelection, SiPrefix,
330    };
331
332    #[test]
333    fn shared_factors_retain_occurrences_units_and_one_deterministic_explanation() {
334        let millions =
335            NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(0))
336                .unwrap()
337                .prefixes(NumericPrefixes::factor(NumericFactor::PowerOfTen("6".into())).unwrap())
338                .unwrap()
339                .unit(Some(NumericUnit::new("", NumericUnitPlacement::Shared)))
340                .unwrap();
341        let set = millions
342            .format_set(&[1e6, 2e6, 3e6, 1e6], false, true)
343            .unwrap()
344            .unwrap();
345        assert_eq!(set.labels, ["1", "2", "3", "1"]);
346        assert_eq!(set.explanation.unwrap().as_str(), "×10⁶");
347        assert_eq!(set.scales.len(), set.members.len());
348        let whole = NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(1))
349            .unwrap()
350            .prefixes(
351                NumericPrefixes::si(NumericSelection::WholeSet, NumericPromotion::KeepThreshold)
352                    .unwrap(),
353            )
354            .unwrap()
355            .unit(Some(NumericUnit::new("m", NumericUnitPlacement::Shared)))
356            .unwrap();
357        let set = whole
358            .format_set(&[1250.0, 2500.0], false, true)
359            .unwrap()
360            .unwrap();
361        assert_eq!(set.labels, ["1.2", "2.5"]);
362        assert_eq!(set.explanation.unwrap().as_str(), "km");
363        let repeated = whole
364            .unit(Some(
365                NumericUnit::new("m", NumericUnitPlacement::PerLabel).separator("\u{202f}"),
366            ))
367            .unwrap();
368        assert_eq!(
369            repeated.format_singleton(1250.0, false).unwrap(),
370            "1.2\u{202f}km"
371        );
372        let mixed = repeated
373            .prefixes(
374                NumericPrefixes::si(NumericSelection::PerValue, NumericPromotion::KeepThreshold)
375                    .unwrap(),
376            )
377            .unwrap()
378            .unit(Some(NumericUnit::new("m", NumericUnitPlacement::Shared)))
379            .unwrap();
380        assert!(mixed.format_set(&[1.0, 1000.0], false, false).is_err());
381        let tiny = millions
382            .prefixes(
383                NumericPrefixes::si(
384                    NumericSelection::Fixed(SiPrefix::from_exponent(-6).unwrap()),
385                    NumericPromotion::KeepThreshold,
386                )
387                .unwrap(),
388            )
389            .unwrap();
390        assert_eq!(
391            tiny.format_set(&[0.0], false, true)
392                .unwrap()
393                .unwrap()
394                .explanation
395                .unwrap()
396                .as_str(),
397            "×10⁻⁶"
398        );
399    }
400}