Skip to content
Open
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
46 changes: 46 additions & 0 deletions frontend/components/article/ArticleMeta.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,48 @@
import React from "react";
import Router from "next/router";
import useSWR, { trigger } from "swr";

import ArticleActions from "./ArticleActions";
import CustomImage from "../common/CustomImage";
import CustomLink from "../common/CustomLink";
import ArticleAPI from "../../lib/api/article";
import checkLogin from "../../lib/utils/checkLogin";
import { SERVER_BASE_URL } from "../../lib/utils/constant";
import storage from "../../lib/utils/storage";

const BOOKMARKED_CLASS = "btn btn-sm btn-primary";
const NOT_BOOKMARKED_CLASS = "btn btn-sm btn-outline-primary";

const ArticleMeta = ({ article }) => {
const { data: currentUser } = useSWR("user", storage);
const isLoggedIn = checkLogin(currentUser);

const [bookmarked, setBookmarked] = React.useState(article?.bookmarked || false);

React.useEffect(() => {
setBookmarked(article?.bookmarked || false);
}, [article?.bookmarked]);

const handleBookmark = async () => {
if (!isLoggedIn) {
Router.push(`/user/login`);
return;
}

try {
if (bookmarked) {
setBookmarked(false);
await ArticleAPI.unbookmark(article.slug, currentUser?.token);
} else {
setBookmarked(true);
await ArticleAPI.bookmark(article.slug, currentUser?.token);
}
trigger(`${SERVER_BASE_URL}/articles/${article.slug}`);
} catch (error) {
setBookmarked(bookmarked);
}
};

if (!article) return;

return (
Expand All @@ -30,6 +68,14 @@ const ArticleMeta = ({ article }) => {
</div>

<ArticleActions article={article} />

<button
className={bookmarked ? BOOKMARKED_CLASS : NOT_BOOKMARKED_CLASS}
onClick={handleBookmark}
style={{ marginLeft: "4px" }}
>
<i className="ion-bookmark" /> {bookmarked ? "Bookmarked" : "Bookmark"}
</button>
</div>
);
};
Expand Down
37 changes: 37 additions & 0 deletions frontend/components/article/ArticlePreview.tsx

@devin-ai-integration devin-ai-integration Bot Jun 15, 2026

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.

🚩 Bookmark error handler in ArticlePreview is more correct than the existing favorite error handler

The new handleClickBookmark error handler at line 48-51 uses bookmarked: preview.bookmarked (the original closure value) to revert state on API failure — this is correct. Interestingly, the pre-existing handleClickFavorite error handler at frontend/components/article/ArticlePreview.tsx:88-94 uses favorited: !preview.favorited which reapplies the toggled value rather than reverting it, effectively making the catch block a no-op for the favorited field. This is a pre-existing bug in the favorite handler that the bookmark handler avoids. Consider fixing handleClickFavorite's error handler to match the bookmark pattern.

Open in 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.

Good catch — the same stale-closure pattern exists in the pre-existing handleClickFavorite. That's a pre-existing bug outside the scope of this PR's bookmark feature, but worth noting for a follow-up fix.

Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ import CustomLink from "../common/CustomLink";
import CustomImage from "../common/CustomImage";
import { usePageDispatch } from "../../lib/context/PageContext";
import checkLogin from "../../lib/utils/checkLogin";
import ArticleAPI from "../../lib/api/article";
import { SERVER_BASE_URL } from "../../lib/utils/constant";
import storage from "../../lib/utils/storage";

const FAVORITED_CLASS = "btn btn-sm btn-primary";
const NOT_FAVORITED_CLASS = "btn btn-sm btn-outline-primary";
const BOOKMARKED_CLASS = "btn btn-sm btn-primary";
const NOT_BOOKMARKED_CLASS = "btn btn-sm btn-outline-primary";

const ArticlePreview = ({ article }) => {
const setPage = usePageDispatch();
Expand All @@ -24,6 +27,31 @@ const ArticlePreview = ({ article }) => {
const { data: currentUser } = useSWR("user", storage);
const isLoggedIn = checkLogin(currentUser);

const handleClickBookmark = async (slug) => {
if (!isLoggedIn) {
Router.push(`/user/login`);
return;
}

setPreview({
...preview,
bookmarked: !preview.bookmarked,
});

try {
if (preview.bookmarked) {
await ArticleAPI.unbookmark(slug, currentUser?.token);
} else {
await ArticleAPI.bookmark(slug, currentUser?.token);
}
} catch (error) {
setPreview({
...preview,
bookmarked: preview.bookmarked,
});
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
}
};

const handleClickFavorite = async (slug) => {
if (!isLoggedIn) {
Router.push(`/user/login`);
Expand Down Expand Up @@ -96,6 +124,15 @@ const ArticlePreview = ({ article }) => {
</div>

<div className="pull-xs-right">
<button
className={
preview.bookmarked ? BOOKMARKED_CLASS : NOT_BOOKMARKED_CLASS
}
onClick={() => handleClickBookmark(preview.slug)}
style={{ marginRight: "4px" }}
>
<i className="ion-bookmark" />
</button>
<button
className={
preview.favorited ? FAVORITED_CLASS : NOT_FAVORITED_CLASS
Expand Down
18 changes: 18 additions & 0 deletions frontend/lib/api/article.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,24 @@ const ArticleAPI = {
unfavorite: (slug) =>
axios.delete(`${SERVER_BASE_URL}/articles/${slug}/favorite`),

bookmark: (slug, token) =>
axios.post(
`${SERVER_BASE_URL}/articles/${slug}/bookmark`,
{},
{
headers: {
Authorization: `Token ${token}`,
},
}
),

unbookmark: (slug, token) =>
axios.delete(`${SERVER_BASE_URL}/articles/${slug}/bookmark`, {
headers: {
Authorization: `Token ${token}`,
},
}),

update: async (article, token) => {
const { data, status } = await axios.put(
`${SERVER_BASE_URL}/articles/${article.slug}`,
Expand Down
2 changes: 1 addition & 1 deletion frontend/pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ class MyDocument extends Document {
}}
/>
<link rel="manifest" href="/manifest.json" />
<link rel="stylesheet" href="//demo.productionready.io/main.css" />
<link rel="stylesheet" href="/main.css" />
<link
rel="stylesheet"
href="//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"
Expand Down
23 changes: 23 additions & 0 deletions frontend/public/main.css

Large diffs are not rendered by default.

62 changes: 62 additions & 0 deletions src/main/java/io/spring/api/ArticleBookmarkApi.java
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package io.spring.api;

import io.spring.api.exception.ResourceNotFoundException;
import io.spring.application.ArticleQueryService;
import io.spring.application.data.ArticleData;
import io.spring.core.article.Article;
import io.spring.core.article.ArticleRepository;
import io.spring.core.bookmark.ArticleBookmark;
import io.spring.core.bookmark.ArticleBookmarkRepository;
import io.spring.core.user.User;
import java.util.HashMap;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path = "articles/{slug}/bookmark")
@AllArgsConstructor
public class ArticleBookmarkApi {
private ArticleBookmarkRepository articleBookmarkRepository;
private ArticleRepository articleRepository;
private ArticleQueryService articleQueryService;

@PostMapping
public ResponseEntity bookmarkArticle(
@PathVariable("slug") String slug, @AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
ArticleBookmark articleBookmark = new ArticleBookmark(article.getId(), user.getId());
articleBookmarkRepository.save(articleBookmark);
return responseArticleData(articleQueryService.findBySlug(slug, user).get());
}

@DeleteMapping
public ResponseEntity unbookmarkArticle(
@PathVariable("slug") String slug, @AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
articleBookmarkRepository
.find(article.getId(), user.getId())
.ifPresent(
bookmark -> {
articleBookmarkRepository.remove(bookmark);
});
return responseArticleData(articleQueryService.findBySlug(slug, user).get());
}

private ResponseEntity<HashMap<String, Object>> responseArticleData(
final ArticleData articleData) {
return ResponseEntity.ok(
new HashMap<String, Object>() {
{
put("article", articleData);
}
});
}
}
17 changes: 17 additions & 0 deletions src/main/java/io/spring/application/ArticleQueryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import io.spring.application.data.ArticleDataList;
import io.spring.application.data.ArticleFavoriteCount;
import io.spring.core.user.User;
import io.spring.infrastructure.mybatis.readservice.ArticleBookmarksReadService;
import io.spring.infrastructure.mybatis.readservice.ArticleFavoritesReadService;
import io.spring.infrastructure.mybatis.readservice.ArticleReadService;
import io.spring.infrastructure.mybatis.readservice.UserRelationshipQueryService;
Expand All @@ -26,6 +27,7 @@ public class ArticleQueryService {
private ArticleReadService articleReadService;
private UserRelationshipQueryService userRelationshipQueryService;
private ArticleFavoritesReadService articleFavoritesReadService;
private ArticleBookmarksReadService articleBookmarksReadService;

public Optional<ArticleData> findById(String id, User user) {
ArticleData articleData = articleReadService.findById(id);
Expand Down Expand Up @@ -126,6 +128,7 @@ private void fillExtraInfo(List<ArticleData> articles, User currentUser) {
setFavoriteCount(articles);
if (currentUser != null) {
setIsFavorite(articles, currentUser);
setIsBookmarked(articles, currentUser);
setIsFollowingAuthor(articles, currentUser);
}
}
Expand Down Expand Up @@ -172,9 +175,23 @@ private void setIsFavorite(List<ArticleData> articles, User currentUser) {
});
}

private void setIsBookmarked(List<ArticleData> articles, User currentUser) {
Set<String> bookmarkedArticles =
articleBookmarksReadService.userBookmarks(
articles.stream().map(ArticleData::getId).collect(toList()), currentUser);

articles.forEach(
articleData -> {
if (bookmarkedArticles.contains(articleData.getId())) {
articleData.setBookmarked(true);
}
});
}

private void fillExtraInfo(String id, User user, ArticleData articleData) {
articleData.setFavorited(articleFavoritesReadService.isUserFavorite(user.getId(), id));
articleData.setFavoritesCount(articleFavoritesReadService.articleFavoriteCount(id));
articleData.setBookmarked(articleBookmarksReadService.isUserBookmark(user.getId(), id));
articleData
.getProfileData()
.setFollowing(
Expand Down
1 change: 1 addition & 0 deletions src/main/java/io/spring/application/data/ArticleData.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public class ArticleData implements io.spring.application.Node {
private String body;
private boolean favorited;
private int favoritesCount;
private boolean bookmarked;
private DateTime createdAt;
private DateTime updatedAt;
private List<String> tagList;
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/io/spring/core/bookmark/ArticleBookmark.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.spring.core.bookmark;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.joda.time.DateTime;

@NoArgsConstructor
@Getter
@EqualsAndHashCode(exclude = "createdAt")
public class ArticleBookmark {
private String articleId;
private String userId;
private DateTime createdAt;

public ArticleBookmark(String articleId, String userId) {
this.articleId = articleId;
this.userId = userId;
this.createdAt = new DateTime();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package io.spring.core.bookmark;

import java.util.Optional;

public interface ArticleBookmarkRepository {
void save(ArticleBookmark articleBookmark);

Optional<ArticleBookmark> find(String articleId, String userId);

void remove(ArticleBookmark bookmark);
}
1 change: 1 addition & 0 deletions src/main/java/io/spring/graphql/ArticleDatafetcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,7 @@ private Article buildArticleResult(ArticleData articleData) {
.description(articleData.getDescription())
.favorited(articleData.isFavorited())
.favoritesCount(articleData.getFavoritesCount())
.bookmarked(articleData.isBookmarked())
.slug(articleData.getSlug())
.tagList(articleData.getTagList())
.title(articleData.getTitle())
Expand Down
54 changes: 54 additions & 0 deletions src/main/java/io/spring/graphql/BookmarkMutation.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package io.spring.graphql;

import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsMutation;
import com.netflix.graphql.dgs.InputArgument;
import graphql.execution.DataFetcherResult;
import io.spring.api.exception.ResourceNotFoundException;
import io.spring.core.article.Article;
import io.spring.core.article.ArticleRepository;
import io.spring.core.bookmark.ArticleBookmark;
import io.spring.core.bookmark.ArticleBookmarkRepository;
import io.spring.core.user.User;
import io.spring.graphql.DgsConstants.MUTATION;
import io.spring.graphql.exception.AuthenticationException;
import io.spring.graphql.types.ArticlePayload;
import lombok.AllArgsConstructor;

@DgsComponent
@AllArgsConstructor
public class BookmarkMutation {

private ArticleBookmarkRepository articleBookmarkRepository;
private ArticleRepository articleRepository;

@DgsMutation(field = MUTATION.BookmarkArticle)
public DataFetcherResult<ArticlePayload> bookmarkArticle(@InputArgument("slug") String slug) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
ArticleBookmark articleBookmark = new ArticleBookmark(article.getId(), user.getId());
articleBookmarkRepository.save(articleBookmark);
return DataFetcherResult.<ArticlePayload>newResult()
.data(ArticlePayload.newBuilder().build())
.localContext(article)
.build();
}

@DgsMutation(field = MUTATION.UnbookmarkArticle)
public DataFetcherResult<ArticlePayload> unbookmarkArticle(@InputArgument("slug") String slug) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
articleBookmarkRepository
.find(article.getId(), user.getId())
.ifPresent(
bookmark -> {
articleBookmarkRepository.remove(bookmark);
});
return DataFetcherResult.<ArticlePayload>newResult()
.data(ArticlePayload.newBuilder().build())
.localContext(article)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package io.spring.infrastructure.mybatis.mapper;

import io.spring.core.bookmark.ArticleBookmark;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface ArticleBookmarkMapper {
ArticleBookmark find(@Param("articleId") String articleId, @Param("userId") String userId);

void insert(@Param("articleBookmark") ArticleBookmark articleBookmark);

void delete(@Param("bookmark") ArticleBookmark bookmark);
}
Loading
Loading