summarize.js 2.2 KB

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