deweygui 1.0.0

An agentic-first GUI framework with pluggable rendering backends and complete ontology for AI agent discoverability
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
//! Date/time picker widget — a calendar-style date selector.

use crate::core::style::{Color, FontWeight, Style, TextStyle};
use crate::core::{Position, Rect};
use crate::ontology::*;
use crate::runtime::Frame;
use crate::widget::StatefulWidget;

/// A date value (year, month 1-12, day 1-31).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DateValue {
    pub year: i32,
    pub month: u32,
    pub day: u32,
}

impl DateValue {
    #[must_use]
    pub fn new(year: i32, month: u32, day: u32) -> Self {
        Self { year, month, day }
    }

    /// Number of days in this date's month.
    pub fn days_in_month(&self) -> u32 {
        match self.month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 => {
                if self.is_leap_year() {
                    29
                } else {
                    28
                }
            }
            _ => 30,
        }
    }

    fn is_leap_year(&self) -> bool {
        (self.year % 4 == 0 && self.year % 100 != 0) || self.year % 400 == 0
    }

    /// Day of week for the 1st of this month (0 = Monday, 6 = Sunday).
    /// Uses Tomohiko Sakamoto's algorithm.
    pub fn first_weekday(&self) -> u32 {
        let y = if self.month <= 2 {
            self.year - 1
        } else {
            self.year
        };
        let m = self.month as i32;
        let t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
        let idx = (m - 1) as usize;
        let dow = (y + y / 4 - y / 100 + y / 400 + t[idx] + 1) % 7;
        // Convert: 0=Sun → Mon-based: 0=Mon
        ((dow + 6) % 7) as u32
    }

    /// Month name.
    pub fn month_name(&self) -> &'static str {
        match self.month {
            1 => "January",
            2 => "February",
            3 => "March",
            4 => "April",
            5 => "May",
            6 => "June",
            7 => "July",
            8 => "August",
            9 => "September",
            10 => "October",
            11 => "November",
            12 => "December",
            _ => "Unknown",
        }
    }

    /// Format as YYYY-MM-DD.
    pub fn to_iso(&self) -> String {
        format!("{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }
}

impl std::fmt::Display for DateValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_iso())
    }
}

/// State for the date picker widget.
pub struct DatePickerState {
    /// The currently selected date.
    pub selected: DateValue,
    /// The month being viewed (may differ from selected).
    pub view_year: i32,
    pub view_month: u32,
    /// Whether the calendar popup is open.
    pub open: bool,
}

impl DatePickerState {
    #[must_use]
    pub fn new(year: i32, month: u32, day: u32) -> Self {
        Self {
            selected: DateValue::new(year, month, day),
            view_year: year,
            view_month: month,
            open: false,
        }
    }

    /// Navigate to the previous month.
    pub fn prev_month(&mut self) {
        if self.view_month == 1 {
            self.view_month = 12;
            self.view_year -= 1;
        } else {
            self.view_month -= 1;
        }
    }

    /// Navigate to the next month.
    pub fn next_month(&mut self) {
        if self.view_month == 12 {
            self.view_month = 1;
            self.view_year += 1;
        } else {
            self.view_month += 1;
        }
    }

    /// Select a specific day in the current view month.
    pub fn select_day(&mut self, day: u32) {
        self.selected = DateValue::new(self.view_year, self.view_month, day);
    }

    /// Toggle the open state.
    pub fn toggle(&mut self) {
        self.open = !self.open;
    }
}

impl Default for DatePickerState {
    fn default() -> Self {
        Self::new(2025, 1, 1)
    }
}

/// A date picker widget showing a calendar grid.
pub struct DatePicker {
    style: Style,
    agent_id: String,
    label: String,
}

impl DatePicker {
    pub fn new() -> Self {
        Self {
            style: Style::default(),
            agent_id: String::new(),
            label: "Select date".to_string(),
        }
    }

    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    pub fn fg(mut self, color: Color) -> Self {
        self.style.foreground = Some(color);
        self
    }

    pub fn bg(mut self, color: Color) -> Self {
        self.style.background = Some(color);
        self
    }

    pub fn agent_id(mut self, id: impl Into<String>) -> Self {
        self.agent_id = id.into();
        self
    }
}

impl Default for DatePicker {
    fn default() -> Self {
        Self::new()
    }
}

impl Discoverable for DatePicker {
    fn schema(&self) -> WidgetSchema {
        let mut schema = WidgetSchema::new(
            "DatePicker",
            "A calendar-style date picker",
            SemanticRole::Input,
        );
        schema.usage_hint = Some("DatePicker::new(\"Birthday\").agent_id(\"bday\")".into());
        schema.tags = vec!["date".into(), "picker".into(), "calendar".into()];
        schema
    }

    fn capabilities(&self) -> Vec<AgentCapability> {
        vec![AgentCapability::Focusable, AgentCapability::Clickable]
    }

    fn actions(&self) -> Vec<AgentAction> {
        vec![
            AgentAction::with_params(
                "set_date",
                "Set the selected date",
                vec![
                    ActionParam::required("year", "Year", ActionParamType::Integer),
                    ActionParam::required("month", "Month (1-12)", ActionParamType::Integer),
                    ActionParam::required("day", "Day (1-31)", ActionParamType::Integer),
                ],
                true,
            ),
            AgentAction::simple("prev_month", "Navigate to previous month", true),
            AgentAction::simple("next_month", "Navigate to next month", true),
            AgentAction::simple("toggle", "Toggle calendar open/closed", true),
        ]
    }

    fn semantic_role(&self) -> SemanticRole {
        SemanticRole::Input
    }

    fn agent_state(&self) -> serde_json::Value {
        serde_json::json!({
            "label": self.label,
            "note": "Use DatePickerState for selected date; see UiTree for live state",
        })
    }

    fn execute_action(
        &mut self,
        _action: &str,
        _params: &serde_json::Value,
    ) -> Result<serde_json::Value, String> {
        Err("Use StatefulWidget for state mutations".to_string())
    }

    fn agent_id(&self) -> Option<&str> {
        if self.agent_id.is_empty() {
            None
        } else {
            Some(&self.agent_id)
        }
    }

    fn accessibility_label(&self) -> Option<String> {
        Some(self.label.clone())
    }
}

impl Discoverable for DatePickerState {
    fn schema(&self) -> WidgetSchema {
        WidgetSchema::new(
            "DatePickerState",
            "The mutable state of a DatePicker, holding selected date and calendar view",
            SemanticRole::Input,
        )
    }

    fn capabilities(&self) -> Vec<AgentCapability> {
        vec![AgentCapability::Focusable, AgentCapability::Clickable]
    }

    fn actions(&self) -> Vec<AgentAction> {
        vec![
            AgentAction::with_params(
                "set_date",
                "Set the selected date",
                vec![
                    ActionParam::required("year", "Year", ActionParamType::Integer),
                    ActionParam::required("month", "Month (1-12)", ActionParamType::Integer),
                    ActionParam::required("day", "Day (1-31)", ActionParamType::Integer),
                ],
                true,
            ),
            AgentAction::simple("prev_month", "Navigate to previous month", true),
            AgentAction::simple("next_month", "Navigate to next month", true),
            AgentAction::simple("toggle", "Toggle calendar open/closed", true),
        ]
    }

    fn semantic_role(&self) -> SemanticRole {
        SemanticRole::Input
    }

    fn agent_state(&self) -> serde_json::Value {
        serde_json::json!({
            "selected": self.selected.to_iso(),
            "view_year": self.view_year,
            "view_month": self.view_month,
            "open": self.open,
        })
    }

    fn execute_action(
        &mut self,
        action: &str,
        params: &serde_json::Value,
    ) -> Result<serde_json::Value, String> {
        match action {
            "set_date" => {
                let year = params["year"].as_i64().ok_or("missing year")? as i32;
                let month = params["month"].as_u64().ok_or("missing month")? as u32;
                let day = params["day"].as_u64().ok_or("missing day")? as u32;
                if !(1..=12).contains(&month) {
                    return Err("month must be 1-12".to_string());
                }
                if !(1..=31).contains(&day) {
                    return Err("day must be 1-31".to_string());
                }
                self.selected = DateValue::new(year, month, day);
                Ok(serde_json::json!({ "selected": self.selected.to_iso() }))
            }
            "prev_month" => {
                self.prev_month();
                Ok(serde_json::json!({
                    "view_year": self.view_year,
                    "view_month": self.view_month,
                }))
            }
            "next_month" => {
                self.next_month();
                Ok(serde_json::json!({
                    "view_year": self.view_year,
                    "view_month": self.view_month,
                }))
            }
            "toggle" => {
                self.toggle();
                Ok(serde_json::json!({ "open": self.open }))
            }
            _ => Err(format!("Unknown action: {action}")),
        }
    }
}

impl StatefulWidget for DatePicker {
    type State = DatePickerState;

    fn render(self, area: Rect, frame: &mut Frame<'_>, state: &mut DatePickerState) {
        let ts = self.style.resolved_text();

        if !self.agent_id.is_empty() {
            let node = UiNode::new("DatePicker", SemanticRole::Input)
                .with_id(&self.agent_id)
                .with_bounds(area.into())
                .with_property("selected", serde_json::json!(state.selected.to_iso()))
                .with_property("open", serde_json::json!(state.open))
                .with_property(
                    "view_month",
                    serde_json::json!(format!(
                        "{} {}",
                        DateValue::new(state.view_year, state.view_month, 1).month_name(),
                        state.view_year
                    )),
                );
            frame.register_widget(node);
            frame.register_hitbox(&self.agent_id, area, 1);
        }

        // Date display row
        let display_text = format!("{}: {}", self.label, state.selected.to_iso());
        frame.painter().fill_rect(
            Rect::new(area.x, area.y, area.width, 28.0),
            Color::DARK_GRAY,
            4.0,
        );
        frame.painter().text(
            Position::new(area.x + 8.0, area.y + 6.0),
            &display_text,
            &ts,
        );

        if !state.open {
            return;
        }

        // Calendar grid
        let cal_y = area.y + 32.0;
        let cell_w = area.width / 7.0;
        let cell_h = 24.0;

        // Month/year header
        let view_date = DateValue::new(state.view_year, state.view_month, 1);
        let header = format!("{} {}", view_date.month_name(), state.view_year);
        let header_ts = TextStyle {
            font_size: 14.0,
            color: Color::WHITE,
            weight: FontWeight::Bold,
            ..Default::default()
        };
        frame.painter().fill_rect(
            Rect::new(area.x, cal_y, area.width, cell_h),
            Color::rgba(0.15, 0.15, 0.2, 1.0),
            0.0,
        );
        frame.painter().text(
            Position::new(area.x + 8.0, cal_y + 4.0),
            &header,
            &header_ts,
        );

        // Day-of-week headers
        let dow_y = cal_y + cell_h;
        let dow_ts = TextStyle {
            font_size: 12.0,
            color: Color::LIGHT_GRAY,
            weight: FontWeight::Bold,
            ..Default::default()
        };
        for (i, name) in ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]
            .iter()
            .enumerate()
        {
            let x = area.x + i as f32 * cell_w;
            frame.painter().text(
                Position::new(x + cell_w / 2.0 - 6.0, dow_y + 4.0),
                name,
                &dow_ts,
            );
        }

        // Day grid
        let first_dow = view_date.first_weekday();
        let days_in_month = view_date.days_in_month();
        let grid_y = dow_y + cell_h;

        let day_ts = TextStyle {
            font_size: 13.0,
            color: Color::WHITE,
            ..Default::default()
        };
        let selected_ts = TextStyle {
            font_size: 13.0,
            color: Color::WHITE,
            weight: FontWeight::Bold,
            ..Default::default()
        };

        for day in 1..=days_in_month {
            let cell_idx = (first_dow + day - 1) as f32;
            let col = cell_idx % 7.0;
            let row = (cell_idx / 7.0).floor();
            let cx = area.x + col * cell_w;
            let cy = grid_y + row * cell_h;

            let is_selected = state.selected.year == state.view_year
                && state.selected.month == state.view_month
                && state.selected.day == day;

            if is_selected {
                frame.painter().fill_circle(
                    Position::new(cx + cell_w / 2.0, cy + cell_h / 2.0),
                    10.0,
                    Color::rgba(0.35, 0.55, 0.95, 1.0),
                );
                frame.painter().text(
                    Position::new(cx + cell_w / 2.0 - 6.0, cy + 4.0),
                    &day.to_string(),
                    &selected_ts,
                );
            } else {
                frame.painter().text(
                    Position::new(cx + cell_w / 2.0 - 6.0, cy + 4.0),
                    &day.to_string(),
                    &day_ts,
                );
            }
        }
    }
}

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

    #[test]
    fn date_value_days_in_month() {
        assert_eq!(DateValue::new(2024, 2, 1).days_in_month(), 29); // leap
        assert_eq!(DateValue::new(2023, 2, 1).days_in_month(), 28);
        assert_eq!(DateValue::new(2024, 1, 1).days_in_month(), 31);
        assert_eq!(DateValue::new(2024, 4, 1).days_in_month(), 30);
    }

    #[test]
    fn date_value_iso() {
        assert_eq!(DateValue::new(2025, 6, 15).to_iso(), "2025-06-15");
    }

    #[test]
    fn state_navigation() {
        let mut state = DatePickerState::new(2025, 1, 15);
        state.prev_month();
        assert_eq!(state.view_month, 12);
        assert_eq!(state.view_year, 2024);
        state.next_month();
        assert_eq!(state.view_month, 1);
        assert_eq!(state.view_year, 2025);
    }
}