Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat rerender markdown #274

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,14 @@ This code will output the following HTML:

> :blue_book: Follow official [marked.renderer](https://marked.js.org/#/USING_PRO.md#renderer) documentation for the list of tokens that can be overriden.

## Re-render Markdown

You might need to re-render Markdown after making a change. If you've updated the text, this would be done automatically however if the change is internal to Markdown such as it's settings, you will need to inform Markdown to update.

`this.markdownService.reload()`

Click [here](/rerender) to view demo.

## Syntax highlight

When using static markdown you are responsible to provide the code block with related language.
Expand Down
5 changes: 5 additions & 0 deletions demo/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MarkdownRerenderComponent } from './markdown-rerender/markdown-rerender.component';

const routes: Routes = [
{
path: 'get-started',
loadChildren: () => import('./get-started/get-started.module').then(m => m.GetStartedModule),
data: { label: 'Get Started' },
},
{
path: 'rerender',
component: MarkdownRerenderComponent
},
{
path: 'cheat-sheet',
loadChildren: () => import('./cheat-sheet/cheat-sheet.module').then(m => m.CheatSheetModule),
Expand Down
5 changes: 4 additions & 1 deletion demo/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { AnchorService } from '@shared/anchor/anchor.service';
import { SharedModule } from '@shared/shared.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MarkdownRerenderComponent } from './markdown-rerender/markdown-rerender.component';
import { FormsModule } from '@angular/forms';

export function markedOptionsFactory(anchorService: AnchorService): MarkedOptions {
const renderer = new MarkedRenderer();
Expand Down Expand Up @@ -44,8 +46,9 @@ export function markedOptionsFactory(anchorService: AnchorService): MarkedOption
MatTabsModule,
MatToolbarModule,
SharedModule,
FormsModule,
],
declarations: [AppComponent],
declarations: [AppComponent, MarkdownRerenderComponent],
bootstrap: [AppComponent],
})
export class AppModule { }
24 changes: 24 additions & 0 deletions demo/src/app/markdown-rerender/markdown-rerender.component.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
.input-container {
margin-bottom: 10px;
}

.input-container > b {
margin-right: 10px;
}

textarea {
width: 30vw;
height: 60vh;
}

.markdown-container {
display: flex;
}

.variable-binding {
margin-left: 10px;
}

::ng-deep .variable-binding h2 {
margin-top: 0 !important;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<div class="input-container">
<b>CSS Color:</b>
<input [(ngModel)]="accentColor" placeholder="Ex: red, blue, #00a, etc." />
</div>
<div class="markdown-container">
<textarea class="variable-textarea" [(ngModel)]="markdown"></textarea>
<markdown class="variable-binding" [data]="markdown"></markdown>
</div>
25 changes: 25 additions & 0 deletions demo/src/app/markdown-rerender/markdown-rerender.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { MarkdownRerenderComponent } from './markdown-rerender.component';

describe('MarkdownRerenderComponent', () => {
let component: MarkdownRerenderComponent;
let fixture: ComponentFixture<MarkdownRerenderComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MarkdownRerenderComponent ]
})
.compileComponents();
});

beforeEach(() => {
fixture = TestBed.createComponent(MarkdownRerenderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
64 changes: 64 additions & 0 deletions demo/src/app/markdown-rerender/markdown-rerender.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { Component, OnInit } from '@angular/core';
import { MarkdownService } from 'ngx-markdown';

@Component({
selector: 'app-markdown-rerender',
templateUrl: './markdown-rerender.component.html',
styleUrls: ['./markdown-rerender.component.css']
})
export class MarkdownRerenderComponent implements OnInit {

private _accentColor = "";
private readonly ZERO_WIDTH_SPACE = "​"; // This is NOT an empty string!

get accentColor() {
return this._accentColor;
}
set accentColor(value: string) {
if (this._accentColor === value) {
return;
}

this._accentColor = value;
this.changeAccentColor();
}

constructor(
private markdownService: MarkdownService
) {}

ngOnInit() {
this.changeAccentColor();
}

private changeAccentColor() {
const styleAttribute = this.accentColor
? ` style="color: ${this.accentColor}"`
: "";
this.markdownService.renderer.heading = (text: string, level: number) => {
return `<h${level}${styleAttribute}>${text}</h${level}>`;
};
/*this.markdown += this.ZERO_WIDTH_SPACE;
setTimeout(
() => (this.markdown = this.markdown.replace(this.ZERO_WIDTH_SPACE, ""))
);*/
this.markdownService.reload();
}

markdown = `## Markdown __rulez__!
---

### Syntax highlight
\`\`\`typescript
const language = 'typescript';
\`\`\`

### Lists
1. Ordered list
2. Another bullet point
- Unordered list
- Another unordered bullet point

### Blockquote
> Blockquote to the max`;
}
9 changes: 9 additions & 0 deletions lib/src/markdown.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,15 @@ describe('MarkdownComponent', () => {

expect(component.render).not.toHaveBeenCalled();
});

it('should rerender content on demand', () => {

spyOn(component, 'loadContent');

markdownService.reload();

expect(component.loadContent).toHaveBeenCalled();
});
});

describe('render', () => {
Expand Down
8 changes: 8 additions & 0 deletions lib/src/markdown.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ export class MarkdownComponent implements OnChanges, AfterViewInit {
) { }

ngOnChanges(): void {
this.loadContent();
}

loadContent(): void {
if (this.data != null) {
this.handleData();
return;
Expand All @@ -73,6 +77,10 @@ export class MarkdownComponent implements OnChanges, AfterViewInit {
if (!this.data && !this.src) {
this.handleTransclusion();
}

this.markdownService._trigger$.subscribe(() => {
this.loadContent();
});
}

render(markdown: string, decodeHtml = false): void {
Expand Down
12 changes: 12 additions & 0 deletions lib/src/markdown.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,18 @@ describe('MarkdowService', () => {
});
});

describe('re-render markdown', () => {

it('should request reload fn', () => {

markdownService._trigger$.subscribe(res => {
expect(res).toBe(1);
});

markdownService.reload();
});
});

describe('compile', () => {

it('should return parsed markdown correctly', () => {
Expand Down
8 changes: 7 additions & 1 deletion lib/src/markdown.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { HttpClient } from '@angular/common/http';
import { Inject, Injectable, InjectionToken, Optional, PLATFORM_ID, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import * as marked from 'marked';
import { Observable } from 'rxjs';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';

import { KatexOptions } from './katex-options';
Expand Down Expand Up @@ -33,6 +33,8 @@ export const SECURITY_CONTEXT = new InjectionToken<SecurityContext>('SECURITY_CO
@Injectable()
export class MarkdownService {

_trigger$ = new Subject();

private readonly initialMarkedOptions: MarkedOptions = {
renderer: new MarkedRenderer(),
};
Expand Down Expand Up @@ -67,6 +69,10 @@ export class MarkdownService {
return this.sanitizer.sanitize(this.securityContext, compiled) || '';
}

reload(): void {
this._trigger$.next(1);
}

getSource(src: string): Observable<string> {
if (!this.http) {
throw new Error(errorSrcWithoutHttpClient);
Expand Down