mirror of
https://github.com/facebook/docusaurus.git
synced 2025-07-11 22:07:56 +02:00
Ensure anchor links are unique per document (#574)
This commit is contained in:
parent
2a83959ac1
commit
9c98142fea
12 changed files with 440 additions and 43 deletions
|
@ -18,7 +18,16 @@ const exceptAlphanum = new RegExp(
|
|||
'g'
|
||||
);
|
||||
|
||||
module.exports = string => {
|
||||
/**
|
||||
* Converts a string to a slug, that can be used in heading anchors
|
||||
*
|
||||
* @param {string} string
|
||||
* @param {Object} [context={}] - an optional context to track used slugs and
|
||||
* ensure that new slug will be unique
|
||||
*
|
||||
* @return {string}
|
||||
*/
|
||||
module.exports = (string, context = {}) => {
|
||||
// var accents = "àáäâèéëêìíïîòóöôùúüûñç";
|
||||
const accents =
|
||||
'\u00e0\u00e1\u00e4\u00e2\u00e8' +
|
||||
|
@ -50,5 +59,22 @@ module.exports = string => {
|
|||
slug += '-';
|
||||
}
|
||||
|
||||
if (!context.slugStats) {
|
||||
context.slugStats = {};
|
||||
}
|
||||
|
||||
if (typeof context.slugStats[slug] === 'number') {
|
||||
// search for an index, that will not clash with an existing headings
|
||||
while (
|
||||
typeof context.slugStats[slug + '-' + ++context.slugStats[slug]] ===
|
||||
'number'
|
||||
);
|
||||
slug += '-' + context.slugStats[slug];
|
||||
}
|
||||
|
||||
// we are tracking both original anchors and suffixed to avoid future name
|
||||
// clashing with headings with numbers e.g. `#Foo 1` may clash with the second `#Foo`
|
||||
context.slugStats[slug] = 0;
|
||||
|
||||
return slug;
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue