diff --git a/bun.lock b/bun.lock index ac785ed3c..ed8e1e549 100644 --- a/bun.lock +++ b/bun.lock @@ -34,6 +34,7 @@ "prettier": "^3.8.1", "typescript": "~5.9.3", "vitest": "^4.0.18", + "zone.js": "~0.16.0", }, }, }, diff --git a/package.json b/package.json index 38bd2b29c..220efa1d5 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,8 @@ "playwright": "^1.58.0", "prettier": "^3.8.1", "typescript": "~5.9.3", - "vitest": "^4.0.18" + "vitest": "^4.0.18", + "zone.js": "~0.16.0" }, "lint-staged": { "*.{ts,html,css,json,md}": "prettier --write" diff --git a/src/app/features/article/components/bookmark-button.component.spec.ts b/src/app/features/article/components/bookmark-button.component.spec.ts new file mode 100644 index 000000000..4d5c92185 --- /dev/null +++ b/src/app/features/article/components/bookmark-button.component.spec.ts @@ -0,0 +1,181 @@ +import 'zone.js'; +import 'zone.js/testing'; +import { describe, it, expect, beforeEach, afterEach, beforeAll, vi } from 'vitest'; +import { TestBed, getTestBed, ComponentFixture } from '@angular/core/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { Router } from '@angular/router'; +import { BehaviorSubject, of, Subject, throwError } from 'rxjs'; +import { BookmarkButtonComponent } from './bookmark-button.component'; +import { ArticlesService } from '../services/articles.service'; +import { AuthState, UserService } from '../../../core/auth/services/user.service'; +import { Article } from '../models/article.model'; + +describe('BookmarkButtonComponent', () => { + beforeAll(() => { + try { + getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); + } catch { + // already initialized by test-setup + } + }); + + const article: Article = { + slug: 'how-to-build-webapps', + title: 'How to build webapps that scale', + description: 'Web development technologies...', + body: 'Body', + tagList: [], + createdAt: '2024-10-27T00:00:00.000Z', + updatedAt: '2024-10-27T00:00:00.000Z', + favorited: false, + favoritesCount: 12, + bookmarked: false, + author: { username: 'eric', bio: null, image: null, following: false }, + }; + + let fixture: ComponentFixture; + let component: BookmarkButtonComponent; + let authState: BehaviorSubject; + let articlesService: { bookmark: ReturnType; unbookmark: ReturnType }; + let router: { navigate: ReturnType }; + + const button = () => fixture.nativeElement.querySelector('button') as HTMLButtonElement; + + function render(input: Article) { + fixture = TestBed.createComponent(BookmarkButtonComponent); + component = fixture.componentInstance; + fixture.componentRef.setInput('article', input); + fixture.detectChanges(); + } + + beforeEach(() => { + authState = new BehaviorSubject('authenticated'); + articlesService = { bookmark: vi.fn(), unbookmark: vi.fn() }; + router = { navigate: vi.fn().mockResolvedValue(true) }; + + TestBed.configureTestingModule({ + imports: [BookmarkButtonComponent], + providers: [ + { provide: ArticlesService, useValue: articlesService }, + { provide: UserService, useValue: { authState: authState.asObservable() } }, + { provide: Router, useValue: router }, + ], + }); + }); + + afterEach(() => { + TestBed.resetTestingModule(); + }); + + it('renders an outlined "πŸ”– Save" button when not bookmarked', () => { + render(article); + expect(button().textContent?.trim()).toBe('πŸ”– Save'); + expect(button().classList).toContain('btn-bookmark'); + expect(button().classList).not.toContain('btn-bookmark-active'); + expect(button().getAttribute('aria-pressed')).toBe('false'); + }); + + it('renders a filled "πŸ”– Saved" button when bookmarked and shows no count', () => { + render({ ...article, bookmarked: true }); + expect(button().textContent?.trim()).toBe('πŸ”– Saved'); + expect(button().classList).toContain('btn-bookmark-active'); + expect(button().getAttribute('aria-pressed')).toBe('true'); + expect(fixture.nativeElement.textContent).not.toMatch(/\d/); + }); + + it('bookmarks and emits the updated article on success', () => { + const response = { ...article, bookmarked: true }; + articlesService.bookmark.mockReturnValue(of(response)); + render(article); + const emitted: Article[] = []; + component.toggle.subscribe(a => emitted.push(a)); + + button().click(); + + expect(articlesService.bookmark).toHaveBeenCalledWith(article.slug); + expect(articlesService.unbookmark).not.toHaveBeenCalled(); + expect(emitted).toEqual([response]); + expect(component.isSubmitting()).toBe(false); + }); + + it('unbookmarks when already saved', () => { + articlesService.unbookmark.mockReturnValue(of({ ...article, bookmarked: false })); + render({ ...article, bookmarked: true }); + const emitted: Article[] = []; + component.toggle.subscribe(a => emitted.push(a)); + + button().click(); + + expect(articlesService.unbookmark).toHaveBeenCalledWith(article.slug); + expect(emitted[0].bookmarked).toBe(false); + }); + + it('disables the button while the request is in flight and ignores repeat clicks', () => { + const pending = new Subject
(); + articlesService.bookmark.mockReturnValue(pending); + render(article); + + button().click(); + fixture.detectChanges(); + expect(button().disabled).toBe(true); + expect(button().getAttribute('aria-busy')).toBe('true'); + + component.toggleBookmark(); + expect(articlesService.bookmark).toHaveBeenCalledTimes(1); + + pending.next({ ...article, bookmarked: true }); + pending.complete(); + fixture.detectChanges(); + expect(button().disabled).toBe(false); + }); + + it('shows an error and keeps the previous state when the request fails', () => { + articlesService.bookmark.mockReturnValue(throwError(() => ({ status: 500, errors: { body: ['boom'] } }))); + render(article); + const emitted: Article[] = []; + component.toggle.subscribe(a => emitted.push(a)); + + button().click(); + fixture.detectChanges(); + + expect(emitted).toEqual([]); + expect(button().textContent?.trim()).toBe('πŸ”– Save'); + expect(button().disabled).toBe(false); + expect(fixture.nativeElement.querySelector('[role="alert"]')?.textContent).toContain('Could not update'); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('redirects anonymous users to /login without calling the API', () => { + authState.next('unauthenticated'); + render(article); + + button().click(); + + expect(router.navigate).toHaveBeenCalledWith(['/login']); + expect(articlesService.bookmark).not.toHaveBeenCalled(); + expect(component.isSubmitting()).toBe(false); + }); + + it('redirects to /login when the API responds 401', () => { + articlesService.bookmark.mockReturnValue(throwError(() => ({ status: 401, errors: {} }))); + render(article); + + button().click(); + + expect(router.navigate).toHaveBeenCalledWith(['/login']); + }); + + it('waits for auth initialization instead of redirecting a persisted session', () => { + authState.next('loading'); + articlesService.bookmark.mockReturnValue(of({ ...article, bookmarked: true })); + render(article); + + button().click(); + expect(router.navigate).not.toHaveBeenCalled(); + expect(articlesService.bookmark).not.toHaveBeenCalled(); + + authState.next('authenticated'); + expect(articlesService.bookmark).toHaveBeenCalledTimes(1); + expect(router.navigate).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/features/article/components/bookmark-button.component.ts b/src/app/features/article/components/bookmark-button.component.ts new file mode 100644 index 000000000..292a64a5b --- /dev/null +++ b/src/app/features/article/components/bookmark-button.component.ts @@ -0,0 +1,112 @@ +import { + ChangeDetectionStrategy, + Component, + DestroyRef, + EventEmitter, + inject, + Input, + Output, + signal, +} from '@angular/core'; +import { Router } from '@angular/router'; +import { EMPTY, filter, switchMap, take } from 'rxjs'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { ArticlesService } from '../services/articles.service'; +import { UserService } from '../../../core/auth/services/user.service'; +import { Article } from '../models/article.model'; + +@Component({ + selector: 'app-bookmark-button', + template: ` + + @if (error()) { + {{ error() }} + } + `, + styles: ` + .btn-bookmark { + color: #f0ad4e; + background-color: transparent; + border-color: #f0ad4e; + } + .btn-bookmark:hover, + .btn-bookmark-active { + color: #fff; + background-color: #f0ad4e; + border-color: #eb9316; + } + .bookmark-error { + margin-left: 0.25rem; + color: #b85c5c; + font-size: 0.8rem; + } + `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class BookmarkButtonComponent { + destroyRef = inject(DestroyRef); + isSubmitting = signal(false); + error = signal(null); + + @Input({ required: true }) article!: Article; + @Output() toggle = new EventEmitter
(); + + constructor( + private readonly articlesService: ArticlesService, + private readonly router: Router, + private readonly userService: UserService, + ) {} + + toggleBookmark(): void { + if (this.isSubmitting()) return; + this.isSubmitting.set(true); + this.error.set(null); + + this.userService.authState + .pipe( + filter(state => state !== 'loading'), + take(1), + switchMap(state => { + if (state === 'unauthenticated') { + this.isSubmitting.set(false); + void this.router.navigate(['/login']); + return EMPTY; + } + if (state === 'unavailable') { + this.isSubmitting.set(false); + this.error.set('Could not reach the server. Try again.'); + return EMPTY; + } + return this.article.bookmarked + ? this.articlesService.unbookmark(this.article.slug) + : this.articlesService.bookmark(this.article.slug); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe({ + next: article => { + this.isSubmitting.set(false); + this.toggle.emit(article); + }, + error: (err: { status?: number }) => { + this.isSubmitting.set(false); + if (err?.status === 401) { + void this.router.navigate(['/login']); + return; + } + this.error.set('Could not update reading list. Try again.'); + }, + }); + } +} diff --git a/src/app/features/article/models/article.model.ts b/src/app/features/article/models/article.model.ts index a7b07584b..17b0bb151 100644 --- a/src/app/features/article/models/article.model.ts +++ b/src/app/features/article/models/article.model.ts @@ -10,5 +10,6 @@ export interface Article { updatedAt: string; favorited: boolean; favoritesCount: number; + bookmarked: boolean; author: Profile; } diff --git a/src/app/features/article/pages/article/article.component.css b/src/app/features/article/pages/article/article.component.css new file mode 100644 index 000000000..96b22d8be --- /dev/null +++ b/src/app/features/article/pages/article/article.component.css @@ -0,0 +1,14 @@ +.article-page .banner { + color: #fff; + background: #333; + border: none; +} + +.article-page .banner h1 { + color: #fff; + text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); +} + +.article-page .banner ::ng-deep .article-meta .author { + color: #fff; +} diff --git a/src/app/features/article/pages/article/article.component.html b/src/app/features/article/pages/article/article.component.html index 87c71ffe0..0eb3bedc3 100644 --- a/src/app/features/article/pages/article/article.component.html +++ b/src/app/features/article/pages/article/article.component.html @@ -36,6 +36,8 @@

{{ a.title }}

{{ a.favorited ? 'Unfavorite' : 'Favorite' }} Article ({{ a.favoritesCount }}) + + } @@ -83,6 +85,8 @@

{{ a.title }}

{{ a.favorited ? 'Unfavorite' : 'Favorite' }} Article ({{ a.favoritesCount }}) + + } diff --git a/src/app/features/article/pages/article/article.component.ts b/src/app/features/article/pages/article/article.component.ts index 0219afad1..7899d2dc7 100644 --- a/src/app/features/article/pages/article/article.component.ts +++ b/src/app/features/article/pages/article/article.component.ts @@ -19,18 +19,21 @@ import { Errors } from '../../../../core/models/errors.model'; import { Profile } from '../../../profile/models/profile.model'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FavoriteButtonComponent } from '../../components/favorite-button.component'; +import { BookmarkButtonComponent } from '../../components/bookmark-button.component'; import { FollowButtonComponent } from '../../../profile/components/follow-button.component'; import { DefaultImagePipe } from '../../../../shared/pipes/default-image.pipe'; @Component({ selector: 'app-article-page', templateUrl: './article.component.html', + styleUrls: ['./article.component.css'], imports: [ ArticleMetaComponent, RouterLink, NgClass, FollowButtonComponent, FavoriteButtonComponent, + BookmarkButtonComponent, MarkdownPipe, AsyncPipe, ListErrorsComponent, @@ -94,6 +97,10 @@ export default class ArticleComponent implements OnInit { }); } + onToggleBookmark(updated: Article): void { + this.article.update(article => (article ? { ...article, bookmarked: updated.bookmarked } : article)); + } + toggleFollowing(profile: Profile): void { this.article.update(article => { if (!article) return article; diff --git a/src/app/features/article/services/articles.service.spec.ts b/src/app/features/article/services/articles.service.spec.ts index a6a8af9a6..560944e57 100644 --- a/src/app/features/article/services/articles.service.spec.ts +++ b/src/app/features/article/services/articles.service.spec.ts @@ -27,6 +27,7 @@ describe('ArticlesService', () => { updatedAt: '2024-01-02', favorited: false, favoritesCount: 5, + bookmarked: false, author: { username: 'testuser', bio: 'Test bio', @@ -263,4 +264,51 @@ describe('ArticlesService', () => { expect(true).toBe(true); }); }); + + describe('bookmark', () => { + it('should POST to the bookmark endpoint and return the viewer-specific article', async () => { + const promise = firstValueFrom(service.bookmark('test-article')); + const req = httpMock.expectOne('/articles/test-article/bookmark'); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual({}); + req.flush({ article: { ...mockArticle, bookmarked: true } }); + const article = await promise; + expect(article.bookmarked).toBe(true); + expect(article).not.toHaveProperty('bookmarksCount'); + }); + + it('should propagate 401 errors for unauthenticated requests', async () => { + const promise = firstValueFrom(service.bookmark('test-article')); + const req = httpMock.expectOne('/articles/test-article/bookmark'); + req.flush({ errors: { body: ['Unauthorized'] } }, { status: 401, statusText: 'Unauthorized' }); + await expect(promise).rejects.toMatchObject({ status: 401 }); + }); + }); + + describe('unbookmark', () => { + it('should DELETE the bookmark endpoint and return the article with bookmarked false', async () => { + const promise = firstValueFrom(service.unbookmark('test-article')); + const req = httpMock.expectOne('/articles/test-article/bookmark'); + expect(req.request.method).toBe('DELETE'); + req.flush({ article: { ...mockArticle, bookmarked: false } }); + const article = await promise; + expect(article.bookmarked).toBe(false); + }); + }); + + describe('queryBookmarked', () => { + it('should GET /articles/bookmarked with limit and offset only', async () => { + const promise = firstValueFrom(service.queryBookmarked(10, 20)); + const req = httpMock.expectOne(request => request.url === '/articles/bookmarked'); + expect(req.request.method).toBe('GET'); + expect(req.request.params.get('limit')).toBe('10'); + expect(req.request.params.get('offset')).toBe('20'); + expect(req.request.params.keys().sort()).toEqual(['limit', 'offset']); + const saved = mockArticleList.map(article => ({ ...article, bookmarked: true })); + req.flush({ articles: saved, articlesCount: 22 }); + const response = await promise; + expect(response.articles.map(a => a.slug)).toEqual(['test-article', 'second-article']); + expect(response.articlesCount).toBe(22); + }); + }); }); diff --git a/src/app/features/article/services/articles.service.ts b/src/app/features/article/services/articles.service.ts index c4b816b98..ea658a641 100644 --- a/src/app/features/article/services/articles.service.ts +++ b/src/app/features/article/services/articles.service.ts @@ -51,4 +51,17 @@ export class ArticlesService { unfavorite(slug: string): Observable { return this.http.delete(`/articles/${slug}/favorite`); } + + bookmark(slug: string): Observable
{ + return this.http.post<{ article: Article }>(`/articles/${slug}/bookmark`, {}).pipe(map(data => data.article)); + } + + unbookmark(slug: string): Observable
{ + return this.http.delete<{ article: Article }>(`/articles/${slug}/bookmark`).pipe(map(data => data.article)); + } + + queryBookmarked(limit: number, offset: number): Observable<{ articles: Article[]; articlesCount: number }> { + const params = new HttpParams().set('limit', limit).set('offset', offset); + return this.http.get<{ articles: Article[]; articlesCount: number }>('/articles/bookmarked', { params }); + } } diff --git a/src/app/features/profile/components/profile-articles.component.ts b/src/app/features/profile/components/profile-articles.component.ts index 453ec2364..af444ab56 100644 --- a/src/app/features/profile/components/profile-articles.component.ts +++ b/src/app/features/profile/components/profile-articles.component.ts @@ -5,6 +5,7 @@ import { ProfileService } from '../services/profile.service'; import { Profile } from '../models/profile.model'; import { ArticleListConfig } from '../../article/models/article-list-config.model'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { switchMap } from 'rxjs'; @Component({ selector: 'app-profile-articles', @@ -25,9 +26,11 @@ export default class ProfileArticlesComponent implements OnInit { ) {} ngOnInit(): void { - this.profileService - .get(this.route.snapshot.params['username']) - .pipe(takeUntilDestroyed(this.destroyRef)) + this.route.paramMap + .pipe( + switchMap(params => this.profileService.get(params.get('username')!)), + takeUntilDestroyed(this.destroyRef), + ) .subscribe({ next: (profile: Profile) => { this.profile.set(profile); diff --git a/src/app/features/profile/components/profile-favorites.component.ts b/src/app/features/profile/components/profile-favorites.component.ts index a48ee96f1..703f45918 100644 --- a/src/app/features/profile/components/profile-favorites.component.ts +++ b/src/app/features/profile/components/profile-favorites.component.ts @@ -5,6 +5,7 @@ import { ProfileService } from '../services/profile.service'; import { Profile } from '../models/profile.model'; import { ArticleListConfig } from '../../article/models/article-list-config.model'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { switchMap } from 'rxjs'; @Component({ selector: 'app-profile-favorites', @@ -25,9 +26,11 @@ export default class ProfileFavoritesComponent implements OnInit { ) {} ngOnInit() { - this.profileService - .get(this.route.parent?.snapshot.params['username']) - .pipe(takeUntilDestroyed(this.destroyRef)) + this.route + .parent!.paramMap.pipe( + switchMap(params => this.profileService.get(params.get('username')!)), + takeUntilDestroyed(this.destroyRef), + ) .subscribe({ next: (profile: Profile) => { this.profile.set(profile); diff --git a/src/app/features/profile/components/profile-reading-list.component.spec.ts b/src/app/features/profile/components/profile-reading-list.component.spec.ts new file mode 100644 index 000000000..b76f97fd3 --- /dev/null +++ b/src/app/features/profile/components/profile-reading-list.component.spec.ts @@ -0,0 +1,203 @@ +import 'zone.js'; +import 'zone.js/testing'; +import { describe, it, expect, beforeEach, afterEach, beforeAll, vi } from 'vitest'; +import { TestBed, getTestBed, ComponentFixture } from '@angular/core/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { provideRouter, Router } from '@angular/router'; +import { BehaviorSubject, of, throwError } from 'rxjs'; +import ProfileReadingListComponent from './profile-reading-list.component'; +import { ArticlesService } from '../../article/services/articles.service'; +import { AuthState, UserService } from '../../../core/auth/services/user.service'; +import { Article } from '../../article/models/article.model'; + +describe('ProfileReadingListComponent', () => { + beforeAll(() => { + try { + getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); + } catch { + // already initialized by test-setup + } + }); + + const makeArticle = (n: number): Article => ({ + slug: `article-${n}`, + title: `Article ${n}`, + description: `Description ${n}`, + body: 'Body', + tagList: [], + createdAt: '2024-10-27T00:00:00.000Z', + updatedAt: '2024-10-27T00:00:00.000Z', + favorited: false, + favoritesCount: 0, + bookmarked: true, + author: { username: 'eric', bio: null, image: null, following: false }, + }); + + let fixture: ComponentFixture; + let component: ProfileReadingListComponent; + let authState: BehaviorSubject; + let currentUser: BehaviorSubject<{ username: string } | null>; + let articlesService: { + queryBookmarked: ReturnType; + bookmark: ReturnType; + unbookmark: ReturnType; + }; + + const el = () => fixture.nativeElement as HTMLElement; + const cards = () => Array.from(el().querySelectorAll('.preview-link h1')).map(h => h.textContent?.trim()); + const pages = () => Array.from(el().querySelectorAll('.page-link')).map(b => b.textContent?.trim()); + const savedButtons = () => Array.from(el().querySelectorAll('app-bookmark-button button')); + + function render() { + fixture = TestBed.createComponent(ProfileReadingListComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + } + + beforeEach(() => { + articlesService = { queryBookmarked: vi.fn(), bookmark: vi.fn(), unbookmark: vi.fn() }; + authState = new BehaviorSubject('authenticated'); + currentUser = new BehaviorSubject<{ username: string } | null>({ username: 'eric' }); + TestBed.configureTestingModule({ + imports: [ProfileReadingListComponent], + providers: [ + provideRouter([]), + { provide: ArticlesService, useValue: articlesService }, + { provide: UserService, useValue: { authState, currentUser } }, + ], + }); + }); + + afterEach(() => TestBed.resetTestingModule()); + + it('loads the first page of the current user’s reading list in API order (newest saved first)', () => { + articlesService.queryBookmarked.mockReturnValue( + of({ articles: [makeArticle(2), makeArticle(1)], articlesCount: 2 }), + ); + render(); + + expect(articlesService.queryBookmarked).toHaveBeenCalledWith(10, 0); + expect(cards()).toEqual(['Article 2', 'Article 1']); + expect(savedButtons().map(b => b.textContent?.trim())).toEqual(['πŸ”– Saved', 'πŸ”– Saved']); + expect(pages()).toEqual([]); + }); + + it('shows the exact empty state text', () => { + articlesService.queryBookmarked.mockReturnValue(of({ articles: [], articlesCount: 0 })); + render(); + expect(el().querySelector('.empty-reading-list')?.textContent?.trim()).toBe( + 'Nothing saved yet. Use πŸ”– Save on any article.', + ); + }); + + it('removes the card immediately on unsave and shows the empty state when the last one is removed', () => { + articlesService.queryBookmarked.mockReturnValue(of({ articles: [makeArticle(1)], articlesCount: 1 })); + articlesService.unbookmark.mockReturnValue(of({ ...makeArticle(1), bookmarked: false })); + render(); + + savedButtons()[0].click(); + fixture.detectChanges(); + + expect(articlesService.unbookmark).toHaveBeenCalledWith('article-1'); + expect(cards()).toEqual([]); + expect(component.articlesCount()).toBe(0); + expect(el().textContent).toContain('Nothing saved yet. Use πŸ”– Save on any article.'); + expect(articlesService.queryBookmarked).toHaveBeenCalledTimes(1); + }); + + it('keeps the card and shows an error when unsave fails', () => { + articlesService.queryBookmarked.mockReturnValue(of({ articles: [makeArticle(1)], articlesCount: 1 })); + articlesService.unbookmark.mockReturnValue(throwError(() => ({ status: 500 }))); + render(); + + savedButtons()[0].click(); + fixture.detectChanges(); + + expect(cards()).toEqual(['Article 1']); + expect(component.articlesCount()).toBe(1); + expect(el().querySelector('[role="alert"]')).not.toBeNull(); + }); + + it('paginates with limit/offset and updates pagination after unsave', () => { + const page1 = Array.from({ length: 10 }, (_, i) => makeArticle(11 - i)); + articlesService.queryBookmarked.mockImplementation((limit: number, offset: number) => + offset === 0 ? of({ articles: page1, articlesCount: 11 }) : of({ articles: [makeArticle(1)], articlesCount: 11 }), + ); + render(); + expect(pages()).toEqual(['1', '2']); + + el().querySelectorAll('.page-link')[1].click(); + fixture.detectChanges(); + expect(articlesService.queryBookmarked).toHaveBeenLastCalledWith(10, 10); + expect(cards()).toEqual(['Article 1']); + + // Unsaving the only card on page 2 drops back to page 1 and the pager collapses + articlesService.unbookmark.mockReturnValue(of({ ...makeArticle(1), bookmarked: false })); + articlesService.queryBookmarked.mockReturnValue(of({ articles: page1, articlesCount: 10 })); + savedButtons()[0].click(); + fixture.detectChanges(); + + expect(component.page()).toBe(1); + expect(articlesService.queryBookmarked).toHaveBeenLastCalledWith(10, 0); + expect(cards()).toHaveLength(10); + expect(pages()).toEqual([]); + }); + + it('backfills the current page from the next page after unsave', () => { + const page1 = Array.from({ length: 10 }, (_, i) => makeArticle(11 - i)); + articlesService.queryBookmarked.mockReturnValueOnce(of({ articles: page1, articlesCount: 11 })); + render(); + + articlesService.unbookmark.mockReturnValue(of({ ...makeArticle(11), bookmarked: false })); + articlesService.queryBookmarked.mockReturnValueOnce( + of({ articles: [...page1.slice(1), makeArticle(1)], articlesCount: 10 }), + ); + savedButtons()[0].click(); + fixture.detectChanges(); + + expect(articlesService.queryBookmarked).toHaveBeenLastCalledWith(10, 0); + expect(cards()).toHaveLength(10); + expect(cards()).not.toContain('Article 11'); + expect(cards()[9]).toBe('Article 1'); + expect(pages()).toEqual([]); + }); + + it('shows a retryable error when loading fails', () => { + articlesService.queryBookmarked.mockReturnValueOnce(throwError(() => ({ status: 500 }))); + render(); + expect(el().querySelector('.reading-list-error')).not.toBeNull(); + + articlesService.queryBookmarked.mockReturnValueOnce(of({ articles: [makeArticle(1)], articlesCount: 1 })); + (el().querySelector('.reading-list-error button') as HTMLButtonElement).click(); + fixture.detectChanges(); + expect(el().querySelector('.reading-list-error')).toBeNull(); + expect(cards()).toEqual(['Article 1']); + }); + + it('clears the private list and leaves when the viewer logs out while on the route', () => { + articlesService.queryBookmarked.mockReturnValue(of({ articles: [makeArticle(1)], articlesCount: 1 })); + render(); + const navigate = vi.spyOn(TestBed.inject(Router), 'navigate').mockResolvedValue(true); + expect(cards()).toEqual(['Article 1']); + + currentUser.next(null); + authState.next('unauthenticated'); + fixture.detectChanges(); + + expect(cards()).toEqual([]); + expect(el().textContent).not.toContain('Article 1'); + expect(navigate).toHaveBeenCalledWith(['/login']); + }); + + it('leaves the route when a different account becomes current', () => { + articlesService.queryBookmarked.mockReturnValue(of({ articles: [makeArticle(1)], articlesCount: 1 })); + render(); + const navigate = vi.spyOn(TestBed.inject(Router), 'navigate').mockResolvedValue(true); + + currentUser.next({ username: 'ana' }); + fixture.detectChanges(); + + expect(cards()).toEqual([]); + expect(navigate).toHaveBeenCalledWith(['/profile', 'ana']); + }); +}); diff --git a/src/app/features/profile/components/profile-reading-list.component.ts b/src/app/features/profile/components/profile-reading-list.component.ts new file mode 100644 index 000000000..1dd7fc49b --- /dev/null +++ b/src/app/features/profile/components/profile-reading-list.component.ts @@ -0,0 +1,164 @@ +import { ChangeDetectionStrategy, Component, DestroyRef, inject, OnInit, signal } from '@angular/core'; +import { Router, RouterLink } from '@angular/router'; +import { NgClass } from '@angular/common'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { ArticlesService } from '../../article/services/articles.service'; +import { Article } from '../../article/models/article.model'; +import { ArticleMetaComponent } from '../../article/components/article-meta.component'; +import { BookmarkButtonComponent } from '../../article/components/bookmark-button.component'; +import { LoadingState } from '../../../core/models/loading-state.model'; +import { UserService } from '../../../core/auth/services/user.service'; +import { combineLatest, filter } from 'rxjs'; + +@Component({ + selector: 'app-profile-reading-list', + template: ` + @if (loading() === LoadingState.LOADING) { +
Loading reading list...
+ } + + @if (loadError()) { + + } + + @if (loading() === LoadingState.LOADED) { + @for (article of results(); track article.slug) { +
+ + + + +

{{ article.title }}

+

{{ article.description }}

+ Read more... +
+
+ } @empty { +
Nothing saved yet. Use πŸ”– Save on any article.
+ } + + @if (totalPages().length > 1) { + + } + } + `, + styles: ` + .page-link { + cursor: pointer; + } + `, + imports: [ArticleMetaComponent, BookmarkButtonComponent, RouterLink, NgClass], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export default class ProfileReadingListComponent implements OnInit { + readonly limit = 10; + results = signal([]); + articlesCount = signal(0); + page = signal(1); + totalPages = signal([]); + loading = signal(LoadingState.NOT_LOADED); + loadError = signal(false); + LoadingState = LoadingState; + destroyRef = inject(DestroyRef); + private readonly router = inject(Router); + private readonly userService = inject(UserService); + + constructor(private readonly articlesService: ArticlesService) {} + + ngOnInit(): void { + this.load(); + this.leaveWhenOwnerChanges(); + } + + /** The guard only runs on navigation; drop private data if the viewer logs out or switches account in place. */ + private leaveWhenOwnerChanges(): void { + let owner: string | undefined; + combineLatest([this.userService.authState, this.userService.currentUser]) + .pipe( + filter(([state]) => state !== 'loading'), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe(([state, user]) => { + if (state === 'unavailable') return; + if (owner === undefined && user) { + owner = user.username; + return; + } + if (user?.username === owner) return; + this.results.set([]); + this.setCount(0); + this.loading.set(LoadingState.NOT_LOADED); + void this.router.navigate(user ? ['/profile', user.username] : ['/login']); + }); + } + + setPageTo(pageNumber: number): void { + if (pageNumber !== this.page()) { + this.page.set(pageNumber); + this.load(); + } + } + + load(background = false): void { + if (!background) { + this.loading.set(LoadingState.LOADING); + this.results.set([]); + } + this.loadError.set(false); + + this.articlesService + .queryBookmarked(this.limit, this.limit * (this.page() - 1)) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: data => { + this.results.set(data.articles); + this.setCount(data.articlesCount); + this.loading.set(LoadingState.LOADED); + if (data.articles.length === 0 && this.page() > 1 && this.totalPages().length < this.page()) { + this.page.set(this.totalPages().length || 1); + this.load(); + } + }, + error: () => { + this.loading.set(LoadingState.NOT_LOADED); + this.loadError.set(true); + }, + }); + } + + onToggle(article: Article): void { + if (article.bookmarked) { + this.results.update(list => + list.map(item => (item.slug === article.slug ? { ...item, bookmarked: true } : item)), + ); + return; + } + + this.results.update(list => list.filter(item => item.slug !== article.slug)); + this.setCount(Math.max(this.articlesCount() - 1, 0)); + + const shownBefore = this.limit * (this.page() - 1); + if (this.results().length === 0 && this.page() > 1) { + this.page.set(this.page() - 1); + this.load(); + } else if (this.articlesCount() > shownBefore + this.results().length) { + this.load(true); + } + } + + private setCount(count: number): void { + this.articlesCount.set(count); + this.totalPages.set(Array.from({ length: Math.ceil(count / this.limit) }, (_, index) => index + 1)); + } +} diff --git a/src/app/features/profile/pages/profile/profile.component.html b/src/app/features/profile/pages/profile/profile.component.html index 04033ccdc..b59727a07 100644 --- a/src/app/features/profile/pages/profile/profile.component.html +++ b/src/app/features/profile/pages/profile/profile.component.html @@ -41,7 +41,7 @@

{{ p.username }}

[routerLinkActiveOptions]="{ exact: true }" [routerLink]="['/profile', p.username]" > - My Posts + My Articles + @if (isUser()) { + + } diff --git a/src/app/features/profile/pages/profile/profile.component.spec.ts b/src/app/features/profile/pages/profile/profile.component.spec.ts new file mode 100644 index 000000000..19fec3c4a --- /dev/null +++ b/src/app/features/profile/pages/profile/profile.component.spec.ts @@ -0,0 +1,69 @@ +import 'zone.js'; +import 'zone.js/testing'; +import { describe, it, expect, beforeEach, afterEach, beforeAll, vi } from 'vitest'; +import { TestBed, getTestBed, ComponentFixture } from '@angular/core/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { ActivatedRoute, convertToParamMap, ParamMap, provideRouter } from '@angular/router'; +import { BehaviorSubject, of } from 'rxjs'; +import { ProfileComponent } from './profile.component'; +import { ProfileService } from '../../services/profile.service'; +import { UserService } from '../../../../core/auth/services/user.service'; +import { User } from '../../../../core/auth/user.model'; +import { Profile } from '../../models/profile.model'; + +describe('ProfileComponent tabs', () => { + beforeAll(() => { + try { + getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); + } catch { + // already initialized by test-setup + } + }); + + const ana: User = { email: 'ana@example.com', token: 't', username: 'ana', bio: null, image: null }; + const profileOf = (username: string): Profile => ({ username, bio: null, image: null, following: false }); + + let fixture: ComponentFixture; + let paramMap: BehaviorSubject; + let currentUser: BehaviorSubject; + + const tabs = () => + Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.nav-link')).map(a => a.textContent?.trim()); + + beforeEach(() => { + paramMap = new BehaviorSubject(convertToParamMap({ username: 'ana' })); + currentUser = new BehaviorSubject(ana); + TestBed.configureTestingModule({ + imports: [ProfileComponent], + providers: [ + provideRouter([]), + { provide: ActivatedRoute, useValue: { paramMap, snapshot: { params: {} } } }, + { provide: ProfileService, useValue: { get: vi.fn((u: string) => of(profileOf(u))) } }, + { provide: UserService, useValue: { currentUser } }, + ], + }); + fixture = TestBed.createComponent(ProfileComponent); + fixture.detectChanges(); + }); + + afterEach(() => TestBed.resetTestingModule()); + + it('shows the Reading list tab on the signed-in user’s own profile', () => { + expect(tabs()).toEqual(['My Articles', 'Favorited Articles', 'Reading list']); + const link = (fixture.nativeElement as HTMLElement).querySelector('.reading-list-tab'); + expect(link?.getAttribute('href')).toBe('/profile/ana/reading-list'); + }); + + it('hides the Reading list tab on other users’ profiles, including when the route is reused', () => { + paramMap.next(convertToParamMap({ username: 'eric' })); + fixture.detectChanges(); + expect((fixture.nativeElement as HTMLElement).querySelector('h4')?.textContent).toBe('eric'); + expect(tabs()).toEqual(['My Articles', 'Favorited Articles']); + }); + + it('hides the Reading list tab for anonymous visitors', () => { + currentUser.next(null); + fixture.detectChanges(); + expect(tabs()).not.toContain('Reading list'); + }); +}); diff --git a/src/app/features/profile/pages/profile/profile.component.ts b/src/app/features/profile/pages/profile/profile.component.ts index 82d89196c..e6deed858 100644 --- a/src/app/features/profile/pages/profile/profile.component.ts +++ b/src/app/features/profile/pages/profile/profile.component.ts @@ -23,6 +23,11 @@ import { DefaultImagePipe } from '../../../../shared/pipes/default-image.pipe'; ListErrorsComponent, DefaultImagePipe, ], + styles: ` + .nav-pills.outline-active .nav-link.reading-list-tab.active { + color: #f0ad4e; + } + `, changeDetection: ChangeDetectionStrategy.OnPush, }) export class ProfileComponent implements OnInit { @@ -39,12 +44,16 @@ export class ProfileComponent implements OnInit { ) {} ngOnInit() { - this.profileService - .get(this.route.snapshot.params['username']) + this.route.paramMap .pipe( - catchError(error => { - this.errors.set(error.errors || { error: ['Failed to load profile'] }); - return EMPTY; + switchMap(params => { + this.errors.set(null); + return this.profileService.get(params.get('username')!).pipe( + catchError(error => { + this.errors.set(error.errors || { error: ['Failed to load profile'] }); + return EMPTY; + }), + ); }), switchMap(profile => { return combineLatest([of(profile), this.userService.currentUser]); diff --git a/src/app/features/profile/profile.routes.ts b/src/app/features/profile/profile.routes.ts index 4687b5611..f4166e015 100644 --- a/src/app/features/profile/profile.routes.ts +++ b/src/app/features/profile/profile.routes.ts @@ -1,5 +1,6 @@ import { Routes } from '@angular/router'; import { ProfileComponent } from './pages/profile/profile.component'; +import { readingListGuard } from './reading-list.guard'; const routes: Routes = [ { @@ -17,6 +18,12 @@ const routes: Routes = [ path: 'favorites', loadComponent: () => import('./components/profile-favorites.component'), }, + { + path: 'reading-list', + loadComponent: () => import('./components/profile-reading-list.component'), + canActivate: [readingListGuard], + runGuardsAndResolvers: 'always', + }, ], }, ], diff --git a/src/app/features/profile/reading-list.guard.spec.ts b/src/app/features/profile/reading-list.guard.spec.ts new file mode 100644 index 000000000..021aabdfa --- /dev/null +++ b/src/app/features/profile/reading-list.guard.spec.ts @@ -0,0 +1,85 @@ +import 'zone.js'; +import 'zone.js/testing'; +import { describe, it, expect, beforeEach, afterEach, beforeAll } from 'vitest'; +import { TestBed, getTestBed } from '@angular/core/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { ActivatedRouteSnapshot, provideRouter, Router, RouterStateSnapshot, UrlTree } from '@angular/router'; +import { BehaviorSubject, isObservable, Observable } from 'rxjs'; +import { readingListGuard } from './reading-list.guard'; +import { AuthState, UserService } from '../../core/auth/services/user.service'; +import { User } from '../../core/auth/user.model'; + +describe('readingListGuard', () => { + beforeAll(() => { + try { + getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); + } catch { + // already initialized by test-setup + } + }); + + const ana: User = { email: 'ana@example.com', token: 't', username: 'ana', bio: null, image: null }; + let authState: BehaviorSubject; + let currentUser: BehaviorSubject; + + beforeEach(() => { + authState = new BehaviorSubject('authenticated'); + currentUser = new BehaviorSubject(ana); + TestBed.configureTestingModule({ + providers: [ + provideRouter([]), + { + provide: UserService, + useValue: { authState: authState.asObservable(), currentUser: currentUser.asObservable() }, + }, + ], + }); + }); + + afterEach(() => TestBed.resetTestingModule()); + + function run(username: string): Observable { + const route = { params: {}, parent: { params: { username } } } as unknown as ActivatedRouteSnapshot; + const result = TestBed.runInInjectionContext(() => readingListGuard(route, {} as RouterStateSnapshot)); + if (!isObservable(result)) throw new Error('guard should return an observable'); + return result as Observable; + } + + function collect(username: string): (boolean | string)[] { + const router = TestBed.inject(Router); + const values: (boolean | string)[] = []; + run(username).subscribe(v => values.push(typeof v === 'boolean' ? v : router.serializeUrl(v))); + return values; + } + + it('allows the owner of the profile', () => { + expect(collect('ana')).toEqual([true]); + }); + + it('redirects another user’s reading list to that user’s profile', () => { + expect(collect('eric')).toEqual(['/profile/eric']); + }); + + it('redirects anonymous users to /login', () => { + authState.next('unauthenticated'); + currentUser.next(null); + expect(collect('ana')).toEqual(['/login']); + }); + + it('waits for auth loading to finish before deciding (direct reload)', () => { + authState.next('loading'); + currentUser.next(null); + const values = collect('ana'); + expect(values).toEqual([]); + + currentUser.next(ana); + authState.next('authenticated'); + expect(values).toEqual([true]); + }); + + it('does not grant access when auth is unavailable', () => { + authState.next('unavailable'); + currentUser.next(null); + expect(collect('ana')).toEqual(['/profile/ana']); + }); +}); diff --git a/src/app/features/profile/reading-list.guard.ts b/src/app/features/profile/reading-list.guard.ts new file mode 100644 index 000000000..38d2d7b75 --- /dev/null +++ b/src/app/features/profile/reading-list.guard.ts @@ -0,0 +1,28 @@ +import { inject } from '@angular/core'; +import { ActivatedRouteSnapshot, CanActivateFn, Router } from '@angular/router'; +import { combineLatest, filter, map, take } from 'rxjs'; +import { UserService } from '../../core/auth/services/user.service'; + +/** + * Reading list is private: only the signed-in owner of the profile may open it. + * Waits for auth initialization so a persisted session isn't redirected on reload. + */ +export const readingListGuard: CanActivateFn = (route: ActivatedRouteSnapshot) => { + const router = inject(Router); + const userService = inject(UserService); + const username = route.parent?.params['username'] ?? route.params['username']; + + return combineLatest([userService.authState, userService.currentUser]).pipe( + filter(([state]) => state !== 'loading'), + take(1), + map(([state, user]) => { + if (state === 'unauthenticated') { + return router.createUrlTree(['/login']); + } + if (!user || user.username !== username) { + return router.createUrlTree(['/profile', username]); + } + return true; + }), + ); +};