Skip to content

Support length-percentage calculations in gradient stops - #139

Merged
asamuzaK merged 10 commits into
asamuzaK:mainfrom
trooney:fix-gradient-math-stops
Oct 8, 2026
Merged

asamuzaK merged 10 commits into
asamuzaK:mainfrom
trooney:fix-gradient-math-stops

Conversation

@trooney

@trooney trooney commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

resolveGradient() rejects valid calculations in color-stop positions, such as calc(100% - 24px), causing otherwise valid gradients to be discarded by consumers.

Accept calc(), min(), max() and clamp() positions in linear and radial gradients, including their repeating forms and transition hints. Validate arithmetic and the final length-percentage type: * requires a <number> on one side and / requires a <number> divisor. Color stops are split into component values before validation, so comments still separate tokens. The validator uses the existing length units and supports numeric clamp() bounds. Reject stops whose colors cannot resolve to valid values in the requested output format.

One use case is a mask fade whose final opaque stop sits a fixed distance from the edge. This came up during a jsdom upgrade in Grafana PR #11626.

Validation: full cssColor build with 1,483 tests; isolated jsdom API and local WPT suites; companion gradient WPT in jsdom and Chrome.

trooney and others added 2 commits October 6, 2026 12:58
Validate calc, min, max and clamp stop positions with the length
percent hint and use shared validation for the first color stop.

Co-authored-by: codex <[email protected]>
Retain nested comments through gradient splitting so validation sees the
original math tokens. Reject missing or invalid resolved stop colors in
the requested output format.

Cover split dimensions and numbers, valid calculation comments, hints,
double stops, output formats and supplied currentColor values.

Co-authored-by: codex <[email protected]>

@asamuzaK asamuzaK left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution.

  • gradient-position.ts looks like a general-purpose utility rather than something specific to gradient-position?
    • If so, please consider moving it under utils/.
    • Also, please reconsider the file name (e.g., length-percentage.ts).
  • Please avoid nesting functions.
  • Please use arrow functions instead of standard function declarations as much as possible.
  • Please add unit tests for the newly created functions.
    It's completely fine to export them for testing purposes.

Extract top-level parser helpers into utils/length-percentage.ts and add
direct unit tests. Follow the existing recursive-parser pattern and keep
gradient tests focused on integration and serialization.

Co-authored-by: codex <[email protected]>
@trooney

trooney commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Thanks for the guidance. Moved the validator to utils/length-percentage.ts, made the helpers top-level, and added direct unit tests. The helpers use arrows except for the recursive value parser, which follows the existing pattern in css-calc-var.ts and avoids extra callback plumbing. The full build passes with 1,437 tests.

@trooney
trooney requested a review from asamuzaK October 6, 2026 22:34
Comment thread test/length-percentage.test.ts Resolved
Comment thread test/length-percentage.test.ts Resolved
trooney and others added 5 commits October 7, 2026 11:50
Reject multiplication unless one side is a number, and division unless
the divisor is a number, so calc(1px * 2px / 1px) and similar typed
arithmetic are no longer accepted as length-percentage positions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comments are preserved in stop parts so math positions keep their token
boundaries, but color parsing does not accept them. Strip comments from
the color before validating and resolving it, so stops like
rgb(0 /* c */ 0 0) remain valid as they were before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Gradient items now keep their comments, and splitting an item that ends
with whitespace and a comment yields an empty trailing part. Drop empty
parts so stops like `blue /* end */` remain valid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parse gradient stops as component values before stripping comments so identifiers and blocks cannot become math functions. Export the position validator at module scope and cover the helpers and gradient rejection paths directly.

Document the scalar arithmetic subset retained for this PR.

Co-authored-by: codex <[email protected]>
Validate calculation arguments as they are parsed, restore the shared splitter to main, and consolidate gradient fixtures with full-input assertion messages.

Co-authored-by: codex <[email protected]>
@trooney

trooney commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the catch. I tightened comment handling in colour stops. * now requires a on one side and / requires a divisor, so calc(1px * 2px / 1px) and calc(1px / 2px * 3em) are rejected. Both are covered in the unit and gradient tests.

@trooney
trooney requested a review from asamuzaK October 7, 2026 21:58
Comment thread src/utils/length-percentage.ts Outdated
/* regexp */
const REG_LENGTH = new RegExp(`^(?:${LENGTH})$`, 'i');
const REG_CALC = /^(?:calc|min|max|clamp)\(/i;
const REG_CONSTANT = /^(?:e|pi|NaN|infinity|-infinity)$/i;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about const REG_CALC_KEYWORD = /^(?:e|pi|-?infinity|NaN)$/i;
However, I'm not sure we should include NaN as case insensitive keyword.
w3c/csswg-drafts#4698
WDYT?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@trooney trooney Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The section you linked lists NaN with infinity and -infinity as ASCII case-insensitive keywords; w3c/csswg-drafts#4698 only fixed its serialized casing.

Chromium accepts calc(nan), calc(nAn) and calc(NAN) and serializes each as calc(NaN), and this library’s cssCalc() does the same, so I’d lean towards keeping it.

That said, NaN isn’t a useful stop position, so I wouldn't mind dropping it if that's your preference.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed that Firefox also accepts calc(nan).
Although it differs from the specification, let's keep NaN included to align with the browser implementations.

}
});

it.each([

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add tests for below:

calc(- infinity) -> valid
calc(+ infinity) -> valid
calc(/* comment */ -infinity) -> valid
calc(-NaN) -> invalid
calc(- NaN) -> valid

TBD:

calc(nan) -> invalid?
calc(nAn) -> invalid?
calc(NAN) -> invalid?

@trooney trooney Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The commit renames the pattern to REG_CALC_KEYWORD = /^(?:e|pi|-?infinity|NaN)$/i, keeps NaN, and adds the keyword test cases.

Three differ from your expectations: calc has no unary +/-, so a sign separated by whitespace isn't part of the keyword.

Case Chromium Test
calc(- infinity) invalid invalid
calc(+ infinity) invalid invalid
calc(/* comment */ -infinity) valid valid
calc(-NaN) invalid invalid
calc(- NaN) invalid invalid
calc(nan), calc(nAn), calc(NAN) valid valid

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.
Looks good.

Rename the keyword pattern to REG_CALC_KEYWORD and fold the infinity
variants together. Keep NaN, which CSS Values 4 defines as an ASCII
case-insensitive calc keyword. Cover case-insensitive keywords and
reject keywords with a separated or prefixed sign.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trooney
trooney requested a review from asamuzaK October 8, 2026 01:35

@asamuzaK asamuzaK left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great.
Especially, shifting from regex to a tokenizer-based approach is a huge step forward for future maintenance.
Thanks a lot.

@asamuzaK
asamuzaK merged commit 66d6abd into asamuzaK:main Oct 8, 2026
15 checks passed
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