All files / src/processors imageProcessor.ts

76.08% Statements 70/92
64.28% Branches 27/42
100% Functions 10/10
76.08% Lines 70/92

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  5x 5x     5x       71x   71x 71x     71x 71x       71x       865x 9x     856x 4x   852x       865x 88x   777x           4x     4x   4x 4x       4x 4x 4x     4x         9x     9x   9x 9x     9x   9x 9x 9x   9x       9x   9x 4x 1x   3x   4x   4x 1x     9x         88x     88x   88x 88x       88x   88x       88x   88x   88x       88x 5x   83x       83x 1x     83x 5x     83x 83x                                                     83x 78x   83x 83x       88x       88x       1x 1x 1x          
/* eslint-disable no-var */
import { ImageCollector } from 'src/imageCollector';
import { CommentParser } from '../comment';
import { ObsidianUtils } from '../obsidianUtils';
 
export class ImageProcessor {
	private utils: ObsidianUtils;
	private parser: CommentParser;
 
	private markdownImageRegex = /^[ ]{0,3}!\[([^\]]*)\]\((.*(?:jpg|png|jpeg|gif|bmp|webp|svg)?)\)\s?(<!--.*-->)?/gim;
 
	private obsidianImageRegex = /!\[\[(.*?(?:jpg|png|jpeg|gif|bmp|webp|svg))\s*\|?\s*([^\]]*)??\]\]\s?(<!--.*-->)?/ig;
	private obsidianImageReferenceRegex = /\[\[(.*?(?:jpg|png|jpeg|webp|gif|bmp|svg))\|?([^\]]*)??\]\]/gi;
 
	constructor(utils: ObsidianUtils) {
		this.utils = utils;
		this.parser = new CommentParser();
	}
 
	process(markdown: string) {
		return markdown
			.split('\n')
			.map(line => {
				// Transform ![[myImage.png]] to ![](myImage.png)
				if (this.obsidianImageRegex.test(line)) {
					return this.transformImageString(line);
				}
				// Transform referenced images to absolute paths (ex. in bg annotation)
				if (this.obsidianImageReferenceRegex.test(line)) {
					return this.transformImageReferenceString(line);
				}
				return line;
			})
			.map(line => {
				// Transform ![](myImage.png) to html
				if (this.markdownImageRegex.test(line)) {
					return this.htmlify(line);
				} else {
					return line;
				}
			})
			.join('\n');
	}
	transformImageReferenceString(line: string): string {
		let result = line;
 
		let m;
		this.obsidianImageReferenceRegex.lastIndex = 0;
 
		while ((m = this.obsidianImageReferenceRegex.exec(result)) !== null) {
			Iif (m.index === this.obsidianImageReferenceRegex.lastIndex) {
				this.obsidianImageReferenceRegex.lastIndex++;
			}
 
			const [match, image] = m;
			const filePath = this.utils.findFile(image);
			result = result.replaceAll(match, filePath);
		}
 
		return result;
	}
 
	private transformImageString(line: string) {
 
		let result = "";
 
		let m;
		this.obsidianImageRegex.lastIndex = 0;
 
		while ((m = this.obsidianImageRegex.exec(line)) !== null) {
			Iif (m.index === this.obsidianImageRegex.lastIndex) {
				this.obsidianImageRegex.lastIndex++;
			}
			const [, image, ext, comment] = m;
 
			const filePath = this.utils.findFile(image);
			const commentAsString = this.buildComment(ext, comment) ?? '';
			result = result + `\n![](${filePath}) ${commentAsString}`;
		}
		return result;
	}
 
	private buildComment(ext: string, commentAsString: string) {
		const comment = commentAsString ? this.parser.parseComment(commentAsString) : this.parser.buildComment('element');
 
		if (ext) {
			if (ext.includes('x')) {
				var [width, height] = ext.split('x');
			} else {
				var width = ext;
			}
			comment.addStyle('width', `${width}px`);
 
			if (height) {
				comment.addStyle('height', `${height}px`);
			}
		}
		return this.parser.commentToString(comment);
	}
 
	private htmlify(line: string) {
 
		let result = "";
 
		let m;
		this.markdownImageRegex.lastIndex = 0;
 
		while ((m = this.markdownImageRegex.exec(line)) !== null) {
			Iif (m.index === this.markdownImageRegex.lastIndex) {
				this.markdownImageRegex.lastIndex++;
			}
			// eslint-disable-next-line prefer-const
			let [, alt, filePath, commentString] = m;
 
			Iif (alt && alt.includes('|')) {
				commentString = this.buildComment(alt.split('|')[1], commentString) ?? '';
			}
 
			const comment = this.parser.parseLine(commentString) ?? this.parser.buildComment('element');
 
			const isIcon = this.isIcon(filePath);
 
			Iif (result.length > 0) {
				result = result + '\n';
			}
 
			if (isIcon) {
				result = result + `<i class="${filePath}" ${this.parser.buildAttributes(comment)}></i>`;
			} else {
				Iif (ImageCollector.getInstance().shouldCollect()) {
					ImageCollector.getInstance().addImage(filePath);
				}
 
				if (filePath.startsWith('file:/')) {
					filePath = this.transformAbsoluteFilePath(filePath);
				}
 
				if (comment.hasStyle('width')) {
					comment.addStyle('object-fit', 'fill');
				}
 
				if (!comment.hasStyle('align-self')) {
					Iif (comment.hasAttribute('align')) {
 
						const align = comment.getAttribute('align');
 
						switch (align) {
							case 'left':
								comment.addStyle('align-self', 'start');
								break;
							case 'right':
								comment.addStyle('align-self', 'end');
								break;
							case 'center':
								comment.addStyle('align-self', 'center');
								break;
							case 'stretch':
								comment.addStyle('align-self', 'stretch');
								comment.addStyle('object-fit', 'cover');
								comment.addStyle('height', '100%');
								comment.addStyle('width', '100%');
								break;
							default:
								break;
						}
						comment.deleteAttribute('align');
					}
				}
 
				if (!comment.hasStyle('object-fit')) {
					comment.addStyle('object-fit', 'scale-down');
				}
				const imageHtml = `<img src="${filePath}" alt="${alt}" ${this.parser.buildAttributes(comment)}>`;
				result = result + imageHtml;
			}
 
		}
		return result + '\n';
	}
 
	private isIcon(path: string) {
		return path.startsWith('fas') || path.startsWith('far') || path.startsWith('fal') || path.startsWith('fad') || path.startsWith('fab');
	}
 
	private transformAbsoluteFilePath(path: string) {
		const pathURL = new URL(path);
		if (pathURL) {
			return '/localFileSlash' + pathURL.pathname;
		}
		return path;
	}
}