@wordpress/block-library
Version:
Block library for the WordPress editor.
67 lines (66 loc) • 1.74 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_url = require("@wordpress/url");
// packages/block-library/src/heading/autogenerate-anchors.js
/**
* Object map tracking anchors.
*
* @type {Record<string, string | null>}
*/
const anchors = {};
/**
* Returns the text without markup.
*
* @param {string} text The text.
*
* @return {string} The text without markup.
*/
const getTextWithoutMarkup = (text) => {
const dummyElement = document.createElement("div");
dummyElement.innerHTML = text;
dummyElement.querySelectorAll("annotation, sup[data-fn]").forEach((element) => element.remove());
return dummyElement.innerText;
};
/**
* Get the slug from the content.
*
* @param {string} content The block content.
*
* @return {string} Returns the slug.
*/
const getSlug = (content) => (0, _wordpress_url.cleanForSlug)(getTextWithoutMarkup(content));
/**
* Generate the anchor for a heading.
*
* @param {string} clientId The block ID.
* @param {string} content The block content.
*
* @return {string|null} Return the heading anchor.
*/
const generateAnchor = (clientId, content) => {
const slug = getSlug(content);
if ("" === slug) return null;
delete anchors[clientId];
let anchor = slug;
let i = 0;
while (Object.values(anchors).includes(anchor)) {
i += 1;
anchor = slug + "-" + i;
}
return anchor;
};
/**
* Set the anchor for a heading.
*
* @param {string} clientId The block ID.
* @param {string|null} anchor The block anchor.
*/
const setAnchor = (clientId, anchor) => {
anchors[clientId] = anchor;
};
exports.generateAnchor = generateAnchor;
exports.setAnchor = setAnchor;
//# sourceMappingURL=autogenerate-anchors.cjs.map