Skip to content

Support 3-digit shorthand hex colors in templates#20

Open
mahmoodhamdi wants to merge 1 commit into
chalk:mainfrom
mahmoodhamdi:fix/support-shorthand-hex
Open

Support 3-digit shorthand hex colors in templates#20
mahmoodhamdi wants to merge 1 commit into
chalk:mainfrom
mahmoodhamdi:fix/support-shorthand-hex

Conversation

@mahmoodhamdi
Copy link
Copy Markdown

While using chalk-template for a terminal dashboard, I noticed that 3-digit shorthand hex colors like {#F00 text} throw an error, even though chalk itself supports chalk.hex('#F00').

Before: {#F00 hello}Unknown Chalk style: undefined
After: {#F00 hello} → works, same as {#FF0000 hello}

The fix updates the style regex to match 3-digit hex and expands shorthand digits in parseHex (F00 → FF0000), matching chalk's own behavior.

Supported:

  • Foreground: {#F00 text}
  • Background: {#:0F0 text}
  • Both: {#F00:0F0 text}
  • Mixed with 6-digit: {#F00:00FF00 text}
  • Chained with modifiers: {bold.#F00 text}

All existing tests pass, new tests added for both tagged template and template() function.

The shorthand hex syntax ({#F00 text}) was not supported, throwing
"Unknown Chalk style: undefined". This updates the style regex and
parseHex to handle 3-digit hex by expanding each digit (F00 → FF0000),
matching chalk's own hex() behavior.

Works for foreground ({#F00}), background ({#:0F0}), and combined
({#F00:0F0}) shorthand, including mixed 3/6-digit combinations.
@sindresorhus
Copy link
Copy Markdown
Member

I think this introduces a regression for invalid hex lengths. I manually checked {#FFFF hello} and {#:FFFF hello} on main and both still throw Unknown Chalk style: undefined, but on this branch they now render plain hello instead. So malformed 4 or 5 digit hex values get partially matched as 3 digit hex and the styling is silently ignored, which seems like a behavior change in the error path.

Could you tighten the parsing so the whole hex token has to match, and add a couple of tests for invalid 4 and 5 digit values?

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

Successfully merging this pull request may close these issues.

2 participants