This repository has been archived by the owner on Jun 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 48
/
docview.ts
245 lines (222 loc) · 9.74 KB
/
docview.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import axios from 'axios';
import cheerio = require('cheerio');
import { URL } from 'url';
import { commands, Disposable, Uri, ViewColumn, WebviewPanel, window,
workspace, WebviewOptions, WebviewPanelOptions } from 'vscode';
import * as fs from 'fs';
import { join } from 'path';
import { StaticServer } from './staticserver';
export function mkCommandUri(commandName: string, ...args: any[]): string {
return `command:${commandName}?${encodeURIComponent(JSON.stringify(args))}`;
}
function findProjectDocumentation(): string | null {
if (!workspace.rootPath) return null;
const html = join(workspace.rootPath, 'html', 'index.html');
return fs.existsSync(html) ? html : null;
}
export class DocViewProvider implements Disposable {
private subscriptions: Disposable[] = [];
private currentURL: string | undefined = undefined;
private backstack: string[] = [];
private forwardstack: string[] = [];
constructor(private staticServer?: StaticServer) {
this.subscriptions.push(
commands.registerCommand('lean.openDocView', (url) => this.open(url)),
commands.registerCommand('lean.backDocView', () => this.back()),
commands.registerCommand('lean.forwardDocView', () => this.forward()),
commands.registerCommand('lean.openTryIt', (code) => this.tryIt(code)),
commands.registerCommand('lean.openExample', (file) => this.example(file)),
);
void this.offerToOpenProjectDocumentation();
}
private async offerToOpenProjectDocumentation() {
if (!workspace.rootPath) return
if (!fs.existsSync(join(workspace.rootPath, 'leanpkg.toml'))) return;
const projDoc = findProjectDocumentation();
if (!projDoc) return;
await this.open(Uri.file(projDoc).toString());
}
private async tryIt(code: string) {
const doc = await workspace.openTextDocument({language: 'lean', content: code});
const editor = await window.showTextDocument(doc, ViewColumn.One);
}
private async example(file: string) {
const doc = await workspace.openTextDocument(Uri.parse(file));
await window.showTextDocument(doc, ViewColumn.One);
}
private webview?: WebviewPanel;
private getWebview(): WebviewPanel {
if (!this.webview) {
const options: WebviewOptions & WebviewPanelOptions = {
enableFindWidget: true,
enableScripts: true,
enableCommandUris: true,
retainContextWhenHidden: true,
};
let closed = false;
this.webview = window.createWebviewPanel('lean', 'Lean Documentation',
{ viewColumn: 3, preserveFocus: true }, options);
this.webview.onDidDispose(() => { closed = true; this.webview = null; });
let first = true;
this.webview.onDidChangeViewState(async () => {
if (first && !closed) {
first = false;
// super hacky way to show both infoview and docview in a split
await commands.executeCommand('workbench.action.focusRightGroup');
await commands.executeCommand('workbench.action.moveEditorToBelowGroup');
}
});
}
return this.webview;
}
async fetch(url?: string): Promise<string> {
if (url) {
const uri = Uri.parse(url);
if (uri.scheme === 'file') {
if (uri.fsPath.endsWith('.html')) {
return fs.readFileSync(uri.fsPath).toString();
}
} else {
const {data, headers} = await axios.get<string>(url);
if (('' + headers['content-type']).startsWith('text/html')) {
return data;
}
}
const $ = cheerio.load('<p>');
$('p').text('Unsupported file. ')
.append($('<a>').attr('href', url).attr('alwaysExternal', 'true')
.text('Open in browser instead.'));
return $.html();
} else {
const $ = cheerio.load('<body>');
const body = $('body');
const html = findProjectDocumentation();
if (html) {
body.append($('<p>').append($('<a>').attr('href', Uri.file(html).toString())
.text('Open documentation of current project')));
}
const books = {
'Theorem Proving in Lean':
'https://leanprover.github.io/theorem_proving_in_lean/',
'Reference Manual': 'https://leanprover.github.io/reference/',
'Mathematics in Lean': 'https://avigad.github.io/mathematics_in_lean/',
'Logic and Proof': 'https://leanprover.github.io/logic_and_proof/',
};
for (const book of Object.getOwnPropertyNames(books)) {
body.append($('<p>').append($('<a>').attr('href', books[book]).text(book)));
}
return $.html();
}
}
private mkRelativeUrl(relative: string, base: string): string {
const uri = new URL(relative, base);
if (uri.protocol === 'file:') {
if (new URL(base).protocol !== 'file:') {
return '';
}
const path = Uri.parse(uri.toString()).fsPath;
if (this.staticServer) {
// workaround for https://github.com/microsoft/vscode/issues/89038
return this.staticServer.mkUri(path);
} else {
return this.webview.webview.asWebviewUri(Uri.parse(uri.toString())).toString();
}
} else {
return uri.toString();
}
}
async setHtml(): Promise<void> {
const {webview} = this.getWebview();
const url = this.currentURL;
let $: cheerio.Root;
try {
$ = cheerio.load(await this.fetch(url));
} catch (e) {
$ = cheerio.load('<pre>');
$('pre').text(e.toString());
}
for (const style of $('link[rel=stylesheet]').get()) {
style.attribs.href = this.mkRelativeUrl(style.attribs.href, url);
}
for (const script of $('script[src]').get()) {
script.attribs.src = this.mkRelativeUrl(script.attribs.src, url);
}
for (const link of $('a[href]').get()) {
const tryItMatch = link.attribs.href.match(/\/(?:live|lean-web-editor)\/.*#code=(.*)/);
if (link.attribs.href.startsWith('#')) {
// keep relative links
} else if (link.attribs.alwaysExternal) {
// keep links with alwaysExternal attribute
} else if (link.attribs.tryitfile) {
link.attribs.title = link.attribs.title || 'Open code block (in existing file)';
link.attribs.href = mkCommandUri('lean.openExample', new URL(link.attribs.tryitfile, url).toString());
} else if (tryItMatch) {
const code = decodeURIComponent(tryItMatch[1]);
link.attribs.title = link.attribs.title || 'Open code block in new editor';
link.attribs.href = mkCommandUri('lean.openTryIt', code);
} else {
const hrefUrl = new URL(link.attribs.href, url);
const isExternal = url && new URL(url).origin !== hrefUrl.origin;
if (!isExternal) {
link.attribs.title = link.attribs.title || link.attribs.href;
link.attribs.href = mkCommandUri('lean.openDocView', hrefUrl.toString());
}
}
}
// javascript search doesn't work
$('.sphinxsidebar #searchbox').remove();
const nav = $('<nav>');
nav.css('width', '100vw');
nav.css('position', 'fixed');
nav.css('top', '0');
nav.css('right', '0');
nav.css('text-align', 'right');
nav.css('z-index', '100');
nav.prependTo($('body'));
const navDiv = $('<span>');
navDiv.css('padding', '4px');
navDiv.css('padding-right', '20px');
navDiv.css('z-index', '100');
navDiv.css('background-color', 'var(--vscode-tab-activeBackground)');
nav.append(navDiv);
const fontSize = workspace.getConfiguration('editor').get('fontSize') + 'px';
const mkLink = (command: string, title: string, text: string) => $('<a>')
.attr('title', title)
.attr('href', mkCommandUri(command))
.css('color', 'var(--vscode-tab-activeForeground)')
.css('font-family', 'sans-serif')
.css('font-size', fontSize)
.css('margin-left', '1em')
.css('text-decoration', 'none')
.text(text);
navDiv.append(mkLink('lean.backDocView', 'back', '⬅ back'));
navDiv.append(mkLink('lean.forwardDocView', 'forward', 'forward ➡'));
$('nav+*').css('margin-top','3em');
webview.html = $.html();
}
/** Called by the user clicking a link. */
async open(url?: string): Promise<void> {
if (url) {
this.backstack.push(this.currentURL);
this.forwardstack = [];
}
this.currentURL = url;
await this.setHtml();
}
async back(): Promise<void> {
if (this.backstack.length === 0) {return;}
this.forwardstack.push(this.currentURL);
this.currentURL = this.backstack.pop();
await this.setHtml();
}
async forward(): Promise<void> {
if (this.forwardstack.length === 0) {return;}
this.backstack.push(this.currentURL);
this.currentURL = this.forwardstack.pop();
await this.setHtml();
}
dispose(): void {
for (const s of this.subscriptions) { s.dispose(); }
}
}