Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 122 additions & 0 deletions packages/block-editor/src/hooks/html-attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { addFilter } from '@wordpress/hooks';
import { getBlockType } from '@wordpress/blocks';
import type { BlockType } from '@wordpress/blocks';
import type { BlockListBlockFeatureProps, BlockWrapperProps } from './types';

type HtmlAttributes = Record< string, string >;

/**
* Adds `htmlAttributes`: attributes of a block's element that the block
* doesn't know, read from its HTML. They're kept out of the delimiter.
*
* @param settings Block settings.
*
* @return Block settings.
*/
export function addAttribute( settings: BlockType ): BlockType {
settings.attributes = {
...settings.attributes,
htmlAttributes: { type: 'object', role: 'local' },
};
return settings;
}

/**
* Turns an inline style into a style object, as React expects.
*
* @param style Value of a `style` attribute.
*/
function getStyleObject( style: string ): Record< string, string > {
const styleObject: Record< string, string > = {};
for ( const declaration of style.split( ';' ) ) {
const colonAt = declaration.indexOf( ':' );
const property = declaration.slice( 0, colonAt ).trim();
if ( colonAt === -1 || ! property ) {
continue;
}
const key = property.startsWith( '--' )
? property
: property
.toLowerCase()
.replace( /^-ms-/, 'ms-' )
.replace( /-([a-z])/g, ( _match, letter ) =>
letter.toUpperCase()
);
styleObject[ key ] = declaration.slice( colonAt + 1 ).trim();
}
return styleObject;
}

/**
* Adds attributes to props without replacing the block's own: its style
* properties win over the same ones in `htmlAttributes`.
*
* @param props Props.
* @param htmlAttributes Attributes to add.
*/
function mergeHtmlAttributes(
props: BlockWrapperProps,
htmlAttributes: HtmlAttributes
): BlockWrapperProps {
const { style, ...attributes } = htmlAttributes;
const merged = { ...props };
for ( const [ name, value ] of Object.entries( attributes ) ) {
if ( ! ( name in merged ) ) {
merged[ name ] = value;
}
}
if ( style ) {
merged.style = { ...getStyleObject( style ), ...props.style };
}
return merged;
}

export function addSaveProps(
extraProps: BlockWrapperProps,
_blockType: BlockType,
{ htmlAttributes }: { htmlAttributes?: HtmlAttributes }
): BlockWrapperProps {
return htmlAttributes
? mergeHtmlAttributes( extraProps, htmlAttributes )
: extraProps;
}

/**
* Shows `htmlAttributes` in the editor, leaving out event handlers, script
* links, and anything that would change how the block is edited.
*
* @param props Block props.
* @param props.htmlAttributes Attributes to show.
*/
function useBlockProps( {
htmlAttributes,
}: BlockListBlockFeatureProps ): BlockWrapperProps {
const safeAttributes = Object.fromEntries(
Object.entries( htmlAttributes as HtmlAttributes ).filter(
( [ name, value ] ) =>
! name.startsWith( 'on' ) &&
name !== 'contenteditable' &&
! /^\s*javascript:/i.test( value )
)
);
return mergeHtmlAttributes( {}, safeAttributes );
}

export default {
useBlockProps,
addSaveProps,
attributeKeys: [ 'htmlAttributes' ],
hasSupport( nameOrType: string | BlockType ) {
const blockType =
typeof nameOrType === 'string'
? getBlockType( nameOrType )
: nameOrType;
return !! blockType?.attributes?.htmlAttributes;
},
};

addFilter(
'blocks.registerBlockType',
'core/editor/html-attributes/attribute',
addAttribute
);
4 changes: 4 additions & 0 deletions packages/block-editor/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import allowedBlocks from './allowed-blocks';
import anchor from './anchor';
import ariaLabel from './aria-label';
import customClassName from './custom-class-name';
import htmlAttributes from './html-attributes';
import './generated-class-name';
import style from './style';
import './settings';
Expand Down Expand Up @@ -57,6 +58,7 @@ createBlockEditFilter(
].filter( Boolean )
);
createBlockListBlockFilter( [
htmlAttributes,
align,
textAlign,
background,
Expand Down Expand Up @@ -88,6 +90,8 @@ createBlockSaveFilter( [
fontFamily,
fontSize,
textShadow,
// Last, so the block's own styles win over these.
htmlAttributes,
] );

export { useCustomSides } from './dimensions';
Expand Down
48 changes: 48 additions & 0 deletions packages/block-editor/src/hooks/test/html-attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import type { BlockType } from '@wordpress/blocks';
import htmlAttributes, { addSaveProps } from '../html-attributes';

describe( 'htmlAttributes', () => {
it( 'shows attributes in the editor, without unsafe ones', () => {
expect(
htmlAttributes.useBlockProps( {
name: 'core/paragraph',
clientId: '1',
htmlAttributes: {
style: 'background:#fffbe6; border-left:4px solid;--gap:1em;-webkit-line-clamp:2',
'data-note': 'tip',
onclick: 'alert(1)',
contenteditable: 'false',
'data-href': ' javascript:alert(1)',
},
} )
).toEqual( {
'data-note': 'tip',
style: {
background: '#fffbe6',
borderLeft: '4px solid',
'--gap': '1em',
WebkitLineClamp: '2',
},
} );
} );

it( 'saves attributes under the block’s own props', () => {
expect(
addSaveProps(
{ className: 'has-text-color', style: { color: '#000' } },
{} as BlockType,
{
htmlAttributes: {
style: 'color:red;padding:1px',
'data-note': 'tip',
},
}
)
).toEqual( {
className: 'has-text-color',
style: { color: '#000', padding: '1px' },
'data-note': 'tip',
} );
} );
} );
7 changes: 6 additions & 1 deletion packages/block-editor/src/store/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,15 @@ export function mapUserPattern(
};
}

// Pattern blocks are inserted as new blocks, not as the pattern is written.
function withoutSource( { undelimitedSource, ...block }: Block ): Block {
return { ...block, innerBlocks: block.innerBlocks.map( withoutSource ) };
}

function parsePattern( pattern: BlockPattern ): ParsedBlockPattern {
const blocks = parse( pattern.content, {
__unstableSkipMigrationLogs: true,
} );
} ).map( withoutSource );
if ( blocks.length === 1 ) {
blocks[ 0 ].attributes = {
...blocks[ 0 ].attributes,
Expand Down
4 changes: 4 additions & 0 deletions packages/blocks/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### New Features

- `parse` reads HTML outside block delimiters as blocks instead of one Classic block, and `serialize` saves blocks that weren't edited as they were read: blocks with delimiters exactly, and HTML outside delimiters as the browser writes it, with nothing added. Blocks read without delimiters are saved without them unless an edit needs one; new blocks get delimiters, Classic blocks too ([#85524](https://github.com/WordPress/gutenberg/pull/85524)).

### Bug Fixes

- Add the `input` block transform type, and let `getSaveElement` take an element in place of inner blocks in the types, as the runtime already does ([#85025](https://github.com/WordPress/gutenberg/pull/85025)).
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { fixCustomClassname } from './fix-custom-classname';
import { fixGlobalAttribute } from './fix-global-attribute';
import { fixHtmlAttributes } from './fix-html-attributes';
import type { Block, BlockAttribute, BlockType } from '../../types';

const ARIA_LABEL_ATTR_SCHEMA: BlockAttribute = {
Expand Down Expand Up @@ -59,6 +60,13 @@ export function applyBuiltInValidationFixes(
ANCHOR_ATTR_SCHEMA
);

// Keep any other attributes of the root element.
updatedBlockAttributes = fixHtmlAttributes(
updatedBlockAttributes,
blockType,
originalContent ?? ''
);

return {
...block,
attributes: updatedBlockAttributes,
Expand Down
76 changes: 76 additions & 0 deletions packages/blocks/src/api/parser/fix-html-attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { getSaveContent } from '../serializer';
import { getRootElement, readStyle } from '../undelimited';
import type { BlockType } from '../../types';

/**
* Returns the attributes of the element a piece of HTML is. Attributes
* without a value are read as empty strings.
*
* @param html HTML.
*/
function getRootAttributes( html: string ): Map< string, string > | null {
const root = getRootElement( html );
return root
? new Map(
root
.getAttributeNames()
.map( ( name ) => [
name,
root.getAttribute( name ) ?? '',
] )
)
: null;
}

/**
* Reads the attributes of a block's root element that its `save` doesn't
* produce into `htmlAttributes`, so they're shown in the editor and saved
* again. For `style`, only the properties `save` doesn't set are kept.
*
* @param blockAttributes Block attributes.
* @param blockType Block type.
* @param innerHTML The block's HTML.
*
* @return Block attributes.
*/
export function fixHtmlAttributes(
blockAttributes: Record< string, unknown >,
blockType: BlockType,
innerHTML: string
): Record< string, unknown > {
if ( ! blockType.attributes?.htmlAttributes ) {
return blockAttributes;
}

const { htmlAttributes, ...attributes } = blockAttributes;
const written = getRootAttributes( innerHTML );
const saved = getRootAttributes( getSaveContent( blockType, attributes ) );
if ( ! written || ! saved ) {
return blockAttributes;
}

const extra: Record< string, string > = {};
for ( const [ name, value ] of written ) {
if ( name === 'style' ) {
const savedStyle = readStyle( saved.get( 'style' ) ?? '' );
const style = value
.split( ';' )
.filter( ( declaration ) => {
const property = declaration.split( ':' )[ 0 ].trim();
return (
property && ! savedStyle.has( property.toLowerCase() )
);
} )
.join( ';' );
if ( style ) {
extra.style = style;
}
} else if ( name !== 'class' && ! saved.has( name ) ) {
extra[ name ] = value;
}
}

return Object.keys( extra ).length
? { ...attributes, htmlAttributes: extra }
: attributes;
}
Loading
Loading