import { Component , ContentChild , ElementRef , Input , OnDestroy , OnInit } from '@angular/core' ; import { HttpClient } from '@angular/common/http' ; import { Subject } from 'rxjs' ; import { takeUntil } from 'rxjs/operators' ; import * as Prism from 'prismjs/prism' ; import '@fuse/components/highlight/prism-languages' ; @ Component ( { selector : 'fuse-highlight' , template : '' , styleUrls : [ './highlight.component.scss' ] } ) export class FuseHighlightComponent implements OnInit , OnDestroy { @ ContentChild ( 'source' , { static : false } ) source : ElementRef ; @ Input ( 'lang' ) lang : string ; @ Input ( 'path' ) path : string ; private _unsubscribeAll : Subject < any > ; param { ElementRef } _elementRef param { HttpClient } _httpClient constructor ( private _elementRef , private _httpClient ) { this . _unsubscribeAll = new Subject ( ) ; } /**
     * On init
     */ ngOnInit ( ) { if ( ! this . lang ) { return ; } if ( this . path ) { this . _httpClient . get ( this . path , { responseType : 'text' } ) . pipe ( takeUntil ( this . _unsubscribeAll ) ) . subscribe ( ( response ) => { this . highlight ( response ) ; } ) ; } if ( ! this . path && this . source ) { this . highlight ( this . source . nativeElement . value ) ; } } /**
     * On destroy
     */ ngOnDestroy ( ) { this . _unsubscribeAll . next ( ) ; this . _unsubscribeAll . complete ( ) ; } param sourceCode highlight ( sourceCode ) { const sourceLines = sourceCode . split ( '\n' ) ; if ( ! sourceLines [ 0 ] . trim ( ) ) { sourceLines . shift ( ) ; } if ( ! sourceLines [ sourceLines . length - 1 ] . trim ( ) ) { sourceLines . pop ( ) ; } const indexOfFirstChar = sourceLines [ 0 ] . search ( /\S|$/ ) ; let source = '' ; sourceLines . forEach ( ( line , index ) => { source = source + line . substr ( indexOfFirstChar , line . length ) ; if ( index !== sourceLines . length - 1 ) { source = source + '\n' ; } } ) ; const highlightedCode = Prism . highlight ( source , Prism . languages [ this . lang ] ) ; this . _elementRef . nativeElement . innerHTML = '<pre><code class="highlight language-' + this . lang + '">' + highlightedCode + '</code></pre>' ; } }