UNPKG

@wordpress/block-library

Version:
61 lines (60 loc) 1.79 kB
// packages/block-library/src/table-of-contents/utils.ts import { createBlock } from "@wordpress/blocks"; import { escapeAttribute, escapeEditableHTML } from "@wordpress/escape-html"; function linearToNestedHeadingList(headingList) { const nestedHeadingList = []; headingList.forEach((heading, key) => { if (heading.content === "") { return; } if (heading.level === headingList[0].level) { if (headingList[key + 1]?.level > heading.level) { let endOfSlice = headingList.length; for (let i = key + 1; i < headingList.length; i++) { if (headingList[i].level === heading.level) { endOfSlice = i; break; } } nestedHeadingList.push({ heading, children: linearToNestedHeadingList( headingList.slice(key + 1, endOfSlice) ) }); } else { nestedHeadingList.push({ heading, children: null }); } } }); return nestedHeadingList; } function createListItemBlocks(nestedHeadingList, ordered) { return nestedHeadingList.map( ({ heading: { content, link }, children }) => createBlock( "core/list-item", { // Headings are plain text, and links can carry query args on // paginated posts, so both need escaping to become markup. content: link ? `<a href="${escapeAttribute( link )}">${escapeEditableHTML(content)}</a>` : escapeEditableHTML(content) }, children?.length ? [ createBlock( "core/list", { ordered }, createListItemBlocks(children, ordered) ) ] : [] ) ); } export { createListItemBlocks, linearToNestedHeadingList }; //# sourceMappingURL=utils.mjs.map