Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Table of Contents block (dynamic rendering + hooks version) #21234

Merged
merged 6 commits into from
Feb 24, 2021
Merged
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
2 changes: 2 additions & 0 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ function gutenberg_reregister_core_block_types() {
'spacer',
'subhead',
'table',
'table-of-contents',
'text-columns',
'verse',
'video',
Expand Down Expand Up @@ -89,6 +90,7 @@ function gutenberg_reregister_core_block_types() {
'site-logo.php' => 'core/site-logo',
'site-tagline.php' => 'core/site-tagline',
'site-title.php' => 'core/site-title',
'table-of-contents.php' => 'core/table-of-contents',
'template-part.php' => 'core/template-part',
)
),
Expand Down
2 changes: 2 additions & 0 deletions packages/block-library/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import * as shortcode from './shortcode';
import * as spacer from './spacer';
import * as subhead from './subhead';
import * as table from './table';
import * as tableOfContents from './table-of-contents';
import * as textColumns from './text-columns';
import * as verse from './verse';
import * as video from './video';
Expand Down Expand Up @@ -162,6 +163,7 @@ export const __experimentalGetCoreBlocks = () => [
spacer,
subhead,
table,
tableOfContents,
tagCloud,
textColumns,
verse,
Expand Down
15 changes: 15 additions & 0 deletions packages/block-library/src/table-of-contents/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"apiVersion": 2,
"name": "core/table-of-contents",
"category": "layout",
"attributes": {
"onlyIncludeCurrentPage": {
"type": "boolean",
"default": false
}
},
"usesContext": [ "postId" ],
"supports": {
"html": false
}
}
215 changes: 215 additions & 0 deletions packages/block-library/src/table-of-contents/edit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/**
* External dependencies
*/
import { isEqual } from 'lodash';

/**
* WordPress dependencies
*/
import {
BlockControls,
BlockIcon,
InspectorControls,
store as blockEditorStore,
useBlockProps,
} from '@wordpress/block-editor';
import { createBlock, store as blocksStore } from '@wordpress/blocks';
import {
PanelBody,
Placeholder,
ToggleControl,
ToolbarButton,
ToolbarGroup,
} from '@wordpress/components';
import { useDispatch, useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import { renderToString, useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import TableOfContentsList from './list';
import { getHeadingsFromContent, linearToNestedHeadingList } from './utils';

/**
* Table of Contents block edit component.
*
* @param {Object} props The props.
* @param {Object} props.attributes The block attributes.
* @param {boolean} props.attributes.onlyIncludeCurrentPage
* Whether to only include headings from the current page (if the post is
* paginated).
* @param {string} props.clientId
* @param {(attributes: Object) => void} props.setAttributes
*
* @return {WPComponent} The component.
*/
export default function TableOfContentsEdit( {
attributes: { onlyIncludeCurrentPage },
clientId,
setAttributes,
} ) {
const blockProps = useBlockProps();

// Local state; not saved to block attributes. The saved block is dynamic and uses PHP to generate its content.
const [ headings, setHeadings ] = useState( [] );
const [ headingTree, setHeadingTree ] = useState( [] );

const { listBlockExists, postContent } = useSelect(
( select ) => ( {
listBlockExists: !! select( blocksStore ).getBlockType(
'core/list'
),
postContent: select( editorStore ).getEditedPostContent(),
} ),
[]
);

// The page this block would be part of on the front-end. For performance
// reasons, this is only calculated when onlyIncludeCurrentPage is true.
const pageIndex = useSelect(
( select ) => {
if ( ! onlyIncludeCurrentPage ) {
return null;
}

const {
getBlockAttributes,
getBlockIndex,
getBlockName,
getBlockOrder,
} = select( blockEditorStore );

const blockIndex = getBlockIndex( clientId );
const blockOrder = getBlockOrder();

// Calculate which page the block will appear in on the front-end by
// counting how many <!--nextpage--> tags precede it.
// Unfortunately, this implementation only accounts for Page Break and
// Classic blocks, so if there are any <!--nextpage--> tags in any
// other block, they won't be counted. This will result in the table
// of contents showing headings from the wrong page if
// onlyIncludeCurrentPage === true. Thankfully, this issue only
// affects the editor implementation.
let page = 1;
for ( let i = 0; i < blockIndex; i++ ) {
const blockName = getBlockName( blockOrder[ i ] );
if ( blockName === 'core/nextpage' ) {
page++;
} else if ( blockName === 'core/freeform' ) {
// Count the page breaks inside the Classic block.
const pageBreaks = getBlockAttributes(
blockOrder[ i ]
).content?.match( /<!--nextpage-->/g );

if ( pageBreaks !== null && pageBreaks !== undefined ) {
page += pageBreaks.length;
}
}
}

return page;
},
[ clientId, onlyIncludeCurrentPage ]
);

useEffect( () => {
let latestHeadings;

if ( onlyIncludeCurrentPage ) {
const pagesOfContent = postContent.split( '<!--nextpage-->' );

latestHeadings = getHeadingsFromContent(
pagesOfContent[ pageIndex - 1 ]
);
} else {
latestHeadings = getHeadingsFromContent( postContent );
}

if ( ! isEqual( headings, latestHeadings ) ) {
setHeadings( latestHeadings );
setHeadingTree( linearToNestedHeadingList( latestHeadings ) );
}
}, [ pageIndex, postContent, onlyIncludeCurrentPage ] );

const { replaceBlocks } = useDispatch( blockEditorStore );

const toolbarControls = listBlockExists && (
<BlockControls>
<ToolbarGroup>
<ToolbarButton
onClick={ () =>
replaceBlocks(
clientId,
createBlock( 'core/list', {
values: renderToString(
<TableOfContentsList
nestedHeadingList={ headingTree }
/>
),
} )
)
}
>
{ __( 'Convert to static list' ) }
</ToolbarButton>
</ToolbarGroup>
</BlockControls>
);

const inspectorControls = (
<InspectorControls>
<PanelBody title={ __( 'Table of Contents settings' ) }>
<ToggleControl
label={ __( 'Only include current page' ) }
checked={ onlyIncludeCurrentPage }
onChange={ ( value ) =>
setAttributes( { onlyIncludeCurrentPage: value } )
}
help={
onlyIncludeCurrentPage
? __(
'Only including headings from the current page (if the post is paginated).'
)
: __(
'Toggle to only include headings from the current page (if the post is paginated).'
)
}
/>
</PanelBody>
</InspectorControls>
);

// If there are no headings or the only heading is empty.
// Note that the toolbar controls are intentionally omitted since the
// "Convert to static list" option is useless to the placeholder state.
if ( headings.length === 0 ) {
return (
<>
<div { ...blockProps }>
<Placeholder
icon={ <BlockIcon icon="list-view" /> }
label="Table of Contents"
instructions={ __(
'Start adding Heading blocks to create a table of contents. Headings with HTML anchors will be linked here.'
) }
/>
</div>
{ inspectorControls }
</>
);
}

return (
<>
<nav { ...blockProps }>
<ul>
<TableOfContentsList nestedHeadingList={ headingTree } />
</ul>
</nav>
{ toolbarControls }
{ inspectorControls }
</>
);
}
18 changes: 18 additions & 0 deletions packages/block-library/src/table-of-contents/icon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* WordPress dependencies
*/
import { SVG, Path } from '@wordpress/components';

export default (
<SVG
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
>
<Path
d="M15.1 15.8H20v-1.5h-4.9v1.5zm-4-8.6v1.5H20V7.2h-8.9zM6 13c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 3c-.6 0-1-.4-1-1s.4-1 1-1 1 .4 1 1-.4 1-1 1zm5-3c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
fill="#1e1e1e"
/>
</SVG>
);
25 changes: 25 additions & 0 deletions packages/block-library/src/table-of-contents/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import metadata from './block.json';
import edit from './edit';
import icon from './icon';

const { name } = metadata;

export { metadata, name };

export const settings = {
title: __( 'Table of Contents' ),
description: __(
'Summarize your post with a list of headings. Add HTML anchors to Heading blocks to link them here.'
),
icon,
keywords: [ __( 'document outline' ), __( 'summary' ) ],
edit,
};
Loading