All files / src/processors footNoteProcessor.ts

97.56% Statements 40/41
87.5% Branches 7/8
100% Functions 7/7
97.56% Lines 40/41

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    5x 142x     71x   71x     98x     99x 2x 2x 2x   97x         71x         6x 4x     2x 2x   2x     2x 4x     29x 8x 4x 4x   4x   4x   4x 4x 4x   4x   4x     21x         2x 2x 2x   2x 4x     2x 2x   2x   2x     2x            
import { Options } from '../options';
 
export class FootnoteProcessor {
	private regex = /\[\^([^\]]*)]/im;
 
	process(markdown: string, options: Options) {
		let output = markdown;
 
		markdown
			.split(new RegExp(options.separator, 'gmi'))
			.map((slidegroup, index) => {
				return slidegroup
					.split(new RegExp(options.verticalSeparator, 'gmi'))
					.map((slide, index) => {
						if (this.regex.test(slide)) {
							const newSlide = this.transformFootNotes(slide);
							output = output.replace(slide, newSlide);
							return newSlide;
						}
						return slide;
					})
					.join(options.verticalSeparator);
			})
			.join(options.separator);
		return output;
	}
 
	transformFootNotes(markdown: string) {
 
		if (!this.regex.test(markdown)) {
			return markdown;
		}
 
		let input = markdown;
		let noteIdx = 1;
 
		const footNotes = new Map();
 
		let reResult: RegExpExecArray;
		while ((reResult = this.regex.exec(input))) {
			input = input
				.split('\n')
				.map((line, index) => {
					if (line.includes(reResult[0])) {
						if (line.includes(reResult[0] + ': ')) {
							if (!footNotes.has(reResult[1])) {
								footNotes.set(reResult[1], line.split(reResult[0] + ': ')[1]);
							}
							return '';
						} else {
							const split = line.split(reResult[0]);
 
							let result = split[0].trim();
							result += '<sup id="fnref:' + reResult[1] + '" role="doc-noteref">' + noteIdx + '</sup>';
							result += split[1].trim();
 
							noteIdx = noteIdx + 1;
 
							return result;
						}
					}
					return line;
				})
				.join('\n');
		}
 
		let footNotesBlock = '';
		footNotesBlock += '<div class="footnotes" role="doc-endnotes">\n';
		footNotesBlock += '<ol>\n';
 
		footNotes.forEach((value, key) => {
			footNotesBlock += '<li id="fn:' + key + '" role="doc-endnote" class="footnote"><p>\n\n' + value + '\n\n</p></li>';
		});
 
		footNotesBlock += '</ol>\n';
		footNotesBlock += '</div>\n';
 
		const footnotePlaceholder = '<%? footnotes %>';
 
		Iif (input.includes(footnotePlaceholder)) {
			return input.replaceAll(footnotePlaceholder, footNotesBlock);
		} else {
			return input + '\n' + footNotesBlock;
		}
 
 
	}
}