rework rehype plugin
This commit is contained in:
@ -1,50 +0,0 @@
|
||||
const nonAlphaNum = /[^A-Za-z0-9\-]/g;
|
||||
const space = /\s/g
|
||||
|
||||
export function makeSlug(text) {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(space, '-')
|
||||
.replace(nonAlphaNum, '')
|
||||
}
|
||||
|
||||
function apply(node, types, fn) {
|
||||
if (typeof types === 'string') {
|
||||
types = new Set([types]);
|
||||
}
|
||||
else if (!(types instanceof Set)) {
|
||||
types = new Set(types)
|
||||
console.log(types)
|
||||
}
|
||||
|
||||
if (types.has(node.type)) {
|
||||
fn(node);
|
||||
}
|
||||
if ('children' in node) {
|
||||
for (let child of node.children) {
|
||||
apply(child, types, fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getTextContent(node) {
|
||||
let segments = [];
|
||||
apply(node, 'text', textNode => {
|
||||
// skip all-whitespace strings
|
||||
if (textNode.value.match(/^\s+$/)) return;
|
||||
segments.push(textNode.value.trim());
|
||||
});
|
||||
|
||||
return segments.join(' ');
|
||||
}
|
||||
|
||||
export default function slug() {
|
||||
return (tree) => {
|
||||
apply(tree, 'element', e => {
|
||||
if (e.tagName.match(/h[1-6]/)) {
|
||||
let text = getTextContent(e);
|
||||
e.properties.id = makeSlug(text);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
8
src/lib/utils.js
Normal file
8
src/lib/utils.js
Normal file
@ -0,0 +1,8 @@
|
||||
const nonAlphaNum = /[^A-Za-z0-9\-]/g;
|
||||
const space = /\s+/g;
|
||||
export function makeSlug(text) {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(space, '-')
|
||||
.replace(nonAlphaNum, '');
|
||||
}
|
Reference in New Issue
Block a user