get_headings.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import { INumberingDictionary } from '../../utils/numbering_dictionary';
  4. import { INumberedHeading } from '../../utils/headings';
  5. import { generateNumbering } from '../../utils/generate_numbering';
  6. import { parseHeading } from '../../utils/parse_heading';
  7. /**
  8. * Returns a "click" handler.
  9. *
  10. * @private
  11. * @param line - line number
  12. * @returns "click" handler
  13. */
  14. type onClickFactory = (line: number) => () => void;
  15. /**
  16. * Parses a provided string and returns a list of headings.
  17. *
  18. * @private
  19. * @param text - input text
  20. * @param onClick - callback which returns a "click" handler
  21. * @param dict - numbering dictionary
  22. * @returns list of headings
  23. */
  24. function getHeadings(
  25. text: string,
  26. onClick: onClickFactory,
  27. dict: INumberingDictionary
  28. ): INumberedHeading[] {
  29. // Split the text into lines:
  30. const lines = text.split('\n');
  31. // Iterate over the lines to get the header level and text for each line:
  32. let headings: INumberedHeading[] = [];
  33. let FLG;
  34. for (let i = 0; i < lines.length; i++) {
  35. let line = lines[i];
  36. // Don't check for Markdown headings if in a code block:
  37. if (line.indexOf('```') === 0) {
  38. FLG = !FLG;
  39. }
  40. if (FLG) {
  41. continue;
  42. }
  43. line += lines[i + 1] ? '\n' + lines[i + 1] : '';
  44. const heading = parseHeading(line); // append the next line to capture alternative style Markdown headings
  45. if (heading) {
  46. headings.push({
  47. text: heading.text,
  48. numbering: generateNumbering(dict, heading.level),
  49. level: heading.level,
  50. onClick: onClick(i)
  51. });
  52. }
  53. }
  54. return headings;
  55. }
  56. /**
  57. * Exports.
  58. */
  59. export { getHeadings };