Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
181 changes: 181 additions & 0 deletions src/app/features/article/components/bookmark-button.component.spec.ts
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 src/app/features/article/components/bookmark-button.component.ts
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.');
},
});
}
}
1 change: 1 addition & 0 deletions src/app/features/article/models/article.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ export interface Article {
updatedAt: string;
favorited: boolean;
favoritesCount: number;
bookmarked: boolean;
author: Profile;
}
14 changes: 14 additions & 0 deletions src/app/features/article/pages/article/article.component.css
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;
}
4 changes: 4 additions & 0 deletions src/app/features/article/pages/article/article.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ <h1>{{ a.title }}</h1>
{{ a.favorited ? 'Unfavorite' : 'Favorite' }} Article
<span class="counter">({{ a.favoritesCount }})</span>
</app-favorite-button>

<app-bookmark-button [article]="a" (toggle)="onToggleBookmark($event)" />

Copy link
Copy Markdown
Author

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-button outside the canModify() alternatives in both action rows, preserving the author-only edit/delete controls and the reader-only follow/favorite controls.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Author

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 the canModify() branch in both action rows.

</span>
}
</app-article-meta>
Expand Down Expand Up @@ -83,6 +85,8 @@ <h1>{{ a.title }}</h1>
{{ a.favorited ? 'Unfavorite' : 'Favorite' }} Article
<span class="counter">({{ a.favoritesCount }})</span>
</app-favorite-button>

<app-bookmark-button [article]="a" (toggle)="onToggleBookmark($event)" />
</span>
}
</app-article-meta>
Expand Down
7 changes: 7 additions & 0 deletions src/app/features/article/pages/article/article.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading