Skip to content

Commit

Permalink
Merged in DSC-1401-cherry-pick-UXP-114-maintenance (pull request DSpa…
Browse files Browse the repository at this point in the history
…ce#1575)

DSC-1401 cherry pick UXP 114 maintenance

Approved-by: Giuseppe Digilio
  • Loading branch information
Andrea Barbasso authored and atarix83 committed Apr 19, 2024
2 parents a56e444 + 9467f4e commit 149fc49
Show file tree
Hide file tree
Showing 28 changed files with 408 additions and 209 deletions.
105 changes: 105 additions & 0 deletions src/app/core/shared/client-math.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { DOCUMENT } from '@angular/common';
import {
Inject,
Injectable,
} from '@angular/core';
import { Observable, ReplaySubject, Subject } from 'rxjs';
import { environment } from 'src/environments/environment';
import {
NativeWindowRef,
NativeWindowService,
} from '../services/window.service';import { MathJaxConfig, MathService } from './math.service';

@Injectable({
providedIn: 'root'
})
/**
* Provide the MathService for CSR
*/
export class ClientMathService extends MathService {

protected isReady$: Subject<boolean>;

protected mathJaxOptions = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
},
svg: {
fontCache: 'global'
},
startup: {
typeset: false
}
};

protected mathJax: MathJaxConfig = {
source: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js',
id: 'MathJaxScript'
};
protected mathJaxFallback: MathJaxConfig = {
source: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-chtml.min.js',
id: 'MathJaxBackupScript'
};

constructor(
@Inject(DOCUMENT) private _document: Document,
@Inject(NativeWindowService) protected _window: NativeWindowRef,
) {
super();

this.isReady$ = new ReplaySubject<boolean>();

void this.registerMathJaxAsync(this.mathJax)
.then(() => this.isReady$.next(true))
.catch(_ => {
void this.registerMathJaxAsync(this.mathJaxFallback)
.then(() => this.isReady$.next(true));
});
}

/**
* Register the specified MathJax script in the document
*
* @param config The configuration object for the script
*/
protected async registerMathJaxAsync(config: MathJaxConfig): Promise<any> {
if (environment.markdown.mathjax) {
return new Promise<void>((resolve, reject) => {

const optionsScript: HTMLScriptElement = this._document.createElement('script');
optionsScript.type = 'text/javascript';
optionsScript.text = `MathJax = ${JSON.stringify(this.mathJaxOptions)};`;
this._document.head.appendChild(optionsScript);

const script: HTMLScriptElement = this._document.createElement('script');
script.id = config.id;
script.type = 'text/javascript';
script.src = config.source;
script.crossOrigin = 'anonymous';
script.async = true;
script.onload = () => resolve();
script.onerror = error => reject(error);
this._document.head.appendChild(script);
});
}
return Promise.resolve();
}

/**
* Return the status of the script registration
*/
ready(): Observable<boolean> {
return this.isReady$;
}

/**
* Render the specified element using the MathJax JavaScript
*
* @param element The element to render with MathJax
*/
render(element: HTMLElement) {
if (environment.markdown.mathjax) {
this._window.nativeWindow.MathJax.typesetPromise([element]);
}
}
}
47 changes: 47 additions & 0 deletions src/app/core/shared/math.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { TestBed } from '@angular/core/testing';
import { Observable, of } from 'rxjs';
import { MathService, MathJaxConfig } from './math.service';

export class MockMathService extends MathService {
protected mathJaxOptions: any = {};
protected mathJax: MathJaxConfig = { source: '', id: '' };
protected mathJaxFallback: MathJaxConfig = { source: '', id: '' };

protected registerMathJaxAsync(config: MathJaxConfig): Promise<any> {
return Promise.resolve();
}

ready(): Observable<boolean> {
return of(true);
}

render(element: HTMLElement): void {
return;
}
}

describe('MathService', () => {
let service: MockMathService;

beforeEach(() => {
TestBed.configureTestingModule({});
service = new MockMathService();
spyOn(service, 'render');
});

it('should be created', () => {
expect(service).toBeTruthy();
});

it('should be ready', (done) => {
service.ready().subscribe(isReady => {
expect(isReady).toBe(true);
done();
});
});

it('should render', () => {
service.render(document.createElement('div'));
expect(service.render).toHaveBeenCalled();
});
});
19 changes: 19 additions & 0 deletions src/app/core/shared/math.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Observable } from 'rxjs';

export interface MathJaxConfig {
source: string;
id: string;
}

/**
* This service is used to provide the MathJax library with the ability to render markdown code
*/
export abstract class MathService {
protected abstract mathJaxOptions: any;
protected abstract mathJax: MathJaxConfig;
protected abstract mathJaxFallback: MathJaxConfig;

protected abstract registerMathJaxAsync(config: MathJaxConfig): Promise<any>;
abstract ready(): Observable<boolean>;
abstract render(element: HTMLElement): void;
}
44 changes: 44 additions & 0 deletions src/app/core/shared/server-math.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Injectable } from '@angular/core';
import { Observable, ReplaySubject, Subject } from 'rxjs';
import { MathJaxConfig, MathService } from './math.service';

@Injectable({
providedIn: 'root'
})
/**
* Provide the MathService for SSR
*/
export class ServerMathService extends MathService {

protected signal: Subject<boolean>;

protected mathJaxOptions = {};

protected mathJax: MathJaxConfig = {
source: '',
id: ''
};
protected mathJaxFallback: MathJaxConfig = {
source: '',
id: ''
};

constructor() {
super();

this.signal = new ReplaySubject<boolean>();
this.signal.next(true);
}

protected async registerMathJaxAsync(config: MathJaxConfig): Promise<any> {
return Promise.resolve();
}

ready(): Observable<boolean> {
return this.signal;
}

render(element: HTMLElement) {
return;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

<!-- Render value as markdown -->
<ng-template #markdown let-value="value">
<span class="dont-break-out" [innerHTML]="value | dsMarkdown | async">
<span class="dont-break-out" [dsMarkdown]="value">
</span>
</ng-template>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class MetadataValuesComponent implements OnChanges {
@Input() label: string;

/**
* Whether the {@link MarkdownPipe} should be used to render these metadata values.
* Whether the {@link MarkdownDirective} should be used to render these metadata values.
* This will only have effect if {@link MarkdownConfig#enabled} is true.
* Mathjax will only be rendered if {@link MarkdownConfig#mathjax} is true.
*/
Expand Down
3 changes: 3 additions & 0 deletions src/app/item-page/item-page.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ import { ThemedItemAlertsComponent } from './alerts/themed-item-alerts.component
import {
ThemedFullFileSectionComponent
} from './full/field-components/file-section/themed-full-file-section.component';
import { MarkdownViewerModule } from '../shared/markdown-viewer/markdown-viewer.module';


const ENTRY_COMPONENTS = [
// put only entry components that use custom decorator
Expand Down Expand Up @@ -123,6 +125,7 @@ const DECLARATIONS = [
CrisItemPageModule,
ContextMenuModule.withEntryComponents(),
MiradorViewerModule,
MarkdownViewerModule,
],
declarations: [
...DECLARATIONS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class ItemPageAbstractFieldComponent extends ItemPageFieldComponent {
label = 'item.page.abstract';

/**
* Use the {@link MarkdownPipe} to render dc.description.abstract values
* Use the {@link MarkdownDirective} to render dc.description.abstract values
*/
enableMarkdown = true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class GenericItemPageFieldComponent extends ItemPageFieldComponent {
@Input() label: string;

/**
* Whether the {@link MarkdownPipe} should be used to render this metadata.
* Whether the {@link MarkdownDirective} should be used to render this metadata.
*/
@Input() enableMarkdown = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ import { MetadataMap, MetadataValue } from '../../../../core/shared/metadata.mod
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { createPaginatedList } from '../../../../shared/testing/utils.test';
import { environment } from '../../../../../environments/environment';
import { MarkdownPipe } from '../../../../shared/utils/markdown.pipe';
import { SharedModule } from '../../../../shared/shared.module';
import { APP_CONFIG } from '../../../../../config/app-config.interface';
import { By } from '@angular/platform-browser';
import { BrowseDefinitionDataService } from '../../../../core/browse/browse-definition-data.service';
import { BrowseDefinitionDataServiceStub } from '../../../../shared/testing/browse-definition-data-service.stub';
import { RouterTestingModule } from '@angular/router/testing';
import { MarkdownDirective } from '../../../../shared/utils/markdown.directive';
import { MathService } from '../../../../core/shared/math.service';

let comp: ItemPageFieldComponent;
let fixture: ComponentFixture<ItemPageFieldComponent>;
Expand Down Expand Up @@ -51,14 +52,15 @@ describe('ItemPageFieldComponent', () => {
],
providers: [
{ provide: APP_CONFIG, useValue: appConfig },
{ provide: BrowseDefinitionDataService, useValue: BrowseDefinitionDataServiceStub }
{ provide: BrowseDefinitionDataService, useValue: BrowseDefinitionDataServiceStub },
{ provide: MathService, useValue: {} }
],
declarations: [ItemPageFieldComponent, MetadataValuesComponent],
schemas: [NO_ERRORS_SCHEMA]
}).overrideComponent(ItemPageFieldComponent, {
set: { changeDetection: ChangeDetectionStrategy.Default }
}).compileComponents();
markdownSpy = spyOn(MarkdownPipe.prototype, 'transform');
markdownSpy = spyOn(MarkdownDirective.prototype, 'render');
fixture = TestBed.createComponent(ItemPageFieldComponent);
comp = fixture.componentInstance;
comp.item = mockItemWithMetadataFieldsAndValue(mockFields, mockValue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class ItemPageFieldComponent {
@Input() item: Item;

/**
* Whether the {@link MarkdownPipe} should be used to render this metadata.
* Whether the {@link MarkdownDirective} should be used to render this metadata.
*/
enableMarkdown = false;

Expand Down
10 changes: 6 additions & 4 deletions src/app/shared/explore/explore.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { ThemedSearchSectionComponent } from './section-component/search-section
import { TextSectionComponent } from './section-component/text-section/text-section.component';
import { ThemedTextSectionComponent } from './section-component/text-section/themed-text-section.component';
import { SharedModule } from '../shared.module';
import { MarkdownViewerModule } from '../markdown-viewer/markdown-viewer.module';

const COMPONENTS = [
BrowseSectionComponent,
Expand All @@ -42,10 +43,11 @@ const COMPONENTS = [
declarations: [
...COMPONENTS
],
imports: [
CommonModule,
SharedModule
],
imports: [
CommonModule,
SharedModule,
MarkdownViewerModule
],
exports: [
...COMPONENTS
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
<div *ngSwitchCase="'image'"><img [src]="textRowSection.content" style="width: 100%"></div>
<div *ngSwitchCase="'text-key'">{{ ('explore.text-section.' + textRowSection.content) | translate }}</div>
<div *ngSwitchCase="'text-raw'">{{ textRowSection.content }}</div>
<div *ngSwitchCase="'text-metadata'" [innerHTML]="metadataValue(textRowSection.content)" [class.text-section-home-news]="textRowSection.content === 'cris.cms.home-news'"></div>
<div *ngSwitchCase="'text-metadata'" [class.text-section-home-news]="textRowSection.content === 'cris.cms.home-news'">
<ds-markdown-viewer data-test="ds-markdown-viewer"
[value]="metadataValue(textRowSection.content)"></ds-markdown-viewer>
</div>
<div *ngSwitchCase="'custom'">
<ng-container *ngTemplateOutlet="custom"></ng-container>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ describe('TextSectionComponent', () => {
expect(component).toBeTruthy();
});
// FIXME: complete scenarios
it('should render text-metadata with innerHtml', () => {
it('should render text-metadata with ds-markdown-viewer', () => {
component.sectionId = 'site';
fixture.detectChanges();
const name = fixture.debugElement.queryAll(By.css('div'))[0].nativeElement;
expect(name.innerHTML).toContain(component.site.metadata['cms.homepage.footer'][0].value);
const dsMarkdownViewer = fixture.debugElement.query(By.css('[data-test="ds-markdown-viewer"]'));
expect(dsMarkdownViewer).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -1 +1 @@
<nu-markdown-preview [value]="value"></nu-markdown-preview>
<span [dsMarkdown]="value"></span>
Loading

0 comments on commit 149fc49

Please sign in to comment.