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

100% Statements 72/72
100% Branches 16/16
100% Functions 12/12
100% Lines 72/72

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 32121x 21x                     21x         12x           12x           12x     12x           12x           12x           12x             12x     12x     12x     12x     12x     12x     12x     12x     12x     12x           12x     12x   12x                                                                                                                                           4x               8x       13x       8x       1x             12x 12x 10x 10x 1x 4x   9x 7x     12x             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               5x 1x   4x 1x   4x             2x 2x 1x   2x                                                                                  
import { Messages, MethodNotAssignedError } from '@zeedhi/core';
import { ComponentRender } from '../zd-component/component-render';
import { ICodeEditor } from './interfaces';
 
/**
 * The Code Editor component <code>zd-code-editor</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 CodeEditor extends ComponentRender implements ICodeEditor {
	/**
	 * 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';
 
	// Set component height to fill all space available
	public fillHeight = false;
 
	/**
	 * 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';
 
	/* Tooltip text */
	public tooltipText = 'COPY';
 
	/* Readonly */
	public readonly?: boolean = false;
 
	/* Whether to show line numbers. */
	public lineNumbers?: boolean = true;
 
	/* Match line numbers text color to the theme. */
	public autoStyleLineNumbers?: boolean = true;
 
	/* The number of characters to insert when pressing tab key. */
	public tabSize?: number | string = 2;
 
	/* Whether to use spaces for indentation */
	public insertSpaces?: boolean = true;
 
	/* Ignore Tab key */
	public ignoreTabKey?: boolean = false;
 
	/* Function to load extraLanguages to render */
	public loadExtraLanguages?: string | (() => void);
 
	/* Enable fullscreen button */
	public enableFullscreen?: boolean = false;
 
	/* Enable copy function and icon */
	public enableCopy?: boolean = true;
 
	private staticCodeValue: object | string | string[] = '';
 
	// TO DO
	// private fullscreenModal?: Modal;
 
	/* istanbul ignore next */
	/**
	 * Creates a new CodeEditor
	 * @param props CodeEditor properties
	 */
	constructor(props: ICodeEditor) {
		super(props);
		this.code = this.getInitValue('code', props.code, 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.fillHeight = this.getInitValue('fillHeight', props.fillHeight, this.fillHeight);
		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.autoStyleLineNumbers = this.getInitValue(
			'autoStyleLineNumbers',
			props.autoStyleLineNumbers,
			this.autoStyleLineNumbers,
		);
		this.showLineNumbers = this.getInitValue('showLineNumbers', props.showLineNumbers, this.showLineNumbers);
		this.readonly = this.getInitValue('readonly', props.readonly, this.readonly);
		this.maxHeight = this.getInitValue('maxHeight', props.maxHeight, this.maxHeight);
		this.tabSize = this.getInitValue('tabSize', props.tabSize, this.tabSize);
		this.insertSpaces = this.getInitValue('insertSpaces', props.insertSpaces, this.insertSpaces);
		this.ignoreTabKey = this.getInitValue('ignoreTabKey', props.ignoreTabKey, this.ignoreTabKey);
		this.loadExtraLanguages = this.getInitValue(
			'loadExtraLanguages',
			props.loadExtraLanguages,
			this.loadExtraLanguages,
		);
		this.enableFullscreen = this.getInitValue('enableFullscreen', props.enableFullscreen, this.enableFullscreen);
		this.enableCopy = this.getInitValue('enableCopy', props.enableCopy, this.enableCopy);
		this.createAccessors();
 
		Messages.add({
			'pt-BR': {
				translation: {
					FULLSCREEN: 'Tela Cheia',
					COPY: 'Copiar',
					COPIED: 'Copiado!',
				},
			},
			'es-ES': {
				translation: {
					FULLSCREEN: 'Pantalla Completa',
					COPY: 'Copiar',
					COPIED: '¡Copiado!',
				},
			},
			'en-US': {
				translation: {
					FULLSCREEN: 'Fullscreen',
					COPY: 'Copy!!',
					COPIED: 'Copied!',
				},
			},
		});
	}
 
	private viewHighlight?: (code: string, language: string) => string;
 
	public setViewHighlight(fn: (code: string, language: string) => string) {
		this.viewHighlight = fn;
	}
 
	/**
	 * Code to be shown. When showing JSON code, the JSON object
	 * can be passed instead of the string code.
	 */
	public get code() {
		return this.staticCodeValue;
	}
 
	public set code(code: object | string | string[]) {
		this.staticCodeValue = code;
	}
 
	public get codeValue() {
		return this.getCode();
	}
 
	public set codeValue(code: string) {
		this.code = code;
	}
 
	/**
	 * Retrieves static code as string
	 */
	public 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.codeValue;
		// 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 = 'COPIED';
		setTimeout(() => {
			this.tooltipText = 'COPY';
		}, 2000);
	}
 
	/**
	 * Get the code highlighted
	 */
	public getHighlightedCode() {
		if (!this.viewHighlight) {
			throw new MethodNotAssignedError('viewHighlight');
		}
		if (typeof this.loadExtraLanguages === 'function') {
			this.loadExtraLanguages();
		}
		return this.viewHighlight(this.getCode(), this.language);
	}
 
	/**
	 * Get the total of lines
	 */
	get lineNumbersCount() {
		let totalLines = this.codeValue.split(/\r\n|\n/).length;
		if (this.codeValue.endsWith('\n') || !this.code) {
			totalLines -= 1;
		}
		return totalLines;
	}
 
	// TO DO
	//
	// private openFullscreenModal() {
	//   if (!this.fullscreenModal) {
	//     const fullscreenModalDef: IModal = {
	//       name: `${this.name}-fullscreen-modal`,
	//       fullscreen: true,
	//       persistent: true,
	//       children: [
	//         {
	//           name: `${this.name}-fullscreen-header`,
	//           component: 'ZdHeader',
	//           color: 'transparent',
	//           padless: true,
	//           elevation: 0,
	//         },
	//         {
	//           name: `${this.name}-modal`,
	//           component: 'ZdHighlight',
	//           instanceObject: this,
	//         },
	//       ],
	//     };
 
	//     this.fullscreenModal = ModalService.create(fullscreenModalDef);
	//   }
	//   this.fullscreenModal.show();
	// }
 
	// get isFullscreen() {
	//   return this.fullscreenModal?.isVisible;
	// }
 
	// public fullscreenClick() {
	//   if (!this.isFullscreen) this.openFullscreenModal();
	//   else this.closeModal();
	// }
}