All files / src/sections section.ts

100% Statements 69/69
100% Branches 18/18
100% Functions 7/7
100% Lines 69/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 701x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 41x 41x 122x 122x 98x 98x 98x 98x 98x 122x 122x 18x 18x 18x 18x 122x 122x 122x 122x 122x 122x 122x 122x 122x 122x 88x 88x 122x 1x 1x 12x 12x 12x 12x 8x 4x 4x 4x 4x 4x 4x 4x 4x  
import { HeadingLevel } from '../elements/heading.js';
 
export interface DocumentSectionOptions {
  title: string;
  parent?: DocumentSection;
  subSections?: Array<DocumentSection>;
}
 
/**
 * Represents a markdown document section.
 */
export abstract class DocumentSection {
  private _subSections: Array<DocumentSection> = [];
 
  title: string;
 
  parent: DocumentSection | undefined;
 
  constructor(options: DocumentSectionOptions) {
    this.title = options.title;
    this.parent = options.parent;
    this.parent?._subSections.push(this);
    options.subSections?.forEach((section) => this.addSubSection(section));
  }
 
  get subSections(): ReadonlyArray<DocumentSection> {
    return this._subSections;
  }
 
  get headingLevel(): HeadingLevel {
    const rootHeadingLevel = 2;
    const maxHeadingLevel = 6;
    const level = this.parent ? this.parent.headingLevel + 1 : rootHeadingLevel;
    return (level > maxHeadingLevel ? maxHeadingLevel : level) as HeadingLevel;
  }
 
  addSubSection(section: DocumentSection) {
    section.parent = this;
    this._subSections.push(section);
    return this;
  }
 
  /**
   * Transform the section data into an array of strings
   */
  protected abstract synthesizeContent(): Array<string>;
 
  /**
   * Synthesize the section data so it can be written to the readme
   */
  public synthesize() {
    return this.synthesizeContent().join('\n');
  }
}
 
export function tryFindSection<S extends DocumentSection>(
  sections: ReadonlyArray<S>,
  path: Array<string>,
): S | undefined {
  for (const section of sections) {
    if (section.title === path[0] && path.length === 1) {
      return section;
    }
 
    return tryFindSection(section.subSections, path.slice(1)) as S;
  }
 
  return undefined;
}