Skip to content

Commit 60f03ed

Browse files
devversionkara
authored andcommitted
fix(docs): properly create links in guide files (#2770)
1 parent 632b964 commit 60f03ed

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

tools/gulp/tasks/docs.ts

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import * as path from 'path';
1111
// viewer.
1212
const EXAMPLE_PATTERN = /<!--\W*example\(([^)]+)\)\W*-->/g;
1313

14+
// Markdown files can contain links to other markdown files.
15+
// Most of those links don't work in the Material docs, because the paths are invalid in the
16+
// documentation page. Using a RegExp to rewrite links in HTML files to work in the docs.
17+
const LINK_PATTERN = /(<a[^>]*) href="([^"]*)"/g;
18+
1419
gulp.task('docs', () => {
1520
return gulp.src(['src/lib/**/*.md', 'guides/*.md'])
1621
.pipe(markdown({
@@ -25,9 +30,7 @@ gulp.task('docs', () => {
2530
return code;
2631
}
2732
}))
28-
.pipe(transform((content: string) =>
29-
content.toString().replace(EXAMPLE_PATTERN, (match: string, name: string) =>
30-
`<div material-docs-example="${name}"></div>`)))
33+
.pipe(transform(transformMarkdownFiles))
3134
.pipe(gulp.dest('dist/docs'));
3235
});
3336

@@ -37,3 +40,36 @@ task('api', () => {
3740
const dgeni = new Dgeni([docsPackage]);
3841
return dgeni.generate();
3942
});
43+
44+
/** Updates the markdown file's content to work inside of the docs app. */
45+
function transformMarkdownFiles(buffer: Buffer, file: any): string {
46+
let content = buffer.toString('utf-8');
47+
48+
/* Replace <!-- example(..) --> comments with HTML elements. */
49+
content = content.replace(EXAMPLE_PATTERN, (match: string, name: string) =>
50+
`<div material-docs-example="${name}"></div>`
51+
);
52+
53+
/* Replaces the URL in anchor elements inside of compiled markdown files. */
54+
content = content.replace(LINK_PATTERN, (match: string, head: string, link: string) =>
55+
// The head is the first match of the RegExp and is necessary to ensure that the RegExp matches
56+
// an anchor element. The head will be then used to re-create the existing anchor element.
57+
// If the head is not prepended to the replaced value, then the first match will be lost.
58+
`${head} href="${fixMarkdownDocLinks(link, file.path)}"`
59+
);
60+
61+
return content;
62+
}
63+
64+
/** Fixes paths in the markdown files to work in the material-docs-io. */
65+
function fixMarkdownDocLinks(link: string, filePath: string): string {
66+
if (link.startsWith('http') && filePath.indexOf('guides/') === -1) {
67+
return link;
68+
}
69+
70+
let baseName = path.basename(link, path.extname(link));
71+
72+
// Temporary link the file to the /guide URL because that's the route where the
73+
// guides can be loaded in the Material docs.
74+
return `guide/${baseName}`;
75+
}

0 commit comments

Comments
 (0)