feat(challenge): create challenge 32 about bug CD

This commit is contained in:
ThomasL
2023-07-25 16:29:49 +02:00
parent 2dc2fd7dfd
commit 9799c4c1e7
22 changed files with 431 additions and 1 deletions

View File

@@ -47,6 +47,7 @@ If you would like to propose a challenge, this project is open source, so feel f
<a href="./apps/router-input/README.md"><img src="https://img.shields.io/badge/22-router--input-green" alt="router-input"/></a> <a href="./apps/router-input/README.md"><img src="https://img.shields.io/badge/22-router--input-green" alt="router-input"/></a>
<a href="./apps/interop-rxjs-signal/README.md"><img src="https://img.shields.io/badge/30-interop rxjs signal-red" alt="interop signal rxjs"/></a> <a href="./apps/interop-rxjs-signal/README.md"><img src="https://img.shields.io/badge/30-interop rxjs signal-red" alt="interop signal rxjs"/></a>
<a href="./apps/module-to-standalone/README.md"><img src="https://img.shields.io/badge/31-module to standalone-green" alt="module to standalone"/></a> <a href="./apps/module-to-standalone/README.md"><img src="https://img.shields.io/badge/31-module to standalone-green" alt="module to standalone"/></a>
<a href="./apps/bug-cd/README.md"><img src="https://img.shields.io/badge/32-bug CD-orange" alt="bug CD"/></a>
</br> </br>
<img src="https://img.shields.io/badge/Typescript--gray?logo=typescript" alt="Typescript"/> <img src="https://img.shields.io/badge/Typescript--gray?logo=typescript" alt="Typescript"/>
@@ -94,7 +95,7 @@ If you would like to propose a challenge, this project is open source, so feel f
<table> <table>
<tbody> <tbody>
<tr> <tr>
<td align="center" valign="top" width="14.28%"><a href="https://medium.com/@thomas.laforge"><img src="https://avatars.githubusercontent.com/u/30832608?s…00&u=6f0ad9676792f29fd7fe6e113df06213d384a813&v=4" width="100px;" alt="Thomas Laforge"/><br /><sub><b>Thomas Laforge</b></sub></a><br />31 🧩</a></td> <td align="center" valign="top" width="14.28%"><a href="https://medium.com/@thomas.laforge"><img src="https://avatars.githubusercontent.com/u/30832608?s…00&u=6f0ad9676792f29fd7fe6e113df06213d384a813&v=4" width="100px;" alt="Thomas Laforge"/><br /><sub><b>Thomas Laforge</b></sub></a><br />32 🧩</a></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

@@ -0,0 +1,36 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
]
},
"extends": [
"plugin:@nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
]
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}

38
apps/bug-cd/README.md Normal file
View File

@@ -0,0 +1,38 @@
<h1>Bug Change Detection</h1>
> Author: Thomas Laforge
This challenge is inspired by a real-life example that I simplified to create this nice challenge.
### Information
In this small application, we have a navigation menu to route our application to either `barComponent` or `FooComponent`. However our application is not loading and no errors are displayed inside the console.
### Statement
The goal of the challenge is to debug this application and make it work.
#### Hint 1
If you comment out `routerLinkActive="isSelected"` inside `NavigationComponent`: the application loads correctly.
#### Hint 2
If you open the [`RouterLinkActive` source code](https://github.com/angular/angular/blob/main/packages/router/src/directives/router_link_active.ts) and go to **line 196**, Angular is calling `this.cdr.markForCheck` inside a microTask which triggers a new CD cycle. If you comment out this line, the application loads again, however the bug is not inside the Angular Framework. 😅😯
### Submitting your work
1. Fork the project
2. clone it
3. npm ci
4. `npx nx serve bug-cd`
5. _...work on it_
6. Commit your work
7. Submit a PR with a title beginning with **Answer:32** that I will review and other dev can review.
<a href="https://github.com/tomalaforge/angular-challenges/pulls?q=label%3A32+label%3Aanswer"><img src="https://img.shields.io/badge/-Solutions-green" alt="bug-cd"/></a>
<a href='https://github.com/tomalaforge/angular-challenges/pulls?q=label%3A32+label%3A"answer+author"'><img src="https://img.shields.io/badge/-Author solution-important" alt="bug-cd solution author"/></a>
<!-- <a href="{Blog post url}" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/-Blog post explanation-blue" alt="bug-cd blog article"/></a> -->
_You can ask any question on_ <a href="https://twitter.com/laforge_toma" target="_blank" rel="noopener noreferrer"><img src="./../../logo/twitter.svg" height=20px alt="twitter"/></a>

View File

@@ -0,0 +1,22 @@
/* eslint-disable */
export default {
displayName: 'bug-cd',
preset: '../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
coverageDirectory: '../../coverage/apps/bug-cd',
transform: {
'^.+\\.(ts|mjs|js|html)$': [
'jest-preset-angular',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
],
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
};

89
apps/bug-cd/project.json Normal file
View File

@@ -0,0 +1,89 @@
{
"name": "bug-cd",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"prefix": "app",
"sourceRoot": "apps/bug-cd/src",
"tags": [],
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/bug-cd",
"index": "apps/bug-cd/src/index.html",
"main": "apps/bug-cd/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/bug-cd/tsconfig.app.json",
"assets": ["apps/bug-cd/src/favicon.ico", "apps/bug-cd/src/assets"],
"styles": ["apps/bug-cd/src/styles.scss"],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "bug-cd:build:production"
},
"development": {
"browserTarget": "bug-cd:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "bug-cd:build"
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["apps/bug-cd/**/*.ts", "apps/bug-cd/**/*.html"]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/bug-cd/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
}
}
}

View File

@@ -0,0 +1,21 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
standalone: true,
imports: [RouterOutlet],
selector: 'app-root',
template: `
<h1 class="text-xl px-4 py-2">My Application</h1>
<section class="flex">
<router-outlet name="side" />
<div class="border p-4">
<router-outlet />
</div>
</section>
`,
host: {
class: 'flex flex-col gap-2',
},
})
export class AppComponent {}

View File

@@ -0,0 +1,30 @@
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { BarComponent } from './bar.component';
import { FooComponent } from './foo.component';
import { MainNavigationComponent } from './main-navigation.component';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter([
{
path: '',
component: MainNavigationComponent,
outlet: 'side',
},
{
path: '',
pathMatch: 'full',
redirectTo: 'foo',
},
{
path: 'foo',
component: FooComponent,
},
{
path: 'bar',
component: BarComponent,
},
]),
],
};

View File

@@ -0,0 +1,7 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-bar',
standalone: true,
template: ` BarComponent `,
})
export class BarComponent {}

View File

@@ -0,0 +1,7 @@
import { Injectable } from '@angular/core';
import { delay, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class FakeServiceService {
getInfoFromBackend = () => of('Client app').pipe(delay(500));
}

View File

@@ -0,0 +1,7 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-foo',
standalone: true,
template: `Foo Component `,
})
export class FooComponent {}

View File

@@ -0,0 +1,67 @@
import { AsyncPipe, NgFor, NgIf } from '@angular/common';
import { Component, Input, inject } from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { FakeServiceService } from './fake.service';
interface MenuItem {
path: string;
name: string;
}
@Component({
selector: 'app-nav',
standalone: true,
imports: [RouterLink, RouterLinkActive, NgFor],
template: `
<ng-container *ngFor="let menu of menus">
<a
class="border px-4 py-2 rounded-md"
[routerLink]="menu.path"
routerLinkActive="isSelected">
{{ menu.name }}
</a>
</ng-container>
`,
styles: [
`
a.isSelected {
@apply bg-gray-600 text-white;
}
`,
],
host: {
class: 'flex flex-col p-2 gap-2',
},
})
export class NavigationComponent {
@Input() menus!: MenuItem[];
}
@Component({
standalone: true,
imports: [NavigationComponent, NgIf, AsyncPipe],
template: `
<ng-container *ngIf="info$ | async as info">
<ng-container *ngIf="info !== null; else noInfo">
<app-nav [menus]="getMenu(info)" />
</ng-container>
</ng-container>
<ng-template #noInfo>
<app-nav [menus]="getMenu('')" />
</ng-template>
`,
host: {},
})
export class MainNavigationComponent {
private fakeBackend = inject(FakeServiceService);
readonly info$ = this.fakeBackend.getInfoFromBackend();
getMenu(prop: string) {
return [
{ path: '/foo', name: `Foo ${prop}` },
{ path: '/bar', name: `Bar ${prop}` },
];
}
}

View File

BIN
apps/bug-cd/src/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>test</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>

7
apps/bug-cd/src/main.ts Normal file
View File

@@ -0,0 +1,7 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);

View File

@@ -0,0 +1,5 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* You can add global styles to this file, and also import other style files */

View File

@@ -0,0 +1,2 @@
import '@testing-library/jest-dom';
import 'jest-preset-angular/setup-jest';

View File

@@ -0,0 +1,14 @@
const { createGlobPatternsForDependencies } = require('@nx/angular/tailwind');
const { join } = require('path');
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
plugins: [],
};

View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": []
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"],
"exclude": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts"]
}

View File

@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts"],
"compilerOptions": {
"types": ["jest", "node"]
}
}

32
apps/bug-cd/tsconfig.json Normal file
View File

@@ -0,0 +1,32 @@
{
"compilerOptions": {
"target": "es2022",
"useDefineForClassFields": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
},
{
"path": "./tsconfig.editor.json"
}
],
"extends": "../../tsconfig.base.json",
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@@ -0,0 +1,15 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node", "@testing-library/jest-dom"]
},
"files": ["src/test-setup.ts"],
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}