-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconvert.js
516 lines (444 loc) · 17.1 KB
/
convert.js
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
'use strict';
var Convert = (function () {
// Supported tags are taken from https://msdn.microsoft.com/en-us/library/5ast78ax.aspx
// Note that <include> and <inheritdoc> tags are not supported!
var processorMap = {
'doc': processDoc,
'assembly': processAssembly,
'members': processMembers,
'member': processMember,
'summary': processSummary,
'value': processValue,
'typeparam': processTypeparam,
'remarks': processRemarks,
'para': processPara,
'param': processParam,
'returns': processReturns,
'example': processExample,
'permission': processPermission,
'exception': processException,
'list': processList,
'code': processCode,
'seealso': processSeealso,
'paramref': processParamref,
'typeparamref': processTypeparamref,
'see': processSee,
'c': processC,
'#text': processText
};
return {
markdownToHtml: function (markdown) {
// We use a vendor provided markdown to html parser called marked.
// Ref: https://github.com/chjj/marked
return marked(markdown);
},
vsdocToMarkdown: function (vsdoc) {
var parser = new DOMParser();
var xml = parser.parseFromString(vsdoc, 'text/xml');
var ctx = {
markdown: [], // Output will be appended here.
paramTypes: {}, // Used to map method signature names to types.
nodeStack: [], // Used to keep track of current position in the node tree.
types: [], // Table of contents will be generated based on types in assembly.
indices: {} // Keeps track of indices of different document parts to later inject content.
};
stripEmptyTextNodes(xml);
process(ctx, xml);
// Attach table of contents before members.
ctx.markdown.splice(ctx.indices.members, 0, getTableOfContents(ctx));
return ctx.markdown.join('');
}
};
/*********************/
/* 1. Tag processors */
/*********************/
function process(ctx, node) {
for (var i = 0; i < node.childNodes.length; i++) {
var childNode = node.childNodes[i];
ctx.previousNode = (i === 0) ? undefined : node.childNodes[i - 1].nodeName;
ctx.nextNode = (i === node.childNodes.length - 1) ? undefined : node.childNodes[i + 1].nodeName;
ctx.nodeStack.push(childNode.nodeName);
var processor = processorMap[childNode.nodeName];
if (processor) processor(ctx, childNode);
ctx.nodeStack.pop();
}
}
function processDoc(ctx, docNode) {
process(ctx, docNode);
}
function processAssembly(ctx, assemblyNode) {
var nameNode = findChildNode(assemblyNode, 'name');
ctx.markdown.push('# ');
ctx.markdown.push(nameNode.textContent);
ctx.markdown.push('\n');
}
function processMembers(ctx, membersNode) {
ctx.indices.members = ctx.markdown.length;
// 1. Extract type and name from members.
var childElements = [];
for (var i = 0; i < membersNode.childNodes.length; i++) {
var childNode = membersNode.childNodes[i];
if (childNode.nodeType === Node.ELEMENT_NODE) {
var childName = childNode.getAttribute('name');
childNode.type = childName.substring(0, 1);
childNode.name = sanitizeMarkdown(childName.substring(2));
childElements.push(childNode);
}
}
// 2. Sort members by their name.
childElements.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
// 3. Append sorted nodes back to their parent.
for (var i = 0; i < childElements.length; i++) {
membersNode.appendChild(childElements[i]);
}
process(ctx, membersNode);
}
function processMember(ctx, memberNode) {
var type = memberNode.type;
var name = memberNode.name;
if (type === 'T') {
ctx.namespace = name.substring(0, name.lastIndexOf('.'));
name = name.replace(ctx.namespace + '.', '');
ctx.typeName = name;
ctx.markdown.push('\n\n## ');
ctx.markdown.push(name);
ctx.markdown.push('\n');
ctx.types.push(name);
} else {
if (type === 'M') {
name = rearrangeParametersInContext(ctx, memberNode);
}
name = name.replace(ctx.namespace + '.' + ctx.typeName + '.', '');
if (name.indexOf('#ctor') >= 0) {
name = name.replace('#ctor', 'Constructor');
}
ctx.markdown.push('\n### ');
ctx.markdown.push(name);
ctx.markdown.push('\n');
}
process(ctx, memberNode);
}
function processSummary(ctx, summaryNode) {
ctx.markdown.push('\n');
process(ctx, summaryNode);
ctx.markdown.push('\n');
}
function processValue(ctx, valueNode) {
ctx.markdown.push('\n#### Value\n\n');
process(ctx, valueNode);
ctx.markdown.push('\n');
}
function processTypeparam(ctx, typeparamNode) {
var name = typeparamNode.getAttribute('name');
if (name) {
if (ctx.previousNode !== 'typeparam') {
ctx.markdown.push('\n#### Type Parameters\n\n');
}
ctx.markdown.push('- ');
ctx.markdown.push(name);
ctx.markdown.push(' - ');
process(ctx, typeparamNode);
ctx.markdown.push('\n');
}
}
function processParam(ctx, paramNode) {
var paramName = paramNode.getAttribute('name');
var paramType = ctx.paramTypes[paramName];
if (ctx.previousNode !== 'param') {
ctx.markdown.push('\n| Name | Description |\n');
ctx.markdown.push('| ---- | ----------- |\n');
}
ctx.markdown.push('| ');
ctx.markdown.push(paramName);
ctx.markdown.push(' | *');
if (paramType) {
ctx.markdown.push(paramType);
} else {
ctx.markdown.push('Unknown type');
}
ctx.markdown.push('*<br>');
process(ctx, paramNode);
ctx.markdown.push(' |\n');
}
function processReturns(ctx, returnsNode) {
ctx.markdown.push('\n#### Returns\n\n');
process(ctx, returnsNode);
ctx.markdown.push('\n');
}
function processRemarks(ctx, remarksNode) {
ctx.markdown.push('\n#### Remarks\n\n');
process(ctx, remarksNode);
ctx.markdown.push('\n');
}
function processExample(ctx, exampleNode) {
var exampleCode = tabsToSpaces(exampleNode.childNodes[0].nodeValue);
exampleCode = removeInitialLineFeed(exampleCode);
exampleCode = removeIndent(exampleCode);
ctx.markdown.push('\n#### Example\n\n');
ctx.markdown.push('\n```\n');
ctx.markdown.push(exampleCode);
ctx.markdown.push('\n```\n');
ctx.markdown.push('\n');
}
function processPermission(ctx, permissionNode) {
var cref = permissionNode.getAttribute('cref');
if (cref) {
if (ctx.previousNode !== 'permission') {
ctx.markdown.push('\n#### Permissions\n\n');
}
var permissionName = sanitizeMarkdown(cref.substring(2));
permissionName = permissionName.replace(ctx.namespace + '.', '');
ctx.markdown.push('- ');
ctx.markdown.push(permissionName);
ctx.markdown.push(': ')
process(ctx, permissionNode);
ctx.markdown.push('\n');
}
}
function processException(ctx, exceptionNode) {
var cref = exceptionNode.getAttribute('cref');
if (cref) {
var exName = sanitizeMarkdown(cref.substring(2));
exName = exName.replace(ctx.namespace + '.', '');
ctx.markdown.push('\n*');
ctx.markdown.push(exName);
ctx.markdown.push(':* ');
process(ctx, exceptionNode);
ctx.markdown.push('\n');
}
}
function processList(ctx, listNode) {
var type = listNode.getAttribute('type');
var newline = (ctx.nodeStack[ctx.nodeStack.length - 2] === 'param') ? '<br>' : '\n';
if (type) {
ctx.markdown.push(newline);
if (type === 'table') {
var listheaderElement = findChildNode(listNode, 'listheader');
var listheaderTermElements = findChildNodes(listheaderElement, 'term')
ctx.markdown.push('| ');
for (var i = 0; i < listheaderTermElements.length; i++) {
ctx.markdown.push(listheaderTermElements[i].textContent);
ctx.markdown.push(' | ');
}
ctx.markdown.push(newline);
itemElements = findChildNodes(listNode, 'item');
for (var i = 0; i < itemElements.length; i++) {
var itemTermElements = findChildNodes(itemElements[i], 'term');
ctx.markdown.push('| ');
for (var j = 0; j < itemTermElements.length; j++) {
process(ctx, itemTermElements[j])
ctx.markdown.push(' | ');
}
ctx.markdown.push(newline);
}
} else {
var prefixFn;
if (type === 'number') {
var counter = 1;
prefixFn = function() { return counter++ + '. '; };
} else { // Bullet.
prefixFn = function() { return '- '; };
}
var itemElements = findChildNodes(listNode, 'item');
for (var i = 0; i < itemElements.length; i++) {
var itemElement = itemElements[i];
ctx.markdown.push(prefixFn());
var termElement = findChildNode(itemElement, 'term');
if (termElement) {
process(ctx, termElement);
ctx.markdown.push(' - ');
}
var descriptionElement = findChildNode(itemElement, 'description');
if (descriptionElement) {
process(ctx, descriptionElement);
}
ctx.markdown.push(newline);
}
}
}
}
function processCode(ctx, codeNode) {
ctx.markdown.push('\n```\n');
ctx.markdown.push(codeNode.textContent);
ctx.markdown.push('\n```\n');
}
function processSeealso(ctx, seealsoNode) {
if (ctx.previousNode !== 'seealso') {
ctx.markdown.push('\n#### See also\n');
}
ctx.markdown.push('\n- ');
processSee(ctx, seealsoNode);
ctx.markdown.push('\n');
}
function processParamref(ctx, paramrefNode) {
var name = paramrefNode.getAttribute('name');
if (name) {
ctx.markdown.push(name);
}
}
function processTypeparamref(ctx, typeparamrefNode) {
var name = typeparamrefNode.getAttribute('name');
if (name) {
ctx.markdown.push(name);
}
}
function processSee(ctx, seeNode) {
var cref = seeNode.getAttribute('cref'); // For example: T:System.String
if (cref) {
var typeName = sanitizeMarkdown(cref.substring(2));
typeName = typeName.replace(ctx.namespace + '.', '');
ctx.markdown.push('<a href="#');
ctx.markdown.push(typeName.toLowerCase());
ctx.markdown.push('">')
ctx.markdown.push(typeName);
ctx.markdown.push('</a>');
} else {
var href = seeNode.getAttribute('href'); // For example: http://stackoverflow.com/
if (href) {
ctx.markdown.push('<a href="');
ctx.markdown.push(href);
ctx.markdown.push('">')
ctx.markdown.push(href);
ctx.markdown.push('</a>');
}
}
}
function processC(ctx, cNode) {
ctx.markdown.push('`');
ctx.markdown.push(cNode.textContent);
ctx.markdown.push('`');
}
function processText(ctx, textNode) {
if (!ctx.previousNode || ctx.previousNode === 'list' || ctx.previousNode === 'code') {
textNode.nodeValue = trimStart(textNode.nodeValue);
}
if (!ctx.nextNode) {
textNode.nodeValue = trimEnd(textNode.nodeValue);
}
ctx.markdown.push(textNode.nodeValue.replace(/\s+/g, ' '));
}
function processPara(ctx, paraNode) {
ctx.markdown.push('\n');
process(ctx, paraNode);
ctx.markdown.push('\n');
}
/****************/
/* 2. Utilities */
/****************/
function tabsToSpaces(input) {
return input.replace(/\t/g, ' ');
}
function removeInitialLineFeed(input) {
return input.replace(/^(?:\r?\n|\r)/, '');
}
function removeIndent(input) {
var indents = input.match(/^[^\S\n\r]*(?=\S)/gm);
if (!indents || !indents[0].length)
return input;
indents.sort(function(a, b) { return a.length - b.length; });
if (!indents[0].length)
return input;
return input.replace(new RegExp('^' + indents[0], 'gm'), '');
}
function rearrangeParametersInContext(ctx, memberNode) {
var methodPrototype = memberNode.name;
var matches = methodPrototype.match(/\((.*)\)/);
if (!matches) {
return methodPrototype;
}
var paramString = matches[1].replace(' ', '');
// Params are separated by commas. However, generic type params also use
// commas as a separator. In order to avoid an invalid split, we must
// not match commas within braces {}.
var matchCommasExceptForInBraces = /,(?![^\{]*\})/g;
var paramTypes = paramString.split(matchCommasExceptForInBraces);
if (paramTypes.length === 0) {
return methodPrototype;
}
var paramNodes = findChildNodes(memberNode, 'param');
if (paramNodes.length === 0) {
return methodPrototype;
}
var newParamString = '';
for (var i = 0; i < paramNodes.length; i++) {
var paramNode = paramNodes[i];
var paramName = paramNode.getAttribute('name');
var paramType = paramTypes[i];
newParamString += newParamString ? ', ' : '';
newParamString += paramName;
ctx.paramTypes[paramName] = paramType;
}
var newMethodPrototype = methodPrototype.replace(/\(.*\)/, '(' + newParamString + ')');
return newMethodPrototype;
}
function trimStart(value) {
return value.replace(/^\s+/, '');
}
function trimEnd(value) {
return value.replace(/\s+$/, '');
}
function sanitizeMarkdown(value) {
return value.replace(/`/g, '\\`');
}
function findChildNode(node, nodeName) {
var childNodes = findChildNodes(node, nodeName);
return childNodes ? childNodes[0] : undefined;
}
function findChildNodes(node, nodeName) {
var result = [];
if (node) {
for (var i = 0; i < node.childNodes.length; i++) {
var childNode = node.childNodes[i];
if (childNode.nodeName === nodeName) {
result = result || [];
result.push(childNode);
}
}
}
return result;
}
// Ref: http://stackoverflow.com/a/5817243/1466456
function stripEmptyTextNodes(node) {
var child, next;
switch (node.nodeType) {
case 3: // Text node
if (/^\s*$/.test(node.nodeValue)) {
node.parentNode.removeChild(node);
}
break;
case 1: // Element node
case 9: // Document node
child = node.firstChild;
while (child) {
next = child.nextSibling;
stripEmptyTextNodes(child);
child = next;
}
break;
}
}
function getTableOfContents(ctx) {
var numTypes = ctx.types.length;
var numTypesPerRow = 2;
var numRows = Math.ceil(numTypes / numTypesPerRow);
var tableOfContents = ['\n<table>\n<tbody>\n'];
for (var i = 0; i < numRows; i++) {
tableOfContents.push('<tr>\n');
for (var j = 0; j < numTypesPerRow; j++) {
var type = ctx.types[i*numTypesPerRow + j];
if (type) {
tableOfContents.push('<td><a href="#');
tableOfContents.push(type.toLowerCase());
tableOfContents.push('">');
tableOfContents.push(type);
tableOfContents.push('</a></td>\n');
}
}
tableOfContents.push('</tr>\n');
}
tableOfContents.push('</tbody>\n</table>\n');
return tableOfContents.join('');
}
})();