From ffafb2f805d1bc24ce4c7da7f99289d0384eebd6 Mon Sep 17 00:00:00 2001 From: 5ZYSZ3K Date: Tue, 17 Nov 2026 23:52:51 +0100 Subject: [PATCH 1/5] fix(css-processor): accept negative lengths on properties that allow 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 --- .../src/__tests__/CSSProcessor.test.ts | 87 ++++++++++++++----- .../src/makepropertiesValidators.ts | 19 ++-- .../LongSignedSizeCSSPropertyValidator.ts | 14 +++ .../LongSizeCSSPropertyValidator.ts | 28 ++++-- 4 files changed, 111 insertions(+), 37 deletions(-) create mode 100644 packages/css-processor/src/validators/LongSignedSizeCSSPropertyValidator.ts diff --git a/packages/css-processor/src/__tests__/CSSProcessor.test.ts b/packages/css-processor/src/__tests__/CSSProcessor.test.ts index de85ed38..53cf9114 100644 --- a/packages/css-processor/src/__tests__/CSSProcessor.test.ts +++ b/packages/css-processor/src/__tests__/CSSProcessor.test.ts @@ -25,6 +25,9 @@ type Specs = { type SpecsModel = Pick; +// Only allowed for signed sizes (margins, offsets, letter-spacing) +const negativeLengthSamples = ['-5px', '-10%', '-.5em']; + const lengthSamples = [ '0', // no-unit 'auto', // special value @@ -44,7 +47,13 @@ const lengthSamples = [ 'inherit', // should be ignored 'calc(100% - 80px)', // should be ignored 'var(--main-bg-color)', // should be ignored - 'not-a-dimension!' // should be ignored + 'not-a-dimension!', // should be ignored + 'px', // no number, should be ignored + '.px', // no digit, should be ignored + '+5px', // explicit positive sign + '-0', // signed unitless zero + '-0px', // negative zero + ...negativeLengthSamples ]; const sizeSpec: Pick< @@ -72,7 +81,25 @@ const sizeSpec: Pick< null, // inherit null, // calc(...) null, // var(...) - null // not-a-dimension! + null, // not-a-dimension! + null, // px + null, // .px + 5, // +5px + 0, // -0 + 0, // -0px + null, // -5px + null, // -10% + null // -.5em + ] +}; + +const signedSizeSpec: typeof sizeSpec = { + ...sizeSpec, + outValues: [ + ...sizeSpec.outValues.slice(0, -negativeLengthSamples.length), + -5, // -5px + '-10%', // -10% + -8 // -.5em ] }; @@ -432,22 +459,22 @@ describe('CSSProcessor', () => { ...sizeSpec, ...nativeRetainedBlockSpec }; + const nativeRetainedBlockSignedSizeSpecModel = { + ...signedSizeSpec, + ...nativeRetainedBlockSpec + }; const nativeRetainedBlockNonPercentSizeSpecModel: Specs = { ...sizeSpec, ...nativeRetainedBlockSpec, - inlineIncomingValues: ['10px', '10%'], - mixedIncomingValues: [10, '10%'], - outValues: [10, null] + inlineIncomingValues: ['10px', '10%', '-10px'], + mixedIncomingValues: [10, '10%', '-10px'], + outValues: [10, null, null] }; const retainedWebBlockSpec: SpecsModel = { compat: 'web', display: 'block', propagation: 'retain' }; - const retainedNativeBlockSizeSpec = { - ...nativeRetainedBlockSpec, - ...sizeSpec - }; const borderWidthValues = [ ...sizeSpec.inlineIncomingValues, 'thin', @@ -546,10 +573,10 @@ describe('CSSProcessor', () => { inlineIncomingValues: propertiesValidators.position.allowedList, mixedIncomingValues: propertiesValidators.position.allowedList }, - left: retainedNativeBlockSizeSpec, - right: retainedNativeBlockSizeSpec, - top: retainedNativeBlockSizeSpec, - bottom: retainedNativeBlockSizeSpec, + left: nativeRetainedBlockSignedSizeSpecModel, + right: nativeRetainedBlockSignedSizeSpecModel, + top: nativeRetainedBlockSignedSizeSpecModel, + bottom: nativeRetainedBlockSignedSizeSpecModel, direction: { compat: 'native', display: 'block', @@ -577,10 +604,10 @@ describe('CSSProcessor', () => { borderTopColor: nativeRetainedBlockColorSpecModel, borderTopWidth: borderWidthSpec, height: nativeRetainedBlockSizeSpecModel, - marginBottom: nativeRetainedBlockSizeSpecModel, - marginLeft: nativeRetainedBlockSizeSpecModel, - marginRight: nativeRetainedBlockSizeSpecModel, - marginTop: nativeRetainedBlockSizeSpecModel, + marginBottom: nativeRetainedBlockSignedSizeSpecModel, + marginLeft: nativeRetainedBlockSignedSizeSpecModel, + marginRight: nativeRetainedBlockSignedSizeSpecModel, + marginTop: nativeRetainedBlockSignedSizeSpecModel, maxHeight: nativeRetainedBlockSizeSpecModel, maxWidth: nativeRetainedBlockSizeSpecModel, minHeight: nativeRetainedBlockSizeSpecModel, @@ -715,14 +742,14 @@ describe('CSSProcessor', () => { ], outValues: [...propertiesValidators.fontWeight.allowedList, null] }, - letterSpacing: { ...flowedNativeTextSpec, ...sizeSpec }, + letterSpacing: { ...flowedNativeTextSpec, ...signedSizeSpec }, lineHeight: { compat: 'native', display: 'text', propagation: 'flow', - inlineIncomingValues: ['1px', '1em'], + inlineIncomingValues: ['1px', '1em', '-1px'], mixedIncomingValues: null, - outValues: [1, 16] + outValues: [1, 16, null] }, textAlign: { ...flowedNativeTextSpec, @@ -1071,7 +1098,9 @@ describe('CSSProcessor', () => { 'auto', '0 auto', '2px 3px auto', - '1px 2px 3px 4px' + '1px 2px 3px 4px', + '-10px 0', + '0 -5px 0 -5%' ], mixedIncomingValues: null, outProps: [ @@ -1098,6 +1127,18 @@ describe('CSSProcessor', () => { marginRight: 2, marginBottom: 3, marginLeft: 4 + }, + { + marginTop: -10, + marginRight: 0, + marginBottom: -10, + marginLeft: 0 + }, + { + marginTop: 0, + marginRight: -5, + marginBottom: 0, + marginLeft: '-5%' } ] }, @@ -1110,7 +1151,8 @@ describe('CSSProcessor', () => { '1px 2px 3px', '1px 2px', '1px', - '1px 1px 1px 1px 1px' // illegal + '1px 1px 1px 1px 1px', // illegal + '-1px 2px' // illegal, padding cannot be negative ], mixedIncomingValues: null, outProps: [ @@ -1138,6 +1180,7 @@ describe('CSSProcessor', () => { paddingBottom: 1, paddingLeft: 1 }, + null, null ] } diff --git a/packages/css-processor/src/makepropertiesValidators.ts b/packages/css-processor/src/makepropertiesValidators.ts index 2408b3f4..9162afc4 100644 --- a/packages/css-processor/src/makepropertiesValidators.ts +++ b/packages/css-processor/src/makepropertiesValidators.ts @@ -4,6 +4,7 @@ import { LongFloatNumberCSSPropertyValidator } from './validators/LongFloatNumbe import { LongBorderWidthCSSPropertyValidator } from './validators/LongBorderWidthCSSPropertyValidator'; import { LongFontSizeCSSValidator } from './validators/LongFontSizeCSSValidator'; import { LongSizeCSSPropertyValidator } from './validators/LongSizeCSSPropertyValidator'; +import { LongSignedSizeCSSPropertyValidator } from './validators/LongSignedSizeCSSPropertyValidator'; import { LongAspectRatioPropertyValidator } from './validators/LongAspectRatioPropertyValidator'; import { LongEnumerationListCSSPropertyValidator } from './validators/LongEnumerationListCSSPropertyValidator'; import { LongBorderStyleCSSPropertyValidator } from './validators/LongBorderStyleCSSPropertyValidator'; @@ -292,7 +293,7 @@ export default function makepropertiesValidators(config: CSSProcessorConfig) { '900' ] ), - letterSpacing: new LongSizeCSSPropertyValidator({ + letterSpacing: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'letterSpacing', model: nativeTranslatableTextFlowModel @@ -372,7 +373,7 @@ export default function makepropertiesValidators(config: CSSProcessorConfig) { model: nativeTranslatableBlockRetainModel, propertyName: 'aspectRatio' }), - bottom: new LongSizeCSSPropertyValidator({ + bottom: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'bottom', model: nativeTranslatableBlockRetainModel @@ -431,7 +432,7 @@ export default function makepropertiesValidators(config: CSSProcessorConfig) { 'space-evenly' ] ), - left: new LongSizeCSSPropertyValidator({ + left: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'left', model: nativeTranslatableBlockRetainModel @@ -444,12 +445,12 @@ export default function makepropertiesValidators(config: CSSProcessorConfig) { }, ['absolute', 'relative'] ), - right: new LongSizeCSSPropertyValidator({ + right: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'right', model: nativeTranslatableBlockRetainModel }), - top: new LongSizeCSSPropertyValidator({ + top: new LongSignedSizeCSSPropertyValidator({ config, model: nativeTranslatableBlockRetainModel, propertyName: 'top' @@ -532,22 +533,22 @@ export default function makepropertiesValidators(config: CSSProcessorConfig) { propertyName: 'height', model: nativeTranslatableBlockRetainModel }), - marginBottom: new LongSizeCSSPropertyValidator({ + marginBottom: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'marginBottom', model: nativeTranslatableBlockRetainModel }), - marginLeft: new LongSizeCSSPropertyValidator({ + marginLeft: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'marginLeft', model: nativeTranslatableBlockRetainModel }), - marginRight: new LongSizeCSSPropertyValidator({ + marginRight: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'marginRight', model: nativeTranslatableBlockRetainModel }), - marginTop: new LongSizeCSSPropertyValidator({ + marginTop: new LongSignedSizeCSSPropertyValidator({ config, propertyName: 'marginTop', model: nativeTranslatableBlockRetainModel diff --git a/packages/css-processor/src/validators/LongSignedSizeCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongSignedSizeCSSPropertyValidator.ts new file mode 100644 index 00000000..ea8f5638 --- /dev/null +++ b/packages/css-processor/src/validators/LongSignedSizeCSSPropertyValidator.ts @@ -0,0 +1,14 @@ +import { LongSizeCSSPropertyValidator } from './LongSizeCSSPropertyValidator'; +import { CSSPropertyModel } from './types'; + +/** + * A validator for size properties accepting negative lengths, such as + * margins, offsets (top, right, bottom, left) and letter-spacing. + */ +export class LongSignedSizeCSSPropertyValidator< + C extends CSSPropertyModel +> extends LongSizeCSSPropertyValidator { + protected allowsNegativeValues(): boolean { + return true; + } +} diff --git a/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts index 19be4aaf..d79c7a61 100644 --- a/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts @@ -2,9 +2,23 @@ import { CSSLengthUnit } from '../config'; import { LongCSSPropertyValidator } from './LongCSSPropertyValidator'; import { CSSPropertyModel } from './types'; +const LENGTH_REGEX = + /^([+-]?(?:\d+\.?\d*|\.\d+))\s*(cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)$/; + +const UNITLESS_ZERO_REGEX = /^[+-]?0$/; + export class LongSizeCSSPropertyValidator< C extends CSSPropertyModel > extends LongCSSPropertyValidator { + /** + * Whether this property accepts negative lengths. Most size properties + * (padding, width, font-size...) don't, see + * {@link LongSignedSizeCSSPropertyValidator} for those which do. + */ + protected allowsNegativeValues(): boolean { + return false; + } + protected computeSize( value: number, unit: CSSLengthUnit @@ -36,18 +50,20 @@ export class LongSizeCSSPropertyValidator< } protected splitValueAndUnit(value: string): [number, CSSLengthUnit] | null { - const match = - /^(\d*\.?\d*)\s*(cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)$/g.exec( - value - ); + const match = LENGTH_REGEX.exec(value); if (match === null) { return null; } - return [Number(match[1]), match[2] as CSSLengthUnit]; + const size = Number(match[1]); + if (size < 0 && !this.allowsNegativeValues()) { + return null; + } + // Normalize -0 to 0 + return [size === 0 ? 0 : size, match[2] as CSSLengthUnit]; } normalizeRawInlineCSSValue(value: string) { - if (value === '0') { + if (UNITLESS_ZERO_REGEX.test(value)) { return 0; } if (value === 'auto') { From c4787f141b87306c9a269e538ecf02fdb28fb065 Mon Sep 17 00:00:00 2001 From: 5ZYSZ3K Date: Tue, 17 Nov 2026 23:53:53 +0100 Subject: [PATCH 2/5] fix(css-processor): reject invalid color values 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 --- packages/css-processor/package.json | 1 + .../css-processor/src/css-color-keywords.d.ts | 7 ++++ .../LongColorCSSPropertyValidator.ts | 22 ++++++++++- .../LongColorCSSPropertyValidator.test.ts | 38 +++++++++++++++++++ yarn.lock | 1 + 5 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 packages/css-processor/src/css-color-keywords.d.ts diff --git a/packages/css-processor/package.json b/packages/css-processor/package.json index 1c449127..966dcdee 100644 --- a/packages/css-processor/package.json +++ b/packages/css-processor/package.json @@ -34,6 +34,7 @@ "prepack": "yarn run build" }, "dependencies": { + "css-color-keywords": "^1.0.0", "css-to-react-native": "^3.2.0", "csstype": "^3.1.3" }, diff --git a/packages/css-processor/src/css-color-keywords.d.ts b/packages/css-processor/src/css-color-keywords.d.ts new file mode 100644 index 00000000..3453d9c9 --- /dev/null +++ b/packages/css-processor/src/css-color-keywords.d.ts @@ -0,0 +1,7 @@ +declare module 'css-color-keywords' { + /** + * A record of CSS named colors, from name to hex value. + */ + const colorKeywords: Record; + export default colorKeywords; +} diff --git a/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts index 1568a078..cd66da58 100644 --- a/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts @@ -1,12 +1,30 @@ +import colorKeywords from 'css-color-keywords'; import { LongForgivingCSSPropertyValidator } from './LongForgivingCSSPropertyValidator'; import { CSSPropertyModel } from './types'; -const COLOR_REGEX = /^(rgb|rgba|hsl|hsla)\([\d,%. ]+\)|[#]?\w+$/; +const HEX_COLOR_REGEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i; + +const FUNCTIONAL_COLOR_REGEX = /^(?:rgb|rgba|hsl|hsla)\([\d,%. ]+\)$/; + +const NAMED_COLORS = new Set([ + ...Object.keys(colorKeywords), + // Supported by React Native, missing from css-color-keywords + 'transparent', + 'cyan', + 'magenta' +]); export class LongColorCSSPropertyValidator< C extends CSSPropertyModel > extends LongForgivingCSSPropertyValidator { normalizeRawInlineCSSValue(value: string): string | null { - return value.match(COLOR_REGEX) ? value : null; + if ( + NAMED_COLORS.has(value) || + HEX_COLOR_REGEX.test(value) || + FUNCTIONAL_COLOR_REGEX.test(value) + ) { + return value; + } + return null; } } diff --git a/packages/css-processor/src/validators/__tests__/LongColorCSSPropertyValidator.test.ts b/packages/css-processor/src/validators/__tests__/LongColorCSSPropertyValidator.test.ts index be9b1f42..9c90f1c6 100644 --- a/packages/css-processor/src/validators/__tests__/LongColorCSSPropertyValidator.test.ts +++ b/packages/css-processor/src/validators/__tests__/LongColorCSSPropertyValidator.test.ts @@ -20,8 +20,46 @@ describe('LongColorCSSPropertyValidator', () => { it('should support hex colors', () => { expect(validator.normalizeRawInlineCSSValue('#121010')).toBe('#121010'); }); + it('should support hex colors with 3, 4, 6 and 8 digits, preserving case', () => { + for (const hex of ['#FFF', '#ffff', '#AbCdEf', '#abcdef80']) { + expect(validator.normalizeRawInlineCSSValue(hex)).toBe(hex); + } + }); + it('should reject hex colors with an invalid length or invalid digits', () => { + for (const hex of ['#', '#ff', '#fffff', '#fffffff', '#zzz', 'fff']) { + expect(validator.normalizeRawInlineCSSValue(hex)).toBe(null); + } + }); it('should support named colors', () => { expect(validator.normalizeRawInlineCSSValue('red')).toBe('red'); + expect(validator.normalizeRawInlineCSSValue('rebeccapurple')).toBe( + 'rebeccapurple' + ); + }); + it('should support named colors missing from css-color-keywords', () => { + for (const name of ['transparent', 'cyan', 'magenta']) { + expect(validator.normalizeRawInlineCSSValue(name)).toBe(name); + } + }); + it('should reject color keywords unsupported by React Native', () => { + for (const name of ['currentColor', 'currentcolor', 'inherit']) { + expect(validator.normalizeRawInlineCSSValue(name)).toBe(null); + } + }); + it('should reject unknown color names', () => { + expect(validator.normalizeRawInlineCSSValue('notacolor')).toBe(null); + }); + it('should reject values with trailing or leading garbage', () => { + for (const value of [ + 'not a color', + 'red !important', + 'rgb(0, 0, 0) !important', + 'url(x.png) blue', + 'red blue', + 'rgb(0,0,0) red' + ]) { + expect(validator.normalizeRawInlineCSSValue(value)).toBe(null); + } }); it('should reject empty values', () => { expect(validator.normalizeRawInlineCSSValue(' ')).toBe(null); diff --git a/yarn.lock b/yarn.lock index 151a0512..50946318 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5111,6 +5111,7 @@ __metadata: "@types/react-native": "npm:^0.73.0" babel-jest: "npm:^29.7.0" change-case: "npm:^5.4.4" + css-color-keywords: "npm:^1.0.0" css-to-react-native: "npm:^3.2.0" csstype: "npm:^3.1.3" eslint: "npm:^8.57.1" From 33a2f9fdbda054f428895c8bccbb0ebd847427f5 Mon Sep 17 00:00:00 2001 From: 5ZYSZ3K Date: Tue, 17 Nov 2026 23:54:21 +0100 Subject: [PATCH 3/5] fix(css-processor): ignore !important in inline styles 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 --- .../doc-pages/src/pages/PageConceptCSS.tsx | 8 +-- .../css-processor/src/CSSInlineParseRun.ts | 15 +++++- .../src/__tests__/CSSProcessor.test.ts | 50 +++++++++++++++++++ 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx b/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx index b00c5dc1..6419fe76 100644 --- a/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx +++ b/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx @@ -170,9 +170,11 @@ export default function PageConceptCSS() { precedence over classes styles, ...etc. - important! directives, complex selectors such - as div > *, pseudo-classes and - pseudo-elements are not supported. + The !important flag is accepted and ignored + in inline styles: a later declaration in the same{' '} + attribute still overrides it. Complex + selectors such as div > *, pseudo-classes + and pseudo-elements are not supported. diff --git a/packages/css-processor/src/CSSInlineParseRun.ts b/packages/css-processor/src/CSSInlineParseRun.ts index ba1cd892..26ce960c 100644 --- a/packages/css-processor/src/CSSInlineParseRun.ts +++ b/packages/css-processor/src/CSSInlineParseRun.ts @@ -9,6 +9,16 @@ import { LongCSSPropertyValidator } from './validators/LongCSSPropertyValidator' type CSSRawPropertiesList = [string, any][]; +/** + * 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; + export class CSSInlineParseRun extends CSSParseRun { private rules: CSSRawPropertiesList; @@ -25,7 +35,10 @@ export class CSSInlineParseRun extends CSSParseRun { .map((prop) => prop.split(':')) .reduce((acc, prop) => { if (prop.length === 2) { - return [...acc, [prop[0].trim(), prop[1].trim()]]; + return [ + ...acc, + [prop[0].trim(), prop[1].replace(IMPORTANT_FLAG_REGEX, '').trim()] + ]; } return acc; }, []); diff --git a/packages/css-processor/src/__tests__/CSSProcessor.test.ts b/packages/css-processor/src/__tests__/CSSProcessor.test.ts index 53cf9114..6b4c5ea4 100644 --- a/packages/css-processor/src/__tests__/CSSProcessor.test.ts +++ b/packages/css-processor/src/__tests__/CSSProcessor.test.ts @@ -403,6 +403,56 @@ describe('CSSProcessor', () => { processor.compileInlineCSS('padding-horizontal: 10px;') ).toStrictEqual(new CSSProcessedProps()); }); + describe('regarding the !important flag', () => { + const flatten = (output: CSSProcessedProps) => ({ + ...output.native.text.flow, + ...output.native.text.retain, + ...output.native.block.flow, + ...output.native.block.retain + }); + it('should ignore the flag on longhand properties', () => { + expect( + flatten( + processor.compileInlineCSS( + 'color: red !important; margin-top: 5px !important; display: flex !important; font-size: 20px !important' + ) + ) + ).toStrictEqual({ + color: 'red', + marginTop: 5, + display: 'flex', + fontSize: 20 + }); + }); + it('should ignore the flag on shorthand properties', () => { + expect( + flatten(processor.compileInlineCSS('margin: -10px 0 !important')) + ).toStrictEqual({ + marginTop: -10, + marginRight: 0, + marginBottom: -10, + marginLeft: 0 + }); + }); + it('should ignore the flag regardless of case and whitespace', () => { + expect( + flatten( + processor.compileInlineCSS( + 'color: rgb(0, 0, 0)!important; background-color: blue ! IMPORTANT ;' + ) + ) + ).toStrictEqual({ + color: 'rgb(0, 0, 0)', + backgroundColor: 'blue' + }); + }); + it('should not leak the flag into forgiving properties', () => { + expect( + processor.compileInlineCSS('font-family: Arial !important').native + .text.flow + ).toStrictEqual({ fontFamily: 'Arial' }); + }); + }); it('should ignore rules from the inlinePropertiesBlacklist config array', () => { const processorWithIgnoreStyles = new CSSProcessor({ ...defaultCSSProcessorConfig, From 49723d0ef286f61e0558a0db859b839e3fd46723 Mon Sep 17 00:00:00 2001 From: 5ZYSZ3K Date: Tue, 17 Nov 2026 23:59:46 +0100 Subject: [PATCH 4/5] fix(css-processor): treat property names and keyword values case-insensitively 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 --- .../css-processor/src/CSSInlineParseRun.ts | 39 +++- .../src/__tests__/CSSProcessor.test.ts | 176 +++++++++++++++++- packages/css-processor/src/helpers.ts | 17 ++ .../validators/GenericPropertyValidator.ts | 20 ++ .../LongColorCSSPropertyValidator.ts | 5 + .../LongEnumerationCSSPropertyValidator.ts | 5 + ...LongEnumerationListCSSPropertyValidator.ts | 10 +- .../LongSizeCSSPropertyValidator.ts | 5 + .../ShortCSSToReactNativeValidator.ts | 8 +- .../src/validators/ShortFontCSSValidator.ts | 26 +++ 10 files changed, 299 insertions(+), 12 deletions(-) diff --git a/packages/css-processor/src/CSSInlineParseRun.ts b/packages/css-processor/src/CSSInlineParseRun.ts index 26ce960c..c32cf18d 100644 --- a/packages/css-processor/src/CSSInlineParseRun.ts +++ b/packages/css-processor/src/CSSInlineParseRun.ts @@ -44,18 +44,51 @@ export class CSSInlineParseRun extends CSSParseRun { }, []); } + /** + * Find the registered property matching a raw inline CSS property name. + * + * @remarks CSS property names are ASCII case-insensitive (e.g. `COLOR`). + * Names registered as written are kept, which preserves support for + * camelCase names (e.g. `paddingBottom`), others get a second attempt + * lowercased. + */ + private resolvePropertyName(rawName: string): keyof ValidatorsType | null { + const camelCaseName = getPropertyName(rawName); + if (this.validationMap.shouldRegisterInlineProperty(camelCaseName)) { + return camelCaseName; + } + const lowercasedName = rawName.toLowerCase(); + if (lowercasedName !== rawName) { + const lowercasedCamelCaseName = getPropertyName(lowercasedName); + if ( + this.validationMap.shouldRegisterInlineProperty(lowercasedCamelCaseName) + ) { + return lowercasedCamelCaseName; + } + } + return null; + } + normalizeProp( rule: CSSRawPropertiesList[number], strict = false ): null | [keyof ValidatorsType, any] { const rawName = rule[0]; const rawValue = rule[1]; - const camelCaseName = getPropertyName(rawName); - if (!this.validationMap.shouldRegisterInlineProperty(camelCaseName)) { + const camelCaseName = this.resolvePropertyName(rawName); + if (camelCaseName === null) { return null; } const validator = this.validationMap.getValidatorForProperty(camelCaseName); - const normalizedValue = validator.normalizeInlineCSSValue(rawValue); + let normalizedValue = validator.normalizeInlineCSSValue(rawValue); + 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); + if (lowercasedValue !== rawValue) { + normalizedValue = validator.normalizeInlineCSSValue(lowercasedValue); + } + } if (normalizedValue === null) { if (strict) { throw new TypeError(); diff --git a/packages/css-processor/src/__tests__/CSSProcessor.test.ts b/packages/css-processor/src/__tests__/CSSProcessor.test.ts index 6b4c5ea4..5e51fa6e 100644 --- a/packages/css-processor/src/__tests__/CSSProcessor.test.ts +++ b/packages/css-processor/src/__tests__/CSSProcessor.test.ts @@ -13,6 +13,22 @@ import { ExtraNativeShortViewStyleKeys } from '../native-types'; const processor = new CSSProcessor(defaultCSSProcessorConfig); const propertiesValidators = processor.registry.validators; +/** + * Merge all categories of processed props into one record. + */ +function flatten(output: CSSProcessedProps) { + return { + ...output.native.text.flow, + ...output.native.text.retain, + ...output.native.block.flow, + ...output.native.block.retain, + ...output.web.text.flow, + ...output.web.text.retain, + ...output.web.block.flow, + ...output.web.block.retain + }; +} + type Specs = { readonly inlineIncomingValues: ReadonlyArray; readonly mixedIncomingValues: ReadonlyArray | null; @@ -377,6 +393,21 @@ describe('CSSProcessor', () => { } as any) ).toEqual(new CSSProcessedProps()); }); + it('should not match keyword values case-insensitively', () => { + expect( + flatten( + processor.compileStyleDeclaration({ + display: 'FLEX', + marginTop: '5PX' + } as any) + ) + ).toStrictEqual({}); + }); + it('should not validate the sign of numeric values', () => { + expect( + flatten(processor.compileStyleDeclaration({ paddingTop: -5 })) + ).toStrictEqual({ paddingTop: -5 }); + }); it('should ignore unknown properties', () => { console.warn = jest.fn(); expect( @@ -404,12 +435,6 @@ describe('CSSProcessor', () => { ).toStrictEqual(new CSSProcessedProps()); }); describe('regarding the !important flag', () => { - const flatten = (output: CSSProcessedProps) => ({ - ...output.native.text.flow, - ...output.native.text.retain, - ...output.native.block.flow, - ...output.native.block.retain - }); it('should ignore the flag on longhand properties', () => { expect( flatten( @@ -453,6 +478,145 @@ describe('CSSProcessor', () => { ).toStrictEqual({ fontFamily: 'Arial' }); }); }); + describe('regarding case-insensitivity', () => { + it('should match property names case-insensitively', () => { + expect( + flatten( + processor.compileInlineCSS( + 'COLOR: red; Font-Size: 20px; MARGIN: 10px' + ) + ) + ).toStrictEqual({ + color: 'red', + fontSize: 20, + marginTop: 10, + marginRight: 10, + marginBottom: 10, + marginLeft: 10 + }); + }); + it('should keep supporting camelCase property names', () => { + expect( + flatten( + processor.compileInlineCSS( + 'paddingBottom: 10px; backgroundColor: red' + ) + ) + ).toStrictEqual({ + paddingBottom: 10, + backgroundColor: 'red' + }); + }); + it('should apply inlinePropertiesBlacklist regardless of property names case', () => { + const processorWithIgnoreStyles = new CSSProcessor({ + ...defaultCSSProcessorConfig, + inlinePropertiesBlacklist: ['backgroundColor'] + }); + expect( + processorWithIgnoreStyles.compileInlineCSS('BACKGROUND-COLOR: red;') + ).toStrictEqual(new CSSProcessedProps()); + }); + it('should match keyword values case-insensitively', () => { + expect( + flatten( + processor.compileInlineCSS( + 'display: FLEX; font-weight: BOLD; font-variant: small-caps OLDSTYLE-NUMS; border-style: SOLID; margin-top: AUTO; margin-left: -5PX; border-top-width: THIN; font-size: LARGE' + ) + ) + ).toStrictEqual({ + display: 'flex', + fontWeight: 'bold', + fontVariant: ['small-caps', 'oldstyle-nums'], + borderStyle: 'solid', + marginTop: 'auto', + marginLeft: -5, + borderTopWidth: + propertiesValidators.borderTopWidth.normalizeInlineCSSValue('thin'), + fontSize: + propertiesValidators.fontSize.normalizeInlineCSSValue('large') + }); + }); + it('should match color keywords case-insensitively', () => { + expect( + flatten( + processor.compileInlineCSS( + 'color: RED; background-color: RGB(0, 0, 0); border-top-color: Transparent' + ) + ) + ).toStrictEqual({ + color: 'red', + backgroundColor: 'rgb(0, 0, 0)', + borderTopColor: 'transparent' + }); + }); + it('should keep values which are valid as written unchanged', () => { + expect( + flatten( + processor.compileInlineCSS( + 'color: #FFF; background-color: #AbCdEf' + ) + ) + ).toStrictEqual({ + color: '#FFF', + backgroundColor: '#AbCdEf' + }); + }); + it('should match keywords of shorthand properties case-insensitively, preserving hex colors', () => { + expect( + flatten( + processor.compileInlineCSS( + 'border: 1px SOLID #FFF; flex-flow: ROW WRAP; text-decoration: UNDERLINE RED' + ) + ) + ).toStrictEqual({ + borderTopWidth: 1, + borderRightWidth: 1, + borderBottomWidth: 1, + borderLeftWidth: 1, + borderTopColor: '#FFF', + borderRightColor: '#FFF', + borderBottomColor: '#FFF', + borderLeftColor: '#FFF', + borderStyle: 'solid', + flexDirection: 'row', + flexWrap: 'wrap', + textDecorationLine: 'underline', + textDecorationColor: 'red', + textDecorationStyle: 'solid' + }); + expect( + flatten(processor.compileInlineCSS('background: RED')) + ).toStrictEqual({ backgroundColor: 'red' }); + }); + it('should not lowercase the font family of the font shorthand', () => { + expect( + flatten( + processor.compileInlineCSS( + 'font: ITALIC BOLD 12PX/18PX Times New Roman' + ) + ) + ).toStrictEqual({ + fontStyle: 'italic', + fontWeight: 'bold', + fontVariant: [], + fontSize: 12, + lineHeight: 18, + fontFamily: 'Times New Roman' + }); + }); + it('should not lowercase case-sensitive values', () => { + expect( + flatten( + processor.compileInlineCSS( + 'font-family: HELVETICA; list-style-type: DISC; transform: ROTATE(45DEG)' + ) + ) + ).toStrictEqual({ + fontFamily: 'HELVETICA', + listStyleType: 'DISC' + }); + }); + }); it('should ignore rules from the inlinePropertiesBlacklist config array', () => { const processorWithIgnoreStyles = new CSSProcessor({ ...defaultCSSProcessorConfig, diff --git a/packages/css-processor/src/helpers.ts b/packages/css-processor/src/helpers.ts index 4c1c7ee6..bd098881 100644 --- a/packages/css-processor/src/helpers.ts +++ b/packages/css-processor/src/helpers.ts @@ -1,3 +1,20 @@ +const HEX_COLOR_TOKEN_REGEX = /(#[0-9a-f]+)/i; + +/** + * Lowercase a CSS value, preserving the case of hex colors. + * + * @param value - The CSS value to lowercase. + */ +export function lowercaseCSSKeywords(value: string): string { + return ( + value + .split(HEX_COLOR_TOKEN_REGEX) + // Captured hex colors are at odd indexes. + .map((chunk, i) => (i % 2 === 1 ? chunk : chunk.toLowerCase())) + .join('') + ); +} + export function lookupRecord>( record: T, key: any diff --git a/packages/css-processor/src/validators/GenericPropertyValidator.ts b/packages/css-processor/src/validators/GenericPropertyValidator.ts index a3f05c52..c032b847 100644 --- a/packages/css-processor/src/validators/GenericPropertyValidator.ts +++ b/packages/css-processor/src/validators/GenericPropertyValidator.ts @@ -50,6 +50,26 @@ export abstract class GenericCSSPropertyValidator< */ abstract normalizeNativeValue(value: N): ShortMergeRequest | N | null; + /** + * Lowercase the keywords of an inline CSS value which failed normalization + * as written, for a second normalization attempt. CSS keywords are ASCII + * case-insensitive (e.g. `display: FLEX`), while React Native style values + * are not, so this is only used for inline CSS. + * + * @remarks The default implementation returns the value unchanged, which + * prevents a second attempt. Validators must not override it when + * lowercasing would change what a value refers to: font families are + * matched by exact name against the available fonts, list style types may + * name user-defined `customListStyleSpecs` entries, and transforms are + * parsed by css-to-react-native, which expects camelCase function names + * such as `translateX`. + * + * @param value - The inline CSS value which failed normalization. + */ + lowercaseInlineCSSKeywords(value: string): string { + return value; + } + isShorthand(): boolean { return this._isShorthand; } diff --git a/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts index cd66da58..8ef40d3f 100644 --- a/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts @@ -1,4 +1,5 @@ import colorKeywords from 'css-color-keywords'; +import { lowercaseCSSKeywords } from '../helpers'; import { LongForgivingCSSPropertyValidator } from './LongForgivingCSSPropertyValidator'; import { CSSPropertyModel } from './types'; @@ -27,4 +28,8 @@ export class LongColorCSSPropertyValidator< } return null; } + + lowercaseInlineCSSKeywords(value: string): string { + return lowercaseCSSKeywords(value); + } } diff --git a/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts index e934df9d..93c8476a 100644 --- a/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts @@ -1,3 +1,4 @@ +import { lowercaseCSSKeywords } from '../helpers'; import { LongCSSPropertyValidator } from './LongCSSPropertyValidator'; import { CSSPropertyValidatorParams, CSSPropertyModel } from './types'; @@ -20,4 +21,8 @@ export class LongEnumerationCSSPropertyValidator< normalizeNativeValue(v: string): string | null { return this.normalizeInlineCSSValue(v); } + + lowercaseInlineCSSKeywords(value: string): string { + return lowercaseCSSKeywords(value); + } } diff --git a/packages/css-processor/src/validators/LongEnumerationListCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongEnumerationListCSSPropertyValidator.ts index e6df41f0..ee524682 100644 --- a/packages/css-processor/src/validators/LongEnumerationListCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongEnumerationListCSSPropertyValidator.ts @@ -12,12 +12,18 @@ export class LongEnumerationListCSSPropertyValidator< this.allowedList = allowedList; } + /** + * Items are matched case-insensitively, since CSS keywords are + * case-insensitive. This doesn't affect React Native style values, which + * are not normalized by this validator. + */ normalizeRawInlineCSSValue(value: string): string[] | null { const input = value.split(WHITESPACE_REGEX); const values: string[] = []; for (const item of input) { - if (this.allowedList.indexOf(item) !== -1) { - values.push(item); + const lowercasedItem = item.toLowerCase(); + if (this.allowedList.indexOf(lowercasedItem) !== -1) { + values.push(lowercasedItem); } } return values.length > 0 ? values : null; diff --git a/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts index d79c7a61..eae1c8f3 100644 --- a/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts @@ -1,4 +1,5 @@ import { CSSLengthUnit } from '../config'; +import { lowercaseCSSKeywords } from '../helpers'; import { LongCSSPropertyValidator } from './LongCSSPropertyValidator'; import { CSSPropertyModel } from './types'; @@ -79,4 +80,8 @@ export class LongSizeCSSPropertyValidator< normalizeNativeValue(value: string | number) { return this.normalizeInlineCSSValue(value); } + + lowercaseInlineCSSKeywords(value: string): string { + return lowercaseCSSKeywords(value); + } } diff --git a/packages/css-processor/src/validators/ShortCSSToReactNativeValidator.ts b/packages/css-processor/src/validators/ShortCSSToReactNativeValidator.ts index 2cb64685..7116fd41 100644 --- a/packages/css-processor/src/validators/ShortCSSToReactNativeValidator.ts +++ b/packages/css-processor/src/validators/ShortCSSToReactNativeValidator.ts @@ -2,12 +2,14 @@ import { ShortCSSPropertyValidator } from './ShortCSSPropertyValidator'; import { CSSPropertyModel } from './types'; import expandCSSToRN from './expandCSSToRN'; import { ShortMergeRequest } from '../ShortMergeRequest'; +import { lowercaseCSSKeywords } from '../helpers'; export class ShortCSSToReactNativeValidator< C extends CSSPropertyModel = any > extends ShortCSSPropertyValidator { normalizeInlineCSSValue(value: string): ShortMergeRequest | null { - return new ShortMergeRequest(expandCSSToRN(this.propertyName, value)); + const expanded = expandCSSToRN(this.propertyName, value); + return expanded ? new ShortMergeRequest(expanded) : null; } /** * Not supported on Native. @@ -16,4 +18,8 @@ export class ShortCSSToReactNativeValidator< normalizeNativeValue() { return null; } + + lowercaseInlineCSSKeywords(value: string): string { + return lowercaseCSSKeywords(value); + } } diff --git a/packages/css-processor/src/validators/ShortFontCSSValidator.ts b/packages/css-processor/src/validators/ShortFontCSSValidator.ts index 9a2d57ea..11bbcc47 100644 --- a/packages/css-processor/src/validators/ShortFontCSSValidator.ts +++ b/packages/css-processor/src/validators/ShortFontCSSValidator.ts @@ -2,12 +2,38 @@ import { ShortCSSToReactNativeValidator } from './ShortCSSToReactNativeValidator import normalizeFontName from './normalizeFontName'; import { CSSPropertyModel } from './types'; import { ShortMergeRequest } from '../ShortMergeRequest'; +import { lowercaseCSSKeywords } from '../helpers'; const WHITESPACE_REGEX = /\s+/; +const WHITESPACE_SEPARATOR_REGEX = /(\s+)/; + +/** + * A font size with a unit, optionally followed by a line height, such as + * `12px` or `12px/1.5`. + */ +const FONT_SIZE_REGEX = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[a-z]+|%)(?:\/\S*)?$/i; + export class ShortFontCSSValidator< C extends CSSPropertyModel > extends ShortCSSToReactNativeValidator { + /** + * Only lowercase the keywords preceding the font family, which is matched + * by exact name against the available fonts. In the font shorthand, the + * font family always follows the font size. + */ + lowercaseInlineCSSKeywords(value: string): string { + const chunks = value.split(WHITESPACE_SEPARATOR_REGEX); + const sizeIndex = chunks.findIndex((chunk) => FONT_SIZE_REGEX.test(chunk)); + if (sizeIndex === -1) { + return value; + } + return ( + lowercaseCSSKeywords(chunks.slice(0, sizeIndex + 1).join('')) + + chunks.slice(sizeIndex + 1).join('') + ); + } + normalizeInlineCSSValue(value: string): ShortMergeRequest | null { // A 'font' declaration may end with a list of multiple font families. // We must check support for this list before processing. From 9bfbb49415f8837d010cf3688290a72611e5ebad Mon Sep 17 00:00:00 2001 From: 5ZYSZ3K Date: Wed, 18 Nov 2026 15:27:41 +0100 Subject: [PATCH 5/5] test(css-processor): cover font values without a size and invalid flex 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 --- .../src/__tests__/CSSProcessor.test.ts | 9 ++++++--- .../__tests__/ShortFontCSSValidator.test.ts | 13 +++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/css-processor/src/__tests__/CSSProcessor.test.ts b/packages/css-processor/src/__tests__/CSSProcessor.test.ts index 5e51fa6e..7df18f92 100644 --- a/packages/css-processor/src/__tests__/CSSProcessor.test.ts +++ b/packages/css-processor/src/__tests__/CSSProcessor.test.ts @@ -434,6 +434,11 @@ describe('CSSProcessor', () => { processor.compileInlineCSS('padding-horizontal: 10px;') ).toStrictEqual(new CSSProcessedProps()); }); + it('should ignore shorthand values which cannot be expanded', () => { + expect(processor.compileInlineCSS('flex: foo;')).toStrictEqual( + new CSSProcessedProps() + ); + }); describe('regarding the !important flag', () => { it('should ignore the flag on longhand properties', () => { expect( @@ -552,9 +557,7 @@ describe('CSSProcessor', () => { it('should keep values which are valid as written unchanged', () => { expect( flatten( - processor.compileInlineCSS( - 'color: #FFF; background-color: #AbCdEf' - ) + processor.compileInlineCSS('color: #FFF; background-color: #AbCdEf') ) ).toStrictEqual({ color: '#FFF', diff --git a/packages/css-processor/src/validators/__tests__/ShortFontCSSValidator.test.ts b/packages/css-processor/src/validators/__tests__/ShortFontCSSValidator.test.ts index 625eee97..bc92a3dc 100644 --- a/packages/css-processor/src/validators/__tests__/ShortFontCSSValidator.test.ts +++ b/packages/css-processor/src/validators/__tests__/ShortFontCSSValidator.test.ts @@ -67,4 +67,17 @@ describe('ShortFontCSSValidator', () => { ); }); }); + describe('lowercaseInlineCSSKeywords method', () => { + const validator = registryFromConfig({}).validators.font; + it('should lowercase keywords up to and including the font size', () => { + expect( + validator.lowercaseInlineCSSKeywords('ITALIC BOLD 12PX/18PX Georgia') + ).toBe('italic bold 12px/18px Georgia'); + }); + it('should return the value unchanged when it has no font size', () => { + expect(validator.lowercaseInlineCSSKeywords('BOLD Georgia')).toBe( + 'BOLD Georgia' + ); + }); + }); });