UNPKG

@wordpress/block-library

Version:
55 lines (54 loc) • 2.18 kB
"use strict"; Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); let _wordpress_blocks = require("@wordpress/blocks"); let _wordpress_escape_html = require("@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 }) => (0, _wordpress_blocks.createBlock)("core/list-item", { content: link ? `<a href="${(0, _wordpress_escape_html.escapeAttribute)(link)}">${(0, _wordpress_escape_html.escapeEditableHTML)(content)}</a>` : (0, _wordpress_escape_html.escapeEditableHTML)(content) }, children?.length ? [(0, _wordpress_blocks.createBlock)("core/list", { ordered }, createListItemBlocks(children, ordered))] : [])); } exports.createListItemBlocks = createListItemBlocks; exports.linearToNestedHeadingList = linearToNestedHeadingList; //# sourceMappingURL=utils.cjs.map