Skip to content

Commit

Permalink
Add color validation
Browse files Browse the repository at this point in the history
  • Loading branch information
ciampo committed Oct 11, 2022
1 parent 6ea5f68 commit 0ac7a24
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 3 deletions.
10 changes: 9 additions & 1 deletion packages/components/src/theme/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,16 @@ const Example = () => {

## Props

### `accent`: `CSSProperties[ 'color' ]`
### `accent`: `string`

Used to set the accent color (used by components as the primary color). If an accent color is not defined, the default fallback value is the original WP Admin main theme color.

Note: this property only supports some of the multiple syntaxes used to specify a CSS color. In particular, these are the known _unsupported_ values:

- the `'currentcolor'` keyword;
- global keyworks (like `'-moz-initial'`, `'inherit'`, `'initial'`, `'revert'` and `'unset'`;
- CSS custom properties (e.g. `var(--my-custom-property)`)



- Required: No
16 changes: 16 additions & 0 deletions packages/components/src/theme/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
/**
* External dependencies
*/
import { colord, extend } from 'colord';
import a11yPlugin from 'colord/plugins/a11y';
import namesPlugin from 'colord/plugins/names';

/**
* Internal dependencies
*/
import type { ThemeProps } from './types';
import type { WordPressComponentProps } from '../ui/context';
import { Wrapper } from './styles';

extend( [ namesPlugin, a11yPlugin ] );

function Theme( props: WordPressComponentProps< ThemeProps, 'div', true > ) {
const { accent } = props;
if ( accent && ! colord( accent ).isValid() ) {
console.warn(
`wp.components.Theme: "${ accent }" is not a valid color value for the 'accent' prop.`
);
}

return <Wrapper { ...props } />;
}

Expand Down
18 changes: 18 additions & 0 deletions packages/components/src/theme/test/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,23 @@ describe( 'Theme', () => {
'--wp-components-color-accent-darker-20': '#091d5f',
} );
} );

describe( 'unsupported values', () => {
it.each( [
// Keywords
'currentcolor',
'initial',
'reset',
'inherit',
'revert',
'unset',
// CSS Custom properties
'var( --my-variable )',
] )( 'should warn when the value is "%s"', ( accentValue ) => {
render( <Theme accent={ accentValue } /> );

expect( console ).toHaveWarned();
} );
} );
} );
} );
4 changes: 2 additions & 2 deletions packages/components/src/theme/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
/**
* External dependencies
*/
import type { ReactNode, CSSProperties } from 'react';
import type { ReactNode } from 'react';

export type ThemeProps = {
accent?: CSSProperties[ 'color' ];
accent?: string;
children?: ReactNode;
};

0 comments on commit 0ac7a24

Please sign in to comment.