Skip to content

Commit

Permalink
Add Table of Contents block (dynamic rendering + hooks version) (#21234)
Browse files Browse the repository at this point in the history
* SeanDS's implementation #21040 (#21040).

Copy changes from pull request #15426 (#15426).

Adds Table of Contents block to the editor.

Code contributions in this commit entirely made by ashwin-pc, originally based on the
"Guidepost" block by sorta brilliant (https://sortabrilliant.com/guidepost/).

Apply polish suggestions from code review.

Improve variable names.

Add comment

Get rid of autosync (users should now convert to list if they want to edit the contents)

Add ability to transform into list; remove unused ListLevel props

Update table-of-contents block test configuration

Simplify expression

Remove unused function

Remove unused styles.

Rename TOCEdit to TableOfContentsEdit

Apply suggestions from code review

Remove non-existent import

Make imports explicit

Remove unused function

Change unsubscribe function to class property

Change JSON.stringify comparison to Lodash's isEqual

Turns out refresh() is required

Remove unnecessary state setting

Don't change state on save

Change behaviour to only add links if there are anchors specified by the user

Newline

Replace anchor with explicit key in map since anchor can now sometimes be empty

Update test data

Update packages/block-library/src/table-of-contents/block.json

Rename ListLevel to ListItem for clarity and polish.

Co-authored-by: ashwin-pc <[email protected]>
Co-authored-by: Daniel Richards <[email protected]>
Co-authored-by: Zebulan Stanphill <[email protected]>
Co-authored-by: JR Tashjian <[email protected]>

* Polish, use hooks, and half-fix undo behavior.

* Make dynamic, and add support for paginated posts + h1-h6 tags outside of core blocks.

DRY out usage of list item class name.

Improve handling of heading attributes.

Add proper placeholder state in editor.

Fix mistakes, improve naming/description, and polish code.

Add support for page breaks in a Classic block.

Always ignore empty headings.

Various performance improvements.

Change List block conversion to be a button in the toolbar. (It can't use the transform API since it uses dynamic data.)

Remove unused key from hierarchical heading list.

* Add unique icon.

Co-authored-by: Joen A <[email protected]>

* Fix "Convert to static list" control.

* Tweak keywords.

Co-authored-by: Sean Leavey <[email protected]>
Co-authored-by: ashwin-pc <[email protected]>
Co-authored-by: Daniel Richards <[email protected]>
Co-authored-by: JR Tashjian <[email protected]>
Co-authored-by: Joen A <[email protected]>
  • Loading branch information
6 people authored Feb 24, 2021
1 parent c19bd61 commit abb2bf7
Show file tree
Hide file tree
Showing 14 changed files with 802 additions and 0 deletions.
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

0 comments on commit abb2bf7

Please sign in to comment.