-
Notifications
You must be signed in to change notification settings - Fork 118
/
documentation_renderer.dart
352 lines (320 loc) · 7.42 KB
/
documentation_renderer.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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright (c) 2019, 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.
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' show parseFragment;
import 'package:markdown/markdown.dart' as md;
abstract class DocumentationRenderer {
DocumentationRenderResult render(
List<md.Node> nodes, {
required bool processFullDocs,
required bool sanitizeHtml,
});
}
class DocumentationRendererHtml implements DocumentationRenderer {
const DocumentationRendererHtml();
@override
DocumentationRenderResult render(
List<md.Node> nodes, {
required bool processFullDocs,
required bool sanitizeHtml,
}) {
if (nodes.isEmpty) {
return DocumentationRenderResult.empty;
}
var rawHtml = md.HtmlRenderer().render(nodes);
var asHtmlFragment = parseFragment(rawHtml);
for (var pre in asHtmlFragment.querySelectorAll('pre')) {
if (pre.children.length > 1 && pre.children.first.localName != 'code') {
continue;
}
if (pre.children.isNotEmpty && pre.children.first.localName == 'code') {
var code = pre.children.first;
pre.classes
.addAll(code.classes.where((name) => name.startsWith('language-')));
}
var specifiesLanguage = pre.classes.isNotEmpty;
// Assume the user intended Dart if there are no other classes present.
if (!specifiesLanguage) pre.classes.add('language-dart');
}
if (sanitizeHtml) {
_sanitize(asHtmlFragment);
}
var asHtml = '';
if (processFullDocs) {
// `trim` fixes an issue with line ending differences between Mac and
// Windows.
asHtml = asHtmlFragment.outerHtml.trim();
}
var asOneLiner = asHtmlFragment.children.isEmpty
? ''
: asHtmlFragment.children.first.innerHtml;
return DocumentationRenderResult(asHtml: asHtml, asOneLiner: asOneLiner);
}
}
class DocumentationRenderResult {
static const empty = DocumentationRenderResult(asHtml: '', asOneLiner: '');
final String asHtml;
final String asOneLiner;
const DocumentationRenderResult(
{required this.asHtml, required this.asOneLiner});
}
bool _allowClassName(String className) =>
className == 'deprecated' ||
className.startsWith('language-') ||
className == 'markdown-alert' ||
className.startsWith('markdown-alert-');
Iterable<String> _addLinkRel(String uriString) {
final uri = Uri.tryParse(uriString);
if (uri != null && uri.host.isNotEmpty) {
// TODO(jonasfj): Consider allowing non-ugc links for trusted sites.
return const ['ugc'];
}
return const [];
}
void _sanitize(dom.Node node) {
if (node is dom.Element) {
final tagName = node.localName!.toUpperCase();
if (!_allowedElements.contains(tagName)) {
node.remove();
return;
}
node.attributes.removeWhere((k, v) {
final attrName = k.toString();
if (attrName == 'class') {
node.classes.removeWhere((cn) => !_allowClassName(cn));
return node.classes.isEmpty;
}
return !_isAttributeAllowed(tagName, attrName, v);
});
if (tagName == 'A') {
final href = node.attributes['href'];
if (href != null) {
final rels = _addLinkRel(href);
if (rels.isNotEmpty) {
node.attributes['rel'] = rels.join(' ');
}
}
}
}
if (node.hasChildNodes()) {
// doing it in reverse order, because we could otherwise skip one, when a
// node is removed...
for (var i = node.nodes.length - 1; i >= 0; i--) {
_sanitize(node.nodes[i]);
}
}
}
bool _isAttributeAllowed(String tagName, String attrName, String value) {
if (_alwaysAllowedAttributes.contains(attrName)) return true;
// Special validators for special attributes on special tags (href/src/cite)
final attributeValidators = _elementAttributeValidators[tagName];
if (attributeValidators == null) {
return false;
}
final validator = attributeValidators[attrName];
if (validator == null) {
return false;
}
return validator(value);
}
// Inspired by the set of HTML tags allowed in GFM.
final _allowedElements = <String>{
'H1',
'H2',
'H3',
'H4',
'H5',
'H6',
'H7',
'H8',
'BR',
'B',
'I',
'STRONG',
'EM',
'A',
'PRE',
'CODE',
'IMG',
'TT',
'DIV',
'INS',
'DEL',
'SUP',
'SUB',
'P',
'OL',
'UL',
'TABLE',
'THEAD',
'TBODY',
'TFOOT',
'BLOCKQUOTE',
'DL',
'DT',
'DD',
'KBD',
'Q',
'SAMP',
'VAR',
'HR',
'RUBY',
'RT',
'RP',
'LI',
'TR',
'TD',
'TH',
'S',
'STRIKE',
'SUMMARY',
'DETAILS',
'CAPTION',
'FIGURE',
'FIGCAPTION',
'ABBR',
'BDO',
'CITE',
'DFN',
'MARK',
'SMALL',
'SPAN',
'TIME',
'WBR',
};
// Inspired by the set of HTML attributes allowed in GFM.
final _alwaysAllowedAttributes = <String>{
'abbr',
'accept',
'accept-charset',
'accesskey',
'action',
'align',
'alt',
'aria-describedby',
'aria-hidden',
'aria-label',
'aria-labelledby',
'axis',
'border',
'cellpadding',
'cellspacing',
'char',
'charoff',
'charset',
'checked',
'clear',
'cols',
'colspan',
'color',
'compact',
'coords',
'datetime',
'dir',
'disabled',
'enctype',
'for',
'frame',
'headers',
'height',
'hreflang',
'hspace',
'ismap',
'label',
'lang',
'maxlength',
'media',
'method',
'multiple',
'name',
'nohref',
'noshade',
'nowrap',
'open',
'prompt',
'readonly',
'rel',
'rev',
'rows',
'rowspan',
'rules',
'scope',
'selected',
'shape',
'size',
'span',
'start',
'summary',
'tabindex',
'target',
'title',
'type',
'usemap',
'valign',
'value',
'vspace',
'width',
'itemprop',
};
bool _alwaysAllowed(String _) => true;
bool _validLink(String url) {
try {
final uri = Uri.parse(url);
return uri.isScheme('https') ||
uri.isScheme('http') ||
uri.isScheme('mailto') ||
!uri.hasScheme;
} on FormatException {
return false;
}
}
bool _validUrl(String url) {
try {
final uri = Uri.parse(url);
return uri.isScheme('https') || uri.isScheme('http') || !uri.hasScheme;
} on FormatException {
return false;
}
}
final _citeAttributeValidator = <String, bool Function(String)>{
'cite': _validUrl,
};
/// Allow the `id` attribute for `h1`, `h2`, ... `h6`.
final _headingAttributeValidator = <String, bool Function(String)>{
'id': (id) {
// This id property is generated by package:markdown in:
// https://github.com/dart-lang/markdown/blob/ecbffa9bf9109d490b9388e9cb1f2bb801aee63c/lib/src/block_syntaxes/block_syntax.dart#L57-L63
// Cannot contain anything but a-z0-9_-
if (id.contains(RegExp('[^a-z0-9_-]'))) {
return false;
}
return true;
},
};
final _elementAttributeValidators =
<String, Map<String, bool Function(String)>>{
'A': {
'href': _validLink,
},
'IMG': {
'src': _validUrl,
'longdesc': _validUrl,
},
'DIV': {
'itemscope': _alwaysAllowed,
'itemtype': _alwaysAllowed,
},
'BLOCKQUOTE': _citeAttributeValidator,
'DEL': _citeAttributeValidator,
'INS': _citeAttributeValidator,
'Q': _citeAttributeValidator,
'H1': _headingAttributeValidator,
'H2': _headingAttributeValidator,
'H3': _headingAttributeValidator,
'H4': _headingAttributeValidator,
'H5': _headingAttributeValidator,
'H6': _headingAttributeValidator,
'H7': _headingAttributeValidator,
'H8': _headingAttributeValidator,
};