revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
//! Drag and Drop example
//!
//! This demonstrates the drag-and-drop system including:
//! - SortableList for reorderable items
//! - DropZone for drag targets
//! - DragContext for manual drag operations
//!
//! Run with: cargo run --example drag_drop

use revue::event::drag::{DragContext, DragData};
use revue::layout::Rect;
use revue::prelude::*;
use revue::widget::{DropZone, SortableList};

// =============================================================================
// Demo App
// =============================================================================

struct DragDropDemo {
    // Sortable list items
    tasks: Vec<String>,
    // Drop zone received items
    completed: Vec<String>,
    trash: Vec<String>,
    // Selected tab
    active_tab: usize,
    // Status message
    status: String,
}

impl DragDropDemo {
    fn new() -> Self {
        Self {
            tasks: vec![
                "Review pull request".to_string(),
                "Write documentation".to_string(),
                "Fix bug #123".to_string(),
                "Add unit tests".to_string(),
                "Refactor module".to_string(),
            ],
            completed: Vec::new(),
            trash: Vec::new(),
            active_tab: 0,
            status: "Use ↑↓ to select, Enter to drag, Tab to switch zones".to_string(),
        }
    }

    fn handle_key(&mut self, key: &Key) -> bool {
        match key {
            Key::Tab => {
                self.active_tab = (self.active_tab + 1) % 3;
                self.status = format!("Switched to tab {}", self.active_tab + 1);
                true
            }
            Key::Char('1') => {
                self.active_tab = 0;
                true
            }
            Key::Char('2') => {
                self.active_tab = 1;
                true
            }
            Key::Char('3') => {
                self.active_tab = 2;
                true
            }
            Key::Char('r') => {
                // Reset demo
                *self = Self::new();
                self.status = "Demo reset!".to_string();
                true
            }
            _ => false,
        }
    }
}

impl View for DragDropDemo {
    fn render(&self, ctx: &mut RenderContext) {
        let view = vstack()
            .gap(1)
            .child(self.render_header())
            .child(self.render_tabs())
            .child(self.render_main_content())
            .child(self.render_status())
            .child(self.render_controls());

        view.render(ctx);
    }

    fn meta(&self) -> WidgetMeta {
        WidgetMeta::new("DragDropDemo")
    }
}

impl DragDropDemo {
    fn render_header(&self) -> impl View {
        vstack()
            .child(
                Text::new("🎯 Drag & Drop Demo")
                    .bold()
                    .fg(Color::CYAN)
                    .align(Alignment::Center),
            )
            .child(Text::muted("Sortable lists and drop zones").align(Alignment::Center))
    }

    fn render_tabs(&self) -> impl View {
        hstack()
            .gap(2)
            .child(self.tab_button("Tasks", 0))
            .child(self.tab_button("Completed", 1))
            .child(self.tab_button("Trash", 2))
    }

    fn tab_button(&self, label: &str, index: usize) -> Text {
        if self.active_tab == index {
            Text::new(format!("[{}]", label)).fg(Color::CYAN).bold()
        } else {
            Text::new(format!(" {} ", label)).fg(Color::WHITE)
        }
    }

    fn render_main_content(&self) -> impl View {
        hstack()
            .gap(2)
            .child(self.render_task_list())
            .child(self.render_drop_zones())
    }

    fn render_task_list(&self) -> Border {
        let items: Vec<Text> = self
            .tasks
            .iter()
            .enumerate()
            .map(|(i, task)| {
                let prefix = if i == 0 { "" } else { "  " };
                Text::new(format!("{}{}", prefix, task))
            })
            .collect();

        let content = if items.is_empty() {
            vstack().child(Text::muted("No tasks"))
        } else {
            let mut stack = vstack();
            for item in items {
                stack = stack.child(item);
            }
            stack
        };

        Border::panel()
            .title(format!("📋 Tasks ({})", self.tasks.len()))
            .child(content)
    }

    fn render_drop_zones(&self) -> impl View {
        vstack()
            .gap(1)
            .child(
                Border::rounded()
                    .title(format!("✅ Completed ({})", self.completed.len()))
                    .fg(Color::GREEN)
                    .child(self.render_completed_items()),
            )
            .child(
                Border::rounded()
                    .title(format!("🗑️  Trash ({})", self.trash.len()))
                    .fg(Color::RED)
                    .child(self.render_trash_items()),
            )
    }

    fn render_completed_items(&self) -> impl View {
        if self.completed.is_empty() {
            vstack().child(Text::muted("Drop completed tasks here"))
        } else {
            let mut stack = vstack();
            for item in &self.completed {
                stack = stack.child(Text::new(format!("{}", item)).fg(Color::GREEN));
            }
            stack
        }
    }

    fn render_trash_items(&self) -> impl View {
        if self.trash.is_empty() {
            vstack().child(Text::muted("Drop items to delete"))
        } else {
            let mut stack = vstack();
            for item in &self.trash {
                stack = stack.child(Text::new(format!("{}", item)).fg(Color::RED));
            }
            stack
        }
    }

    fn render_status(&self) -> impl View {
        Border::single().child(
            Text::new(&self.status)
                .fg(Color::YELLOW)
                .align(Alignment::Center),
        )
    }

    fn render_controls(&self) -> impl View {
        Border::single().title("Controls").child(
            vstack()
                .child(
                    hstack()
                        .gap(4)
                        .child(Text::muted("[1-3]"))
                        .child(Text::new("Switch panels")),
                )
                .child(
                    hstack()
                        .gap(4)
                        .child(Text::muted("[Tab]"))
                        .child(Text::new("Next panel")),
                )
                .child(
                    hstack()
                        .gap(4)
                        .child(Text::muted("[r]"))
                        .child(Text::new("Reset demo")),
                )
                .child(
                    hstack()
                        .gap(4)
                        .child(Text::muted("[q]"))
                        .child(Text::new("Quit")),
                ),
        )
    }
}

// =============================================================================
// Sortable List Demo (separate view for API showcase)
// =============================================================================

struct SortableDemo {
    items: Vec<String>,
    reorder_count: usize,
}

impl SortableDemo {
    #[allow(dead_code)]
    fn new() -> Self {
        Self {
            items: vec![
                "First item".to_string(),
                "Second item".to_string(),
                "Third item".to_string(),
                "Fourth item".to_string(),
                "Fifth item".to_string(),
            ],
            reorder_count: 0,
        }
    }
}

impl View for SortableDemo {
    fn render(&self, ctx: &mut RenderContext) {
        // This demonstrates the SortableList widget API
        let _sortable = SortableList::new(self.items.clone())
            .selected_color(Color::CYAN)
            .handles(true);

        // For the demo, we'll render a simulated view
        let view = vstack()
            .gap(1)
            .child(Text::new("SortableList API Demo").bold())
            .child(Text::muted("Drag items to reorder"))
            .child(Border::single().child({
                let mut stack = vstack();
                for (i, item) in self.items.iter().enumerate() {
                    stack = stack.child(
                        hstack()
                            .gap(1)
                            .child(Text::new("").fg(Color::CYAN))
                            .child(Text::new(format!("{}. {}", i + 1, item))),
                    );
                }
                stack
            }))
            .child(Text::muted(format!(
                "Reordered {} times",
                self.reorder_count
            )));

        view.render(ctx);
    }

    fn meta(&self) -> WidgetMeta {
        WidgetMeta::new("SortableDemo")
    }
}

// =============================================================================
// DropZone Demo (separate view for API showcase)
// =============================================================================

struct DropZoneDemo {
    dropped_items: Vec<String>,
}

impl DropZoneDemo {
    #[allow(dead_code)]
    fn new() -> Self {
        Self {
            dropped_items: Vec::new(),
        }
    }
}

impl View for DropZoneDemo {
    fn render(&self, ctx: &mut RenderContext) {
        // This demonstrates the DropZone widget API
        let _dropzone = DropZone::new("Drop items here").accepts(&["text", "file", "list_item"]);

        // For the demo, we'll render a simulated view
        let view = vstack()
            .gap(1)
            .child(Text::new("DropZone API Demo").bold())
            .child(
                Border::rounded().fg(Color::CYAN).child(
                    vstack()
                        .child(Text::new("📥 Drop Zone").align(Alignment::Center))
                        .child(Text::muted("Accepts: text, file, list_item")),
                ),
            )
            .child(Text::new(format!(
                "Received {} items",
                self.dropped_items.len()
            )));

        view.render(ctx);
    }

    fn meta(&self) -> WidgetMeta {
        WidgetMeta::new("DropZoneDemo")
    }
}

// =============================================================================
// DragContext Demo (manual drag API showcase)
// =============================================================================

fn demonstrate_drag_context_api() {
    // Create a drag context
    let mut ctx = DragContext::new();

    // Start a drag operation with text data
    ctx.start_drag(DragData::text("Hello World"), 10, 5);

    // Check drag state
    assert!(ctx.is_dragging());
    assert_eq!(ctx.position(), (10, 5));

    // Update position as "mouse" moves
    ctx.update_position(15, 8);
    assert_eq!(ctx.offset(), (5, 3));

    // Register drop targets (normally done by DropZone widget)
    use revue::event::drag::DropTarget;
    let target1 = DropTarget::new(1, Rect::new(0, 0, 20, 10));
    let target2 = DropTarget::new(2, Rect::new(25, 0, 20, 10));
    ctx.register_target(target1);
    ctx.register_target(target2);

    // Check if over a target
    if ctx.is_over_target() {
        println!("Over a drop target: {:?}", ctx.hovered_target());
    }

    // End the drag (would return data if over valid target)
    let result = ctx.end_drag();
    println!("Drag result: {:?}", result);

    // Different data types
    let _text_data = DragData::text("Plain text");
    let _file_data = DragData::file("/path/to/file.txt");
    let _list_data = DragData::list_item(0, "First Item");
    let _tree_data = DragData::tree_node("node-1", "Root Node");

    // Custom data
    #[derive(Debug)]
    struct CustomItem {
        id: u64,
        name: String,
    }

    let custom = CustomItem {
        id: 42,
        name: "My Item".to_string(),
    };
    println!("Custom item: id={}, name={}", custom.id, custom.name);
    let _custom_data = DragData::new("custom", custom).with_label("My Item");
}

// =============================================================================
// Main
// =============================================================================

fn main() -> Result<()> {
    println!("🎯 Drag & Drop Example");
    println!("======================\n");
    println!("This example demonstrates:");
    println!("  • SortableList - reorderable list widget");
    println!("  • DropZone - drag target areas");
    println!("  • DragContext - manual drag state management");
    println!("  • DragData - type-safe drag payloads\n");

    // Demonstrate the API (prints to console before TUI starts)
    demonstrate_drag_context_api();

    let mut app = App::builder().build();
    let demo = DragDropDemo::new();

    app.run(demo, |event, app_view, _app| match event {
        Event::Key(key_event) => app_view.handle_key(&key_event.key),
        _ => false,
    })
}