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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 | 7x 7x 7x 7x 7x 7x 66x 7x 66x 7x 66x 7x 66x 7x 66x 7x 66x 66x 7x 66x 7x 36x 33x 26x 10x 10x 34x 3x 7x 16x 8x 21x 21x 21x 21x 21x 36x 36x 36x 36x 3x 3x 3x 3x 33x 7x 7x 7x 7x 7x 26x 16x 16x 16x 16x 10x 10x 10x 10x 10x 2x 2x 8x 8x 21x 34x 34x 36x 36x 34x 34x 2x 2x 2x 2x 36x 36x 534x 534x 534x 534x 36x 36x 34x 3x 31x 16x 16x 1x 1x 15x 15x 34x 34x 21x 21x 34x 119x 13x 34x 11x 11x 1693x 1693x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1682x 45x 45x 45x 45x 45x 45x 3x 3x 3x 3x 3x 3x 3x 42x 42x 42x 57x 53x 53x 53x 53x 53x 42x 42x 428x 428x 11x 11x 11x 11x 11x 11x 11x 417x 2x 2x 2x 2x 2x 2x 2x 415x 1x 1x 1x 1x 1x 1x 1x 1x 1x 414x 414x 414x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42x 42x 42x 17x 42x 68x 42x 42x 42x 42x 21x 21x 21x 21x 21x 21x 34x 16x 16x 16x 5x 5x 5x 5x 5x 5x 16x 16x 5x 5x 5x 5x 5x 5x 11x 1x 3x 1x 1x 1x 1x 1x 16x 16x 18x 18x 18x 18x 18x 21x 7x 7x 21x 21x 21x 21x 21x 21x 21x 21x 23x 21x 23x 171x 106x 106x 8x 98x 21x | /* * The coLAB project * Copyright (C) 2021-2023 AlbaSim, MEI, HEIG-VD, HES-SO * * Licensed under the MIT License */ import { getLogger } from '../../../../logger'; import { MarkdownRange } from './domToMarkdown'; const logger = getLogger('Markdown2DomParser'); logger.setLevel(4); // detect lines and indentation levels // A line may be : // -> a UL item "* Item 1" with any indentation level, // -> a OL item "1. Item 1" with any indentation level // -> a todo item: "* [] // const newMajorBlockDetector = /(?:^(?! ))/; // New line which starts with non-space character export function getFirstMajorTag(md: string): MajorTagParsed | undefined { return extractMajorTags(md)[0]; } const regexBuilder = () => { // seems some odd browsers do not support negative lookbehind group... // current mitigation: delay regexp instantiation so the whole app won't crash... // TODO: fix safari // TODO: do not use lookbehind groups let linesRegex: RegExp; /** two consecutive unescaped '*' */ let boldRegex: RegExp; /** one unescaped '/' */ let italicRegex: RegExp; /** one unescaped unescaped '~' */ let strikethroughRegex: RegExp; /** one unescaped unescaped '_' */ let underlineRegex: RegExp; /** [link label](link_url) */ let linkRegex: RegExp; return () => { if (!boldRegex) { boldRegex = new RegExp('(\\*\\*)', 'g'); } if (!italicRegex) { italicRegex = new RegExp('(\\/)', 'g'); } if (!strikethroughRegex) { strikethroughRegex = new RegExp('(~)', 'g'); } if (!underlineRegex) { underlineRegex = new RegExp('(_)', 'g'); } /* WITH NEGATIVE LOOKBEHIND */ // if (!boldRegex) { // boldRegex = new RegExp('(?<!\\\\)(\\*\\*)'); // } // // if (!italicRegex) { // italicRegex = new RegExp('(?<!\\\\)(\\/)'); // } // // if (!strikethroughRegex) { // strikethroughRegex = new RegExp('(?<!\\\\)(~)'); // } // // if (!underlineRegex) { // underlineRegex = new RegExp('(?<!\\\\)(_)'); // } if (!linkRegex) { linkRegex = new RegExp('^(?<LINK>\\[(?<LINK_LABEL>.*?)\\]\\((?<LINK_HREF>.*?)\\))'); } const anyWhiteSpace = '[^\\S\n\r]'; // aka not not-a-whitespace nor \r nor \n if (!linesRegex) { linesRegex = new RegExp( [ '(?<CODE>(?<codeIndent>^```(?<codeLang>.*)\n)(?<codeData>(?:.|\n|\r)*?)\n```)', `(?<UL>^(?<ulIndent>(?<ulLevel>${anyWhiteSpace}*[*-])(?:${anyWhiteSpace}\\[(?<ulChecked>[ x])\\])?${anyWhiteSpace})(?<ulData>.*)$)`, `(?<OL>^(?<olIndent>(?<olLevel>${anyWhiteSpace}*)(?<olNumber>\\d+)\\.${anyWhiteSpace})(?<olData>.*)$)`, `(?<H>^(?<hIndent>(?<hLevel>#{1,5})${anyWhiteSpace}?)(?<hData>.*)$)`, `(?<P>^(?<pIndent>${anyWhiteSpace}*)(?<pData>.*)$)`, ].join('|'), 'gm', ); } return { linesRegex, boldRegex, italicRegex, strikethroughRegex, underlineRegex, linkRegex }; }; }; const getRegexes = regexBuilder(); export type HeadingLevel = 1 | 2 | 3 | 4 | 5; interface CodeRegexGroup { CODE: string; codeIndent: string; codeLang: string; codeData: string; } interface HeadingLineRegexGroup { H: string; hIndent: string; hLevel: string; hData: string; } interface UlLineRegexGroup { UL: string; ulIndent: string; ulData: string; ulLevel: string; ulChecked: ' ' | 'x' | undefined; } interface OlLineRegexGroup { OL: string; olIndent: string; olLevel: string; olNumber: string; olData: string; } interface PLineRegexGroup { P: string; pIndent: string; pData: string; } //type LineGroup = CodeGroup HeadingLineRegexGroup | UlLineRegexGroup | OlLineRegexGroup | PLineRegexGroup; function isCodeGroup(group: object): group is CodeRegexGroup { return 'CODE' in group && (group as unknown as { CODE: unknown }).CODE != null; } function isHeadingGroup(group: object): group is HeadingLineRegexGroup { return 'H' in group && (group as unknown as { H: unknown }).H != null; } function isUlGroup(group: object): group is UlLineRegexGroup { return 'UL' in group && (group as unknown as { UL: unknown }).UL != null; } function isOlGroup(group: object): group is OlLineRegexGroup { return 'OL' in group && (group as unknown as { OL: unknown }).OL != null; } function isPLineGroup(group: object): group is PLineRegexGroup { return 'P' in group && (group as unknown as { P: unknown }).P != null; } interface Line { offset: number; data: string; postOffset: number; } interface Multiline { initialMark: string; text: Line[]; } interface Heading extends Multiline { tagType: 'Heading'; headerLevel: HeadingLevel; } interface Code extends Multiline { tagType: 'Code'; lang: string; } interface UListItem extends Multiline { tagType: 'UListItem'; listLevel: number; checked: boolean | undefined; } interface OListItem extends Multiline { tagType: 'OListItem'; listLevel: number; startNumber: number; } interface Paragraph extends Multiline { tagType: 'P'; } export type MajorTagParsed = Code | Heading | UListItem | OListItem | Paragraph; function getTagFromMajor(major: MajorTagParsed): string { switch (major.tagType) { case 'Code': return 'PRE'; case 'Heading': return `H${major.headerLevel}`; case 'UListItem': return 'LI'; case 'OListItem': return 'LI'; case 'P': return 'P'; } } function extractMajorTags(markdown: string): MajorTagParsed[] { let m: RegExpExecArray | null; const { linesRegex } = getRegexes(); linesRegex.lastIndex = 0; const majorTags: MajorTagParsed[] = []; let currentIndentation: number | undefined = undefined; // harvest lines and group adjacent with same indentation level while ((m = linesRegex.exec(markdown)) !== null) { // This is necessary to avoid infinite loops with zero-width matches Iif (m.index === linesRegex.lastIndex) { linesRegex.lastIndex++; } logger.trace('Groupe: ', m.groups); if (m.groups) { //logger.trace("GROUP"); if (isCodeGroup(m.groups)) { logger.trace('Hit code: ', m.groups.codeLang, m.groups.codeData); currentIndentation = 0; majorTags.push({ tagType: 'Code', initialMark: m.groups.codeIndent, lang: m.groups.codeLang, text: [ { offset: 3 + m.groups.codeLang.length + 1, data: m.groups.codeData, postOffset: 4 }, ], }); logger.trace('CurrentLevel', currentIndentation); } else if (isHeadingGroup(m.groups)) { logger.trace('Hit heading: ', m.groups.hIndent, m.groups.hData); currentIndentation = m.groups.hIndent.length; const t: Heading = { tagType: 'Heading', initialMark: m.groups.hIndent, headerLevel: m.groups.hLevel.length as HeadingLevel, text: [{ offset: m.groups.hIndent.length, data: m.groups.hData, postOffset: 0 }], }; majorTags.push(t); logger.trace('CurrentLevel', currentIndentation); } else if (isUlGroup(m.groups)) { logger.trace('Hit UL item'); currentIndentation = m.groups.ulIndent.length; majorTags.push({ tagType: 'UListItem', initialMark: m.groups.ulIndent, listLevel: m.groups.ulLevel.length, checked: m.groups.ulChecked === undefined ? undefined : m.groups.ulChecked !== ' ', text: [{ offset: currentIndentation, data: m.groups.ulData, postOffset: 0 }], }); logger.trace('CurrentLevel', currentIndentation); } else Iif (isOlGroup(m.groups)) { logger.trace('Hit OL item'); currentIndentation = m.groups.olIndent.length; majorTags.push({ tagType: 'OListItem', initialMark: m.groups.olIndent, listLevel: m.groups.olLevel.length + 1, startNumber: +m.groups.olNumber, text: [{ offset: currentIndentation || 0, data: m.groups.olData, postOffset: 0 }], }); logger.trace('CurrentLevel', currentIndentation); } else if (isPLineGroup(m.groups)) { const pLevel = m.groups.pIndent.length; logger.trace('Hit P:', pLevel, ':', m.groups.pData, currentIndentation); //if (pLevel > 0 && currentIndentation && pLevel >= currentIndentation) { if (pLevel > 0 && currentIndentation) { // merge line within previous group logger.trace('Group'); majorTags[majorTags.length - 1]!.text.push({ offset: pLevel, data: m.groups.pData, postOffset: 0, }); } else { logger.trace('No Group'); majorTags.push({ tagType: 'P', initialMark: m.groups.pIndent, text: [ { offset: 0, data: m.groups.P, postOffset: 0, }, ], }); } } } } return majorTags; } interface Combined { tag: string; initialMark: string; attributes: Record<string, string>; data: string | undefined; offset: number[]; major: MajorTagParsed; currentRowPosition: number; currentDataPosition: number; } function combineMultiline(majorTag: MajorTagParsed): Combined { const tag = getTagFromMajor(majorTag); const combined = majorTag.text.reduce<Combined>( (acc, cur) => { acc.currentRowPosition += cur.offset; if (acc.data == null) { acc.data = ''; acc.offset[acc.currentDataPosition] = acc.currentRowPosition; } else { acc.data = `${acc.data}\n`; acc.offset[acc.currentDataPosition] = acc.currentRowPosition; acc.currentDataPosition++; acc.currentRowPosition++; } logger.trace('cur.data: ', cur.data); for (const c of cur.data) { acc.offset[acc.currentDataPosition] = acc.currentRowPosition; acc.data += c; acc.currentRowPosition++; acc.currentDataPosition++; } acc.currentRowPosition += cur.postOffset; return acc; }, { tag: tag, initialMark: majorTag.initialMark, attributes: {}, data: undefined, offset: [], major: majorTag, currentRowPosition: 0, currentDataPosition: 0, }, ); if (majorTag.tagType === 'Code') { combined.attributes['data-lang'] = majorTag.lang; } else if (majorTag.tagType === 'UListItem') { combined.attributes['data-list-type'] = 'UL'; if (majorTag.checked != undefined) { combined.attributes['data-checked'] = majorTag.checked ? 'DONE' : 'TODO'; combined.attributes['data-list-type'] = 'TL'; } else { combined.attributes['data-list-type'] = 'UL'; } } else Iif (majorTag.tagType === 'OListItem') { combined.attributes['data-list-type'] = 'OL'; } logger.trace('Combined', combined); return combined; } /** * Make offset absolute */ function consolidate(combineds: Combined[]) { let currentRawPos = 0; combineds.forEach(c => { if (currentRawPos > 0) { c.offset = c.offset.map(o => o + currentRawPos); c.currentRowPosition += currentRawPos; } // new line currentRawPos = c.currentRowPosition + 1; }); } function extract( combined: Combined, from: number, to: number, tag: string, mark: string, ): Combined { const extraction: Combined = { tag: tag, initialMark: mark, data: combined.data!.substring(from, to), offset: combined.offset.slice(from, to), major: combined.major, currentRowPosition: combined.currentRowPosition, currentDataPosition: combined.currentDataPosition, attributes: {}, }; return extraction; } interface NodeWithPosition { node: Node; rawPosition: number; consumed: number; combined: Combined; } interface DomTree { root: NodeWithPosition; all: NodeWithPosition[]; } function processTag( combined: Combined, position: number, mark: string, markRegex: RegExp, tag: string, ): DomTree | false { const data = combined.data!.substring(position); if (data.startsWith(mark)) { logger.trace(`Start of tag ${mark} found at :${position}`); const markLength = mark.length; const sub = data.substring(markLength); // one would use negative-lookbehin regex but odd browsers still do not implement such ES2018 spec... // With such a regex, simply use: //const endIndex = sub.search(markRegex); let endIndex = -1; const endIndexes = [...sub.matchAll(markRegex)]; const firstNonEscapedMatch = endIndexes.find(match => { const currentIndex = match.index; // is the group escaped? return currentIndex != null && sub.charAt(currentIndex - 1) !== '\\'; }); if (firstNonEscapedMatch?.index != null) { endIndex = firstNonEscapedMatch.index; } if (endIndex >= 0) { logger.trace(`end of tag ${mark} found at :${position + endIndex + 2 * markLength}`); const inner = extract( combined, position + markLength, position + markLength + endIndex, tag, mark, ); logger.trace(`Extrated data`, inner); const parsed = parseMinor(inner); // count marks parsed.root.consumed += markLength * 2; logger.trace(`Consumed: ${parsed.root.consumed}`); return parsed; } } return false; } function parseMinor(minor: Combined): DomTree { const children: NodeWithPosition[] = []; const all: NodeWithPosition[] = []; const { boldRegex, italicRegex, strikethroughRegex, underlineRegex, linkRegex } = getRegexes(); logger.trace(`ParseMinor(${minor.tag}): >${minor.data}<`); Iif (minor.tag === 'P' && minor.data?.length == 0) { // Empty P => <p><br /><p> const p = document.createElement('P'); const br = document.createElement('BR'); p.append(br); const node = { node: p, rawPosition: minor.offset[0]!, consumed: 0, combined: minor, }; return { root: node, all: [ node, { node: br, rawPosition: minor.offset[0]!, consumed: 0, combined: minor, }, ], }; } if (minor.tag === 'PRE') { // do not parse pre tags content const pre = document.createElement(minor.tag); Object.entries(minor.attributes).forEach(([attr, value]) => { pre.setAttribute(attr, value); }); const textNode = document.createTextNode(minor.data!); pre.append(textNode); const node = { node: pre, rawPosition: minor.offset[0]! - minor.initialMark.length, consumed: minor.data!.length + 4, // data length + '\n```' combined: minor, }; return { root: node, all: [ node, { node: textNode, rawPosition: minor.offset[0]!, consumed: textNode.length, combined: minor, }, ], }; } else { let offset = 0; let nodeStart = 0; const createTextNode = () => { if (offset > nodeStart) { const textNode = document.createTextNode(minor.data!.substring(nodeStart, offset)); logger.trace('Create Text node: ', nodeStart, offset, textNode.data); const n = { node: textNode, rawPosition: minor.offset[nodeStart]!, consumed: textNode.length, combined: minor, }; children.push(n); all.push(n); } }; if (minor.data != null) { for (offset = 0; offset < minor.data.length; offset++) { // try to parse a sub tag const tag = processTag(minor, offset, '**', boldRegex, 'STRONG') || processTag(minor, offset, '/', italicRegex, 'EM') || processTag(minor, offset, '_', underlineRegex, 'U') || processTag(minor, offset, '~', strikethroughRegex, 'STRIKE'); if (tag != false) { // subtag found and parsed createTextNode(); logger.trace(`Tagged "${tag.root.node.textContent}"`); children.push(tag.root); logger.trace('SubTag.all: ', tag.all); all.push(...tag.all); // move cursor to last character of tag offset += tag.root.consumed - 1; nodeStart = offset + 1; } else if (minor.data[offset] === '\n') { createTextNode(); const br = document.createElement('BR'); const n = { node: br, rawPosition: minor.offset[offset]!, consumed: 1, combined: minor, }; children.push(n); all.push(n); offset++; nodeStart = offset; } else if (minor.data[offset] === '\\') { const escaped = minor.data[offset + 1]; if (escaped) { createTextNode(); const span = document.createElement('span'); const n = { node: span, rawPosition: minor.offset[offset]!, consumed: 1, combined: minor, }; children.push(n); all.push(n); offset++; nodeStart = offset; } } else { const data = minor.data!.substring(offset); const match = data.match(linkRegex); if (match != null) { if (match.groups) { const label = match.groups['LINK_LABEL']; const href = match.groups['LINK_HREF']; const full = match.groups['LINK']; const rawLength = full?.length ?? 0; createTextNode(); const span = document.createElement('span'); span.setAttribute('data-type', 'link'); span.setAttribute('data-link-href', href ?? ''); const textNode = document.createTextNode(label ?? ''); span.append(textNode); const n = { node: span, rawPosition: minor.offset[offset]!, consumed: rawLength, combined: minor, }; children.push(n); all.push(n); all.push({ node: textNode, rawPosition: minor.offset[offset]! + 1, consumed: label?.length ?? 0, combined: minor, }); offset += rawLength; nodeStart = offset; } } } } createTextNode(); } // const element = document.createElement(minor.tag); Object.entries(minor.attributes).forEach(([attr, value]) => { element.setAttribute(attr, value); }); children.forEach(c => { element.appendChild(c.node); }); const node = { node: element, rawPosition: minor.offset[0]! - minor.initialMark.length, consumed: minor.data!.length, combined: minor, }; all.push(node); logger.trace('all: ', all); return { root: node, all: all }; } } function rebuildHierarchy(domTrees: DomTree[]): DomTree[] { const domTreeWithList: DomTree[] = []; let currentListLevel: number = 0; let rootTree: DomTree | undefined = undefined; const listContext: (HTMLUListElement | HTMLOListElement)[] = []; const listLevels: number[] = []; domTrees.forEach(child => { if (child.root.combined.tag == 'LI') { const liMajor = child.root.combined.major as UListItem | OListItem; const itemLevel = liMajor.listLevel; if (currentListLevel === 0) { // no list context //const listType = liMajor.tagType === 'UListItem' ? 'UL' : 'OL'; const listTag = document.createElement('UL') as HTMLUListElement | HTMLOListElement; listContext.push(listTag); listLevels.push(itemLevel); rootTree = { root: { ...child.root, node: listTag, }, all: [], }; domTreeWithList.push(rootTree); currentListLevel = itemLevel; } rootTree!.all.push(...child.all); if (itemLevel > currentListLevel) { // const listType = liMajor.tagType === 'UListItem' ? 'UL' : 'OL'; const listTag = document.createElement('UL') as HTMLUListElement | HTMLOListElement; const list = listContext[listContext.length - 1]!; (list.lastChild as Element).append(listTag); listContext.push(listTag); currentListLevel = itemLevel; listLevels.push(itemLevel); } else if (itemLevel < currentListLevel) { // How far back should we go? let level = listLevels.findIndex(level => { return level > itemLevel; }); // no greater level found, keep same level Iif (level < 0) { level = listContext.length; } // make sure not to kill the top-level list Iif (level < 1) { level = 1; } listLevels.length = level; listContext.length = level; currentListLevel = itemLevel; } // append LI to current List const list = listContext[listContext.length - 1]!; list.append(child.root.node); } else { rootTree = undefined; listContext.length = 0; listLevels.length = 0; currentListLevel = 0; domTreeWithList.push(child); } }); return domTreeWithList; } export interface NodesAndOffsets { nodes: Node[]; offsets: Record<number, Node[]>; } function convertPosition( md: NodesAndOffsets, position: number | undefined, ): { node: Node; offset: number } | null { Iif (position != null) { const sortedOffset = Object.keys(md.offsets) .filter(offset => +offset <= position) .sort((a, b) => +a - +b); const strOffset = sortedOffset[sortedOffset.length - 1]; Iif (strOffset != null) { const theOffset = +strOffset; const nodes = md.offsets[theOffset]; Iif (nodes != null && nodes.length > 0) { const text = nodes.find(n => n instanceof Text); if (text != null) { const delta = position - theOffset; const textLength = (text as Text).length; if (delta > textLength) { logger.warn('Range '); return { node: text, offset: textLength, }; } else { return { node: text, offset: delta, }; } } else { return { node: nodes[0]!, offset: 0, }; } } } } return null; } export function convertRange(md: NodesAndOffsets, mdRange: MarkdownRange): Range { const range = document.createRange(); const anchor = convertPosition(md, mdRange.anchor); Iif (anchor != null) { range.setStart(anchor.node, anchor.offset); } const focus = convertPosition(md, mdRange.focus); Iif (focus != null) { range.setEnd(focus.node, focus.offset); } return range; } export default function markdownToDom(markdown: string): NodesAndOffsets { logger.trace('MarkDown: ', markdown); Iif (markdown == '') { const p = document.createElement('P'); const br = document.createElement('BR'); p.append(br); return { nodes: [p], offsets: { 0: [p] }, }; } const majorTags = extractMajorTags(markdown); const combined = majorTags.map(combineMultiline); consolidate(combined); const domTrees = combined.map(parseMinor); const domTreeWithHierarchy = rebuildHierarchy(domTrees); const result: NodesAndOffsets = { nodes: domTreeWithHierarchy.map(dt => dt.root.node), offsets: {}, }; domTreeWithHierarchy .flatMap(dt => dt.all) .sort((a, b) => { return a.rawPosition - b.rawPosition; }) .forEach(c => { const list = result.offsets[c.rawPosition]; if (list != null) { list.push(c.node); } else { result.offsets[c.rawPosition] = [c.node]; } }); return result; } |