Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Support parsing TrueColor from RGB string #123

Open
dhruvkb opened this issue Nov 28, 2022 · 1 comment
Open

Feature: Support parsing TrueColor from RGB string #123

dhruvkb opened this issue Nov 28, 2022 · 1 comment

Comments

@dhruvkb
Copy link

dhruvkb commented Nov 28, 2022

Problem

Currently the from_str function supports parsing color names to Color enum based on the names. But this function does not parse TrueColor.

https://github.com/mackwic/colored/blob/11ffd20e7b5d1b48e4de7bb78ced26131ae5e114/src/color.rs#L88

Expectation

Given a string like rgb(<u8>,<u8>,<u8>), from_str should support parsing it to a Color::TrueColor instance.

Suggestion

In a project of mine, I've used a regex check to determine if the string matches the specific pattern and converts it to Color::TrueColor. A refined version of this could be added in the crate to be supported out-of-the-box.

let true_color = Regex::new(r"(?x)^
    (?:bg:)?
    rgb\(
        (?P<red>\d{1,3}),\s?
        (?P<green>\d{1,3}),\s?
        (?P<blue>\d{1,3})
    \)
$").unwrap();

let mut color: Option<Color> = None;
if let Some(caps) = true_color.captures(style) { // RGB colors
    let channels: Vec<u8> = vec!["red", "green", "blue"]
        .into_iter()
        .map(|x| caps[x].parse().expect("Must be int between 0 and 255."))
        .collect();
    color = Some(Color::TrueColor { r: channels[0], g: channels[1], b: channels[2] });
}
@spenserblack
Copy link
Collaborator

spenserblack commented Jul 5, 2023

It kind of looks like you're parsing a CSS color format into a Color instance. IMO it might be better for some sort of Color::from_str implementation to support all CSS color formats, so rgb(0, 0, 0), #000000, and black would all parse to Color::TrueColor{ r: 0, g: 0, b: 0 }.

BTW there are crates that handle the bulk of the work, like cssparser and css-color from a quick search, if this is reasonable. Maybe locked behind a feature called parsing or something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants