diff --git a/docs/block-api/attributes.md b/docs/block-api/attributes.md index 718f6794cd9ea..30a5d010863e0 100644 --- a/docs/block-api/attributes.md +++ b/docs/block-api/attributes.md @@ -77,6 +77,26 @@ _Example_: Extract child nodes from a paragraph of rich text. // } ``` +### `styleProperty` + +Use `inlineStyle` to extract a value from the inline style declaration of the matched element. + +_Example_: Extract the width value from the an inline style + +```js +{ + width: { + type: 'string', + source: 'inlineStyle', + selector: 'div', + styleProperty: 'width' + } +} +// { +// "width": "20px" +// } +``` + ### `query` Use `query` to extract an array of values from markup. Entries of the array are determined by the selector argument, where each matched element within the block will have an entry structured corresponding to the second argument, an object of attribute sources. diff --git a/packages/blocks/src/api/parser.js b/packages/blocks/src/api/parser.js index 6390d3a8852a3..20dd836fdae01 100644 --- a/packages/blocks/src/api/parser.js +++ b/packages/blocks/src/api/parser.js @@ -112,6 +112,11 @@ export function matcherFromSource( sourceConfig ) { return children( sourceConfig.selector ); case 'node': return node( sourceConfig.selector ); + case 'inlineStyle': + return flow( [ + prop( sourceConfig.selector, `style.${ sourceConfig.styleProperty }` ), + ( value ) => value !== '' ? value : undefined, + ] ); case 'query': const subMatchers = mapValues( sourceConfig.query, matcherFromSource ); return query( sourceConfig.selector, subMatchers ); @@ -164,6 +169,7 @@ export function getBlockAttribute( attributeKey, attributeSchema, innerHTML, com case 'text': case 'children': case 'node': + case 'inlineStyle': case 'query': case 'tag': value = parseWithAttributeSchema( innerHTML, attributeSchema ); diff --git a/packages/blocks/src/api/test/parser.js b/packages/blocks/src/api/test/parser.js index 3c12fee973ff4..11b989cb082c9 100644 --- a/packages/blocks/src/api/test/parser.js +++ b/packages/blocks/src/api/test/parser.js @@ -137,7 +137,7 @@ describe( 'block parser', () => { } ); describe( 'parseWithAttributeSchema', () => { - it( 'should return the matcher’s attribute value', () => { + it( 'should return the matcher’s text content value', () => { const value = parseWithAttributeSchema( '
chicken
', { @@ -149,6 +149,19 @@ describe( 'block parser', () => { expect( value ).toBe( 'chicken' ); } ); + it( 'should return the matcher’s style property value', () => { + const value = parseWithAttributeSchema( + '
chicken
', + { + type: 'string', + source: 'inlineStyle', + selector: 'div', + styleProperty: 'width', + }, + ); + expect( value ).toBe( '10px' ); + } ); + it( 'should return the matcher’s string attribute value', () => { const value = parseWithAttributeSchema( '