Skip to content

Commit

Permalink
Merge pull request #27 from disco07/table
Browse files Browse the repository at this point in the history
Table
  • Loading branch information
disco07 authored Mar 19, 2023
2 parents 8612746 + e244d3c commit 8f53643
Show file tree
Hide file tree
Showing 9 changed files with 181 additions and 27 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rct"
version = "0.1.2"
version = "0.1.3"
edition = "2021"
authors = ["disco07"]
description = "CLI Table Output for Rust Project"
Expand Down
58 changes: 55 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ A CLI Table Output for Rust 🦀 projects.
## Installation
Add from command line.
```
cargo add [email protected].2
cargo add [email protected].3
```
Or add this to your Cargo.toml file.
```
[dependencies]
rct = "0.1.2"
rct = "0.1.3"
# Or add from github main branch.
rct = { git = "https://github.com/disco07/rct.git", branch = "main" }
Expand Down Expand Up @@ -70,7 +70,59 @@ fn main() {
table.view()
}
```
![Basic bar](images/basic.PNG)
![Basic table](images/basic.PNG)

### Customizing the table (add colors)
```rust
use rct::cell::ICell;
use rct::color::Colorizer;
use rct::table::Table;

fn main() {
let mut table = Table::new();

table
.add_header(vec![
"ID".cell(),
"Title".cell(),
"is_enabled".cell(),
"price".cell(),
"currency".cell(),
"description".cell(),
"created_at".cell(),
])
.add_row(vec![
1.cell(),
"Harry \nPotter".cell().color("#ff0000"),
"1".cell(),
"14.87".cell(),
"".cell(),
"Harry Potter".cell(),
"2001-12-05 22:05:20".cell(),
])
.add_row(vec![
2.cell(),
"Spider-man".cell(),
"0".cell(),
"18.80".cell(),
"".cell(),
"Spider-man, No Way Home.".cell().color("#0000ff"),
"2018-12-12 09:04:50".cell(),
])
.add_row(vec![
3.cell(),
"Avenger".cell().color("#00ff00"),
"1".cell(),
"18.50".cell(),
"".cell(),
"Avenger".cell(),
"2017-10-12 10:34:39".cell(),
]);

table.view();
}
```
![Color table](images/color_table.PNG)

## Contributing 🤝
Contributions, issues, and feature requests are welcome!
Expand Down
47 changes: 47 additions & 0 deletions examples/colors_table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use rct::cell::ICell;
use rct::color::Colorizer;
use rct::table::Table;

fn main() {
let mut table = Table::new();

table
.add_header(vec![
"ID".cell(),
"Title".cell(),
"is_enabled".cell(),
"price".cell(),
"currency".cell(),
"description".cell(),
"created_at".cell(),
])
.add_row(vec![
1.cell(),
"Harry \nPotter".cell().color("#ff0000"),
"1".cell(),
"14.87".cell(),
"€".cell(),
"Harry Potter".cell(),
"2001-12-05 22:05:20".cell(),
])
.add_row(vec![
2.cell(),
"Spider-man".cell(),
"0".cell(),
"18.80".cell(),
"€".cell(),
"Spider-man, No Way Home.".cell().color("#0000ff"),
"2018-12-12 09:04:50".cell(),
])
.add_row(vec![
3.cell(),
"Avenger".cell().color("#00ff00"),
"1".cell(),
"18.50".cell(),
"€".cell(),
"Avenger".cell(),
"2017-10-12 10:34:39".cell(),
]);

table.view();
}
Binary file added images/color_table.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 7 additions & 7 deletions src/cell.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt::Display;
use std::fmt::{Display, Formatter};
use unicode_width::UnicodeWidthStr;

#[derive(Debug, Clone)]
Expand All @@ -12,6 +12,12 @@ pub trait ICell {
fn cell(self) -> Cell;
}

impl Display for Cell {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.data.join("\n"))
}
}

impl<T> ICell for T
where
T: Display,
Expand All @@ -26,9 +32,3 @@ where
}
}
}

impl ICell for Cell {
fn cell(self) -> Cell {
self
}
}
77 changes: 66 additions & 11 deletions src/color.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
use crate::cell::Cell;

pub trait Colorizer {
fn colorize(&self, hex: &str) -> String;
fn color(&self, hex: &str) -> Cell;
}

impl Colorizer for str {
fn colorize(&self, hex: &str) -> String {
impl Colorizer for Cell {
/// Colorizes [Cell] with hex color.
///
/// # Examples
///
/// ```
/// use rct::cell::ICell;
/// use rct::color::Colorizer;
///
/// let colour = "string".cell().color("#ffffff");
/// assert_eq!(colour.to_string(), "\u{1b}[38;2;255;255;255mstring\u{1b}[0m")
/// ```
fn color(&self, hex: &str) -> Cell {
let mut color = String::new();
if hex.starts_with('#') && hex.len() == 7 {
color.push_str("\x1B[38;2;");
Expand All @@ -17,26 +30,68 @@ impl Colorizer for str {
.as_str(),
);
}
format!("{}{}\x1b[0m", color, self)
let mut data = vec![];
for cell in &self.data {
let c = format!("{}{}\x1b[0m", color, cell);
data.push(c);
}

Cell {
data,
height: self.height,
width: self.width,
}
}
}

/// Transforms string colored to string.
/// ```
/// use rct::color::split_colors;
/// let string = String::from("\u{1b}[38;2;255;255;255mstring\u{1b}[0m");
/// let split_color = split_colors(&string);
///
/// assert_eq!(split_color, "string ")
/// ```
pub fn split_colors(color: &str) -> String {
if color.contains("[38;2;") {
let (_, c) = color.split_once('m').unwrap();
let color_splited = c
.to_string()
.split('\u{1b}')
.map(String::from)
.collect::<Vec<_>>();
return color_splited[0].to_string() + &" ".repeat(2);
}

color.to_string()
}

#[cfg(test)]
mod tests {
use crate::color::Colorizer;
use crate::cell::ICell;
use crate::color::{split_colors, Colorizer};
#[test]
fn test_colorize_white() {
let colour = "string".colorize("#ffffff");
assert_eq!(colour, "\u{1b}[38;2;255;255;255mstring\u{1b}[0m")
let colour = "string".cell().color("#ffffff");
assert_eq!(
colour.to_string(),
"\u{1b}[38;2;255;255;255mstring\u{1b}[0m"
)
}
#[test]
fn test_colorize_black() {
let colour = "string".colorize("#000000");
assert_eq!(colour, "\u{1b}[38;2;0;0;0mstring\u{1b}[0m")
let colour = "string".cell().color("#000000");
assert_eq!(colour.to_string(), "\u{1b}[38;2;0;0;0mstring\u{1b}[0m")
}
#[test]
fn test_colorize_not_hex() {
let colour = "string".colorize("black");
assert_eq!(colour, "string\u{1b}[0m")
let colour = "string".cell().color("black");
assert_eq!(colour.to_string(), "string\u{1b}[0m")
}
#[test]
fn test_split_colors() {
let string = String::from("\u{1b}[38;2;255;255;255mstring\u{1b}[0m");
let split_color = split_colors(&string);
assert_eq!(split_color, "string ")
}
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod cell;
pub mod color;
pub mod table;
pub mod row;
pub mod cell;
pub mod table;
4 changes: 2 additions & 2 deletions src/table.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::color::split_colors;
use crate::row::Row;
use std::cmp::min;
use std::fmt::{Display, Formatter};
Expand Down Expand Up @@ -267,7 +268,7 @@ impl Table {
*width_column.get(index).unwrap_or(&(0_usize))
- min(
*width_column.get(index).unwrap_or(&(0_usize)),
value.chars().count(),
split_colors(value).chars().count(),
),
),
),
Expand Down Expand Up @@ -346,7 +347,6 @@ impl Table {
/// Calculates the max length for every column.
fn max_column_length(column_len: &mut [usize], row: &Row) {
let rows: Vec<_> = row.width();

for (index, row) in rows.iter().enumerate() {
let current_max = column_len.get(index).unwrap_or(&0);
if *row > *current_max {
Expand Down

0 comments on commit 8f53643

Please sign in to comment.