diff --git a/tools/gulp/tasks/docs.ts b/tools/gulp/tasks/docs.ts index e6b9fc5021a1..ace221fde277 100644 --- a/tools/gulp/tasks/docs.ts +++ b/tools/gulp/tasks/docs.ts @@ -11,6 +11,11 @@ import * as path from 'path'; // viewer. const EXAMPLE_PATTERN = //g; +// Markdown files can contain links to other markdown files. +// Most of those links don't work in the Material docs, because the paths are invalid in the +// documentation page. Using a RegExp to rewrite links in HTML files to work in the docs. +const LINK_PATTERN = /(]*) href="([^"]*)"/g; + gulp.task('docs', () => { return gulp.src(['src/lib/**/*.md', 'guides/*.md']) .pipe(markdown({ @@ -25,9 +30,7 @@ gulp.task('docs', () => { return code; } })) - .pipe(transform((content: string) => - content.toString().replace(EXAMPLE_PATTERN, (match: string, name: string) => - `
`))) + .pipe(transform(transformMarkdownFiles)) .pipe(gulp.dest('dist/docs')); }); @@ -37,3 +40,36 @@ task('api', () => { const dgeni = new Dgeni([docsPackage]); return dgeni.generate(); }); + +/** Updates the markdown file's content to work inside of the docs app. */ +function transformMarkdownFiles(buffer: Buffer, file: any): string { + let content = buffer.toString('utf-8'); + + /* Replace comments with HTML elements. */ + content = content.replace(EXAMPLE_PATTERN, (match: string, name: string) => + `
` + ); + + /* Replaces the URL in anchor elements inside of compiled markdown files. */ + content = content.replace(LINK_PATTERN, (match: string, head: string, link: string) => + // The head is the first match of the RegExp and is necessary to ensure that the RegExp matches + // an anchor element. The head will be then used to re-create the existing anchor element. + // If the head is not prepended to the replaced value, then the first match will be lost. + `${head} href="${fixMarkdownDocLinks(link, file.path)}"` + ); + + return content; +} + +/** Fixes paths in the markdown files to work in the material-docs-io. */ +function fixMarkdownDocLinks(link: string, filePath: string): string { + if (link.startsWith('http') && filePath.indexOf('guides/') === -1) { + return link; + } + + let baseName = path.basename(link, path.extname(link)); + + // Temporary link the file to the /guide URL because that's the route where the + // guides can be loaded in the Material docs. + return `guide/${baseName}`; +}