diff --git a/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx b/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx index b00c5dc1..ed74ee8f 100644 --- a/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx +++ b/doc-tools/doc-pages/src/pages/PageConceptCSS.tsx @@ -170,9 +170,9 @@ 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 will be ignored. Declaration blocks + after complex selectors such as div > *, + pseudo-classes and pseudo-elements will be ignored. diff --git a/packages/css-processor/src/CSSInlineParseRun.ts b/packages/css-processor/src/CSSInlineParseRun.ts index ba1cd892..b149517a 100644 --- a/packages/css-processor/src/CSSInlineParseRun.ts +++ b/packages/css-processor/src/CSSInlineParseRun.ts @@ -5,10 +5,13 @@ import { CSSPropertiesValidationRegistry } from './CSSPropertiesValidationRegist import { ValidatorsType } from './makepropertiesValidators'; import { CSSProperties } from './processor-types'; import { ShortMergeRequest } from './ShortMergeRequest'; +import { GenericCSSPropertyValidator } from './validators/GenericPropertyValidator'; import { LongCSSPropertyValidator } from './validators/LongCSSPropertyValidator'; type CSSRawPropertiesList = [string, any][]; +const IMPORTANT_FLAG_REGEX = /\s*!\s*important\s*$/i; + export class CSSInlineParseRun extends CSSParseRun { private rules: CSSRawPropertiesList; @@ -25,24 +28,82 @@ export class CSSInlineParseRun extends CSSParseRun { .map((prop) => prop.split(':')) .reduce((acc, prop) => { if (prop.length === 2) { - return [...acc, [prop[0].trim(), prop[1].trim()]]; + // 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. + return [ + ...acc, + [prop[0].trim(), prop[1].replace(IMPORTANT_FLAG_REGEX, '').trim()] + ]; } return acc; }, []); } + /** + * 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; + } + + /** + * 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); + } + 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); + // CSS keywords and units are case-insensitive. Values valid as written + // are kept unchanged, others get a second attempt lowercased. + const normalizedValue = + validator.normalizeInlineCSSValue(rawValue) ?? + this.normalizeLowercasedValue(validator, rawValue); 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 de85ed38..fee7f164 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; @@ -25,6 +41,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 +63,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 +97,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 ] }; @@ -350,6 +393,21 @@ describe('CSSProcessor', () => { } as any) ).toEqual(new CSSProcessedProps()); }); + it('should not match 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( @@ -376,6 +434,213 @@ 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( + 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' }); + }); + }); + 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 keywords and units 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 names and functions 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 not retry rejected non-string values expanded from shorthands', () => { + // No built-in longhand validator rejects the non-string values + // shorthands expand to (`flex: 1` gives `flexGrow: 1`), so the + // rejection is stubbed, on a dedicated processor to avoid leaks. + const isolatedProcessor = new CSSProcessor(defaultCSSProcessorConfig); + const flexGrowValidator = isolatedProcessor.registry.validators.flexGrow; + jest + .spyOn(flexGrowValidator, 'normalizeInlineCSSValue') + .mockReturnValue(null); + const lowercaseSpy = jest.spyOn( + flexGrowValidator, + 'lowercaseInlineCSSValue' + ); + expect(isolatedProcessor.compileInlineCSS('flex: 1')).toStrictEqual( + new CSSProcessedProps() + ); + expect(flexGrowValidator.normalizeInlineCSSValue).toHaveBeenCalledWith( + 1 + ); + expect(lowercaseSpy).not.toHaveBeenCalled(); + }); + }); it('should ignore rules from the inlinePropertiesBlacklist config array', () => { const processorWithIgnoreStyles = new CSSProcessor({ ...defaultCSSProcessorConfig, @@ -432,22 +697,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 +811,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 +842,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 +980,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 +1336,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 +1365,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 +1389,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 +1418,7 @@ describe('CSSProcessor', () => { paddingBottom: 1, paddingLeft: 1 }, + null, null ] } diff --git a/packages/css-processor/src/helpers.ts b/packages/css-processor/src/helpers.ts index 4c1c7ee6..fb0e131a 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 lowercaseCSSValue(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/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/GenericPropertyValidator.ts b/packages/css-processor/src/validators/GenericPropertyValidator.ts index a3f05c52..fb5f7585 100644 --- a/packages/css-processor/src/validators/GenericPropertyValidator.ts +++ b/packages/css-processor/src/validators/GenericPropertyValidator.ts @@ -50,6 +50,27 @@ export abstract class GenericCSSPropertyValidator< */ abstract normalizeNativeValue(value: N): ShortMergeRequest | N | null; + /** + * Lowercase the case-insensitive parts of an inline CSS value which failed + * normalization as written, for a second normalization attempt. CSS + * keywords and units are ASCII case-insensitive (e.g. `display: FLEX`, + * `width: 10PX`), 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. + */ + lowercaseInlineCSSValue(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 1568a078..b2fbb2ef 100644 --- a/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongColorCSSPropertyValidator.ts @@ -1,12 +1,181 @@ +import { lowercaseCSSValue } from '../helpers'; 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,%. ]+\)$/; + +/** + * CSS named colors supported by React Native. + */ +const NAMED_COLORS = new Set([ + 'aliceblue', + 'antiquewhite', + 'aqua', + 'aquamarine', + 'azure', + 'beige', + 'bisque', + 'black', + 'blanchedalmond', + 'blue', + 'blueviolet', + 'brown', + 'burlywood', + 'cadetblue', + 'chartreuse', + 'chocolate', + 'coral', + 'cornflowerblue', + 'cornsilk', + 'crimson', + 'cyan', + 'darkblue', + 'darkcyan', + 'darkgoldenrod', + 'darkgray', + 'darkgreen', + 'darkgrey', + 'darkkhaki', + 'darkmagenta', + 'darkolivegreen', + 'darkorange', + 'darkorchid', + 'darkred', + 'darksalmon', + 'darkseagreen', + 'darkslateblue', + 'darkslategray', + 'darkslategrey', + 'darkturquoise', + 'darkviolet', + 'deeppink', + 'deepskyblue', + 'dimgray', + 'dimgrey', + 'dodgerblue', + 'firebrick', + 'floralwhite', + 'forestgreen', + 'fuchsia', + 'gainsboro', + 'ghostwhite', + 'gold', + 'goldenrod', + 'gray', + 'green', + 'greenyellow', + 'grey', + 'honeydew', + 'hotpink', + 'indianred', + 'indigo', + 'ivory', + 'khaki', + 'lavender', + 'lavenderblush', + 'lawngreen', + 'lemonchiffon', + 'lightblue', + 'lightcoral', + 'lightcyan', + 'lightgoldenrodyellow', + 'lightgray', + 'lightgreen', + 'lightgrey', + 'lightpink', + 'lightsalmon', + 'lightseagreen', + 'lightskyblue', + 'lightslategray', + 'lightslategrey', + 'lightsteelblue', + 'lightyellow', + 'lime', + 'limegreen', + 'linen', + 'magenta', + 'maroon', + 'mediumaquamarine', + 'mediumblue', + 'mediumorchid', + 'mediumpurple', + 'mediumseagreen', + 'mediumslateblue', + 'mediumspringgreen', + 'mediumturquoise', + 'mediumvioletred', + 'midnightblue', + 'mintcream', + 'mistyrose', + 'moccasin', + 'navajowhite', + 'navy', + 'oldlace', + 'olive', + 'olivedrab', + 'orange', + 'orangered', + 'orchid', + 'palegoldenrod', + 'palegreen', + 'paleturquoise', + 'palevioletred', + 'papayawhip', + 'peachpuff', + 'peru', + 'pink', + 'plum', + 'powderblue', + 'purple', + 'rebeccapurple', + 'red', + 'rosybrown', + 'royalblue', + 'saddlebrown', + 'salmon', + 'sandybrown', + 'seagreen', + 'seashell', + 'sienna', + 'silver', + 'skyblue', + 'slateblue', + 'slategray', + 'slategrey', + 'snow', + 'springgreen', + 'steelblue', + 'tan', + 'teal', + 'thistle', + 'tomato', + 'transparent', + 'turquoise', + 'violet', + 'wheat', + 'white', + 'whitesmoke', + 'yellow', + 'yellowgreen' +]); 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; + } + + lowercaseInlineCSSValue(value: string): string { + return lowercaseCSSValue(value); } } diff --git a/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts b/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts index e934df9d..e0ef60bf 100644 --- a/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongEnumerationCSSPropertyValidator.ts @@ -1,3 +1,4 @@ +import { lowercaseCSSValue } 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); } + + lowercaseInlineCSSValue(value: string): string { + return lowercaseCSSValue(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/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..a3e9674a 100644 --- a/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts +++ b/packages/css-processor/src/validators/LongSizeCSSPropertyValidator.ts @@ -1,10 +1,25 @@ import { CSSLengthUnit } from '../config'; +import { lowercaseCSSValue } from '../helpers'; 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 +51,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') { @@ -63,4 +80,8 @@ export class LongSizeCSSPropertyValidator< normalizeNativeValue(value: string | number) { return this.normalizeInlineCSSValue(value); } + + lowercaseInlineCSSValue(value: string): string { + return lowercaseCSSValue(value); + } } diff --git a/packages/css-processor/src/validators/ShortCSSToReactNativeValidator.ts b/packages/css-processor/src/validators/ShortCSSToReactNativeValidator.ts index 2cb64685..820f01d4 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 { lowercaseCSSValue } 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; } + + lowercaseInlineCSSValue(value: string): string { + return lowercaseCSSValue(value); + } } diff --git a/packages/css-processor/src/validators/ShortFontCSSValidator.ts b/packages/css-processor/src/validators/ShortFontCSSValidator.ts index 9a2d57ea..a8dbcc28 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 { lowercaseCSSValue } 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 part 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. + */ + lowercaseInlineCSSValue(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 ( + lowercaseCSSValue(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. diff --git a/packages/css-processor/src/validators/__tests__/LongColorCSSPropertyValidator.test.ts b/packages/css-processor/src/validators/__tests__/LongColorCSSPropertyValidator.test.ts index be9b1f42..d5f9975f 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 transparent, cyan and magenta', () => { + 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/packages/css-processor/src/validators/__tests__/ShortFontCSSValidator.test.ts b/packages/css-processor/src/validators/__tests__/ShortFontCSSValidator.test.ts index 625eee97..7e51904d 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('lowercaseInlineCSSValue method', () => { + const validator = registryFromConfig({}).validators.font; + it('should lowercase the value up to and including the font size', () => { + expect( + validator.lowercaseInlineCSSValue('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.lowercaseInlineCSSValue('BOLD Georgia')).toBe( + 'BOLD Georgia' + ); + }); + }); });