All files / src/components/blocks/markdown/parser domToMarkdown.ts

65.78% Statements 125/190
56.94% Branches 82/144
69.23% Functions 9/13
65.78% Lines 125/190

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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387              7x     7x 7x                                     7x                                                                                                                         74x   74x 74x   74x 112x     112x       112x 53x 53x 53x   53x 53x 417x 417x         417x         417x                   1x 1x 1x     417x 417x 417x   53x     53x       59x     59x 59x         74x     74x       74x     7x     80x 80x 7x   73x               80x       80x   80x 80x     95x 95x               18x       18x 18x 18x 18x 18x           4x 4x 4x     4x       4x     4x     4x     4x     4x       4x     4x         80x   80x 80x 7x     7x   73x           73x   1x 1x 1x 1x 72x 1x 71x               29x   1x 1x     29x 42x 3x 3x   39x 2x 2x   37x 4x 4x   33x 2x 2x   31x 10x 10x 10x 21x       21x 16x 16x 16x 11x   16x 16x 16x     16x 16x 15x   1x     16x   5x 3x 1x   3x 3x 3x 3x 2x 2x                             80x                         7x 21x 21x             21x   21x                
/*
 * The coLAB project
 * Copyright (C) 2021-2023 AlbaSim, MEI, HEIG-VD, HES-SO
 *
 * Licensed under the MIT License
 */
 
import { getLogger } from '../../../../logger';
import { HeadingLevel } from './markdownToDom';
 
const logger = getLogger('Dom2Markdown2Parser');
logger.setLevel(4);
 
interface DomParserContext {
  current: number;
  anchor: number | undefined;
  focus: number | undefined;
  heading?: boolean;
  em?: boolean;
  strong?: boolean;
  strike?: boolean;
  u?: boolean;
  list: ('ul' | 'ol')[];
}
 
export interface Position {
  element: Node;
  offset: number;
}
 
export function escapeText(text: string | null): string {
  Iif (!text) {
    return '';
  }
 
  const result: string[] = [];
  for (const char of text) {
    Iif (
      char === '*' ||
      char === '_' ||
      char === '~' ||
      char == '/' ||
      char === '[' ||
      char === ']' ||
      char === '(' ||
      char === ')'
    ) {
      result.push('\\');
    }
 
    result.push(char);
  }
  return result.join('');
}
 
function convertTable(table: Element) {
  const md: string[] = [];
  const line: string[] = [];
 
  function processElement(element: Element) {
    element.childNodes.forEach(child => {
      Iif (child instanceof Element) {
        const tag = child.tagName;
        if (tag === 'TH') {
          line.push(`*${child.textContent ?? ''}*`);
        } else if (tag === 'TD') {
          line.push(child.textContent ?? '');
        } else if (tag === 'TR') {
          processElement(child);
 
          Iif (md.length > 0) {
            md.push('\n');
          }
          md.push(line.join(' '));
          line.length = 0;
        } else {
          processElement(child);
        }
      }
    });
  }
  processElement(table);
 
  return md.join('');
}
 
function processChildren(
  element: Element,
  selection: Selection | null,
  context: DomParserContext,
): string {
  const md: string[] = [];
 
  const anchorElemOffset = selection?.anchorNode === element ? selection.anchorOffset : undefined;
  const focusElemOffset = selection?.focusNode === element ? selection.focusOffset : undefined;
 
  element.childNodes.forEach((node, nodeIndex) => {
    Iif (anchorElemOffset === nodeIndex) {
      context.anchor = context.current;
    }
    Iif (focusElemOffset === nodeIndex) {
      context.focus = context.current;
    }
 
    if (node instanceof Text) {
      if (node.textContent) {
        const anchor = selection?.anchorNode === node ? selection.anchorOffset : undefined;
        const focus = selection?.focusNode === node ? selection.focusOffset : undefined;
 
        let i = 0;
        for (const char of node.textContent) {
          logger.trace('Range | anchor | focus: ', i, context, anchor, focus);
          Iif (anchor === i) {
            context.anchor = context.current;
            logger.trace('Reach Anchor: ', i, context, anchor, focus);
          }
 
          Iif (focus === i) {
            context.focus = context.current;
            logger.trace('Reach Focus: ', i, context, anchor, focus);
          }
 
          if (
            char === '*' ||
            char === '_' ||
            char === '~' ||
            char == '/' ||
            char === '[' ||
            char === ']' ||
            char === '(' ||
            char === ')'
          ) {
            context.current++;
            logger.trace('Escaped: ', i, context, anchor, focus);
            md.push('\\');
          }
 
          context.current++;
          md.push(char);
          i++;
        }
        Iif (anchor === i) {
          context.anchor = context.current;
        }
        Iif (focus === i) {
          context.focus = context.current;
        }
      }
    } else if (node instanceof Element) {
      // detect and skip emptiness (<p><br/></p> is quite normal to reprensent one single empty line)
      // if last child is a <BR />, it should be ignored
      if (node != element.lastChild || node instanceof HTMLBRElement === false) {
        md.push(_domToMarkdown(node, selection, context));
      }
    }
  });
 
  Iif (anchorElemOffset === element.childNodes.length) {
    context.anchor = context.current;
  }
  Iif (focusElemOffset === element.childNodes.length) {
    context.focus = context.current;
  }
 
  return md.join('');
}
 
const tagHeaderRegex = /^H([1-5])$/;
 
function isHeader(tag: string): number | undefined {
  const result = tagHeaderRegex.exec(tag);
  if (result != null && result.length == 2) {
    return +result[1]! as HeadingLevel;
  }
  return undefined;
}
 
function _domToMarkdown(
  elementArg: Element | null,
  selection: Selection | null,
  context: DomParserContext,
): string {
  Iif (elementArg == null) {
    return '';
  }
 
  const element = elementArg;
 
  const md: string[] = [];
  const tag = element.tagName;
 
  function push(content: string) {
    md.push(content);
    context.current += content.length;
  }
 
  function process(
    localCtx: 'em' | 'u' | 'strike' | 'strong' | 'heading',
    start: string,
    stop: string,
  ) {
    Iif (context[localCtx]) {
      // local context already active
      md.push(processChildren(element, selection, context));
    } else {
      push(start);
      context[localCtx] = true;
      md.push(processChildren(element, selection, context));
      context[localCtx] = false;
      push(stop);
    }
  }
 
  function processUnformatable(element: Element, escape: boolean = false) {
    // Consume the whole text as-is and detect selection
    const children = [...element.childNodes];
    children.forEach((child, index) => {
      Iif (element === selection?.anchorNode && selection.anchorOffset === index) {
        context.anchor = context.current;
      }
      Iif (child === selection?.anchorNode) {
        context.anchor = context.current + selection.anchorOffset;
      }
 
      Iif (element === selection?.focusNode && selection.focusOffset === index) {
        context.focus = context.current;
      }
      Iif (child === selection?.focusNode) {
        context.focus = context.current + selection.focusOffset;
      }
      Iif (escape) {
        push(escapeText(child.textContent || ''));
      } else {
        push(child.textContent || '');
      }
 
      Iif (child instanceof HTMLBRElement) {
        push('\n');
      }
    });
    Iif (element === selection?.anchorNode && selection.anchorOffset === children.length) {
      context.anchor = context.current;
    }
    Iif (element === selection?.focusNode && selection.focusOffset === children.length) {
      context.focus = context.current;
    }
  }
 
  logger.trace('Parser: ', tag);
 
  const headerLevel = isHeader(tag);
  if (headerLevel != null) {
    Iif (context.current > 0) {
      push('\n');
    }
    process('heading', `${'#'.repeat(headerLevel)} `, '');
  } else {
    Iif (tag === 'A') {
      // convert links to markdown: [link label](url)
      const url = element.getAttribute('href');
      const label = element.textContent;
      const data = `[${label}](${url})`;
      push(data);
    } else if (tag === 'SPAN' && element.getAttribute('DATA-TYPE') === 'link') {
      // convert custom links to markdown: [link label](url)
      const url = element.getAttribute('data-link-href');
      push('[');
      processUnformatable(element);
      push(`](${url})`);
    } else if (tag === 'SPAN') {
      md.push(processChildren(element, selection, context));
    } else if (
      tag === 'P' ||
      tag === 'DIV' ||
      tag === 'SECTION' ||
      tag === 'ARTICLE' ||
      tag === 'HEADER' ||
      tag === 'FOOTER'
    ) {
      if (context.current > 0) {
        // hack no newline within lists
        if (context.list.length === 0) {
          push('\n');
        }
      }
      md.push(processChildren(element, selection, context));
    } else if (tag === 'STRONG' || tag === 'B') {
      if (element.textContent) {
        process('strong', '**', '**');
      }
    } else if (tag === 'STRIKE') {
      if (element.textContent) {
        process('strike', '~', '~');
      }
    } else if (tag === 'EM' || tag === 'I') {
      if (element.textContent) {
        process('em', '/', '/');
      }
    } else if (tag === 'U') {
      if (element.textContent) {
        process('u', '_', '_');
      }
    } else if (tag === 'UL') {
      context.list.push('ul');
      md.push(processChildren(element, selection, context));
      context.list.pop();
    } else Iif (tag === 'OL') {
      context.list.push('ol');
      md.push(processChildren(element, selection, context));
      context.list.pop();
    } else if (tag === 'LI') {
      const currentList = context.list[context.list.length - 1];
      if (currentList) {
        if (context.current > 0) {
          push('\n');
        }
        push('  '.repeat(context.list.length - 1));
        const listType = element.getAttribute('data-list-type');
        Iif (listType === 'OL') {
          push('1. ');
        } else {
          const checked = element.getAttribute('data-checked');
          if (checked == null) {
            push('- ');
          } else {
            push(`- [${checked === 'DONE' ? 'x' : ' '}] `);
          }
        }
        md.push(processChildren(element, selection, context));
      }
    } else if (tag === 'PRE') {
      if (context.current > 0) {
        push('\n');
      }
      const lang = element.getAttribute('data-lang') || '';
      push(`\`\`\`${lang}\n`);
      processUnformatable(element);
      push('\n```');
    } else if (tag === 'BR') {
      push('\n ');
    } else Eif (tag === 'IMG') {
      // convert links to markdown: [link label](url)
      const src = element.getAttribute('src');
      const label = element.getAttribute('alt');
      const data = `![${label}](${src})`;
      push(data);
    } else if (tag === 'TABLE') {
      logger.warn('TABLE');
      const text = convertTable(element);
      push(text);
    } else {
      logger.info('Unhandled tag', tag, '=>', element.textContent, '<=');
    }
  }
  return md.join('');
}
 
export interface MarkdownRange {
  anchor: number | undefined;
  focus: number | undefined;
}
 
export interface MarkdownWithSelection {
  data: string;
  range: MarkdownRange;
}
 
export default function domToMarkdown(element: Element | null): MarkdownWithSelection {
  const selection = window.getSelection();
  const context: DomParserContext = {
    current: 0,
    anchor: undefined,
    focus: undefined,
    list: [],
  };
 
  const result = _domToMarkdown(element, selection, context);
 
  return {
    data: result,
    range: {
      anchor: context.anchor,
      focus: context.focus,
    },
  };
}