import classnames from "classnames"; import { __ } from "@wordpress/i18n"; import { registerBlockType } from "@wordpress/blocks"; import { useEffect } from "react"; import { cleanForSlug } from "@wordpress/url"; const IconTableOfContents = ( ); registerBlockType("custom-block/table-of-contents", { title: __("Table of Contents"), description: __("List of all H2 and H3 in the page."), keywords: [__("contents"), __("table of contents")], category: "common", icon: IconTableOfContents, example: {}, attributes: { headings: { type: "array", default: [], }, }, edit: (props) => { const { className, attributes: { headings }, setAttributes, } = props; const getHeadings = () => { const _headings = []; document.querySelectorAll(".is-root-container :is(h2,h3)").forEach((item) => { const tier = item.tagName === "H2" ? "2" : "3"; const slug = cleanForSlug(item.innerText); const title = item.innerText; _headings.push({ tier, slug, title }); }); setAttributes({ headings: _headings }); }; useEffect(() => { document.querySelector(".editor-post-publish-button__button").addEventListener("click", async () => { getHeadings(); }); }, []); window.addEventListener("load", async () => { getHeadings(); }); const newClass = classnames(className, "toc"); return (
Table of Contents
); }, save: (props) => { const { className, attributes: { headings }, } = props; const newClass = classnames(className, "toc"); const openToc = (e) => { console.log(e); }; return (
Table of Contents
); }, });