use super::prelude::*;
use regex::Regex;
use std::borrow::Cow;
use std::sync::LazyLock;
static HEX_COLOR: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$").unwrap());
pub const RULE_COLOR: Rule = Rule {
name: "color",
position: LineRequirement::Any,
try_consume_fn,
};
fn try_consume_fn<'r, 't>(
parser: &mut Parser<'r, 't>,
) -> ParseResult<'r, 't, Elements<'t>> {
debug!("Trying to create color container");
assert_step(parser, Token::Color)?;
let color = collect_text(
parser,
RULE_COLOR,
&[ParseCondition::current(Token::Pipe)],
&[
ParseCondition::current(Token::ParagraphBreak),
ParseCondition::current(Token::LineBreak),
],
None,
)?;
trace!("Retrieved color descriptor, now building container ('{color}')");
let (elements, errors, paragraph_safe) = collect_consume(
parser,
RULE_COLOR,
&[ParseCondition::current(Token::Color)],
&[ParseCondition::current(Token::ParagraphBreak)],
None,
)?
.into();
let element = Element::Color {
color: hexify_color(color),
elements,
};
ok!(paragraph_safe; element, errors)
}
fn hexify_color(color: &str) -> Cow<'_, str> {
if HEX_COLOR.is_match(color) {
Cow::Owned(format!("#{color}"))
} else {
Cow::Borrowed(color)
}
}