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
5 changes: 3 additions & 2 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
126 changes: 126 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,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<BookmarkButtonComponent>;
let httpMock: HttpTestingController;
let isAuthenticated: BehaviorSubject<boolean>;
let router: { navigate: ReturnType<typeof vi.fn> };
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);
});
});
105 changes: 105 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,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: `
<button
type="button"
class="btn btn-sm bookmark-btn"
[ngClass]="{
disabled: isSubmitting(),
'btn-outline-bookmark': !article.bookmarked,
'btn-bookmark': article.bookmarked,
}"
[attr.aria-pressed]="!!article.bookmarked"
(click)="toggleBookmark()"
>
🔖 {{ article.bookmarked ? 'Saved' : 'Save' }}
</button>
`,
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<boolean>();

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);
},
});
}
}
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;
}
8 changes: 8 additions & 0 deletions src/app/features/article/pages/article/article.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ <h1>{{ a.title }}</h1>
>
<i class="ion-trash-a"></i> Delete Article
</button>

<app-bookmark-button [article]="a" (toggle)="onToggleBookmark($event)" />
</span>
} @else {
<span>
Expand All @@ -36,6 +38,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)" />
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
</span>
}
</app-article-meta>
Expand Down Expand Up @@ -74,6 +78,8 @@ <h1>{{ a.title }}</h1>
>
<i class="ion-trash-a"></i> Delete Article
</button>

<app-bookmark-button [article]="a" (toggle)="onToggleBookmark($event)" />
</span>
} @else {
<span>
Expand All @@ -83,6 +89,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
6 changes: 6 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,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';

Expand All @@ -31,6 +32,7 @@ import { DefaultImagePipe } from '../../../../shared/pipes/default-image.pipe';
NgClass,
FollowButtonComponent,
FavoriteButtonComponent,
BookmarkButtonComponent,
MarkdownPipe,
AsyncPipe,
ListErrorsComponent,
Expand Down Expand Up @@ -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;
Expand Down
49 changes: 49 additions & 0 deletions src/app/features/article/services/articles.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});
});
});
Loading
Loading