colored-rs/colored

Support for WASM

Opened this issue · 2 comments

Firstly, thanks for the crate!

Would it be possible to get this crate working when building for WASM?

I've built a text based adventure game which I'm also building for WASM and it's a shame for the colored text not to work: https://github.com/hseager/you-are-merlin

I thought I'd ask for some advice before diving in and to see if it's a terrible idea or not as I apprectiate this crate is built with the terminal in mind. Thanks!

I've created a wrapper module which detects WASM builds and isn't perfect, but is working well enough for my needs.

pub trait TextFormatter {
    fn format_bold(self) -> String;
}

impl TextFormatter for &str {
    #[cfg(target_arch = "wasm32")]
    fn format_bold(self) -> String {
        format!("<span style='font-weight: bold;'>{}</span>", self)
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn format_bold(self) -> String {
        use colored::Colorize;

        self.bold().to_string()
    }
}

I wonder if there would be interest in integrating this into this crate, or if it better separated out into another crate.

IMO a tool that does what you're asking, wrapping text in <span style="STYLE"></span>, should be a separate crate. This could also be useful even when not used in WASM. For example, a server rendering an HTML response.

BTW, such a tool should probably use the appropriate HTML elements. As a usage example, perhaps something like this:

assert_eq!("foo".strong().style("color: red;").to_string(), "<strong style=\"color: red;\">foo</strong>");

This could be achieved, for example, if str implements fn strong(&self) -> SomeHTMLType and SomeHTMLType implements fn style(mut self, style: SomeStyleType) -> Self.

You might want to check if a crate that does this already exists, because this usage I'm making up does feel vaguely familiar.