Browse Source

Improve markdown component

pull/5552/head
Igor Kulikov 5 years ago
parent
commit
4349f14d19
  1. 58
      ui-ngx/src/app/core/services/dynamic-component-factory.service.ts
  2. 21
      ui-ngx/src/app/shared/components/markdown.component.html
  3. 20
      ui-ngx/src/app/shared/components/markdown.component.scss
  4. 93
      ui-ngx/src/app/shared/components/markdown.component.ts
  5. 4
      ui-ngx/src/styles.scss

58
ui-ngx/src/app/core/services/dynamic-component-factory.service.ts

@ -23,10 +23,12 @@ import {
NgModule, NgModule,
NgModuleRef, NgModuleRef,
OnDestroy, OnDestroy,
Type Type,
ɵresetCompiledComponents
} from '@angular/core'; } from '@angular/core';
import { Observable, ReplaySubject } from 'rxjs'; import { from, Observable } from 'rxjs';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { catchError, map, mergeMap } from 'rxjs/operators';
@NgModule() @NgModule()
export abstract class DynamicComponentModule implements OnDestroy { export abstract class DynamicComponentModule implements OnDestroy {
@ -56,10 +58,10 @@ export class DynamicComponentFactoryService {
componentType: Type<T>, componentType: Type<T>,
template: string, template: string,
modules?: Type<any>[], modules?: Type<any>[],
preserveWhitespaces?: boolean): Observable<ComponentFactory<T>> { preserveWhitespaces?: boolean,
const dymamicComponentFactorySubject = new ReplaySubject<ComponentFactory<T>>(); compileAttempt = 1): Observable<ComponentFactory<T>> {
import('@angular/compiler').then( return from(import('@angular/compiler')).pipe(
() => { mergeMap(() => {
const comp = this.createDynamicComponent(componentType, template, preserveWhitespaces); const comp = this.createDynamicComponent(componentType, template, preserveWhitespaces);
let moduleImports: Type<any>[] = [CommonModule]; let moduleImports: Type<any>[] = [CommonModule];
if (modules) { if (modules) {
@ -70,29 +72,33 @@ export class DynamicComponentFactoryService {
declarations: [comp], declarations: [comp],
imports: moduleImports imports: moduleImports
})(class DynamicComponentInstanceModule extends DynamicComponentModule {}); })(class DynamicComponentInstanceModule extends DynamicComponentModule {});
try { return from(this.compiler.compileModuleAsync(dynamicComponentInstanceModule)).pipe(
this.compiler.compileModuleAsync(dynamicComponentInstanceModule).then( map((module) => {
(module) => { let moduleRef: NgModuleRef<any>;
const moduleRef = module.create(this.injector); try {
const factory = moduleRef.componentFactoryResolver.resolveComponentFactory(comp); moduleRef = module.create(this.injector);
this.dynamicComponentModulesMap.set(factory, { } catch (e) {
moduleRef, this.compiler.clearCacheFor(module.moduleType);
moduleType: module.moduleType throw e;
});
dymamicComponentFactorySubject.next(factory);
dymamicComponentFactorySubject.complete();
} }
).catch( const factory = moduleRef.componentFactoryResolver.resolveComponentFactory(comp);
(e) => { this.dynamicComponentModulesMap.set(factory, {
dymamicComponentFactorySubject.error(e); moduleRef,
moduleType: module.moduleType
});
return factory;
}),
catchError((error) => {
if (compileAttempt === 1) {
ɵresetCompiledComponents();
return this.createDynamicComponentFactory(componentType, template, modules, preserveWhitespaces, ++compileAttempt);
} else {
throw error;
} }
); })
} catch (e) { );
dymamicComponentFactorySubject.error(e); })
}
}
); );
return dymamicComponentFactorySubject.asObservable();
} }
public destroyDynamicComponentFactory<T>(factory: ComponentFactory<T>) { public destroyDynamicComponentFactory<T>(factory: ComponentFactory<T>) {

21
ui-ngx/src/app/shared/components/markdown.component.html

@ -1,21 +0,0 @@
<!--
Copyright © 2016-2021 The Thingsboard Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<ng-container #markdownContainer>
<markdown *ngIf="!isMarkdownReady" #markdownComponent [data]="data"
[lineNumbers]="lineNumbers" (ready)="onMarkdownReady()"></markdown>
</ng-container>

20
ui-ngx/src/app/shared/components/markdown.component.scss

@ -1,20 +0,0 @@
/**
* Copyright © 2016-2021 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
:host {
markdown {
display: none;
}
}

93
ui-ngx/src/app/shared/components/markdown.component.ts

@ -15,6 +15,7 @@
/// ///
import { import {
ChangeDetectorRef,
Component, Component,
ComponentFactory, ComponentFactory,
ComponentRef, ComponentRef,
@ -22,38 +23,31 @@ import {
Inject, Inject,
Injector, Injector,
Input, OnChanges, Input, OnChanges,
OnDestroy,
OnInit,
Output, Output,
Renderer2, SimpleChanges, SimpleChanges,
Type, Type, ViewChild,
ViewChild,
ViewContainerRef ViewContainerRef
} from '@angular/core'; } from '@angular/core';
import { HelpService } from '@core/services/help.service'; import { HelpService } from '@core/services/help.service';
import { MarkdownComponent } from 'ngx-markdown'; import { MarkdownService, PrismPlugin } from 'ngx-markdown';
import { DynamicComponentFactoryService } from '@core/services/dynamic-component-factory.service'; import { DynamicComponentFactoryService } from '@core/services/dynamic-component-factory.service';
import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { SHARED_MODULE_TOKEN } from '@shared/components/tokens'; import { SHARED_MODULE_TOKEN } from '@shared/components/tokens';
@Component({ @Component({
selector: 'tb-markdown', selector: 'tb-markdown',
templateUrl: './markdown.component.html', template: '<ng-container #markdownContainer>' +
styleUrls: ['./markdown.component.scss'] '</ng-container>' +
'<div *ngIf="error" style="color: #f00; font-size: 14px;' +
' line-height: 28px;' +
' background: #efefef;">' +
'{{error}}' +
'</div>'
}) })
export class TbMarkdownComponent implements OnDestroy, OnInit, OnChanges { export class TbMarkdownComponent implements OnChanges {
private markdownComponent: MarkdownComponent;
@ViewChild('markdownContainer', {read: ViewContainerRef, static: true}) markdownContainer: ViewContainerRef; @ViewChild('markdownContainer', {read: ViewContainerRef, static: true}) markdownContainer: ViewContainerRef;
@ViewChild('markdownComponent', {static: false}) set content(content: MarkdownComponent) {
this.markdownComponent = content;
if (this.isMarkdownReady && this.markdownComponent) {
this.processMarkdownComponent();
}
}
@Input() data: string | undefined; @Input() data: string | undefined;
@Input() markdownClass: string | undefined; @Input() markdownClass: string | undefined;
@ -70,35 +64,25 @@ export class TbMarkdownComponent implements OnDestroy, OnInit, OnChanges {
isMarkdownReady = false; isMarkdownReady = false;
error = null;
private tbMarkdownInstanceComponentRef: ComponentRef<any>; private tbMarkdownInstanceComponentRef: ComponentRef<any>;
private tbMarkdownInstanceComponentFactory: ComponentFactory<any>; private tbMarkdownInstanceComponentFactory: ComponentFactory<any>;
constructor(private help: HelpService, constructor(private help: HelpService,
private renderer: Renderer2, private cd: ChangeDetectorRef,
public markdownService: MarkdownService,
@Inject(SHARED_MODULE_TOKEN) private sharedModule: Type<any>, @Inject(SHARED_MODULE_TOKEN) private sharedModule: Type<any>,
private dynamicComponentFactoryService: DynamicComponentFactoryService) {} private dynamicComponentFactoryService: DynamicComponentFactoryService) {}
ngOnInit(): void {
}
ngOnDestroy(): void {
}
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
for (const propName of Object.keys(changes)) { if (this.data) {
const change = changes[propName]; this.render(this.data);
if (!change.firstChange && change.currentValue !== change.previousValue) {
if (propName === 'data') {
if (this.data) {
this.isMarkdownReady = false;
}
}
}
} }
} }
private processMarkdownComponent() { private render(markdown: string) {
let template = this.markdownComponent.element.nativeElement.innerHTML; let template = this.markdownService.compile(markdown, false);
template = this.sanitizeCurlyBraces(template); template = this.sanitizeCurlyBraces(template);
let markdownClass = 'tb-markdown-view'; let markdownClass = 'tb-markdown-view';
if (this.markdownClass) { if (this.markdownClass) {
@ -106,7 +90,6 @@ export class TbMarkdownComponent implements OnDestroy, OnInit, OnChanges {
} }
template = `<div [ngStyle]="style" class="${markdownClass}">${template}</div>`; template = `<div [ngStyle]="style" class="${markdownClass}">${template}</div>`;
this.markdownContainer.clear(); this.markdownContainer.clear();
this.markdownComponent = null;
const parent = this; const parent = this;
this.dynamicComponentFactoryService.createDynamicComponentFactory( this.dynamicComponentFactoryService.createDynamicComponentFactory(
class TbMarkdownInstance { class TbMarkdownInstance {
@ -124,13 +107,38 @@ export class TbMarkdownComponent implements OnDestroy, OnInit, OnChanges {
this.tbMarkdownInstanceComponentRef = this.tbMarkdownInstanceComponentRef =
this.markdownContainer.createComponent(this.tbMarkdownInstanceComponentFactory, 0, injector); this.markdownContainer.createComponent(this.tbMarkdownInstanceComponentFactory, 0, injector);
this.tbMarkdownInstanceComponentRef.instance.style = this.style; this.tbMarkdownInstanceComponentRef.instance.style = this.style;
} catch (e) { this.handlePlugins(this.tbMarkdownInstanceComponentRef.location.nativeElement);
this.markdownService.highlight(this.tbMarkdownInstanceComponentRef.location.nativeElement);
this.error = null;
} catch (error) {
this.error = (error ? error + '' : 'Failed to render markdown!').replace(/\n/g, '<br>');
this.destroyMarkdownInstanceResources(); this.destroyMarkdownInstanceResources();
} }
this.cd.detectChanges();
this.ready.emit();
},
(error) => {
this.error = (error ? error + '' : 'Failed to render markdown!').replace(/\n/g, '<br>');
this.destroyMarkdownInstanceResources();
this.cd.detectChanges();
this.ready.emit(); this.ready.emit();
}); });
} }
private handlePlugins(element: HTMLElement): void {
if (this.lineNumbers) {
this.setPluginClass(element, PrismPlugin.LineNumbers);
}
}
private setPluginClass(element: HTMLElement, plugin: string | string[]): void {
const preElements = element.querySelectorAll('pre');
for (let i = 0; i < preElements.length; i++) {
const classes = plugin instanceof Array ? plugin : [plugin];
preElements.item(i).classList.add(...classes);
}
}
private sanitizeCurlyBraces(template: string): string { private sanitizeCurlyBraces(template: string): string {
return template.replace(/{/g, '&#123;').replace(/}/g, '&#125;'); return template.replace(/{/g, '&#123;').replace(/}/g, '&#125;');
} }
@ -142,13 +150,4 @@ export class TbMarkdownComponent implements OnDestroy, OnInit, OnChanges {
} }
this.tbMarkdownInstanceComponentRef = null; this.tbMarkdownInstanceComponentRef = null;
} }
onMarkdownReady() {
if (this.data) {
this.isMarkdownReady = true;
if (this.markdownComponent) {
this.processMarkdownComponent();
}
}
}
} }

4
ui-ngx/src/styles.scss

@ -516,12 +516,12 @@ mat-label {
} }
p, div { p, div {
padding-right: 32px;
color: rgba(15, 22, 29, 0.8); color: rgba(15, 22, 29, 0.8);
line-height: 1.5em; line-height: 1.5em;
} }
p, div { & > p, & > div {
padding-right: 32px;
padding-left: 32px; padding-left: 32px;
} }

Loading…
Cancel
Save