dampen-core 0.3.2

Core parser, IR, and traits for Dampen UI framework
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
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
//! Styling system types for Dampen UI framework
//!
//! This module defines the IR types for visual styling properties including
//! backgrounds, colors, borders, shadows, opacity, and transforms.
//! All types are backend-agnostic and serializable.

use serde::{Deserialize, Serialize};

/// Complete style properties for a widget
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct StyleProperties {
    /// Background fill
    pub background: Option<Background>,
    /// Foreground/text color
    pub color: Option<Color>,
    /// Border styling
    pub border: Option<Border>,
    /// Drop shadow
    pub shadow: Option<Shadow>,
    /// Opacity (0.0 = transparent, 1.0 = opaque)
    pub opacity: Option<f32>,
    /// Visual transformations
    pub transform: Option<Transform>,
}

impl StyleProperties {
    /// Validates all style properties
    ///
    /// Returns an error if:
    /// - Opacity is not in 0.0-1.0 range
    /// - Colors are invalid
    pub fn validate(&self) -> Result<(), String> {
        if let Some(opacity) = self.opacity
            && !(0.0..=1.0).contains(&opacity)
        {
            return Err(format!("opacity must be 0.0-1.0, got {}", opacity));
        }

        if let Some(ref color) = self.color {
            color.validate()?;
        }

        if let Some(ref background) = self.background {
            background.validate()?;
        }

        if let Some(ref border) = self.border {
            border.validate()?;
        }

        Ok(())
    }
}

/// Background fill type
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Background {
    /// Solid color
    Color(Color),
    /// Gradient fill
    Gradient(Gradient),
    /// Image background
    Image { path: String, fit: ImageFit },
}

impl Background {
    pub fn validate(&self) -> Result<(), String> {
        match self {
            Background::Color(color) => color.validate(),
            Background::Gradient(gradient) => gradient.validate(),
            Background::Image { .. } => Ok(()),
        }
    }
}

/// Image fitting strategy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ImageFit {
    Fill,
    Contain,
    Cover,
    ScaleDown,
}

/// Color representation (RGBA, 0.0-1.0 range)
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    /// Parse color from CSS string
    ///
    /// Supports:
    /// - Hex: "#3498db", "#3498dbff"
    /// - RGB: "rgb(52, 152, 219)", "rgba(52, 152, 219, 0.8)"
    /// - HSL: "hsl(204, 70%, 53%)", "hsla(204, 70%, 53%, 0.8)"
    /// - Named: "red", "blue", "transparent"
    pub fn parse(s: &str) -> Result<Self, String> {
        let css_color =
            csscolorparser::parse(s).map_err(|e| format!("Invalid color '{}': {}", s, e))?;

        let [r, g, b, a] = css_color.to_array();

        Ok(Color {
            r: r as f32,
            g: g as f32,
            b: b as f32,
            a: a as f32,
        })
    }

    /// Parse color from hex string
    ///
    /// Supports:
    /// - "#RGB" (e.g., "#f00" → red)
    /// - "#RRGGBB" (e.g., "#ff0000" → red)
    /// - "#RRGGBBAA" (e.g., "#ff000080" → semi-transparent red)
    pub fn from_hex(s: &str) -> Result<Self, String> {
        let s = s.trim();
        if !s.starts_with('#') {
            return Err(format!("Invalid hex color '{}': must start with '#'", s));
        }

        let hex = &s[1..];
        let (r, g, b, a) = match hex.len() {
            3 => {
                // Expand each character to two (e.g., "f" -> "ff")
                let r = u8::from_str_radix(&format!("{}{}", &hex[0..1], &hex[0..1]), 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                let g = u8::from_str_radix(&format!("{}{}", &hex[1..2], &hex[1..2]), 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                let b = u8::from_str_radix(&format!("{}{}", &hex[2..3], &hex[2..3]), 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                (r, g, b, 255)
            }
            6 => {
                let r = u8::from_str_radix(&hex[0..2], 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                let g = u8::from_str_radix(&hex[2..4], 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                let b = u8::from_str_radix(&hex[4..6], 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                (r, g, b, 255)
            }
            8 => {
                let r = u8::from_str_radix(&hex[0..2], 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                let g = u8::from_str_radix(&hex[2..4], 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                let b = u8::from_str_radix(&hex[4..6], 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                let a = u8::from_str_radix(&hex[6..8], 16)
                    .map_err(|_| format!("Invalid hex color '{}'", s))?;
                (r, g, b, a)
            }
            _ => {
                return Err(format!(
                    "Invalid hex color '{}': expected 3, 6, or 8 hex digits",
                    s
                ));
            }
        };

        Ok(Color {
            r: r as f32 / 255.0,
            g: g as f32 / 255.0,
            b: b as f32 / 255.0,
            a: a as f32 / 255.0,
        })
    }

    /// Convert to hex string
    pub fn to_hex(&self) -> String {
        let r = (self.r.clamp(0.0, 1.0) * 255.0) as u8;
        let g = (self.g.clamp(0.0, 1.0) * 255.0) as u8;
        let b = (self.b.clamp(0.0, 1.0) * 255.0) as u8;
        format!("#{:02x}{:02x}{:02x}", r, g, b)
    }

    /// Convert to hex string with alpha channel
    pub fn to_rgba_hex(&self) -> String {
        let r = (self.r.clamp(0.0, 1.0) * 255.0) as u8;
        let g = (self.g.clamp(0.0, 1.0) * 255.0) as u8;
        let b = (self.b.clamp(0.0, 1.0) * 255.0) as u8;
        let a = (self.a.clamp(0.0, 1.0) * 255.0) as u8;
        format!("#{:02x}{:02x}{:02x}{:02x}", r, g, b, a)
    }

    /// Create color from RGB bytes (0-255 range)
    ///
    /// # Arguments
    ///
    /// * `r` - Red component (0-255)
    /// * `g` - Green component (0-255)
    /// * `b` - Blue component (0-255)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dampen_core::ir::style::Color;
    ///
    /// let color = Color::from_rgb8(52, 152, 219);
    /// assert_eq!(color.r, 52.0 / 255.0);
    /// ```
    pub fn from_rgb8(r: u8, g: u8, b: u8) -> Self {
        Self {
            r: r as f32 / 255.0,
            g: g as f32 / 255.0,
            b: b as f32 / 255.0,
            a: 1.0,
        }
    }

    /// Create color from RGBA bytes (0-255 range)
    ///
    /// # Arguments
    ///
    /// * `r` - Red component (0-255)
    /// * `g` - Green component (0-255)
    /// * `b` - Blue component (0-255)
    /// * `a` - Alpha component (0-255)
    ///
    /// # Example
    ///
    /// ```rust
    /// use dampen_core::ir::style::Color;
    ///
    /// let color = Color::from_rgba8(52, 152, 219, 200);
    /// assert_eq!(color.r, 52.0 / 255.0);
    /// assert_eq!(color.a, 200.0 / 255.0);
    /// ```
    pub fn from_rgba8(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self {
            r: r as f32 / 255.0,
            g: g as f32 / 255.0,
            b: b as f32 / 255.0,
            a: a as f32 / 255.0,
        }
    }

    /// Validate color values
    pub fn validate(&self) -> Result<(), String> {
        if self.r < 0.0 || self.r > 1.0 {
            return Err(format!("Red component out of range: {}", self.r));
        }
        if self.g < 0.0 || self.g > 1.0 {
            return Err(format!("Green component out of range: {}", self.g));
        }
        if self.b < 0.0 || self.b > 1.0 {
            return Err(format!("Blue component out of range: {}", self.b));
        }
        if self.a < 0.0 || self.a > 1.0 {
            return Err(format!("Alpha component out of range: {}", self.a));
        }
        Ok(())
    }
}

/// Gradient fill
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Gradient {
    Linear {
        angle: f32,
        stops: Vec<ColorStop>,
    },
    Radial {
        shape: RadialShape,
        stops: Vec<ColorStop>,
    },
}

impl Gradient {
    /// Validate gradient
    ///
    /// Returns an error if:
    /// - Less than 2 or more than 8 color stops (Iced limitation)
    /// - Color stop offsets not sorted or out of range
    /// - Angle not normalized
    pub fn validate(&self) -> Result<(), String> {
        let stops = match self {
            Gradient::Linear { angle, stops } => {
                // Normalize angle to 0.0-360.0
                if *angle < 0.0 || *angle > 360.0 {
                    return Err(format!("Gradient angle must be 0.0-360.0, got {}", angle));
                }
                stops
            }
            Gradient::Radial { stops, .. } => stops,
        };

        if stops.len() < 2 {
            return Err("Gradient must have at least 2 color stops".to_string());
        }

        if stops.len() > 8 {
            return Err(
                "Gradient cannot have more than 8 color stops (Iced limitation)".to_string(),
            );
        }

        let mut last_offset = -1.0;
        for stop in stops {
            if stop.offset < 0.0 || stop.offset > 1.0 {
                return Err(format!(
                    "Color stop offset must be 0.0-1.0, got {}",
                    stop.offset
                ));
            }

            if stop.offset <= last_offset {
                return Err("Color stop offsets must be in ascending order".to_string());
            }

            stop.color.validate()?;
            last_offset = stop.offset;
        }

        Ok(())
    }
}

/// Color stop for gradients
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ColorStop {
    pub color: Color,
    /// Offset in gradient (0.0 = start, 1.0 = end)
    pub offset: f32,
}

/// Radial gradient shape
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RadialShape {
    Circle,
    Ellipse,
}

/// Border styling
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Border {
    pub width: f32,
    pub color: Color,
    pub radius: BorderRadius,
    pub style: BorderStyle,
}

impl Border {
    pub fn validate(&self) -> Result<(), String> {
        if self.width < 0.0 {
            return Err(format!(
                "Border width must be non-negative, got {}",
                self.width
            ));
        }
        self.color.validate()?;
        self.radius.validate()?;
        Ok(())
    }
}

/// Border radius (corner rounding)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BorderRadius {
    pub top_left: f32,
    pub top_right: f32,
    pub bottom_right: f32,
    pub bottom_left: f32,
}

impl BorderRadius {
    /// Parse from string
    ///
    /// # Formats
    /// - `"<all>"`: All corners (e.g., "8")
    /// - `"<tl> <tr> <br> <bl>"`: Individual corners
    pub fn parse(s: &str) -> Result<Self, String> {
        let parts: Vec<&str> = s.split_whitespace().collect();

        match parts.len() {
            1 => {
                let all: f32 = parts[0]
                    .parse()
                    .map_err(|_| format!("Invalid border radius: {}", s))?;
                Ok(BorderRadius {
                    top_left: all,
                    top_right: all,
                    bottom_right: all,
                    bottom_left: all,
                })
            }
            4 => {
                let tl: f32 = parts[0]
                    .parse()
                    .map_err(|_| format!("Invalid top-left radius: {}", parts[0]))?;
                let tr: f32 = parts[1]
                    .parse()
                    .map_err(|_| format!("Invalid top-right radius: {}", parts[1]))?;
                let br: f32 = parts[2]
                    .parse()
                    .map_err(|_| format!("Invalid bottom-right radius: {}", parts[2]))?;
                let bl: f32 = parts[3]
                    .parse()
                    .map_err(|_| format!("Invalid bottom-left radius: {}", parts[3]))?;
                Ok(BorderRadius {
                    top_left: tl,
                    top_right: tr,
                    bottom_right: br,
                    bottom_left: bl,
                })
            }
            _ => Err(format!(
                "Invalid border radius format: '{}'. Expected 1 or 4 values",
                s
            )),
        }
    }

    pub fn validate(&self) -> Result<(), String> {
        if self.top_left < 0.0
            || self.top_right < 0.0
            || self.bottom_right < 0.0
            || self.bottom_left < 0.0
        {
            return Err("Border radius values must be non-negative".to_string());
        }
        Ok(())
    }
}

/// Border line style
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BorderStyle {
    Solid,
    Dashed,
    Dotted,
}

impl BorderStyle {
    pub fn parse(s: &str) -> Result<Self, String> {
        match s.trim().to_lowercase().as_str() {
            "solid" => Ok(BorderStyle::Solid),
            "dashed" => Ok(BorderStyle::Dashed),
            "dotted" => Ok(BorderStyle::Dotted),
            _ => Err(format!(
                "Invalid border style: '{}'. Expected solid, dashed, or dotted",
                s
            )),
        }
    }
}

/// Drop shadow
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Shadow {
    pub offset_x: f32,
    pub offset_y: f32,
    pub blur_radius: f32,
    pub color: Color,
}

impl Shadow {
    /// Parse from string format: "offset_x offset_y blur color"
    ///
    /// # Example
    /// ```rust
    /// use dampen_core::ir::style::Shadow;
    ///
    /// let shadow = Shadow::parse("2 2 4 #00000040").unwrap();
    /// assert_eq!(shadow.offset_x, 2.0);
    /// assert_eq!(shadow.offset_y, 2.0);
    /// assert_eq!(shadow.blur_radius, 4.0);
    /// ```
    pub fn parse(s: &str) -> Result<Self, String> {
        let parts: Vec<&str> = s.split_whitespace().collect();

        if parts.len() < 4 {
            return Err(format!(
                "Invalid shadow format: '{}'. Expected: offset_x offset_y blur color",
                s
            ));
        }

        let offset_x: f32 = parts[0]
            .parse()
            .map_err(|_| format!("Invalid offset_x: {}", parts[0]))?;
        let offset_y: f32 = parts[1]
            .parse()
            .map_err(|_| format!("Invalid offset_y: {}", parts[1]))?;
        let blur_radius: f32 = parts[2]
            .parse()
            .map_err(|_| format!("Invalid blur_radius: {}", parts[2]))?;

        // Color is everything after the first 3 parts
        let color_str = parts[3..].join(" ");
        let color = Color::parse(&color_str)?;

        Ok(Shadow {
            offset_x,
            offset_y,
            blur_radius,
            color,
        })
    }
}

/// Visual transformation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Transform {
    /// Uniform scale
    Scale(f32),
    /// Non-uniform scale
    ScaleXY { x: f32, y: f32 },
    /// Rotation in degrees
    Rotate(f32),
    /// Translation in pixels
    Translate { x: f32, y: f32 },
    /// Matrix transform
    Matrix([f32; 6]),
    /// Multiple composed transforms
    Multiple(Vec<Transform>),
}

impl Transform {
    /// Parse from string
    ///
    /// # Examples
    /// ```rust
    /// use dampen_core::ir::style::Transform;
    ///
    /// assert_eq!(Transform::parse("scale(1.2)"), Ok(Transform::Scale(1.2)));
    /// assert_eq!(Transform::parse("rotate(45)"), Ok(Transform::Rotate(45.0)));
    /// assert_eq!(Transform::parse("translate(10, 20)"), Ok(Transform::Translate { x: 10.0, y: 20.0 }));
    /// ```
    pub fn parse(s: &str) -> Result<Self, String> {
        let s = s.trim();

        // Scale
        if s.starts_with("scale(") && s.ends_with(')') {
            let inner = &s[6..s.len() - 1];
            let parts: Vec<&str> = inner.split(',').collect();
            if parts.len() == 1 {
                let value: f32 = inner
                    .parse()
                    .map_err(|_| format!("Invalid scale value: {}", s))?;
                return Ok(Transform::Scale(value));
            } else if parts.len() == 2 {
                let x: f32 = parts[0]
                    .trim()
                    .parse()
                    .map_err(|_| format!("Invalid scale x: {}", parts[0]))?;
                let y: f32 = parts[1]
                    .trim()
                    .parse()
                    .map_err(|_| format!("Invalid scale y: {}", parts[1]))?;
                return Ok(Transform::ScaleXY { x, y });
            }
        }

        // Rotate
        if s.starts_with("rotate(") && s.ends_with(')') {
            let inner = &s[7..s.len() - 1];
            let value: f32 = inner
                .parse()
                .map_err(|_| format!("Invalid rotate value: {}", s))?;
            return Ok(Transform::Rotate(value));
        }

        // Translate
        if s.starts_with("translate(") && s.ends_with(')') {
            let inner = &s[10..s.len() - 1];
            let parts: Vec<&str> = inner.split(',').collect();
            if parts.len() == 2 {
                let x: f32 = parts[0]
                    .trim()
                    .parse()
                    .map_err(|_| format!("Invalid translate x: {}", parts[0]))?;
                let y: f32 = parts[1]
                    .trim()
                    .parse()
                    .map_err(|_| format!("Invalid translate y: {}", parts[1]))?;
                return Ok(Transform::Translate { x, y });
            }
        }

        // Matrix
        if s.starts_with("matrix(") && s.ends_with(')') {
            let inner = &s[7..s.len() - 1];
            let parts: Vec<&str> = inner.split(',').collect();
            if parts.len() == 6 {
                let mut matrix = [0.0; 6];
                for (i, p) in parts.iter().enumerate() {
                    matrix[i] = p
                        .trim()
                        .parse()
                        .map_err(|_| format!("Invalid matrix value at index {}: {}", i, p))?;
                }
                return Ok(Transform::Matrix(matrix));
            }
        }

        Err(format!(
            "Invalid transform format: '{}'. Expected scale(n), scale(x, y), rotate(rad), translate(x, y), or matrix(...)",
            s
        ))
    }
}