forked from dart-lang/dart-pad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
documentation.dart
220 lines (177 loc) · 6.78 KB
/
documentation.dart
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
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library dartpad.documentation;
import 'dart:convert' as convert show htmlEscape;
import 'dart:html';
import 'dart:math' as math;
import 'package:markdown/markdown.dart' as markdown;
import 'context.dart';
import 'dart_pad.dart';
import 'editing/editor.dart';
import 'services/common.dart';
import 'services/dartservices.dart';
import 'src/util.dart';
import 'util/detect_flutter.dart';
class DocHandler {
static const Set<int> cursorKeys = {
KeyCode.LEFT,
KeyCode.RIGHT,
KeyCode.UP,
KeyCode.DOWN
};
final Editor _editor;
final ContextBase _sourceProvider;
final NodeValidator _htmlValidator = PermissiveNodeValidator();
int? _previousDocHash;
DocHandler(this._editor, this._sourceProvider);
void generateDoc(List<DivElement> docElements) {
if (docElements.isEmpty) {
return;
}
if (!_sourceProvider.isFocused) {
_previousDocHash = null;
for (final docPanel in docElements) {
docPanel.innerHtml = '';
}
return;
}
if (!_editor.hasFocus || _editor.document.selection.isNotEmpty) {
return;
}
final offset = _editor.document.indexFromPos(_editor.document.cursor);
final request = SourceRequest()..offset = offset;
if (_editor.completionActive) {
// If the completion popup is open we create a new source as if the
// completion popup was chosen, and ask for the documentation of that
// source.
request.source =
_sourceWithCompletionInserted(_sourceProvider.dartSource, offset);
} else {
request.source = _sourceProvider.dartSource;
}
dartServices
.document(request)
.timeout(serviceCallTimeout)
.then((DocumentResponse result) {
final hash = result.hashCode;
// If nothing has changed, don't need to parse Markdown and
// manipulate HTML again.
if (hash == _previousDocHash) {
return;
}
_previousDocHash = hash;
final docResult = _getHtmlTextFor(result);
final docType = 'type-${docResult.entityKind}';
for (final docPanel in docElements) {
docPanel.setInnerHtml(docResult.html, validator: _htmlValidator);
for (final a in docPanel.querySelectorAll('a')) {
if (a is AnchorElement) a.target = 'docs';
}
for (final h in docPanel.querySelectorAll('h1')) {
h.classes.add(docType);
}
}
});
}
String _sourceWithCompletionInserted(String source, int offset) {
final completionText = querySelector('.CodeMirror-hint-active')!.text!;
final lastSpace = source.substring(0, offset).lastIndexOf(' ') + 1;
final lastDot = source.substring(0, offset).lastIndexOf('.') + 1;
final insertOffset = math.max(lastSpace, lastDot);
return _sourceProvider.dartSource.substring(0, insertOffset) +
completionText +
_sourceProvider.dartSource.substring(offset);
}
_DocResult _getHtmlTextFor(DocumentResponse result) {
final info = result.info;
if (info['description'] == null && info['dartdoc'] == null) {
return _DocResult('');
}
final libraryName = info['libraryName'];
final kind = info['kind']!;
final hasDartdoc = info['dartdoc'] != null;
final isVariable = kind.contains('variable');
final apiLink = _dartApiLink(libraryName);
final propagatedType = info['propagatedType'];
final mdDocs = '''# `${info['description']}`\n\n
${hasDartdoc ? "${info['dartdoc']}\n\n" : ''}
${isVariable ? "$kind\n\n" : ''}
${(isVariable && propagatedType != null) ? "**Propagated type:** $propagatedType\n\n" : ''}
$apiLink\n\n''';
var htmlDocs = markdown.markdownToHtml(mdDocs,
inlineSyntaxes: [InlineBracketsColon(), InlineBrackets()]);
// Append a 'launch' icon to the 'Open library docs' link.
htmlDocs = htmlDocs.replaceAll('library docs</a>',
"library docs <span class='launch-icon'></span></a>");
return _DocResult(htmlDocs, kind.replaceAll(' ', '_'));
}
String _dartApiLink(String? libraryName) {
if (libraryName == null ||
libraryName.isEmpty ||
libraryName == 'main.dart') {
return '';
}
final usingFlutter = hasFlutterContent(_sourceProvider.dartSource);
final isDartLibrary = libraryName.contains('dart:');
// Only can link to library docs for dart libraries or `package:flutter`.
if (isDartLibrary || usingFlutter) {
if (usingFlutter) {
final splitFlutter = libraryName.split('/');
if (splitFlutter[0] == 'package:flutter') {
splitFlutter.removeAt(0);
// Find library name, either after package declaration or `src`.
libraryName = splitFlutter
.firstWhere((element) => element != 'src')
.replaceAll('.dart', '');
} else if (!isDartLibrary) {
// If it's not a Flutter or Dart library, return just the name.
return libraryName;
}
}
final apiLink = StringBuffer('[Open library docs](');
if (usingFlutter) {
apiLink.write('https://api.flutter.dev/flutter');
} else {
apiLink.write('https://api.dart.dev/stable');
}
libraryName = libraryName.replaceAll(':', '-');
apiLink.write('/$libraryName/$libraryName-library.html)');
return apiLink.toString();
}
return libraryName;
}
}
class _DocResult {
final String html;
final String? entityKind;
_DocResult(this.html, [this.entityKind]);
}
class InlineBracketsColon extends markdown.InlineSyntax {
InlineBracketsColon() : super(r'\[:\s?((?:.|\n)*?)\s?:\]');
String htmlEscape(String text) => convert.htmlEscape.convert(text);
@override
bool onMatch(markdown.InlineParser parser, Match match) {
final element = markdown.Element.text('code', htmlEscape(match[1]!));
parser.addNode(element);
return true;
}
}
// TODO: [someCodeReference] should be converted to for example
// https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:core.someReference
// for now it gets converted <code>someCodeReference</code>
class InlineBrackets extends markdown.InlineSyntax {
// This matches URL text in the documentation, with a negative filter
// to detect if it is followed by a URL to prevent e.g.
// [text] (http://www.example.com) getting turned into
// <code>text</code> (http://www.example.com)
InlineBrackets() : super(r'\[\s?((?:.|\n)*?)\s?\](?!\s?\()');
String htmlEscape(String text) => convert.htmlEscape.convert(text);
@override
bool onMatch(markdown.InlineParser parser, Match match) {
final element =
markdown.Element.text('code', '<em>${htmlEscape(match[1]!)}</em>');
parser.addNode(element);
return true;
}
}