1 | import { IHtmlEngineHelper, IHandlebarsOptions } from './html-engine-helper.interface';
|
2 | import { JsdocTagInterface } from '../../interfaces/jsdoc-tag.interface';
|
3 |
|
4 | export class JsdocCodeExampleHelper implements IHtmlEngineHelper {
|
5 | private cleanTag(comment: string): string {
|
6 | if (comment.charAt(0) === '*') {
|
7 | comment = comment.substring(1, comment.length);
|
8 | }
|
9 | if (comment.charAt(0) === ' ') {
|
10 | comment = comment.substring(1, comment.length);
|
11 | }
|
12 | if (comment.indexOf('<p>') === 0) {
|
13 | comment = comment.substring(3, comment.length);
|
14 | }
|
15 | if (comment.substr(-1) === '\n') {
|
16 | comment = comment.substring(0, comment.length - 1);
|
17 | }
|
18 | if (comment.substr(-4) === '</p>') {
|
19 | comment = comment.substring(0, comment.length - 4);
|
20 | }
|
21 | return comment;
|
22 | }
|
23 |
|
24 | private getHtmlEntities(str): string {
|
25 | return String(str)
|
26 | .replace(/&/g, '&')
|
27 | .replace(/</g, '<')
|
28 | .replace(/>/g, '>')
|
29 | .replace(/"/g, '"');
|
30 | }
|
31 |
|
32 | public helperFunc(context: any, jsdocTags: JsdocTagInterface[], options: IHandlebarsOptions) {
|
33 | let i = 0;
|
34 | let len = jsdocTags.length;
|
35 | let tags = [];
|
36 | let type = 'html';
|
37 |
|
38 | if (options.hash.type) {
|
39 | type = options.hash.type;
|
40 | }
|
41 |
|
42 | for (i; i < len; i++) {
|
43 | if (jsdocTags[i].tagName) {
|
44 | if (jsdocTags[i].tagName.text === 'example') {
|
45 | let tag = {} as JsdocTagInterface;
|
46 | if (jsdocTags[i].comment) {
|
47 | if (jsdocTags[i].comment.indexOf('<caption>') !== -1) {
|
48 | tag.comment = jsdocTags[i].comment
|
49 | .replace(/<caption>/g, '<b><i>')
|
50 | .replace(/\/caption>/g, '/b></i>');
|
51 | } else {
|
52 | tag.comment =
|
53 | `<pre class="line-numbers"><code class="language-${type}">` +
|
54 | this.getHtmlEntities(this.cleanTag(jsdocTags[i].comment)) +
|
55 | `</code></pre>`;
|
56 | }
|
57 | tags.push(tag);
|
58 | }
|
59 | }
|
60 | }
|
61 | }
|
62 |
|
63 | if (tags.length > 0) {
|
64 | context.tags = tags;
|
65 | return options.fn(context);
|
66 | }
|
67 | }
|
68 | }
|