description.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { Markers } from '../../primitives.js';
  2. /**
  3. * Makes no changes to `spec.lines[].tokens` but joins them into `spec.description`
  4. * following given spacing srtategy
  5. * @param {Spacing} spacing tells how to handle the whitespace
  6. * @param {BlockMarkers} markers tells how to handle comment block delimitation
  7. */
  8. export default function descriptionTokenizer(spacing = 'compact', markers = Markers) {
  9. const join = getJoiner(spacing);
  10. return (spec) => {
  11. spec.description = join(spec.source, markers);
  12. return spec;
  13. };
  14. }
  15. export function getJoiner(spacing) {
  16. if (spacing === 'compact')
  17. return compactJoiner;
  18. if (spacing === 'preserve')
  19. return preserveJoiner;
  20. return spacing;
  21. }
  22. function compactJoiner(lines, markers = Markers) {
  23. return lines
  24. .map(({ tokens: { description } }) => description.trim())
  25. .filter((description) => description !== '')
  26. .join(' ');
  27. }
  28. const lineNo = (num, { tokens }, i) => tokens.type === '' ? num : i;
  29. const getDescription = ({ tokens }) => (tokens.delimiter === '' ? tokens.start : tokens.postDelimiter.slice(1)) +
  30. tokens.description;
  31. function preserveJoiner(lines, markers = Markers) {
  32. if (lines.length === 0)
  33. return '';
  34. // skip the opening line with no description
  35. if (lines[0].tokens.description === '' &&
  36. lines[0].tokens.delimiter === markers.start)
  37. lines = lines.slice(1);
  38. // skip the closing line with no description
  39. const lastLine = lines[lines.length - 1];
  40. if (lastLine !== undefined &&
  41. lastLine.tokens.description === '' &&
  42. lastLine.tokens.end.endsWith(markers.end))
  43. lines = lines.slice(0, -1);
  44. // description starts at the last line of type definition
  45. lines = lines.slice(lines.reduce(lineNo, 0));
  46. return lines.map(getDescription).join('\n');
  47. }