All files / src/components/zd-code-viewer code-viewer.ts

100% Statements 61/61
100% Branches 15/15
100% Functions 10/10
100% Lines 61/61

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 20093x 93x                   93x         11x           11x           11x           11x           11x           11x           11x         11x         11x   11x   11x   11x         3x                                                   4x       11x 11x             11x 11x 8x 8x 1x 4x   7x 6x     11x             4x     4x 1x 1x 1x       3x 3x   3x 3x   3x   3x 3x 3x 3x 2x 2x 2x   2x   2x 2x     3x 1x         3x       2x 2x 1x               4x 1x     3x             2x 2x 1x   2x      
import { I18n, MethodNotAssignedError } from '@zeedhi/core';
import { ComponentRender } from '../zd-component/component-render';
import { ICodeViewer } from './interfaces';
 
/**
 * The Code Viewer component <code>zd-code-viewer</code> is used to show code highlighted using one of the
 * language supported by <a href=\"http://prismjs.com\" alt=\"Prism JS\" target=\"_blank\">Prism JS</a>
 * (<strong>html</strong>, <strong>javascript</strong>, <strong>typescript</strong>, <strong>css</strong>,
 * <strong>json</strong>, <strong>bash</strong>, <strong>etc.</strong>).
 * It can show code from a datasource field or static code.
 */
export class CodeViewer extends ComponentRender implements ICodeViewer {
	/**
	 * Defines the component height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public height: string | number = 'auto';
 
	/**
	 * Defines the component min height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public minHeight: string | number = 'auto';
 
	/**
	 * Defines the component max height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public maxHeight: string | number = 'none';
 
	/**
	 * Defines the component width. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public width: string | number = 'auto';
 
	/**
	 * Defines the component min width. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public minWidth: string | number = 'auto';
 
	/**
	 * Defines the component max height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public maxWidth: string | number = 'none';
 
	/**
	 * Language code to be used for highlight (js|javascript, css, html, json, ts|typescript, bash|shell)
	 * Other languages must be imported above
	 */
	public language = 'ts';
 
	/**
	 * Controls if line numbers are shown
	 */
	public showLineNumbers: boolean | string = true;
 
	/**
	 * Icon to be shown on copy action
	 */
	public copyIcon?: string = 'content-copy';
 
	public tooltipText = I18n.instance.t('COPY');
 
	private code = '';
 
	private staticCodeValue: object | string | string[] = '';
 
	private viewHighlight?: (code: string, language: string) => string;
 
	public setViewHighlight(fn: (code: string, language: string) => string) {
		this.viewHighlight = fn;
	}
 
	/* istanbul ignore next */
	/**
	 * Creates a new CodeViewer
	 * @param props CodeViewer properties
	 */
	constructor(props: ICodeViewer) {
		super(props);
		this.staticCode = this.getInitValue('staticCode', props.staticCode, this.staticCodeValue);
		this.copyIcon = this.getInitValue('copyIcon', props.copyIcon, this.copyIcon);
		this.height = this.getInitValue('height', props.height, this.height);
		this.minHeight = this.getInitValue('minHeight', props.minHeight, this.minHeight);
		this.maxHeight = this.getInitValue('maxHeight', props.maxHeight, this.maxHeight);
		this.width = this.getInitValue('width', props.width, this.width);
		this.minWidth = this.getInitValue('minWidth', props.minWidth, this.minWidth);
		this.maxWidth = this.getInitValue('maxWidth', props.maxWidth, this.maxWidth);
		this.language = this.getInitValue('language', props.language, this.language);
		this.showLineNumbers = this.getInitValue('showLineNumbers', props.showLineNumbers, this.showLineNumbers);
	}
 
	/**
	 * Code to be shown. When showing JSON code, the JSON object can be passed instead of the string code.
	 */
	public get staticCode() {
		return this.staticCodeValue;
	}
 
	public set staticCode(code: object | string | string[]) {
		this.staticCodeValue = code;
		this.code = this.getCode();
	}
 
	/**
	 * Retrieves static code as string
	 */
	private getCode() {
		let result: any = '';
		if (this.staticCodeValue) {
			result = this.staticCodeValue;
			if (Array.isArray(result)) {
				result = result
					.map((item: any) => (typeof item === 'object' ? JSON.stringify(item, null, 2) : item))
					.join('\n');
			} else if (typeof result === 'object') {
				result = JSON.stringify(result, null, 2);
			}
		}
		return result;
	}
 
	/**
	 * Copy the component content to clipboard
	 */
	public async copyToClipboard() {
		const text = this.code;
		// Use the Async Clipboard API when available. Requires a secure browing
		// context (i.e. HTTPS)
		if (navigator.clipboard) {
			await navigator.clipboard.writeText(text);
			this.changeTooltipText();
			return Promise.resolve();
		}
		// ...Otherwise, use document.execCommand() fallback
		// Put the text to copy into a <span>
		const span = document.createElement('span');
		span.textContent = text;
		// Preserve consecutive spaces and newlines
		span.style.whiteSpace = 'pre';
		span.style.opacity = '0';
		// Add the <span> to the page
		document.body.appendChild(span);
		// Make a selection object representing the range of text selected by the user
		const selection = window.getSelection();
		const range = window.document.createRange();
		let success = false;
		if (selection) {
			selection.removeAllRanges();
			range.selectNode(span);
			selection.addRange(range);
			// Copy text to the clipboard
			success = window.document.execCommand('copy');
			// Cleanup
			selection.removeAllRanges();
			window.document.body.removeChild(span);
		}
 
		if (success) {
			this.changeTooltipText();
		}
 
		// The Async Clipboard API returns a promise that may reject with `undefined`
		// so we match that here for consistency.
		return success ? Promise.resolve() : Promise.reject();
	}
 
	private changeTooltipText() {
		this.tooltipText = I18n.instance.t('COPIED');
		setTimeout(() => {
			this.tooltipText = I18n.instance.t('COPY');
		}, 2000);
	}
 
	/**
	 * Get the code highlighted
	 */
	public getHighlightedCode() {
		if (!this.viewHighlight) {
			throw new MethodNotAssignedError('viewHighlight');
		}
 
		return this.viewHighlight(this.code, this.language);
	}
 
	/**
	 * Get the total of lines
	 */
	get lineNumbersCount() {
		let totalLines = this.code.split(/\r\n|\n/).length;
		if (this.code.endsWith('\n') || !this.code) {
			totalLines -= 1;
		}
		return totalLines;
	}
}