Skip to content
This repository has been archived by the owner on Aug 27, 2024. It is now read-only.

feat(demo-app): update meta data for site #60

Merged
merged 8 commits into from
Jan 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions apps/chill-viking-ng-libs/src/app/page-meta-data.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { Meta, MetaDefinition, Title } from '@angular/platform-browser';
import { BrowserTestingModule } from '@angular/platform-browser/testing';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { MockProvider } from 'ng-mocks';
import { PageMetaDataService } from './page-meta-data.service';

describe('PageMetaDataService', () => {
let titleSpy: Title;
let metaSpy: Meta;
let service: PageMetaDataService;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule, BrowserTestingModule],
providers: [
PageMetaDataService,
MockProvider(Title, { setTitle: jest.fn() }),
MockProvider(Meta, { updateTag: jest.fn() }),
],
}).compileComponents();

titleSpy = TestBed.inject(Title);
metaSpy = TestBed.inject(Meta);
service = TestBed.inject(PageMetaDataService);
});

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

const createActivatedSnapshot = ({
outlet = 'primary',
...val
}: Partial<ActivatedRouteSnapshot>): ActivatedRouteSnapshot =>
({ outlet, ...val } as ActivatedRouteSnapshot);

const createRouterStateSnapshot = (
val: Partial<RouterStateSnapshot>,
): RouterStateSnapshot => val as RouterStateSnapshot;

describe('updateTitle', () => {
let snapshot: RouterStateSnapshot;
let updateMetaSpy: jest.SpiedFunction<(v: RouterStateSnapshot) => void>;

beforeEach(() => {
snapshot = createRouterStateSnapshot({
root: createActivatedSnapshot({
children: [
createActivatedSnapshot({
title: 'First',
children: [
createActivatedSnapshot({
title: 'Second',
children: [createActivatedSnapshot({ title: 'Third' })],
}),
],
}),
],
}),
});

updateMetaSpy = jest.spyOn(service, 'updateMeta');
updateMetaSpy.mockImplementation(() => {
/* do nothing */
});
});

it('should set correct title', async () => {
service.updateTitle(snapshot);
expect(titleSpy.setTitle).toHaveBeenCalledWith(
'Third | Second | First | Chill Viking | ng-libs',
);
});

it('should call updateMeta', () => {
service.updateTitle(snapshot);
expect(updateMetaSpy).toHaveBeenCalledWith(snapshot);
});
});

describe('updateMeta', () => {
let snapshot: RouterStateSnapshot;
let updateTagSpy: jest.SpiedFunction<
(tag: MetaDefinition, selector?: string) => HTMLMetaElement | null
>;

beforeEach(() => {
updateTagSpy = jest.spyOn(metaSpy, 'updateTag');
});

it('should use meta from current activated route data', async () => {
snapshot = createRouterStateSnapshot({
root: createActivatedSnapshot({
children: [
createActivatedSnapshot({
children: [
createActivatedSnapshot({
data: {
metaTags: {
description: 'Third description',
other: 'other tag',
},
},
}),
],
}),
],
}),
});

service.updateMeta(snapshot);
expect(updateTagSpy).toHaveBeenCalledWith({
name: 'description',
content: 'Third description',
});
expect(updateTagSpy).toHaveBeenCalledWith({
name: 'other',
content: 'other tag',
});
});

describe('when no metaTags available', () => {
it('should do nothing', () => {
snapshot = createRouterStateSnapshot({
root: createActivatedSnapshot({
children: [
createActivatedSnapshot({
data: {},
}),
],
}),
});

service.updateMeta(snapshot);
expect(updateTagSpy).not.toHaveBeenCalled();
});
});
});
});
64 changes: 64 additions & 0 deletions apps/chill-viking-ng-libs/src/app/page-meta-data.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { Injectable } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import {
ActivatedRouteSnapshot,
RouterStateSnapshot,
TitleStrategy,
} from '@angular/router';

@Injectable()
export class PageMetaDataService extends TitleStrategy {
constructor(private readonly _title: Title, private readonly _meta: Meta) {
super();
}

private getPrimaryNavigationChildren({
root,
}: Partial<RouterStateSnapshot>): ActivatedRouteSnapshot[] {
const result: ActivatedRouteSnapshot[] = [];
let primarySnapshot = root?.children.find((c) => c.outlet === 'primary');
while (primarySnapshot) {
result.push(primarySnapshot);
primarySnapshot = primarySnapshot.children?.find(
(c) => c.outlet === 'primary',
);
}

return result;
}

private resolveChildTitles(
activatedRootSnapshot: ActivatedRouteSnapshot,
): string[] {
return this.getPrimaryNavigationChildren({ root: activatedRootSnapshot })
.map((snapshot) => snapshot.title ?? '')
.filter((title) => title !== '');
}

private makeCurrentTitleFirst(...arr: string[]): string[] {
return [...arr].reverse();
}

updateMeta(snapshot: RouterStateSnapshot): void {
const routes = this.getPrimaryNavigationChildren(snapshot);
if (routes.length === 0) return;

const data = routes[routes.length - 1].data;
if (data === undefined || data['metaTags'] === undefined) return;

const metaTags = data['metaTags'];
for (const name in metaTags) {
this._meta.updateTag({ name, content: metaTags[name] });
}
}

override updateTitle(snapshot: RouterStateSnapshot): void {
const titles = this.makeCurrentTitleFirst(
'Chill Viking | ng-libs',
...this.resolveChildTitles(snapshot.root),
);
this._title.setTitle(titles.join(' | '));

this.updateMeta(snapshot);
}
}

This file was deleted.

41 changes: 0 additions & 41 deletions apps/chill-viking-ng-libs/src/app/page-title-strategy.service.ts

This file was deleted.

1 change: 1 addition & 0 deletions apps/chill-viking-ng-libs/src/app/pages/home.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './home/home.component';
51 changes: 25 additions & 26 deletions apps/chill-viking-ng-libs/src/app/pages/home/home.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,37 @@
<ng-template cvHeader let-header>
<ng-libs-header [context]="header" [subTitle$]="subTitle$"></ng-libs-header>
</ng-template>
<section id="overview">
<section id="welcome">
<div class="section-title">
<h1>Overview</h1>
<h1>Welcome 👋</h1>
</div>
<div class="introduction">
<span class="question">
Are you tired of tackling common Angular development challenges on your
own?
</span>

<div class="cta">
<!-- To be added after packages page created
<ng-libs-cta [title]="'View available packages'" (clicked)='goToPackages()'></ng-libs-cta>
-->
<ng-libs-cta (clicked)="goToRepository()" type="secondary">
<mat-icon>open_in_new</mat-icon>
<span>Visit Repository</span>
</ng-libs-cta>
<ng-libs-cta (clicked)="goToDiscussions()" type="secondary">
<mat-icon>open_in_new</mat-icon>
<span>Ask Us a Question</span>
</ng-libs-cta>
</div>
<div class="section-body">
<p>
Welcome to the Chill Viking <code>ng-libs</code> repository! Here,
you'll find a variety of high-quality npm packages for Angular projects.
</p>
<p>
Chill Viking, more specifically this repository, is here to help! Using
this repository, we aim to create npm packages that solve problems and
make your life easier.
Our packages are easy to use and constantly updated to ensure
compatibility with the latest version of Angular.
</p>
<p>
Check out our offerings and see how we can help you become an Angular
pro.
Explore our packages and see how they can benefit your projects. We hope
you'll join our community and stay up-to-date on the latest
developments.
</p>
<div class="cta">
<!-- To be added after packages page created
<ng-libs-cta [title]="'View available packages'" (clicked)='goToPackages()'></ng-libs-cta>
-->
<ng-libs-cta (clicked)="goToRepository()" type="secondary">
<mat-icon>open_in_new</mat-icon>
<span>Visit Repository</span>
</ng-libs-cta>
<ng-libs-cta (clicked)="goToDiscussions()" type="secondary">
<mat-icon>open_in_new</mat-icon>
<span>Ask Us a Question</span>
</ng-libs-cta>
</div>
</div>
</section>
</cv-layout>
Loading