gilt 0.11.2

Fast, beautiful terminal formatting for Rust — styles, tables, trees, syntax highlighting, progress bars, markdown.
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
//! Protocol utilities for third-party crate interoperability.
//!
//! This module provides utilities for checking renderability, casting objects,
//! and converting types to renderable representations. It implements Rust equivalents
//! of Python's `__gilt__` protocol from the library.
//!
//! # The `__gilt__` Protocol
//!
//! In Python's library, objects can implement a `__gilt__` method that returns
//! a renderable representation. This module brings that same concept to Rust through
//! the [`GiltCast`] trait.
//!
//! ## Key Types
//!
//! - [`GiltCast`] - The core trait for objects that can be converted to renderables.
//!   Implement this on your types to make them printable with gilt.
//! - [`IntoRenderable`] - A conversion trait that allows any `GiltCast` type to be
//!   converted to a `Box<dyn Renderable>`.
//! - [`gilt_cast`] - Attempt to downcast a `Box<dyn Any>` to a concrete renderable type.
//! - [`RenderableBox`] - A type-erased wrapper for renderable values.
//!
//! # Examples
//!
//! ```
//! use gilt::protocol::{GiltCast, IntoRenderable};
//! use gilt::prelude::*;
//!
//! // Implement GiltCast for a custom type
//! struct MyData {
//!     name: String,
//!     value: i32,
//! }
//!
//! impl GiltCast for MyData {
//!     fn __gilt__(self) -> Box<dyn gilt::console::Renderable> {
//!         let text = Text::from(format!("{} = {}", self.name, self.value));
//!         Box::new(Panel::new(text))
//!     }
//! }
//!
//! // Now MyData can be converted to a renderable
//! let data = MyData { name: "count".into(), value: 42 };
//! let renderable = data.into_renderable();
//! ```

use std::any::Any;

use crate::console::Renderable;

/// Attempt to cast a `Box<dyn Any>` to a concrete renderable type.
///
/// This function is useful when you have a boxed `Any` trait object and want to
/// downcast it to a specific renderable type. It returns `None` if the type
/// doesn't match.
///
/// # Type Parameters
///
/// * `T` - The concrete renderable type to cast to. Must implement `Renderable`.
///
/// # Parameters
///
/// * `value` - The boxed `Any` value to cast.
///
/// # Returns
///
/// Returns `Some(Box<T>)` if the cast succeeds, `None` otherwise.
///
/// # Examples
///
/// ```
/// use gilt::protocol::gilt_cast;
/// use gilt::prelude::*;
///
/// // Create a boxed Text
/// let text: Box<dyn std::any::Any> = Box::new(Text::from("Hello"));
///
/// // Try to cast it back to Text
/// if let Some(text) = gilt_cast::<Text>(text) {
///     println!("Successfully cast to Text");
/// }
///
/// // Trying to cast to wrong type returns None
/// let text: Box<dyn std::any::Any> = Box::new(Text::from("Hello"));
/// assert!(gilt_cast::<Panel>(text).is_none());
/// ```
pub fn gilt_cast<T: Renderable + 'static>(value: Box<dyn Any>) -> Option<Box<T>> {
    value.downcast::<T>().ok()
}

/// Check if a value is a specific renderable type.
///
/// This is a convenience function that attempts to downcast and returns
/// a boolean indicating success.
///
/// # Examples
///
/// ```
/// use gilt::protocol::{is_type, gilt_cast};
/// use gilt::prelude::*;
///
/// let text: Box<dyn std::any::Any> = Box::new(Text::from("Hello"));
/// assert!(is_type::<Text>(&*text));
/// assert!(!is_type::<Panel>(&*text));
/// ```
pub fn is_type<T: 'static>(value: &dyn Any) -> bool {
    value.is::<T>()
}

/// Trait for types that can be converted to a renderable representation.
///
/// This is the Rust equivalent of Python's `__gilt__` protocol. Implement this
/// trait on your custom types to make them convertible to renderable widgets.
///
/// Once implemented, your type automatically implements [`IntoRenderable`] and
/// can be converted to a `Box<dyn Renderable>`.
///
/// # Examples
///
/// ```
/// use gilt::protocol::{GiltCast, IntoRenderable};
/// use gilt::prelude::*;
///
/// struct User {
///     name: String,
///     email: String,
///     active: bool,
/// }
///
/// impl GiltCast for User {
///     fn __gilt__(self) -> Box<dyn gilt::console::Renderable> {
///         let status = if self.active { "✓ Active" } else { "✗ Inactive" };
///         let content = Text::from(format!(
///             "Name: {}\nEmail: {}\nStatus: {}",
///             self.name, self.email, status
///         ));
///         Box::new(Panel::new(content).with_title("User Profile"))
///     }
/// }
///
/// let user = User {
///     name: "Alice".into(),
///     email: "alice@example.com".into(),
///     active: true,
/// };
///
/// // Convert to renderable and print
/// let renderable = user.into_renderable();
/// ```
pub trait GiltCast: Sized + 'static {
    /// Convert this value to a renderable representation.
    ///
    /// This method should create a widget (like a [`Panel`](crate::panel::Panel),
    /// [`Table`](crate::table::Table), or [`Text`](crate::text::Text)) that
    /// represents this value visually.
    ///
    /// # Returns
    ///
    /// A boxed trait object implementing `Renderable`.
    fn __gilt__(self) -> Box<dyn Renderable>;
}

/// Trait for types that can be converted into a `Box<dyn Renderable>`.
///
/// This trait provides a uniform way to convert various types into renderable
/// objects. It's automatically implemented for any type implementing [`GiltCast`]
/// via a blanket implementation.
///
/// You typically won't need to implement this trait directly - instead, implement
/// [`GiltCast`] and get this trait for free.
///
/// # Examples
///
/// ```
/// use gilt::protocol::IntoRenderable;
/// use gilt::prelude::*;
///
/// // Types that implement GiltCast also implement IntoRenderable
/// struct Message(String);
///
/// impl gilt::protocol::GiltCast for Message {
///     fn __gilt__(self) -> Box<dyn gilt::console::Renderable> {
///         Box::new(Panel::new(Text::from(self.0)))
///     }
/// }
///
/// let msg = Message("Hello, World!".into());
/// let renderable = msg.into_renderable();
/// ```
pub trait IntoRenderable {
    /// Convert this value into a boxed renderable.
    ///
    /// # Returns
    ///
    /// A `Box<dyn Renderable>` that can be passed to console methods.
    fn into_renderable(self) -> Box<dyn Renderable>;
}

// Blanket implementation: any GiltCast type automatically implements IntoRenderable
impl<T: GiltCast> IntoRenderable for T {
    fn into_renderable(self) -> Box<dyn Renderable> {
        self.__gilt__()
    }
}

/// Extension trait for types that implement `Renderable`.
///
/// This trait provides convenience methods for working with renderable values.
/// Since it requires `Renderable` as a bound, it will only be implemented
/// for types that are actually renderable.
///
/// # Examples
///
/// ```
/// use gilt::protocol::RenderableExt;
/// use gilt::prelude::*;
///
/// // Wrap a Text value
/// let text = Text::from("Hello");
/// let boxed = text.into_boxed_renderable();
/// ```
pub trait RenderableExt: Renderable + Sized + 'static {
    /// Convert this renderable into a `RenderableBox` for type-erased storage.
    ///
    /// # Returns
    ///
    /// A `RenderableBox` wrapping this value.
    fn into_boxed_renderable(self) -> RenderableBox;
}

impl<T: Renderable + 'static> RenderableExt for T {
    fn into_boxed_renderable(self) -> RenderableBox {
        RenderableBox::new(self)
    }
}

/// A type-erased wrapper that can hold any renderable value.
///
/// This struct wraps a `Box<dyn Renderable>` and can be used when you need
/// to store renderable values in a type-erased context while still being
/// able to use them as renderables.
///
/// # Examples
///
/// ```
/// use gilt::protocol::{RenderableBox, RenderableExt};
/// use gilt::prelude::*;
///
/// let text = Text::from("Hello");
/// let boxed = text.into_boxed_renderable();
///
/// // boxed can now be stored in collections or passed around
/// let items: Vec<RenderableBox> = vec![boxed];
/// ```
pub struct RenderableBox {
    inner: Box<dyn Renderable>,
}

impl RenderableBox {
    /// Create a new RenderableBox from any renderable value.
    pub fn new<R: Renderable + 'static>(renderable: R) -> Self {
        Self {
            inner: Box::new(renderable),
        }
    }

    /// Get a reference to the inner renderable.
    pub fn as_renderable(&self) -> &dyn Renderable {
        &*self.inner
    }

    /// Convert back into a boxed renderable.
    pub fn into_inner(self) -> Box<dyn Renderable> {
        self.inner
    }
}

impl Renderable for RenderableBox {
    fn gilt_console(
        &self,
        console: &crate::console::Console,
        options: &crate::console::ConsoleOptions,
    ) -> Vec<crate::segment::Segment> {
        self.inner.gilt_console(console, options)
    }
}

/// Attempt to cast a reference to a renderable trait object.
///
/// This is similar to `gilt_cast` but works with references instead of owned values.
///
/// # Examples
///
/// ```
/// use gilt::protocol::as_renderable_ref;
/// use gilt::prelude::*;
///
/// let text = Text::from("Hello");
/// let renderable = as_renderable_ref(&text);
/// // renderable is &dyn Renderable
/// // Use renderable here
/// ```
pub fn as_renderable_ref<T: Renderable>(value: &T) -> &dyn Renderable {
    value
}

/// Attempt to cast a mutable reference to a renderable trait object.
///
/// # Examples
///
/// ```
/// use gilt::protocol::as_renderable_mut;
/// use gilt::prelude::*;
///
/// let mut text = Text::from("Hello");
/// let renderable = as_renderable_mut(&mut text);
/// ```
pub fn as_renderable_mut<T: Renderable>(value: &mut T) -> &mut dyn Renderable {
    value
}

/// Macro to derive GiltCast implementation (placeholder for future derive macro).
///
/// This macro is a marker for the planned derive macro that will automatically
/// implement `GiltCast` for structs and enums. Currently, it does nothing but
/// documents the intended usage.
///
/// # Future Usage
///
/// ```ignore
/// use gilt::protocol::{GiltCast, IntoRenderable};
///
/// #[derive(GiltCast)]
/// #[rich(panel)]
/// struct User {
///     name: String,
///     email: String,
/// }
/// ```
#[macro_export]
macro_rules! derive_gilt_cast {
    // Placeholder for future derive macro
    ($item:item) => {
        $item
    };
}

/// Macro to implement GiltCast using a closure-like syntax.
///
/// This macro provides a concise way to implement `GiltCast` without writing
/// out the full impl block. The syntax uses a closure pattern where you specify
/// a parameter name for `self`.
///
/// # Examples
///
/// ```
/// use gilt::gilt_cast_impl;
/// use gilt::prelude::*;
///
/// struct Status { code: u16, message: String }
///
/// gilt_cast_impl! { Status => |s|
///     Box::new(Panel::new(Text::from(format!("Status {}: {}",
///         s.code, s.message))))
/// }
/// ```
#[macro_export]
macro_rules! gilt_cast_impl {
    ($type:ty => |$this:ident| $body:expr) => {
        impl $crate::protocol::GiltCast for $type {
            fn __gilt__(self) -> Box<dyn $crate::console::Renderable> {
                let $this = self;
                $body
            }
        }
    };
}

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

    #[test]
    fn test_gilt_cast_success() {
        let text = Text::from("Hello, World!");
        let boxed: Box<dyn Any> = Box::new(text);

        let cast_result = gilt_cast::<Text>(boxed);
        assert!(cast_result.is_some());
    }

    #[test]
    fn test_gilt_cast_failure() {
        let text = Text::from("Hello");
        let boxed: Box<dyn Any> = Box::new(text);

        // Trying to cast Text to Panel should fail
        let cast_result = gilt_cast::<Panel>(boxed);
        assert!(cast_result.is_none());
    }

    #[test]
    fn test_gilt_cast_with_panel() {
        let panel = Panel::new(Text::from("Content"));
        let boxed: Box<dyn Any> = Box::new(panel);

        let cast_result = gilt_cast::<Panel>(boxed);
        assert!(cast_result.is_some());
    }

    // Test GiltCast implementation
    struct TestData {
        value: i32,
    }

    impl GiltCast for TestData {
        fn __gilt__(self) -> Box<dyn Renderable> {
            Box::new(Panel::new(Text::from(format!("Value: {}", self.value))))
        }
    }

    #[test]
    fn test_gilt_cast_trait() {
        let data = TestData { value: 42 };
        let renderable = data.into_renderable();

        // The renderable should be usable
        let mut console = crate::console::Console::builder().width(80).build();
        console.begin_capture();
        console.print(&*renderable);
        let output = console.end_capture();

        assert!(output.contains("Value: 42"));
    }

    #[test]
    fn test_into_renderable_blanket_impl() {
        struct SimpleData(&'static str);

        impl GiltCast for SimpleData {
            fn __gilt__(self) -> Box<dyn Renderable> {
                Box::new(Text::from(self.0))
            }
        }

        let data = SimpleData("Test");
        let _renderable: Box<dyn Renderable> = data.into_renderable();
        // If this compiles, the blanket implementation works
    }

    #[test]
    fn test_renderable_box() {
        let text = Text::from("Boxed text");
        let boxed = RenderableBox::new(text);

        // Can be used as a renderable
        let mut console = crate::console::Console::builder().width(80).build();
        console.begin_capture();
        console.print(&boxed);
        let output = console.end_capture();

        assert!(output.contains("Boxed text"));
    }

    #[test]
    fn test_renderable_box_from_panel() {
        let panel = Panel::new(Text::from("Panel content"));
        let boxed = RenderableBox::new(panel);

        let inner = boxed.into_inner();
        // inner is Box<dyn Renderable>
        let mut console = crate::console::Console::builder().width(80).build();
        console.begin_capture();
        console.print(&*inner);
        let output = console.end_capture();

        assert!(output.contains("Panel content"));
    }

    #[test]
    fn test_renderable_ext() {
        let text = Text::from("Extended");
        let boxed = text.into_boxed_renderable();

        let mut console = crate::console::Console::builder().width(80).build();
        console.begin_capture();
        console.print(&boxed);
        let output = console.end_capture();

        assert!(output.contains("Extended"));
    }

    #[test]
    fn test_is_type() {
        let text: Box<dyn Any> = Box::new(Text::from("Test"));
        assert!(is_type::<Text>(&*text));
        assert!(!is_type::<Panel>(&*text));
    }

    #[test]
    fn test_as_renderable_ref() {
        let text = Text::from("Reference");
        let renderable_ref = as_renderable_ref(&text);

        // Should be usable as a renderable reference
        let mut console = crate::console::Console::builder().width(80).build();
        console.begin_capture();
        console.print(renderable_ref);
        let output = console.end_capture();

        assert!(output.contains("Reference"));
    }

    #[test]
    fn test_gilt_cast_impl_macro() {
        struct QuickData {
            x: i32,
            y: i32,
        }

        gilt_cast_impl! { QuickData => |p|
            Box::new(Text::from(format!("Point: ({}, {})", p.x, p.y)))
        }

        let data = QuickData { x: 10, y: 20 };
        let renderable = data.into_renderable();

        let mut console = crate::console::Console::builder().width(80).build();
        console.begin_capture();
        console.print(&*renderable);
        let output = console.end_capture();

        assert!(output.contains("Point: (10, 20)"));
    }

    #[test]
    fn test_collection_of_boxes() {
        let items: Vec<RenderableBox> = vec![
            RenderableBox::new(Text::from("Item 1")),
            RenderableBox::new(Panel::new(Text::from("Item 2"))),
            RenderableBox::new(Rule::with_title("Item 3")),
        ];

        let mut console = crate::console::Console::builder().width(80).build();
        console.begin_capture();

        for item in &items {
            console.print(item);
        }

        let output = console.end_capture();
        assert!(output.contains("Item 1"));
        assert!(output.contains("Item 2"));
        assert!(output.contains("Item 3"));
    }
}