UNPKG

2.33 kBJavaScriptView Raw
1/**
2 * @overview This plugin creates a summary tag, if missing, from the first sentence in the
3 * description.
4 * @module plugins/summarize
5 * @author Mads Bondo Dydensborg <mbd@dbc.dk>
6 */
7'use strict';
8
9exports.handlers = {
10 /**
11 * Autogenerate summaries, if missing, from the description, if present.
12 */
13 newDoclet: function(e) {
14 var endTag;
15 var tags;
16 var stack;
17
18 // If the summary is missing, grab the first sentence from the description
19 // and use that.
20 if (e.doclet && !e.doclet.summary && e.doclet.description) {
21 // The summary may end with `.$`, `. `, or `.<` (a period followed by an HTML tag).
22 e.doclet.summary = e.doclet.description.split(/\.$|\.\s|\.</)[0];
23 // Append `.` as it was removed in both cases, or is possibly missing.
24 e.doclet.summary += '.';
25
26 // This is an excerpt of something that is possibly HTML.
27 // Balance it using a stack. Assume it was initially balanced.
28 tags = e.doclet.summary.match(/<[^>]+>/g) || [];
29 stack = [];
30
31 tags.forEach(function(tag) {
32 var idx = tag.indexOf('/');
33
34 if (idx === -1) {
35 // start tag -- push onto the stack
36 stack.push(tag);
37 } else if (idx === 1) {
38 // end tag -- pop off of the stack
39 stack.pop();
40 }
41
42 // otherwise, it's a self-closing tag; don't modify the stack
43 });
44
45 // stack should now contain only the start tags that lack end tags,
46 // with the most deeply nested start tag at the top
47 while (stack.length > 0) {
48 // pop the unmatched tag off the stack
49 endTag = stack.pop();
50 // get just the tag name
51 endTag = endTag.substring(1, endTag.search(/[ >]/));
52 // append the end tag
53 e.doclet.summary += '</' + endTag + '>';
54 }
55
56 // and, finally, if the summary starts and ends with a <p> tag, remove it; let the
57 // template decide whether to wrap the summary in a <p> tag
58 e.doclet.summary = e.doclet.summary.replace(/^<p>(.*)<\/p>$/i, '$1');
59 }
60 }
61};