hwpforge-core 0.5.1

Format-independent Document Object Model for HwpForge
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
//! Chart types for OOXML-based chart support.
//!
//! Charts in HWPX use the OOXML chart XML format (`xmlns:c`).
//! This module defines the chart type enum (18 variants covering all 16
//! OOXML chart types, with Bar/Column direction split) and the data model
//! for category-based and XY-based chart data.
//!
//! # Examples
//!
//! ```
//! use hwpforge_core::chart::{ChartType, ChartData, ChartGrouping, LegendPosition};
//!
//! let data = ChartData::category(
//!     &["Q1", "Q2", "Q3"],
//!     &[("Sales", &[100.0, 150.0, 200.0])],
//! );
//! assert!(matches!(data, ChartData::Category { .. }));
//! ```

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// OOXML chart types supported by ν•œκΈ€ (16 OOXML types β†’ 18 variants).
///
/// Bar and Column are both `<c:barChart>` in OOXML, distinguished by
/// `<c:barDir val="bar|col">`. Similarly for 3D variants.
///
/// # Examples
///
/// ```
/// use hwpforge_core::chart::ChartType;
///
/// let ct = ChartType::Column;
/// assert_eq!(format!("{ct:?}"), "Column");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub enum ChartType {
    /// Horizontal bar chart (`<c:barChart>` with `barDir=bar`).
    Bar,
    /// Vertical bar chart (`<c:barChart>` with `barDir=col`).
    Column,
    /// 3D horizontal bar chart (`<c:bar3DChart>` with `barDir=bar`).
    Bar3D,
    /// 3D vertical bar chart (`<c:bar3DChart>` with `barDir=col`).
    Column3D,
    /// Line chart (`<c:lineChart>`).
    Line,
    /// 3D line chart (`<c:line3DChart>`).
    Line3D,
    /// Pie chart (`<c:pieChart>`).
    Pie,
    /// 3D pie chart (`<c:pie3DChart>`).
    Pie3D,
    /// Doughnut chart (`<c:doughnutChart>`).
    Doughnut,
    /// Pie-of-pie or bar-of-pie chart (`<c:ofPieChart>`).
    OfPie,
    /// Area chart (`<c:areaChart>`).
    Area,
    /// 3D area chart (`<c:area3DChart>`).
    Area3D,
    /// Scatter (XY) chart (`<c:scatterChart>`).
    Scatter,
    /// Bubble chart (`<c:bubbleChart>`).
    Bubble,
    /// Radar chart (`<c:radarChart>`).
    Radar,
    /// Surface chart (`<c:surfaceChart>`).
    Surface,
    /// 3D surface chart (`<c:surface3DChart>`).
    Surface3D,
    /// Stock chart (`<c:stockChart>`).
    Stock,
}

/// Chart data grouping mode.
///
/// Determines how multiple series are arranged visually.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
pub enum ChartGrouping {
    /// Side-by-side bars/areas (default).
    #[default]
    Clustered,
    /// Stacked on top of each other.
    Stacked,
    /// Stacked to 100%.
    PercentStacked,
    /// Standard grouping (used by line/scatter).
    Standard,
}

/// Stock chart sub-variant determining series composition.
///
/// The basic `ChartType::Stock` maps to HLC (High-Low-Close, 3 series).
/// Volume variants require a composite `<c:plotArea>` with both a `<c:barChart>`
/// (volume series) and a `<c:stockChart>` (price series).
///
/// # OOXML mapping
///
/// | Variant | Series | plotArea layout |
/// |---------|--------|-----------------|
/// | `Hlc`   | 3      | stockChart only |
/// | `Ohlc`  | 4      | stockChart only |
/// | `Vhlc`  | 4      | barChart + stockChart |
/// | `Vohlc` | 5      | barChart + stockChart |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum StockVariant {
    /// High-Low-Close (3 price series, default).
    Hlc,
    /// Open-High-Low-Close (4 price series).
    Ohlc,
    /// Volume-High-Low-Close (1 volume + 3 price series, composite plotArea).
    Vhlc,
    /// Volume-Open-High-Low-Close (1 volume + 4 price series, composite plotArea).
    Vohlc,
}

/// Bar/column 3D shape variant.
///
/// Controls the visual shape of bars in 3D bar and column charts.
/// Maps to OOXML `<c:shape val="..."/>` within `<c:bar3DChart>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum BarShape {
    /// Standard rectangular box (default).
    Box,
    /// Cylindrical column.
    Cylinder,
    /// Conical column.
    Cone,
    /// Pyramid-shaped column.
    Pyramid,
}

/// Scatter chart line/marker style.
///
/// Controls how data points are connected and displayed in scatter charts.
/// Maps to OOXML `<c:scatterStyle val="..."/>` within `<c:scatterChart>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum ScatterStyle {
    /// Points only, no lines.
    Dots,
    /// Straight lines with markers.
    LineMarker,
    /// Smooth curves with markers.
    SmoothMarker,
    /// Straight lines without markers.
    Line,
    /// Smooth curves without markers.
    Smooth,
}

/// Radar chart rendering style.
///
/// Controls how the radar chart area is rendered.
/// Maps to OOXML `<c:radarStyle val="..."/>` within `<c:radarChart>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum RadarStyle {
    /// Standard radar (lines only).
    Standard,
    /// Radar with data point markers.
    Marker,
    /// Filled/shaded radar area.
    Filled,
}

/// Pie-of-pie or bar-of-pie sub-type.
///
/// Determines whether the secondary chart is a pie or a bar.
/// Maps to OOXML `<c:ofPieType val="..."/>` within `<c:ofPieChart>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum OfPieType {
    /// Pie-of-pie chart.
    Pie,
    /// Bar-of-pie chart.
    Bar,
}

/// Legend position relative to the chart area.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
pub enum LegendPosition {
    /// Legend on the right side (default).
    #[default]
    Right,
    /// Legend at the bottom.
    Bottom,
    /// Legend at the top.
    Top,
    /// Legend on the left side.
    Left,
    /// No legend displayed.
    None,
}

/// Chart data β€” either category-based or XY-based.
///
/// # Examples
///
/// ```
/// use hwpforge_core::chart::ChartData;
///
/// let cat = ChartData::category(
///     &["A", "B"],
///     &[("Series1", &[10.0, 20.0])],
/// );
/// assert!(matches!(cat, ChartData::Category { .. }));
///
/// let xy = ChartData::xy(&[("Points", &[1.0, 2.0], &[3.0, 4.0])]);
/// assert!(matches!(xy, ChartData::Xy { .. }));
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub enum ChartData {
    /// Category-based data (bar, line, pie, area, radar, etc.).
    Category {
        /// Category labels (X-axis).
        categories: Vec<String>,
        /// Data series, each with a name and values.
        series: Vec<ChartSeries>,
    },
    /// XY-based data (scatter, bubble).
    Xy {
        /// XY series, each with name + x/y value arrays.
        series: Vec<XySeries>,
    },
}

/// A named data series with values aligned to categories.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ChartSeries {
    /// Series name (shown in legend).
    pub name: String,
    /// Numeric values (one per category).
    pub values: Vec<f64>,
}

/// A named XY data series (for scatter/bubble charts).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct XySeries {
    /// Series name (shown in legend).
    pub name: String,
    /// X-axis values.
    pub x_values: Vec<f64>,
    /// Y-axis values (must be same length as `x_values`).
    pub y_values: Vec<f64>,
}

impl ChartData {
    /// Creates category-based chart data from slices.
    ///
    /// # Examples
    ///
    /// ```
    /// use hwpforge_core::chart::ChartData;
    ///
    /// let data = ChartData::category(
    ///     &["Jan", "Feb", "Mar"],
    ///     &[("Revenue", &[100.0, 200.0, 300.0])],
    /// );
    /// match &data {
    ///     ChartData::Category { categories, series } => {
    ///         assert_eq!(categories.len(), 3);
    ///         assert_eq!(series.len(), 1);
    ///     }
    ///     _ => unreachable!(),
    /// }
    /// ```
    pub fn category(cats: &[&str], series: &[(&str, &[f64])]) -> Self {
        Self::Category {
            categories: cats.iter().map(|s| (*s).to_string()).collect(),
            series: series
                .iter()
                .map(|(name, vals)| ChartSeries {
                    name: (*name).to_string(),
                    values: vals.to_vec(),
                })
                .collect(),
        }
    }

    /// Creates XY-based chart data from slices.
    ///
    /// # Examples
    ///
    /// ```
    /// use hwpforge_core::chart::ChartData;
    ///
    /// let data = ChartData::xy(&[("Points", &[1.0, 2.0], &[3.0, 4.0])]);
    /// match &data {
    ///     ChartData::Xy { series } => {
    ///         assert_eq!(series.len(), 1);
    ///         assert_eq!(series[0].x_values.len(), 2);
    ///     }
    ///     _ => unreachable!(),
    /// }
    /// ```
    pub fn xy(series: &[(&str, &[f64], &[f64])]) -> Self {
        Self::Xy {
            series: series
                .iter()
                .map(|(name, xs, ys)| XySeries {
                    name: (*name).to_string(),
                    x_values: xs.to_vec(),
                    y_values: ys.to_vec(),
                })
                .collect(),
        }
    }

    /// Returns `true` if the chart data contains no series.
    ///
    /// A chart with zero series cannot be rendered. This is checked during
    /// document validation (see [`ValidationError::EmptyChartData`](crate::error::ValidationError::EmptyChartData)).
    pub fn has_no_series(&self) -> bool {
        match self {
            Self::Category { series, .. } => series.is_empty(),
            Self::Xy { series } => series.is_empty(),
        }
    }

    /// Returns `true` if the chart data contains no series.
    #[deprecated(since = "0.2.0", note = "Use `has_no_series()` instead")]
    pub fn is_empty(&self) -> bool {
        self.has_no_series()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn chart_type_all_18_variants() {
        let variants = [
            ChartType::Bar,
            ChartType::Column,
            ChartType::Bar3D,
            ChartType::Column3D,
            ChartType::Line,
            ChartType::Line3D,
            ChartType::Pie,
            ChartType::Pie3D,
            ChartType::Doughnut,
            ChartType::OfPie,
            ChartType::Area,
            ChartType::Area3D,
            ChartType::Scatter,
            ChartType::Bubble,
            ChartType::Radar,
            ChartType::Surface,
            ChartType::Surface3D,
            ChartType::Stock,
        ];
        assert_eq!(variants.len(), 18);
        // All distinct
        for (i, a) in variants.iter().enumerate() {
            for (j, b) in variants.iter().enumerate() {
                if i != j {
                    assert_ne!(a, b, "variants {i} and {j} should be distinct");
                }
            }
        }
    }

    #[test]
    fn chart_data_category_convenience() {
        let data = ChartData::category(
            &["Q1", "Q2", "Q3", "Q4"],
            &[("Sales", &[100.0, 150.0, 200.0, 250.0]), ("Costs", &[80.0, 90.0, 100.0, 110.0])],
        );
        match &data {
            ChartData::Category { categories, series } => {
                assert_eq!(categories.len(), 4);
                assert_eq!(series.len(), 2);
                assert_eq!(series[0].name, "Sales");
                assert_eq!(series[1].values, &[80.0, 90.0, 100.0, 110.0]);
            }
            _ => panic!("expected Category"),
        }
    }

    #[test]
    fn chart_data_xy_convenience() {
        let data = ChartData::xy(&[("Points", &[1.0, 2.0, 3.0], &[10.0, 20.0, 30.0])]);
        match &data {
            ChartData::Xy { series } => {
                assert_eq!(series.len(), 1);
                assert_eq!(series[0].name, "Points");
                assert_eq!(series[0].x_values, &[1.0, 2.0, 3.0]);
                assert_eq!(series[0].y_values, &[10.0, 20.0, 30.0]);
            }
            _ => panic!("expected Xy"),
        }
    }

    #[test]
    fn chart_data_has_no_series() {
        let empty_cat = ChartData::category(&["A"], &[]);
        assert!(empty_cat.has_no_series());

        let non_empty = ChartData::category(&["A"], &[("S", &[1.0])]);
        assert!(!non_empty.has_no_series());

        let empty_xy = ChartData::Xy { series: vec![] };
        assert!(empty_xy.has_no_series());
    }

    #[test]
    #[allow(deprecated)]
    fn chart_data_is_empty_deprecated_alias() {
        let empty = ChartData::category(&["A"], &[]);
        assert!(empty.is_empty());
        assert_eq!(empty.is_empty(), empty.has_no_series());
    }

    #[test]
    fn serde_roundtrip_chart_data() {
        let data = ChartData::category(&["A", "B"], &[("S1", &[1.0, 2.0])]);
        let json = serde_json::to_string(&data).unwrap();
        let back: ChartData = serde_json::from_str(&json).unwrap();
        assert_eq!(data, back);
    }

    #[test]
    fn serde_roundtrip_xy_data() {
        let data = ChartData::xy(&[("P", &[1.0, 2.0], &[3.0, 4.0])]);
        let json = serde_json::to_string(&data).unwrap();
        let back: ChartData = serde_json::from_str(&json).unwrap();
        assert_eq!(data, back);
    }

    #[test]
    fn chart_grouping_default() {
        assert_eq!(ChartGrouping::default(), ChartGrouping::Clustered);
    }

    #[test]
    fn legend_position_default() {
        assert_eq!(LegendPosition::default(), LegendPosition::Right);
    }

    #[test]
    fn chart_type_copy_clone() {
        let ct = ChartType::Pie;
        let ct2 = ct;
        assert_eq!(ct, ct2);
    }
}