Skip to content

fix/css-processor-inline-css-validation - #61

Open
5ZYSZ3K wants to merge 10 commits into
mainfrom
fix/css-processor-inline-css-validation
Open

5ZYSZ3K wants to merge 10 commits into
mainfrom
fix/css-processor-inline-css-validation

Conversation

@5ZYSZ3K

@5ZYSZ3K 5ZYSZ3K commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

Fixes #59

Summary

This PR fixes the three bugs from the issue, in one commit each. A fourth commit makes inline CSS ignore !important. Below: how the validators and the inline parser changed, and which behavior differs from the issue's expected output or from main beyond it.

Validators

The diff below leaves out intermediate base classes.

 GenericCSSPropertyValidator
+  lowercaseInlineCSSKeywords(value)          # by default returns value: no second attempt
   LongSizeCSSPropertyValidator
+    allowsNegativeValues() → false
+    LongSignedSizeCSSPropertyValidator       # → true: margin*, top, right, bottom, left, letterSpacing
   LongColorCSSPropertyValidator
-    COLOR_REGEX
+    hex | rgb/rgba/hsl/hsla | NAMED_COLORS     # css-color-keywords + transparent, cyan, magenta
   LongEnumerationListCSSPropertyValidator
+    matches each item lowercased
   ShortCSSToReactNativeValidator
+    returns null when css-to-react-native can't expand the value
     ShortFontCSSValidator
+      lowercases only up to the font size

lowercaseInlineCSSKeywords is overridden by validators of sizes, colors, enumerations and css-to-react-native shorthands (border, background, flex-flow, text-decoration, font). They call the new lowercaseCSSKeywords helper, which leaves hex colors as written.

Inline parsing

 CSSInlineParseRun
   parseInlineCSS
+    strip a trailing !important (any case, any whitespace)
   normalizeProp(rawName, rawValue)
-    getPropertyName(rawName)
+    resolvePropertyName(rawName)
+      getPropertyName(rawName), if registered
+      else getPropertyName(rawName.toLowerCase())
     validator.normalizeInlineCSSValue(rawValue)
+    if null: validator.normalizeInlineCSSValue(
+               validator.lowercaseInlineCSSKeywords(rawValue))

Design decisions

  • Try as written, lowercase only on failure. Anything valid on main still gives the same output. camelCase names such as paddingBottom still resolve, and a test in render relies on that. #FFF keeps its case.
  • Each validator opts in to lowercasing. It is only safe where the value is a keyword:
    • font-family is left out because fonts are matched by exact name.
    • list-style-type is left out because it may name a user-defined customListStyleSpecs entry.
    • transform is left out because css-to-react-native expects camelCase function names such as translateX.
    • In the font shorthand, only the part up to the font size is lowercased, so the family keeps its case.
  • Enumeration lists lowercase each item instead. fontVariant keeps the valid items and drops the rest. In small-caps OLDSTYLE-NUMS, small-caps is already valid as written, so the second attempt would never run and the second item would be lost.
  • css-to-react-native shorthands return null on failure. Before, a failed expansion was wrapped in a merge request that merged nothing. Returning null lets normalizeProp see the failure and try again lowercased.
  • The validator decides whether a negative value is allowed. The length regex now accepts a sign, and splitValueAndUnit rejects negative values unless allowsNegativeValues() returns true.
  • Colors are checked against a closed list, not \w+. css-color-keywords was already installed through css-to-react-native. It is now a direct dependency, with a local type declaration.

Behavior changes

Input main This branch Notes
color: red !important { color: 'red !important' } { color: 'red' } The issue expects {}. Instead the flag is stripped from every declaration, so margin-top: 5px !important now applies too.
display: FLEX, border: 1PX SOLID RED {} lowercased and applied The issue only covers property names. Keyword values are case-insensitive in CSS too.
color: currentColor, color: inherit passed through {} Not in the color list. iOS and Android already rejected them. On web, border-color: currentColor now falls back to black.
margin-top: px { marginTop: 0 } {} A length needs at least one digit. +5px, .5px and -0 are accepted.
tagsStyles: { marginTop: '-5px' } {} { marginTop: -5 } Strings in native styles go through the same length regex. 'px' is now dropped there as well.

Unchanged on purpose:

  • Native style values (tagsStyles, classesStyles, idsStyles):
    • They are not lowercased, because React Native is case-sensitive: { display: 'FLEX' } fails there.
    • Numbers are not checked for sign: { paddingTop: -5 } is kept.
    • Colors are not validated, as on main.
  • !important within one style attribute: a later declaration still overrides an earlier important one. color: red !important; color: blue gives blue, where a browser shows red. The docs now say that the flag is accepted and ignored.

Evidence

  • css-processor passes yarn test (1847 jest tests, tsc and lint) on each of the four commits. New tests cover each row of the table above, and the cases left unchanged on purpose.
  • On the last commit, transient-render-engine (191 tests) and render (265 tests) pass, and the type check and lint pass for doc-pages.

Merge Danger

Door: Two-way

The changes stay inside css-processor validation code. Validators aren't exported, so no public API changes. Reverting the commits restores the old output.

Blast Radius: Styling

  • Inline declarations that main dropped now apply: negative margins and offsets, uppercase names and keywords, and !important values. Existing content can shift.
  • Values that main passed through are now dropped: invalid colors, currentColor and inherit.

@5ZYSZ3K
5ZYSZ3K requested a review from jsamr November 18, 2026 14:19
@5ZYSZ3K 5ZYSZ3K self-assigned this Nov 18, 2026
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.69%. Comparing base (2fe3a2e) to head (880500f).

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #61      +/-   ##
==========================================
+ Coverage   98.65%   98.69%   +0.03%     
==========================================
  Files         140      141       +1     
  Lines        2088     2147      +59     
  Branches      636      652      +16     
==========================================
+ Hits         2060     2119      +59     
  Misses         27       27              
  Partials        1        1              
Flag Coverage Δ
css-processor 100.00% <100.00%> (ø)
render 97.85% <ø> (ø)
transient-render-engine 98.95% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's not introduce a 10 yo unmaintained package for basically a list of strings...

@5ZYSZ3K 5ZYSZ3K Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It isn't really introduced, as it is already used under the hood by css-to-react-native.
But yes, it's old, I still need to extrapolate it, so you're right, it would be better to get rid of it.
Done

@jsamr jsamr Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@5ZYSZ3K The indirect dep was a fair argument, could have been addressed later. Thank you though

Comment on lines +9 to +15
return (
value
.split(HEX_COLOR_TOKEN_REGEX)
// Captured hex colors are at odd indexes.
.map((chunk, i) => (i % 2 === 1 ? chunk : chunk.toLowerCase()))
.join('')
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Lost track of the purpose of this code. Why are we lowercasing only odd indexes?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Splitting by regex with a capturing group always make string chunks captured by the group appear at even indexes, for example:
"1px solid #faf".split(/(#[0-9a-f]+)/i) gives [ "1px solid ", "#faf", "" ]
"#faf solid whatever".split(/(#[0-9a-f]+)/i) gives [ "", "#faf", " solid whatever" ]
"#faf".split(/(#[0-9a-f]+)/i) gives [ "", "#faf", "" ]

Here we lowercase everything that is not a hex color.
Arguably, this could be brought down to simple return value.toLowerCase(), and everything would work.
I just assumed that people are used to seeing uppercased hexes, and without it, in their devtools they would see them lowercased

But if you want me to simplify it and not care about the hex colors case, I can do it

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Now I get it; it's a way to exclude from lowercasing any word that matches a hex number regex. The higher end-goal still evades me though: To my knowledge, hex values are case insensitive in CSS.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, those are insensitive, and could be just as well always standardized.
My idea was to keep that exactly as it is, since it's insensitive anyway, I didn't it so that they change their casing or not depending on the surroundings, it just felt weird

But I can simplify this if you would like to get rid of that, I can just standardize the casing

if (normalizedValue === null && typeof rawValue === 'string') {
// CSS keywords are case-insensitive. Values valid as written are kept
// unchanged, others get a second attempt with lowercased keywords.
const lowercasedValue = validator.lowercaseInlineCSSKeywords(rawValue);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This lowercaseInlineCSSKeywords(rawValue) reads logically inconsistent. The argument is a raw value, hence we don't know yet if it's a keyword. But the method name is "lowercase inline CSS Keywords". Yet, not all values are keywords.

Also, you're introducing a mutable variable, when that can be avoided.

Consider this:

const rawValueOrKeyword = validator.isKeyword(rawValue) ? validator.normalizeKeyword(rawValue) : rawValue;
// CSS keywords are case-insensitive. Values valid as written are kept
// unchanged, others get a second attempt with lowercased keywords.
const normalizedValue =  validator.normalizeInlineCSSValue(rawValue) ?? validator.normalizeInlineCSSValue(rawValueOrKeyword) ;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed it
I didn't go with the isKeyword suggestion, because it would require quite a refactor - CSS values can be constructed from keywords and values at the same time (for example 1px solid red for border). But I changed the name and got rid of naming inconsistency

Comment on lines +12 to +20
/**
* The `!important` flag is stripped and ignored. Between style sources, this
* makes no difference: inline styles are merged last, and tagsStyles,
* classesStyles and idsStyles are JS objects which can't carry the flag.
* Within one style attribute however, declarations are applied in order, so
* a later declaration overrides an earlier important one, unlike in
* browsers: `color: red !important; color: blue` gives blue.
*/
const IMPORTANT_FLAG_REGEX = /\s*!\s*important\s*$/i;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The comment should document logic, not local declarations. Move it to where the stripping logic is applied, and use // to denote a code comment versus a JSDoc.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

fixed

5ZYSZ3K and others added 8 commits November 22, 2026 16:11
…them

Negative lengths such as `margin-top: -5px`, `top: -10%` or
`letter-spacing: -0.5px` were discarded because the length regex had no
sign, which also dropped whole shorthands like `margin: -10px 0`.

The length regex now accepts an optional sign and requires at least one
digit, so `px` and `.px` are no longer parsed as `0` and `NaN`. Size
validators reject negative values by default, while the new
LongSignedSizeCSSPropertyValidator allows them for margins, offsets
(top, right, bottom, left) and letter-spacing. `-0` is normalized to `0`.

Refs #59

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The color regex alternation was not grouped, so its first branch was
only anchored at the start and its second branch only at the end.
Invalid values such as `red !important`, `not a color` or
`url(x.png) blue` passed validation and reached React Native styles.

Colors are now validated as a whole against:
- hex colors with 3, 4, 6 or 8 digits;
- rgb(), rgba(), hsl() and hsla() functions, with the same grammar as
  before;
- named colors from css-color-keywords (already a transitive dependency
  via css-to-react-native), plus `transparent`, `cyan` and `magenta`
  which React Native supports.

Other keywords are discarded, including `inherit` and `currentColor`,
which iOS and Android reject. `color` is already inherited by the render
engine, so discarding `inherit` gives the expected result.

Refs #59

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The `!important` flag was kept as part of the value, so declarations
like `margin-top: 5px !important` or `display: flex !important` were
discarded, while forgiving properties such as `font-family` kept the
flag in their value.

The flag is now stripped from every inline declaration, regardless of
case and whitespace, and ignored. Between style sources, this makes no
difference: inline styles are merged last, and tagsStyles,
classesStyles and idsStyles are JS objects which can't carry the flag.
Within one style attribute, declarations are still applied in order,
so `color: red !important; color: blue` gives blue where a browser
shows red, as it did before this change.

The CSS concepts documentation page now states that the flag is
accepted and ignored in inline styles.

Refs #59

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nsitively

CSS property names and keywords are ASCII case-insensitive, but
uppercase or mixed-case names (`COLOR: red`, `Font-Size: 20px`) failed
registry lookup, and uppercase keywords (`display: FLEX`,
`margin-top: 5PX`, `color: RED`) were either discarded or passed through
to React Native, which rejects them.

Names and values are first matched as written, so values which are
valid as written are kept unchanged (e.g. `#FFF`) and camelCase
property names such as `paddingBottom` keep working. On failure, they
get a second attempt lowercased:
- property names are lowercased before being camelCased;
- validators opt into keyword lowercasing with the new
  lowercaseInlineCSSKeywords method: enumerations, sizes (units, `auto`,
  border width and font size keywords), colors and shorthands relying on
  css-to-react-native (border, background, flex-flow, text-decoration);
- hex colors are never lowercased, and the font shorthand only
  lowercases the part preceding the font family;
- font-family, list-style-type and transform values are left untouched,
  since lowercasing would change what they refer to: font families are
  matched by exact name against the available fonts, list style types
  may name user-defined customListStyleSpecs entries, and
  css-to-react-native expects camelCase transform functions such as
  `translateX`.

This only applies to inline CSS: React Native style values stay
case-sensitive.

Refs #59

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…x values

Two lines were left uncovered:
- ShortFontCSSValidator.lowercaseInlineCSSKeywords returns the value
  unchanged when it has no font size;
- ShortMergeRequest.entries with null properties is no longer reached
  through ShortCSSToReactNativeValidator, which now returns null when
  css-to-react-native can't expand a value. It is still reached through
  the flex shorthand.

Also reformat a test changed by the case-insensitivity commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@5ZYSZ3K
5ZYSZ3K requested a review from jsamr November 22, 2026 17:03
@5ZYSZ3K
5ZYSZ3K force-pushed the fix/css-processor-inline-css-validation branch from 9bfbb49 to 7b51ace Compare November 22, 2026 17:11
Comment on lines +173 to +177
<InlineCode>important!</InlineCode> directives, complex selectors such
as <InlineCode>div &gt; *</InlineCode>, pseudo-classes and
pseudo-elements are not supported.
The <InlineCode>!important</InlineCode> flag is accepted and ignored
in inline styles: a later declaration in the same{' '}
<RefHtmlAttr name="style" /> attribute still overrides it. Complex
selectors such as <InlineCode>div &gt; *</InlineCode>, pseudo-classes
and pseudo-elements are not supported.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Criticism of my past self: I find the "not supported" expression ambiguous. Also, !important is always ignored, there is nothing specific to inline styles. Let's be slightly more explicit:

Suggested change
<InlineCode>important!</InlineCode> directives, complex selectors such
as <InlineCode>div &gt; *</InlineCode>, pseudo-classes and
pseudo-elements are not supported.
The <InlineCode>!important</InlineCode> flag is accepted and ignored
in inline styles: a later declaration in the same{' '}
<RefHtmlAttr name="style" /> attribute still overrides it. Complex
selectors such as <InlineCode>div &gt; *</InlineCode>, pseudo-classes
and pseudo-elements are not supported.
The <InlineCode>!important</InlineCode> flag will be ignored. Declaration blocks
after complex selectors such as <InlineCode>div &gt; *</InlineCode>,
pseudo-classes and pseudo-elements will be ignored.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

done

Comment on lines +72 to +90
/**
* Normalize the lowercased form of a raw inline CSS value, or return null
* when lowercasing leaves it unchanged, since it already failed as written.
*
* @remarks Values can be non-strings when expanded from a shorthand.
*/
private normalizeLowercasedValue(
validator: GenericCSSPropertyValidator,
rawValue: unknown
) {
if (typeof rawValue !== 'string') {
return null;
}
const lowercasedValue = validator.lowercaseInlineCSSValue(rawValue);
return lowercasedValue === rawValue
? null
: validator.normalizeInlineCSSValue(lowercasedValue);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This part of the PR i'm not following. In #59, the problem was property names, not values.

Can you explain in more details what lower-casing values addresses?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I just felt like such a request might follow.
I decided to go ahead and make an opt-in solution that lowercases values too

CSS allows for example text-decoration: UNDERLINE, and RN doesn't work with textDecorationLine: "UNDERLINE", it needs to be lowercased

@5ZYSZ3K
5ZYSZ3K requested a review from jsamr November 26, 2026 22:45

This branch has not been deployed

No deployments
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.

css-processor: negative lengths and uppercase property names are dropped, and color validator accepts invalid strings

2 participants