Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
16 changes: 16 additions & 0 deletions packages/block-editor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,22 @@ _Returns_

- `Component`: The component to be rendered.

### HTMLElementSelectControl

Renders a SelectControl for choosing HTML elements with validation to prevent duplicate <main> elements.

_Parameters_

- _props_ `Object`: Component props.
- _props.tagName_ `string`: The current HTML tag name.
- _props.onChange_ `Function`: Function to call when the tag is changed.
- _props.currentClientId_ `string`: The client ID of the current block.
- _props.options_ `Array`: SelectControl options (optional).

_Returns_

- `Component`: The HTML element select control with validation.

### InnerBlocks

_Related_
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# HTML Element Select Control

A specialized component for selecting HTML elements with validation to prevent duplicate `<main>` elements.

The `HTMLElementSelectControl` is an extension of the WordPress `SelectControl` component that adds validation to prevent duplicate `<main>` HTML elements. This component is designed to help ensure valid HTML structure and improve accessibility in content created with the WordPress block editor.

## Development guidelines

### Usage

```jsx
import { HTMLElementSelectControl } from '@wordpress/block-editor';

function MyBlockEdit( { attributes, setAttributes, clientId } ) {
const { tagName } = attributes;

return (
<InspectorControls group="advanced">
<HTMLElementSelectControl
tagName={ tagName }
onChange={ ( value ) => setAttributes( { tagName: value } ) }
currentClientId={ clientId }
options={ [
{ label: 'Default (<div>)', value: 'div' },
{ label: '<header>', value: 'header' },
{ label: '<main>', value: 'main' },
{ label: '<section>', value: 'section' },
{ label: '<article>', value: 'article' },
{ label: '<aside>', value: 'aside' },
{ label: '<footer>', value: 'footer' },
] }
/>
</InspectorControls>
);
}
```

### Props

#### `tagName`

- **Type:** `String`

The current HTML tag name selected for the block.

#### `onChange`

- **Type:** `Function`

A callback function that is invoked when the user selects a different HTML element.

#### `currentClientId`

- **Type:** `String`

The client ID of the current block. Used for validating element uniqueness across blocks.

#### `options`

- **Type:** `Array`
- **Default:** Standard HTML elements (div, header, main, section, article, aside, footer)

An array of options for the select control. Each option should contain a `label` and `value` property.

Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { SelectControl, Notice } from '@wordpress/components';

/**
* Internal dependencies
*/
import { useSelect } from '@wordpress/data';
import { store as blockEditorStore } from '../../store';
import { htmlElementMessages } from './messages';

/**
* Checks if a block has a specific HTML element tag.
*
* @param {Object} block Block object to check.
* @param {string} tag HTML tag to look for.
* @return {boolean} Whether the block has the specified HTML element.
*/
const blockHasHtmlTag = ( block, tag ) => {
if ( ! block ) {
return false;
}

if ( block.attributes && block.attributes.tagName === tag ) {
return true;
}

if ( block.innerBlocks && block.innerBlocks.length ) {
return block.innerBlocks.some( ( innerBlock ) =>
blockHasHtmlTag( innerBlock, tag )
);
}

return false;
};

/**
* Renders a SelectControl for choosing HTML elements with validation
* to prevent duplicate <main> elements.
*
* @param {Object} props Component props.
* @param {string} props.tagName The current HTML tag name.
* @param {Function} props.onChange Function to call when the tag is changed.
* @param {string} props.currentClientId The client ID of the current block.
* @param {Array} props.options SelectControl options (optional).
*
* @return {Component} The HTML element select control with validation.
*/
export default function HTMLElementSelectControl( {
tagName,
onChange,
currentClientId,
options = [
{ label: __( 'Default (<div>)' ), value: 'div' },
{ label: '<header>', value: 'header' },
{ label: '<main>', value: 'main' },
{ label: '<section>', value: 'section' },
{ label: '<article>', value: 'article' },
{ label: '<aside>', value: 'aside' },
{ label: '<footer>', value: 'footer' },
],
} ) {
const { hasMultipleMainElements, hasMainElementElsewhere } = useSelect(
( select ) => {
const { getBlocks, getBlock } = select( blockEditorStore );
const allBlocks = getBlocks();
const currentBlock = getBlock( currentClientId );

let mainElementCount = 0;

// Check if the current block or its inner blocks have a main element.
if ( currentBlock && tagName === 'main' ) {
mainElementCount++;
}

const hasMainElsewhere = allBlocks.some( ( block ) => {
if ( block.clientId === currentClientId ) {
return false;
}

return blockHasHtmlTag( block, 'main' );
} );

if ( hasMainElsewhere ) {
mainElementCount++;
}

return {
hasMultipleMainElements: mainElementCount > 1,
hasMainElementElsewhere: hasMainElsewhere,
};
},
[ currentClientId, tagName ]
);

// Create a modified options array that disables the main option if needed.
const modifiedOptions = options.map( ( option ) => {
if (
option.value === 'main' &&
hasMainElementElsewhere &&
tagName !== 'main'
) {
return {
...option,
disabled: true,
label: `${ option.label } (${ __( 'Already in use' ) })`,
};
}
return option;
} );

return (
<>
{ tagName === 'main' && hasMultipleMainElements && (
<Notice status="warning" isDismissible={ false }>
{ __(
'Multiple <main> elements detected. This is not valid HTML and may cause accessibility issues. Please change this HTML element.'
) }
</Notice>
) }

<SelectControl
__nextHasNoMarginBottom
__next40pxDefaultSize
label={ __( 'HTML element' ) }
options={ modifiedOptions }
value={ tagName }
onChange={ onChange }
help={ htmlElementMessages[ tagName ] }
/>
</>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
*/
import { __ } from '@wordpress/i18n';

/**
* Messages providing helpful descriptions for HTML elements.
*/
export const htmlElementMessages = {
article: __(
'The <article> element should represent a self-contained, syndicatable portion of the document.'
Expand Down
1 change: 1 addition & 0 deletions packages/block-editor/src/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export { default as __experimentalDateFormatPicker } from './date-format-picker'
export { default as __experimentalDuotoneControl } from './duotone-control';
export { default as __experimentalFontAppearanceControl } from './font-appearance-control';
export { default as __experimentalFontFamilyControl } from './font-family';
export { default as HTMLElementSelectControl } from './html-element-select-control';
export { default as __experimentalLetterSpacingControl } from './letter-spacing-control';
export { default as __experimentalTextDecorationControl } from './text-decoration-control';
export { default as __experimentalTextTransformControl } from './text-transform-control';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,31 @@
/**
* WordPress dependencies
*/
import { SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { InspectorControls } from '@wordpress/block-editor';

/**
* Internal dependencies
*/
import { htmlElementMessages } from '../../utils/messages';
import {
InspectorControls,
HTMLElementSelectControl,
} from '@wordpress/block-editor';

export default function CommentsInspectorControls( {
attributes: { tagName },
setAttributes,
clientId,
} ) {
return (
<InspectorControls>
<InspectorControls group="advanced">
<SelectControl
__nextHasNoMarginBottom
__next40pxDefaultSize
label={ __( 'HTML element' ) }
<HTMLElementSelectControl
tagName={ tagName }
onChange={ ( value ) =>
setAttributes( { tagName: value } )
}
currentClientId={ clientId }
options={ [
{ label: __( 'Default (<div>)' ), value: 'div' },
{ label: '<section>', value: 'section' },
{ label: '<aside>', value: 'aside' },
] }
value={ tagName }
onChange={ ( value ) =>
setAttributes( { tagName: value } )
}
help={ htmlElementMessages[ tagName ] }
/>
</InspectorControls>
</InspectorControls>
Expand Down
3 changes: 2 additions & 1 deletion packages/block-library/src/comments/edit/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import CommentsLegacy from './comments-legacy';
import TEMPLATE from './template';

export default function CommentsEdit( props ) {
const { attributes, setAttributes } = props;
const { attributes, setAttributes, clientId } = props;
const { tagName: TagName, legacy } = attributes;

const blockProps = useBlockProps();
Expand All @@ -28,6 +28,7 @@ export default function CommentsEdit( props ) {
<CommentsInspectorControls
attributes={ attributes }
setAttributes={ setAttributes }
clientId={ clientId }
/>
<TagName { ...innerBlocksProps } />
</>
Expand Down
18 changes: 7 additions & 11 deletions packages/block-library/src/cover/edit/inspector-controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
RangeControl,
TextareaControl,
ToggleControl,
SelectControl,
__experimentalUseCustomUnits as useCustomUnits,
__experimentalToolsPanel as ToolsPanel,
__experimentalToolsPanelItem as ToolsPanelItem,
Expand All @@ -24,6 +23,7 @@ import {
__experimentalUseGradient,
__experimentalUseMultipleOriginColorsAndGradients as useMultipleOriginColorsAndGradients,
privateApis as blockEditorPrivateApis,
HTMLElementSelectControl,
} from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
Expand All @@ -36,7 +36,6 @@ import { COVER_MIN_HEIGHT, mediaPosition } from '../shared';
import { unlock } from '../../lock-unlock';
import { useToolsPanelDropdownMenuProps } from '../../utils/hooks';
import { DEFAULT_MEDIA_SIZE_SLUG } from '../constants';
import { htmlElementMessages } from '../../utils/messages';

const { cleanEmptyObject, ResolutionTool } = unlock( blockEditorPrivateApis );

Expand Down Expand Up @@ -421,10 +420,12 @@ export default function CoverInspectorControls( {
</ToolsPanelItem>
</InspectorControls>
<InspectorControls group="advanced">
<SelectControl
__nextHasNoMarginBottom
__next40pxDefaultSize
label={ __( 'HTML element' ) }
<HTMLElementSelectControl
tagName={ tagName }
onChange={ ( value ) =>
setAttributes( { tagName: value } )
}
currentClientId={ clientId }
options={ [
{ label: __( 'Default (<div>)' ), value: 'div' },
{ label: '<header>', value: 'header' },
Expand All @@ -434,11 +435,6 @@ export default function CoverInspectorControls( {
{ label: '<aside>', value: 'aside' },
{ label: '<footer>', value: 'footer' },
] }
value={ tagName }
onChange={ ( value ) =>
setAttributes( { tagName: value } )
}
help={ htmlElementMessages[ tagName ] }
/>
</InspectorControls>
</>
Expand Down
Loading
Loading