zebflow 0.8.3

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
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
//! Platform UI component catalog — shadcn-compatible Zeb React components
//! installable into user projects at `repo/pipelines/shared/ui/`.

use std::collections::HashMap;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::platform::policy::package::{
    PackagePolicyEntry, PackageReviewOptions, review_package_entries,
};

/// One entry in the UI component catalog.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CatalogEntry {
    /// Component name slug, e.g. "button"
    pub name: String,
    /// Category group
    pub category: String,
    /// Short description
    pub description: String,
    /// Filename, e.g. "button.tsx"
    pub filename: String,
    /// True when the component already exists in the project
    #[serde(default)]
    pub installed: bool,
}

/// Result of an install operation.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CloneReport {
    pub installed: Vec<String>,
    pub skipped: Vec<String>,
}

/// Policy review for installing built-in UI components through Add+.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct UiInstallReview {
    pub source: String,
    pub asset_kind: String,
    pub install_root: String,
    pub components: Vec<String>,
    pub files_added: Vec<String>,
    pub files_overwritten: Vec<String>,
    pub files_skipped: Vec<String>,
    pub nodes_used: Vec<String>,
    pub credentials_required: Vec<String>,
    pub external_urls: Vec<String>,
    pub database_effects: Vec<String>,
    pub filesystem_effects: Vec<String>,
    pub public_endpoints: Vec<String>,
    pub schedules: Vec<String>,
    pub large_files: Vec<String>,
    pub seed_data: Vec<String>,
    pub warnings: Vec<String>,
    pub risk_level: String,
}

/// Request to install UI components.
#[derive(Debug, Serialize, Deserialize)]
pub struct InstallUiRequest {
    pub names: Vec<String>,
    #[serde(default)]
    pub overwrite: bool,
}

// ── Embedded component sources ────────────────────────────────────────────────

macro_rules! ui_sources {
    ( $( ($name:expr, $file:expr, $cat:expr, $desc:expr) ),* $(,)? ) => {
        &[
            $(
                ($name, include_str!(concat!("ui/", $file)), $file, $cat, $desc),
            )*
        ]
    };
}

/// `(name, source, filename, category, description)`
static UI_SOURCES: &[(&str, &str, &str, &str, &str)] = ui_sources![
    // Primitives
    (
        "button",
        "button.tsx",
        "primitives",
        "Accessible button with variant and size props"
    ),
    (
        "input",
        "input.tsx",
        "primitives",
        "Text input with consistent styling"
    ),
    (
        "textarea",
        "textarea.tsx",
        "primitives",
        "Multi-line text input"
    ),
    (
        "label",
        "label.tsx",
        "primitives",
        "Form label with peer-disabled support"
    ),
    (
        "checkbox",
        "checkbox.tsx",
        "primitives",
        "Checkbox with onCheckedChange API"
    ),
    (
        "radio-group",
        "radio-group.tsx",
        "primitives",
        "Radio group with single selection"
    ),
    (
        "switch",
        "switch.tsx",
        "primitives",
        "Toggle switch with checked/onCheckedChange"
    ),
    (
        "slider",
        "slider.tsx",
        "primitives",
        "Range slider with onValueChange"
    ),
    // Display
    (
        "badge",
        "badge.tsx",
        "display",
        "Inline status badge with variants"
    ),
    (
        "avatar",
        "avatar.tsx",
        "display",
        "Avatar with image and fallback"
    ),
    ("progress", "progress.tsx", "display", "Progress bar 0–100"),
    (
        "skeleton",
        "skeleton.tsx",
        "display",
        "Loading skeleton placeholder"
    ),
    (
        "separator",
        "separator.tsx",
        "display",
        "Horizontal or vertical divider"
    ),
    ("kbd", "kbd.tsx", "display", "Keyboard shortcut display"),
    (
        "alert",
        "alert.tsx",
        "display",
        "Alert banner with title and description"
    ),
    // Layout
    (
        "card",
        "card.tsx",
        "layout",
        "Card with header, content, and footer"
    ),
    (
        "table",
        "table.tsx",
        "layout",
        "Styled HTML table with all sub-parts"
    ),
    (
        "tabs",
        "tabs.tsx",
        "layout",
        "Tab panels with internal active state"
    ),
    (
        "accordion",
        "accordion.tsx",
        "layout",
        "Collapsible accordion, single or multiple"
    ),
    (
        "collapsible",
        "collapsible.tsx",
        "layout",
        "Simple open/close collapsible container"
    ),
    (
        "scroll-area",
        "scroll-area.tsx",
        "layout",
        "Styled scrollable container"
    ),
    // Navigation
    (
        "breadcrumb",
        "breadcrumb.tsx",
        "navigation",
        "Breadcrumb nav with all sub-parts"
    ),
    (
        "pagination",
        "pagination.tsx",
        "navigation",
        "Page pagination with previous/next"
    ),
    (
        "toggle",
        "toggle.tsx",
        "navigation",
        "Pressable toggle button"
    ),
    (
        "toggle-group",
        "toggle-group.tsx",
        "navigation",
        "Toggle group with single or multiple selection"
    ),
    // Overlay
    (
        "dialog",
        "dialog.tsx",
        "overlay",
        "Modal dialog with backdrop and close button"
    ),
    (
        "alert-dialog",
        "alert-dialog.tsx",
        "overlay",
        "Confirmation dialog, no outside-click dismiss"
    ),
    (
        "sheet",
        "sheet.tsx",
        "overlay",
        "Slide-in panel from any edge"
    ),
    ("drawer", "drawer.tsx", "overlay", "Bottom drawer sheet"),
    (
        "popover",
        "popover.tsx",
        "overlay",
        "Anchored popover panel"
    ),
    (
        "hover-card",
        "hover-card.tsx",
        "overlay",
        "Content card shown on hover"
    ),
    (
        "tooltip",
        "tooltip.tsx",
        "overlay",
        "Tooltip shown on hover/focus"
    ),
    (
        "dropdown-menu",
        "dropdown-menu.tsx",
        "overlay",
        "Dropdown menu with items, checkboxes, radios"
    ),
    // Complex
    (
        "select",
        "select.tsx",
        "complex",
        "Custom select with item list"
    ),
    (
        "sonner",
        "sonner.tsx",
        "complex",
        "Toast notifications with queue"
    ),
    (
        "input-otp",
        "input-otp.tsx",
        "complex",
        "OTP input with auto-advance slots"
    ),
    (
        "calendar",
        "calendar.tsx",
        "complex",
        "Month calendar with date selection"
    ),
    (
        "data-table",
        "data-table.tsx",
        "complex",
        "Table with sorting, filtering, pagination"
    ),
];

// ── CatalogService ─────────────────────────────────────────────────────────────

pub struct CatalogService;

impl CatalogService {
    /// Return all UI catalog entries (without presence info).
    pub fn list_ui() -> Vec<CatalogEntry> {
        UI_SOURCES
            .iter()
            .map(|(name, _, filename, category, description)| CatalogEntry {
                name: name.to_string(),
                category: category.to_string(),
                description: description.to_string(),
                filename: filename.to_string(),
                installed: false,
            })
            .collect()
    }

    /// Return all UI catalog entries enriched with `installed` presence flag.
    pub fn list_ui_with_presence(shared_ui_dir: &PathBuf) -> Vec<CatalogEntry> {
        UI_SOURCES
            .iter()
            .map(|(name, _, filename, category, description)| {
                let installed = shared_ui_dir.join(filename).exists();
                CatalogEntry {
                    name: name.to_string(),
                    category: category.to_string(),
                    description: description.to_string(),
                    filename: filename.to_string(),
                    installed,
                }
            })
            .collect()
    }

    /// Returns a map of `name → installed` for quick lookups.
    pub fn check_presence(shared_ui_dir: &PathBuf) -> HashMap<String, bool> {
        UI_SOURCES
            .iter()
            .map(|(name, _, filename, _, _)| {
                let installed = shared_ui_dir.join(filename).exists();
                (name.to_string(), installed)
            })
            .collect()
    }

    /// Review installing UI components before writing to the project repo.
    pub fn review_ui(
        names: &[String],
        shared_ui_dir: &PathBuf,
        overwrite: bool,
    ) -> UiInstallReview {
        let source_map: HashMap<&str, (&str, &str)> = UI_SOURCES
            .iter()
            .map(|(name, src, filename, _, _)| (*name, (*src, *filename)))
            .collect();

        let mut components = Vec::new();
        let mut files_added = Vec::new();
        let mut files_overwritten = Vec::new();
        let mut files_skipped = Vec::new();
        let mut warnings = Vec::new();
        let mut policy_entries = Vec::new();

        for name in names {
            let Some((src, filename)) = source_map.get(name.as_str()) else {
                warnings.push(format!("unknown UI component '{name}'"));
                continue;
            };
            components.push(name.clone());
            let rel_path = format!("pipelines/shared/ui/{filename}");
            let dest = shared_ui_dir.join(filename);
            if dest.exists() && overwrite {
                files_overwritten.push(rel_path.clone());
            } else if dest.exists() {
                files_skipped.push(rel_path.clone());
            } else {
                files_added.push(rel_path.clone());
            }
            policy_entries.push(PackagePolicyEntry {
                rel_path,
                kind: "template".to_string(),
                size_bytes: src.len(),
                content: (*src).to_string(),
            });
        }

        if components.is_empty() {
            warnings.push("no valid UI components selected".to_string());
        }
        if !files_overwritten.is_empty() {
            warnings.push("install will overwrite existing shared UI files".to_string());
        }

        let mut policy = review_package_entries(
            &policy_entries,
            warnings,
            PackageReviewOptions {
                publish_mode: true,
                ..PackageReviewOptions::default()
            },
        );
        if !files_overwritten.is_empty() && policy.risk_level == "low" {
            policy.risk_level = "medium".to_string();
        }

        UiInstallReview {
            source: "built_in".to_string(),
            asset_kind: "ui_components".to_string(),
            install_root: "pipelines/shared/ui".to_string(),
            components,
            files_added,
            files_overwritten,
            files_skipped,
            nodes_used: policy.nodes_used,
            credentials_required: policy.credentials_required,
            external_urls: policy.external_urls,
            database_effects: policy.database_effects,
            filesystem_effects: policy.filesystem_effects,
            public_endpoints: policy.public_endpoints,
            schedules: policy.schedules,
            large_files: policy.large_files,
            seed_data: policy.seed_data,
            warnings: policy.warnings,
            risk_level: policy.risk_level,
        }
    }

    /// Install the requested components into `shared_ui_dir`.
    /// Returns a `CloneReport` describing what was installed vs skipped.
    pub fn install_ui(
        names: &[String],
        shared_ui_dir: &PathBuf,
        overwrite: bool,
    ) -> Result<CloneReport, String> {
        std::fs::create_dir_all(shared_ui_dir)
            .map_err(|e| format!("Failed to create shared/ui dir: {e}"))?;

        let source_map: HashMap<&str, (&str, &str)> = UI_SOURCES
            .iter()
            .map(|(name, src, filename, _, _)| (*name, (*src, *filename)))
            .collect();

        let mut report = CloneReport::default();

        for name in names {
            let Some((src, filename)) = source_map.get(name.as_str()) else {
                continue; // Unknown component — skip silently
            };
            let dest = shared_ui_dir.join(filename);
            if dest.exists() && !overwrite {
                report.skipped.push(name.clone());
                continue;
            }
            std::fs::write(&dest, src).map_err(|e| format!("Failed to write {filename}: {e}"))?;
            report.installed.push(name.clone());
        }

        Ok(report)
    }

    /// Get source content for a single component by name.
    pub fn get_source(name: &str) -> Option<&'static str> {
        UI_SOURCES
            .iter()
            .find(|(n, _, _, _, _)| *n == name)
            .map(|(_, src, _, _, _)| *src)
    }
}

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

    fn temp_shared_ui_dir(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!("zebflow-catalog-{name}-{}", std::process::id()))
    }

    #[test]
    fn ui_install_review_reports_files_before_write() {
        let dir = temp_shared_ui_dir("review-files-before-write");
        let _ = std::fs::remove_dir_all(&dir);

        let review = CatalogService::review_ui(&["button".to_string()], &dir, false);

        assert_eq!(review.source, "built_in");
        assert_eq!(review.asset_kind, "ui_components");
        assert_eq!(review.install_root, "pipelines/shared/ui");
        assert_eq!(review.components, vec!["button"]);
        assert_eq!(review.files_added, vec!["pipelines/shared/ui/button.tsx"]);
        assert!(review.files_skipped.is_empty());
        assert!(review.files_overwritten.is_empty());
        assert_eq!(review.risk_level, "low");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn ui_install_review_reports_skip_and_overwrite() {
        let dir = temp_shared_ui_dir("review-skip-overwrite");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("button.tsx"), "local edit").unwrap();

        let skipped = CatalogService::review_ui(&["button".to_string()], &dir, false);
        assert_eq!(
            skipped.files_skipped,
            vec!["pipelines/shared/ui/button.tsx"]
        );
        assert!(skipped.files_overwritten.is_empty());

        let overwritten = CatalogService::review_ui(&["button".to_string()], &dir, true);
        assert!(overwritten.files_skipped.is_empty());
        assert_eq!(
            overwritten.files_overwritten,
            vec!["pipelines/shared/ui/button.tsx"]
        );
        assert_eq!(overwritten.risk_level, "medium");

        let _ = std::fs::remove_dir_all(&dir);
    }
}