Repository navigation
[Measurement run – do not merge] STORY-142: Save for later + private Reading list (frontend, Fusion) #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
[Measurement run – do not merge] STORY-142: Save for later + private Reading list (frontend, Fusion) #84
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
181 changes: 181 additions & 0 deletions
181
src/app/features/article/components/bookmark-button.component.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<BookmarkButtonComponent>; | ||
| let component: BookmarkButtonComponent; | ||
| let authState: BehaviorSubject<AuthState>; | ||
| let articlesService: { bookmark: ReturnType<typeof vi.fn>; unbookmark: ReturnType<typeof vi.fn> }; | ||
| let router: { navigate: ReturnType<typeof vi.fn> }; | ||
|
|
||
| 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<AuthState>('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<Article>(); | ||
| 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(); | ||
| }); | ||
| }); |
112 changes: 112 additions & 0 deletions
112
src/app/features/article/components/bookmark-button.component.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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: ` | ||
| <button | ||
| type="button" | ||
| class="btn btn-sm btn-bookmark" | ||
| [class.btn-bookmark-active]="article.bookmarked" | ||
| [class.disabled]="isSubmitting()" | ||
| [disabled]="isSubmitting()" | ||
| [attr.aria-pressed]="article.bookmarked" | ||
| [attr.aria-busy]="isSubmitting()" | ||
| (click)="toggleBookmark()" | ||
| > | ||
| 🔖 {{ article.bookmarked ? 'Saved' : 'Save' }} | ||
| </button> | ||
| @if (error()) { | ||
| <span class="bookmark-error" role="alert">{{ error() }}</span> | ||
| } | ||
| `, | ||
| 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<string | null>(null); | ||
|
|
||
| @Input({ required: true }) article!: Article; | ||
| @Output() toggle = new EventEmitter<Article>(); | ||
|
|
||
| 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.'); | ||
| }, | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
src/app/features/article/pages/article/article.component.css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Authors cannot save their own articles
For an article's author,
canModify()hides both Save buttons behind the reader-only branch. Authors cannot add their own articles to their reading list.Learn more
Both article action rows render the Save button only when
canModify()is false. That signal is true when the signed-in user's username matches the article author's username in ngOnInit. The author branch renders only edit and delete controls, so an author viewing their own article cannot invoke the new bookmark endpoint.Example: Ana opens an article she published. She sees Edit and Delete in the banner and lower action row, but no Save button; she cannot add the article to her reading list.
Recommended fix: Render
app-bookmark-buttonoutside thecanModify()alternatives in both action rows, preserving the author-only edit/delete controls and the reader-only follow/favorite controls.Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Confirmed: the button sits in the reader branch next to Favorite, so authors don't see it on their own articles. This follows the story brief ("Show Save for anonymous… and readers") and matches how Favorite works. I've asked the coordinator whether authors should get it too. If so, the fix is to move
<app-bookmark-button>out of thecanModify()branch in both action rows.