diff --git a/bun.lock b/bun.lock index ac785ed3c..08d0e78e8 100644 --- a/bun.lock +++ b/bun.lock @@ -8,7 +8,7 @@ "@angular/animations": "21.1.1", "@angular/common": "21.1.1", "@angular/compiler": "21.1.1", - "@angular/core": "21.1.1", + "@angular/core": "21.2.4", "@angular/forms": "21.1.1", "@angular/platform-browser": "21.1.1", "@angular/platform-browser-dynamic": "21.1.1", @@ -34,6 +34,7 @@ "prettier": "^3.8.1", "typescript": "~5.9.3", "vitest": "^4.0.18", + "zone.js": "~0.16.0", }, }, }, @@ -90,7 +91,7 @@ "@angular/compiler-cli": ["@angular/compiler-cli@21.1.1", "", { "dependencies": { "@babel/core": "7.28.5", "@jridgewell/sourcemap-codec": "^1.4.14", "chokidar": "^5.0.0", "convert-source-map": "^1.5.1", "reflect-metadata": "^0.2.0", "semver": "^7.0.0", "tslib": "^2.3.0", "yargs": "^18.0.0" }, "peerDependencies": { "@angular/compiler": "21.1.1", "typescript": ">=5.9 <6.0" }, "optionalPeers": ["typescript"], "bin": { "ngc": "bundles/src/bin/ngc.js", "ng-xi18n": "bundles/src/bin/ng_xi18n.js" } }, "sha512-CCB8SZS0BzqLOdOaMpPpOW256msuatYCFDRTaT+awYIY1vQp/eLXzkMTD2uqyHraQy8cReeH/P6optRP9A077Q=="], - "@angular/core": ["@angular/core@21.1.1", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/compiler": "21.1.1", "rxjs": "^6.5.3 || ^7.4.0", "zone.js": "~0.15.0 || ~0.16.0" }, "optionalPeers": ["@angular/compiler", "zone.js"] }, "sha512-KFRCEhsi02pY1EqJ5rnze4mzSaacqh14D8goDhtmARiUH0tefaHR+uKyu4bKSrWga2T/ExG0DJX52LhHRs2qSw=="], + "@angular/core": ["@angular/core@21.2.4", "", { "dependencies": { "tslib": "^2.3.0" }, "peerDependencies": { "@angular/compiler": "21.2.4", "rxjs": "^6.5.3 || ^7.4.0", "zone.js": "~0.15.0 || ~0.16.0" }, "optionalPeers": ["@angular/compiler", "zone.js"] }, "sha512-2+gd67ZuXHpGOqeb2o7XZPueEWEP81eJza2tSHkT5QMV8lnYllDEmaNnkPxnIjSLGP1O3PmiXxo4z8ibHkLZwg=="], "@angular/forms": ["@angular/forms@21.1.1", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "tslib": "^2.3.0" }, "peerDependencies": { "@angular/common": "21.1.1", "@angular/core": "21.1.1", "@angular/platform-browser": "21.1.1", "rxjs": "^6.5.3 || ^7.4.0" } }, "sha512-NBbJOynLOeMsPo03+3dfdxE0P7SB7SXRqoFJ7WP2sOgOIxODna/huo2blmRlnZAVPTn1iQEB9Q+UeyP5c4/1+w=="], 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..27952fda0 --- /dev/null +++ b/src/app/features/article/components/bookmark-button.component.spec.ts @@ -0,0 +1,126 @@ +import 'zone.js'; +import 'zone.js/testing'; +import { describe, it, expect, beforeEach, afterEach, beforeAll, vi } from 'vitest'; +import { ComponentFixture, TestBed, getTestBed } from '@angular/core/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Router } from '@angular/router'; +import { BehaviorSubject } from 'rxjs'; +import { BookmarkButtonComponent } from './bookmark-button.component'; +import { UserService } from '../../../core/auth/services/user.service'; +import { Article } from '../models/article.model'; + +describe('BookmarkButtonComponent', () => { + beforeAll(() => { + getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); + }); + + const article: Article = { + slug: 'how-to-build-webapps-that-scale', + title: 'How to build webapps that scale', + description: 'Web development technologies have evolved...', + body: 'body', + tagList: [], + createdAt: '2026-10-27T00:00:00.000Z', + updatedAt: '2026-10-27T00:00:00.000Z', + favorited: false, + favoritesCount: 12, + bookmarked: false, + author: { username: 'eric', bio: null, image: '', following: false }, + }; + + let fixture: ComponentFixture; + let httpMock: HttpTestingController; + let isAuthenticated: BehaviorSubject; + let router: { navigate: ReturnType }; + let emitted: boolean[]; + + const button = () => fixture.nativeElement.querySelector('button') as HTMLButtonElement; + + const render = (value: Article) => { + fixture.componentRef.setInput('article', value); + fixture.detectChanges(); + }; + + beforeEach(() => { + isAuthenticated = new BehaviorSubject(true); + router = { navigate: vi.fn().mockResolvedValue(true) }; + TestBed.configureTestingModule({ + imports: [BookmarkButtonComponent], + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + { provide: UserService, useValue: { isAuthenticated } }, + { provide: Router, useValue: router }, + ], + }); + fixture = TestBed.createComponent(BookmarkButtonComponent); + httpMock = TestBed.inject(HttpTestingController); + emitted = []; + fixture.componentInstance.toggle.subscribe(value => emitted.push(value)); + }); + + afterEach(() => { + httpMock.verify(); + TestBed.resetTestingModule(); + }); + + it('renders an outline "Save" button when not bookmarked', () => { + render(article); + expect(button().textContent?.trim()).toBe('๐Ÿ”– Save'); + expect(button().classList).toContain('btn-sm'); + expect(button().classList).toContain('btn-outline-bookmark'); + expect(button().classList).not.toContain('btn-bookmark'); + }); + + it('renders a filled "Saved" button when bookmarked', () => { + render({ ...article, bookmarked: true }); + expect(button().textContent?.trim()).toBe('๐Ÿ”– Saved'); + expect(button().classList).toContain('btn-bookmark'); + expect(button().classList).not.toContain('btn-outline-bookmark'); + }); + + it('treats a missing bookmarked field as not saved', () => { + const { bookmarked: _ignored, ...withoutField } = article; + render(withoutField as Article); + expect(button().textContent?.trim()).toBe('๐Ÿ”– Save'); + }); + + it('bookmarks the article when not saved and emits true', () => { + render(article); + button().click(); + const req = httpMock.expectOne(`/articles/${article.slug}/bookmark`); + expect(req.request.method).toBe('POST'); + req.flush({ article: { ...article, bookmarked: true } }); + expect(emitted).toEqual([true]); + expect(fixture.componentInstance.isSubmitting()).toBe(false); + }); + + it('unbookmarks the article when saved and emits false', () => { + render({ ...article, bookmarked: true }); + button().click(); + const req = httpMock.expectOne(`/articles/${article.slug}/bookmark`); + expect(req.request.method).toBe('DELETE'); + req.flush({ article: { ...article, bookmarked: false } }); + expect(emitted).toEqual([false]); + }); + + it('does not emit when the request fails', () => { + render(article); + button().click(); + httpMock.expectOne(`/articles/${article.slug}/bookmark`).flush(null, { status: 500, statusText: 'Error' }); + expect(emitted).toEqual([]); + expect(fixture.componentInstance.isSubmitting()).toBe(false); + }); + + it('redirects anonymous users to /login without calling the API', () => { + isAuthenticated.next(false); + render(article); + button().click(); + expect(router.navigate).toHaveBeenCalledWith(['/login']); + httpMock.expectNone(() => true); + expect(emitted).toEqual([]); + expect(fixture.componentInstance.isSubmitting()).toBe(false); + }); +}); 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..ccf34e253 --- /dev/null +++ b/src/app/features/article/components/bookmark-button.component.ts @@ -0,0 +1,105 @@ +import { + ChangeDetectionStrategy, + Component, + DestroyRef, + EventEmitter, + inject, + Input, + Output, + signal, +} from '@angular/core'; +import { Router } from '@angular/router'; +import { EMPTY, switchMap, take } from 'rxjs'; +import { NgClass } from '@angular/common'; +import { ArticlesService } from '../services/articles.service'; +import { UserService } from '../../../core/auth/services/user.service'; +import { Article } from '../models/article.model'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; + +@Component({ + selector: 'app-bookmark-button', + template: ` + + `, + styles: ` + .btn-outline-bookmark { + color: #f0ad4e; + background-color: transparent; + border-color: #f0ad4e; + } + .btn-outline-bookmark:hover { + color: #fff; + background-color: #f0ad4e; + border-color: #f0ad4e; + } + .btn-bookmark { + color: #fff; + background-color: #f0ad4e; + border-color: #f0ad4e; + } + .btn-bookmark:hover, + .btn-bookmark:focus { + color: #fff; + background-color: #ec971f; + border-color: #eb9316; + } + `, + imports: [NgClass], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class BookmarkButtonComponent { + destroyRef = inject(DestroyRef); + isSubmitting = signal(false); + + @Input() article!: Article; + @Output() toggle = new EventEmitter(); + + constructor( + private readonly articleService: ArticlesService, + private readonly router: Router, + private readonly userService: UserService, + ) {} + + toggleBookmark(): void { + const wasBookmarked = !!this.article.bookmarked; + this.isSubmitting.set(true); + + this.userService.isAuthenticated + .pipe( + take(1), + switchMap(authenticated => { + if (!authenticated) { + this.isSubmitting.set(false); + void this.router.navigate(['/login']); + return EMPTY; + } + + return wasBookmarked + ? this.articleService.unbookmark(this.article.slug) + : this.articleService.bookmark(this.article.slug); + }), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe({ + next: () => { + this.isSubmitting.set(false); + this.toggle.emit(!wasBookmarked); + }, + error: () => { + this.isSubmitting.set(false); + }, + }); + } +} diff --git a/src/app/features/article/models/article.model.ts b/src/app/features/article/models/article.model.ts index a7b07584b..f12bb0b0a 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.html b/src/app/features/article/pages/article/article.component.html index 87c71ffe0..19c1b9831 100644 --- a/src/app/features/article/pages/article/article.component.html +++ b/src/app/features/article/pages/article/article.component.html @@ -27,6 +27,8 @@

{{ a.title }}

> Delete Article + + } @else { @@ -36,6 +38,8 @@

{{ a.title }}

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

{{ a.title }}

> Delete Article + + } @else { @@ -83,6 +89,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..8ee6c4bbf 100644 --- a/src/app/features/article/pages/article/article.component.ts +++ b/src/app/features/article/pages/article/article.component.ts @@ -19,6 +19,7 @@ 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'; @@ -31,6 +32,7 @@ import { DefaultImagePipe } from '../../../../shared/pipes/default-image.pipe'; NgClass, FollowButtonComponent, FavoriteButtonComponent, + BookmarkButtonComponent, MarkdownPipe, AsyncPipe, ListErrorsComponent, @@ -94,6 +96,10 @@ export default class ArticleComponent implements OnInit { }); } + onToggleBookmark(bookmarked: boolean): void { + this.article.update(article => (article ? { ...article, 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..675e3c929 100644 --- a/src/app/features/article/services/articles.service.spec.ts +++ b/src/app/features/article/services/articles.service.spec.ts @@ -263,4 +263,53 @@ describe('ArticlesService', () => { expect(true).toBe(true); }); }); + + describe('bookmark', () => { + it('should POST to the bookmark endpoint and return the article', async () => { + const slug = 'article-to-save'; + const promise = firstValueFrom(service.bookmark(slug)); + const req = httpMock.expectOne(`/articles/${slug}/bookmark`); + expect(req.request.method).toBe('POST'); + expect(req.request.body).toEqual({}); + req.flush({ article: { ...mockArticle, slug, bookmarked: true } }); + const article = await promise; + expect(article.slug).toBe(slug); + expect(article.bookmarked).toBe(true); + }); + }); + + describe('unbookmark', () => { + it('should DELETE the bookmark endpoint and return the article', async () => { + const slug = 'article-to-unsave'; + const promise = firstValueFrom(service.unbookmark(slug)); + const req = httpMock.expectOne(`/articles/${slug}/bookmark`); + expect(req.request.method).toBe('DELETE'); + req.flush({ article: { ...mockArticle, slug, bookmarked: false } }); + const article = await promise; + expect(article.slug).toBe(slug); + expect(article.bookmarked).toBe(false); + }); + }); + + describe('queryBookmarked', () => { + it('should GET the bookmarked list with limit and offset', async () => { + const promise = firstValueFrom(service.queryBookmarked({ limit: 20, offset: 40 })); + const req = httpMock.expectOne(r => r.url === '/articles/bookmarked'); + expect(req.request.method).toBe('GET'); + expect(req.request.params.get('limit')).toBe('20'); + expect(req.request.params.get('offset')).toBe('40'); + const bookmarked = mockArticleList.map(a => ({ ...a, bookmarked: true })); + req.flush({ articles: bookmarked, articlesCount: 42 }); + const response = await promise; + expect(response.articles).toEqual(bookmarked); + expect(response.articlesCount).toBe(42); + }); + + it('should omit params when none are given', () => { + service.queryBookmarked().subscribe(); + const req = httpMock.expectOne('/articles/bookmarked'); + expect(req.request.params.keys()).toEqual([]); + req.flush({ articles: [], articlesCount: 0 }); + }); + }); }); diff --git a/src/app/features/article/services/articles.service.ts b/src/app/features/article/services/articles.service.ts index c4b816b98..374e4e569 100644 --- a/src/app/features/article/services/articles.service.ts +++ b/src/app/features/article/services/articles.service.ts @@ -51,4 +51,23 @@ 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(filters: { limit?: number; offset?: number } = {}): Observable<{ + articles: Article[]; + articlesCount: number; + }> { + let params = new HttpParams(); + if (filters.limit !== undefined) params = params.set('limit', filters.limit); + if (filters.offset !== undefined) params = params.set('offset', filters.offset); + + return this.http.get<{ articles: Article[]; articlesCount: number }>('/articles/bookmarked', { params }); + } } 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..3c794a059 --- /dev/null +++ b/src/app/features/profile/components/profile-reading-list.component.spec.ts @@ -0,0 +1,220 @@ +import 'zone.js'; +import 'zone.js/testing'; +import { describe, it, expect, beforeEach, afterEach, beforeAll } from 'vitest'; +import { Component } from '@angular/core'; +import { TestBed, getTestBed } from '@angular/core/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter, Router, RouterOutlet } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { BehaviorSubject } from 'rxjs'; +import ProfileReadingListComponent from './profile-reading-list.component'; +import { AuthState, UserService } from '../../../core/auth/services/user.service'; +import { User } from '../../../core/auth/user.model'; +import { Article } from '../../article/models/article.model'; + +@Component({ template: '', imports: [RouterOutlet] }) +class ProfileShellStub {} + +@Component({ template: 'my posts' }) +class ProfileArticlesStub {} + +describe('ProfileReadingListComponent', () => { + beforeAll(() => { + getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); + }); + + const ana = { username: 'ana', email: 'ana@example.com', token: 't', bio: null, image: null } as unknown as User; + + const makeArticle = (slug: string, author: string, title: string): Article => ({ + slug, + title, + description: `${title} description`, + body: 'body', + tagList: [], + createdAt: '2026-10-27T00:00:00.000Z', + updatedAt: '2026-10-27T00:00:00.000Z', + favorited: false, + favoritesCount: 3, + bookmarked: true, + author: { username: author, bio: null, image: '', following: false }, + }); + + const saved = [ + makeArticle('how-to-build-webapps-that-scale', 'eric', 'How to build webapps that scale'), + makeArticle('event-driven-payments-with-spring', 'sara', 'Event-driven payments with Spring'), + ]; + + let httpMock: HttpTestingController; + let currentUser: User | null; + let authState: BehaviorSubject; + + beforeEach(() => { + currentUser = ana; + authState = new BehaviorSubject('authenticated'); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideRouter([ + { + path: 'profile/:username', + component: ProfileShellStub, + children: [ + { path: '', component: ProfileArticlesStub }, + { path: 'reading-list', component: ProfileReadingListComponent }, + ], + }, + ]), + { + provide: UserService, + useValue: { + authState, + isAuthenticated: new BehaviorSubject(true), + getCurrentUserSync: () => currentUser, + }, + }, + ], + }); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + TestBed.resetTestingModule(); + }); + + const cards = (el: HTMLElement) => Array.from(el.querySelectorAll('.reading-list-item')) as HTMLElement[]; + + it("renders the current user's saved articles with a filled Saved button and no count", async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana/reading-list'); + + const req = httpMock.expectOne(r => r.url === '/articles/bookmarked'); + expect(req.request.method).toBe('GET'); + expect(req.request.params.get('limit')).toBe('10'); + expect(req.request.params.get('offset')).toBe('0'); + req.flush({ articles: saved, articlesCount: 2 }); + harness.detectChanges(); + + const el = harness.routeNativeElement!; + const items = cards(el); + expect(items.length).toBe(2); + expect(items[0].querySelector('h1')?.textContent).toContain('How to build webapps that scale'); + expect(items[0].querySelector('.author')?.textContent).toContain('eric'); + expect(items[0].querySelector('p')?.textContent).toContain('How to build webapps that scale description'); + expect(items[0].querySelector('a.preview-link')?.getAttribute('href')).toBe( + '/article/how-to-build-webapps-that-scale', + ); + const button = items[0].querySelector('button')!; + expect(button.textContent?.trim()).toBe('๐Ÿ”– Saved'); + expect(button.classList).toContain('btn-bookmark'); + expect(el.querySelector('.counter')).toBeNull(); + expect(el.querySelector('.ion-heart')).toBeNull(); + expect(el.querySelector('.pagination')).toBeNull(); + }); + + it('shows the exact empty state text when nothing is saved', async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana/reading-list'); + httpMock.expectOne(r => r.url === '/articles/bookmarked').flush({ articles: [], articlesCount: 0 }); + harness.detectChanges(); + + const el = harness.routeNativeElement!; + expect(cards(el).length).toBe(0); + expect(el.querySelector('.empty-reading-list-message')?.textContent?.trim()).toBe( + 'Nothing saved yet. Use ๐Ÿ”– Save on any article.', + ); + }); + + it('removes the card when an article is un-saved', async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana/reading-list'); + httpMock.expectOne(r => r.url === '/articles/bookmarked').flush({ articles: saved, articlesCount: 2 }); + harness.detectChanges(); + + const el = harness.routeNativeElement!; + (cards(el)[0].querySelector('button') as HTMLButtonElement).click(); + const req = httpMock.expectOne('/articles/how-to-build-webapps-that-scale/bookmark'); + expect(req.request.method).toBe('DELETE'); + req.flush({ article: { ...saved[0], bookmarked: false } }); + harness.detectChanges(); + + const remaining = cards(el); + expect(remaining.length).toBe(1); + expect(remaining[0].querySelector('h1')?.textContent).toContain('Event-driven payments with Spring'); + + (remaining[0].querySelector('button') as HTMLButtonElement).click(); + httpMock + .expectOne('/articles/event-driven-payments-with-spring/bookmark') + .flush({ article: { ...saved[1], bookmarked: false } }); + harness.detectChanges(); + expect(el.querySelector('.empty-reading-list-message')?.textContent?.trim()).toBe( + 'Nothing saved yet. Use ๐Ÿ”– Save on any article.', + ); + }); + + it('paginates when articlesCount exceeds the page size', async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana/reading-list'); + httpMock.expectOne(r => r.url === '/articles/bookmarked').flush({ articles: saved, articlesCount: 25 }); + harness.detectChanges(); + + const el = harness.routeNativeElement!; + const pages = el.querySelectorAll('.pagination .page-link'); + expect(pages.length).toBe(3); + (pages[1] as HTMLButtonElement).click(); + const req = httpMock.expectOne(r => r.url === '/articles/bookmarked'); + expect(req.request.params.get('offset')).toBe('10'); + req.flush({ articles: [], articlesCount: 25 }); + }); + + it('moves back to the last valid page when the only card on the last page is un-saved', async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana/reading-list'); + httpMock.expectOne(r => r.url === '/articles/bookmarked').flush({ articles: saved, articlesCount: 11 }); + harness.detectChanges(); + + const el = harness.routeNativeElement!; + (el.querySelectorAll('.pagination .page-link')[1] as HTMLButtonElement).click(); + httpMock + .expectOne(r => r.url === '/articles/bookmarked' && r.params.get('offset') === '10') + .flush({ articles: [saved[1]], articlesCount: 11 }); + harness.detectChanges(); + + (cards(el)[0].querySelector('button') as HTMLButtonElement).click(); + httpMock + .expectOne('/articles/event-driven-payments-with-spring/bookmark') + .flush({ article: { ...saved[1], bookmarked: false } }); + + const reload = httpMock.expectOne(r => r.url === '/articles/bookmarked'); + expect(reload.request.params.get('offset')).toBe('0'); + reload.flush({ articles: [saved[0]], articlesCount: 10 }); + harness.detectChanges(); + + expect(cards(el).length).toBe(1); + expect(el.querySelector('.empty-reading-list-message')).toBeNull(); + expect(el.querySelector('.pagination')).toBeNull(); + }); + + it("redirects to the profile and never requests bookmarks on someone else's profile", async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/eric/reading-list'); + await harness.fixture.whenStable(); + + expect(TestBed.inject(Router).url).toBe('/profile/eric'); + httpMock.expectNone(r => r.url === '/articles/bookmarked'); + }); + + it('redirects anonymous users away from the reading list', async () => { + currentUser = null; + authState.next('unauthenticated'); + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana/reading-list'); + await harness.fixture.whenStable(); + + expect(TestBed.inject(Router).url).toBe('/profile/ana'); + httpMock.expectNone(r => r.url === '/articles/bookmarked'); + }); +}); 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..69f2a12c4 --- /dev/null +++ b/src/app/features/profile/components/profile-reading-list.component.ts @@ -0,0 +1,147 @@ +import { ChangeDetectionStrategy, Component, DestroyRef, inject, OnInit, signal } from '@angular/core'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { DatePipe, NgClass } from '@angular/common'; +import { filter, take } from 'rxjs/operators'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { ArticlesService } from '../../article/services/articles.service'; +import { Article } from '../../article/models/article.model'; +import { BookmarkButtonComponent } from '../../article/components/bookmark-button.component'; +import { UserService } from '../../../core/auth/services/user.service'; +import { LoadingState } from '../../../core/models/loading-state.model'; + +@Component({ + selector: 'app-profile-reading-list', + template: ` + @if (loading() === LoadingState.LOADING) { +
Loading articles...
+ } + + @if (loading() === LoadingState.LOADED) { + @for (article of results(); track article.slug) { +
+ + +

{{ article.title }}

+

{{ article.description }}

+
+
+ } @empty { +
Nothing saved yet. Use ๐Ÿ”– Save on any article.
+ } + + @if (totalPages().length > 1) { + + } + } + `, + styles: ` + .page-link { + cursor: pointer; + } + .reading-list-meta { + color: #bbb; + font-size: 0.8rem; + vertical-align: middle; + } + .reading-list-meta .author { + color: inherit; + font-weight: normal; + } + `, + imports: [BookmarkButtonComponent, RouterLink, DatePipe, 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); + LoadingState = LoadingState; + destroyRef = inject(DestroyRef); + + constructor( + private readonly route: ActivatedRoute, + private readonly router: Router, + private readonly articlesService: ArticlesService, + private readonly userService: UserService, + ) {} + + ngOnInit(): void { + const username = this.route.parent?.snapshot.params['username']; + + this.userService.authState + .pipe( + filter(state => state !== 'loading'), + take(1), + takeUntilDestroyed(this.destroyRef), + ) + .subscribe(() => { + const user = this.userService.getCurrentUserSync(); + if (!user || user.username !== username) { + void this.router.navigate(['/profile', username], { replaceUrl: true }); + return; + } + this.runQuery(); + }); + } + + setPageTo(pageNumber: number): void { + if (pageNumber !== this.page()) { + this.page.set(pageNumber); + this.runQuery(); + } + } + + onToggleBookmark(article: Article, bookmarked: boolean): void { + if (bookmarked) return; + this.results.update(articles => articles.filter(item => item.slug !== article.slug)); + this.articlesCount.update(count => Math.max(count - 1, 0)); + this.totalPages.set(this.pageRange(this.articlesCount())); + + if (this.results().length === 0 && this.articlesCount() > 0) { + this.page.set(Math.min(this.page(), this.totalPages().length)); + this.runQuery(); + } + } + + private pageRange(count: number): number[] { + return Array.from({ length: Math.ceil(count / this.limit) }, (_, index) => index + 1); + } + + private runQuery(): void { + this.loading.set(LoadingState.LOADING); + this.results.set([]); + + this.articlesService + .queryBookmarked({ limit: this.limit, offset: this.limit * (this.page() - 1) }) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(data => { + this.loading.set(LoadingState.LOADED); + this.results.set(data.articles); + this.articlesCount.set(data.articlesCount); + this.totalPages.set(this.pageRange(data.articlesCount)); + }); + } +} diff --git a/src/app/features/profile/pages/profile/profile.component.html b/src/app/features/profile/pages/profile/profile.component.html index 04033ccdc..1a5ef4451 100644 --- a/src/app/features/profile/pages/profile/profile.component.html +++ b/src/app/features/profile/pages/profile/profile.component.html @@ -54,6 +54,18 @@

{{ p.username }}

Favorited Posts + @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..41eb9f3d8 --- /dev/null +++ b/src/app/features/profile/pages/profile/profile.component.spec.ts @@ -0,0 +1,87 @@ +import 'zone.js'; +import 'zone.js/testing'; +import { describe, it, expect, beforeEach, afterEach, beforeAll } from 'vitest'; +import { Component } from '@angular/core'; +import { TestBed, getTestBed } from '@angular/core/testing'; +import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { provideRouter } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +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'; + +@Component({ template: '' }) +class ChildStub {} + +describe('ProfileComponent tabs', () => { + beforeAll(() => { + getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); + }); + + const ana = { username: 'ana', email: 'ana@example.com', token: 't', bio: null, image: null } as unknown as User; + let currentUser: BehaviorSubject; + + beforeEach(() => { + currentUser = new BehaviorSubject(ana); + TestBed.configureTestingModule({ + providers: [ + provideRouter([ + { + path: 'profile/:username', + component: ProfileComponent, + children: [ + { path: '', component: ChildStub }, + { path: 'favorites', component: ChildStub }, + { path: 'reading-list', component: ChildStub }, + ], + }, + ]), + { + provide: ProfileService, + useValue: { + get: (username: string) => of({ username, bio: null, image: '', following: false }), + }, + }, + { provide: UserService, useValue: { currentUser, isAuthenticated: of(true) } }, + ], + }); + }); + + afterEach(() => TestBed.resetTestingModule()); + + const tabLabels = (el: HTMLElement) => + Array.from(el.querySelectorAll('.articles-toggle .nav-link')).map(a => a.textContent?.trim()); + + it('shows the Reading list tab on your own profile', async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana'); + harness.detectChanges(); + + const el = harness.routeNativeElement!; + expect(tabLabels(el)).toEqual(['My Posts', 'Favorited Posts', 'Reading list']); + const link = Array.from(el.querySelectorAll('.articles-toggle .nav-link')).find( + a => a.textContent?.trim() === 'Reading list', + ); + expect(link?.getAttribute('href')).toBe('/profile/ana/reading-list'); + }); + + it("hides the Reading list tab on another user's profile", async () => { + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/eric'); + harness.detectChanges(); + + expect(tabLabels(harness.routeNativeElement!)).toEqual(['My Posts', 'Favorited Posts']); + }); + + it('hides the Reading list tab for anonymous visitors', async () => { + currentUser.next(null); + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/profile/ana'); + harness.detectChanges(); + + expect(tabLabels(harness.routeNativeElement!)).toEqual(['My Posts', 'Favorited Posts']); + }); +}); diff --git a/src/app/features/profile/pages/profile/profile.component.ts b/src/app/features/profile/pages/profile/profile.component.ts index 82d89196c..7f61f6c4e 100644 --- a/src/app/features/profile/pages/profile/profile.component.ts +++ b/src/app/features/profile/pages/profile/profile.component.ts @@ -14,6 +14,11 @@ import { DefaultImagePipe } from '../../../../shared/pipes/default-image.pipe'; @Component({ selector: 'app-profile-page', templateUrl: './profile.component.html', + styles: ` + .nav-pills.outline-active .nav-link.reading-list-tab.active { + color: #f0ad4e; + } + `, imports: [ FollowButtonComponent, RouterLink, diff --git a/src/app/features/profile/profile.routes.ts b/src/app/features/profile/profile.routes.ts index 4687b5611..358f3b324 100644 --- a/src/app/features/profile/profile.routes.ts +++ b/src/app/features/profile/profile.routes.ts @@ -17,6 +17,10 @@ const routes: Routes = [ path: 'favorites', loadComponent: () => import('./components/profile-favorites.component'), }, + { + path: 'reading-list', + loadComponent: () => import('./components/profile-reading-list.component'), + }, ], }, ],