1
1
// Copyright (c) jdneo. All rights reserved.
2
2
// Licensed under the MIT license.
3
3
4
+ import * as hljs from "highlight.js" ;
5
+ import * as MarkdownIt from "markdown-it" ;
4
6
import { Disposable , ExtensionContext , ViewColumn , WebviewPanel , window } from "vscode" ;
5
7
import { Solution } from "./shared" ;
6
8
7
9
class LeetCodeSolutionProvider implements Disposable {
8
10
9
11
private context : ExtensionContext ;
10
12
private panel : WebviewPanel | undefined ;
13
+ private markdown : MarkdownIt ;
14
+ private solution : Solution ;
11
15
12
16
public initialize ( context : ExtensionContext ) : void {
13
17
this . context = context ;
18
+ this . markdown = new MarkdownIt ( {
19
+ linkify : true ,
20
+ typographer : true ,
21
+ highlight : this . codeHighlighter . bind ( this ) ,
22
+ } ) ;
14
23
}
15
24
16
25
public async show ( solutionString : string ) : Promise < void > {
@@ -25,9 +34,9 @@ class LeetCodeSolutionProvider implements Disposable {
25
34
} , null , this . context . subscriptions ) ;
26
35
}
27
36
28
- const solution : Solution = this . parseSolution ( solutionString ) ;
29
- this . panel . title = solution . title ;
30
- this . panel . webview . html = this . getWebViewContent ( solution . body ) ;
37
+ this . solution = this . parseSolution ( solutionString ) ;
38
+ this . panel . title = this . solution . title ;
39
+ this . panel . webview . html = this . getWebViewContent ( this . solution . body ) ;
31
40
this . panel . reveal ( ViewColumn . Active ) ;
32
41
}
33
42
@@ -50,20 +59,35 @@ class LeetCodeSolutionProvider implements Disposable {
50
59
return solution ;
51
60
}
52
61
53
- private getWebViewContent ( result : string ) : string {
54
- return `
55
- <!DOCTYPE html>
56
- <html lang="en">
57
- <head>
58
- <meta charset="UTF-8">
59
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
60
- <title>LeetCode Top Voted Solution</title>
61
- </head>
62
- <body>
63
- <pre>${ result } </pre>
64
- </body>
65
- </html>
66
- ` ;
62
+ private codeHighlighter ( code : string , lang : string | undefined ) : string {
63
+ if ( ! lang ) {
64
+ lang = this . solution . lang ;
65
+ }
66
+ // tslint:disable-next-line:typedef
67
+ const hljst = hljs ;
68
+ if ( hljst . getLanguage ( lang ) ) {
69
+ try {
70
+ return hljst . highlight ( lang , code ) . value ;
71
+ } catch ( error ) { /* do not highlight */ }
72
+ }
73
+ return "" ; // use external default escaping
74
+ }
75
+
76
+ private getWebViewContent ( body : string ) : string {
77
+ return this . markdown . render ( body ) ;
78
+ // return `
79
+ // <!DOCTYPE html>
80
+ // <html lang="en">
81
+ // <head>
82
+ // <meta charset="UTF-8">
83
+ // <meta name="viewport" content="width=device-width, initial-scale=1.0">
84
+ // <title>LeetCode Top Voted Solution</title>
85
+ // </head>
86
+ // <body>
87
+ // <pre>${body}</pre>
88
+ // </body>
89
+ // </html>
90
+ // `;
67
91
}
68
92
}
69
93
0 commit comments