figgy-model 0.10.0

figgy chart model — option SSoT, interaction contracts, preset policies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Editable decoration positions for bounded charts. The same `HitMap`,
//! `Selectable`, `Draggable` and `SelectionBox` policy as Cartesian charts applies.
use crate::{
    drag::{DragConfig, Draggable},
    layout::{NudgeReject, NudgeResult, RectF, Side},
    select::Selectable,
    text::MeasureText,
};

/// Stable identity within a chart. Category/series IDs survive reordering;
/// radial indices refer to the original arrays, including zero-valued slices.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DecorationId {
    /// The plot layout region; registered behind labels and axes.
    DataArea,
    /// Mutation target used by the common resize policy, not a separate hit.
    DataAreaEdge(Side),
    ChartTitle,
    Axis(Side),
    AxisLabel(Side),
    AxisTitle(Side),
    Legend,
    RadialLabel(crate::radial::RadialTarget),
    DataLabel {
        category_id: String,
        series_id: String,
    },
}
impl DecorationId {
    pub fn element_id(&self) -> String {
        let side = |s: &Side| match s {
            Side::Top => "top",
            Side::Bottom => "bottom",
            Side::Left => "left",
            Side::Right => "right",
        };
        match self {
            Self::DataArea => "data_area".into(),
            Self::DataAreaEdge(s) => format!("data_area_edge_{}", side(s)),
            Self::ChartTitle => "chart_title".into(),
            Self::Axis(s) => format!("axis_{}", side(s)),
            Self::AxisLabel(s) => format!("tick_labels_{}", side(s)),
            Self::AxisTitle(s) => format!("axis_title_{}", side(s)),
            Self::Legend => "legend".into(),
            Self::RadialLabel(t) => format!("radial_label_{}_{}", t.group, t.index),
            Self::DataLabel {
                category_id,
                series_id,
            } => format!(
                "data_label_{}:{}{}:{}",
                category_id.len(),
                category_id,
                series_id.len(),
                series_id
            ),
        }
    }
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DecorationOffset {
    pub element: DecorationId,
    /// Chart-local logical pixels, independent of DPR/export scale.
    pub offset: [f32; 2],
}
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(default)
)]
pub struct DecorationLayout {
    /// Explicit plot region in logical pixels. None uses the measured automatic
    /// region; a chosen region must fit inside it to retain space for labels.
    pub data_area: Option<RectF>,
    pub offsets: Vec<DecorationOffset>,
    /// Decoration selection is separate from data selection and hover.
    pub selected: Option<DecorationId>,
}
impl DecorationLayout {
    pub fn offset(&self, id: &DecorationId) -> [f32; 2] {
        self.offsets
            .iter()
            .find(|o| &o.element == id)
            .map_or([0.; 2], |o| o.offset)
    }
    /// Axis labels follow detached axes, plus their own freely editable offset.
    pub fn effective_offset(&self, id: &DecorationId) -> [f32; 2] {
        let mut p = self.offset(id);
        if let DecorationId::AxisLabel(side) = id {
            let q = self.offset(&DecorationId::Axis(side.clone()));
            p[0] += q[0];
            p[1] += q[1];
        }
        p
    }
    pub fn reset(&mut self, id: &DecorationId) {
        if *id == DecorationId::DataArea {
            self.data_area = None;
        }
        self.offsets.retain(|o| &o.element != id);
    }
    pub fn resolve_data_area(&self, automatic: RectF) -> Result<RectF, &'static str> {
        let r = self.data_area.unwrap_or(automatic);
        if ![r.x, r.y, r.width, r.height, r.x + r.width, r.y + r.height]
            .into_iter()
            .all(f32::is_finite)
            || r.x < 0.
            || r.y < 0.
            || r.width < 80.
            || r.height < 60.
            || r.x < automatic.x
            || r.y < automatic.y
            || r.x + r.width > automatic.x + automatic.width
            || r.y + r.height > automatic.y + automatic.height
        {
            return Err(
                "data area must fit the measured plot region and be at least 80 by 60 logical pixels",
            );
        }
        Ok(r)
    }
    pub fn validate(&self) -> Result<(), &'static str> {
        if let Some(r) = self.data_area {
            self.resolve_data_area(r)?;
        }
        if self.offsets.len() > 1024 {
            return Err("too many decoration offsets");
        }
        for (i, o) in self.offsets.iter().enumerate() {
            if o.offset.iter().any(|x| !x.is_finite())
                || self.offsets[..i].iter().any(|p| p.element == o.element)
                || matches!(
                    o.element,
                    DecorationId::DataArea | DecorationId::DataAreaEdge(_)
                )
            {
                return Err("decoration offsets must be finite and unique");
            }
            if let DecorationId::Axis(s) = &o.element {
                let parallel = match s {
                    Side::Top | Side::Bottom => o.offset[0],
                    _ => o.offset[1],
                };
                if parallel != 0.0 {
                    return Err("axes only move perpendicular to their direction");
                }
            }
        }
        Ok(())
    }
}
/// Renderer-measured base bounds, before user offsets. A fresh frame supplies
/// these after resizing/reflow; hosts never reconstruct text or axis geometry.
#[derive(Clone, Debug)]
pub struct DecorationElement {
    pub id: DecorationId,
    pub base_bounds: RectF,
    pub canvas_size: (u32, u32),
    /// Parts that move together with this target (e.g. a detached axis's labels).
    pub followers: Vec<(DecorationId, RectF)>,
}
impl Selectable<DecorationLayout> for DecorationElement {
    fn bounds(&self, cfg: &DecorationLayout, _: &dyn MeasureText) -> Option<RectF> {
        match self.id {
            DecorationId::DataArea => return cfg.resolve_data_area(self.base_bounds).ok(),
            DecorationId::DataAreaEdge(_) => return None,
            _ => {}
        }
        let p = cfg.effective_offset(&self.id);
        Some(self.base_bounds.translated(p[0], p[1]))
    }
    fn as_draggable(&self) -> Option<&dyn Draggable<DecorationLayout>> {
        Some(self)
    }
    fn as_resizable(&self) -> Option<&dyn crate::resize::Resizable<DecorationLayout>> {
        (self.id == DecorationId::DataArea).then_some(self)
    }
    fn element_id(&self) -> String {
        self.id.element_id()
    }
}
impl Draggable<DecorationLayout> for DecorationElement {
    fn nudge_element(&self) -> DecorationElement {
        self.clone()
    }
}
impl crate::resize::Resizable<DecorationLayout> for DecorationElement {
    fn resize_targets(&self, handle: crate::resize::ResizeHandle) -> (Option<Self>, Option<Self>) {
        use crate::resize::ResizeHandle::*;
        let edge = |side| {
            let mut e = self.clone();
            e.id = DecorationId::DataAreaEdge(side);
            e
        };
        let x = match handle {
            NW | W | SW => Some(edge(Side::Left)),
            NE | E | SE => Some(edge(Side::Right)),
            N | S => None,
        };
        let y = match handle {
            NW | N | NE => Some(edge(Side::Top)),
            SW | S | SE => Some(edge(Side::Bottom)),
            E | W => None,
        };
        (x, y)
    }
    fn resize_by(
        &self,
        cfg: &mut DecorationLayout,
        handle: crate::resize::ResizeHandle,
        dx: f32,
        dy: f32,
    ) -> NudgeResult {
        let reject = NudgeResult::Rejected(NudgeReject::OutOfBounds);
        if self.id != DecorationId::DataArea || !dx.is_finite() || !dy.is_finite() {
            return reject;
        }
        let (x, y) = self.resize_targets(handle);
        let mut trial = cfg.clone();
        for (element, dx, dy) in [(x, dx, 0.), (y, 0., dy)] {
            if let Some(element) = element {
                if trial.nudge(element, dx, dy) != NudgeResult::Moved {
                    return reject;
                }
            }
        }
        *cfg = trial;
        NudgeResult::Moved
    }
}
impl DragConfig for DecorationLayout {
    type Element = DecorationElement;
    fn nudge(&mut self, element: DecorationElement, mut dx: f32, mut dy: f32) -> NudgeResult {
        let reject = NudgeResult::Rejected(NudgeReject::OutOfBounds);
        if !dx.is_finite() || !dy.is_finite() {
            return reject;
        }
        if matches!(
            element.id,
            DecorationId::DataArea | DecorationId::DataAreaEdge(_)
        ) {
            let Ok(mut r) = self.resolve_data_area(element.base_bounds) else {
                return reject;
            };
            match element.id {
                DecorationId::DataArea => {
                    r.x += dx;
                    r.y += dy;
                }
                DecorationId::DataAreaEdge(Side::Left) => {
                    r.x += dx;
                    r.width -= dx;
                }
                DecorationId::DataAreaEdge(Side::Right) => r.width += dx,
                DecorationId::DataAreaEdge(Side::Top) => {
                    r.y += dy;
                    r.height -= dy;
                }
                DecorationId::DataAreaEdge(Side::Bottom) => r.height += dy,
                _ => unreachable!(),
            }
            let mut trial = self.clone();
            trial.data_area = Some(r);
            if trial.resolve_data_area(element.base_bounds).is_err() {
                return reject;
            }
            self.data_area = Some(r);
            return NudgeResult::Moved;
        }
        if let DecorationId::Axis(side) = &element.id {
            match side {
                Side::Top | Side::Bottom => dx = 0.,
                _ => dy = 0.,
            }
        }
        let inside = |rect: RectF, offset: [f32; 2]| {
            let r = rect.translated(offset[0] + dx, offset[1] + dy);
            r.x >= 0.
                && r.y >= 0.
                && r.x + r.width <= element.canvas_size.0 as f32
                && r.y + r.height <= element.canvas_size.1 as f32
        };
        if !inside(element.base_bounds, self.effective_offset(&element.id))
            || element
                .followers
                .iter()
                .any(|(id, rect)| !inside(*rect, self.effective_offset(id)))
        {
            return reject;
        }
        let old = self.offset(&element.id);
        let next = [old[0] + dx, old[1] + dy];
        self.reset(&element.id);
        if next != [0., 0.] {
            self.offsets.push(DecorationOffset {
                element: element.id,
                offset: next,
            });
        }
        NudgeResult::Moved
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn area_handles_move_only_their_edges_and_reject_atomically() {
        use crate::resize::{Resizable, ResizeHandle::*};
        let e = DecorationElement {
            id: DecorationId::DataArea,
            base_bounds: RectF {
                x: 20.,
                y: 20.,
                width: 240.,
                height: 160.,
            },
            canvas_size: (300, 200),
            followers: vec![],
        };
        let original = RectF {
            x: 50.,
            y: 50.,
            width: 150.,
            height: 90.,
        };
        for (handle, left, right, top, bottom) in [
            (NW, true, false, true, false),
            (N, false, false, true, false),
            (NE, false, true, true, false),
            (E, false, true, false, false),
            (SE, false, true, false, true),
            (S, false, false, false, true),
            (SW, true, false, false, true),
            (W, true, false, false, false),
        ] {
            let mut state = DecorationLayout {
                data_area: Some(original),
                ..Default::default()
            };
            assert_eq!(e.resize_by(&mut state, handle, 7., 9.), NudgeResult::Moved);
            let r = state.data_area.unwrap();
            assert_eq!(r.x, original.x + if left { 7. } else { 0. });
            assert_eq!(r.y, original.y + if top { 9. } else { 0. });
            assert_eq!(
                r.x + r.width,
                original.x + original.width + if right { 7. } else { 0. }
            );
            assert_eq!(
                r.y + r.height,
                original.y + original.height + if bottom { 9. } else { 0. }
            );
        }
        let mut state = DecorationLayout {
            data_area: Some(original),
            ..Default::default()
        };
        let before = state.clone();
        for (dx, dy) in [
            (7., -1000.),
            (f32::NAN, 0.),
            (0., f32::INFINITY),
            (100., 0.),
        ] {
            assert!(matches!(
                e.resize_by(&mut state, NW, dx, dy),
                NudgeResult::Rejected(_)
            ));
            assert_eq!(state, before);
        }
        state.reset(&DecorationId::DataArea);
        assert_eq!(
            state.resolve_data_area(e.base_bounds).unwrap(),
            e.base_bounds
        );
    }
    fn element(id: DecorationId) -> DecorationElement {
        DecorationElement {
            id,
            base_bounds: RectF {
                x: 20.,
                y: 20.,
                width: 100.,
                height: 20.,
            },
            canvas_size: (300, 200),
            followers: vec![],
        }
    }
    #[test]
    fn cartesian_hit_map_constructors_keep_type_inference_without_annotations() {
        let empty = crate::HitMap::new();
        let default = crate::HitMap::default();
        assert!(empty.is_empty() && default.is_empty());
    }
    #[test]
    fn drag_rejects_nonfinite_outside_and_axis_follower_overflow_atomically() {
        let mut state = DecorationLayout::default();
        let mut axis = element(DecorationId::Axis(Side::Left));
        axis.followers.push((
            DecorationId::AxisLabel(Side::Left),
            RectF {
                x: 1.,
                y: 20.,
                width: 20.,
                height: 30.,
            },
        ));
        for delta in [[f32::NAN, 0.], [0., f32::INFINITY], [-2., 0.], [1000., 0.]] {
            assert!(matches!(
                axis.drag_by(&mut state, delta[0], delta[1]),
                NudgeResult::Rejected(_)
            ));
            assert_eq!(state, DecorationLayout::default());
        }
        assert_eq!(axis.drag_by(&mut state, 5., 80.), NudgeResult::Moved);
        assert_eq!(state.offset(&axis.id), [5., 0.]);
        assert_eq!(
            state.effective_offset(&DecorationId::AxisLabel(Side::Left)),
            [5., 0.]
        );
    }
    #[test]
    fn duplicate_nonfinite_and_parallel_axis_offsets_are_rejected() {
        let mut state = DecorationLayout {
            data_area: None,
            offsets: vec![DecorationOffset {
                element: DecorationId::Legend,
                offset: [f32::NAN, 0.],
            }],
            selected: None,
        };
        assert!(state.validate().is_err());
        state.offsets[0].offset = [1., 2.];
        state.offsets.push(state.offsets[0].clone());
        assert!(state.validate().is_err());
        state.offsets.pop();
        state.offsets[0].element = DecorationId::Axis(Side::Left);
        assert!(state.validate().is_err());
    }
    #[cfg(feature = "serde")]
    #[test]
    fn old_documents_default_positions_and_all_models_preserve_edits() {
        for mut value in [
            serde_json::to_value(crate::RadialChart::default()).unwrap(),
            serde_json::to_value(crate::CategoricalChart::default()).unwrap(),
            serde_json::to_value(crate::BoxPlotChart::default()).unwrap(),
        ] {
            value.as_object_mut().unwrap().remove("decorations");
            assert!(value.get("decorations").is_none());
            // Each old chart type fills only the newly added state with defaults.
            if value.get("slices").is_some() {
                assert_eq!(
                    serde_json::from_value::<crate::RadialChart>(value)
                        .unwrap()
                        .decorations,
                    DecorationLayout::default()
                );
            } else if value.get("mode").is_some() {
                assert_eq!(
                    serde_json::from_value::<crate::CategoricalChart>(value)
                        .unwrap()
                        .decorations,
                    DecorationLayout::default()
                );
            } else {
                assert_eq!(
                    serde_json::from_value::<crate::BoxPlotChart>(value)
                        .unwrap()
                        .decorations,
                    DecorationLayout::default()
                );
            }
        }
        let mut state = DecorationLayout::default();
        element(DecorationId::ChartTitle).drag_by(&mut state, 4., 6.);
        state.selected = Some(DecorationId::ChartTitle);
        let mut radial = crate::RadialChart::default();
        radial.decorations = state.clone();
        let mut categorical = crate::CategoricalChart::default();
        categorical.decorations = state.clone();
        let mut boxplot = crate::BoxPlotChart::default();
        boxplot.decorations = state;
        assert_eq!(
            serde_json::from_str::<crate::RadialChart>(&serde_json::to_string(&radial).unwrap())
                .unwrap(),
            radial
        );
        assert_eq!(
            serde_json::from_str::<crate::CategoricalChart>(
                &serde_json::to_string(&categorical).unwrap()
            )
            .unwrap(),
            categorical
        );
        assert_eq!(
            serde_json::from_str::<crate::BoxPlotChart>(&serde_json::to_string(&boxplot).unwrap())
                .unwrap(),
            boxplot
        );
    }
}