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
use crate::ir::layout::{Breakpoint, LayoutConstraints};
use crate::ir::span::Span;
use crate::ir::style::StyleProperties;
use crate::ir::theme::WidgetState;
use std::collections::HashMap;

/// A node in the widget tree
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, Default)]
pub struct WidgetNode {
    pub kind: WidgetKind,
    pub id: Option<String>,
    pub attributes: HashMap<String, AttributeValue>,
    pub events: Vec<EventBinding>,
    pub children: Vec<WidgetNode>,
    pub span: Span,

    // Styling extensions
    pub style: Option<StyleProperties>,
    pub layout: Option<LayoutConstraints>,
    pub theme_ref: Option<AttributeValue>,
    pub classes: Vec<String>,
    pub breakpoint_attributes: HashMap<Breakpoint, HashMap<String, AttributeValue>>,
    /// State-specific styles from inline attributes (e.g., hover:background="#ff0000")
    #[serde(default)]
    pub inline_state_variants: HashMap<WidgetState, StyleProperties>,
}

/// Enumeration of all supported widget types
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, Default)]
pub enum WidgetKind {
    #[default]
    Column,
    Row,
    Container,
    Scrollable,
    Stack,
    Text,
    Image,
    Svg,
    Button,
    TextInput,
    Checkbox,
    Slider,
    PickList,
    Toggler,
    Space,
    Rule,
    Radio,
    // Advanced widgets
    ComboBox,
    ProgressBar,
    Tooltip,
    Grid,
    Canvas,
    CanvasRect,
    CanvasCircle,
    CanvasLine,
    CanvasText,
    CanvasGroup,
    /// Date selection widget with calendar overlay
    DatePicker,
    /// Time selection widget with hour/minute/second picker
    TimePicker,
    /// Color selection widget with color picker overlay
    ColorPicker,
    Menu,
    MenuItem,
    MenuSeparator,
    ContextMenu,
    Float,
    // Data display
    DataTable,
    DataColumn,
    // Tree widget
    TreeView,
    TreeNode,
    // Tab widgets
    TabBar,
    Tab,
    // Control flow
    For,
    If,
    Custom(String),
}

/// A value that can be either static or dynamically bound
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum AttributeValue {
    Static(String),
    Binding(crate::expr::BindingExpr),
    Interpolated(Vec<InterpolatedPart>),
}

impl Default for AttributeValue {
    fn default() -> Self {
        AttributeValue::Static(String::new())
    }
}

/// Part of an interpolated string
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum InterpolatedPart {
    Literal(String),
    Binding(crate::expr::BindingExpr),
}

impl Default for InterpolatedPart {
    fn default() -> Self {
        InterpolatedPart::Literal(String::new())
    }
}

/// Attribute structures for advanced widgets
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ComboBoxAttributes {
    pub options: Vec<String>,
    pub selected: Option<crate::expr::BindingExpr>,
    pub placeholder: Option<String>,
    pub on_select: Option<String>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PickListAttributes {
    pub options: Vec<String>,
    pub selected: Option<crate::expr::BindingExpr>,
    pub placeholder: Option<String>,
    pub on_select: Option<String>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CanvasAttributes {
    pub width: f32,
    pub height: f32,
    pub program: Option<crate::expr::BindingExpr>,
    pub on_click: Option<String>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ProgressBarAttributes {
    pub min: Option<f32>,
    pub max: Option<f32>,
    pub value: crate::expr::BindingExpr,
    pub style: Option<ProgressBarStyle>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ProgressBarStyle {
    Primary,
    Success,
    Warning,
    Danger,
    Secondary,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TooltipAttributes {
    pub message: String,
    pub position: Option<TooltipPosition>,
    pub delay: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum TooltipPosition {
    FollowCursor,
    Top,
    Bottom,
    Left,
    Right,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct GridAttributes {
    pub columns: u32,
    pub spacing: Option<f32>,
    pub padding: Option<f32>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FloatAttributes {
    pub position: Option<FloatPosition>,
    pub offset_x: Option<f32>,
    pub offset_y: Option<f32>,
    pub z_index: Option<u32>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum FloatPosition {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
}

/// An event binding from XML to a Rust handler
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, Default)]
pub struct EventBinding {
    pub event: EventKind,
    pub handler: String,
    /// Optional parameter expression (e.g., for on_click="delete:{item.id}")
    pub param: Option<crate::expr::BindingExpr>,
    pub span: Span,
}

/// Supported event types
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, Default)]
pub enum EventKind {
    #[default]
    Click,
    Press,
    Release,
    Change,
    Input,
    Submit,
    Select,
    Toggle,
    Scroll,
    CanvasClick,
    CanvasDrag,
    CanvasMove,
    CanvasRelease,
    RowClick,
    Cancel,
    Open,
    Close,
}

impl std::fmt::Display for WidgetKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            WidgetKind::Column => "column",
            WidgetKind::Row => "row",
            WidgetKind::Container => "container",
            WidgetKind::Scrollable => "scrollable",
            WidgetKind::Stack => "stack",
            WidgetKind::Text => "text",
            WidgetKind::Image => "image",
            WidgetKind::Svg => "svg",
            WidgetKind::Button => "button",
            WidgetKind::TextInput => "text_input",
            WidgetKind::Checkbox => "checkbox",
            WidgetKind::Slider => "slider",
            WidgetKind::PickList => "pick_list",
            WidgetKind::Toggler => "toggler",
            WidgetKind::Space => "space",
            WidgetKind::Rule => "rule",
            WidgetKind::Radio => "radio",
            WidgetKind::ComboBox => "combobox",
            WidgetKind::ProgressBar => "progress_bar",
            WidgetKind::Tooltip => "tooltip",
            WidgetKind::Grid => "grid",
            WidgetKind::Canvas => "canvas",
            WidgetKind::CanvasRect => "rect",
            WidgetKind::CanvasCircle => "circle",
            WidgetKind::CanvasLine => "line",
            WidgetKind::CanvasText => "canvas_text",
            WidgetKind::CanvasGroup => "group",
            WidgetKind::DatePicker => "date_picker",
            WidgetKind::TimePicker => "time_picker",
            WidgetKind::ColorPicker => "color_picker",
            WidgetKind::Menu => "menu",
            WidgetKind::MenuItem => "menu_item",
            WidgetKind::MenuSeparator => "menu_separator",
            WidgetKind::ContextMenu => "context_menu",
            WidgetKind::Float => "float",
            WidgetKind::DataTable => "data_table",
            WidgetKind::DataColumn => "data_column",
            WidgetKind::TreeView => "tree_view",
            WidgetKind::TreeNode => "tree_node",
            WidgetKind::TabBar => "tab_bar",
            WidgetKind::Tab => "tab",
            WidgetKind::For => "for",
            WidgetKind::If => "if",
            WidgetKind::Custom(name) => return write!(f, "{}", name),
        };
        write!(f, "{}", name)
    }
}

impl WidgetKind {
    /// Returns a list of all standard widget tag names.
    pub fn all_standard() -> &'static [&'static str] {
        &[
            "column",
            "row",
            "container",
            "scrollable",
            "stack",
            "text",
            "image",
            "svg",
            "button",
            "text_input",
            "checkbox",
            "slider",
            "pick_list",
            "toggler",
            "space",
            "rule",
            "radio",
            "combobox",
            "progress_bar",
            "tooltip",
            "grid",
            "canvas",
            "rect",
            "circle",
            "line",
            "canvas_text",
            "group",
            "date_picker",
            "time_picker",
            "color_picker",
            "menu",
            "menu_item",
            "menu_separator",
            "context_menu",
            "float",
            "data_table",
            "data_column",
            "tree_view",
            "tree_node",
            "tab_bar",
            "tab",
            "for",
            "if",
        ]
    }

    /// Returns true if this is a custom widget.
    pub fn is_custom(&self) -> bool {
        matches!(self, WidgetKind::Custom(_))
    }

    /// Returns the minimum schema version required for this widget type.
    ///
    /// This method provides infrastructure for version-gating widgets in future releases.
    /// Currently, all widgets return version 1.0 as they are part of the initial release.
    ///
    /// # Future Usage
    ///
    /// When new widgets are added in future schema versions (e.g., 1.1, 1.2), this method
    /// will be updated to return the appropriate minimum version for those widgets.
    /// The parser can then validate that documents declaring older schema versions
    /// do not use widgets that were introduced in later versions.
    ///
    /// # Examples
    ///
    /// ```
    /// use dampen_core::{WidgetKind, SchemaVersion};
    ///
    /// let column = WidgetKind::Column;
    /// assert_eq!(column.minimum_version(), SchemaVersion { major: 1, minor: 0 });
    /// ```
    ///
    /// # Returns
    ///
    /// The minimum `SchemaVersion` required to use this widget type.
    pub fn minimum_version(&self) -> crate::ir::SchemaVersion {
        // Canvas is a v1.1 widget (experimental, not fully functional)
        // All other widgets are part of v1.0
        match self {
            WidgetKind::Canvas => crate::ir::SchemaVersion { major: 1, minor: 1 },
            WidgetKind::DatePicker
            | WidgetKind::TimePicker
            | WidgetKind::ColorPicker
            | WidgetKind::Menu
            | WidgetKind::MenuItem
            | WidgetKind::MenuSeparator
            | WidgetKind::ContextMenu
            | WidgetKind::DataTable
            | WidgetKind::DataColumn
            | WidgetKind::TreeView
            | WidgetKind::TreeNode
            | WidgetKind::TabBar
            | WidgetKind::Tab => crate::ir::SchemaVersion { major: 1, minor: 1 },
            _ => crate::ir::SchemaVersion { major: 1, minor: 0 },
        }
    }

    /// Returns the validation schema for this widget type.
    pub fn schema(&self) -> crate::schema::WidgetSchema {
        crate::schema::get_widget_schema(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::style::StyleProperties;
    use crate::ir::theme::WidgetState;

    #[test]
    fn test_widget_node_default_has_empty_inline_state_variants() {
        let node = WidgetNode::default();
        assert!(node.inline_state_variants.is_empty());
    }

    #[test]
    fn test_widget_node_inline_state_variants_serialization() {
        let mut node = WidgetNode {
            kind: WidgetKind::Button,
            id: Some("test-button".to_string()),
            attributes: Default::default(),
            events: Default::default(),
            children: Default::default(),
            span: Default::default(),
            style: Default::default(),
            layout: Default::default(),
            theme_ref: Default::default(),
            classes: Default::default(),
            breakpoint_attributes: Default::default(),
            inline_state_variants: Default::default(),
        };

        // Add state variant
        node.inline_state_variants.insert(
            WidgetState::Hover,
            StyleProperties {
                opacity: Some(0.8),
                ..Default::default()
            },
        );

        // Serialize and deserialize
        let json = serde_json::to_string(&node).expect("Should serialize");
        let deserialized: WidgetNode = serde_json::from_str(&json).expect("Should deserialize");

        // Verify field preserved
        assert_eq!(deserialized.inline_state_variants.len(), 1);
        assert!(
            deserialized
                .inline_state_variants
                .contains_key(&WidgetState::Hover)
        );
    }

    #[test]
    fn test_widget_node_inline_state_variants_multiple_states() {
        let mut node = WidgetNode::default();

        node.inline_state_variants.insert(
            WidgetState::Hover,
            StyleProperties {
                opacity: Some(0.9),
                ..Default::default()
            },
        );

        node.inline_state_variants.insert(
            WidgetState::Active,
            StyleProperties {
                opacity: Some(0.7),
                ..Default::default()
            },
        );

        node.inline_state_variants.insert(
            WidgetState::Disabled,
            StyleProperties {
                opacity: Some(0.5),
                ..Default::default()
            },
        );

        assert_eq!(node.inline_state_variants.len(), 3);
        assert!(node.inline_state_variants.contains_key(&WidgetState::Hover));
        assert!(
            node.inline_state_variants
                .contains_key(&WidgetState::Active)
        );
        assert!(
            node.inline_state_variants
                .contains_key(&WidgetState::Disabled)
        );
    }
}

// Canvas Shape Types

/// A declarative representation of a shape in a canvas widget.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum CanvasShape {
    /// A rectangle shape.
    Rect(RectShape),
    /// A circle shape.
    Circle(CircleShape),
    /// A line segment.
    Line(LineShape),
    /// Text drawn on the canvas.
    Text(TextShape),
    /// A group of shapes with a common transformation.
    Group(GroupShape),
}

/// Attributes for a declarative rectangle shape.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct RectShape {
    /// The X coordinate of the top-left corner.
    pub x: AttributeValue,
    /// The Y coordinate of the top-left corner.
    pub y: AttributeValue,
    /// The width of the rectangle.
    pub width: AttributeValue,
    /// The height of the rectangle.
    pub height: AttributeValue,
    /// The fill color.
    pub fill: Option<AttributeValue>,
    /// The stroke color.
    pub stroke: Option<AttributeValue>,
    /// The width of the stroke.
    pub stroke_width: Option<AttributeValue>,
    /// The corner radius for rounded rectangles.
    pub radius: Option<AttributeValue>,
}

/// Attributes for a declarative circle shape.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CircleShape {
    /// The X coordinate of the center.
    pub cx: AttributeValue,
    /// The Y coordinate of the center.
    pub cy: AttributeValue,
    /// The radius of the circle.
    pub radius: AttributeValue,
    /// The fill color.
    pub fill: Option<AttributeValue>,
    /// The stroke color.
    pub stroke: Option<AttributeValue>,
    /// The width of the stroke.
    pub stroke_width: Option<AttributeValue>,
}

/// Attributes for a declarative line shape.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct LineShape {
    /// The X coordinate of the starting point.
    pub x1: AttributeValue,
    /// The Y coordinate of the starting point.
    pub y1: AttributeValue,
    /// The X coordinate of the ending point.
    pub x2: AttributeValue,
    /// The Y coordinate of the ending point.
    pub y2: AttributeValue,
    /// The stroke color.
    pub stroke: Option<AttributeValue>,
    /// The width of the stroke.
    pub stroke_width: Option<AttributeValue>,
}

/// Attributes for a declarative text element.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TextShape {
    /// The X coordinate of the text baseline.
    pub x: AttributeValue,
    /// The Y coordinate of the text baseline.
    pub y: AttributeValue,
    /// The content to be displayed.
    pub content: AttributeValue,
    /// The font size.
    pub size: Option<AttributeValue>,
    /// The text color.
    pub color: Option<AttributeValue>,
}

/// Attributes for a group of canvas shapes.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct GroupShape {
    /// An optional transformation to apply to all child shapes.
    pub transform: Option<Transform>,
    /// The child shapes within this group.
    pub children: Vec<CanvasShape>,
}

/// Geometric transformations for canvas groups.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Transform {
    /// Translate by (x, y).
    Translate(f32, f32),
    /// Rotate by an angle in radians.
    Rotate(f32),
    /// Uniformly scale.
    Scale(f32),
    /// Scale non-uniformly by (x, y).
    ScaleXY(f32, f32),
    /// A 2D transformation matrix.
    Matrix([f32; 6]),
}