From b74c1fc6779f65a06cdc06f1f82f293e546bc089 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Raphael=20Vall=C3=A9e?= <72668371+Tranzitron@users.noreply.github.com> Date: Fri, 2 Oct 2026 18:37:08 -0400 Subject: [PATCH 1/3] Redesign the frontend UI as a dark reference tool Rebuilds all five pages of the brand to model to generation to trim drill-down, and fixes several data-handling bugs found while reviewing it. Design: cool graphite surfaces separated by lightness rather than by borders and shadows, with a single amber signal reserved for "active" and "in production". Archivo for prose, JetBrains Mono only for measured values, where decimal alignment is the point. Each level gets the list treatment its data actually calls for: a dense index for marques, image rows for models, a table for generations, a photo grid for trims, and a spec sheet for a trim's 70-odd measurements. Navigation: the header now shows the whole drill-down path, so a page four levels deep is one click from any ancestor. The old build had no way back up at all. On narrow screens the path keeps its last two levels. The brands index drops its logo cards. At index size a marque badge is too small to identify and duplicates the name beside it, and 398 of them in 100px tiles needed an enormous scroll. The logo stays on the brand page, where it is rendered large enough to do a job. Bug fixes: - power never holds horsepower. The backend matches labels containing "power" before "power per litre", so the field is named for one and carries the other. The UI labels it from the value. - In-production models store an invalid end date, which the API sends as null. The old @if (item.endYear) treated that as truthy, so current cars rendered NaN years under a red "discontinued" badge. - Header path links resolved relative to the current route, so the brand crumb pointed at /alfa_romeo-11 instead of /browse/alfa_romeo-11. - Item anchors had no href, making them unreachable by keyboard and unannounced as links. They are real router links now. - Reusing the global .row rule on a turned the generations table row into a CSS grid and collapsed the name column to one word per line. - Grid containers used a gap over a tinted background, which painted the short final row of each letter group as a solid block. - --faint measured 3.9:1 on the page background, under the 4.5:1 needed for small text. All pages now pass AA, verified in the browser. Verified by building, then walking every page at 1400px and at phone width: no console errors, no contrast failures, no horizontal overflow. ApiService reads from a hardcoded fixture table via useFixtures, because auto-data.net blocks this browser and the backend does not currently start. Flip the flag to false to go back to HTTP; nothing else changes. --- frontend/src/app/api.service.ts | 14 +- frontend/src/app/app.component.css | 109 ++++ frontend/src/app/app.component.html | 31 +- frontend/src/app/app.component.ts | 14 +- .../all-brands-item.component.css | 53 +- .../all-brands-item.component.html | 10 +- .../all-brands-item.component.ts | 36 +- .../all-brands/all-brands.component.css | 192 +++++-- .../all-brands/all-brands.component.html | 82 ++- .../browse/all-brands/all-brands.component.ts | 134 +++-- .../brand/brand-item/brand-item.component.css | 97 +--- .../brand-item/brand-item.component.html | 45 +- .../brand/brand-item/brand-item.component.ts | 42 +- .../src/app/browse/brand/brand.component.css | 14 +- .../src/app/browse/brand/brand.component.html | 59 +- .../src/app/browse/brand/brand.component.ts | 59 +- .../generation-item.component.css | 0 .../generation-item.component.html | 3 - .../generation-item.component.ts | 24 - .../generation/generation.component.css | 3 + .../generation/generation.component.html | 68 ++- .../browse/generation/generation.component.ts | 80 ++- .../model/model-item/model-item.component.css | 0 .../model-item/model-item.component.html | 3 - .../model/model-item/model-item.component.ts | 24 - .../src/app/browse/model/model.component.css | 35 ++ .../src/app/browse/model/model.component.html | 76 ++- .../src/app/browse/model/model.component.ts | 82 ++- .../trim-details/trim-details.component.css | 216 ++++++++ .../trim-details/trim-details.component.html | 98 +++- .../trim-details/trim-details.component.ts | 105 +++- frontend/src/app/fixtures.ts | 406 ++++++++++++++ frontend/src/app/format.ts | 235 ++++++++ frontend/src/app/nav-state.ts | 26 + frontend/src/app/slugify-pipe.ts | 17 +- frontend/src/index.html | 10 +- frontend/src/styles.css | 512 +++++++++++++++++- 37 files changed, 2455 insertions(+), 559 deletions(-) delete mode 100644 frontend/src/app/browse/generation/generation-item/generation-item.component.css delete mode 100644 frontend/src/app/browse/generation/generation-item/generation-item.component.html delete mode 100644 frontend/src/app/browse/generation/generation-item/generation-item.component.ts delete mode 100644 frontend/src/app/browse/model/model-item/model-item.component.css delete mode 100644 frontend/src/app/browse/model/model-item/model-item.component.html delete mode 100644 frontend/src/app/browse/model/model-item/model-item.component.ts create mode 100644 frontend/src/app/fixtures.ts create mode 100644 frontend/src/app/format.ts create mode 100644 frontend/src/app/nav-state.ts diff --git a/frontend/src/app/api.service.ts b/frontend/src/app/api.service.ts index 16dae8f..f4301af 100644 --- a/frontend/src/app/api.service.ts +++ b/frontend/src/app/api.service.ts @@ -2,6 +2,7 @@ import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {lastValueFrom} from 'rxjs'; import {Brand, Generation, Model, Trim} from "../../../library/src/models"; +import {FIXTURES} from './fixtures'; @Injectable({ providedIn: 'root', @@ -9,26 +10,37 @@ import {Brand, Generation, Model, Trim} from "../../../library/src/models"; export class ApiService { serverUrl = "http://localhost:3000/"; + /** + * Set to false to read from the backend again. Nothing else changes: the + * fixture table returns the same shapes the endpoints serialise. + */ + private readonly useFixtures = true; + constructor(public http: HttpClient,) { } async getAllBrands(): Promise { + if (this.useFixtures) return FIXTURES.getAllBrands(); return await lastValueFrom(this.http.get(this.serverUrl + 'brands')); } async getBrandWithModels(brandId: number): Promise { + if (this.useFixtures) return FIXTURES.getBrandWithModels(brandId); return await lastValueFrom(this.http.get(this.serverUrl + 'brand/' + brandId)); } async getModelWithGenerations(modelId: number): Promise { + if (this.useFixtures) return FIXTURES.getModelWithGenerations(modelId); return await lastValueFrom(this.http.get(this.serverUrl + 'model/' + modelId)); } async getGenerationWithTrims(generationId: number): Promise { + if (this.useFixtures) return FIXTURES.getGenerationWithTrims(generationId); return await lastValueFrom(this.http.get(this.serverUrl + 'generation/' + generationId)); } async getTrimDetails(trimId: number): Promise { + if (this.useFixtures) return FIXTURES.getTrimDetails(trimId); return await lastValueFrom(this.http.get(this.serverUrl + 'trim/' + trimId)); } -} +} \ No newline at end of file diff --git a/frontend/src/app/app.component.css b/frontend/src/app/app.component.css index e69de29..d3309f8 100644 --- a/frontend/src/app/app.component.css +++ b/frontend/src/app/app.component.css @@ -0,0 +1,109 @@ +.bar { + position: sticky; + top: 0; + z-index: 50; + display: flex; + align-items: center; + gap: 1rem 1.5rem; + flex-wrap: wrap; + min-height: var(--bar-h); + padding: 0.625rem var(--gutter); + /* Opaque, because content scrolls underneath it and a blur would let the + letters of a brand grid show through the path. */ + background: var(--bg); + border-bottom: 1px solid var(--line); +} + +.mark { + display: inline-flex; + align-items: center; + gap: 0.5rem; + flex-shrink: 0; +} + +.mark__glyph { + width: 21px; + height: 21px; + color: var(--signal); +} + +.mark__name { + font-size: 0.9375rem; + font-weight: 600; + letter-spacing: -0.02em; +} + +.mark__name-rest { + color: var(--faint); + font-weight: 400; +} + +.mark:hover .mark__name-rest { + color: var(--dim); +} + +/* The path runs to the end of the bar and truncates, so a long trim name never + pushes the layout around or wraps into a second row on desktop. */ +.path { + flex: 1; + justify-content: flex-end; + align-items: baseline; + gap: 0 0.5rem; + min-width: 0; + margin: 0; + overflow: hidden; + flex-wrap: nowrap; +} + +.path__item { + display: inline-flex; + align-items: baseline; + gap: 0.5rem; + min-width: 0; +} + +/* The separator belongs to the item it follows, so hiding an item on narrow + screens takes its separator with it. */ +.path__item + .path__item::before { + content: '/'; + flex-shrink: 0; + color: var(--line); +} + +.path__crumb { + color: var(--dim); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + transition: color 0.15s var(--ease); +} + +.path__crumb--here { + color: var(--text); + font-weight: 500; + /* The current level keeps its full weight so the eye lands there first. */ +} + +.path__crumb:not(.path__crumb--here):hover { + color: var(--signal); +} + +/* Below this width there is no room to put the path beside the wordmark, so it + drops to its own row. Only the last two levels survive: the full path runs to + five items deep and would truncate every one of them to nothing. */ +@media (max-width: 46rem) { + .bar { + align-items: center; + row-gap: 0.375rem; + } + + .path { + order: 3; + flex-basis: 100%; + justify-content: flex-start; + } + + .path__item:not(:nth-last-child(-n + 2)) { + display: none; + } +} \ No newline at end of file diff --git a/frontend/src/app/app.component.html b/frontend/src/app/app.component.html index 3e499ef..6e93603 100644 --- a/frontend/src/app/app.component.html +++ b/frontend/src/app/app.component.html @@ -1,4 +1,29 @@ -
-
+
+ + + AutoDataWrapper + + + @if (nav.crumbs().length > 0) { + + } +
- +
+ +
\ No newline at end of file diff --git a/frontend/src/app/app.component.ts b/frontend/src/app/app.component.ts index d1eda49..85eee22 100644 --- a/frontend/src/app/app.component.ts +++ b/frontend/src/app/app.component.ts @@ -1,12 +1,14 @@ -import {Component, signal} from '@angular/core'; -import {RouterOutlet} from '@angular/router'; +import {ChangeDetectionStrategy, Component, inject} from '@angular/core'; +import {RouterLink, RouterOutlet} from '@angular/router'; +import {NavState} from './nav-state'; @Component({ selector: 'app-root', - imports: [RouterOutlet], + imports: [RouterLink, RouterOutlet], templateUrl: './app.component.html', - styleUrl: './app.component.css' + styleUrl: './app.component.css', + changeDetection: ChangeDetectionStrategy.OnPush, }) export class AppComponent { - protected readonly title = signal('AutoDataWrapper'); -} + protected readonly nav = inject(NavState); +} \ No newline at end of file diff --git a/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.css b/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.css index 27d2cb4..1de3271 100644 --- a/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.css +++ b/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.css @@ -1,39 +1,32 @@ -.brand-item { +.entry { display: flex; - flex-direction: column; align-items: center; - text-decoration: none; - color: inherit; + /* Flush cells inside the .entries lattice, so no radius or border of its own. */ + padding: 0.5rem 0.75rem; cursor: pointer; - padding: 0.5rem 0.5rem 0; - border: 1px solid #ddd; - border-radius: 8px; - background-color: #fff; - transition: box-shadow 0.2s; - width: 100px; + transition: background 0.15s var(--ease); } -.brand-item:hover { - box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); +.entry:hover { + background: var(--panel); } -.logo-container { - width: 100px; - height: 100px; - display: flex; - align-items: center; - justify-content: center; - margin-bottom: 0.25rem; +/* + * No logo here on purpose. At index size a marque mark lands around 30px, which + * is too small to identify most badges and duplicates what the name already + * says, so 398 of them were decoration competing with the text. The logo earns + * its place on the brand page, where it is rendered large enough to read. + */ +.entry__name { + font-size: 0.8125rem; + color: var(--dim); + line-height: 1.35; + /* Long marques wrap to two lines rather than truncate: a truncated name is + useless in an index whose whole job is recognising names. */ + overflow-wrap: anywhere; + transition: color 0.15s var(--ease); } -.brand-logo { - width: 100%; - height: 100%; - object-fit: contain; -} - -.brand-name { - margin: 0; - font-weight: bold; - text-align: center; -} +.entry:hover .entry__name { + color: var(--text); +} \ No newline at end of file diff --git a/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.html b/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.html index 90f242a..e3c7d33 100644 --- a/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.html +++ b/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.html @@ -1,7 +1,3 @@ - -
- -
-

{{ item.name }}

-
+ + {{ item.name }} + \ No newline at end of file diff --git a/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.ts b/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.ts index 5457b1b..9ae3bac 100644 --- a/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.ts +++ b/frontend/src/app/browse/all-brands/all-brands-item/all-brands-item.component.ts @@ -1,39 +1,21 @@ -import {Component, Input} from '@angular/core'; -import {ActivatedRoute, Router} from '@angular/router'; +import {ChangeDetectionStrategy, Component, Input, computed} from '@angular/core'; +import {RouterLink} from '@angular/router'; import {Brand} from "../../../../../../library/src/models"; -import {SlugifyPipe} from '../../../slugify-pipe'; +import {entitySlug} from '../../../format'; @Component({ selector: 'app-allbrands-item', - imports: [], + imports: [RouterLink], templateUrl: './all-brands-item.component.html', styleUrl: './all-brands-item.component.css', - providers: [SlugifyPipe] + changeDetection: ChangeDetectionStrategy.OnPush, }) export class AllBrandsItemComponent { @Input({required: true}) item!: Brand; - /** Shown when the marque has no logo, or its logo fails to load. */ - readonly placeholder = 'https://placehold.co/100x100?text=No+logo'; - - constructor(public router: Router, private route: ActivatedRoute, private pipe: SlugifyPipe) { - } - /** - * A stored imageUrl is a URL to another origin, so it can fail even though it - * is well-formed: a logo the site has since renamed or dropped 404s. Without - * this the browser shows its own broken-image icon, which reads as a bug in - * the app rather than missing artwork. + * A real router link, not a click handler on a bare anchor: that keeps the + * entry focusable, reachable by keyboard, and openable in a new tab. */ - onImageError(event: Event): void { - const img = event.target as HTMLImageElement; - if (img.src === this.placeholder) return; - img.src = this.placeholder; - } - - public async clicked() { - let brandName = this.pipe.transform(this.item.name); - let brandUrl = brandName + "-" + this.item.id; - await this.router.navigate([brandUrl], {relativeTo: this.route}); - } -} + protected readonly slug = computed(() => entitySlug(this.item?.name ?? '', this.item?.id ?? 0)); +} \ No newline at end of file diff --git a/frontend/src/app/browse/all-brands/all-brands.component.css b/frontend/src/app/browse/all-brands/all-brands.component.css index 18ebaa9..9a304e5 100644 --- a/frontend/src/app/browse/all-brands/all-brands.component.css +++ b/frontend/src/app/browse/all-brands/all-brands.component.css @@ -1,76 +1,156 @@ -.navigation-bar { - display: flex; - flex-wrap: wrap; - gap: 0.5rem; - padding: 1rem; - background-color: #f8f9fa; - z-index: 100; - border-bottom: 1px solid #dee2e6; - margin-bottom: 1rem; - transition: all 0.3s ease; +.index { + display: grid; + /* The rail is intrinsic: one narrow column of letters. Everything else goes + to the body, which is where the 398 brands live. */ + grid-template-columns: auto minmax(0, 1fr); + gap: 0 clamp(1.25rem, 0.4rem + 2vw, 3rem); + max-width: 1320px; + margin: 0 auto; + padding: 1.75rem var(--gutter) 6rem; + align-items: start; } -.navigation-bar.floating { - position: fixed; - right: 1rem; - top: 50%; - transform: translateY(-50%) translateX(150%); - flex-direction: column; - align-items: center; - background-color: rgba(248, 249, 250, 0.9); - box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); - border-radius: 8px; - border: 1px solid #dee2e6; - padding: 0.5rem; - max-height: 90vh; - overflow-y: auto; - opacity: 0; - transition: transform 0.25s ease-out, opacity 0.25s ease-out, visibility 0s linear 0.25s; - visibility: hidden; -} +/* ------------------------------------------------------------- the rail --- */ -.navigation-bar.floating.visible { - transform: translateY(-50%) translateX(0); - opacity: 1; - visibility: visible; - transition-delay: 0s; +.rail { + position: sticky; + /* Clears the fixed page header. */ + top: calc(var(--bar-h) + 1.75rem); + align-self: start; } -.navigation-bar.floating .nav-letter { - font-size: 0.8rem; - padding: 0.15rem 0.3rem; +.rail__list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 0.0625rem; } -.nav-letter { - text-decoration: none; - color: #007bff; - font-weight: bold; - padding: 0.25rem 0.5rem; +.rail__letter { + display: grid; + place-items: center; + width: 26px; + height: 22px; + font-family: var(--mono); + font-size: 0.75rem; + /* Navigation, so it carries real text contrast rather than the faint tone + used for supporting meta. */ + color: var(--dim); border-radius: 4px; + transition: color 0.15s var(--ease), background 0.15s var(--ease); } -.nav-letter:hover { - background-color: #e9ecef; +.rail__letter:hover { + color: var(--text); + background: var(--panel); } -.brands-container { - padding: 1rem; +/* The active letter is amber with a filled box: position within a 398-item + list, readable without scrolling the list itself. */ +.rail__letter--active { + color: var(--signal); + background: var(--signal-wash); + font-weight: 500; } -.letter-section { - margin-bottom: 2rem; - scroll-margin-top: 2rem; +/* ---------------------------------------------------------- the sections -- */ + +.index__body { + min-width: 0; } -.letter-header { - border-bottom: 2px solid #343a40; - padding-bottom: 0.5rem; - margin-bottom: 1rem; +.letter-section { + margin-bottom: 2.25rem; + /* Anchor jumps must land below the sticky header and the sticky heading. */ + scroll-margin-top: calc(var(--bar-h) + 3rem); } -.letter-brands { +.letter-head { + position: sticky; + top: var(--bar-h); + z-index: 10; display: flex; - flex-wrap: wrap; - gap: 1.5rem; - justify-content: flex-start; + align-items: center; + gap: 0.75rem; + padding: 0.625rem 0 0.5rem; + margin-bottom: 0.75rem; + background: linear-gradient(var(--bg) 72%, rgba(15, 20, 27, 0)); + font-size: 1.25rem; + font-weight: 600; + letter-spacing: -0.02em; } + +.letter-head__key { + color: var(--text); +} + +.letter-head__count { + font-size: 0.75rem; + font-weight: 400; + color: var(--faint); + margin-left: auto; + order: 3; +} + +.letter-head::after { + content: ''; + flex: 1; + height: 1px; + background: var(--line); + order: 2; +} + +/* The index reads as one dense mass of flush cells, not a grid of cards: the + lattice is drawn by borders, so the short final row of each letter group + leaves empty background rather than a filled block. */ +.entries { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); + border-top: 1px solid var(--line-soft); + border-left: 1px solid var(--line-soft); + border-radius: var(--radius); + overflow: hidden; +} + +/* ------------------------------------------------------------ responsive -- */ + +/* Under the two-column threshold the rail becomes a horizontal strip that stays + reachable while the long list scrolls. */ +@media (max-width: 60rem) { + .index { + grid-template-columns: minmax(0, 1fr); + padding-top: 0.75rem; + } + + .rail { + top: var(--bar-h); + z-index: 20; + /* Full-bleed so the strip can scroll to the last letter without the page + scrolling under it. */ + margin: 0 calc(var(--gutter) * -1); + padding: 0.5rem var(--gutter); + background: var(--bg); + border-bottom: 1px solid var(--line); + } + + .rail__list { + flex-direction: row; + gap: 0.125rem; + overflow-x: auto; + scrollbar-width: none; + } + + .rail__list::-webkit-scrollbar { + display: none; + } + + .letter-head { + top: calc(var(--bar-h) + 2.25rem); + } + + .entries { + grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); + } +} \ No newline at end of file diff --git a/frontend/src/app/browse/all-brands/all-brands.component.html b/frontend/src/app/browse/all-brands/all-brands.component.html index 1650c05..b17ba31 100644 --- a/frontend/src/app/browse/all-brands/all-brands.component.html +++ b/frontend/src/app/browse/all-brands/all-brands.component.html @@ -1,32 +1,58 @@ -

All Brands

+
+ - - - +
+
+
+

All brands

+

+ Every marque in the database. Pick one to list its models. +

+
+ @if (!loading()) { +

{{ total() }} marques

+ } +
-
- @if (loading) { -

Fetching brands...

- } @else if (groupedBrands.length === 0) { -

No brands found.

- } @else { - @for (group of groupedBrands; track group.letter) { -
-

{{ group.letter }}

-
- @for (item of group.brands; track item.id) { - - } -
+ @if (loading()) { +
+ @for (placeholder of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; track placeholder) { +
+ }
+ } @else if (total() === 0) { +

+ No brands yet + The database has no marques in it. Add some, then reload. +

+ } @else { + @for (group of groupedBrands(); track group.letter) { +
+

+ {{ group.letter }} + {{ group.brands.length }} +

+
+ @for (item of group.brands; track item.id) { + + } +
+
+ } } - } -
+
+
\ No newline at end of file diff --git a/frontend/src/app/browse/all-brands/all-brands.component.ts b/frontend/src/app/browse/all-brands/all-brands.component.ts index 01527eb..e51f4a7 100644 --- a/frontend/src/app/browse/all-brands/all-brands.component.ts +++ b/frontend/src/app/browse/all-brands/all-brands.component.ts @@ -1,9 +1,18 @@ -import {CommonModule} from '@angular/common'; -import {AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild} from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + ElementRef, + OnDestroy, + OnInit, + computed, + inject, + signal, +} from '@angular/core'; import {RouterModule} from '@angular/router'; import {ApiService} from '../../api.service'; import {AllBrandsItemComponent} from './all-brands-item/all-brands-item.component'; -import {Brand} from '../../../../../library/src/models' +import {Brand} from '../../../../../library/src/models'; +import {NavState} from '../../nav-state'; interface GroupedBrands { letter: string; @@ -12,75 +21,92 @@ interface GroupedBrands { @Component({ selector: 'app-brands', - imports: [ - AllBrandsItemComponent, - CommonModule, - RouterModule - ], + imports: [AllBrandsItemComponent, RouterModule], templateUrl: './all-brands.component.html', styleUrl: './all-brands.component.css', + changeDetection: ChangeDetectionStrategy.OnPush, }) -export class AllBrandsComponent implements OnInit, AfterViewInit, OnDestroy { - brands: Brand[] = []; - groupedBrands: GroupedBrands[] = []; - letters: string[] = []; - isFloating = false; - loading = true; +export class AllBrandsComponent implements OnInit, OnDestroy { + private readonly api = inject(ApiService); + private readonly nav = inject(NavState); + + readonly loading = signal(true); + readonly groupedBrands = signal([]); + readonly activeLetter = signal(null); + + readonly total = computed(() => + this.groupedBrands().reduce((sum, group) => sum + group.brands.length, 0), + ); - @ViewChild('navTrigger') navTrigger!: ElementRef; private observer: IntersectionObserver | null = null; - constructor(public api: ApiService, private changeDetector: ChangeDetectorRef) { + ngOnInit(): void { + this.nav.set([]); + void this.load(); } - async ngOnInit() { - this.loading = true; + ngOnDestroy(): void { + this.observer?.disconnect(); + } + + private async load(): Promise { + this.loading.set(true); try { - this.brands = await this.api.getAllBrands(); - this.processBrands(); + this.groupedBrands.set(this.group(await this.api.getAllBrands())); + // Observed after the sections exist, and after a frame so the browser has + // laid them out. Observing earlier would catch every section at zero + // height and pick the wrong active letter. + queueMicrotask(() => this.watchSections()); } finally { - this.loading = false; - this.changeDetector.detectChanges(); + this.loading.set(false); } } - ngAfterViewInit() { - this.observer = new IntersectionObserver(([entry]) => { - this.isFloating = !entry.isIntersecting; - this.changeDetector.detectChanges(); - }, { - threshold: [0] - }); - - if (this.navTrigger) { - this.observer.observe(this.navTrigger.nativeElement); + private group(brands: Brand[]): GroupedBrands[] { + const groups = new Map(); + for (const brand of [...brands].sort((a, b) => a.name.localeCompare(b.name))) { + // Brands starting with a digit ("212") group under the digit, so the rail + // and the sections always describe the same set. + const key = brand.name[0]?.toUpperCase() ?? '#'; + const bucket = groups.get(key); + if (bucket) { + bucket.push(brand); + } else { + groups.set(key, [brand]); + } } + return [...groups.entries()] + .sort(([a], [b]) => a.localeCompare(b)) + .map(([letter, items]) => ({letter, brands: items})); } - ngOnDestroy() { - if (this.observer) { - this.observer.disconnect(); + /** + * Tracks which letter the reader is under. The root margin shrinks the + * viewport to a band just below the header, so a section becomes active as + * its heading reaches the top rather than the instant it enters from below. + */ + private watchSections(): void { + this.observer?.disconnect(); + this.observer = new IntersectionObserver( + (entries) => { + for (const entry of entries) { + if (entry.isIntersecting) this.activeLetter.set(entry.target.id); + } + }, + {rootMargin: '-72px 0px -70% 0px', threshold: 0}, + ); + for (const section of document.querySelectorAll('.letter-section')) { + this.observer.observe(section); } } - private processBrands() { - // Sort brands alphabetically - this.brands.sort((a, b) => a.name.localeCompare(b.name)); - - // Group brands by first letter - const groups: { [key: string]: Brand[] } = {}; - this.brands.forEach(brand => { - const firstLetter = brand.name[0].toUpperCase(); - if (!groups[firstLetter]) { - groups[firstLetter] = []; - } - groups[firstLetter].push(brand); - }); + trackLetter(_: number, group: GroupedBrands): string { + return group.letter; + } - this.letters = Object.keys(groups).sort().filter(letter => /^[A-Z]$/.test(letter)); - this.groupedBrands = Object.keys(groups).sort().map(letter => ({ - letter, - brands: groups[letter] - })); + jumpTo(letter: string, event: Event): void { + event.preventDefault(); + document.getElementById(letter)?.scrollIntoView({behavior: 'smooth', block: 'start'}); + this.activeLetter.set(letter); } -} +} \ No newline at end of file diff --git a/frontend/src/app/browse/brand/brand-item/brand-item.component.css b/frontend/src/app/browse/brand/brand-item/brand-item.component.css index 97aacab..d86323b 100644 --- a/frontend/src/app/browse/brand/brand-item/brand-item.component.css +++ b/frontend/src/app/browse/brand/brand-item/brand-item.component.css @@ -1,78 +1,19 @@ -.model-item { - display: flex; - flex-direction: row; - align-items: center; - text-decoration: none; - color: inherit; - cursor: pointer; - padding: 0.5rem; - border: 1px solid #ddd; - border-radius: 8px; - background-color: #fff; - transition: box-shadow 0.2s; - width: 100%; - gap: 1rem; -} - -.model-item:hover { - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); -} - -.image-container { - width: 120px; - height: 80px; - flex-shrink: 0; - display: flex; - align-items: center; - justify-content: center; - overflow: hidden; - background-color: #f5f5f5; - border-radius: 4px; -} - -.model-image { - width: 100%; - height: 100%; - object-fit: cover; /* fill the area without stretching */ -} - -.model-details { - display: flex; - flex-direction: column; - gap: 0.25rem; -} - -.model-name { - margin: 0; - font-weight: bold; - font-size: 1.1rem; -} - -.model-years { - margin: 0; - font-size: 0.9rem; - color: #666; -} - -.status-badge { - display: flex; - align-items: center; - justify-content: center; - margin-left: auto; - padding: 4px; - border-radius: 50%; - background-color: #e6f4ea; - color: #1e8e3e; - width: 24px; - height: 24px; -} - -.status-badge svg { - width: 18px; - height: 18px; -} - -.status-badge.stopped { - background-color: #fce8e6; - color: #d93025; -} +/* The row primitives live in styles.css, shared with the generation and trim + pages. Only the parts that differ live here. */ + +@media (max-width: 40rem) { + .row { + grid-template-columns: 88px minmax(0, 1fr); + gap: 0.875rem; + } + + .row__thumb { + width: 88px; + height: 60px; + } + + .row__aside { + grid-column: 2; + margin-top: -0.25rem; + } +} \ No newline at end of file diff --git a/frontend/src/app/browse/brand/brand-item/brand-item.component.html b/frontend/src/app/browse/brand/brand-item/brand-item.component.html index d71a8ab..62e45d2 100644 --- a/frontend/src/app/browse/brand/brand-item/brand-item.component.html +++ b/frontend/src/app/browse/brand/brand-item/brand-item.component.html @@ -1,30 +1,17 @@ - -
- -
-
-

{{ item.name }}

-

- {{ item.startYear | date:'yyyy' }} - - @if (item.endYear) { - {{ item.endYear | date:'yyyy' }} - } @else { - Present - } -

-
-
- + + + {{ years() }} + + \ No newline at end of file diff --git a/frontend/src/app/browse/brand/brand-item/brand-item.component.ts b/frontend/src/app/browse/brand/brand-item/brand-item.component.ts index f8879c7..391cea7 100644 --- a/frontend/src/app/browse/brand/brand-item/brand-item.component.ts +++ b/frontend/src/app/browse/brand/brand-item/brand-item.component.ts @@ -1,41 +1,29 @@ -import {Component, Input} from '@angular/core'; -import {ActivatedRoute, Router} from '@angular/router'; -import {Model} from '../../../../../../library/src/models' -import {SlugifyPipe} from '../../../slugify-pipe'; -import {DatePipe} from '@angular/common'; +import {ChangeDetectionStrategy, Component, Input, computed} from '@angular/core'; +import {RouterLink} from '@angular/router'; +import {Model} from '../../../../../../library/src/models'; +import {entitySlug, isInProduction, yearRange} from '../../../format'; @Component({ selector: 'app-brand-item', - imports: [ - DatePipe - ], + imports: [RouterLink], templateUrl: './brand-item.component.html', styleUrl: './brand-item.component.css', - providers: [SlugifyPipe] + changeDetection: ChangeDetectionStrategy.OnPush, }) export class BrandItemComponent { @Input({required: true}) item!: Model; - /** Shown when the model has no photo, or its photo fails to load. */ - readonly placeholder = 'https://placehold.co/100x100?text=No+photo'; - - constructor(public router: Router, private route: ActivatedRoute, private pipe: SlugifyPipe) { - } + protected readonly slug = computed(() => entitySlug(this.item?.name ?? '', this.item?.id ?? 0)); + protected readonly years = computed(() => yearRange(this.item?.startYear, this.item?.endYear)); + protected readonly inProduction = computed(() => isInProduction(this.item?.endYear)); /** * A stored imageUrl is a URL to another origin, so it can fail even though it - * is well-formed: a photo the site has since removed 404s. Without this the - * browser shows its own broken-image icon. + * is well-formed: a photo the site has since removed will 404, and some + * origins are blocked outright. Dropping the image leaves the sunken plate, + * which reads as a deliberate empty frame instead of a broken-image glyph. */ - onImageError(event: Event): void { - const img = event.target as HTMLImageElement; - if (img.src === this.placeholder) return; - img.src = this.placeholder; - } - - public async clicked() { - let modelName = this.pipe.transform(this.item.name); - let modelUrl = modelName + "-" + this.item.id; - await this.router.navigate([modelUrl], {relativeTo: this.route}); + protected onImageError(event: Event): void { + (event.target as HTMLImageElement).style.display = 'none'; } -} +} \ No newline at end of file diff --git a/frontend/src/app/browse/brand/brand.component.css b/frontend/src/app/browse/brand/brand.component.css index 9613091..f03e190 100644 --- a/frontend/src/app/browse/brand/brand.component.css +++ b/frontend/src/app/browse/brand/brand.component.css @@ -1,7 +1,7 @@ -.models-container { - display: flex; - flex-direction: column; - gap: 0.5rem; - padding: 1rem; - max-width: 800px; -} +/* Narrower than the default measure on purpose: a model row carries a name, a + production status and a year range. The years stay in a right-aligned column + so they scan vertically, and a wider measure would only open a gap between + the two. */ +.page { + max-width: 700px; +} \ No newline at end of file diff --git a/frontend/src/app/browse/brand/brand.component.html b/frontend/src/app/browse/brand/brand.component.html index e40df0e..321693b 100644 --- a/frontend/src/app/browse/brand/brand.component.html +++ b/frontend/src/app/browse/brand/brand.component.html @@ -1,19 +1,46 @@ -

brand works!

- -@if (brand?.name) { -

Showing models for {{ brand.name }}

-} @else { -

Showing models for ...

-} +
+
+ @if (brand(); as b) { + @if (b.imageUrl) { + + } +
+
+

{{ b.name }}

+
+

+ {{ models().length }} {{ models().length === 1 ? 'model' : 'models' }} in the database. + Pick one to see its generations. +

+
+ } @else { +
+

Loading

+
+ } +
-
- @if (loading) { -

Fetching models...

- } @else if (models.length === 0) { -

No models found.

+ @if (loading()) { +
+ @for (placeholder of [1, 2, 3, 4, 5, 6, 7]; track placeholder) { +
+ } +
+ } @else if (failed()) { +

+ We could not load that brand + The database has no marque matching this address. It may have been removed. +

+ } @else if (models().length === 0) { +

+ No models recorded + Nothing has been added under {{ brand()?.name }} yet. +

} @else { - @for (item of models; track item) { - - } +
+ @for (item of models(); track item.id) { + + } +
} -
+
\ No newline at end of file diff --git a/frontend/src/app/browse/brand/brand.component.ts b/frontend/src/app/browse/brand/brand.component.ts index b3068c0..f79016a 100644 --- a/frontend/src/app/browse/brand/brand.component.ts +++ b/frontend/src/app/browse/brand/brand.component.ts @@ -1,42 +1,53 @@ -import {ChangeDetectorRef, Component, OnInit} from '@angular/core'; +import {ChangeDetectionStrategy, Component, OnInit, inject, signal} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {ApiService} from '../../api.service'; -import {Brand, Model} from '../../../../../library/src/models' +import {Brand, Model} from '../../../../../library/src/models'; import {BrandItemComponent} from './brand-item/brand-item.component'; +import {NavState} from '../../nav-state'; @Component({ selector: 'app-brand', - imports: [ - BrandItemComponent - ], + imports: [BrandItemComponent], templateUrl: './brand.component.html', styleUrl: './brand.component.css', + changeDetection: ChangeDetectionStrategy.OnPush, }) export class BrandComponent implements OnInit { - brand: Brand | undefined; - models: Model[] = []; - loading = true; + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly api = inject(ApiService); + private readonly nav = inject(NavState); - - constructor(private route: ActivatedRoute, public api: ApiService, public router: Router, private changeDetector: ChangeDetectorRef) { - } + readonly brand = signal(null); + readonly models = signal([]); + readonly loading = signal(true); + readonly failed = signal(false); async ngOnInit() { - this.loading = true; + this.loading.set(true); + this.failed.set(false); + this.nav.set([]); try { - let brandUrl: string = this.route.snapshot.params["brandId"]; - let brandId: number = parseInt(brandUrl.split("-")[1]); - let tempBrand: Brand = await this.api.getBrandWithModels(brandId); - if (tempBrand == null) { - console.log(`no brand found for: ${brandUrl}`); - await this.router.navigate([""]); + const segment: string = this.route.snapshot.params['brandId']; + const brandId = parseInt(segment.split('-')[1], 10); + const loaded = await this.api.getBrandWithModels(brandId); + if (!loaded) { + this.failed.set(true); + return; } - this.models = tempBrand!.models; - tempBrand!.models = []; - this.brand = tempBrand!; + const models = loaded.models ?? []; + this.models.set(models); + // models is dropped before the brand is stored: the list owns them now, + // and a page should not hold the whole tree twice. + this.brand.set({...loaded, models: []}); + this.nav.set([ + {label: 'Brands', link: ['/browse']}, + {label: loaded.name, link: null}, + ]); + } catch { + this.failed.set(true); } finally { - this.loading = false; - this.changeDetector.detectChanges(); + this.loading.set(false); } } -} +} \ No newline at end of file diff --git a/frontend/src/app/browse/generation/generation-item/generation-item.component.css b/frontend/src/app/browse/generation/generation-item/generation-item.component.css deleted file mode 100644 index e69de29..0000000 diff --git a/frontend/src/app/browse/generation/generation-item/generation-item.component.html b/frontend/src/app/browse/generation/generation-item/generation-item.component.html deleted file mode 100644 index 9ece37d..0000000 --- a/frontend/src/app/browse/generation/generation-item/generation-item.component.html +++ /dev/null @@ -1,3 +0,0 @@ - -

{{ item.name }}

-
diff --git a/frontend/src/app/browse/generation/generation-item/generation-item.component.ts b/frontend/src/app/browse/generation/generation-item/generation-item.component.ts deleted file mode 100644 index 58d4a8e..0000000 --- a/frontend/src/app/browse/generation/generation-item/generation-item.component.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {Component, Input} from '@angular/core'; -import {ActivatedRoute, Router} from '@angular/router'; -import {Trim} from "../../../../../../library/src/models"; -import {SlugifyPipe} from '../../../slugify-pipe'; - -@Component({ - selector: 'app-generation-item', - imports: [], - templateUrl: './generation-item.component.html', - styleUrl: './generation-item.component.css', - providers: [SlugifyPipe] -}) -export class GenerationItemComponent { - @Input({required: true}) item!: Trim; - - constructor(public router: Router, private route: ActivatedRoute, private pipe: SlugifyPipe) { - } - - public async clicked() { - let trimName = this.pipe.transform(this.item.name); - let trimUrl = trimName + "-" + this.item.id; - await this.router.navigate([trimUrl], {relativeTo: this.route}); - } -} diff --git a/frontend/src/app/browse/generation/generation.component.css b/frontend/src/app/browse/generation/generation.component.css index e69de29..a069e5e 100644 --- a/frontend/src/app/browse/generation/generation.component.css +++ b/frontend/src/app/browse/generation/generation.component.css @@ -0,0 +1,3 @@ +.page { + max-width: 1180px; +} \ No newline at end of file diff --git a/frontend/src/app/browse/generation/generation.component.html b/frontend/src/app/browse/generation/generation.component.html index b69a225..ab6bade 100644 --- a/frontend/src/app/browse/generation/generation.component.html +++ b/frontend/src/app/browse/generation/generation.component.html @@ -1,18 +1,54 @@ -

generation works!

+
+
+ @if (generation(); as g) { +
+

{{ g.name }}

+

+ {{ g.chassisType || 'Body not recorded' }} + {{ years(g.startYear, g.endYear) }} + {{ trims().length }} {{ trims().length === 1 ? 'trim' : 'trims' }} +

+
+ } @else { +
+

Loading

+
+ } +
-@if (generation?.name) { -

Showing trims for {{ generation.name }}

-} @else { -

Showing trims for ...

-} - - -@if (loading) { -

Fetching trims...

-} @else if (trims.length === 0) { -

No trims found.

-} @else { - @for (item of trims; track item) { - + @if (loading()) { +
+ @for (placeholder of [1, 2, 3, 4]; track placeholder) { +
+ } +
+ } @else if (failed()) { +

+ We could not load that generation + Nothing in the database matches this address. +

+ } @else if (trims().length === 0) { +

+ No trims recorded + The source page listed no variants for this generation. +

+ } @else { + + } -} +
\ No newline at end of file diff --git a/frontend/src/app/browse/generation/generation.component.ts b/frontend/src/app/browse/generation/generation.component.ts index 2119ba7..ff62f41 100644 --- a/frontend/src/app/browse/generation/generation.component.ts +++ b/frontend/src/app/browse/generation/generation.component.ts @@ -1,41 +1,73 @@ -import {ChangeDetectorRef, Component, OnInit} from '@angular/core'; +import {ChangeDetectionStrategy, Component, OnInit, inject, signal} from '@angular/core'; +import {ActivatedRoute, RouterLink} from '@angular/router'; import {Generation, Trim} from "../../../../../library/src/models"; -import {ActivatedRoute, Router} from '@angular/router'; import {ApiService} from '../../api.service'; -import {GenerationItemComponent} from './generation-item/generation-item.component'; +import {Crumb, NavState} from '../../nav-state'; +import {entitySlug, yearRange} from '../../format'; @Component({ selector: 'app-generation', - imports: [ - GenerationItemComponent - ], + imports: [RouterLink], templateUrl: './generation.component.html', styleUrl: './generation.component.css', + changeDetection: ChangeDetectionStrategy.OnPush, }) export class GenerationComponent implements OnInit { - generation: Generation | undefined; - trims: Trim[] = []; - loading = true; + private readonly route = inject(ActivatedRoute); + private readonly api = inject(ApiService); + private readonly nav = inject(NavState); - constructor(private route: ActivatedRoute, public api: ApiService, public router: Router, private changeDetector: ChangeDetectorRef) { - } + readonly generation = signal(null); + readonly trims = signal([]); + readonly loading = signal(true); + readonly failed = signal(false); + readonly slugs = signal>(new Map()); async ngOnInit() { - this.loading = true; + this.loading.set(true); + this.failed.set(false); + this.nav.set([]); try { - let generationUrl: string = this.route.snapshot.params["generationId"]; - let generationId: number = parseInt(generationUrl.split("-")[1]); - let tempGeneration: Generation = await this.api.getGenerationWithTrims(generationId); - if (tempGeneration == null) { - console.log(`no generation found for: ${generationUrl}`); - await this.router.navigate([""]); + const segment: string = this.route.snapshot.params['generationId']; + const generationId = parseInt(segment.split('-')[1], 10); + const loaded = await this.api.getGenerationWithTrims(generationId); + if (!loaded) { + this.failed.set(true); + return; } - this.trims = tempGeneration!.trims; - tempGeneration!.trims = []; - this.generation = tempGeneration!; + const trims = loaded.trims ?? []; + this.trims.set(trims); + this.slugs.set(new Map(trims.map((t) => [t.id, entitySlug(t.name, t.id)]))); + this.generation.set({...loaded, trims: []}); + this.nav.set(this.pathFor(loaded)); + } catch { + this.failed.set(true); } finally { - this.loading = false; - this.changeDetector.detectChanges(); + this.loading.set(false); } } -} + + /** + * Normally the model page has already published the path, so this only + * appends to it. On a direct load of a deep link the path starts empty, and + * the model name on the generation record is the most that is known without + * another request. + */ + private pathFor(generation: Generation): Crumb[] { + const self: Crumb = {label: generation.name, link: null}; + const inherited = this.nav.crumbs(); + if (inherited.length > 0) return [...inherited, self]; + const parent = generation.model; + return parent + ? [ + {label: 'Brands', link: ['/browse']}, + {label: parent.name, link: ['/browse', entitySlug(parent.name, parent.id)]}, + self, + ] + : [{label: 'Brands', link: ['/browse']}, self]; + } + + years(start: Date | string | null, end: Date | string | null): string { + return yearRange(start, end); + } +} \ No newline at end of file diff --git a/frontend/src/app/browse/model/model-item/model-item.component.css b/frontend/src/app/browse/model/model-item/model-item.component.css deleted file mode 100644 index e69de29..0000000 diff --git a/frontend/src/app/browse/model/model-item/model-item.component.html b/frontend/src/app/browse/model/model-item/model-item.component.html deleted file mode 100644 index 9ece37d..0000000 --- a/frontend/src/app/browse/model/model-item/model-item.component.html +++ /dev/null @@ -1,3 +0,0 @@ - -

{{ item.name }}

-
diff --git a/frontend/src/app/browse/model/model-item/model-item.component.ts b/frontend/src/app/browse/model/model-item/model-item.component.ts deleted file mode 100644 index ab7ce0c..0000000 --- a/frontend/src/app/browse/model/model-item/model-item.component.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {Component, Input} from '@angular/core'; -import {ActivatedRoute, Router} from '@angular/router'; -import {Generation} from "../../../../../../library/src/models"; -import {SlugifyPipe} from '../../../slugify-pipe'; - -@Component({ - selector: 'app-model-item', - imports: [], - templateUrl: './model-item.component.html', - styleUrl: './model-item.component.css', - providers: [SlugifyPipe] -}) -export class ModelItemComponent { - @Input({required: true}) item!: Generation; - - constructor(public router: Router, private route: ActivatedRoute, private pipe: SlugifyPipe) { - } - - public async clicked() { - let generationName = this.pipe.transform(this.item.name); - let generationUrl = generationName + "-" + this.item.id; - await this.router.navigate([generationUrl], {relativeTo: this.route}); - } -} diff --git a/frontend/src/app/browse/model/model.component.css b/frontend/src/app/browse/model/model.component.css index e69de29..caeb887 100644 --- a/frontend/src/app/browse/model/model.component.css +++ b/frontend/src/app/browse/model/model.component.css @@ -0,0 +1,35 @@ +/* + * Deliberately NOT reusing the global .row class here. That rule is + * `display: grid` with a 116px / 1fr / auto track list, and on a it turns + * the row into a grid container, which throws away the table's column widths + * and squeezes the long generation name to one word per line. + */ +tbody .gen-row { + cursor: pointer; +} + +tbody .gen-row:hover { + background: var(--panel); +} + +tbody .gen-row td { + padding-top: 0.75rem; + padding-bottom: 0.75rem; +} + +tbody .gen-row td:first-child { + position: relative; + overflow-wrap: anywhere; +} + +/* + * The anchor is only as wide as the generation name, but its hit area is + * stretched over that whole cell, so the name reads as one target. The + * remaining cells are caught by the row's click handler, and the guard there + * stops the click being handled twice when the anchor is the one hit. + */ +.gen-link::after { + content: ''; + position: absolute; + inset: 0; +} \ No newline at end of file diff --git a/frontend/src/app/browse/model/model.component.html b/frontend/src/app/browse/model/model.component.html index 8b3650c..4b225f0 100644 --- a/frontend/src/app/browse/model/model.component.html +++ b/frontend/src/app/browse/model/model.component.html @@ -1,18 +1,62 @@ -

model works!

+
+
+ @if (model(); as m) { +
+

{{ m.name }}

+

+ {{ generations().length }} {{ generations().length === 1 ? 'generation' : 'generations' }}. + Pick one to compare its trims. +

+
+ } @else { +
+

Loading

+
+ } +
-@if (model?.name) { -

Showing generations for {{ model.name }}

-} @else { -

Showing generations for ...

-} - - -@if (loading) { -

Fetching generations...

-} @else if (generations.length === 0) { -

No generations found.

-} @else { - @for (item of generations; track item) { - + @if (loading()) { +
+ } @else if (failed()) { +

+ We could not load that model + Nothing in the database matches this address. +

+ } @else if (generations().length === 0) { +

+ No generations recorded + Nothing has been added under {{ model()?.name }} yet. +

+ } @else { + + + + + + + + + + + + + + + + @for (item of generations(); track item.id) { + + + + + + } + +
GenerationBodyYears
+ {{ item.name }} + {{ item.chassisType || '—' }}{{ years(item.startYear, item.endYear) }}
} -} +
\ No newline at end of file diff --git a/frontend/src/app/browse/model/model.component.ts b/frontend/src/app/browse/model/model.component.ts index 55ec42a..0762747 100644 --- a/frontend/src/app/browse/model/model.component.ts +++ b/frontend/src/app/browse/model/model.component.ts @@ -1,41 +1,73 @@ -import {ChangeDetectorRef, Component, OnInit} from '@angular/core'; -import {ActivatedRoute, Router} from '@angular/router'; -import {ApiService} from '../../api.service'; +import {ChangeDetectionStrategy, Component, OnInit, inject, signal} from '@angular/core'; +import {ActivatedRoute, Router, RouterLink} from '@angular/router'; import {Generation, Model} from "../../../../../library/src/models"; -import {ModelItemComponent} from './model-item/model-item.component'; +import {ApiService} from '../../api.service'; +import {Crumb, NavState} from '../../nav-state'; +import {entitySlug, yearRange} from '../../format'; @Component({ selector: 'app-model', - imports: [ - ModelItemComponent - ], + imports: [RouterLink], templateUrl: './model.component.html', styleUrl: './model.component.css', + changeDetection: ChangeDetectionStrategy.OnPush, }) export class ModelComponent implements OnInit { - model: Model | undefined; - generations: Generation[] = []; - loading = true; + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly api = inject(ApiService); + private readonly nav = inject(NavState); - constructor(private route: ActivatedRoute, public api: ApiService, public router: Router, private changeDetector: ChangeDetectorRef) { - } + readonly model = signal(null); + readonly generations = signal([]); + readonly loading = signal(true); + readonly failed = signal(false); + + /** Prebuilt so a row can link without re-deriving its own slug. */ + readonly slugs = signal>(new Map()); async ngOnInit() { - this.loading = true; + this.loading.set(true); + this.failed.set(false); + this.nav.set([]); try { - let modelUrl: string = this.route.snapshot.params["modelId"]; - let modelId: number = parseInt(modelUrl.split("-")[1]); - let tempModel: Model = await this.api.getModelWithGenerations(modelId); - if (tempModel == null) { - console.log(`no model found for: ${modelUrl}`); - await this.router.navigate([""]); + const segment: string = this.route.snapshot.params['modelId']; + const modelId = parseInt(segment.split('-')[1], 10); + const loaded = await this.api.getModelWithGenerations(modelId); + if (!loaded) { + this.failed.set(true); + return; + } + const generations = loaded.generations ?? []; + this.generations.set(generations); + this.slugs.set(new Map(generations.map((g) => [g.id, entitySlug(g.name, g.id)]))); + this.model.set({...loaded, generations: []}); + + const brand = loaded.brand; + const crumbs: Crumb[] = [{label: 'Brands', link: ['/browse']}]; + if (brand) { + crumbs.push({label: brand.name, link: ['/browse', entitySlug(brand.name, brand.id)]}); } - this.generations = tempModel!.generations; - tempModel!.generations = []; - this.model = tempModel!; + crumbs.push({label: loaded.name, link: null}); + this.nav.set(crumbs); + } catch { + this.failed.set(true); } finally { - this.loading = false; - this.changeDetector.detectChanges(); + this.loading.set(false); } } -} + + /** + * Clicks anywhere in the row navigate, except on the anchor itself: that one + * carries its own routerLink, and letting both handle the same click would + * start two navigations. + */ + open(event: Event, slug: string): void { + if ((event.target as Element).closest('a')) return; + void this.router.navigate([slug], {relativeTo: this.route}); + } + + years(start: Date | string | null, end: Date | string | null): string { + return yearRange(start, end); + } +} \ No newline at end of file diff --git a/frontend/src/app/browse/trim-details/trim-details.component.css b/frontend/src/app/browse/trim-details/trim-details.component.css index e69de29..b14f55d 100644 --- a/frontend/src/app/browse/trim-details/trim-details.component.css +++ b/frontend/src/app/browse/trim-details/trim-details.component.css @@ -0,0 +1,216 @@ +.page { + max-width: 1180px; +} + +.source { + color: var(--dim); + text-decoration: underline; + text-underline-offset: 2px; + text-decoration-color: var(--line); + transition: color 0.15s var(--ease); +} + +.source:hover { + color: var(--signal); + text-decoration-color: currentColor; +} + +/* ------------------------------------------------------- headline figures -- */ + +.figures { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); + margin: 0 0 2.25rem; + /* Border lattice, not a gap over a tinted background. Narrow screens wrap + the figures onto a short final row, and a gap-filled grid paints that + remainder as a solid block. */ + border-top: 1px solid var(--line); + border-left: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; +} + +.figures__cell { + display: flex; + flex-direction: column; + gap: 0.4375rem; + padding: 1.125rem 1.125rem 1.25rem; + background: var(--panel); + border-right: 1px solid var(--line); + border-bottom: 1px solid var(--line); +} + +.figures__label { + font-size: 0.75rem; + color: var(--dim); + line-height: 1.3; +} + +.figures__value { + margin: 0; + font-family: var(--mono); + font-variant-numeric: tabular-nums; + font-size: clamp(1.125rem, 0.85rem + 0.9vw, 1.5rem); + font-weight: 500; + letter-spacing: -0.03em; + line-height: 1.15; + overflow-wrap: anywhere; +} + +/* The one orchestrated entrance on the site: the figures arrive in order, + once, because they are the answer the page exists to give. */ +@media (prefers-reduced-motion: no-preference) { + .figures__cell { + animation: arrive 0.42s var(--ease) both; + } + + .figures__cell:nth-child(1) { animation-delay: 0.02s; } + .figures__cell:nth-child(2) { animation-delay: 0.08s; } + .figures__cell:nth-child(3) { animation-delay: 0.14s; } + .figures__cell:nth-child(4) { animation-delay: 0.20s; } + .figures__cell:nth-child(5) { animation-delay: 0.26s; } +} + +@keyframes arrive { + from { + opacity: 0; + transform: translateY(6px); + } +} + +/* ----------------------------------------------------------- photo plate -- */ + +.readout { + display: grid; + /* Weighted towards the sheet: the figures and the 60-odd measurements are + the payload, the photo is a reference for them. */ + grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.3fr); + gap: 2.25rem; + align-items: start; +} + +.plate { + position: sticky; + top: calc(var(--bar-h) + 1.5rem); + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.plate__main { + aspect-ratio: 4 / 3; + background: var(--sunken); + border: 1px solid var(--line-soft); + border-radius: var(--radius); + overflow: hidden; +} + +.plate__main img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.plate__main--empty { + display: grid; + place-items: center; +} + +.plate__thumbs { + display: grid; + grid-template-columns: repeat(6, 1fr); + gap: 0.375rem; +} + +.plate__thumb { + aspect-ratio: 4 / 3; + padding: 0; + background: var(--sunken); + border: 1px solid var(--line-soft); + border-radius: 4px; + overflow: hidden; + opacity: 0.55; + transition: opacity 0.15s var(--ease), border-color 0.15s var(--ease); +} + +.plate__thumb:hover { + opacity: 0.85; +} + +/* The selected plate is outlined in amber: the same signal the rest of the + interface uses for "this is the one". */ +.plate__thumb--on { + opacity: 1; + border-color: var(--signal); +} + +.plate__thumb img { + width: 100%; + height: 100%; + object-fit: cover; +} + +/* --------------------------------------------------------- spec groups ---- */ + +.groups { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(288px, 1fr)); + gap: 1.75rem 2.25rem; + align-content: start; +} + +/* Groups are separated by a rule, not boxed. There are six of them and each + holds a table, so a card would be an extra edge around data that already has + one. */ +.group__title { + font-size: 0.8125rem; + font-weight: 600; + letter-spacing: 0.005em; + color: var(--text); + padding-bottom: 0.4375rem; + margin-bottom: 0.125rem; + border-bottom: 1px solid var(--line); +} + +.group .sheet th, +.group .sheet td { + padding-left: 0; + padding-right: 0; +} + +/* Long prose values ("Independent, McPherson type, Anti-roll bar") have to + wrap; the short ones in the generation table do not. */ +.group .sheet__value { + white-space: normal; + text-align: right; + overflow-wrap: anywhere; + padding-left: 1rem; +} + +.group .sheet tbody tr:last-child td, +.group .sheet tbody tr:last-child th { + border-bottom: 0; +} + +/* ------------------------------------------------------------ responsive -- */ + +@media (max-width: 62rem) { + .readout { + grid-template-columns: minmax(0, 1fr); + gap: 1.75rem; + } + + .plate { + position: static; + } +} + +@media (max-width: 40rem) { + .figures { + grid-template-columns: repeat(auto-fit, minmax(132px, 1fr)); + } + + .figures__cell { + padding: 0.875rem 0.9375rem 1rem; + } +} \ No newline at end of file diff --git a/frontend/src/app/browse/trim-details/trim-details.component.html b/frontend/src/app/browse/trim-details/trim-details.component.html index a88a2fd..843230f 100644 --- a/frontend/src/app/browse/trim-details/trim-details.component.html +++ b/frontend/src/app/browse/trim-details/trim-details.component.html @@ -1,6 +1,94 @@ -

trim works!

+
+
+ @if (trim(); as t) { +
+

{{ t.name }}

+

+ @if (details(); as d) { + {{ d.bodyType || 'Body not recorded' }} + @if (d.engineDisplacement) { + {{ d.engineDisplacement }} + } + } + {{ years }} + @if (t.url) { + Source page + } +

+
+ } @else { +
+

Loading

+
+ } +
-

Name: {{ trim?.name }}

-

Url: {{ trim?.url }}

-

startYear: {{ trim?.startYear }}

-

endYear: {{ trim?.endYear }}

+ @if (loading()) { +
+
+ } @else if (failed()) { +

+ We could not load that trim + Nothing in the database matches this address. +

+ } @else { + + @if (figures().length > 0) { +
+ @for (figure of figures(); track figure.label) { +
+
{{ figure.label }}
+
{{ figure.value }}
+
+ } +
+ } + +
+
+ @if (photos.length > 0) { +
+ +
+ @if (photos.length > 1) { +
+ @for (image of photos; track $index) { + + } +
+ } + } @else { +
+ No photo for this trim +
+ } +
+ +
+ @for (group of groups(); track group.title) { +
+

{{ group.title }}

+ + + @for (row of group.rows; track row.key) { + + + + + } + +
{{ row.label }} + {{ valueText(row.value, row.locked) }} +
+
+ } +
+
+ } +
\ No newline at end of file diff --git a/frontend/src/app/browse/trim-details/trim-details.component.ts b/frontend/src/app/browse/trim-details/trim-details.component.ts index 2b0c693..293fb6e 100644 --- a/frontend/src/app/browse/trim-details/trim-details.component.ts +++ b/frontend/src/app/browse/trim-details/trim-details.component.ts @@ -1,29 +1,108 @@ -import {ChangeDetectorRef, Component, OnInit} from '@angular/core'; +import {ChangeDetectionStrategy, Component, OnInit, inject, signal} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; +import {Trim, TrimDetails} from "../../../../../library/src/models"; import {ApiService} from '../../api.service'; -import {Trim} from "../../../../../library/src/models"; +import {Crumb, NavState} from '../../nav-state'; +import {SpecGroup, entitySlug, groupDetails, headlineFigures, yearRange} from '../../format'; @Component({ selector: 'app-trim', imports: [], templateUrl: './trim-details.component.html', styleUrl: './trim-details.component.css', + changeDetection: ChangeDetectionStrategy.OnPush, }) export class TrimDetailsComponent implements OnInit { - trim: Trim | undefined; + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + private readonly api = inject(ApiService); + private readonly nav = inject(NavState); - constructor(private route: ActivatedRoute, public api: ApiService, public router: Router, private changeDetector: ChangeDetectorRef) { - } + readonly trim = signal(null); + readonly loading = signal(true); + readonly failed = signal(false); + + readonly figures = signal<{ label: string; value: string }[]>([]); + readonly groups = signal([]); + + /** Index into imageUrls; the plate above the sheet shows this one. */ + readonly photo = signal(0); async ngOnInit() { - let trimUrl: string = this.route.snapshot.params["trimId"]; - let trimId: number = parseInt(trimUrl.split("-")[1]); - this.trim = await this.api.getTrimDetails(trimId); - if (!this.trim) { - console.log(`no trim found for: ${trimUrl}`); - await this.router.navigate([""]); + this.loading.set(true); + this.failed.set(false); + this.nav.set([]); + try { + const segment: string = this.route.snapshot.params['trimId']; + const trimId = parseInt(segment.split('-')[1], 10); + const loaded = await this.api.getTrimDetails(trimId); + if (!loaded) { + this.failed.set(true); + return; + } + const details = loaded.trimDetails; + this.trim.set(loaded); + if (details) { + this.figures.set(headlineFigures(details)); + this.groups.set(groupDetails(details)); + } + this.nav.set(this.pathFor(loaded)); + } catch { + this.failed.set(true); + } finally { + this.loading.set(false); } + } + + /** Appends to the path the generation page published, as with generations. */ + private pathFor(trim: Trim): Crumb[] { + const generation = trim.generation; + const self: Crumb = {label: trim.name, link: null}; + const inherited = this.nav.crumbs(); + if (inherited.length > 0) return [...inherited, self]; + if (!generation) return [{label: 'Brands', link: ['/browse']}, self]; + return [ + {label: 'Brands', link: ['/browse']}, + { + label: generation.model?.name ?? generation.name, + link: generation.model + ? ['/browse', entitySlug(generation.model.name, generation.model.id)] + : null, + }, + self, + ]; + } + + get photos(): string[] { + return this.trim()?.imageUrls ?? []; + } + + /** Null when the backend has no scraped record for this trim yet. */ + details(): TrimDetails | null { + return this.trim()?.trimDetails ?? null; + } + + get years(): string { + const trim = this.trim(); + return trim ? yearRange(trim.startYear, trim.endYear) : ''; + } + + selectPhoto(index: number): void { + this.photo.set(index); + } + + goToGeneration(): void { + const generation = this.trim()?.generation; + if (generation) void this.router.navigate([entitySlug(generation.name, generation.id)]); + } + + onImageError(event: Event): void { + // Leaves the empty plate showing rather than a broken-image glyph. + (event.target as HTMLImageElement).style.visibility = 'hidden'; + } - this.changeDetector.detectChanges(); + /** Missing source data is stated, not left blank; "?" means locked upstream. */ + valueText(value: string, locked: boolean): string { + return locked ? 'Locked on the source site' : value || '—'; } -} +} \ No newline at end of file diff --git a/frontend/src/app/fixtures.ts b/frontend/src/app/fixtures.ts new file mode 100644 index 0000000..ca08d62 --- /dev/null +++ b/frontend/src/app/fixtures.ts @@ -0,0 +1,406 @@ +import {Brand, Generation, Model, Trim, TrimDetails} from '../../../library/src/models'; + +/** + * TEMPORARY fixture data so the UI can be built and reviewed without the + * backend running. Values are lifted from the dev database, including its + * rough edges, because those are what the layout has to survive: + * + * - `power` holds a per-litre figure ("78.7 Hp/l"). The backend scraper's + * label match for "power" swallows "power per litre" first, so the field is + * named for horsepower but carries Hp/l. `labelFor()` sniffs the value. + * - Several fields are empty strings where the source page has no data. + * - `engineOilSpecification` is "?", the source site's paywall marker. + * - In-production models store an invalid end date, which the API emits as + * null rather than a year. + * + * ApiService reads from here while FIXTURES is on. Flip it off to go back to + * HTTP and nothing else needs to change. + */ + +/** + * Stand-in artwork, generated inline. + * + * The real logos and photos are served from auto-data.net, which blocks + * automated browsers outright, so a review build would show nothing. These + * draw the same shapes at the same aspect ratios: a mark for a marque logo, a + * landscape frame for a car photo. Revert LOGO and the plate() calls below to + * go back to the real URLs. + */ +const plate = (label: string, hue: number, w = 600, h = 400) => { + const svg = + `` + + `` + + `` + + `` + + `` + + `` + + `` + + `` + + `` + + `${label}`; + return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; +}; + +/** A badge-shaped mark with the marque initial, legible at header size. */ +const logoPlate = (name: string) => { + const svg = + `` + + `` + + `${name[0]}`; + return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; +}; + +const UPDATED = '2026-10-02T06:33:28.000Z'; + +const year = (y: number) => `${y}-01-01T05:00:00.000Z`; + +const brand = (id: number, name: string): Brand => ({ + id, + name, + url: `${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-brand-${id}`, + updatedAt: new Date(UPDATED), + imageUrl: logoPlate(name), + models: [], +}); + +const BRANDS: Brand[] = [ + brand(1, '212'), + brand(3, 'AC'), + brand(8, 'AITO'), + brand(9, 'Aiways'), + brand(10, 'Aixam'), + brand(11, 'Alfa Romeo'), + brand(12, 'Alpina'), + brand(13, 'Alpine'), + brand(17, 'Arcfox'), + brand(19, 'Ariel'), + brand(24, 'Aston Martin'), + brand(26, 'Audi'), + brand(28, 'Aurus'), + brand(30, 'Austin-Healey'), + brand(31, 'Autobianchi'), + brand(33, 'B.Engineering'), + brand(34, 'BAC'), + brand(36, 'Baltasar'), + brand(38, 'Baojun'), + brand(42, 'Bentley'), + brand(46, 'Bitter'), + brand(47, 'Bizzarrini'), + brand(49, 'BMW'), + brand(50, 'Bollinger'), + brand(52, 'Borgward'), + brand(53, 'Brabham'), + brand(55, 'Brilliance'), + brand(58, 'Bugatti'), + brand(59, 'Buick'), + brand(63, 'Cadillac'), + brand(66, 'Caterham'), + brand(70, 'Chevrolet'), + brand(76, 'Chrysler'), + brand(80, 'Citroen'), + brand(84, 'Cupra'), + brand(88, 'Dacia'), + brand(92, 'Daewoo'), + brand(95, 'Daihatsu'), + brand(98, 'Datsun'), + brand(101, 'Dodge'), + brand(105, 'DS'), + brand(110, 'Ferrari'), + brand(114, 'Fiat'), + brand(118, 'Ford'), + brand(124, 'Ghia'), + brand(128, 'GMC'), + brand(131, 'Hafei'), + brand(136, 'Holden'), + brand(140, 'Honda'), + brand(145, 'Hummer'), + brand(149, 'Hyundai'), + brand(153, 'Infiniti'), + brand(158, 'Isuzu'), + brand(162, 'Jaguar'), + brand(167, 'Jeep'), + brand(171, 'Kia'), + brand(175, 'Koenigsegg'), + brand(179, 'Lada'), + brand(183, 'Lamborghini'), + brand(188, 'Lancia'), + brand(192, 'Land Rover'), + brand(196, 'Lexus'), + brand(200, 'Ligier'), + brand(203, 'Lincoln'), + brand(206, 'Lotus'), + brand(210, 'Mahindra'), + brand(214, 'Maserati'), + brand(218, 'Mazda'), + brand(222, 'McLaren'), + brand(226, 'Mercedes-Benz'), + brand(230, 'Mini'), + brand(234, 'Mitsubishi'), + brand(238, 'Nissan'), + brand(242, 'Opel'), + brand(246, 'Peugeot'), + brand(250, 'Polestar'), + brand(254, 'Porsche'), + brand(258, 'Renault'), + brand(262, 'Rolls-Royce'), + brand(266, 'Saab'), + brand(270, 'Seat'), + brand(274, 'Skoda'), + brand(278, 'Smart'), + brand(282, 'SsangYong'), + brand(286, 'Subaru'), + brand(290, 'Suzuki'), + brand(294, 'Tesla'), + brand(298, 'Toyota'), + brand(302, 'Volkswagen'), + brand(306, 'Volvo'), + brand(310, 'Xpeng'), + brand(314, 'ZAZ'), +]; + +const model = ( + id: number, + name: string, + startYear: number, + endYear: number | null, + imageUrl: string, +): Model => ({ + id, + name, + url: `model-${id}`, + updatedAt: new Date(UPDATED), + startYear: new Date(year(startYear)), + // The API emits null for an in-production row, not a sentinel date. + endYear: endYear === null ? (null as never) : new Date(year(endYear)), + imageUrl, + brand: undefined as never, + generations: [], +}); + +/** Marks a model still in production. */ +const current = null; + +const ALFA_MODELS: Model[] = [ + model(122, 'GT', 1963, 2010, plate('GT', 210)), + model(120, 'Giulia', 1965, current, plate('Giulia', 12)), + model(129, 'Spider', 1966, 2010, plate('Spider', 268)), + model(109, '33', 1967, 1994, plate('33', 32)), + model(123, 'GTA Coupe', 1968, 1976, plate('GTA Coupe', 348)), + model(127, 'Montreal', 1970, 1977, plate('Montreal', 96)), + model(116, 'Alfasud', 1972, 1989, plate('Alfasud', 168)), + model(117, 'Alfetta', 1974, 1986, plate('Alfetta', 300)), + model(121, 'Giulietta', 1977, 2020, plate('Giulietta', 44)), + model(124, 'GTV', 1978, 2004, plate('GTV', 228)), + model(112, '6', 1979, 1988, plate('6', 132)), + model(118, 'Arna', 1983, 1986, plate('Arna', 316)), + model(115, '90', 1984, 1987, plate('90', 76)), + model(100, '145', 1994, 2000, plate('145', 4)), +]; + +const generation = ( + id: number, + name: string, + chassisType: string, + startYear: number, + endYear: number, +): Generation => ({ + id, + name, + url: `generation-${id}`, + updatedAt: new Date(UPDATED), + chassisType, + startYear: new Date(year(startYear)), + endYear: new Date(year(endYear)), + imageUrl: plate('145 930', 204), + model: undefined as never, + trims: [], +}); + +const G_145_GENERATIONS: Generation[] = [ + generation(1, 'Alfa Romeo 145 (930, facelift 1999)', 'Hatchback', 1999, 2000), + generation(2, 'Alfa Romeo 145 (930, facelift 1997)', 'Hatchback', 1997, 1999), + generation(3, 'Alfa Romeo 145 (930)', 'Hatchback', 1994, 1996), +]; + +const TRIM_IMAGES = [ + plate('Quadrifoglio', 8, 800, 500), + plate('Quadrifoglio', 26, 800, 500), + plate('Quadrifoglio', 44, 800, 500), + plate('Quadrifoglio', 8, 800, 500), + plate('Quadrifoglio', 26, 800, 500), + plate('Quadrifoglio', 44, 800, 500), +]; + +const trim = (id: number, name: string, startYear: number, endYear: number): Trim => ({ + id, + name, + url: `trim-${id}`, + updatedAt: new Date(UPDATED), + startYear: new Date(year(startYear)), + endYear: new Date(year(endYear)), + imageUrls: TRIM_IMAGES, + generation: undefined as never, + trimDetails: undefined as never, +}); + +const G1_TRIMS: Trim[] = [ + trim(1, '2.0 Twin Spark Quadrifoglio (155 Hp)', 1999, 2000), + trim(2, '1.9 JTD (105 Hp)', 1999, 2000), + trim(3, '1.8 Twin Spark 16V (144 Hp)', 1999, 2000), + trim(4, '1.6 Twin Spark 16V (120 Hp)', 1999, 2000), + trim(5, '1.4 Twin Spark 16V (103 Hp)', 1999, 2000), +]; + +/** Full scraped record for trim 1, empty strings included on purpose. */ +const TRIM_1_DETAILS: TrimDetails = { + id: 1, + name: '2.0 Twin Spark Quadrifoglio (155 Hp)', + url: 'alfa-romeo-145-930-facelift-1999-2.0-twin-spark-quadrifoglio-155hp-41204', + updatedAt: new Date(UPDATED), + brand: 'Alfa Romeo', + model: '145', + generation: '145 (930, facelift 1999)', + modification: '2.0 Twin Spark Quadrifoglio (155 Hp)', + startOfProduction: '1999', + endOfProduction: '2000', + powertrainArchitecture: 'Internal Combustion engine', + bodyType: 'Hatchback', + seats: '5', + doors: '3', + fuelConsumptionUrban: '12.5 l/100 km', + fuelConsumptionExtraUrban: '6.6 l/100 km', + fuelConsumptionCombined: '8.7 l/100 km', + co2Emissions: '210 g/km', + fuelType: 'Petrol (Gasoline)', + acceleration0100: '8.3 sec', + acceleration062: '8.3 sec', + acceleration060: '7.9 sec', + maximumSpeed: '211 km/h', + maximumEngineSpeed: '', + emissionStandard: 'Euro 2', + weightToPowerRatio: '8 kg/Hp, 125 Hp/tonne', + weightToTorqueRatio: '6.6 kg/Nm, 150.8 Nm/tonne', + power: '78.7 Hp/l', + powerPerLitre: '', + torque: '187 Nm @ 3500 rpm.', + engineLayout: 'Front, Transverse', + engineModelCode: 'AR 32301', + engineDisplacement: '1970 cm', + numberOfCylinders: '4', + engineConfiguration: 'Inline', + cylinderBore: '83 mm', + pistonStroke: '91 mm', + compressionRatio: '10:1', + valvesPerCylinder: '4', + fuelInjectionSystem: 'Multi-port manifold injection', + engineAspiration: 'Naturally aspirated engine', + valvetrain: 'DOHC', + engineOilCapacity: '4.4 l', + engineOilSpecification: '?', + coolantCapacity: '8.3 l', + kerbWeight: '1240 kg', + maxWeight: '1765 kg', + maxLoad: '525 kg', + trunkSpaceMin: '1130 l', + fuelTankCapacity: '51 l', + maxRoofLoad: '', + permittedTrailerLoadWithBrakes: '1200 kg', + permittedTrailerLoadWithoutBrakes: '350 kg', + permittedTowbarDownload: '50 kg', + length: '4061 mm', + width: '1712 mm', + widthIncludingMirrors: '', + height: '1431 mm', + wheelbase: '2540 mm', + frontTrack: '1468 mm', + rearTrack: '1441 mm', + rideHeight: '', + dragCoefficient: '', + minimumTurningCircle: '10.5 m', + driveWheel: 'Front wheel drive', + gearbox: '5 gears, manual transmission', + frontSuspension: 'Independent, McPherson type, Anti-roll bar', + rearSuspension: 'Anti-roll bar, Trailing arm, Coil spring', + frontBrakes: 'Disc, 284x21.8 mm', + rearBrakes: 'Drum, 228.7 mm', + assistingSystems: 'ABS (Anti-lock braking system)', + steeringType: '', + powerSteering: '', + tiresSize: '195/55 R 15', + wheelRimsSize: '6 J x 15', +}; + +const dieselDetails = (id: number, modification: string): TrimDetails => ({ + ...TRIM_1_DETAILS, + id, + modification, + name: modification, + power: '55.1 Hp/l', + torque: '290 Nm @ 3900 rpm.', + acceleration0100: '11.5 sec', + acceleration060: '11 sec', + maximumSpeed: '187 km/h', + fuelConsumptionUrban: '7.2 l/100 km', + fuelConsumptionExtraUrban: '4.4 l/100 km', + fuelConsumptionCombined: '5.4 l/100 km', + co2Emissions: '145 g/km', + fuelType: 'Diesel', + emissionStandard: 'Euro 2', + engineModelCode: 'AR 32303', + engineConfiguration: 'Inline', + numberOfCylinders: '4', + fuelInjectionSystem: 'Direct injection', + engineOilSpecification: '5W-40', +}); + +export const FIXTURES = { + getAllBrands(): Brand[] { + return BRANDS.map((b) => ({ ...b })); + }, + + getBrandWithModels(brandId: number): Brand { + const found = BRANDS.find((b) => b.id === brandId) ?? BRANDS[10]; + const models = + found.id === 11 ? ALFA_MODELS.map((m) => ({ ...m })) : ([ + model(900 + found.id, 'Model A', 1990, 2000, plate('Model A', 18)), + model(950 + found.id, 'Model B', 2004, current, plate('Model B', 190)), + ] as Model[]); + return {...found, models}; + }, + + getModelWithGenerations(modelId: number): Model { + const found = ALFA_MODELS.find((m) => m.id === modelId) ?? ALFA_MODELS[13]; + const parent = BRANDS.find((b) => b.id === 11) ?? BRANDS[0]; + // The real endpoint loads relations for generations *and* brand, so the + // model arrives with its marque attached. The header path relies on it. + return { + ...found, + brand: {...parent, models: []}, + generations: G_145_GENERATIONS.map((g) => ({...g})), + }; + }, + + getGenerationWithTrims(generationId: number): Generation { + const found = G_145_GENERATIONS.find((g) => g.id === generationId) ?? G_145_GENERATIONS[0]; + return {...found, trims: G1_TRIMS.map((t) => ({ ...t }))}; + }, + + getTrimDetails(trimId: number): Trim { + const found = G1_TRIMS.find((t) => t.id === trimId) ?? G1_TRIMS[0]; + const details = + found.id === 2 + ? dieselDetails(2, '1.9 JTD (105 Hp)') + : {...TRIM_1_DETAILS, id: found.id, name: found.name, modification: found.name}; + // The real endpoint loads relations for generation too. Without it a direct + // load of a trim URL has no parent to name in the header path. + const generation = G_145_GENERATIONS.find((g) => g.id === 1) ?? G_145_GENERATIONS[0]; + const parent = ALFA_MODELS.find((m) => m.id === 100) ?? ALFA_MODELS[13]; + return { + ...found, + generation: {...generation, trims: [], model: {...parent, generations: []}}, + trimDetails: details, + }; + }, +}; \ No newline at end of file diff --git a/frontend/src/app/format.ts b/frontend/src/app/format.ts new file mode 100644 index 0000000..d97e2b8 --- /dev/null +++ b/frontend/src/app/format.ts @@ -0,0 +1,235 @@ +import {TrimDetails} from '../../../library/src/models'; + +/** + * The canonical slug for a route segment. SlugifyPipe delegates here so the + * template and the router cannot drift apart on how a name becomes a URL. + */ +export function slugify(input: string): string { + return input.toString().toLowerCase() + .replace(/\s+/g, '_') + .replace(/[^\w\-]+/g, '') + .replace(/--+/g, '_') + .replace(/^-+/, '') + .replace(/-+$/, ''); +} + +export function entitySlug(name: string, id: number): string { + return slugify(name) + '-' + id; +} + +/** + * The production year of a date, or null when there isn't a usable one. + * + * An in-production row stores an invalid end date, which the API serialises as + * null. A guard on the year also catches a year-zero sentinel, so both shapes + * read as "still being built" instead of rendering 0000 or NaN. + */ +export function yearOf(value: Date | string | null | undefined): number | null { + if (value == null) return null; + const date = value instanceof Date ? value : new Date(value); + const time = date.getTime(); + if (Number.isNaN(time)) return null; + const year = date.getUTCFullYear(); + return year > 0 ? year : null; +} + +export function isInProduction(endYear: Date | string | null | undefined): boolean { + return yearOf(endYear) === null; +} + +/** "1994 – 2000", or "1965 – present" for a car still being built. */ +export function yearRange(start: Date | string | null | undefined, + end: Date | string | null | undefined): string { + const from = yearOf(start); + const to = yearOf(end); + if (from === null && to === null) return 'Years unknown'; + if (to === null) return from === null ? 'Present' : `${from} – present`; + if (from === null) return `– ${to}`; + return from === to ? `${from}` : `${from} – ${to}`; +} + +/** + * Spec labels, written out rather than derived from the field name, because + * the names are the product's copy: "co2Emissions" is not a label anyone wants + * to read. Keyed by TrimDetails field. + */ +const LABELS: Record = { + brand: 'Brand', + model: 'Model', + generation: 'Generation', + modification: 'Modification', + startOfProduction: 'Production start', + endOfProduction: 'Production end', + powertrainArchitecture: 'Powertrain', + bodyType: 'Body', + seats: 'Seats', + doors: 'Doors', + fuelConsumptionUrban: 'Fuel use, urban', + fuelConsumptionExtraUrban: 'Fuel use, extra urban', + fuelConsumptionCombined: 'Fuel use, combined', + co2Emissions: 'CO2 emissions', + fuelType: 'Fuel', + acceleration0100: '0 to 100 km/h', + acceleration062: '0 to 62 mph', + acceleration060: '0 to 60 mph', + maximumSpeed: 'Top speed', + maximumEngineSpeed: 'Maximum engine speed', + emissionStandard: 'Emission standard', + weightToPowerRatio: 'Weight to power', + weightToTorqueRatio: 'Weight to torque', + power: 'Power', + powerPerLitre: 'Power per litre', + torque: 'Torque', + engineLayout: 'Layout', + engineModelCode: 'Engine code', + engineDisplacement: 'Displacement', + numberOfCylinders: 'Cylinders', + engineConfiguration: 'Configuration', + cylinderBore: 'Bore', + pistonStroke: 'Stroke', + compressionRatio: 'Compression ratio', + valvesPerCylinder: 'Valves per cylinder', + fuelInjectionSystem: 'Fuel injection', + engineAspiration: 'Aspiration', + valvetrain: 'Valvetrain', + engineOilCapacity: 'Engine oil capacity', + engineOilSpecification: 'Engine oil spec', + coolantCapacity: 'Coolant capacity', + kerbWeight: 'Kerb weight', + maxWeight: 'Maximum weight', + maxLoad: 'Maximum load', + trunkSpaceMin: 'Boot space', + fuelTankCapacity: 'Fuel tank', + maxRoofLoad: 'Maximum roof load', + permittedTrailerLoadWithBrakes: 'Trailer load, braked', + permittedTrailerLoadWithoutBrakes: 'Trailer load, unbraked', + permittedTowbarDownload: 'Towbar download', + length: 'Length', + width: 'Width', + widthIncludingMirrors: 'Width over mirrors', + height: 'Height', + wheelbase: 'Wheelbase', + frontTrack: 'Front track', + rearTrack: 'Rear track', + rideHeight: 'Ride height', + dragCoefficient: 'Drag coefficient', + minimumTurningCircle: 'Turning circle', + driveWheel: 'Drive', + gearbox: 'Gearbox', + frontSuspension: 'Front suspension', + rearSuspension: 'Rear suspension', + frontBrakes: 'Front brakes', + rearBrakes: 'Rear brakes', + assistingSystems: 'Assisting systems', + steeringType: 'Steering', + powerSteering: 'Power steering', + tiresSize: 'Tyre size', + wheelRimsSize: 'Wheel size', +}; + +/** + * Resolves the label for a details field, correcting the power field's unit: + * the backend's label match for "power" catches "power per litre" first, so + * that field is named for horsepower but usually holds a per-litre figure. + * Labelling it from the value avoids repeating the wrong unit. + */ +export function detailsLabel(details: TrimDetails, key: keyof TrimDetails): string { + if (key === 'power') { + return /hp\s*\/\s*l/i.test(details.power ?? '') ? LABELS['powerPerLitre'] : LABELS['power']; + } + return LABELS[key as string] ?? String(key); +} + +/** A recorded value. The source uses "?" where its own data is locked. */ +export function hasValue(value: string | null | undefined): boolean { + return value != null && value.trim() !== '' && value.trim() !== '?'; +} + +export interface SpecGroup { + title: string; + rows: { key: keyof TrimDetails; label: string; value: string; locked: boolean }[]; +} + +/** + * The full record, grouped the way a spec sheet is read. Order within a group + * follows the source, so a familiar car spec is in the familiar place. + */ +export function groupDetails(details: TrimDetails): SpecGroup[] { + const groups: { title: string; keys: (keyof TrimDetails)[] }[] = [ + { + title: 'General', + keys: ['brand', 'model', 'generation', 'modification', 'startOfProduction', + 'endOfProduction', 'powertrainArchitecture', 'bodyType', 'seats', 'doors'], + }, + { + title: 'Performance', + keys: ['acceleration0100', 'acceleration060', 'acceleration062', 'maximumSpeed', + 'maximumEngineSpeed', 'fuelConsumptionUrban', 'fuelConsumptionExtraUrban', + 'fuelConsumptionCombined', 'co2Emissions', 'fuelType', 'emissionStandard', + 'weightToPowerRatio', 'weightToTorqueRatio'], + }, + { + title: 'Engine', + keys: ['power', 'powerPerLitre', 'torque', 'engineLayout', 'engineModelCode', + 'engineDisplacement', 'numberOfCylinders', 'engineConfiguration', 'cylinderBore', + 'pistonStroke', 'compressionRatio', 'valvesPerCylinder', 'fuelInjectionSystem', + 'engineAspiration', 'valvetrain', 'engineOilCapacity', 'engineOilSpecification', + 'coolantCapacity'], + }, + { + title: 'Weight and capacity', + keys: ['kerbWeight', 'maxWeight', 'maxLoad', 'trunkSpaceMin', 'fuelTankCapacity', + 'maxRoofLoad', 'permittedTrailerLoadWithBrakes', 'permittedTrailerLoadWithoutBrakes', + 'permittedTowbarDownload'], + }, + { + title: 'Dimensions', + keys: ['length', 'width', 'widthIncludingMirrors', 'height', 'wheelbase', + 'frontTrack', 'rearTrack', 'rideHeight', 'dragCoefficient', 'minimumTurningCircle'], + }, + { + title: 'Drivetrain and chassis', + keys: ['driveWheel', 'gearbox', 'frontSuspension', 'rearSuspension', 'frontBrakes', + 'rearBrakes', 'assistingSystems', 'steeringType', 'powerSteering', 'tiresSize', + 'wheelRimsSize'], + }, + ]; + + return groups + .map(({title, keys}) => { + const rows = keys.map((key) => { + const value = String(details[key] ?? ''); + return { + key, + label: detailsLabel(details, key), + value, + locked: value.trim() === '?', + }; + }); + // powerPerLitre is never populated: the generic "power" match above it + // claims every label containing "power". Drop the duplicate rather than + // show two rows with the same figure under different units. + const unique = rows.filter( + (row) => !(row.key === 'powerPerLitre' && (row.value === '' || row.value === rows.find((r) => r.key === 'power')?.value)), + ); + return {title, rows: unique}; + }) + .filter((group) => group.rows.length > 0); +} + +/** + * The five numbers that answer "what is this car, actually". Deliberately not + * power: the trim name already states it, and the field behind it is unreliable. + */ +export function headlineFigures(details: TrimDetails): { label: string; value: string }[] { + const figures = [ + {key: 'power' as keyof TrimDetails, label: detailsLabel(details, 'power')}, + {key: 'torque' as keyof TrimDetails, label: 'Torque'}, + {key: 'acceleration0100' as keyof TrimDetails, label: '0 to 100 km/h'}, + {key: 'maximumSpeed' as keyof TrimDetails, label: 'Top speed'}, + {key: 'fuelConsumptionCombined' as keyof TrimDetails, label: 'Fuel use, combined'}, + ]; + return figures + .filter(({key}) => hasValue(details[key] as string)) + .map(({key, label}) => ({label, value: (details[key] ?? '') as string})); +} \ No newline at end of file diff --git a/frontend/src/app/nav-state.ts b/frontend/src/app/nav-state.ts new file mode 100644 index 0000000..f45191f --- /dev/null +++ b/frontend/src/app/nav-state.ts @@ -0,0 +1,26 @@ +import {Injectable, signal} from '@angular/core'; + +/** One stop on the drill-down path. A null link is the level you are on. */ +export interface Crumb { + label: string; + /** + * Router link segments. Absolute from the site root, not relative to the + * current page: the pages live at nested depths, so a relative link would + * resolve to somewhere inside the current branch instead of at an ancestor. + */ + link: string[] | null; +} + +/** + * The path is four levels deep and the old build had no way back up it. The + * header shows the whole path at all times, so every page is one click from any + * ancestor. Pages publish their own crumbs as they load. + */ +@Injectable({providedIn: 'root'}) +export class NavState { + readonly crumbs = signal([]); + + set(crumbs: Crumb[]): void { + this.crumbs.set(crumbs); + } +} \ No newline at end of file diff --git a/frontend/src/app/slugify-pipe.ts b/frontend/src/app/slugify-pipe.ts index 494852b..3edb39e 100644 --- a/frontend/src/app/slugify-pipe.ts +++ b/frontend/src/app/slugify-pipe.ts @@ -1,17 +1,16 @@ import {Pipe, PipeTransform} from '@angular/core'; +import {slugify} from './format'; +/** + * Kept as a pipe for template use. The implementation lives in format.ts + * because route building needs the same slug outside a template, and two + * copies of this would be free to drift apart. + */ @Pipe({ name: 'slugify', }) export class SlugifyPipe implements PipeTransform { - transform(input: string): string { - return input.toString().toLowerCase() - .replace(/\s+/g, '_') // Replace spaces with - - .replace(/[^\w\-]+/g, '') // Remove all non-word chars - .replace(/--+/g, '_') // Replace multiple - with single - - .replace(/^-+/, '') // Trim - from start of text - .replace(/-+$/, ''); // Trim - from end of text + return slugify(input); } - -} +} \ No newline at end of file diff --git a/frontend/src/index.html b/frontend/src/index.html index 3a0692f..478757f 100644 --- a/frontend/src/index.html +++ b/frontend/src/index.html @@ -1,13 +1,17 @@ - + AutoDataWrapper - + + + + + - + \ No newline at end of file diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 90d4ee0..bd55e4b 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -1 +1,511 @@ -/* You can add global styles to this file, and also import other style files */ +/* AutoDataWrapper design tokens and shared primitives. + Kept global rather than per-component: the build caps component styles at + 4kB, and the recurring pieces (rows, spec tables, plates, tiles) are shared + by several pages. */ + +@import url('https://fonts.googleapis.com/css2?family=Archivo:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap'); + +:root { + /* Cool graphite stack. Panels separate by lightness, not by border + shadow. */ + --bg: #0f141b; + --panel: #161d26; + --raised: #1d2632; + --sunken: #0b0f15; + + --line: #273140; + --line-soft: #1e2733; + + --text: #e8edf4; + --dim: #9aa7b8; + /* Lightened from a dimmer grey that measured 3.9:1 on the page background, + under the 4.5:1 needed for small text. Now 5:1. */ + --faint: #78859a; + + /* Amber instrument signal. Only ever means "active" or "in production". */ + --signal: #ffb020; + --signal-wash: rgba(255, 176, 32, 0.1); + --signal-line: rgba(255, 176, 32, 0.32); + + --radius: 10px; + --radius-sm: 6px; + + --bar-h: 56px; + --gutter: clamp(1rem, 0.4rem + 2.4vw, 2.75rem); + + --ui: 'Archivo', system-ui, sans-serif; + --mono: 'JetBrains Mono', ui-monospace, monospace; + + --ease: cubic-bezier(0.2, 0.6, 0.2, 1); +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html { + background: var(--bg); + /* Anchor jumps must clear the fixed header. */ + scroll-padding-top: calc(var(--bar-h) + 1.5rem); +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: var(--ui); + font-size: 0.9375rem; + line-height: 1.55; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; +} + +h1, +h2, +h3, +p, +figure { + margin: 0; +} + +a { + color: inherit; + text-decoration: none; +} + +img { + display: block; + max-width: 100%; +} + +button { + font: inherit; + color: inherit; + background: none; + border: 0; + cursor: pointer; +} + +/* Focus is visible everywhere and always amber, so it reads as one system. */ +:focus-visible { + outline: 2px solid var(--signal); + outline-offset: 2px; + border-radius: 3px; +} + +::selection { + background: var(--signal); + color: #0f141b; +} + +/* ---------------------------------------------------------------- type ---- */ + +.display { + font-size: clamp(1.9rem, 1.2rem + 2.4vw, 3rem); + font-weight: 600; + line-height: 1.04; + letter-spacing: -0.028em; +} + +.subtitle { + font-size: 1.0625rem; + font-weight: 500; + letter-spacing: -0.012em; +} + +.meta { + font-size: 0.8125rem; + color: var(--dim); +} + +/* Meta items are separated by space alone. A dot between them would be + decoration standing in for a gap the layout can express directly. */ +.meta-line { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.125rem 0.875rem; + font-size: 0.8125rem; + color: var(--dim); +} + +/* Values that must line up on the decimal. Never used for labels. */ +.figure { + font-family: var(--mono); + font-variant-numeric: tabular-nums; + letter-spacing: -0.02em; +} + +/* Missing source data. A spec sheet states the absence rather than going blank. */ +.absent { + color: var(--faint); +} + +/* -------------------------------------------------------- page scaffold ---- */ + +.page { + max-width: 1180px; + margin: 0 auto; + padding: 2.25rem var(--gutter) 6rem; +} + +/* The amber rule is the one persistent accent: it marks which level of the + drill-down you are on. Structure, not decoration. */ +.page-head { + display: flex; + align-items: flex-start; + gap: 1.125rem; + padding-bottom: 1.375rem; + margin-bottom: 1.75rem; + border-bottom: 1px solid var(--line); +} + +.page-head::before { + content: ''; + width: 2px; + align-self: stretch; + flex-shrink: 0; + background: var(--signal); + border-radius: 2px; +} + +.page-head__body { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 0.3125rem; +} + +.page-head__title-row { + display: flex; + align-items: center; + gap: 0.875rem; + flex-wrap: wrap; +} + +.page-head__mark { + width: 36px; + height: 36px; + flex-shrink: 0; + object-fit: contain; + /* Logos are full-colour art on transparent; flattening them to white keeps + 398 of them from turning the index into confetti. */ + filter: grayscale(1) brightness(2.2); +} + +.page-head__count { + font-family: var(--mono); + font-size: 0.8125rem; + color: var(--dim); + white-space: nowrap; + flex-shrink: 0; + padding-top: 0.375rem; +} + +/* ------------------------------------------------------------- states ----- */ + +.state { + padding: 2.75rem 1.5rem; + text-align: center; + color: var(--dim); + background: var(--panel); + border: 1px dashed var(--line); + border-radius: var(--radius); +} + +.state strong { + display: block; + color: var(--text); + font-weight: 500; + margin-bottom: 0.25rem; +} + +/* Loading keeps the layout stable so nothing jumps when data lands. */ +.skeleton { + border-radius: var(--radius-sm); + background: linear-gradient(90deg, var(--panel) 25%, var(--raised) 37%, var(--panel) 63%); + background-size: 400% 100%; + animation: sweep 1.3s ease-in-out infinite; +} + +@keyframes sweep { + from { + background-position: 100% 50%; + } + to { + background-position: 0 50%; + } +} + +/* ------------------------------------------------------- production mark -- */ + +/* Amber = still built. Hollow = finished. One hue pair, no red/green. */ +.prod { + display: inline-flex; + align-items: center; + gap: 0.4375rem; + font-size: 0.75rem; + white-space: nowrap; + color: var(--faint); +} + +.prod::before { + content: ''; + width: 6px; + height: 6px; + border-radius: 50%; + border: 1px solid var(--line); +} + +.prod--live { + color: var(--signal); +} + +.prod--live::before { + background: var(--signal); + border-color: var(--signal); + box-shadow: 0 0 0 3px var(--signal-wash); +} + +/* ----------------------------------------------------------- model rows -- */ + +.rows { + border-top: 1px solid var(--line); +} + +.row { + position: relative; + display: grid; + grid-template-columns: 116px minmax(0, 1fr) auto; + align-items: center; + gap: 1.25rem; + padding: 0.6875rem 0.75rem; + border-bottom: 1px solid var(--line-soft); + cursor: pointer; + transition: background 0.15s var(--ease); +} + +.row:hover { + background: var(--panel); +} + +/* The amber tick marks the row under the pointer without shifting the layout. */ +.row__mark { + position: absolute; + left: 0; + top: 50%; + width: 2px; + height: 1.75rem; + margin-top: -0.875rem; + background: var(--signal); + border-radius: 0 2px 2px 0; + opacity: 0; + transform: scaleY(0.4); + transition: opacity 0.15s var(--ease), transform 0.15s var(--ease); +} + +.row:hover .row__mark { + opacity: 1; + transform: scaleY(1); +} + +.row__thumb { + width: 116px; + height: 72px; + object-fit: cover; + background: var(--sunken); + border-radius: var(--radius-sm); +} + +.row__body { + display: flex; + flex-direction: column; + gap: 0.125rem; + min-width: 0; +} + +.row__name { + font-size: 1rem; + font-weight: 500; + letter-spacing: -0.012em; +} + +.row__aside { + display: flex; + align-items: center; + gap: 1.25rem; +} + +.row__years { + font-family: var(--mono); + font-size: 0.8125rem; + color: var(--dim); + white-space: nowrap; +} + +/* ---------------------------------------------------------- spec tables --- */ + +.sheet { + width: 100%; + border-collapse: collapse; +} + +.sheet th, +.sheet td { + text-align: left; + padding: 0.5rem 0.75rem; + border-bottom: 1px solid var(--line-soft); + vertical-align: baseline; +} + +.sheet thead th { + font-size: 0.6875rem; + font-weight: 600; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--faint); + border-bottom-color: var(--line); + white-space: nowrap; +} + +.sheet tbody tr { + transition: background 0.15s var(--ease); +} + +.sheet tbody tr:hover { + background: var(--panel); +} + +.sheet__label { + font-size: 0.8125rem; + color: var(--dim); + font-weight: 400; +} + +.sheet__value { + font-family: var(--mono); + font-size: 0.8125rem; + text-align: right; + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.sheet__row-title { + font-size: 0.9375rem; + font-weight: 500; +} + +/* Fixed layout with every column given a width. Generation names run long + ("Alfa Romeo 145 (930, facelift 1999)") and, in an auto table, that string + starves the other columns and wraps to one word per line. */ +.sheet--gens { + table-layout: fixed; +} + +.sheet__col-name { + width: auto; +} + +.sheet__col-narrow { + width: 9rem; +} + +.sheet__col-years { + width: 10rem; +} + +/* The fixed columns are sized for the desktop table. At phone width they would + leave the generation name a couple of characters wide, so they tighten and + the name column takes the difference. */ +@media (max-width: 44rem) { + .sheet--gens { + width: 100%; + } + + .sheet__col-narrow { + width: 5.5rem; + } + + .sheet__col-years { + width: 6.75rem; + } + + .sheet--gens th, + .sheet--gens td { + padding-left: 0.5rem; + padding-right: 0.5rem; + } +} + +/* -------------------------------------------------------------- tiles ----- */ + +.tiles { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(248px, 1fr)); + /* A border lattice rather than a gap over a tinted background: with + auto-fill the last row is usually short, and a gap-filled grid paints the + empty remainder as one solid block that reads as a rendering fault. */ + border-top: 1px solid var(--line-soft); + border-left: 1px solid var(--line-soft); + border-radius: var(--radius); + overflow: hidden; +} + +.tile { + display: flex; + flex-direction: column; + border-right: 1px solid var(--line-soft); + border-bottom: 1px solid var(--line-soft); + transition: background 0.15s var(--ease); +} + +.tile:hover { + background: var(--panel); +} + +.tile__plate { + aspect-ratio: 16 / 10; + overflow: hidden; + background: var(--sunken); +} + +.tile__plate img { + width: 100%; + height: 100%; + object-fit: cover; + transition: transform 0.4s var(--ease); +} + +.tile:hover .tile__plate img { + transform: scale(1.035); +} + +.tile__body { + display: flex; + flex-direction: column; + gap: 0.1875rem; + padding: 0.75rem 0.875rem 0.875rem; +} + +.tile__name { + font-size: 0.9375rem; + font-weight: 500; + letter-spacing: -0.01em; + color: var(--text); + overflow-wrap: anywhere; +} + +/* ------------------------------------------------------ reduced motion ---- */ + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} \ No newline at end of file From 76c28ec53c7502e2bbf707175a6d9a7588a92bc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Raphael=20Vall=C3=A9e?= <72668371+Tranzitron@users.noreply.github.com> Date: Fri, 2 Oct 2026 23:04:39 -0400 Subject: [PATCH 2/3] Read from the backend instead of fixtures The redesign shipped with a fixture table and a `useFixtures` flag so the pages could be built while the backend was unrunnable. The backend runs, so the fixtures go: ApiService now only does HTTP, and fixtures.ts is deleted. Removing them exposed what the fixture had been papering over. - The API returns a generation without its model.brand, and a trim without its generation.model. The fixture attached them by hand, so a deep link looked fine there and would have lost breadcrumb levels here. Both endpoints now load the whole ancestor chain. - The rebuilt breadcrumb paths used one-segment links, which resolve against the current route. A model link reached the brand route, because both read the first segment as an id. Every crumb now carries the segments down to its own level. - The shared types claimed relations were always present and years were always Dates. The API genuinely sends `endYear: null` for a car still in production, and the fixture had to cast around it. Types now say so. - A failed load left the heading reading "Loading" above the failure message, on all four pages. - 28 of 42 trims have no scraped record. That page rendered as an empty spec column, which read as "this car has no specifications"; it now says the record has not been scraped and links to the source. One data bug, visible only against real rows: the assisting-systems cell ends with a `
`, so the scraper stored a value ending in ", ". Empty entries are now dropped. Five tests cover the shapes, and the 12 already stored rows are repaired by `bun run fix:assisting-systems`. Verified against the running backend: all 5 pages at 1280 and 390, no contrast failures, no overflow, real logos and photos. Backend 111 pass. --- backend/package.json | 1 + backend/scripts/fix-assisting-systems.ts | 43 ++ backend/src/data/fetch-provider.service.ts | 31 +- backend/test/fetch-provider.service.test.ts | 25 ++ backend/test/helpers/edge-cases.ts | 20 +- frontend/src/app/api.service.ts | 14 +- .../src/app/browse/brand/brand.component.html | 4 +- .../generation/generation.component.html | 4 +- .../browse/generation/generation.component.ts | 35 +- .../src/app/browse/model/model.component.html | 4 +- .../trim-details/trim-details.component.html | 18 +- .../trim-details/trim-details.component.ts | 44 +- frontend/src/app/fixtures.ts | 406 ------------------ frontend/src/styles.css | 22 +- library/src/models.ts | 37 +- 15 files changed, 236 insertions(+), 472 deletions(-) create mode 100644 backend/scripts/fix-assisting-systems.ts delete mode 100644 frontend/src/app/fixtures.ts diff --git a/backend/package.json b/backend/package.json index afd1778..75fb5a7 100644 --- a/backend/package.json +++ b/backend/package.json @@ -15,6 +15,7 @@ "test:live": "LIVE_SCRAPER=1 bun test --isolate test/live-scraper.test.ts", "record:fixtures": "bun run scripts/record-scraper-pages.ts", "sync:db": "bun run scripts/sync-db.ts", + "fix:assisting-systems": "bun run scripts/fix-assisting-systems.ts", "smoke:sqlite": "bun scripts/smoke-sqlite.ts" }, "prettier": { diff --git a/backend/scripts/fix-assisting-systems.ts b/backend/scripts/fix-assisting-systems.ts new file mode 100644 index 0000000..47d56f2 --- /dev/null +++ b/backend/scripts/fix-assisting-systems.ts @@ -0,0 +1,43 @@ +/** + * Repairs trim_details rows stored before the trailing-
fix in + * scrapeTrimDetailsByTrimUrl: a cell whose last
had no entry after it + * became a value ending in ", ", which the UI then rendered verbatim. + * + * Only rows that still carry the old shape are touched, and only their + * trailing separator is removed, so a legitimately comma-ended value cannot be + * mangled. Idempotent: a second run finds nothing to do. + * + * bun run scripts/fix-assisting-systems.ts + */ +import {AppDataSource} from "../src/data-source"; +import {TrimDetails} from "../src/entity/entities"; + +await AppDataSource.initialize(); + +try { + // A stored value ends in the separator only because of the bug, so the + // trailing ", " is the whole of the damage. + const affected = await AppDataSource.manager + .createQueryBuilder(TrimDetails, "details") + .where("details.assistingSystems LIKE :suffix", {suffix: "%,%"}) + .getMany(); + + console.log(`rows ending in a separator: ${affected.length}`); + for (const details of affected) { + console.log(` ${details.id}: ${JSON.stringify(details.assistingSystems)}`); + } + + for (const details of affected) { + details.assistingSystems = details.assistingSystems.replace(/,[\s,]*$/, "").trimEnd(); + await AppDataSource.manager.save(details); + } + console.log(`updated ${affected.length}`); + + const remaining = await AppDataSource.manager + .createQueryBuilder(TrimDetails, "details") + .where("details.assistingSystems LIKE :suffix", {suffix: "%,%"}) + .getCount(); + console.log(`still ending in a separator: ${remaining}`); +} finally { + await AppDataSource.destroy(); +} \ No newline at end of file diff --git a/backend/src/data/fetch-provider.service.ts b/backend/src/data/fetch-provider.service.ts index a87ef01..172f33c 100644 --- a/backend/src/data/fetch-provider.service.ts +++ b/backend/src/data/fetch-provider.service.ts @@ -229,9 +229,15 @@ export class FetchProvider { where: { id: generationId, }, + // The model carries its brand, and a deep link to a generation has no + // other way to name the marque: there is no page above it to inherit + // the path from, so a missing brand here shows up as a path that + // starts at the model. relations: { trims: true, - model: true, + model: { + brand: true, + }, }, }); @@ -251,8 +257,16 @@ export class FetchProvider { where: { id: trimId, }, + // The whole ancestor chain, not just the generation. A deep link to a + // trim is the one page with no page above it to inherit a path from, + // so anything missing here is a breadcrumb that cannot be rendered + // or linked. relations: { - generation: true, + generation: { + model: { + brand: true, + }, + }, trimDetails: true, }, }); @@ -590,9 +604,16 @@ export class FetchProvider { else if (label.includes('front brakes')) trimDetails.frontBrakes = value; else if (label.includes('rear brakes')) trimDetails.rearBrakes = value; else if (label.includes('assisting systems')) { - const systems = Array.from(td.querySelectorAll('br')).map(() => ''); - const text = td.innerHTML.replace(//g, '|').replace(/<[^>]*>/g, ''); - trimDetails.assistingSystems = text.replace(/\|/g, ', ').trim(); + // The list is
-separated inside one cell. Turning each + // break into a separator, then dropping empty entries, is + // what keeps a trailing
- which the real pages carry - + // from becoming a value that ends in ", ". + const marked = td.innerHTML.replace(//gi, '\n').replace(/<[^>]*>/g, ''); + trimDetails.assistingSystems = marked + .split('\n') + .map((entry) => entry.replace(/\s+/g, ' ').trim()) + .filter((entry) => entry !== '') + .join(', '); } else if (label.includes('steering type') && !label.includes('power')) trimDetails.steeringType = value; else if (label.includes('power steering')) trimDetails.powerSteering = value; // The site labels this "Tire size" now; "Tires size"/"Tyres size" before. diff --git a/backend/test/fetch-provider.service.test.ts b/backend/test/fetch-provider.service.test.ts index b420845..7f5ce1f 100644 --- a/backend/test/fetch-provider.service.test.ts +++ b/backend/test/fetch-provider.service.test.ts @@ -3,6 +3,7 @@ import type {EntityManager} from "typeorm"; import {Brand, Generation, Model, Trim, TrimDetails} from "../src/entity/entities"; import { + ASSISTING_SYSTEMS_SHAPES, BRANDS_WITH_GAPS, BRANDS_WITH_IMAGE_URL_SHAPES, DETAILS_WITH_GAPS, @@ -574,6 +575,30 @@ describe("FetchProvider", () => { expect(found?.trimDetails?.seats).toBe(""); }); + // One test per shape rather than one page carrying them all: a page + // yields a single value per label, so several rows of the same label + // would only ever assert the last one. + test.each(ASSISTING_SYSTEMS_SHAPES)( + "joins the assisting systems list without stray separators: $expected", + async ({html, expected}) => { + const {trim} = await seedFullChain(); + RecordedScraper.serveHtml(` +
+
+
Brand
BMW
+
Assisting systems
+
${html}
+
+
+
+ `); + + const found = await new FetchProvider().getTrimWithDetails(trim.id); + + expect(found?.trimDetails?.assistingSystems).toBe(expected); + }, + ); + test("does not crash when the specification is missing entirely", async () => { const {trim} = await seedFullChain(); RecordedScraper.serveHtml(EMPTY_PAGE); diff --git a/backend/test/helpers/edge-cases.ts b/backend/test/helpers/edge-cases.ts index 665ce5a..aaddc35 100644 --- a/backend/test/helpers/edge-cases.ts +++ b/backend/test/helpers/edge-cases.ts @@ -160,4 +160,22 @@ export const DETAILS_WITH_GAPS = `
Tire size
205/55 R16
-`; \ No newline at end of file +`; + +/** + * The
-separated "Assisting systems" cell in the shapes the real trim pages + * produce. Separate from DETAILS_WITH_GAPS because one page yields one value + * per label: adding these rows there would only test whichever came last. + * + * The trailing and doubled breaks are the point. A live trim page ends the + * cell with a break, and the source nests its entries across lines, so both + * produce an empty entry that must not become a trailing ", " or a blank + * between two systems. + */ +export const ASSISTING_SYSTEMS_SHAPES: {html: string, expected: string}[] = [ + {html: 'ABS
ESP
TCS', expected: 'ABS, ESP, TCS'}, + {html: 'ABS (Anti-lock braking system)
', expected: 'ABS (Anti-lock braking system)'}, + {html: 'ABS
\n ESP', expected: 'ABS, ESP'}, + {html: 'ABS

ESP', expected: 'ABS, ESP'}, + {html: 'ABS', expected: 'ABS'}, +]; \ No newline at end of file diff --git a/frontend/src/app/api.service.ts b/frontend/src/app/api.service.ts index f4301af..16dae8f 100644 --- a/frontend/src/app/api.service.ts +++ b/frontend/src/app/api.service.ts @@ -2,7 +2,6 @@ import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {lastValueFrom} from 'rxjs'; import {Brand, Generation, Model, Trim} from "../../../library/src/models"; -import {FIXTURES} from './fixtures'; @Injectable({ providedIn: 'root', @@ -10,37 +9,26 @@ import {FIXTURES} from './fixtures'; export class ApiService { serverUrl = "http://localhost:3000/"; - /** - * Set to false to read from the backend again. Nothing else changes: the - * fixture table returns the same shapes the endpoints serialise. - */ - private readonly useFixtures = true; - constructor(public http: HttpClient,) { } async getAllBrands(): Promise { - if (this.useFixtures) return FIXTURES.getAllBrands(); return await lastValueFrom(this.http.get(this.serverUrl + 'brands')); } async getBrandWithModels(brandId: number): Promise { - if (this.useFixtures) return FIXTURES.getBrandWithModels(brandId); return await lastValueFrom(this.http.get(this.serverUrl + 'brand/' + brandId)); } async getModelWithGenerations(modelId: number): Promise { - if (this.useFixtures) return FIXTURES.getModelWithGenerations(modelId); return await lastValueFrom(this.http.get(this.serverUrl + 'model/' + modelId)); } async getGenerationWithTrims(generationId: number): Promise { - if (this.useFixtures) return FIXTURES.getGenerationWithTrims(generationId); return await lastValueFrom(this.http.get(this.serverUrl + 'generation/' + generationId)); } async getTrimDetails(trimId: number): Promise { - if (this.useFixtures) return FIXTURES.getTrimDetails(trimId); return await lastValueFrom(this.http.get(this.serverUrl + 'trim/' + trimId)); } -} \ No newline at end of file +} diff --git a/frontend/src/app/browse/brand/brand.component.html b/frontend/src/app/browse/brand/brand.component.html index 321693b..a1dd59b 100644 --- a/frontend/src/app/browse/brand/brand.component.html +++ b/frontend/src/app/browse/brand/brand.component.html @@ -15,7 +15,9 @@

{{ b.name }}

} @else {
-

Loading

+ +

{{ failed() ? 'Not found' : 'Loading' }}

} diff --git a/frontend/src/app/browse/generation/generation.component.html b/frontend/src/app/browse/generation/generation.component.html index ab6bade..9d756d9 100644 --- a/frontend/src/app/browse/generation/generation.component.html +++ b/frontend/src/app/browse/generation/generation.component.html @@ -11,7 +11,9 @@

{{ g.name }}

} @else {
-

Loading

+ +

{{ failed() ? 'Not found' : 'Loading' }}

} diff --git a/frontend/src/app/browse/generation/generation.component.ts b/frontend/src/app/browse/generation/generation.component.ts index ff62f41..91a5275 100644 --- a/frontend/src/app/browse/generation/generation.component.ts +++ b/frontend/src/app/browse/generation/generation.component.ts @@ -1,6 +1,6 @@ import {ChangeDetectionStrategy, Component, OnInit, inject, signal} from '@angular/core'; import {ActivatedRoute, RouterLink} from '@angular/router'; -import {Generation, Trim} from "../../../../../library/src/models"; +import {Brand, Generation, Trim} from "../../../../../library/src/models"; import {ApiService} from '../../api.service'; import {Crumb, NavState} from '../../nav-state'; import {entitySlug, yearRange} from '../../format'; @@ -49,22 +49,33 @@ export class GenerationComponent implements OnInit { /** * Normally the model page has already published the path, so this only - * appends to it. On a direct load of a deep link the path starts empty, and - * the model name on the generation record is the most that is known without - * another request. + * appends to it. On a direct load of a deep link the path starts empty and + * has to be rebuilt from the record, which arrives with its model and the + * model's brand. + * + * The links are absolute segment lists, not just a slug: the model route sits + * at /browse/:brandId/:modelId, so a one-segment link would be read as a + * brand id and land on the wrong page. */ private pathFor(generation: Generation): Crumb[] { const self: Crumb = {label: generation.name, link: null}; const inherited = this.nav.crumbs(); if (inherited.length > 0) return [...inherited, self]; - const parent = generation.model; - return parent - ? [ - {label: 'Brands', link: ['/browse']}, - {label: parent.name, link: ['/browse', entitySlug(parent.name, parent.id)]}, - self, - ] - : [{label: 'Brands', link: ['/browse']}, self]; + + const model = generation.model; + if (!model) return [{label: 'Brands', link: ['/browse']}, self]; + const brand = model.brand; + return [ + {label: 'Brands', link: ['/browse']}, + ...(brand ? [{label: brand.name, link: ['/browse', entitySlug(brand.name, brand.id)]}] : []), + {label: model.name, link: ['/browse', ...this.ancestors(brand), entitySlug(model.name, model.id)]}, + self, + ]; + } + + /** The brand segments a deeper route has to repeat to stay addressable. */ + private ancestors(brand: Brand | undefined): string[] { + return brand ? [entitySlug(brand.name, brand.id)] : []; } years(start: Date | string | null, end: Date | string | null): string { diff --git a/frontend/src/app/browse/model/model.component.html b/frontend/src/app/browse/model/model.component.html index 4b225f0..3db74a4 100644 --- a/frontend/src/app/browse/model/model.component.html +++ b/frontend/src/app/browse/model/model.component.html @@ -10,7 +10,9 @@

{{ m.name }}

} @else {
-

Loading

+ +

{{ failed() ? 'Not found' : 'Loading' }}

} diff --git a/frontend/src/app/browse/trim-details/trim-details.component.html b/frontend/src/app/browse/trim-details/trim-details.component.html index 843230f..4506f31 100644 --- a/frontend/src/app/browse/trim-details/trim-details.component.html +++ b/frontend/src/app/browse/trim-details/trim-details.component.html @@ -19,7 +19,9 @@

{{ t.name }}

} @else {
-

Loading

+ +

{{ failed() ? 'Not found' : 'Loading' }}

} @@ -87,6 +89,20 @@

{{ group.title }}

+ } @empty { + +

+ No specification recorded + This trim has no scraped specification sheet yet. The source page has + @if (trim()?.url) { + the figures here. + } @else { + the figures. + } +

} diff --git a/frontend/src/app/browse/trim-details/trim-details.component.ts b/frontend/src/app/browse/trim-details/trim-details.component.ts index 293fb6e..1329b23 100644 --- a/frontend/src/app/browse/trim-details/trim-details.component.ts +++ b/frontend/src/app/browse/trim-details/trim-details.component.ts @@ -1,5 +1,5 @@ import {ChangeDetectionStrategy, Component, OnInit, inject, signal} from '@angular/core'; -import {ActivatedRoute, Router} from '@angular/router'; +import {ActivatedRoute} from '@angular/router'; import {Trim, TrimDetails} from "../../../../../library/src/models"; import {ApiService} from '../../api.service'; import {Crumb, NavState} from '../../nav-state'; @@ -14,7 +14,6 @@ import {SpecGroup, entitySlug, groupDetails, headlineFigures, yearRange} from '. }) export class TrimDetailsComponent implements OnInit { private readonly route = inject(ActivatedRoute); - private readonly router = inject(Router); private readonly api = inject(ApiService); private readonly nav = inject(NavState); @@ -54,21 +53,41 @@ export class TrimDetailsComponent implements OnInit { } } - /** Appends to the path the generation page published, as with generations. */ + /** + * Appends to the path the generation page published, as with generations. On a + * direct load of a deep link there is nothing to inherit, so the chain is + * rebuilt from the record, which arrives with its generation, that + * generation's model, and the model's brand. + * + * The links carry every segment down to their own level, not just a slug: each + * route is nested under the one above it, so a short link resolves against the + * current route and lands somewhere else entirely. + */ private pathFor(trim: Trim): Crumb[] { - const generation = trim.generation; const self: Crumb = {label: trim.name, link: null}; const inherited = this.nav.crumbs(); if (inherited.length > 0) return [...inherited, self]; + + const generation = trim.generation; if (!generation) return [{label: 'Brands', link: ['/browse']}, self]; + + const model = generation.model; + if (!model) { + return [ + {label: 'Brands', link: ['/browse']}, + {label: generation.name, link: null}, + self, + ]; + } + + const brand = model.brand; + const brandSegments = brand ? [entitySlug(brand.name, brand.id)] : []; + const modelSegments = [...brandSegments, entitySlug(model.name, model.id)]; return [ {label: 'Brands', link: ['/browse']}, - { - label: generation.model?.name ?? generation.name, - link: generation.model - ? ['/browse', entitySlug(generation.model.name, generation.model.id)] - : null, - }, + ...(brand ? [{label: brand.name, link: ['/browse', ...brandSegments]}] : []), + {label: model.name, link: ['/browse', ...modelSegments]}, + {label: generation.name, link: ['/browse', ...modelSegments, entitySlug(generation.name, generation.id)]}, self, ]; } @@ -91,11 +110,6 @@ export class TrimDetailsComponent implements OnInit { this.photo.set(index); } - goToGeneration(): void { - const generation = this.trim()?.generation; - if (generation) void this.router.navigate([entitySlug(generation.name, generation.id)]); - } - onImageError(event: Event): void { // Leaves the empty plate showing rather than a broken-image glyph. (event.target as HTMLImageElement).style.visibility = 'hidden'; diff --git a/frontend/src/app/fixtures.ts b/frontend/src/app/fixtures.ts deleted file mode 100644 index ca08d62..0000000 --- a/frontend/src/app/fixtures.ts +++ /dev/null @@ -1,406 +0,0 @@ -import {Brand, Generation, Model, Trim, TrimDetails} from '../../../library/src/models'; - -/** - * TEMPORARY fixture data so the UI can be built and reviewed without the - * backend running. Values are lifted from the dev database, including its - * rough edges, because those are what the layout has to survive: - * - * - `power` holds a per-litre figure ("78.7 Hp/l"). The backend scraper's - * label match for "power" swallows "power per litre" first, so the field is - * named for horsepower but carries Hp/l. `labelFor()` sniffs the value. - * - Several fields are empty strings where the source page has no data. - * - `engineOilSpecification` is "?", the source site's paywall marker. - * - In-production models store an invalid end date, which the API emits as - * null rather than a year. - * - * ApiService reads from here while FIXTURES is on. Flip it off to go back to - * HTTP and nothing else needs to change. - */ - -/** - * Stand-in artwork, generated inline. - * - * The real logos and photos are served from auto-data.net, which blocks - * automated browsers outright, so a review build would show nothing. These - * draw the same shapes at the same aspect ratios: a mark for a marque logo, a - * landscape frame for a car photo. Revert LOGO and the plate() calls below to - * go back to the real URLs. - */ -const plate = (label: string, hue: number, w = 600, h = 400) => { - const svg = - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `` + - `${label}`; - return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; -}; - -/** A badge-shaped mark with the marque initial, legible at header size. */ -const logoPlate = (name: string) => { - const svg = - `` + - `` + - `${name[0]}`; - return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; -}; - -const UPDATED = '2026-10-02T06:33:28.000Z'; - -const year = (y: number) => `${y}-01-01T05:00:00.000Z`; - -const brand = (id: number, name: string): Brand => ({ - id, - name, - url: `${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-brand-${id}`, - updatedAt: new Date(UPDATED), - imageUrl: logoPlate(name), - models: [], -}); - -const BRANDS: Brand[] = [ - brand(1, '212'), - brand(3, 'AC'), - brand(8, 'AITO'), - brand(9, 'Aiways'), - brand(10, 'Aixam'), - brand(11, 'Alfa Romeo'), - brand(12, 'Alpina'), - brand(13, 'Alpine'), - brand(17, 'Arcfox'), - brand(19, 'Ariel'), - brand(24, 'Aston Martin'), - brand(26, 'Audi'), - brand(28, 'Aurus'), - brand(30, 'Austin-Healey'), - brand(31, 'Autobianchi'), - brand(33, 'B.Engineering'), - brand(34, 'BAC'), - brand(36, 'Baltasar'), - brand(38, 'Baojun'), - brand(42, 'Bentley'), - brand(46, 'Bitter'), - brand(47, 'Bizzarrini'), - brand(49, 'BMW'), - brand(50, 'Bollinger'), - brand(52, 'Borgward'), - brand(53, 'Brabham'), - brand(55, 'Brilliance'), - brand(58, 'Bugatti'), - brand(59, 'Buick'), - brand(63, 'Cadillac'), - brand(66, 'Caterham'), - brand(70, 'Chevrolet'), - brand(76, 'Chrysler'), - brand(80, 'Citroen'), - brand(84, 'Cupra'), - brand(88, 'Dacia'), - brand(92, 'Daewoo'), - brand(95, 'Daihatsu'), - brand(98, 'Datsun'), - brand(101, 'Dodge'), - brand(105, 'DS'), - brand(110, 'Ferrari'), - brand(114, 'Fiat'), - brand(118, 'Ford'), - brand(124, 'Ghia'), - brand(128, 'GMC'), - brand(131, 'Hafei'), - brand(136, 'Holden'), - brand(140, 'Honda'), - brand(145, 'Hummer'), - brand(149, 'Hyundai'), - brand(153, 'Infiniti'), - brand(158, 'Isuzu'), - brand(162, 'Jaguar'), - brand(167, 'Jeep'), - brand(171, 'Kia'), - brand(175, 'Koenigsegg'), - brand(179, 'Lada'), - brand(183, 'Lamborghini'), - brand(188, 'Lancia'), - brand(192, 'Land Rover'), - brand(196, 'Lexus'), - brand(200, 'Ligier'), - brand(203, 'Lincoln'), - brand(206, 'Lotus'), - brand(210, 'Mahindra'), - brand(214, 'Maserati'), - brand(218, 'Mazda'), - brand(222, 'McLaren'), - brand(226, 'Mercedes-Benz'), - brand(230, 'Mini'), - brand(234, 'Mitsubishi'), - brand(238, 'Nissan'), - brand(242, 'Opel'), - brand(246, 'Peugeot'), - brand(250, 'Polestar'), - brand(254, 'Porsche'), - brand(258, 'Renault'), - brand(262, 'Rolls-Royce'), - brand(266, 'Saab'), - brand(270, 'Seat'), - brand(274, 'Skoda'), - brand(278, 'Smart'), - brand(282, 'SsangYong'), - brand(286, 'Subaru'), - brand(290, 'Suzuki'), - brand(294, 'Tesla'), - brand(298, 'Toyota'), - brand(302, 'Volkswagen'), - brand(306, 'Volvo'), - brand(310, 'Xpeng'), - brand(314, 'ZAZ'), -]; - -const model = ( - id: number, - name: string, - startYear: number, - endYear: number | null, - imageUrl: string, -): Model => ({ - id, - name, - url: `model-${id}`, - updatedAt: new Date(UPDATED), - startYear: new Date(year(startYear)), - // The API emits null for an in-production row, not a sentinel date. - endYear: endYear === null ? (null as never) : new Date(year(endYear)), - imageUrl, - brand: undefined as never, - generations: [], -}); - -/** Marks a model still in production. */ -const current = null; - -const ALFA_MODELS: Model[] = [ - model(122, 'GT', 1963, 2010, plate('GT', 210)), - model(120, 'Giulia', 1965, current, plate('Giulia', 12)), - model(129, 'Spider', 1966, 2010, plate('Spider', 268)), - model(109, '33', 1967, 1994, plate('33', 32)), - model(123, 'GTA Coupe', 1968, 1976, plate('GTA Coupe', 348)), - model(127, 'Montreal', 1970, 1977, plate('Montreal', 96)), - model(116, 'Alfasud', 1972, 1989, plate('Alfasud', 168)), - model(117, 'Alfetta', 1974, 1986, plate('Alfetta', 300)), - model(121, 'Giulietta', 1977, 2020, plate('Giulietta', 44)), - model(124, 'GTV', 1978, 2004, plate('GTV', 228)), - model(112, '6', 1979, 1988, plate('6', 132)), - model(118, 'Arna', 1983, 1986, plate('Arna', 316)), - model(115, '90', 1984, 1987, plate('90', 76)), - model(100, '145', 1994, 2000, plate('145', 4)), -]; - -const generation = ( - id: number, - name: string, - chassisType: string, - startYear: number, - endYear: number, -): Generation => ({ - id, - name, - url: `generation-${id}`, - updatedAt: new Date(UPDATED), - chassisType, - startYear: new Date(year(startYear)), - endYear: new Date(year(endYear)), - imageUrl: plate('145 930', 204), - model: undefined as never, - trims: [], -}); - -const G_145_GENERATIONS: Generation[] = [ - generation(1, 'Alfa Romeo 145 (930, facelift 1999)', 'Hatchback', 1999, 2000), - generation(2, 'Alfa Romeo 145 (930, facelift 1997)', 'Hatchback', 1997, 1999), - generation(3, 'Alfa Romeo 145 (930)', 'Hatchback', 1994, 1996), -]; - -const TRIM_IMAGES = [ - plate('Quadrifoglio', 8, 800, 500), - plate('Quadrifoglio', 26, 800, 500), - plate('Quadrifoglio', 44, 800, 500), - plate('Quadrifoglio', 8, 800, 500), - plate('Quadrifoglio', 26, 800, 500), - plate('Quadrifoglio', 44, 800, 500), -]; - -const trim = (id: number, name: string, startYear: number, endYear: number): Trim => ({ - id, - name, - url: `trim-${id}`, - updatedAt: new Date(UPDATED), - startYear: new Date(year(startYear)), - endYear: new Date(year(endYear)), - imageUrls: TRIM_IMAGES, - generation: undefined as never, - trimDetails: undefined as never, -}); - -const G1_TRIMS: Trim[] = [ - trim(1, '2.0 Twin Spark Quadrifoglio (155 Hp)', 1999, 2000), - trim(2, '1.9 JTD (105 Hp)', 1999, 2000), - trim(3, '1.8 Twin Spark 16V (144 Hp)', 1999, 2000), - trim(4, '1.6 Twin Spark 16V (120 Hp)', 1999, 2000), - trim(5, '1.4 Twin Spark 16V (103 Hp)', 1999, 2000), -]; - -/** Full scraped record for trim 1, empty strings included on purpose. */ -const TRIM_1_DETAILS: TrimDetails = { - id: 1, - name: '2.0 Twin Spark Quadrifoglio (155 Hp)', - url: 'alfa-romeo-145-930-facelift-1999-2.0-twin-spark-quadrifoglio-155hp-41204', - updatedAt: new Date(UPDATED), - brand: 'Alfa Romeo', - model: '145', - generation: '145 (930, facelift 1999)', - modification: '2.0 Twin Spark Quadrifoglio (155 Hp)', - startOfProduction: '1999', - endOfProduction: '2000', - powertrainArchitecture: 'Internal Combustion engine', - bodyType: 'Hatchback', - seats: '5', - doors: '3', - fuelConsumptionUrban: '12.5 l/100 km', - fuelConsumptionExtraUrban: '6.6 l/100 km', - fuelConsumptionCombined: '8.7 l/100 km', - co2Emissions: '210 g/km', - fuelType: 'Petrol (Gasoline)', - acceleration0100: '8.3 sec', - acceleration062: '8.3 sec', - acceleration060: '7.9 sec', - maximumSpeed: '211 km/h', - maximumEngineSpeed: '', - emissionStandard: 'Euro 2', - weightToPowerRatio: '8 kg/Hp, 125 Hp/tonne', - weightToTorqueRatio: '6.6 kg/Nm, 150.8 Nm/tonne', - power: '78.7 Hp/l', - powerPerLitre: '', - torque: '187 Nm @ 3500 rpm.', - engineLayout: 'Front, Transverse', - engineModelCode: 'AR 32301', - engineDisplacement: '1970 cm', - numberOfCylinders: '4', - engineConfiguration: 'Inline', - cylinderBore: '83 mm', - pistonStroke: '91 mm', - compressionRatio: '10:1', - valvesPerCylinder: '4', - fuelInjectionSystem: 'Multi-port manifold injection', - engineAspiration: 'Naturally aspirated engine', - valvetrain: 'DOHC', - engineOilCapacity: '4.4 l', - engineOilSpecification: '?', - coolantCapacity: '8.3 l', - kerbWeight: '1240 kg', - maxWeight: '1765 kg', - maxLoad: '525 kg', - trunkSpaceMin: '1130 l', - fuelTankCapacity: '51 l', - maxRoofLoad: '', - permittedTrailerLoadWithBrakes: '1200 kg', - permittedTrailerLoadWithoutBrakes: '350 kg', - permittedTowbarDownload: '50 kg', - length: '4061 mm', - width: '1712 mm', - widthIncludingMirrors: '', - height: '1431 mm', - wheelbase: '2540 mm', - frontTrack: '1468 mm', - rearTrack: '1441 mm', - rideHeight: '', - dragCoefficient: '', - minimumTurningCircle: '10.5 m', - driveWheel: 'Front wheel drive', - gearbox: '5 gears, manual transmission', - frontSuspension: 'Independent, McPherson type, Anti-roll bar', - rearSuspension: 'Anti-roll bar, Trailing arm, Coil spring', - frontBrakes: 'Disc, 284x21.8 mm', - rearBrakes: 'Drum, 228.7 mm', - assistingSystems: 'ABS (Anti-lock braking system)', - steeringType: '', - powerSteering: '', - tiresSize: '195/55 R 15', - wheelRimsSize: '6 J x 15', -}; - -const dieselDetails = (id: number, modification: string): TrimDetails => ({ - ...TRIM_1_DETAILS, - id, - modification, - name: modification, - power: '55.1 Hp/l', - torque: '290 Nm @ 3900 rpm.', - acceleration0100: '11.5 sec', - acceleration060: '11 sec', - maximumSpeed: '187 km/h', - fuelConsumptionUrban: '7.2 l/100 km', - fuelConsumptionExtraUrban: '4.4 l/100 km', - fuelConsumptionCombined: '5.4 l/100 km', - co2Emissions: '145 g/km', - fuelType: 'Diesel', - emissionStandard: 'Euro 2', - engineModelCode: 'AR 32303', - engineConfiguration: 'Inline', - numberOfCylinders: '4', - fuelInjectionSystem: 'Direct injection', - engineOilSpecification: '5W-40', -}); - -export const FIXTURES = { - getAllBrands(): Brand[] { - return BRANDS.map((b) => ({ ...b })); - }, - - getBrandWithModels(brandId: number): Brand { - const found = BRANDS.find((b) => b.id === brandId) ?? BRANDS[10]; - const models = - found.id === 11 ? ALFA_MODELS.map((m) => ({ ...m })) : ([ - model(900 + found.id, 'Model A', 1990, 2000, plate('Model A', 18)), - model(950 + found.id, 'Model B', 2004, current, plate('Model B', 190)), - ] as Model[]); - return {...found, models}; - }, - - getModelWithGenerations(modelId: number): Model { - const found = ALFA_MODELS.find((m) => m.id === modelId) ?? ALFA_MODELS[13]; - const parent = BRANDS.find((b) => b.id === 11) ?? BRANDS[0]; - // The real endpoint loads relations for generations *and* brand, so the - // model arrives with its marque attached. The header path relies on it. - return { - ...found, - brand: {...parent, models: []}, - generations: G_145_GENERATIONS.map((g) => ({...g})), - }; - }, - - getGenerationWithTrims(generationId: number): Generation { - const found = G_145_GENERATIONS.find((g) => g.id === generationId) ?? G_145_GENERATIONS[0]; - return {...found, trims: G1_TRIMS.map((t) => ({ ...t }))}; - }, - - getTrimDetails(trimId: number): Trim { - const found = G1_TRIMS.find((t) => t.id === trimId) ?? G1_TRIMS[0]; - const details = - found.id === 2 - ? dieselDetails(2, '1.9 JTD (105 Hp)') - : {...TRIM_1_DETAILS, id: found.id, name: found.name, modification: found.name}; - // The real endpoint loads relations for generation too. Without it a direct - // load of a trim URL has no parent to name in the header path. - const generation = G_145_GENERATIONS.find((g) => g.id === 1) ?? G_145_GENERATIONS[0]; - const parent = ALFA_MODELS.find((m) => m.id === 100) ?? ALFA_MODELS[13]; - return { - ...found, - generation: {...generation, trims: [], model: {...parent, generations: []}}, - trimDetails: details, - }; - }, -}; \ No newline at end of file diff --git a/frontend/src/styles.css b/frontend/src/styles.css index bd55e4b..cc711c4 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -222,6 +222,18 @@ button { margin-bottom: 0.25rem; } +/* A state message sitting inside a two-column readout rather than spanning the + page on its own: it fills the column beside the photo instead of dropping + the reader below the fold. */ +.state--inline { + padding: 1.75rem 1.25rem; + text-align: left; +} + +.state--inline .source { + white-space: nowrap; +} + /* Loading keeps the layout stable so nothing jumps when data lands. */ .skeleton { border-radius: var(--radius-sm); @@ -418,24 +430,28 @@ button { /* The fixed columns are sized for the desktop table. At phone width they would leave the generation name a couple of characters wide, so they tighten and - the name column takes the difference. */ + the name column takes the difference. The name is the thing being read and + the other two columns are short fixed vocabulary ("Hatchback", "1999 – 2000"), + so they give up width first and shrink a step in type rather than squeezing + the name further. */ @media (max-width: 44rem) { .sheet--gens { width: 100%; } .sheet__col-narrow { - width: 5.5rem; + width: 4.5rem; } .sheet__col-years { - width: 6.75rem; + width: 5.75rem; } .sheet--gens th, .sheet--gens td { padding-left: 0.5rem; padding-right: 0.5rem; + font-size: 0.8125rem; } } diff --git a/library/src/models.ts b/library/src/models.ts index ac23b0a..3e758e5 100644 --- a/library/src/models.ts +++ b/library/src/models.ts @@ -4,7 +4,9 @@ export interface Brand { url: string; updatedAt: Date; imageUrl?: string; - models: Model[]; + // Optional because only /brand/:id loads them; /brands returns the marques + // alone. + models?: Model[]; } export interface Model { @@ -12,11 +14,16 @@ export interface Model { name: string; url: string; updatedAt: Date; - startYear: Date; - endYear: Date; + // Nullable because the source has no end date for a car still in production, + // and the scraper stores an unparseable value that the API serialises as + // null rather than a sentinel date. `format.yearOf` reads both shapes. + startYear: Date | null; + endYear: Date | null; imageUrl: string; - brand: Brand; - generations: Generation[]; + // Optional: an endpoint loads the brand only when the page above it needs + // one to name, which is /model/:id and the deep-link pages below it. + brand?: Brand; + generations?: Generation[]; } export interface Generation { @@ -25,11 +32,11 @@ export interface Generation { url: string; updatedAt: Date; chassisType: string; - startYear: Date; - endYear: Date; + startYear: Date | null; + endYear: Date | null; imageUrl: string; - model: Model; - trims: Trim[]; + model?: Model; + trims?: Trim[]; } export interface TrimDetails { @@ -121,9 +128,13 @@ export interface Trim { name: string; url: string; updatedAt: Date; - startYear: Date; - endYear: Date; + // Nullable for the same reason as Model: an open-ended production run. + startYear: Date | null; + endYear: Date | null; imageUrls: string[]; - generation: Generation; - trimDetails: TrimDetails; + generation?: Generation; + // Optional: /trim/:id loads the scraped record, but only once the scraper + // has run for this trim. Until then the endpoint returns it as null and the + // page shows the summary without a spec sheet. + trimDetails?: TrimDetails | null; } \ No newline at end of file From c30ad014aa91bf4ef9e2fe991f5ebfd4b247bd28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Raphael=20Vall=C3=A9e?= <72668371+Tranzitron@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:22:35 -0400 Subject: [PATCH 3/3] Name the wait instead of shading a block The old indicator was one grey rectangle per page, at a height picked by eye. It said nothing about what was being waited for, and the height had nothing to do with the content that replaced it, so data landing moved the page. Measured first, because the right indicator depends on how long a wait actually is. Against the dev database a stored car answers in 8-100ms and an unstored one in 4-34s, because the backend drives a headless browser to the source site on demand. So: - Under 150ms nothing is drawn. The old code flashed a skeleton for 8ms, which reads as a rendering fault rather than as progress. - Past 2s the wait is named, with a clock. - Past 3s it is named as what it is: a first look-up, fetching from the source site. The threshold sits above every cached read and below every observed scrape. The brand index opts out, since it only reads. Placeholders are now drawn from the same primitives as the content they stand in for, so nothing shifts: rows keep the 116x72 thumbnail column, the generation table keeps its three columns, the trim page keeps its figures strip, photo plate and spec tables, and the index keeps its letter groups and the rail's height. The trim page was the reason to measure. Its placeholder was two blocks of arbitrary height in place of five headline figures, a photo and seventy spec rows. For assistive technology: aria-busy on the region being updated, a status region that is always in the DOM so its text change is announced, and a clock that is aria-hidden because it would otherwise interrupt the message every second. Reduced motion removes the sweep, which leaves a placeholder looking like an empty panel, so it gains a border instead. Verified: 5 pages at 1280 and 390 in both the loaded and loading states, 20 combinations, no contrast failures and no overflow. The phases were driven at a held response time, and the scrape message was checked against a real 34s scrape. --- .../all-brands/all-brands.component.css | 29 ++++ .../all-brands/all-brands.component.html | 38 +++++- .../browse/all-brands/all-brands.component.ts | 34 ++++- .../src/app/browse/brand/brand.component.html | 22 ++- .../src/app/browse/brand/brand.component.ts | 10 +- .../generation/generation.component.html | 19 ++- .../browse/generation/generation.component.ts | 10 +- .../load-status/load-status.component.css | 20 +++ .../load-status/load-status.component.html | 12 ++ .../load-status/load-status.component.ts | 79 +++++++++++ .../src/app/browse/model/model.component.html | 33 ++++- .../src/app/browse/model/model.component.ts | 10 +- .../trim-details/trim-details.component.html | 47 ++++++- .../trim-details/trim-details.component.ts | 10 +- frontend/src/app/load-state.ts | 107 +++++++++++++++ frontend/src/styles.css | 128 ++++++++++++++++++ 16 files changed, 565 insertions(+), 43 deletions(-) create mode 100644 frontend/src/app/browse/load-status/load-status.component.css create mode 100644 frontend/src/app/browse/load-status/load-status.component.html create mode 100644 frontend/src/app/browse/load-status/load-status.component.ts create mode 100644 frontend/src/app/load-state.ts diff --git a/frontend/src/app/browse/all-brands/all-brands.component.css b/frontend/src/app/browse/all-brands/all-brands.component.css index 9a304e5..4bf0fc0 100644 --- a/frontend/src/app/browse/all-brands/all-brands.component.css +++ b/frontend/src/app/browse/all-brands/all-brands.component.css @@ -55,6 +55,35 @@ font-weight: 500; } +/* A placeholder letter. Sized to .rail__letter and inert, so the rail keeps its + height while the index loads instead of collapsing and shoving the body + sideways when the letters arrive. */ +.sk-rail { + cursor: default; + background-color: var(--panel); +} + +/* One placeholder per brand cell, carrying .entry's padding so the grid rows + are the height they will be once the names arrive. The lattice is drawn by + the borders around .entries, so this adds no border of its own. The sweep + lives on the ::before because the element itself is a padded box, and + animating its background would sweep across the padding too. */ +.sk-index-cell { + display: flex; + align-items: center; + padding: 0.5rem 0.75rem; +} + +.sk-index-cell::before { + content: ''; + flex: 1; + height: 0.8125rem; + border-radius: 3px; + background: linear-gradient(90deg, var(--panel) 25%, var(--raised) 37%, var(--panel) 63%); + background-size: 400% 100%; + animation: sweep 1.3s ease-in-out infinite; +} + /* ---------------------------------------------------------- the sections -- */ .index__body { diff --git a/frontend/src/app/browse/all-brands/all-brands.component.html b/frontend/src/app/browse/all-brands/all-brands.component.html index b17ba31..9d7ad93 100644 --- a/frontend/src/app/browse/all-brands/all-brands.component.html +++ b/frontend/src/app/browse/all-brands/all-brands.component.html @@ -11,11 +11,20 @@ [href]="'#' + group.letter" >{{ group.letter }} + } @empty { + + @for (placeholder of railPlaceholders; track placeholder) { + + } } -
+

All brands

@@ -23,15 +32,32 @@

All brands

Every marque in the database. Pick one to list its models.

- @if (!loading()) { + @if (!load.busy()) {

{{ total() }} marques

}
- @if (loading()) { -
- @for (placeholder of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; track placeholder) { -
+ + + + @if (load.visible()) { + + } @else if (total() === 0) { diff --git a/frontend/src/app/browse/all-brands/all-brands.component.ts b/frontend/src/app/browse/all-brands/all-brands.component.ts index e51f4a7..36f1cb4 100644 --- a/frontend/src/app/browse/all-brands/all-brands.component.ts +++ b/frontend/src/app/browse/all-brands/all-brands.component.ts @@ -13,6 +13,8 @@ import {ApiService} from '../../api.service'; import {AllBrandsItemComponent} from './all-brands-item/all-brands-item.component'; import {Brand} from '../../../../../library/src/models'; import {NavState} from '../../nav-state'; +import {LoadState} from '../../load-state'; +import {LoadStatusComponent} from '../load-status/load-status.component'; interface GroupedBrands { letter: string; @@ -21,7 +23,7 @@ interface GroupedBrands { @Component({ selector: 'app-brands', - imports: [AllBrandsItemComponent, RouterModule], + imports: [AllBrandsItemComponent, RouterModule, LoadStatusComponent], templateUrl: './all-brands.component.html', styleUrl: './all-brands.component.css', changeDetection: ChangeDetectionStrategy.OnPush, @@ -29,8 +31,8 @@ interface GroupedBrands { export class AllBrandsComponent implements OnInit, OnDestroy { private readonly api = inject(ApiService); private readonly nav = inject(NavState); + readonly load = inject(LoadState); - readonly loading = signal(true); readonly groupedBrands = signal([]); readonly activeLetter = signal(null); @@ -40,17 +42,37 @@ export class AllBrandsComponent implements OnInit, OnDestroy { private observer: IntersectionObserver | null = null; + /** One per letter the real rail holds, so its height is reserved up front. */ + readonly railPlaceholders = Array.from({length: 27}, (_, i) => i); + +/** + * Placeholder letter groups, sized to the real distribution: the index runs + * from one marque under "2" to thirty-odd under "A", so a uniform block of + * rows would be a different height from what replaces it. These are the real + * per-letter counts for the sections at the top of the page, which is where + * its height is decided. + * + * Each group carries its own cells rather than a row count the template counts + * up to: a repeater over a bare number array rendered nothing here, and the + * cells are what the template actually iterates. + */ +readonly placeholderGroups = [1, 12, 8, 9, 7].map((count, group) => ({ + id: group, + count, + cells: Array.from({length: count}, (_, i) => ({id: `${group}-${i}`})), +})); + ngOnInit(): void { this.nav.set([]); - void this.load(); + void this.fetchBrands(); } ngOnDestroy(): void { this.observer?.disconnect(); } - private async load(): Promise { - this.loading.set(true); + private async fetchBrands(): Promise { + const token = this.load.begin(); try { this.groupedBrands.set(this.group(await this.api.getAllBrands())); // Observed after the sections exist, and after a frame so the browser has @@ -58,7 +80,7 @@ export class AllBrandsComponent implements OnInit, OnDestroy { // height and pick the wrong active letter. queueMicrotask(() => this.watchSections()); } finally { - this.loading.set(false); + this.load.end(token); } } diff --git a/frontend/src/app/browse/brand/brand.component.html b/frontend/src/app/browse/brand/brand.component.html index a1dd59b..64a7140 100644 --- a/frontend/src/app/browse/brand/brand.component.html +++ b/frontend/src/app/browse/brand/brand.component.html @@ -1,4 +1,4 @@ -
+
@if (brand(); as b) { @if (b.imageUrl) { @@ -18,14 +18,28 @@

{{ b.name }}

{{ failed() ? 'Not found' : 'Loading' }}

+ +
} - @if (loading()) { -
+ @if (load.visible()) { + + } @else if (failed()) { diff --git a/frontend/src/app/browse/brand/brand.component.ts b/frontend/src/app/browse/brand/brand.component.ts index f79016a..54fbe3d 100644 --- a/frontend/src/app/browse/brand/brand.component.ts +++ b/frontend/src/app/browse/brand/brand.component.ts @@ -4,10 +4,12 @@ import {ApiService} from '../../api.service'; import {Brand, Model} from '../../../../../library/src/models'; import {BrandItemComponent} from './brand-item/brand-item.component'; import {NavState} from '../../nav-state'; +import {LoadState} from '../../load-state'; +import {LoadStatusComponent} from '../load-status/load-status.component'; @Component({ selector: 'app-brand', - imports: [BrandItemComponent], + imports: [BrandItemComponent, LoadStatusComponent], templateUrl: './brand.component.html', styleUrl: './brand.component.css', changeDetection: ChangeDetectionStrategy.OnPush, @@ -17,16 +19,16 @@ export class BrandComponent implements OnInit { private readonly router = inject(Router); private readonly api = inject(ApiService); private readonly nav = inject(NavState); + readonly load = inject(LoadState); readonly brand = signal(null); readonly models = signal([]); - readonly loading = signal(true); readonly failed = signal(false); async ngOnInit() { - this.loading.set(true); this.failed.set(false); this.nav.set([]); + const token = this.load.begin(); try { const segment: string = this.route.snapshot.params['brandId']; const brandId = parseInt(segment.split('-')[1], 10); @@ -47,7 +49,7 @@ export class BrandComponent implements OnInit { } catch { this.failed.set(true); } finally { - this.loading.set(false); + this.load.end(token); } } } \ No newline at end of file diff --git a/frontend/src/app/browse/generation/generation.component.html b/frontend/src/app/browse/generation/generation.component.html index 9d756d9..ca49c76 100644 --- a/frontend/src/app/browse/generation/generation.component.html +++ b/frontend/src/app/browse/generation/generation.component.html @@ -1,4 +1,4 @@ -
+
@if (generation(); as g) {
@@ -14,14 +14,25 @@

{{ g.name }}

{{ failed() ? 'Not found' : 'Loading' }}

+ +
}
- @if (loading()) { -
+ @if (load.visible()) { + + } @else if (failed()) { diff --git a/frontend/src/app/browse/generation/generation.component.ts b/frontend/src/app/browse/generation/generation.component.ts index 91a5275..1689ab1 100644 --- a/frontend/src/app/browse/generation/generation.component.ts +++ b/frontend/src/app/browse/generation/generation.component.ts @@ -3,11 +3,13 @@ import {ActivatedRoute, RouterLink} from '@angular/router'; import {Brand, Generation, Trim} from "../../../../../library/src/models"; import {ApiService} from '../../api.service'; import {Crumb, NavState} from '../../nav-state'; +import {LoadState} from '../../load-state'; import {entitySlug, yearRange} from '../../format'; +import {LoadStatusComponent} from '../load-status/load-status.component'; @Component({ selector: 'app-generation', - imports: [RouterLink], + imports: [RouterLink, LoadStatusComponent], templateUrl: './generation.component.html', styleUrl: './generation.component.css', changeDetection: ChangeDetectionStrategy.OnPush, @@ -16,17 +18,17 @@ export class GenerationComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly api = inject(ApiService); private readonly nav = inject(NavState); + readonly load = inject(LoadState); readonly generation = signal(null); readonly trims = signal([]); - readonly loading = signal(true); readonly failed = signal(false); readonly slugs = signal>(new Map()); async ngOnInit() { - this.loading.set(true); this.failed.set(false); this.nav.set([]); + const token = this.load.begin(); try { const segment: string = this.route.snapshot.params['generationId']; const generationId = parseInt(segment.split('-')[1], 10); @@ -43,7 +45,7 @@ export class GenerationComponent implements OnInit { } catch { this.failed.set(true); } finally { - this.loading.set(false); + this.load.end(token); } } diff --git a/frontend/src/app/browse/load-status/load-status.component.css b/frontend/src/app/browse/load-status/load-status.component.css new file mode 100644 index 0000000..40b09b7 --- /dev/null +++ b/frontend/src/app/browse/load-status/load-status.component.css @@ -0,0 +1,20 @@ +/* Sits under the page heading, in the meta line's own type, so a wait reads as + part of the page rather than as a modal or an alert. */ +.load-status { + display: flex; + align-items: baseline; + gap: 0.625rem; + min-height: 1.375rem; + margin-top: 0.5rem; + font-size: 0.8125rem; + color: var(--dim); +} + +.load-status__text { + min-width: 0; +} + +.load-status__clock { + flex-shrink: 0; + color: var(--faint); +} \ No newline at end of file diff --git a/frontend/src/app/browse/load-status/load-status.component.html b/frontend/src/app/browse/load-status/load-status.component.html new file mode 100644 index 0000000..3ac6a5a --- /dev/null +++ b/frontend/src/app/browse/load-status/load-status.component.html @@ -0,0 +1,12 @@ +

+ @if (load.visible()) { + @if (announce()) { + {{ message() }} + } @else { + {{ message() }} + } + @if (showClock()) { + + } + } +

\ No newline at end of file diff --git a/frontend/src/app/browse/load-status/load-status.component.ts b/frontend/src/app/browse/load-status/load-status.component.ts new file mode 100644 index 0000000..2df8db5 --- /dev/null +++ b/frontend/src/app/browse/load-status/load-status.component.ts @@ -0,0 +1,79 @@ +import {ChangeDetectionStrategy, Component, computed, inject, input} from '@angular/core'; +import {LoadState, secondsLabel} from '../../load-state'; + +/** + * The line that says what is happening, for the loads long enough to need it. + * + * It escalates rather than repeating itself. A cached read answers in 8-100ms + * and is covered by the skeletons alone; a cold read is the backend going out + * to the source site for a car it has never seen, which is a genuinely + * different wait and is worth naming so the page does not look hung. + * + * The region is always in the DOM and only its text changes, because a live + * region that appears at the same moment as its content is unreliable in + * several screen readers. + */ +@Component({ + selector: 'app-load-status', + templateUrl: './load-status.component.html', + styleUrl: './load-status.component.css', + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class LoadStatusComponent { + /** + * What is being waited for. Empty on the way in, because the name is part of + * the response that has not arrived, so the copy has to stand on its own + * rather than leave a dangling "Loading …". + * + * A noun phrase without an article ("the brand index"), so the messages can + * add their own and never produce "Loading the brand index" mid-sentence with + * a stray capital. + */ + readonly subject = input(''); + + /** + * Whether a long wait here means the backend is scraping. + * + * True for a drill-down page, which fetches on demand for a car it has not + * stored. False for the brand index, which only scrapes when the marques + * table is empty and otherwise just reads: claiming a scrape there would + * explain a wait that never happens, and would explain it wrongly. + */ + readonly scrapes = input(true); + + private readonly load = inject(LoadState); + + /** What the wait is being called, with its own capital for sentence starts. */ + private readonly thing = computed(() => { + const raw = this.subject().trim(); + return raw ? raw[0].toUpperCase() + raw.slice(1) : ''; + }); + + readonly message = computed(() => { + const subject = this.thing(); + + if (this.load.phase() === 'scrape') { + if (!this.scrapes()) { + return subject + ? `Still reading the database. ${subject} is taking longer than usual.` + : 'Still reading the database.'; + } + return subject + ? `Fetching ${subject} from the source site. First look-up, so it can take a minute.` + : 'Fetching this car from the source site. First look-up, so it can take a minute.'; + } + return subject ? `Loading ${subject}` : 'Loading'; + }); + + /** Only the escalating message is worth announcing; the brief one repeats. */ + readonly announce = computed(() => this.load.phase() !== 'brief'); + + /** + * The clock is only useful once there is something to count. Before the slow + * phase it ticks over from 1s on a request that may finish at 1.1s, which + * draws the eye to a number about to be contradicted. + */ + readonly showClock = computed(() => this.load.phase() !== 'brief'); + + readonly elapsed = computed(() => secondsLabel(this.load.elapsed())); +} \ No newline at end of file diff --git a/frontend/src/app/browse/model/model.component.html b/frontend/src/app/browse/model/model.component.html index 3db74a4..7c725f9 100644 --- a/frontend/src/app/browse/model/model.component.html +++ b/frontend/src/app/browse/model/model.component.html @@ -1,4 +1,4 @@ -
+
@if (model(); as m) {
@@ -13,12 +13,39 @@

{{ m.name }}

{{ failed() ? 'Not found' : 'Loading' }}

+ +
}
- @if (loading()) { -
+ @if (load.visible()) { + + + + + + + + + + + + + + + + @for (row of [1, 2, 3, 4, 5]; track row) { + + + + + + } + + } @else if (failed()) {

We could not load that model diff --git a/frontend/src/app/browse/model/model.component.ts b/frontend/src/app/browse/model/model.component.ts index 0762747..0e08326 100644 --- a/frontend/src/app/browse/model/model.component.ts +++ b/frontend/src/app/browse/model/model.component.ts @@ -3,11 +3,13 @@ import {ActivatedRoute, Router, RouterLink} from '@angular/router'; import {Generation, Model} from "../../../../../library/src/models"; import {ApiService} from '../../api.service'; import {Crumb, NavState} from '../../nav-state'; +import {LoadState} from '../../load-state'; import {entitySlug, yearRange} from '../../format'; +import {LoadStatusComponent} from '../load-status/load-status.component'; @Component({ selector: 'app-model', - imports: [RouterLink], + imports: [RouterLink, LoadStatusComponent], templateUrl: './model.component.html', styleUrl: './model.component.css', changeDetection: ChangeDetectionStrategy.OnPush, @@ -17,19 +19,19 @@ export class ModelComponent implements OnInit { private readonly router = inject(Router); private readonly api = inject(ApiService); private readonly nav = inject(NavState); + readonly load = inject(LoadState); readonly model = signal(null); readonly generations = signal([]); - readonly loading = signal(true); readonly failed = signal(false); /** Prebuilt so a row can link without re-deriving its own slug. */ readonly slugs = signal>(new Map()); async ngOnInit() { - this.loading.set(true); this.failed.set(false); this.nav.set([]); + const token = this.load.begin(); try { const segment: string = this.route.snapshot.params['modelId']; const modelId = parseInt(segment.split('-')[1], 10); @@ -53,7 +55,7 @@ export class ModelComponent implements OnInit { } catch { this.failed.set(true); } finally { - this.loading.set(false); + this.load.end(token); } } diff --git a/frontend/src/app/browse/trim-details/trim-details.component.html b/frontend/src/app/browse/trim-details/trim-details.component.html index 4506f31..ada391f 100644 --- a/frontend/src/app/browse/trim-details/trim-details.component.html +++ b/frontend/src/app/browse/trim-details/trim-details.component.html @@ -1,4 +1,4 @@ -

+
@if (trim(); as t) {
@@ -22,13 +22,52 @@

{{ t.name }}

{{ failed() ? 'Not found' : 'Loading' }}

+ +
}
- @if (loading()) { -
-
+ @if (load.visible()) { + +
+ @for (placeholder of [1, 2, 3, 4, 5]; track placeholder) { +
+
+
+
+ } +
+ +
+ +
+
+

+ @for (row of [1, 2, 3, 4, 5, 6, 7]; track row) { + + } +
+
+

+ @for (row of [1, 2, 3, 4, 5, 6, 7]; track row) { + + } +
+
+
} @else if (failed()) {

We could not load that trim diff --git a/frontend/src/app/browse/trim-details/trim-details.component.ts b/frontend/src/app/browse/trim-details/trim-details.component.ts index 1329b23..71ebf8d 100644 --- a/frontend/src/app/browse/trim-details/trim-details.component.ts +++ b/frontend/src/app/browse/trim-details/trim-details.component.ts @@ -3,11 +3,13 @@ import {ActivatedRoute} from '@angular/router'; import {Trim, TrimDetails} from "../../../../../library/src/models"; import {ApiService} from '../../api.service'; import {Crumb, NavState} from '../../nav-state'; +import {LoadState} from '../../load-state'; import {SpecGroup, entitySlug, groupDetails, headlineFigures, yearRange} from '../../format'; +import {LoadStatusComponent} from '../load-status/load-status.component'; @Component({ selector: 'app-trim', - imports: [], + imports: [LoadStatusComponent], templateUrl: './trim-details.component.html', styleUrl: './trim-details.component.css', changeDetection: ChangeDetectionStrategy.OnPush, @@ -16,9 +18,9 @@ export class TrimDetailsComponent implements OnInit { private readonly route = inject(ActivatedRoute); private readonly api = inject(ApiService); private readonly nav = inject(NavState); + readonly load = inject(LoadState); readonly trim = signal(null); - readonly loading = signal(true); readonly failed = signal(false); readonly figures = signal<{ label: string; value: string }[]>([]); @@ -28,9 +30,9 @@ export class TrimDetailsComponent implements OnInit { readonly photo = signal(0); async ngOnInit() { - this.loading.set(true); this.failed.set(false); this.nav.set([]); + const token = this.load.begin(); try { const segment: string = this.route.snapshot.params['trimId']; const trimId = parseInt(segment.split('-')[1], 10); @@ -49,7 +51,7 @@ export class TrimDetailsComponent implements OnInit { } catch { this.failed.set(true); } finally { - this.loading.set(false); + this.load.end(token); } } diff --git a/frontend/src/app/load-state.ts b/frontend/src/app/load-state.ts new file mode 100644 index 0000000..05d5265 --- /dev/null +++ b/frontend/src/app/load-state.ts @@ -0,0 +1,107 @@ +import {DestroyRef, Injectable, computed, inject, signal} from '@angular/core'; + +/** + * One page's load, shared by the skeleton placeholders and the status line so + * the two can never disagree about whether something is still in flight. + * + * Root-provided, like NavState, because only one drill-down page is mounted at + * a time. `end` takes the token `begin` handed out, so a late response from a + * page the router has already replaced cannot clear the state belonging to its + * successor. + */ + +/** + * Below this the response lands within the same frame or two. Showing a + * skeleton for 8ms and then replacing it is a grey flash, which reads as a + * rendering fault rather than as progress, so nothing is drawn yet. + */ +export const FLASH_MS = 150; + +/** Long enough that the skeleton alone stops explaining itself. */ +export const SLOW_MS = 2000; + +/** + * Past this the wait is a scrape. The backend fetches a car it has never seen + * from the source site on demand, driving a headless browser, and the scraper + * allows itself 60s. + * + * Measured against the dev database: a stored car answers in 8-100ms, an + * unstored one in 4-9s. The threshold sits above every observed cached read + * and below every observed scrape, so the message names the right cause rather + * than appearing on a slow disk or guessing at a hang. + */ +export const SCRAPE_MS = 3000; + +export type LoadPhase = 'brief' | 'slow' | 'scrape'; + +@Injectable({providedIn: 'root'}) +export class LoadState { + private readonly destroyRef = inject(DestroyRef); + + private readonly active = signal(false); + private readonly elapsedMs = signal(0); + + /** Identifies one begin/end pair, so a stale end cannot clear a newer load. */ + private token = 0; + private currentToken = 0; + private timer: ReturnType | null = null; + + /** True for the whole request, used for aria-busy. */ + readonly busy = computed(() => this.active()); + + /** Whether anything should be drawn yet. See FLASH_MS. */ + readonly visible = computed(() => this.active() && this.elapsedMs() >= FLASH_MS); + + readonly elapsed = computed(() => this.elapsedMs()); + + readonly phase = computed(() => { + const elapsed = this.elapsedMs(); + if (elapsed >= SCRAPE_MS) return 'scrape'; + if (elapsed >= SLOW_MS) return 'slow'; + return 'brief'; + }); + + constructor() { + this.destroyRef.onDestroy(() => this.stop()); + } + + begin(): number { + this.token += 1; + this.currentToken = this.token; + this.active.set(true); + this.elapsedMs.set(0); + this.start(); + return this.token; + } + + /** Ignores a token that is no longer the current load. */ + end(token: number): void { + if (token !== this.currentToken) return; + this.stop(); + this.active.set(false); + this.elapsedMs.set(0); + } + + private start(): void { + this.stop(); + const started = performance.now(); + this.timer = setInterval(() => { + this.elapsedMs.set(Math.round(performance.now() - started)); + }, 100); + } + + private stop(): void { + if (this.timer !== null) { + clearInterval(this.timer); + this.timer = null; + } + } +} + +/** + * Seconds, rounded up, because the useful question is "is this still going" + * rather than how precise the count is. + */ +export function secondsLabel(elapsedMs: number): string { + return `${Math.max(1, Math.ceil(elapsedMs / 1000))}s`; +} \ No newline at end of file diff --git a/frontend/src/styles.css b/frontend/src/styles.css index cc711c4..a9b26dc 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -137,6 +137,20 @@ button { letter-spacing: -0.02em; } +/* Present to assistive technology, absent from the visual layout. Used where a + status needs to be announced but adds nothing to what is on screen. */ +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + border: 0; +} + /* Missing source data. A spec sheet states the absence rather than going blank. */ .absent { color: var(--faint); @@ -251,6 +265,99 @@ button { } } +/* Skeletons are drawn from the same primitives as the real content, so the + placeholders share its geometry: a placeholder that is a plain block where + the page has a photo, a table or a row of type shifts the layout the moment + data lands, which is the opposite of what a placeholder is for. + + The sweep is shared by every primitive rather than living on .skeleton alone, + so a placeholder made of several pieces moves as one object instead of + leaving one part of itself still. */ +.skeleton, +.sk-line, +.sk-thumb, +.sk-plate { + background: linear-gradient(90deg, var(--panel) 25%, var(--raised) 37%, var(--panel) 63%); + background-size: 400% 100%; + animation: sweep 1.3s ease-in-out infinite; +} + +.sk-plate { + /* Blockified for the same reason as .sk-line: an inline box drops its + aspect-ratio. */ + display: block; + aspect-ratio: 16 / 10; + background-color: var(--sunken); +} + +.sk-line { + /* A span is inline, and an inline box ignores height, so a placeholder line + inside a

, or heading would collapse to nothing. Blockifying it + here means the same class works in any of those containers. */ + display: block; + height: 0.6875rem; + border-radius: 3px; +} + +.sk-line--sm { + height: 0.5625rem; +} + +.sk-line--title { + height: 1.25rem; + width: 9rem; +} + +.sk-line--wide { + width: 100%; +} + +.sk-line--mid { + width: 62%; +} + +.sk-line--short { + width: 38%; +} + +/* A stand-in for the leading image on a model row. Fixed to the same 116x72 the + real thumbnail uses, so the name beside it starts in the same place in both + states and the row does not change height when data lands. */ +.sk-thumb { + display: block; + width: 116px; + height: 72px; + border-radius: var(--radius-sm); + background-color: var(--sunken); +} + +/* A placeholder row borrows the real row's geometry but none of its + behaviour: it is not clickable, and a pointer cursor or a hover highlight on + something that goes nowhere is a promise the page cannot keep. */ +.sk-row { + cursor: default; +} + +.sk-row:hover { + background: none; +} + +/* A stand-in row for the spec sheet: label on the left, value right-aligned, + the same two columns the real table uses. */ +.sk-spec-row { + display: grid; + grid-template-columns: 1fr 9rem; + align-items: center; + gap: 1rem; + padding: 0.5rem 0; + border-bottom: 1px solid var(--line-soft); +} + +.sk-spec-row .sk-line:last-child { + justify-self: end; + width: 100%; +} + /* ------------------------------------------------------- production mark -- */ /* Amber = still built. Hollow = finished. One hue pair, no red/green. */ @@ -524,4 +631,25 @@ button { transition-duration: 0.01ms !important; scroll-behavior: auto !important; } + + /* The sweep is the only thing distinguishing a placeholder from an empty + panel, and reduced motion removes it. A static tone alone leaves the page + looking unfinished, so the placeholders keep a visible border instead. */ + .skeleton, + .sk-line, + .sk-thumb, + .sk-plate, + .sk-index-cell::before { + animation: none !important; + background: var(--panel); + outline: 1px solid var(--line-soft); + outline-offset: -1px; + } + + /* The placeholder cell is a padded box with a ::before doing the visible + work, so the outline belongs on that ::before rather than the box. */ + .sk-index-cell { + background: none; + outline: none; + } } \ No newline at end of file