docs(api.md): fix table-of-contents (#2636)

This patch drops the markdown-toc module and instead rolls out
our own simple markdown table-of-contents generator.

As a side effect, it fixes links to `page.$` and `page.$$`.
This commit is contained in:
Andrey Lushnikov
2018-05-31 14:21:43 -07:00
committed by GitHub
parent 0ad0096e21
commit 754df58d4e
4 changed files with 57 additions and 11 deletions

View File

@@ -56,6 +56,8 @@ module.exports = function(sources, version) {
newText = isReleaseVersion ? '' : command.originalText;
else if (command.name === 'last-released-api')
newText = lastReleasedAPILink;
else if (command.name === 'toc')
newText = generateTableOfContents(command.source.text().substring(command.to));
if (newText === null)
messages.push(Message.error(`Unknown command 'gen:${command.name}'`));
else if (applyCommand(command, newText))
@@ -77,3 +79,30 @@ function applyCommand(command, editText) {
return command.source.setText(newText);
}
function generateTableOfContents(mdText) {
const ids = new Set();
const titles = mdText.split('\n').map(line => line.trim()).filter(line => line.startsWith('#'));
const tocEntries = [];
for (const title of titles) {
const [, nesting, name] = title.match(/^(#+)\s+(.*)$/);
const id = name.trim().toLowerCase().replace(/\s/g, '-').replace(/[^-0-9a-zа-яё]/ig, '');
let dedupId = id;
let counter = 0;
while (ids.has(dedupId))
dedupId = id + '-' + (++counter);
ids.add(dedupId);
tocEntries.push({
level: nesting.length,
name,
id: dedupId
});
}
const minLevel = Math.min(...tocEntries.map(entry => entry.level));
tocEntries.forEach(entry => entry.level -= minLevel);
return '\n' + tocEntries.map(entry => {
const prefix = entry.level % 2 === 0 ? '-' : '*';
const padding = ' '.repeat(entry.level);
return `${padding}${prefix} [${entry.name}](#${entry.id})`;
}).join('\n') + '\n';
}

View File

@@ -126,6 +126,26 @@ describe('preprocessor', function() {
`);
});
});
describe('gen:toc', function() {
it('should work', () => {
const source = new Source('doc.md', `<!-- gen:toc -->XXX<!-- gen:stop -->
### class: page
#### page.$
#### page.$$`);
const messages = preprocessor([source], '1.3.0');
expect(messages.length).toBe(1);
expect(messages[0].type).toBe('warning');
expect(messages[0].text).toContain('doc.md');
expect(source.text()).toBe(`<!-- gen:toc -->
- [class: page](#class-page)
* [page.$](#page)
* [page.$$](#page-1)
<!-- gen:stop -->
### class: page
#### page.$
#### page.$$`);
});
});
it('should work with multiple commands', function() {
const source = new Source('doc.md', `
<!-- gen:version -->XXX<!-- gen:stop -->