All files / app/assets/javascripts/content_editor/services markdown_sourcemap.js

96.15% Statements 25/26
83.33% Branches 10/12
100% Functions 3/3
100% Lines 23/23

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    62x 22x   22x 19x     3x     62x 18x 18x 18x   18x           62x 36x   18x 18x 18x 18x   18x   18x 35x 18x   17x       17x   1x      
import { isString } from 'lodash';
 
export const getFullSource = (element) => {
  const commentNode = element.ownerDocument.body.lastChild;
 
  if (commentNode?.nodeName === '#comment' && isString(commentNode.textContent)) {
    return commentNode.textContent.split('\n');
  }
 
  return [];
};
 
const getRangeFromSourcePos = (sourcePos) => {
  const [start, end] = sourcePos.split('-');
  const [startRow, startCol] = start.split(':');
  const [endRow, endCol] = end.split(':');
 
  return {
    start: { row: Math.max(0, Number(startRow) - 1), col: Math.max(0, Number(startCol) - 1) },
    end: { row: Math.max(0, Number(endRow) - 1), col: Math.max(0, Number(endCol) - 1) },
  };
};
 
export const getMarkdownSource = (element) => {
  if (!element.dataset.sourcepos) return undefined;
 
  try {
    const source = getFullSource(element);
    const range = getRangeFromSourcePos(element.dataset.sourcepos);
    let elSource = '';
 
    Iif (!source.length) return undefined;
 
    for (let i = range.start.row; i <= range.end.row; i += 1) {
      if (i === range.start.row) {
        elSource += source[i].substring(range.start.col);
      } else {
        elSource += `\n${source[i]}` || '';
      }
    }
 
    return elSource.trim();
  } catch {
    return undefined;
  }
};