1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum NumericUnitPlacement {
15 PerLabel,
17 Shared,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct NumericUnit {
24 text: String,
25 separator: String,
26 placement: NumericUnitPlacement,
27}
28
29impl NumericUnit {
30 pub fn new(text: impl Into<String>, placement: NumericUnitPlacement) -> Self {
33 Self {
34 text: text.into(),
35 separator: " ".into(),
36 placement,
37 }
38 }
39 #[must_use]
41 pub fn separator(mut self, value: impl Into<String>) -> Self {
42 self.separator = value.into();
43 self
44 }
45 pub fn text(&self) -> &str {
47 &self.text
48 }
49 pub fn get_separator(&self) -> &str {
51 &self.separator
52 }
53 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#[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 pub fn automatic() -> Self {
85 Self(Arc::new(Text::UNSET))
86 }
87 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 #[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 #[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 #[must_use]
108 pub fn clear_style(mut self) -> Self {
109 Arc::make_mut(&mut self.0).edit_clear_style();
110 self
111 }
112 #[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 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 #[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::formatting::{
305 NumericPrecision, NumericPrefixes, NumericPromotion, NumericSelection, SiPrefix,
306 };
307
308 #[test]
309 fn shared_factors_retain_occurrences_units_and_one_deterministic_explanation() {
310 let millions =
311 NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(0))
312 .unwrap()
313 .prefixes(NumericPrefixes::factor(NumericFactor::PowerOfTen("6".into())).unwrap())
314 .unwrap()
315 .unit(Some(NumericUnit::new("", NumericUnitPlacement::Shared)))
316 .unwrap();
317 let set = millions
318 .format_set(&[1e6, 2e6, 3e6, 1e6], false, true)
319 .unwrap()
320 .unwrap();
321 assert_eq!(set.labels, ["1", "2", "3", "1"]);
322 assert_eq!(set.explanation.unwrap().as_str(), "×10⁶");
323 assert_eq!(set.scales.len(), set.members.len());
324 let whole = NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(1))
325 .unwrap()
326 .prefixes(
327 NumericPrefixes::si(NumericSelection::WholeSet, NumericPromotion::KeepThreshold)
328 .unwrap(),
329 )
330 .unwrap()
331 .unit(Some(NumericUnit::new("m", NumericUnitPlacement::Shared)))
332 .unwrap();
333 let set = whole
334 .format_set(&[1250.0, 2500.0], false, true)
335 .unwrap()
336 .unwrap();
337 assert_eq!(set.labels, ["1.2", "2.5"]);
338 assert_eq!(set.explanation.unwrap().as_str(), "km");
339 let repeated = whole
340 .unit(Some(
341 NumericUnit::new("m", NumericUnitPlacement::PerLabel).separator("\u{202f}"),
342 ))
343 .unwrap();
344 assert_eq!(
345 repeated.format_singleton(1250.0, false).unwrap(),
346 "1.2\u{202f}km"
347 );
348 let mixed = repeated
349 .prefixes(
350 NumericPrefixes::si(NumericSelection::PerValue, NumericPromotion::KeepThreshold)
351 .unwrap(),
352 )
353 .unwrap()
354 .unit(Some(NumericUnit::new("m", NumericUnitPlacement::Shared)))
355 .unwrap();
356 assert!(mixed.format_set(&[1.0, 1000.0], false, false).is_err());
357 let tiny = millions
358 .prefixes(
359 NumericPrefixes::si(
360 NumericSelection::Fixed(SiPrefix::from_exponent(-6).unwrap()),
361 NumericPromotion::KeepThreshold,
362 )
363 .unwrap(),
364 )
365 .unwrap();
366 assert_eq!(
367 tiny.format_set(&[0.0], false, true)
368 .unwrap()
369 .unwrap()
370 .explanation
371 .unwrap()
372 .as_str(),
373 "×10⁻⁶"
374 );
375 }
376}