milsymbol-rs 0.3.2

A Rust wrapper for the milsymbol JavaScript library to generate military symbols (MIL-STD-2525 and APP-6).
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
use serde::{Deserialize, Serialize};

/// The anchor point of a symbol (absolute pixel coordinates within the image).
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq)]
pub struct Anchor {
    /// The x-coordinate.
    pub x: f64,
    /// The y-coordinate.
    pub y: f64,
}

/// A bounding box of a symbol.
///
/// Individual coordinate fields default to `0.0` so that a partially-populated JSON object
/// (such as the `{}` emitted by the JS library when no geometry is resolved) can be
/// deserialized without error.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq)]
pub struct BoundingBox {
    /// The x-coordinate of the top-left corner.
    #[serde(default)]
    pub x1: f64,
    /// The y-coordinate of the top-left corner.
    #[serde(default)]
    pub y1: f64,
    /// The x-coordinate of the bottom-right corner.
    #[serde(default)]
    pub x2: f64,
    /// The y-coordinate of the bottom-right corner.
    #[serde(default)]
    pub y2: f64,
}

/// The rendered image dimensions of a symbol.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq)]
pub struct SymbolSize {
    /// The width in pixels.
    pub width: f64,
    /// The height in pixels.
    pub height: f64,
}

/// The output of a rendered symbol.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct SymbolOutput {
    /// The SVG string.
    pub svg: String,
    /// The anchor point (in image-pixel coordinates).
    pub anchor: Anchor,
    /// The anchor point for the octagon (used for debug/alignment).
    #[serde(rename = "octagonAnchor")]
    pub octagon_anchor: Anchor,
    /// The rendered image size in pixels.
    pub size: SymbolSize,
    /// Bounding box of the symbol.
    pub bbox: BoundingBox,
    /// Metadata about the symbol.
    pub metadata: SymbolMetadata,
    /// Colors used for the symbol.
    pub colors: SymbolColors,
    /// Resolved style information.
    pub style: SymbolStyle,
    /// The effective options used for rendering.
    pub options: crate::options::MilsymbolOptions,
    /// Low-level draw instructions.
    #[serde(rename = "drawInstructions")]
    pub draw_instructions: Vec<DrawInstruction>,
}

/// Resolved style information for a symbol.
///
/// This struct maps 1-to-1 to the object returned by `sym.getStyle()` in the JavaScript
/// milsymbol library, which is a full clone of the internal `this.style` object. All fields
/// the JS library may set are represented here so no data is silently dropped on
/// deserialization.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SymbolStyle {
    /// Use the alternate MEDAL icon (MIL-STD-2525D option).
    #[serde(default)]
    pub alternate_medal: bool,
    /// Whether civilian purple color should be applied to civilian symbols.
    #[serde(default = "default_true")]
    pub civilian_color: bool,
    /// Active color mode — either a named mode string (e.g. `"Light"`) or a full
    /// [`ColorMode`] object. Stored as a raw JSON value to accommodate both.
    #[serde(default)]
    pub color_mode: serde_json::Value,
    /// Whether the symbol is filled with color.
    #[serde(default = "default_true")]
    pub fill: bool,
    /// Fill color override (empty string means "use the color mode default").
    #[serde(default)]
    pub fill_color: String,
    /// Fill opacity (0.0–1.0).
    #[serde(default = "default_fill_opacity")]
    pub fill_opacity: f64,
    /// Font family used for text modifiers.
    #[serde(default = "default_font_family")]
    pub fontfamily: String,
    /// Whether the symbol is framed.
    #[serde(default = "default_true")]
    pub frame: bool,
    /// Frame color override (empty string means "use the color mode default").
    #[serde(default)]
    pub frame_color: String,
    /// Per-instance HQ staff length override (0 means use the global default).
    #[serde(default)]
    pub hq_staff_length: f64,
    /// Whether the icon is drawn inside the frame.
    #[serde(default = "default_true")]
    pub icon: bool,
    /// Icon color override (empty string means "use the color mode default").
    #[serde(default)]
    pub icon_color: String,
    /// Background color for info text fields.
    #[serde(default)]
    pub info_background: String,
    /// Frame color for the info text field background.
    #[serde(default)]
    pub info_background_frame: String,
    /// Color override for all info text fields.
    #[serde(default)]
    pub info_color: String,
    /// Whether info text fields are rendered.
    #[serde(default = "default_true")]
    pub info_fields: bool,
    /// Color of the text outline for info fields.
    #[serde(default = "default_info_outline_color")]
    pub info_outline_color: String,
    /// Width of the text outline for info fields.
    ///
    /// The JS library defaults this to `false` (a boolean meaning "no outline"), and may
    /// return a number when an outline width is set. Stored as a raw [`serde_json::Value`] to
    /// faithfully represent the JS boolean-or-number union without triggering a type mismatch
    /// in `serde_v8`. Use [`SymbolStyle::info_outline_width_f64`] to obtain the numeric value.
    #[serde(default)]
    pub info_outline_width: serde_json::Value,
    /// Relative size of the info text fields (percentage of symbol size).
    #[serde(default = "default_info_size")]
    pub info_size: f64,
    /// Monochrome color override — when non-empty the entire symbol is rendered in this color.
    #[serde(default)]
    pub mono_color: String,
    /// Outline color of the symbol frame.
    #[serde(default = "default_outline_color")]
    pub outline_color: String,
    /// Stroke width of the outline (0 means no outline).
    #[serde(default)]
    pub outline_width: f64,
    /// Extra padding added around the symbol bounding box (pixels).
    #[serde(default)]
    pub padding: f64,
    /// Force use of simple (non-standard) status modifiers.
    #[serde(default)]
    pub simple_status_modifier: bool,
    /// Symbol size — corresponds to the `L` variable in the MIL-STD geometry.
    #[serde(default = "default_size")]
    pub size: f64,
    /// Whether the symbol bounding box should be forced to a square.
    #[serde(default)]
    pub square: bool,
    /// Standard override (`"2525"` or `"APP6"`; empty string means use the global default).
    #[serde(default)]
    pub standard: String,
    /// Stroke width of the symbol frame.
    #[serde(default = "default_stroke_width")]
    pub stroke_width: f64,
    /// Internal flag used during fill-style resolution; not normally needed by callers.
    #[serde(default)]
    pub style_fill: bool,
}

fn default_true() -> bool {
    true
}

fn default_fill_opacity() -> f64 {
    1.0
}

fn default_font_family() -> String {
    "Arial".to_string()
}

fn default_info_outline_color() -> String {
    "rgb(239, 239, 239)".to_string()
}

fn default_info_size() -> f64 {
    40.0
}

fn default_outline_color() -> String {
    "rgb(239, 239, 239)".to_string()
}

fn default_size() -> f64 {
    100.0
}

fn default_stroke_width() -> f64 {
    4.0
}



impl Default for SymbolStyle {
    fn default() -> Self {
        Self {
            alternate_medal: false,
            civilian_color: default_true(),
            color_mode: serde_json::Value::String("Light".to_string()),
            fill: default_true(),
            fill_color: String::new(),
            fill_opacity: default_fill_opacity(),
            fontfamily: default_font_family(),
            frame: default_true(),
            frame_color: String::new(),
            hq_staff_length: 0.0,
            icon: default_true(),
            icon_color: String::new(),
            info_background: String::new(),
            info_background_frame: String::new(),
            info_color: String::new(),
            info_fields: default_true(),
            info_outline_color: default_info_outline_color(),
            info_outline_width: serde_json::Value::Bool(false),
            info_size: default_info_size(),
            mono_color: String::new(),
            outline_color: default_outline_color(),
            outline_width: 0.0,
            padding: 0.0,
            simple_status_modifier: false,
            size: default_size(),
            square: false,
            standard: String::new(),
            stroke_width: default_stroke_width(),
            style_fill: false,
        }
    }
}

impl SymbolStyle {
    /// Returns the info text-outline width as `f64`.
    ///
    /// The JS library stores this field as `false` (boolean, meaning "no outline") or a number.
    /// Returns `0.0` when the JS value is `false` or any non-numeric type.
    pub fn info_outline_width_f64(&self) -> f64 {
        match &self.info_outline_width {
            serde_json::Value::Number(n) => n.as_f64().unwrap_or(0.0),
            _ => 0.0,
        }
    }
}

impl SymbolOutput {
    /// Converts an SVG string to a Data URL (UTF-8 encoded).
    pub fn to_data_url(&self) -> String {
        format!("data:image/svg+xml;utf8,{}", urlencoding::encode(&self.svg))
    }

    /// Returns the SVG string as a byte vector.
    pub fn as_bytes(&self) -> Vec<u8> {
        self.svg.as_bytes().to_vec()
    }

    /// Renders the SVG to a static image (RGBA).
    #[cfg(feature = "image")]
    pub fn to_image(&self) -> Result<image::DynamicImage, crate::error::MilsymbolError> {
        let opt = resvg::usvg::Options::default();
        let rtree = resvg::usvg::Tree::from_str(&self.svg, &opt)?;

        let pixmap_size = rtree.size();
        let mut pixmap =
            resvg::tiny_skia::Pixmap::new(pixmap_size.width() as u32, pixmap_size.height() as u32)
                .ok_or(crate::error::MilsymbolError::PixmapCreationError)?;

        resvg::render(
            &rtree,
            resvg::usvg::Transform::default(),
            &mut pixmap.as_mut(),
        );

        let rgba_image =
            image::RgbaImage::from_raw(pixmap.width(), pixmap.height(), pixmap.data().to_vec())
                .ok_or(crate::error::MilsymbolError::RgbaImageCreationError)?;

        Ok(image::DynamicImage::ImageRgba8(rgba_image))
    }
}

/// Dash array styles for different line types.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DashArrays {
    /// Dash array for pending symbols.
    pub pending: String,
    /// Dash array for anticipated symbols.
    pub anticipated: String,
    /// Dash array for feint/dummy symbols.
    #[serde(rename = "feintDummy")]
    pub feint_dummy: String,
}

fn deserialize_color_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum StrOrBool {
        Str(String),
        Bool(bool),
    }

    match StrOrBool::deserialize(deserializer)? {
        StrOrBool::Str(s) => Ok(s),
        StrOrBool::Bool(b) => {
            if !b {
                Ok(String::new())
            } else {
                Ok("true".to_string())
            }
        }
    }
}

/// Colors used for different affiliations.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub struct ColorMode {
    /// Color for civilians.
    #[serde(deserialize_with = "deserialize_color_string")]
    pub civilian: String,
    /// Color for friendlies.
    #[serde(deserialize_with = "deserialize_color_string")]
    pub friend: String,
    /// Color for hostiles.
    #[serde(deserialize_with = "deserialize_color_string")]
    pub hostile: String,
    /// Color for neutrals.
    #[serde(deserialize_with = "deserialize_color_string")]
    pub neutral: String,
    /// Color for unknowns.
    #[serde(deserialize_with = "deserialize_color_string")]
    pub unknown: String,
    /// Color for suspects.
    #[serde(deserialize_with = "deserialize_color_string")]
    pub suspect: String,
}

impl ColorMode {
    /// Creates a new ColorMode, validating that all provided strings are valid CSS colors.
    pub fn new(
        civilian: &str,
        friend: &str,
        hostile: &str,
        neutral: &str,
        unknown: &str,
        suspect: &str,
    ) -> Result<Self, crate::error::MilsymbolError> {
        let parse = |c: &str| -> Result<String, crate::error::MilsymbolError> {
            csscolorparser::parse(c).map_err(|e| crate::error::MilsymbolError::InvalidColor {
                color: c.to_string(),
                source: e,
            })?;
            Ok(c.to_string())
        };

        Ok(Self {
            civilian: parse(civilian)?,
            friend: parse(friend)?,
            hostile: parse(hostile)?,
            neutral: parse(neutral)?,
            unknown: parse(unknown)?,
            suspect: parse(suspect)?,
        })
    }
}

/// The full color palette for a rendered symbol.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SymbolColors {
    /// Symbol fill color.
    pub fill_color: ColorMode,
    /// Symbol frame color.
    pub frame_color: ColorMode,
    /// Icon color.
    pub icon_color: ColorMode,
    /// Icon fill color.
    pub icon_fill_color: ColorMode,
    /// Transparent/none parts of the symbol.
    pub none: ColorMode,
    /// Black parts of the symbol.
    pub black: ColorMode,
    /// White parts of the symbol.
    pub white: ColorMode,
}

/// Base geometry of a symbol's frame shape, returned as part of [`SymbolMetadata`].
///
/// The `g` field mirrors the JS `baseGeometry.g` union — it is either a path descriptor object
/// (`{ type: "path", d: "..." }`) or a plain string, preserved here as raw JSON.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct BaseGeometry {
    /// Bounding box of the base frame.
    pub bbox: BoundingBox,
    /// Raw geometry descriptor — either a `{ type, d }` object or a string.
    pub g: serde_json::Value,
}

/// Detailed validation results for a symbol.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ValidationDetails {
    /// Whether the affiliation is valid.
    pub affiliation: String,
    /// Whether the dimension is valid.
    pub dimension: String,
    /// Whether the dimension is unknown.
    pub dimension_unknown: bool,
    /// Whether the draw instructions are valid (no nulls).
    pub draw_instructions: bool,
    /// Whether a valid icon was found.
    pub icon: bool,
    /// Whether the mobility modifier is considered valid by the JS library.
    ///
    /// # Known limitation (inherited from upstream JS)
    /// The JavaScript `isValid(true)` computes this as:
    /// ```js
    /// mobility: this.metadata.mobility != undefined
    /// ```
    /// However, `metadata.mobility` is initialised to `""` (empty string) in
    /// `getmetadata.js`, and `"" != undefined` is always `true` in JavaScript.
    /// As a result, **this field is always `true`** regardless of whether the
    /// symbol actually has a mobility modifier. Do not use it to test for the
    /// presence of a mobility type; check [`SymbolMetadata::mobility`] instead.
    pub mobility: bool,
}

/// Parsed metadata about a specific military symbol.
///
/// # Serde renaming strategy
/// This struct uses `rename_all = "camelCase"` as a baseline so that most `snake_case` Rust
/// field names map automatically to the `camelCase` keys emitted by the JavaScript
/// `getMetadata()` function. A small number of fields override this with an explicit
/// `#[serde(rename = "...")]` attribute where the JS source uses a non-standard key (e.g. a
/// typo or an acronym that `camelCase` would transform incorrectly). See individual field
/// comments for details.
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SymbolMetadata {
    /// Is it an Activity.
    pub activity: bool,
    /// Affiliation it is shown as (Friend, Hostile, etc.).
    pub affiliation: String,
    /// Affiliation it belongs to.
    ///
    /// # Note on spelling
    /// The JSON key is intentionally misspelled as `"baseAffilation"` (one `l`) to match the
    /// upstream milsymbol JavaScript library which emits that exact key from `getMetadata()`.
    /// **Do not correct the spelling in the `rename` attribute** without a corresponding fix in
    /// the upstream JS library, or deserialization will silently produce an empty string.
    #[serde(rename = "baseAffilation")]
    pub base_affiliation: String,
    /// Base geometry of the symbol's frame shape (bounding box + path/string descriptor).
    ///
    /// The JavaScript `getMetadata()` **always** emits this key, so it is non-optional.
    /// When no geometry is resolved for the symbol the JS library sets `baseGeometry.bbox`
    /// to an empty object `{}`; `BoundingBox` handles this via `#[serde(default)]` on each
    /// coordinate field, producing all-zero coordinates rather than a deserialization error.
    #[serde(default)]
    pub base_geometry: BaseGeometry,
    /// Dimension it belongs to (Air, Ground, etc.).
    pub base_dimension: String,
    /// Is it Civilian.
    pub civilian: bool,
    /// What condition is it in (Present, Planned, etc.).
    #[serde(default)]
    pub condition: String,
    /// Context of the symbol (Reality, Exercise, Simulation).
    pub context: String,
    /// Dimension it is shown as.
    pub dimension: String,
    /// Is the dimension unknown.
    pub dimension_unknown: bool,
    /// Land dismounted individual flag (optional in JS).
    #[serde(default)]
    pub dismounted: Option<bool>,
    /// What echelon (Platoon, Company, etc.).
    #[serde(default)]
    pub echelon: String,
    /// Is it a Faker.
    pub faker: bool,
    /// Is it a feint/dummy.
    ///
    /// # Note on spelling
    /// The JS source (`getmetadata.js`) emits `"fenintDummy"` — a typo for `"feintDummy"`.
    /// The explicit rename here overrides the struct-level `rename_all = "camelCase"` (which
    /// would produce the correctly-spelled `"feintDummy"`) to match the actual JS wire key.
    /// **Do not remove this rename attribute** without a corresponding upstream JS fix.
    #[serde(rename = "fenintDummy")]
    pub feint_dummy: bool,
    /// Standard says it should be filled.
    pub fill: bool,
    /// Standard says it should be framed.
    pub frame: bool,
    /// Part of SIDC referring to the icon.
    pub functionid: String,
    /// Is it a Headquarters.
    pub headquarters: bool,
    /// Is it an Installation.
    pub installation: bool,
    /// Is it a Joker.
    pub joker: bool,
    /// Leadership role if applicable ("Leader Individual" or "Deputy Individual").
    #[serde(default)]
    pub leadership: Option<String>,
    /// What mobility (Tracked, Sled, etc.).
    #[serde(default)]
    pub mobility: String,
    /// Is it Anticipated or Pending.
    #[serde(default)]
    pub notpresent: String,
    /// Is the SIDC number based.
    #[serde(rename = "numberSIDC")]
    pub number_sidc: bool,
    /// Is it in Space.
    pub space: bool,
    /// Is it a suspect symbol.
    #[serde(default)]
    pub suspect: bool,
    /// Is it a task force.
    ///
    /// Serializes as `"taskForce"` via the struct-level `rename_all = "camelCase"` — no
    /// explicit rename needed as the camelCase conversion is correct here.
    pub task_force: bool,
    /// Is this equipment or not.
    pub unit: bool,
    /// Is it following MIL-STD-2525 or APP-6.
    #[serde(rename = "STD2525", default)]
    pub std2525: bool,
}

/// Low-level draw instructions for custom symbol parts.
#[cfg(feature = "custom-parts")]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum DrawInstruction {
    /// A known instruction type.
    Typed(TypedInstruction),
    /// An unknown or raw instruction.
    Unknown(serde_json::Value),
}

/// Known draw instruction types.
#[cfg(feature = "custom-parts")]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum TypedInstruction {
    /// A path geometry.
    Path {
        /// SVG path data (d attribute).
        d: String,
        /// Fill color.
        #[serde(skip_serializing_if = "Option::is_none")]
        fill: Option<serde_json::Value>,
        /// Stroke color.
        #[serde(skip_serializing_if = "Option::is_none")]
        stroke: Option<serde_json::Value>,
        /// Stroke width.
        #[serde(skip_serializing_if = "Option::is_none")]
        strokewidth: Option<f64>,
        /// Stroke dasharray.
        #[serde(skip_serializing_if = "Option::is_none")]
        strokedasharray: Option<String>,
        /// Stroke linecap.
        #[serde(skip_serializing_if = "Option::is_none")]
        strokelinecap: Option<String>,
        /// Stroke linejoin.
        #[serde(skip_serializing_if = "Option::is_none")]
        strokelinejoin: Option<String>,
    },
    /// A circle geometry.
    Circle {
        /// Center x-coordinate.
        cx: f64,
        /// Center y-coordinate.
        cy: f64,
        /// Radius.
        r: f64,
        /// Fill color.
        #[serde(skip_serializing_if = "Option::is_none")]
        fill: Option<serde_json::Value>,
        /// Stroke color.
        #[serde(skip_serializing_if = "Option::is_none")]
        stroke: Option<serde_json::Value>,
        /// Stroke width.
        #[serde(skip_serializing_if = "Option::is_none")]
        strokewidth: Option<f64>,
    },
    /// A text element.
    Text {
        /// x-coordinate.
        x: f64,
        /// y-coordinate.
        y: f64,
        /// The text content.
        text: String,
        /// Text anchor (start, middle, end).
        #[serde(rename = "textanchor", skip_serializing_if = "Option::is_none")]
        text_anchor: Option<String>,
        /// Font size.
        #[serde(rename = "fontsize", skip_serializing_if = "Option::is_none")]
        font_size: Option<f64>,
        /// Font family.
        #[serde(rename = "fontfamily", skip_serializing_if = "Option::is_none")]
        font_family: Option<String>,
        /// Font weight.
        #[serde(rename = "fontweight", skip_serializing_if = "Option::is_none")]
        font_weight: Option<String>,
        /// Fill color.
        #[serde(skip_serializing_if = "Option::is_none")]
        fill: Option<serde_json::Value>,
        /// Stroke color.
        #[serde(skip_serializing_if = "Option::is_none")]
        stroke: Option<serde_json::Value>,
    },
    /// A translation transformation.
    Translate {
        /// x-offset.
        x: f64,
        /// y-offset.
        y: f64,
        /// Nested instructions to translate.
        draw: Vec<DrawInstruction>,
    },
    /// A rotation transformation.
    Rotate {
        /// Angle in degrees.
        degree: f64,
        /// Center x of rotation.
        x: f64,
        /// Center y of rotation.
        y: f64,
        /// Nested instructions to rotate.
        draw: Vec<DrawInstruction>,
    },
    /// A scale transformation.
    Scale {
        /// Scale factor.
        factor: f64,
        /// Nested instructions to scale.
        draw: Vec<DrawInstruction>,
    },
    /// Raw SVG fragment injection.
    Svg {
        /// The SVG string.
        svg: String,
    },
}

/// A custom symbol part definition.
#[cfg(feature = "custom-parts")]
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct SymbolPart {
    /// Instructions to draw before the main icon.
    pub pre: Vec<DrawInstruction>,
    /// Instructions to draw after the main icon.
    pub post: Vec<DrawInstruction>,
    /// Bounding box of the custom part.
    pub bbox: BoundingBox,
}

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

    /// Regression test: the JS milsymbol library emits `"baseAffilation"` (one 'l') from
    /// `getMetadata()`. If this test fails it means the serde rename attribute was "fixed"
    /// without a corresponding upstream JS change, which would silently break deserialization.
    #[test]
    fn test_base_affiliation_wire_key_is_misspelled() {
        // --- serialization ---
        let meta = SymbolMetadata {
            base_affiliation: "Friend".to_string(),
            ..Default::default()
        };
        let v = serde_json::to_value(&meta).unwrap();
        assert!(
            v.get("baseAffilation").is_some(),
            "Expected key 'baseAffilation' (one l) in JSON output, found: {:?}",
            v.as_object().map(|o| o.keys().collect::<Vec<_>>())
        );
        assert!(
            v.get("baseAffiliation").is_none(),
            "Unexpected key 'baseAffiliation' (two l's) in JSON output"
        );
        assert_eq!(v["baseAffilation"], "Friend");

        // --- deserialization ---
        let input = json!({
            "activity": false,
            "affiliation": "Friend",
            "baseAffilation": "Friend",
            "baseDimension": "",
            "baseGeometry": { "g": "", "bbox": { "x1": 0.0, "y1": 0.0, "x2": 0.0, "y2": 0.0 } },
            "civilian": false,
            "condition": "",
            "context": "",
            "dimension": "",
            "dimensionUnknown": false,
            "echelon": "",
            "faker": false,
            "fenintDummy": false,
            "fill": false,
            "frame": false,
            "functionid": "",
            "headquarters": false,
            "installation": false,
            "joker": false,
            "mobility": "",
            "notpresent": "",
            "numberSIDC": false,
            "space": false,
            "suspect": false,
            "taskForce": false,
            "unit": false,
            "STD2525": false
        });
        let deserialized: SymbolMetadata = serde_json::from_value(input).unwrap();
        assert_eq!(deserialized.base_affiliation, "Friend");
    }

    /// Verify that an empty `bbox: {}` object (the JS default when no geometry is found)
    /// deserializes cleanly to all-zero coordinates rather than producing an error.
    #[test]
    fn test_bounding_box_empty_object_deserializes_to_zeros() {
        let input = json!({});
        let bbox: BoundingBox = serde_json::from_value(input).unwrap();
        assert_eq!(bbox, BoundingBox { x1: 0.0, y1: 0.0, x2: 0.0, y2: 0.0 });
    }

    /// Verify that `base_geometry` is non-optional and always accessible without unwrapping,
    /// and that the JS default `{ g: "", bbox: {} }` deserializes correctly.
    #[test]
    fn test_base_geometry_is_non_optional() {
        let input = json!({
            "activity": false,
            "affiliation": "undefined",
            "baseAffilation": "",
            "baseDimension": "",
            // JS default: g is empty string, bbox is empty object
            "baseGeometry": { "g": "", "bbox": {} },
            "civilian": false,
            "condition": "",
            "context": "",
            "dimension": "undefined",
            "dimensionUnknown": false,
            "echelon": "",
            "faker": false,
            "fenintDummy": false,
            "fill": true,
            "frame": true,
            "functionid": "",
            "headquarters": false,
            "installation": false,
            "joker": false,
            "mobility": "",
            "notpresent": "",
            "numberSIDC": false,
            "space": false,
            "suspect": false,
            "taskForce": false,
            "unit": false,
            "STD2525": true
        });
        let meta: SymbolMetadata = serde_json::from_value(input).unwrap();
        // Field is directly accessible — no Option::unwrap() needed.
        assert_eq!(meta.base_geometry.bbox, BoundingBox::default());
    }
}