Repository navigation
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Let's not introduce a 10 yo unmaintained package for basically a list of strings...
There was a problem hiding this comment.
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
There was a problem hiding this comment.
@5ZYSZ3K The indirect dep was a fair argument, could have been addressed later. Thank you though
| return ( | ||
| value | ||
| .split(HEX_COLOR_TOKEN_REGEX) | ||
| // Captured hex colors are at odd indexes. | ||
| .map((chunk, i) => (i % 2 === 1 ? chunk : chunk.toLowerCase())) | ||
| .join('') | ||
| ); |
There was a problem hiding this comment.
Lost track of the purpose of this code. Why are we lowercasing only odd indexes?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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) ;There was a problem hiding this comment.
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
| /** | ||
| * 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; |
There was a problem hiding this comment.
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.
…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>
9bfbb49 to
7b51ace
Compare
| <InlineCode>important!</InlineCode> directives, complex selectors such | ||
| as <InlineCode>div > *</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 > *</InlineCode>, pseudo-classes | ||
| and pseudo-elements are not supported. |
There was a problem hiding this comment.
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:
| <InlineCode>important!</InlineCode> directives, complex selectors such | |
| as <InlineCode>div > *</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 > *</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 > *</InlineCode>, | |
| pseudo-classes and pseudo-elements will be ignored. |
| /** | ||
| * 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); | ||
| } | ||
|
|
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
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 frommainbeyond it.Validators
The diff below leaves out intermediate base classes.
lowercaseInlineCSSKeywordsis overridden by validators of sizes, colors, enumerations and css-to-react-native shorthands (border,background,flex-flow,text-decoration,font). They call the newlowercaseCSSKeywordshelper, which leaves hex colors as written.Inline parsing
Design decisions
mainstill gives the same output. camelCase names such aspaddingBottomstill resolve, and a test inrenderrelies on that.#FFFkeeps its case.font-familyis left out because fonts are matched by exact name.list-style-typeis left out because it may name a user-definedcustomListStyleSpecsentry.transformis left out because css-to-react-native expects camelCase function names such astranslateX.fontshorthand, only the part up to the font size is lowercased, so the family keeps its case.fontVariantkeeps the valid items and drops the rest. Insmall-caps OLDSTYLE-NUMS,small-capsis already valid as written, so the second attempt would never run and the second item would be lost.nullon failure. Before, a failed expansion was wrapped in a merge request that merged nothing. ReturningnullletsnormalizePropsee the failure and try again lowercased.splitValueAndUnitrejects negative values unlessallowsNegativeValues()returns true.\w+.css-color-keywordswas already installed throughcss-to-react-native. It is now a direct dependency, with a local type declaration.Behavior changes
maincolor: red !important{ color: 'red !important' }{ color: 'red' }{}. Instead the flag is stripped from every declaration, somargin-top: 5px !importantnow applies too.display: FLEX,border: 1PX SOLID RED{}color: currentColor,color: inherit{}border-color: currentColornow falls back to black.margin-top: px{ marginTop: 0 }{}+5px,.5pxand-0are accepted.tagsStyles: { marginTop: '-5px' }{}{ marginTop: -5 }'px'is now dropped there as well.Unchanged on purpose:
tagsStyles,classesStyles,idsStyles):{ display: 'FLEX' }fails there.{ paddingTop: -5 }is kept.main.!importantwithin onestyleattribute: a later declaration still overrides an earlier important one.color: red !important; color: bluegives blue, where a browser shows red. The docs now say that the flag is accepted and ignored.Evidence
css-processorpassesyarn 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.transient-render-engine(191 tests) andrender(265 tests) pass, and the type check and lint pass fordoc-pages.Merge Danger
Door: Two-way
The changes stay inside
css-processorvalidation code. Validators aren't exported, so no public API changes. Reverting the commits restores the old output.Blast Radius: Styling
maindropped now apply: negative margins and offsets, uppercase names and keywords, and!importantvalues. Existing content can shift.mainpassed through are now dropped: invalid colors,currentColorandinherit.