Skip to content

Commit

Permalink
PostCSS style transformation: fail gracefully instead of throwing error
Browse files Browse the repository at this point in the history
  • Loading branch information
zaguiini committed Nov 22, 2023
1 parent 6e532f4 commit 514a1dd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 13 deletions.
22 changes: 22 additions & 0 deletions packages/block-editor/src/utils/test/transform-styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@
import transformStyles from '../transform-styles';

describe( 'transformStyles', () => {
it( 'should not throw error in case of invalid css', () => {
const run = () =>
transformStyles(
[
{
css: 'h1 { color: red; }', // valid CSS
},
{
css: 'h1 { color: red;', // invalid CSS
},
],
'.my-namespace'
);

expect( run ).not.toThrow();

const [ validCSS, invalidCSS ] = run();

expect( validCSS ).toBe( '.my-namespace h1 { color: red; }' );
expect( invalidCSS ).toBe( null );
} );

describe( 'selector wrap', () => {
it( 'should wrap regular selectors', () => {
const input = `h1 { color: red; }`;
Expand Down
38 changes: 25 additions & 13 deletions packages/block-editor/src/utils/transform-styles/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import postcss from 'postcss';
import postcss, { CssSyntaxError } from 'postcss';
import wrap from 'postcss-prefixwrap';
import rebaseUrl from 'postcss-urlrebase';

Expand All @@ -19,18 +19,30 @@ import rebaseUrl from 'postcss-urlrebase';
*/
const transformStyles = ( styles, wrapperSelector = '' ) => {
return styles.map( ( { css, ignoredSelectors = [], baseURL } ) => {
return postcss(
[
wrapperSelector &&
wrap( wrapperSelector, {
ignoredSelectors: [
...ignoredSelectors,
wrapperSelector,
],
} ),
baseURL && rebaseUrl( { rootUrl: baseURL } ),
].filter( Boolean )
).process( css, {} ).css; // use sync PostCSS API
try {
return postcss(
[
wrapperSelector &&
wrap( wrapperSelector, {
ignoredSelectors: [
...ignoredSelectors,
wrapperSelector,
],
} ),
baseURL && rebaseUrl( { rootUrl: baseURL } ),
].filter( Boolean )
).process( css, {} ).css; // use sync PostCSS API
} catch ( error ) {
if ( ! ( error instanceof CssSyntaxError ) ) {
// eslint-disable-next-line no-console
console.warn(
'wp.blockEditor.transformStyles Failed to transform CSS.',
error
);
}

return null;
}
} );
};

Expand Down

0 comments on commit 514a1dd

Please sign in to comment.