# All files / src/lib/markdown-it/highlight Highlighter.ts

100% Statements 13/13
100% Branches 4/4
100% Functions 4/4
100% Lines 13/13

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
    3822x

    22x

    3x
    3x

    4x
    4x
    4x

    7x

    7x
    10x
    10x

    7x

    7x

     import { collateAllIntervalsWithColors, splitCodeAndIndentation } from './helper';

    export class Highlighter {
      static highlightWholeLine(code: string, color?: string) {
        const style = color ? `style="background-color:${color};"` : 'class="highlighted"';
        return `<span ${style}>${code}\n</span>`;
      }

      static highlightWholeText(code: string, color?: string) {
        const style = color ? `style="background-color:${color};"` : 'class="highlighted"';
        const [indents, content] = splitCodeAndIndentation(code);
        return `<span>${indents}<span ${style}>${content}</span>\n</span>`;
      }

      static highlightPartOfText(
        code: string,
        boundsWithColors: Array<{ bounds: [number, number], color: string }>,
      ) {
        /*
        * Note: As part-of-text highlighting requires walking over the node of the generated
        * html by highlight.js, highlighting will be applied in NodeProcessor instead.
        * hl-data is used to pass over the bounds and colors.
        */
        const mergedBoundsWithColors = collateAllIntervalsWithColors(boundsWithColors);

        // Generate the hl-data string for all bounds and colors
        const dataStr = mergedBoundsWithColors.map(({ bounds, color }) => {
          const [start, end] = bounds; // each bound is an array of 2 integers
          return `${start}-${end}:${color}`; // include color for each bound
        }).join(',');

        const formattedCode = code.replace(/\t/g, '    '); // Convert tabs to 4 spaces by default

        // Wrap the code in a span with the hl-data attribute
        return `<span hl-data="${dataStr}">${formattedCode}\n</span>`;
      }
    }