Skip to content

Commit d3ed9c4

Browse files
annieywjelbourn
authored andcommitted
refactor: update api for embedded example comments in md docs (#19252)
* update example comment api in md to html renderer * support for old and new api before docs are updated * stringify lines to preserve brackets Co-authored-by: Annie Wang <annieyw@google.com>
1 parent 8987ad4 commit d3ed9c4

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

tools/markdown-to-html/docs-marked-renderer.ts

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {basename, extname} from 'path';
55
const whitespaceRegex = /\W+/g;
66

77
/** Regular expression that matches example comments. */
8-
const exampleCommentRegex = /<!--\W*example\(([^)]+)\)\W*-->/g;
8+
const exampleCommentRegex = /<!--\s*example\(([^)]+)\)\s*-->/g;
99

1010
/**
1111
* Custom renderer for marked that will be used to transform markdown files to HTML
@@ -47,17 +47,44 @@ export class DocsMarkdownRenderer extends Renderer {
4747

4848
/**
4949
* Method that will be called whenever inline HTML is processed by marked. In that case,
50-
* we can easily transform the example comments into real HTML elements. For example:
50+
* we can easily transform the example comments into real HTML elements.
51+
* For example:
52+
* (New API)
53+
* `<!-- example(
54+
* {
55+
* "example": "exampleName",
56+
* "file": "example-html.html",
57+
* "lines": [5, 10],
58+
* "expanded": true
59+
* }
60+
* ) -->`
61+
* turns into
62+
* `<div material-docs-example="exampleName"
63+
* file="example-html.html"
64+
* lines="[5, 10]"
65+
* expanded="true"></div>`
5166
*
52-
* `<!-- example(name) -->` turns into `<div material-docs-example="name"></div>`
67+
* (old API)
68+
* `<!-- example(name) -->`
69+
* turns into
70+
* `<div material-docs-example="name"></div>`
5371
*/
5472
html(html: string) {
55-
html = html.replace(exampleCommentRegex, (_match: string, name: string) =>
56-
`<div material-docs-example="${name}"></div>`
57-
);
73+
html = html.replace(exampleCommentRegex, (_match: string, content: string) => {
74+
if (content.startsWith('{')) {
75+
const {example, file, lines, expanded} = JSON.parse(content);
76+
return `<div material-docs-example="${example}"
77+
file="${file}"
78+
lines="${JSON.stringify(lines)}"
79+
expanded="${!!expanded}"></div>`;
80+
} else {
81+
return `<div material-docs-example="${content}"></div>`;
82+
}
83+
}
84+
);
5885

59-
return super.html(html);
60-
}
86+
return super.html(html);
87+
}
6188

6289
/**
6390
* Method that will be called after a markdown file has been transformed to HTML. This method

0 commit comments

Comments
 (0)