Skip to content

feat: enforce hex color digit counts in css parser#5176

Open
rajkandula wants to merge 1 commit into
google:masterfrom
charanrajkandula-opensource:feat/parser-hex-digit-enforcement
Open

feat: enforce hex color digit counts in css parser#5176
rajkandula wants to merge 1 commit into
google:masterfrom
charanrajkandula-opensource:feat/parser-hex-digit-enforcement

Conversation

@rajkandula

Copy link
Copy Markdown

Reference Issue

Resolves the inline TODO in packages/model-viewer/src/styles/parsers.ts:
// TODO(cdata): right now we don't actually enforce the number of digits

Description

Currently, HEX_RE in the CSS expression parser matches any number of hexadecimal characters (including invalid lengths like 0, 1, 2, 5, 7, etc.), which is not compliant with CSS specifications (where hex colors must have exactly 3, 4, 6, or 8 digits).

This PR updates the regular expression to enforce the correct number of digits (3, 4, 6, or 8) and uses a negative lookahead (?![a-f0-9]) to prevent partial matching on invalid lengths.

Changes

  • parsers.ts: Updated HEX_RE to /^([a-f0-9]{8}|[a-f0-9]{6}|[a-f0-9]{4}|[a-f0-9]{3})(?![a-f0-9])/i and removed the TODO comment.
  • parsers-spec.ts: Added unit tests to verify:
    • Correct parsing of 4-digit hex colors (#abcd).
    • Correct parsing failure (returns empty terms/expression) for invalid hex lengths (#, #1, #12, #12345, #1234567, #123456789, #123456fg).
    • Mixed values where a valid hex is followed by non-hex characters (e.g., #123456g parses as hex #123456 and ident g).

Verification

  • Ran npm run build to verify compilation.
  • Ran npm run format and npm run lint to confirm formatting guidelines are met.
  • Ran npm run test:ci and confirmed all 393 tests successfully pass.

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.

1 participant