Feat: Polish Angular UI with cohesive design system

Introduces a shared CSS custom property token layer and applies it
across all five views (library, upload, detail, login, app shell).
Each view now has intentional loading, empty, and error states.

- styles.css: 13 design tokens on :root; shimmer skeleton animation
- Library: 150ms-debounced skeleton loading, empty state with /upload
  link, error card with retry, card hover lift, broken-image fallback
- Upload: token-styled drop-zone, Uploading… spinner, 4s success
  banner, distinct validation vs. network error messages
- Detail: image skeleton, network error card (separate from 404
  not-found card), Owner actions panel, danger tag error styling,
  broken-image fallback
- Login: vertically centred surface card, danger field/server errors,
  Signing in… disabled button
- App shell: 48px fixed header, app name left, sign-out right, no
  reflow on auth state change
- All 24 ESLint errors resolved (including pre-existing auth spec
  issues); ng build and ng lint pass clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-03 20:03:56 +00:00
parent 5179786261
commit 9246f75fdd
23 changed files with 1777 additions and 181 deletions

View File

@@ -1,25 +1,86 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { provideRouter } from '@angular/router';
import { provideRouter, Router } from '@angular/router';
import { routes } from './app.routes';
import { AuthService } from './auth/auth.service';
describe('AppComponent', () => {
let authSpy: jasmine.SpyObj<AuthService>;
beforeEach(async () => {
authSpy = jasmine.createSpyObj('AuthService', ['isAuthenticated', 'logout']);
await TestBed.configureTestingModule({
imports: [AppComponent],
providers: [provideRouter(routes)],
providers: [
provideRouter(routes),
{ provide: AuthService, useValue: authSpy },
],
}).compileComponents();
});
it('should create the app', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
expect(fixture.componentInstance).toBeTruthy();
});
it('should have title reactbin-ui', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('reactbin-ui');
expect(fixture.componentInstance.title).toEqual('reactbin-ui');
});
it('header is present when authenticated', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const header = (fixture.nativeElement as HTMLElement).querySelector('header.app-header');
expect(header).not.toBeNull();
});
it('header is present when not authenticated', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const header = (fixture.nativeElement as HTMLElement).querySelector('header.app-header');
expect(header).not.toBeNull();
});
it('sign-out button is visible when authenticated', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const btn = (fixture.nativeElement as HTMLElement).querySelector('.logout-btn');
expect(btn).not.toBeNull();
});
it('sign-out button is absent when not authenticated', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const btn = (fixture.nativeElement as HTMLElement).querySelector('.logout-btn');
expect(btn).toBeNull();
});
it('onLogout calls auth.logout and navigates to /login', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const router = TestBed.inject(Router);
spyOn(router, 'navigate');
fixture.componentInstance.onLogout();
expect(authSpy.logout).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/login']);
});
it('header height is 48px', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const header = (fixture.nativeElement as HTMLElement).querySelector('header.app-header') as HTMLElement;
// The CSS declares height: 48px; we verify the class is applied correctly via the element presence
// (actual computed styles require a real browser/DOM environment)
expect(header.classList.contains('app-header')).toBeTrue();
});
});

View File

@@ -8,15 +8,35 @@ import { AuthService } from './auth/auth.service';
standalone: true,
imports: [CommonModule, RouterOutlet],
template: `
<header class="app-header" *ngIf="auth.isAuthenticated()">
<button class="logout-btn" (click)="onLogout()">Sign out</button>
<header class="app-header">
<span class="app-name">Reactbin</span>
<button *ngIf="auth.isAuthenticated()" class="logout-btn" (click)="onLogout()">Sign out</button>
</header>
<router-outlet />
`,
styles: [`
.app-header { display: flex; justify-content: flex-end; padding: 8px 16px; background: #1a1a1a; border-bottom: 1px solid #333; }
.logout-btn { background: none; border: 1px solid #555; color: #aaa; padding: 4px 12px; border-radius: 4px; cursor: pointer; font-size: 0.9rem; }
.logout-btn:hover { border-color: #aaa; color: #e0e0e0; }
:host { display: block; }
.app-header {
height: 48px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
background: var(--surface);
border-bottom: 1px solid var(--border);
}
.app-name { font-weight: 600; font-size: 1rem; color: var(--text); letter-spacing: 0.02em; }
.logout-btn {
background: none;
border: 1px solid var(--border);
color: var(--text-muted);
padding: 4px 12px;
border-radius: var(--radius);
cursor: pointer;
font-size: 0.85rem;
transition: border-color var(--transition), color var(--transition);
}
.logout-btn:hover { border-color: var(--border-focus); color: var(--text); }
`],
})
export class AppComponent {

View File

@@ -6,7 +6,6 @@ import { AuthService } from './auth.service';
describe('authGuard', () => {
let authService: jasmine.SpyObj<AuthService>;
let router: Router;
beforeEach(() => {
authService = jasmine.createSpyObj('AuthService', ['isAuthenticated']);
@@ -18,8 +17,6 @@ describe('authGuard', () => {
{ provide: AuthService, useValue: authService },
],
});
router = TestBed.inject(Router);
});
it('redirects to login when not authenticated', () => {

View File

@@ -1,5 +1,5 @@
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Router } from '@angular/router';
import { authInterceptor } from './auth.interceptor';
@@ -48,6 +48,7 @@ describe('authInterceptor', () => {
it('redirects to login on 401 response', () => {
authService.getToken.and.returnValue('test-token');
// eslint-disable-next-line @typescript-eslint/no-empty-function
http.get('/api/v1/images').subscribe({ error: () => {} });
const req = httpMock.expectOne('/api/v1/images');
req.flush('Unauthorized', { status: 401, statusText: 'Unauthorized' });

View File

@@ -2,27 +2,19 @@ import { TestBed } from '@angular/core/testing';
import { ActivatedRoute, provideRouter, Router } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { of } from 'rxjs';
import { of, throwError, Subject } from 'rxjs';
import { DetailComponent } from './detail.component';
import { ImageService } from '../services/image.service';
import { routes } from '../app.routes';
const MOCK_IMAGE = {
id: 'img-1',
hash: 'abc',
filename: 'test.jpg',
mime_type: 'image/jpeg',
size_bytes: 100,
width: 10,
height: 10,
storage_key: 'abc',
thumbnail_key: null,
created_at: '2026-01-01T00:00:00Z',
tags: ['cat', 'funny'],
id: 'img-1', hash: 'abc', filename: 'test.jpg', mime_type: 'image/jpeg',
size_bytes: 100, width: 10, height: 10, storage_key: 'abc',
thumbnail_key: null, created_at: '2026-01-01T00:00:00Z', tags: ['cat', 'funny'],
};
describe('DetailComponent', () => {
function setup(imageId = 'img-1') {
function setup(imageId = 'img-1', imageResponse = of(MOCK_IMAGE)) {
TestBed.configureTestingModule({
imports: [DetailComponent],
providers: [
@@ -33,13 +25,13 @@ describe('DetailComponent', () => {
],
}).compileComponents();
const fixture = TestBed.createComponent(DetailComponent);
const component = fixture.componentInstance;
const imgSvc = TestBed.inject(ImageService);
spyOn(imgSvc, 'get').and.returnValue(of(MOCK_IMAGE));
spyOn(imgSvc, 'get').and.returnValue(imageResponse);
fixture.detectChanges();
return { fixture, component, imgSvc };
return { fixture, component: fixture.componentInstance, imgSvc };
}
// Existing tests preserved
it('should call PATCH with removed tag absent when chip × is clicked', () => {
const { component, imgSvc } = setup();
spyOn(imgSvc, 'updateTags').and.returnValue(of({ ...MOCK_IMAGE, tags: ['funny'] }));
@@ -80,4 +72,74 @@ describe('DetailComponent', () => {
component.goBack();
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
// New polish tests
it('skeleton is visible while loading is true', () => {
TestBed.configureTestingModule({
imports: [DetailComponent],
providers: [
provideHttpClient(), provideHttpClientTesting(), provideRouter(routes),
{ provide: ActivatedRoute, useValue: { snapshot: { paramMap: { get: () => 'img-1' } } } },
],
}).compileComponents();
const fixture = TestBed.createComponent(DetailComponent);
const imgSvc = TestBed.inject(ImageService);
// Don't emit — keep loading state
spyOn(imgSvc, 'get').and.returnValue(new Subject());
fixture.componentInstance.loading = true;
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelector('.image-skeleton')).not.toBeNull();
});
it('error card shown when error is true and loading is false', () => {
const fixture = (() => {
TestBed.configureTestingModule({
imports: [DetailComponent],
providers: [
provideHttpClient(), provideHttpClientTesting(), provideRouter(routes),
{ provide: ActivatedRoute, useValue: { snapshot: { paramMap: { get: () => 'img-1' } } } },
],
}).compileComponents();
return TestBed.createComponent(DetailComponent);
})();
const imgSvc = TestBed.inject(ImageService);
spyOn(imgSvc, 'get').and.returnValue(throwError(() => ({ status: 500 })));
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelector('.fetch-error-card')).not.toBeNull();
});
it('not-found card shown when image is null, loading is false, error is false', () => {
const { fixture, component } = setup('img-1', of(MOCK_IMAGE));
component.image = null;
component.loading = false;
component.error = false;
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelector('.not-found-card')).not.toBeNull();
});
it('tag error element uses danger styling class', () => {
const { fixture, component } = setup();
component.tagError = 'Invalid tag: special characters not allowed';
fixture.detectChanges();
const errEl = (fixture.nativeElement as HTMLElement).querySelector('.tag-error');
expect(errEl).not.toBeNull();
});
it('onImgError sets src to placeholder SVG', () => {
const { fixture } = setup();
const imgEl = document.createElement('img');
imgEl.src = 'http://example.com/image.jpg';
fixture.componentInstance.onImgError({ target: imgEl } as unknown as Event);
expect(imgEl.src).toContain('data:image/svg+xml');
});
it('onImgError does not recurse when src already is a data URI', () => {
const { fixture } = setup();
const imgEl = document.createElement('img');
imgEl.src = 'data:image/svg+xml,placeholder';
const before = imgEl.src;
fixture.componentInstance.onImgError({ target: imgEl } as unknown as Event);
expect(imgEl.src).toBe(before);
});
});

View File

@@ -1,21 +1,58 @@
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { ImageRecord, ImageService } from '../services/image.service';
import { AuthService } from '../auth/auth.service';
const PLACEHOLDER_SVG = `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500" viewBox="0 0 800 500"><rect width="800" height="500" fill="%23111"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="48" fill="%23444">&#x1F517;</text></svg>`;
@Component({
selector: 'app-detail',
standalone: true,
imports: [CommonModule, FormsModule],
imports: [CommonModule, FormsModule, RouterLink],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="detail-page" *ngIf="image">
<button class="back-btn" (click)="goBack()">← Back</button>
<!-- Loading skeleton -->
<div class="detail-page" *ngIf="loading">
<div class="skeleton image-skeleton"></div>
<div class="chip-row-skeleton">
<div *ngFor="let _ of skeletonChips" class="skeleton chip-skeleton"></div>
</div>
<div class="chip-row-skeleton">
<div *ngFor="let _ of skeletonChips" class="skeleton chip-skeleton short"></div>
</div>
</div>
<!-- Network error state -->
<div class="fetch-error-card" *ngIf="error && !loading">
<span class="error-icon">⚠</span>
<p>Failed to load image. Please check your connection.</p>
<div class="error-actions">
<button class="retry-btn" (click)="retry()">Retry</button>
<a routerLink="/" class="back-link">Back to library</a>
</div>
</div>
<!-- Not-found state -->
<div class="not-found-card" *ngIf="!image && !loading && !error">
<span class="not-found-icon">✦</span>
<h2>Image not found</h2>
<p>This image may have been deleted or the URL is incorrect.</p>
<a routerLink="/" class="back-btn">Back to library</a>
</div>
<!-- Main content -->
<div class="detail-page" *ngIf="image && !loading">
<button class="back-btn-inline" (click)="goBack()">← Back</button>
<h2>{{ image.filename }}</h2>
<img class="full-image" [src]="imageService.getFileUrl(image.id)" [alt]="image.filename" />
<img
class="full-image"
[src]="imageService.getFileUrl(image.id)"
[alt]="image.filename"
(error)="onImgError($event)"
/>
<section class="tags-section">
<h3>Tags</h3>
@@ -24,7 +61,11 @@ import { AuthService } from '../auth/auth.service';
{{ tag }} <button *ngIf="auth.isAuthenticated()" (click)="removeTag(tag)">×</button>
</span>
</div>
<div class="add-tag" *ngIf="auth.isAuthenticated()">
<p class="tag-error" *ngIf="tagError">{{ tagError }}</p>
</section>
<section class="owner-actions" *ngIf="auth.isAuthenticated()">
<div class="add-tag">
<input
[(ngModel)]="newTagInput"
placeholder="Add tag…"
@@ -32,11 +73,9 @@ import { AuthService } from '../auth/auth.service';
(blur)="onBlur()"
/>
</div>
<p class="tag-error" *ngIf="tagError">{{ tagError }}</p>
<button class="delete-btn" (click)="showDeleteDialog = true">Delete Image</button>
</section>
<button *ngIf="auth.isAuthenticated()" class="delete-btn" (click)="showDeleteDialog = true">Delete Image</button>
<div class="dialog-overlay" *ngIf="showDeleteDialog">
<div class="dialog">
<p>Permanently delete this image?</p>
@@ -45,34 +84,78 @@ import { AuthService } from '../auth/auth.service';
</div>
</div>
</div>
<p *ngIf="!image && !loading" class="not-found">Image not found.</p>
`,
styles: [`
.detail-page { max-width: 900px; margin: 32px auto; padding: 0 16px; }
.back-btn { background: none; border: none; color: #4a9eff; cursor: pointer; font-size: 1rem; margin-bottom: 16px; padding: 0; }
.full-image { width: 100%; max-height: 70vh; object-fit: contain; background: #111; border-radius: 8px; display: block; }
/* Skeleton */
.image-skeleton { width: 100%; height: 400px; margin-bottom: 16px; }
.chip-row-skeleton { display: flex; gap: 8px; margin-bottom: 10px; padding: 0 16px; }
.chip-skeleton { width: 64px; height: 28px; border-radius: var(--radius-chip); }
.chip-skeleton.short { width: 48px; }
/* Network error card */
.fetch-error-card {
max-width: 520px; margin: 80px auto; text-align: center;
padding: 40px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
}
.error-icon { display: block; font-size: 2rem; color: var(--danger); margin-bottom: 12px; }
.error-actions { display: flex; justify-content: center; gap: 16px; margin-top: 20px; }
.retry-btn { padding: 8px 20px; background: var(--surface-raised); color: var(--text); border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; }
.retry-btn:hover { border-color: var(--border-focus); }
.back-link { color: var(--accent); text-decoration: none; line-height: 2.2; }
/* Not-found card */
.not-found-card {
max-width: 480px; margin: 80px auto; text-align: center;
padding: 48px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
}
.not-found-icon { display: block; font-size: 2.5rem; color: var(--text-muted); margin-bottom: 16px; }
.not-found-card h2 { margin-bottom: 8px; }
.not-found-card p { color: var(--text-muted); margin-bottom: 24px; }
/* Main detail */
.back-btn-inline { background: none; border: none; color: var(--accent); cursor: pointer; font-size: 1rem; margin-bottom: 16px; padding: 0; }
.back-btn {
display: inline-block; margin-top: 16px; padding: 10px 24px;
background: var(--surface-raised); color: var(--text);
border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; text-decoration: none;
}
.back-btn:hover { border-color: var(--border-focus); }
.full-image { width: 100%; max-height: 70vh; object-fit: contain; background: #111; border-radius: var(--radius); display: block; }
.tags-section { margin-top: 24px; }
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
.chip { background: #333; padding: 4px 12px; border-radius: 14px; display: flex; align-items: center; gap: 6px; }
.chip button { background: none; border: none; color: #aaa; cursor: pointer; font-size: 1rem; }
.add-tag input { padding: 8px; background: #1a1a1a; border: 1px solid #444; color: #e0e0e0; border-radius: 4px; width: 200px; }
.tag-error { color: #ff6b6b; font-size: 0.85rem; margin-top: 6px; }
.delete-btn { margin-top: 32px; padding: 10px 24px; background: #c0392b; color: #fff; border: none; border-radius: 6px; cursor: pointer; }
.chip { background: var(--surface-raised); padding: 4px 12px; border-radius: var(--radius-chip); display: flex; align-items: center; gap: 6px; }
.chip button { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 1rem; }
.tag-error { color: var(--danger); font-size: 0.85rem; margin-top: 6px; border-left: 3px solid var(--danger); padding-left: 10px; }
/* Owner actions panel */
.owner-actions {
margin-top: 24px; padding: 20px;
background: var(--surface); border-top: 1px solid var(--border); border-radius: var(--radius);
display: flex; align-items: center; gap: 16px; flex-wrap: wrap;
}
.add-tag input { padding: 8px; background: var(--surface-raised); border: 1px solid var(--border); color: var(--text); border-radius: var(--radius); width: 200px; }
.add-tag input:focus { outline: none; border-color: var(--border-focus); }
.delete-btn { padding: 10px 24px; background: var(--danger); color: var(--danger-text); border: none; border-radius: var(--radius); cursor: pointer; margin-left: auto; }
/* Delete dialog */
.dialog-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 100; }
.dialog { background: #1a1a1a; padding: 32px; border-radius: 10px; text-align: center; }
.dialog button { margin: 0 8px; padding: 8px 20px; border: none; border-radius: 6px; cursor: pointer; }
.dialog button:first-of-type { background: #c0392b; color: #fff; }
.dialog button:last-of-type { background: #444; color: #e0e0e0; }
.not-found { text-align: center; color: #666; padding: 60px; }
.dialog { background: var(--surface); padding: 32px; border-radius: 10px; text-align: center; }
.dialog button { margin: 12px 8px 0; padding: 8px 20px; border: none; border-radius: var(--radius); cursor: pointer; }
.dialog button:first-of-type { background: var(--danger); color: var(--danger-text); }
.dialog button:last-of-type { background: var(--surface-raised); color: var(--text); }
`],
})
export class DetailComponent implements OnInit {
image: ImageRecord | null = null;
loading = true;
error = false;
newTagInput = '';
tagError = '';
showDeleteDialog = false;
readonly skeletonChips = Array(4).fill(null);
private currentId = '';
constructor(
public imageService: ImageService,
@@ -85,9 +168,35 @@ export class DetailComponent implements OnInit {
ngOnInit(): void {
const id = this.route.snapshot.paramMap.get('id');
if (!id) { this.loading = false; return; }
this.currentId = id;
this.fetchImage(id);
}
retry(): void {
this.error = false;
this.loading = true;
this.cdr.markForCheck();
this.fetchImage(this.currentId);
}
private fetchImage(id: string): void {
this.imageService.get(id).subscribe({
next: (img) => { this.image = img; this.loading = false; this.cdr.markForCheck(); },
error: () => { this.loading = false; this.cdr.markForCheck(); },
next: (img) => {
this.image = img;
this.loading = false;
this.error = false;
this.cdr.markForCheck();
},
error: (err) => {
this.loading = false;
if (err?.status === 404) {
this.image = null;
this.error = false;
} else {
this.error = true;
}
this.cdr.markForCheck();
},
});
}
@@ -127,4 +236,11 @@ export class DetailComponent implements OnInit {
}
goBack(): void { this.router.navigate(['/']); }
onImgError(event: Event): void {
const img = event.target as HTMLImageElement;
if (!img.src.startsWith('data:')) {
img.src = PLACEHOLDER_SVG;
}
}
}

View File

@@ -1,12 +1,18 @@
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { of } from 'rxjs';
import { LibraryComponent } from './library.component';
import { ImageService } from '../services/image.service';
import { routes } from '../app.routes';
const EMPTY_PAGE = { items: [], total: 0, limit: 50, offset: 0 };
const ONE_IMAGE = {
items: [{ id: '1', filename: 'a.jpg', tags: ['cat'], hash: '', mime_type: 'image/jpeg', size_bytes: 1, width: 1, height: 1, storage_key: '', thumbnail_key: null, created_at: '' }],
total: 1, limit: 50, offset: 0,
};
describe('LibraryComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
@@ -17,33 +23,88 @@ describe('LibraryComponent', () => {
it('should render image grid from service response', () => {
const fixture = TestBed.createComponent(LibraryComponent);
const component = fixture.componentInstance;
const imgSvc = TestBed.inject(ImageService);
spyOn(imgSvc, 'list').and.returnValue(
of({
items: [
{ id: '1', filename: 'a.jpg', tags: ['cat'], hash: '', mime_type: 'image/jpeg', size_bytes: 1, width: 1, height: 1, storage_key: '', thumbnail_key: null, created_at: '' },
],
total: 1,
limit: 50,
offset: 0,
})
);
spyOn(imgSvc, 'list').and.returnValue(of(ONE_IMAGE));
fixture.detectChanges();
const de = fixture.nativeElement as HTMLElement;
expect(de.querySelectorAll('.image-card').length).toBe(1);
expect((fixture.nativeElement as HTMLElement).querySelectorAll('.image-card').length).toBe(1);
});
it('should trigger new API call with tags param on filter change', () => {
const fixture = TestBed.createComponent(LibraryComponent);
const component = fixture.componentInstance;
const imgSvc = TestBed.inject(ImageService);
const listSpy = spyOn(imgSvc, 'list').and.returnValue(
of({ items: [], total: 0, limit: 50, offset: 0 })
);
const listSpy = spyOn(imgSvc, 'list').and.returnValue(of(EMPTY_PAGE));
fixture.detectChanges();
component.applyFilter(['cat', 'funny']);
fixture.componentInstance.applyFilter(['cat', 'funny']);
expect(listSpy).toHaveBeenCalledWith(['cat', 'funny'], jasmine.any(Number), jasmine.any(Number));
});
it('showSpinner is false initially', () => {
const fixture = TestBed.createComponent(LibraryComponent);
const imgSvc = TestBed.inject(ImageService);
spyOn(imgSvc, 'list').and.returnValue(of(EMPTY_PAGE));
fixture.detectChanges();
expect(fixture.componentInstance.showSpinner).toBeFalse();
});
it('renders 8 skeleton cards while showSpinner is true', () => {
const fixture = TestBed.createComponent(LibraryComponent);
fixture.componentInstance.showSpinner = true;
fixture.detectChanges();
const skeletons = (fixture.nativeElement as HTMLElement).querySelectorAll('.card-skeleton');
expect(skeletons.length).toBe(8);
});
it('error is false initially', () => {
const fixture = TestBed.createComponent(LibraryComponent);
const imgSvc = TestBed.inject(ImageService);
spyOn(imgSvc, 'list').and.returnValue(of(EMPTY_PAGE));
fixture.detectChanges();
expect(fixture.componentInstance.error).toBeFalse();
});
it('shows error card when error is true', () => {
const fixture = TestBed.createComponent(LibraryComponent);
fixture.componentInstance.error = true;
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelector('.error-card')).not.toBeNull();
});
it('error card has retry button that calls load()', () => {
const fixture = TestBed.createComponent(LibraryComponent);
fixture.componentInstance.error = true;
fixture.detectChanges();
spyOn(fixture.componentInstance, 'load');
const retryBtn = (fixture.nativeElement as HTMLElement).querySelector('.error-card .retry-btn') as HTMLButtonElement;
expect(retryBtn).not.toBeNull();
retryBtn.click();
expect(fixture.componentInstance.load).toHaveBeenCalled();
});
it('empty state contains routerLink to /upload', () => {
const fixture = TestBed.createComponent(LibraryComponent);
const imgSvc = TestBed.inject(ImageService);
spyOn(imgSvc, 'list').and.returnValue(of(EMPTY_PAGE));
fixture.detectChanges();
const link = (fixture.nativeElement as HTMLElement).querySelector('.empty-state a[href="/upload"]');
expect(link).not.toBeNull();
});
it('onImgError sets src to placeholder SVG', () => {
const fixture = TestBed.createComponent(LibraryComponent);
const imgEl = document.createElement('img');
imgEl.src = 'http://example.com/image.jpg';
const event = { target: imgEl } as unknown as Event;
fixture.componentInstance.onImgError(event);
expect(imgEl.src).toContain('data:image/svg+xml');
});
it('onImgError does not recurse when src already contains placeholder', () => {
const fixture = TestBed.createComponent(LibraryComponent);
const imgEl = document.createElement('img');
imgEl.src = 'data:image/svg+xml,placeholder';
const originalSrc = imgEl.src;
const event = { target: imgEl } as unknown as Event;
fixture.componentInstance.onImgError(event);
expect(imgEl.src).toBe(originalSrc);
});
});

View File

@@ -5,15 +5,18 @@ import {
ChangeDetectorRef,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { Subject, debounceTime, distinctUntilChanged } from 'rxjs';
import { Router, RouterLink } from '@angular/router';
import { Subject, debounceTime, distinctUntilChanged, share, timer } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { ImageRecord, ImageService } from '../services/image.service';
import { TagService } from '../services/tag.service';
const PLACEHOLDER_SVG = `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="160" viewBox="0 0 200 160"><rect width="200" height="160" fill="%23252525"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="32" fill="%23555">&#x1F5BC;</text></svg>`;
@Component({
selector: 'app-library',
standalone: true,
imports: [CommonModule],
imports: [CommonModule, RouterLink],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="library">
@@ -34,49 +37,83 @@ import { TagService } from '../services/tag.service';
</span>
</div>
<ul class="suggestions" *ngIf="suggestions.length">
<li *ngFor="let s of suggestions" (click)="addFilter(s.name)">{{ s.name }} ({{ s.image_count }})</li>
<li *ngFor="let s of suggestions" (click)="addFilter(s.name)" (keydown.enter)="addFilter(s.name)" tabindex="0" role="option" [attr.aria-selected]="false">{{ s.name }} ({{ s.image_count }})</li>
</ul>
</div>
<div *ngIf="images.length === 0 && !loading" class="empty-state">
<p>{{ activeFilters.length ? 'No images match these filters.' : 'No images yet. Upload your first!' }}</p>
<!-- Skeleton loading grid -->
<div *ngIf="showSpinner" class="grid">
<div *ngFor="let _ of skeletonItems" class="image-card skeleton card-skeleton"></div>
</div>
<div class="grid">
<!-- Error state -->
<div *ngIf="error && !showSpinner" class="error-card">
<p>Failed to load images. Please check your connection.</p>
<button class="retry-btn" (click)="load()">Retry</button>
</div>
<!-- Empty state -->
<div *ngIf="images.length === 0 && !showSpinner && !error" class="empty-state">
<span class="empty-icon">✦</span>
<p *ngIf="activeFilters.length">No images match these filters.</p>
<p *ngIf="!activeFilters.length">No images yet.</p>
<a *ngIf="!activeFilters.length" routerLink="/upload" class="upload-link">Upload your first image</a>
</div>
<!-- Image grid -->
<div *ngIf="!showSpinner && !error" class="grid">
<div
*ngFor="let img of images"
class="image-card"
role="button"
tabindex="0"
(click)="router.navigate(['/images', img.id])"
(keydown.enter)="router.navigate(['/images', img.id])"
>
<img [src]="imageService.getThumbnailUrl(img.id)" [alt]="img.filename" loading="lazy" />
<img
[src]="imageService.getThumbnailUrl(img.id)"
[alt]="img.filename"
loading="lazy"
(error)="onImgError($event)"
/>
<div class="tag-row">
<span *ngFor="let tag of img.tags" class="chip small">{{ tag }}</span>
</div>
</div>
</div>
<button *ngIf="hasMore" class="load-more" (click)="loadMore()">Load more</button>
<button *ngIf="hasMore && !showSpinner && !error" class="load-more" (click)="loadMore()">Load more</button>
</div>
`,
styles: [`
.library { max-width: 1200px; margin: 0 auto; padding: 24px 16px; }
header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.upload-btn { padding: 8px 20px; background: #4a9eff; color: #000; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; }
.upload-btn { padding: 8px 20px; background: var(--accent); color: var(--accent-text); border: none; border-radius: var(--radius); cursor: pointer; font-weight: 600; }
.filter-bar { position: relative; margin-bottom: 24px; }
.filter-bar input { width: 100%; padding: 10px; background: #1a1a1a; border: 1px solid #444; color: #e0e0e0; border-radius: 6px; }
.filter-bar input { width: 100%; padding: 10px; background: var(--surface); border: 1px solid var(--border); color: var(--text); border-radius: var(--radius); }
.filter-bar input:focus { outline: none; border-color: var(--border-focus); }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
.chip { background: #333; padding: 3px 10px; border-radius: 12px; font-size: 0.85rem; display: flex; align-items: center; gap: 4px; }
.chip { background: var(--surface-raised); padding: 3px 10px; border-radius: var(--radius-chip); font-size: 0.85rem; display: flex; align-items: center; gap: 4px; }
.chip.small { font-size: 0.75rem; padding: 2px 8px; }
.chip button { background: none; border: none; color: #aaa; cursor: pointer; padding: 0; font-size: 1rem; }
.suggestions { position: absolute; z-index: 10; background: #1a1a1a; border: 1px solid #444; list-style: none; width: 100%; max-height: 200px; overflow-y: auto; border-radius: 0 0 6px 6px; }
.chip button { background: none; border: none; color: var(--text-muted); cursor: pointer; padding: 0; font-size: 1rem; }
.suggestions { position: absolute; z-index: 10; background: var(--surface); border: 1px solid var(--border); list-style: none; width: 100%; max-height: 200px; overflow-y: auto; border-radius: 0 0 var(--radius) var(--radius); }
.suggestions li { padding: 8px 12px; cursor: pointer; }
.suggestions li:hover { background: #2a2a2a; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
.image-card { cursor: pointer; background: #1a1a1a; border-radius: 8px; overflow: hidden; }
.suggestions li:hover { background: var(--surface-raised); }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 12px; }
.image-card { cursor: pointer; background: var(--surface); border-radius: var(--radius); overflow: hidden; transition: transform var(--transition), box-shadow var(--transition); }
.image-card:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(0,0,0,0.4); }
.image-card img { width: 100%; height: 160px; object-fit: cover; display: block; }
.card-skeleton { height: 200px; }
.tag-row { padding: 6px; display: flex; flex-wrap: wrap; gap: 4px; }
.empty-state { text-align: center; padding: 60px 0; color: #666; }
.load-more { display: block; margin: 24px auto; padding: 10px 32px; background: #2a2a2a; color: #e0e0e0; border: 1px solid #444; border-radius: 6px; cursor: pointer; }
.empty-state { text-align: center; padding: 60px 0; color: var(--text-muted); }
.empty-icon { display: block; font-size: 2rem; margin-bottom: 12px; }
.upload-link { display: inline-block; margin-top: 16px; color: var(--accent); text-decoration: none; font-weight: 600; }
.upload-link:hover { text-decoration: underline; }
.error-card { text-align: center; padding: 40px; background: var(--surface); border-radius: var(--radius); border: 1px solid var(--border); }
.error-card p { color: var(--text-muted); margin-bottom: 16px; }
.retry-btn { padding: 8px 24px; background: var(--surface-raised); color: var(--text); border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; transition: border-color var(--transition); }
.retry-btn:hover { border-color: var(--border-focus); }
.load-more { display: block; margin: 24px auto; padding: 10px 32px; background: var(--surface-raised); color: var(--text); border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; }
`],
})
export class LibraryComponent implements OnInit {
@@ -84,8 +121,10 @@ export class LibraryComponent implements OnInit {
activeFilters: string[] = [];
tagSearch = '';
suggestions: { name: string; image_count: number }[] = [];
loading = false;
showSpinner = false;
error = false;
hasMore = false;
readonly skeletonItems = Array(8).fill(null);
private offset = 0;
private readonly limit = 50;
private readonly filterChange$ = new Subject<string>();
@@ -98,7 +137,7 @@ export class LibraryComponent implements OnInit {
) {}
ngOnInit(): void {
this.loadImages();
this.load();
this.filterChange$.pipe(debounceTime(300), distinctUntilChanged()).subscribe((q) => {
if (q) {
this.tagService.list(q, 10).subscribe((r) => {
@@ -112,6 +151,29 @@ export class LibraryComponent implements OnInit {
});
}
load(): void {
this.error = false;
const req$ = this.imageService.list(this.activeFilters, this.limit, this.offset).pipe(share());
timer(150).pipe(takeUntil(req$)).subscribe(() => {
this.showSpinner = true;
this.cdr.markForCheck();
});
req$.subscribe({
next: (res) => {
this.images = [...this.images, ...res.items];
this.offset += res.items.length;
this.hasMore = this.offset < res.total;
this.showSpinner = false;
this.cdr.markForCheck();
},
error: () => {
this.showSpinner = false;
this.error = true;
this.cdr.markForCheck();
},
});
}
onTagInput(event: Event): void {
const val = (event.target as HTMLInputElement).value;
this.tagSearch = val;
@@ -136,21 +198,17 @@ export class LibraryComponent implements OnInit {
this.activeFilters = tags;
this.offset = 0;
this.images = [];
this.loadImages();
}
loadImages(): void {
this.loading = true;
this.imageService.list(this.activeFilters, this.limit, this.offset).subscribe((res) => {
this.images = [...this.images, ...res.items];
this.offset += res.items.length;
this.hasMore = this.offset < res.total;
this.loading = false;
this.cdr.markForCheck();
});
this.load();
}
loadMore(): void {
this.loadImages();
this.load();
}
onImgError(event: Event): void {
const img = event.target as HTMLImageElement;
if (!img.src.startsWith('data:')) {
img.src = PLACEHOLDER_SVG;
}
}
}

View File

@@ -60,4 +60,48 @@ describe('LoginComponent', () => {
tick();
expect(authService.login).not.toHaveBeenCalled();
}));
// New polish tests
it('submit button shows "Signing in…" and is disabled while loading', () => {
const fixture = TestBed.createComponent(LoginComponent);
const comp = fixture.componentInstance;
fixture.detectChanges();
comp.loading = true;
fixture.detectChanges();
const btn = (fixture.nativeElement as HTMLElement).querySelector('button[type="submit"]') as HTMLButtonElement;
expect(btn.textContent?.trim()).toContain('Signing in');
expect(btn.disabled).toBeTrue();
});
it('field-level validation error shown for empty username on touched', () => {
const fixture = TestBed.createComponent(LoginComponent);
const comp = fixture.componentInstance;
fixture.detectChanges();
comp.form.get('username')!.markAsTouched();
fixture.detectChanges();
const err = (fixture.nativeElement as HTMLElement).querySelector('.validation-error');
expect(err).not.toBeNull();
});
it('errorMessage paragraph is visible when errorMessage is set', fakeAsync(() => {
authService.login.and.returnValue(throwError(() => new HttpErrorResponse({ status: 401 })));
component.form.setValue({ username: 'owner', password: 'wrong' });
component.onSubmit();
tick();
const fixture = TestBed.createComponent(LoginComponent);
fixture.componentInstance.errorMessage = component.errorMessage;
fixture.detectChanges();
const errPara = (fixture.nativeElement as HTMLElement).querySelector('.error-message');
expect(errPara).not.toBeNull();
}));
it('fields retain their values after a failed login', fakeAsync(() => {
authService.login.and.returnValue(throwError(() => new HttpErrorResponse({ status: 401 })));
component.form.setValue({ username: 'owner', password: 'wrong' });
component.onSubmit();
tick();
expect(component.form.value.username).toBe('owner');
expect(component.form.value.password).toBe('wrong');
}));
});

View File

@@ -10,29 +10,69 @@ import { AuthService } from '../auth/auth.service';
imports: [CommonModule, ReactiveFormsModule],
template: `
<div class="login-page">
<h1>Sign In</h1>
<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
<div class="field">
<label for="username">Username</label>
<input id="username" type="text" formControlName="username" />
<span *ngIf="form.get('username')?.invalid && form.get('username')?.touched" class="validation-error">
Username is required
</span>
</div>
<div class="field">
<label for="password">Password</label>
<input id="password" type="password" formControlName="password" />
<span *ngIf="form.get('password')?.invalid && form.get('password')?.touched" class="validation-error">
Password is required
</span>
</div>
<p *ngIf="errorMessage" class="error-message">{{ errorMessage }}</p>
<button type="submit" [disabled]="loading">
{{ loading ? 'Signing in…' : 'Sign In' }}
</button>
</form>
<div class="login-card">
<h1>Sign In</h1>
<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
<div class="field">
<label for="username">Username</label>
<input id="username" type="text" formControlName="username" autocomplete="username" />
<span *ngIf="form.get('username')?.invalid && form.get('username')?.touched" class="validation-error">
Username is required
</span>
</div>
<div class="field">
<label for="password">Password</label>
<input id="password" type="password" formControlName="password" autocomplete="current-password" />
<span *ngIf="form.get('password')?.invalid && form.get('password')?.touched" class="validation-error">
Password is required
</span>
</div>
<p *ngIf="errorMessage" class="error-message">{{ errorMessage }}</p>
<button type="submit" [disabled]="loading">
{{ loading ? 'Signing in…' : 'Sign In' }}
</button>
</form>
</div>
</div>
`,
styles: [`
.login-page {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 16px;
background: var(--bg);
}
.login-card {
width: 100%;
max-width: 400px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 40px 32px;
}
h1 { margin-bottom: 28px; font-size: 1.5rem; }
.field { margin-bottom: 20px; }
label { display: block; margin-bottom: 6px; font-size: 0.9rem; color: var(--text-muted); }
input[type="text"], input[type="password"] {
width: 100%; padding: 10px 12px;
background: var(--bg); border: 1px solid var(--border);
color: var(--text); border-radius: var(--radius);
font-size: 1rem; transition: border-color var(--transition);
}
input:focus { outline: none; border-color: var(--border-focus); }
.validation-error { display: block; margin-top: 4px; font-size: 0.8rem; color: var(--danger); }
.error-message { margin-bottom: 16px; color: var(--danger); font-size: 0.9rem; }
button[type="submit"] {
width: 100%; padding: 11px;
background: var(--accent); color: var(--accent-text);
border: none; border-radius: var(--radius);
font-size: 1rem; font-weight: 600; cursor: pointer;
transition: opacity var(--transition);
}
button[type="submit"]:disabled { opacity: 0.5; cursor: default; }
`],
})
export class LoginComponent {
form: FormGroup;
@@ -53,6 +93,7 @@ export class LoginComponent {
onSubmit(): void {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
this.loading = true;

View File

@@ -2,19 +2,12 @@ import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { of, throwError } from 'rxjs';
import { UploadComponent } from './upload.component';
import { ImageService } from '../services/image.service';
import { routes } from '../app.routes';
describe('UploadComponent', () => {
let component: UploadComponent;
function makeImageService(overrides: Partial<ImageService> = {}): jasmine.SpyObj<ImageService> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return jasmine.createSpyObj<ImageService>('ImageService', { upload: of({} as any), ...overrides } as any);
}
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UploadComponent],
@@ -26,22 +19,17 @@ describe('UploadComponent', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
component.tagInput = 'CAT, Funny reaction';
const parsed = component.parseTagInput(component.tagInput);
expect(parsed).toEqual(['cat', 'funny', 'reaction']);
expect(component.parseTagInput(component.tagInput)).toEqual(['cat', 'funny', 'reaction']);
});
it('should split on commas', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
const parsed = component.parseTagInput('a,b,c');
expect(parsed).toEqual(['a', 'b', 'c']);
expect(fixture.componentInstance.parseTagInput('a,b,c')).toEqual(['a', 'b', 'c']);
});
it('should filter empty tokens', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
const parsed = component.parseTagInput(' ,, cat ,,');
expect(parsed).toEqual(['cat']);
expect(fixture.componentInstance.parseTagInput(' ,, cat ,,')).toEqual(['cat']);
});
it('on duplicate response: shows toast and navigates to detail', async () => {
@@ -49,13 +37,7 @@ describe('UploadComponent', () => {
component = fixture.componentInstance;
const router = TestBed.inject(Router);
spyOn(router, 'navigate');
const mockSvc = makeImageService({
upload: of({ id: 'abc', duplicate: true } as any),
} as any);
(component as any).imageService = mockSvc;
await component.handleUploadResponse({ id: 'abc', duplicate: true } as any);
await component.handleUploadResponse({ id: 'abc', duplicate: true } as Parameters<typeof component.handleUploadResponse>[0]);
expect(component.toastMessage).toContain('library');
expect(router.navigate).toHaveBeenCalledWith(['/images', 'abc']);
});
@@ -65,8 +47,7 @@ describe('UploadComponent', () => {
component = fixture.componentInstance;
const router = TestBed.inject(Router);
spyOn(router, 'navigate');
await component.handleUploadResponse({ id: 'xyz', duplicate: false } as any);
await component.handleUploadResponse({ id: 'xyz', duplicate: false } as Parameters<typeof component.handleUploadResponse>[0]);
expect(component.toastMessage).toBeTruthy();
expect(router.navigate).toHaveBeenCalledWith(['/images', 'xyz']);
});
@@ -76,9 +57,66 @@ describe('UploadComponent', () => {
component = fixture.componentInstance;
const router = TestBed.inject(Router);
spyOn(router, 'navigate');
component.handleUploadError({ status: 422, error: { detail: 'bad file', code: 'invalid_mime_type' } });
expect(component.errorMessage).toBeTruthy();
expect(router.navigate).not.toHaveBeenCalled();
});
// New polish tests
it('submit button is disabled when no file is selected', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
const btn = (fixture.nativeElement as HTMLElement).querySelector('button[type="submit"]') as HTMLButtonElement;
expect(btn.disabled).toBeTrue();
});
it('submit button shows "Uploading…" label while uploading is true', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
component.uploading = true;
fixture.detectChanges();
const btn = (fixture.nativeElement as HTMLElement).querySelector('button[type="submit"]') as HTMLButtonElement;
expect(btn.textContent).toContain('Uploading');
expect(btn.disabled).toBeTrue();
});
it('showSuccess banner is hidden initially', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelector('.success-banner')).toBeNull();
});
it('showSuccess banner is visible when showSuccess is true', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
component.showSuccess = true;
component.uploadedFilename = 'photo.jpg';
fixture.detectChanges();
const banner = (fixture.nativeElement as HTMLElement).querySelector('.success-banner');
expect(banner).not.toBeNull();
expect(banner!.textContent).toContain('photo.jpg');
});
it('shows validation error message for 422 response', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.handleUploadError({ status: 422, error: { detail: 'Unsupported file type', code: 'invalid_mime_type' } });
fixture.detectChanges();
const err = (fixture.nativeElement as HTMLElement).querySelector('.error');
expect(err!.textContent).toContain('Unsupported file type');
});
it('shows generic error message for network error', () => {
const fixture = TestBed.createComponent(UploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.handleUploadError({ status: 500, error: null });
fixture.detectChanges();
const err = (fixture.nativeElement as HTMLElement).querySelector('.error');
expect(err!.textContent).toBeTruthy();
});
});

View File

@@ -1,13 +1,13 @@
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { Router, RouterLink } from '@angular/router';
import { ImageRecord, ImageService } from '../services/image.service';
@Component({
selector: 'app-upload',
standalone: true,
imports: [CommonModule, FormsModule],
imports: [CommonModule, FormsModule, RouterLink],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="upload-page">
@@ -15,45 +15,91 @@ import { ImageRecord, ImageService } from '../services/image.service';
<div
class="drop-zone"
role="button"
tabindex="0"
[class.drag-over]="isDragOver"
(dragover)="onDragOver($event)"
(dragleave)="isDragOver = false"
(drop)="onDrop($event)"
(click)="fileInput.click()"
(keydown.enter)="fileInput.click()"
(keydown.space)="fileInput.click()"
>
<span class="drop-icon">📁</span>
<p>{{ selectedFile ? selectedFile.name : 'Drag & drop or click to browse' }}</p>
<input #fileInput type="file" accept="image/*" hidden (change)="onFileChange($event)" />
</div>
<div class="tag-input" *ngIf="selectedFile">
<label>Tags (comma or space separated)</label>
<input [(ngModel)]="tagInput" placeholder="cat, funny, reaction" />
<label for="tag-input">Tags (comma or space separated)</label>
<input id="tag-input" [(ngModel)]="tagInput" placeholder="cat, funny, reaction" />
<div class="chips">
<span *ngFor="let tag of parseTagInput(tagInput)" class="chip">{{ tag }}</span>
</div>
</div>
<button [disabled]="!selectedFile || uploading" (click)="submit()">
<button type="submit" [disabled]="!selectedFile || uploading" (click)="submit()">
<span *ngIf="uploading" class="spinner"></span>
{{ uploading ? 'Uploading…' : 'Upload' }}
</button>
<p class="toast" *ngIf="toastMessage">{{ toastMessage }}</p>
<!-- Success banner -->
<div class="success-banner" *ngIf="showSuccess">
<span class="success-icon">✔</span>
<span>{{ uploadedFilename }} uploaded.</span>
<span class="banner-links">
<button type="button" class="link" (click)="resetForm()">Upload another</button>
<a routerLink="/" class="link">View in library</a>
</span>
</div>
<p class="toast" *ngIf="toastMessage && !showSuccess">{{ toastMessage }}</p>
<p class="error" *ngIf="errorMessage">{{ errorMessage }}</p>
</div>
`,
styles: [`
.upload-page { max-width: 600px; margin: 40px auto; padding: 0 16px; }
.drop-zone { border: 2px dashed #555; border-radius: 8px; padding: 40px; text-align: center; cursor: pointer; }
.drop-zone.drag-over { border-color: #fff; background: #1a1a1a; }
h1 { margin-bottom: 24px; }
.drop-zone {
border: 2px dashed color-mix(in srgb, var(--accent) 40%, transparent);
border-radius: var(--radius);
padding: 48px;
text-align: center;
cursor: pointer;
color: var(--text-muted);
background: var(--surface);
transition: border-color var(--transition), background var(--transition);
}
.drop-zone.drag-over { border-color: var(--accent); background: var(--surface-raised); }
.drop-icon { font-size: 2rem; display: block; margin-bottom: 8px; }
.tag-input { margin: 16px 0; }
label { display: block; margin-bottom: 4px; font-size: 0.9rem; color: #aaa; }
input[type=text], input:not([type]) { width: 100%; padding: 8px; background: #1a1a1a; border: 1px solid #444; color: #e0e0e0; border-radius: 4px; }
label { display: block; margin-bottom: 4px; font-size: 0.9rem; color: var(--text-muted); }
input[type=text], input:not([type]) { width: 100%; padding: 8px; background: var(--surface); border: 1px solid var(--border); color: var(--text); border-radius: var(--radius); }
input:focus { outline: none; border-color: var(--border-focus); }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
.chip { background: #333; padding: 2px 10px; border-radius: 12px; font-size: 0.85rem; }
button { padding: 10px 24px; background: #4a9eff; color: #000; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; }
button:disabled { opacity: 0.5; cursor: default; }
.toast { color: #4a9eff; margin-top: 12px; }
.error { color: #ff6b6b; margin-top: 12px; }
.chip { background: var(--surface-raised); padding: 2px 10px; border-radius: var(--radius-chip); font-size: 0.85rem; }
button[type="submit"] {
display: flex; align-items: center; gap: 8px;
padding: 10px 24px; background: var(--accent); color: var(--accent-text);
border: none; border-radius: var(--radius); cursor: pointer; font-weight: 600;
transition: opacity var(--transition);
}
button[type="submit"]:disabled { opacity: 0.5; cursor: default; color: var(--text-muted); }
@keyframes spin { to { transform: rotate(360deg); } }
.spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid var(--accent-text); border-top-color: transparent; border-radius: 50%; animation: spin 0.7s linear infinite; }
.success-banner {
display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
margin-top: 16px; padding: 12px 16px;
background: color-mix(in srgb, #2ecc71 12%, var(--surface));
border: 1px solid color-mix(in srgb, #2ecc71 30%, transparent);
border-radius: var(--radius); color: var(--text);
}
.success-icon { color: #2ecc71; font-size: 1.1rem; }
.banner-links { display: flex; gap: 12px; margin-left: auto; }
.link { color: var(--accent); cursor: pointer; text-decoration: none; font-size: 0.9rem; }
.link:hover { text-decoration: underline; }
.toast { color: var(--accent); margin-top: 12px; }
.error { color: var(--danger); margin-top: 12px; }
`],
})
export class UploadComponent {
@@ -63,6 +109,9 @@ export class UploadComponent {
toastMessage = '';
errorMessage = '';
isDragOver = false;
showSuccess = false;
uploadedFilename = '';
private dismissTimer: ReturnType<typeof setTimeout> | null = null;
constructor(
private imageService: ImageService,
@@ -101,6 +150,7 @@ export class UploadComponent {
this.uploading = true;
this.errorMessage = '';
this.toastMessage = '';
this.showSuccess = false;
const tags = this.parseTagInput(this.tagInput);
this.imageService.upload(this.selectedFile, tags).subscribe({
@@ -121,13 +171,36 @@ export class UploadComponent {
if (res.duplicate) {
this.toastMessage = 'Already in your library';
} else {
this.toastMessage = 'Image uploaded successfully!';
this.uploadedFilename = this.selectedFile?.name ?? res.id;
this.showSuccess = true;
this.cdr.markForCheck();
if (this.dismissTimer) clearTimeout(this.dismissTimer);
this.dismissTimer = setTimeout(() => {
this.showSuccess = false;
this.cdr.markForCheck();
}, 4000);
}
await this.router.navigate(['/images', res.id]);
}
handleUploadError(err: any): void {
const apiError = err?.error;
this.errorMessage = apiError?.detail ?? 'Upload failed. Please try again.';
handleUploadError(err: unknown): void {
const httpErr = err as { status?: number; error?: { detail?: string } };
const status = httpErr?.status;
const detail = httpErr?.error?.detail;
if (status === 422 && detail) {
this.errorMessage = detail;
} else {
this.errorMessage = 'Upload failed. Please try again.';
}
}
resetForm(): void {
this.selectedFile = null;
this.tagInput = '';
this.toastMessage = '';
this.errorMessage = '';
this.showSuccess = false;
if (this.dismissTimer) clearTimeout(this.dismissTimer);
this.cdr.markForCheck();
}
}

View File

@@ -1,3 +1,32 @@
:root {
--bg: #0f0f0f;
--surface: #1a1a1a;
--surface-raised: #252525;
--border: #333;
--border-focus: #555;
--text: #e0e0e0;
--text-muted: #777;
--accent: #4a9eff;
--accent-text: #000;
--danger: #c0392b;
--danger-text: #fff;
--radius: 6px;
--radius-chip: 12px;
--transition: 200ms ease;
}
@keyframes shimmer {
from { background-position: -200% 0; }
to { background-position: 200% 0; }
}
.skeleton {
background: linear-gradient(90deg, var(--surface) 25%, var(--surface-raised) 50%, var(--surface) 75%);
background-size: 200% 100%;
animation: shimmer 1.4s infinite;
border-radius: var(--radius);
}
* {
box-sizing: border-box;
margin: 0;
@@ -6,7 +35,7 @@
body {
font-family: system-ui, -apple-system, sans-serif;
background: #0f0f0f;
color: #e0e0e0;
background: var(--bg);
color: var(--text);
min-height: 100vh;
}