UNPKG

@wordpress/block-library

Version:
49 lines (48 loc) • 1.88 kB
import { createBlock } from "@wordpress/blocks"; import { escapeAttribute, escapeEditableHTML } from "@wordpress/escape-html"; // packages/block-library/src/table-of-contents/utils.ts /** * Takes a flat list of heading parameters and nests them based on each header's * immediate parent's level. * * @param headingList The flat list of headings to nest. * * @return The nested list of headings. */ 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; } /** * Converts a nested heading list into `core/list-item` blocks, with * sub-headings nested in a `core/list` block inside their parent item. * * @param nestedHeadingList The nested list of headings. * @param ordered Whether nested lists are ordered. * * @return The list item blocks. */ function createListItemBlocks(nestedHeadingList, ordered) { return nestedHeadingList.map(({ heading: { content, link }, children }) => createBlock("core/list-item", { 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