Updated to only add numbering to slugified heading anchors when absolutely neccessary

This commit is contained in:
Tom Moor
2018-01-27 11:45:46 -08:00
parent 7647d23804
commit edcb92d223
3 changed files with 26 additions and 22 deletions

View File

@ -1,10 +1,25 @@
// @flow
import { escape } from 'lodash';
import { Node } from 'slate';
import { Document, Block, Node } from 'slate';
import slug from 'slug';
export default function headingToSlug(node: Node, index: number = 0) {
const slugified = escape(slug(node.text));
if (index === 0) return slugified;
return `${index}-${slugified}`;
// finds the index of this heading in the document compared to other headings
// with the same slugified text
function indexOfType(document, heading) {
const slugified = escape(slug(heading.text));
const headings = document.nodes.filter((node: Block) => {
if (!node.text) return false;
return node.type.match(/^heading/) && slugified === escape(slug(node.text));
});
return headings.indexOf(heading);
}
// calculates a unique slug for this heading based on it's text and position
// in the document that is as stable as possible
export default function headingToSlug(document: Document, node: Node) {
const slugified = escape(slug(node.text));
const index = indexOfType(document, node);
if (index === 0) return slugified;
return `${slugified}-${index}`;
}