UNPKG

@angular-package/prism

Version:
93 lines 2.82 kB
import { ElementRef, Injectable, SecurityContext } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; import { PartialObserver } from 'rxjs/Observer'; import Prism from 'prismjs'; import * as _ from 'lodash-es'; import { CallbackType, SanitizedType } from './prism.type'; export class PrismService { constructor(sanitizer) { this.sanitizer = sanitizer; this.subject = { code: new Subject(), language: new Subject() }; this.templateOptions = { interpolate: /{{([\s\S]+?)}}/g }; this.code$ = this.subject.code.asObservable(); this.language$ = this.subject.language.asObservable(); this.prism = Prism; } set async(value) { this._async = value; } get async() { return this._async; } set callback(value) { this._callback = value; } get callback() { return this._callback; } set code(value) { this._code = value; if (value) { value = this.sanitizer.sanitize(SecurityContext.HTML, this.escapeHtml(value)); } } get code() { return this._code; } set hooks(value) { this._hooks = value; if (value instanceof Object) { _.forEach(value, (element, key) => { this.prism.hooks.add(key, element); }); } } get hooks() { return this._hooks; } set interpolation(value) { this._interpolation = value; } get interpolation() { return this._interpolation; } set language(value) { this._language = value; } get language() { return this._language; } highlightElement(codeElementRef) { if (codeElementRef instanceof ElementRef) { this.interpolate(codeElementRef); this.prism.highlightElement(codeElementRef.nativeElement, this.async, this.callback); } } interpolate(codeElementRef) { if (this.interpolation && codeElementRef instanceof ElementRef) { codeElementRef.nativeElement.innerHTML = _.template(codeElementRef.nativeElement.innerHTML, this.templateOptions)(this.interpolation); } return codeElementRef; } escapeHtml(unsafe) { return unsafe .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;'); } } PrismService.decorators = [ { type: Injectable }, ]; PrismService.ctorParameters = () => [ { type: DomSanitizer, }, ]; //# sourceMappingURL=prism.service.js.map