Skip to content

Commit

Permalink
feat: add basic code render
Browse files Browse the repository at this point in the history
  • Loading branch information
phodal committed Mar 12, 2020
1 parent c3c3f29 commit 93c3fc4
Showing 1 changed file with 60 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Component, Input, OnInit } from '@angular/core';
import { MarkdownService } from 'ngx-markdown';
import {Component, Input, OnInit} from '@angular/core';
import {MarkdownService} from 'ngx-markdown';

@Component({
selector: 'component-markdown-render',
Expand All @@ -11,11 +11,30 @@ export class MarkdownRenderComponent implements OnInit {
src: string;
loading = true;

constructor(private markdownService: MarkdownService) { }
// marked
escapeTest = /[&<>"']/;
escapeReplace = /[&<>"']/g;
escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
escapeReplacements = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#39;'
};

constructor(private markdownService: MarkdownService) {
}

ngOnInit(): void {
const markedOptions: any = this.markdownService.options;
this.markdownService.renderer.image = this.renderImage(markedOptions).bind(this);
this.markdownService.renderer.code = this.renderCode(markedOptions).bind(this);
}

endLoading() {
this.loading = false;
}

private renderImage(markedOptions: any) {
Expand All @@ -34,8 +53,44 @@ export class MarkdownRenderComponent implements OnInit {
};
}

endLoading() {
this.loading = false;
private renderCode(options: any) {
return (code: any, infoStr: any, escaped: any) => {
const lang = (infoStr || '').match(/\S*/)[0];

if (options.highlight) {
const out = options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}

if (!lang) {
return '<pre><code>' + (escaped ? code : this.escape(code, true)) + '</code></pre>';
}

return `<pre>
<code class="${options.langPrefix}${this.escape(lang, true)}">${escaped ? code : this.escape(code, true)}</code>
</pre>`;
};
}

getEscapeReplacement(ch) {
return this.escapeReplacements[ch];
}

escape(html: string, encode: boolean) {
if (encode) {
if (this.escapeTest.test(html)) {
return html.replace(this.escapeReplace, this.getEscapeReplacement.bind(this));
}
} else {
if (this.escapeTestNoEncode.test(html)) {
return html.replace(this.escapeReplaceNoEncode, this.getEscapeReplacement.bind(this));
}
}

return html;
}

}

0 comments on commit 93c3fc4

Please sign in to comment.