Open platform to collect and prioritize feedback
Working reactions UI and backend
Matt Robertse1a6ebdef6d4
diff --git a/app/actions/post.go b/app/actions/post.goindex fa7ba65a7..1ee204788 100644--- a/app/actions/post.go+++ b/app/actions/post.go@@ -133,6 +133,23 @@ func (action *UpdatePost) Validate(ctx context.Context, user *entity.User) *valireturn result}+type ToggleCommentReaction struct {+ Number int `route:"number"`+ Comment int `route:"id"`+ Reaction string `route:"reaction"`+}++// IsAuthorized returns true if current user is authorized to perform this action+func (action *ToggleCommentReaction) IsAuthorized(ctx context.Context, user *entity.User) bool {+ return user != nil+}++// Validate if current model is valid+func (action *ToggleCommentReaction) Validate(ctx context.Context, user *entity.User) *validate.Result {+ result := validate.Success()+ return result+}+// AddNewComment represents a new comment to be addedtype AddNewComment struct {Number int `route:"number"`diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 87da777f7..7744caa62 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -196,6 +196,7 @@ func routes(r *web.Engine) *web.Engine {membersApi.Post("/api/v1/posts", apiv1.CreatePost())membersApi.Put("/api/v1/posts/:number", apiv1.UpdatePost())+ membersApi.Post("/api/v1/posts/:number/comments/:id/reactions/:reaction", apiv1.ToggleReaction())membersApi.Post("/api/v1/posts/:number/comments", apiv1.PostComment())membersApi.Put("/api/v1/posts/:number/comments/:id", apiv1.UpdateComment())membersApi.Delete("/api/v1/posts/:number/comments/:id", apiv1.DeleteComment())diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.goindex bf33153ef..3718315ff 100644--- a/app/handlers/apiv1/post.go+++ b/app/handlers/apiv1/post.go@@ -218,6 +218,34 @@ func GetComment() web.HandlerFunc {}}+// ToggleReaction adds or removes a reaction on a comment+func ToggleReaction() web.HandlerFunc {+ return func(c *web.Context) error {+ action := new(actions.ToggleCommentReaction)+ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ getComment := &query.GetCommentByID{CommentID: action.Comment}+ if err := bus.Dispatch(c, getComment); err != nil {+ return c.Failure(err)+ }++ toggleReaction := &cmd.ToggleCommentReaction{+ Comment: getComment.Result,+ Emoji: action.Reaction,+ User: c.User(),+ }+ if err := bus.Dispatch(c, toggleReaction); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{+ "added": toggleReaction.Result,+ })+ }+}+// PostComment creates a new comment on given postfunc PostComment() web.HandlerFunc {return func(c *web.Context) error {diff --git a/app/handlers/apiv1/post_test.go b/app/handlers/apiv1/post_test.goindex 72e9c9572..9790e537b 100644--- a/app/handlers/apiv1/post_test.go+++ b/app/handlers/apiv1/post_test.go@@ -124,11 +124,11 @@ func TestUpdatePostHandler_NonAuthorized(t *testing.T) {RegisterT(t)post := &entity.Post{- ID: 5,- Number: 5,- Title: "My First Post",+ ID: 5,+ Number: 5,+ Title: "My First Post",Description: "Such an amazing description",- User: mock.JonSnow,+ User: mock.JonSnow,}bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {if q.Number == post.Number {@@ -151,12 +151,12 @@ func TestUpdatePostHandler_IsOwner_AfterGracePeriod(t *testing.T) {RegisterT(t)post := &entity.Post{- ID: 5,- Number: 5,- Title: "My First Post",+ ID: 5,+ Number: 5,+ Title: "My First Post",Description: "Such an amazing description",- User: mock.AryaStark,- CreatedAt: time.Now().UTC().Add(-2 * time.Hour),+ User: mock.AryaStark,+ CreatedAt: time.Now().UTC().Add(-2 * time.Hour),}bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {if q.Number == post.Number {@@ -175,17 +175,16 @@ func TestUpdatePostHandler_IsOwner_AfterGracePeriod(t *testing.T) {Expect(code).Equals(http.StatusForbidden)}-func TestUpdatePostHandler_IsOwner_WithinGracePeriod(t *testing.T) {RegisterT(t)post := &entity.Post{- ID: 5,- Number: 5,- Title: "My First Post",+ ID: 5,+ Number: 5,+ Title: "My First Post",Description: "Such an amazing description",- User: mock.AryaStark,- CreatedAt: time.Now().UTC(),+ User: mock.AryaStark,+ CreatedAt: time.Now().UTC(),}bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {if q.Number == post.Number {@@ -654,3 +653,69 @@ func TestListCommentHandler(t *testing.T) {Expect(query.IsArray()).IsTrue()Expect(query.ArrayLength()).Equals(2)}++func TestCommentReactionToggleHandler(t *testing.T) {+ RegisterT(t)++ comment := &entity.Comment{ID: 5, Content: "Old comment text", User: mock.AryaStark}++ bus.AddHandler(func(ctx context.Context, q *query.GetCommentByID) error {+ q.Result = comment+ return nil+ })++ testCases := []struct {+ name string+ user *entity.User+ reaction string+ }{+ {"JonSnow reacts with like", mock.JonSnow, "like"},+ {"AryaStark reacts with smile", mock.AryaStark, "smile"},+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ var toggleReaction *cmd.ToggleCommentReaction+ bus.AddHandler(func(ctx context.Context, c *cmd.ToggleCommentReaction) error {+ toggleReaction = c+ return nil+ })++ code, _ := mock.NewServer().+ OnTenant(mock.DemoTenant).+ AsUser(tc.user).+ AddParam("number", 1).+ AddParam("id", comment.ID).+ AddParam("reaction", tc.reaction).+ ExecutePost(apiv1.ToggleReaction(), ``)++ Expect(code).Equals(http.StatusOK)+ Expect(toggleReaction.Emoji).Equals(tc.reaction)+ Expect(toggleReaction.Comment).Equals(comment)+ Expect(toggleReaction.User).Equals(tc.user)+ })+ }+}++func TestCommentReactionToggleHandler_UnAuthorised(t *testing.T) {+ RegisterT(t)++ comment := &entity.Comment{ID: 5, Content: "Old comment text", User: mock.AryaStark}+ bus.AddHandler(func(ctx context.Context, q *query.GetCommentByID) error {+ q.Result = comment+ return nil+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.ToggleCommentReaction) error {+ return nil+ })++ code, _ := mock.NewServer().+ OnTenant(mock.DemoTenant).+ AddParam("number", 1).+ AddParam("id", comment.ID).+ AddParam("reaction", "like").+ ExecutePost(apiv1.ToggleReaction(), ``)++ Expect(code).Equals(http.StatusForbidden)+}diff --git a/app/models/cmd/reaction.go b/app/models/cmd/reaction.gonew file mode 100644index 000000000..36782deb9--- /dev/null+++ b/app/models/cmd/reaction.go@@ -0,0 +1,10 @@+package cmd++import "github.com/getfider/fider/app/models/entity"++type ToggleCommentReaction struct {+ Comment *entity.Comment+ Emoji string+ User *entity.User+ Result bool+}diff --git a/app/models/entity/comment.go b/app/models/entity/comment.goindex 12912b488..b0ef76b98 100644--- a/app/models/entity/comment.go+++ b/app/models/entity/comment.go@@ -3,19 +3,19 @@ package entityimport "time"type ReactionCounts struct {- Emoji string `json:"emoji"`- Count int `json:"count"`+ Emoji string `json:"emoji"`+ Count int `json:"count"`+ IncludesMe bool `json:"includesMe"`}// Comment represents an user comment on an posttype Comment struct {- ID int `json:"id"`- Content string `json:"content"`- CreatedAt time.Time `json:"createdAt"`- User *User `json:"user"`- Attachments []string `json:"attachments,omitempty"`- EditedAt *time.Time `json:"editedAt,omitempty"`- EditedBy *User `json:"editedBy,omitempty"`- ReactionCounts map[string]int `json:"reactionCounts,omitempty"`- Reactions string `json:"reactions,omitempty"`+ ID int `json:"id"`+ Content string `json:"content"`+ CreatedAt time.Time `json:"createdAt"`+ User *User `json:"user"`+ Attachments []string `json:"attachments,omitempty"`+ EditedAt *time.Time `json:"editedAt,omitempty"`+ EditedBy *User `json:"editedBy,omitempty"`+ ReactionCounts []ReactionCounts `json:"reactionCounts,omitempty"`}diff --git a/app/services/sqlstore/postgres/comment.go b/app/services/sqlstore/postgres/comment.goindex 84163a521..3bbbf6f98 100644--- a/app/services/sqlstore/postgres/comment.go+++ b/app/services/sqlstore/postgres/comment.go@@ -12,11 +12,6 @@ import ("github.com/getfider/fider/app/pkg/errors")-type ReactionCounts struct {- Emoji string `db:"emoji"`- Count int `db:"count"`-}-type dbComment struct {ID int `db:"id"`Content string `db:"content"`@@ -26,7 +21,6 @@ type dbComment struct {EditedAt dbx.NullTime `db:"edited_at"`EditedBy *dbUser `db:"edited_by"`ReactionCounts dbx.NullString `db:"reaction_counts"`- // Reactions dbx.NullString `db:"reactions"`}func (c *dbComment) toModel(ctx context.Context) *entity.Comment {@@ -36,22 +30,15 @@ func (c *dbComment) toModel(ctx context.Context) *entity.Comment {CreatedAt: c.CreatedAt,User: c.User.toModel(ctx),Attachments: c.Attachments,- // Reactions: c.Reactions.String,}if c.EditedAt.Valid {comment.EditedBy = c.EditedBy.toModel(ctx)comment.EditedAt = &c.EditedAt.Time}- comment.ReactionCounts = make(map[string]int)if c.ReactionCounts.Valid {- var reactionCounts map[string]int- err := json.Unmarshal([]byte(c.ReactionCounts.String), &reactionCounts)- if err == nil {- comment.ReactionCounts = reactionCounts- }+ json.Unmarshal([]byte(c.ReactionCounts.String), &comment.ReactionCounts)}-return comment}@@ -76,6 +63,38 @@ func addNewComment(ctx context.Context, c *cmd.AddNewComment) error {})}+func toggleCommentReaction(ctx context.Context, c *cmd.ToggleCommentReaction) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ var added bool+ err := trx.Scalar(&added, `+ WITH toggle_reaction AS (+ INSERT INTO reactions (comment_id, user_id, emoji, created_on)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (comment_id, user_id, emoji) DO NOTHING+ RETURNING true AS added+ ),+ delete_existing AS (+ DELETE FROM reactions+ WHERE comment_id = $1 AND user_id = $2 AND emoji = $3+ AND NOT EXISTS (SELECT 1 FROM toggle_reaction)+ RETURNING false AS added+ )+ SELECT COALESCE(+ (SELECT added FROM toggle_reaction),+ (SELECT added FROM delete_existing),+ false+ )+ `, c.Comment.ID, user.ID, c.Emoji, time.Now())++ if err != nil {+ return errors.Wrap(err, "failed to toggle reaction")+ }++ c.Result = added+ return nil+ })+}+func updateComment(ctx context.Context, c *cmd.UpdateComment) error {return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {_, err := trx.Execute(`@@ -168,9 +187,17 @@ func getCommentsByPost(ctx context.Context, q *query.GetCommentsByPost) error {agg_reactions AS (SELECTcomment_id,- json_object_agg(emoji, count) as reaction_counts+ json_agg(json_build_object(+ 'emoji', emoji,+ 'count', count,+ 'includesMe', CASE WHEN $3 = ANY(user_ids) THEN true ELSE false END+ )) as reaction_countsFROM (- SELECT comment_id, emoji, COUNT(*) as count+ SELECT+ comment_id,+ emoji,+ COUNT(*) as count,+ array_agg(user_id) as user_idsFROM reactionsWHERE comment_id IN (SELECT id FROM comments WHERE post_id = $1)GROUP BY comment_id, emoji@@ -214,7 +241,7 @@ func getCommentsByPost(ctx context.Context, q *query.GetCommentsByPost) error {WHERE p.id = $1AND p.tenant_id = $2AND c.deleted_at IS NULL- ORDER BY c.created_at ASC`, q.Post.ID, tenant.ID)+ ORDER BY c.created_at ASC`, q.Post.ID, tenant.ID, user.ID)if err != nil {return errors.Wrap(err, "failed get comments of post with id '%d'", q.Post.ID)}diff --git a/app/services/sqlstore/postgres/common_test.go b/app/services/sqlstore/postgres/common_test.goindex 15ffee531..078658b3e 100644--- a/app/services/sqlstore/postgres/common_test.go+++ b/app/services/sqlstore/postgres/common_test.go@@ -6,8 +6,11 @@ import ("github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models/cmd""github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/query". "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/services/sqlstore/postgres")@@ -45,3 +48,49 @@ func withUser(ctx context.Context, user *entity.User) context.Context {ctx = context.WithValue(ctx, app.UserCtxKey, user)return ctx}++func TestToggleReaction_Add(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ newPost := &cmd.AddNewPost{Title: "My new post", Description: "with this description"}+ err := bus.Dispatch(jonSnowCtx, newPost)+ Expect(err).IsNil()++ newComment := &cmd.AddNewComment{Post: newPost.Result, Content: "This is my comment"}+ err = bus.Dispatch(jonSnowCtx, newComment)+ Expect(err).IsNil()++ // Now add a reaction+ reaction := &cmd.ToggleCommentReaction{Comment: newComment.Result, Emoji: "π", User: jonSnow}+ err = bus.Dispatch(jonSnowCtx, reaction)+ Expect(err).IsNil()+ Expect(reaction.Result).IsTrue()++ // Get the comment, and check that the reaction was added+ commentByID := &query.GetCommentsByPost{Post: &entity.Post{ID: newPost.Result.ID}}+ err = bus.Dispatch(jonSnowCtx, commentByID)+ Expect(err).IsNil()++ Expect(commentByID.Result).IsNotNil()+ Expect(commentByID.Result[0].ReactionCounts).IsNotNil()+ Expect(len(commentByID.Result[0].ReactionCounts)).Equals(1)+ Expect(commentByID.Result[0].ReactionCounts[0].Emoji).Equals("π")+ Expect(commentByID.Result[0].ReactionCounts[0].Count).Equals(1)+ Expect(commentByID.Result[0].ReactionCounts[0].IncludesMe).IsTrue()++ // Now remove the reaction+ reaction = &cmd.ToggleCommentReaction{Comment: newComment.Result, Emoji: "π", User: jonSnow}+ err = bus.Dispatch(jonSnowCtx, reaction)+ Expect(err).IsNil()+ Expect(reaction.Result).IsFalse()++ // Get the comment, and check that the reaction was removed+ commentByID = &query.GetCommentsByPost{Post: &entity.Post{ID: newPost.Result.ID}}+ err = bus.Dispatch(jonSnowCtx, commentByID)+ Expect(err).IsNil()++ Expect(commentByID.Result).IsNotNil()+ Expect(commentByID.Result[0].ReactionCounts).IsNil()++}diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex 0f64e4709..8d0f3103a 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -76,6 +76,7 @@ func (s Service) Init() {bus.AddHandler(addNewComment)bus.AddHandler(updateComment)+ bus.AddHandler(toggleCommentReaction)bus.AddHandler(deleteComment)bus.AddHandler(getCommentByID)bus.AddHandler(getCommentsByPost)diff --git a/migrations/202410122105_create_reactions_up.sql b/migrations/202410122105_create_reactions_up.sqlindex 7f3307f55..ca8fb6e72 100644--- a/migrations/202410122105_create_reactions_up.sql+++ b/migrations/202410122105_create_reactions_up.sql@@ -7,3 +7,5 @@ create table if not exists reactions (foreign key (comment_id) references comments(id),foreign key (user_id) references users(id));++ALTER TABLE reactions ADD CONSTRAINT unique_reaction UNIQUE (comment_id, user_id, emoji);diff --git a/public/assets/images/reaction-add.svg b/public/assets/images/reaction-add.svgnew file mode 100644index 000000000..5761c7e7f--- /dev/null+++ b/public/assets/images/reaction-add.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">+ <path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 1 1-18 0 9 9 0 0 1 9-9" />+ <path stroke-linecap="round" stroke-linejoin="round" d="M9.75 9.75c0 .414-.168.75-.375.75S9 10.164 9 9.75 9.168 9 9.375 9s.375.336.375.75Zm-.375 0h.008v.015h-.008V9.75Zm5.625 0c0 .414-.168.75-.375.75s-.375-.336-.375-.75.168-.75.375-.75.375.336.375.75Zm-.375 0h.008v.015h-.008V9.75Z" />+ <path stroke-linecap="round" stroke-linejoin="round" d="M15.182 15.182a4.5 4.5 0 0 1-6.364 0" />+ <path stroke-linecap="round" stroke-linejoin="round" d="M19 2 L19 7 M16.5 4.5 L21.5 4.5" />+</svg>diff --git a/public/assets/styles/utility/display.scss b/public/assets/styles/utility/display.scssindex 814c5db7e..2bb8b2a2d 100644--- a/public/assets/styles/utility/display.scss+++ b/public/assets/styles/utility/display.scss@@ -10,6 +10,10 @@position: relative;}+.absolute {+ position: absolute;+}+.inline-block {display: inline-block;}diff --git a/public/components/Reactions.scss b/public/components/Reactions.scssnew file mode 100644index 000000000..056f154b1--- /dev/null+++ b/public/components/Reactions.scss@@ -0,0 +1,20 @@+@import "~@fider/assets/styles/variables.scss";++.c-reactions {++ &-add-reaction {+ svg {+ position: relative;+ top:1px;+ left:0;+ }+ }++ &-emojis {+ top: -30px;+ }++ button {+ background-color: 'pink';+ }+}\ No newline at end of filediff --git a/public/components/Reactions.tsx b/public/components/Reactions.tsxnew file mode 100644index 000000000..a06a0233e--- /dev/null+++ b/public/components/Reactions.tsx@@ -0,0 +1,81 @@+import React, { useEffect, useState } from "react"+import { ReactionCount } from "@fider/models"+import { Icon } from "@fider/components"+import ReactionAdd from "@fider/assets/images/reaction-add.svg"+import { HStack } from "@fider/components/layout"+import { useFider } from "@fider/hooks"+import "./Reactions.scss"++interface ReactionsProps {+ emojiSelectorRef: React.RefObject<HTMLDivElement>+ toggleReaction: (emoji: string) => void+ reactions?: ReactionCount[]+}++const availableEmojis = ["π", "π", "π", "π", "π", "β€οΈ", "π", "π"]++export const Reactions: React.FC<ReactionsProps> = ({ emojiSelectorRef, toggleReaction, reactions }) => {+ const fider = useFider()+ const [isEmojiSelectorOpen, setIsEmojiSelectorOpen] = useState(false)++ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (emojiSelectorRef.current && !emojiSelectorRef.current.contains(event.target as Node)) {+ setIsEmojiSelectorOpen(false)+ }+ }++ document.addEventListener("click", handleClickOutside)+ return () => {+ document.removeEventListener("click", handleClickOutside)+ }+ }, [])++ return (+ <div ref={emojiSelectorRef}>+ <HStack spacing={2} center={true} className="mt-2 c-reactions relative">+ {fider.session.isAuthenticated && (+ <>+ <span+ onClick={() => setIsEmojiSelectorOpen(!isEmojiSelectorOpen)}+ className="c-reactions-add-reaction relative text-gray-600 clickable inline-flex items-center px-1 py-1 rounded-full text-xs bg-blue-100 hover:bg-blue-200"+ >+ <Icon width="18" height="18" sprite={ReactionAdd} className="" />+ </span>+ {isEmojiSelectorOpen && (+ <div className="c-reactions-emojis p-2 absolute bg-white border rounded shadow-lg">+ {availableEmojis.map((emoji) => (+ <a+ key={emoji}+ className="clickable p-2 hover:bg-gray-100"+ onClick={() => {+ toggleReaction(emoji)+ setIsEmojiSelectorOpen(false)+ }}+ >+ {emoji}+ </a>+ ))}+ </div>+ )}+ </>+ )}+ {reactions !== undefined && (+ <>+ {reactions.map((reaction) => (+ <span+ key={reaction.emoji}+ onClick={() => toggleReaction(reaction.emoji)}+ className={`clickable inline-flex items-center px-2 py-1 rounded-full text-xs ${+ reaction.includesMe ? "bg-blue-100 hover:bg-blue-200" : "bg-gray-100 hover:bg-gray-200"+ }`}+ >+ {reaction.emoji} <span className="ml-1 font-semibold">{reaction.count}</span>+ </span>+ ))}+ </>+ )}+ </HStack>+ </div>+ )+}diff --git a/public/components/index.tsx b/public/components/index.tsxindex c4fc4afce..0e5109b29 100644--- a/public/components/index.tsx+++ b/public/components/index.tsx@@ -7,5 +7,6 @@ export * from "./SignInModal"export * from "./VoteCounter"export * from "./NotificationIndicator"export * from "./UserMenu"+export * from "./Reactions"export * from "./ReadOnlyNotice"export * from "./common"diff --git a/public/models/post.ts b/public/models/post.tsindex efc454580..0f12c52af 100644--- a/public/models/post.ts+++ b/public/models/post.ts@@ -51,15 +51,19 @@ export interface PostResponse {}}+export interface ReactionCount {+ emoji: string+ count: number+ includesMe: boolean+}+export interface Comment {id: numbercontent: stringcreatedAt: stringuser: Userattachments?: string[]- reactionCounts: {- [key: string]: number- }+ reactionCounts?: ReactionCount[]editedAt?: stringeditedBy?: User}diff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsxindex 94349bb0d..2ef8b8ad9 100644--- a/public/pages/ShowPost/components/ShowComment.tsx+++ b/public/pages/ShowPost/components/ShowComment.tsx@@ -1,6 +1,20 @@import React, { useEffect, useRef, useState } from "react"import { Comment, Post, ImageUpload } from "@fider/models"-import { Avatar, UserName, Moment, Form, TextArea, Button, Markdown, Modal, ImageViewer, MultiImageUploader, Dropdown, Icon } from "@fider/components"+import {+ Reactions,+ Avatar,+ UserName,+ Moment,+ Form,+ TextArea,+ Button,+ Markdown,+ Modal,+ ImageViewer,+ MultiImageUploader,+ Dropdown,+ Icon,+} from "@fider/components"import { HStack } from "@fider/components/layout"import { formatDate, Failure, actions, notify, copyToClipboard, classSet, clearUrlHash } from "@fider/services"import { useFider } from "@fider/hooks"@@ -11,6 +25,7 @@ interface ShowCommentProps {post: Postcomment: Commenthighlighted?: boolean+ onToggleReaction?: () => void}export const ShowComment = (props: ShowCommentProps) => {@@ -20,6 +35,9 @@ export const ShowComment = (props: ShowCommentProps) => {const [newContent, setNewContent] = useState("")const [isDeleteConfirmationModalOpen, setIsDeleteConfirmationModalOpen] = useState(false)const [attachments, setAttachments] = useState<ImageUpload[]>([])+ const [localReactionCounts, setLocalReactionCounts] = useState(props.comment.reactionCounts)+ const emojiSelectorRef = useRef<HTMLDivElement>(null)+const [error, setError] = useState<Failure>()const handleClick = (e: MouseEvent) => {@@ -72,6 +90,33 @@ export const ShowComment = (props: ShowCommentProps) => {}}+ const toggleReaction = async (emoji: string) => {+ const response = await actions.toggleCommentReaction(props.post.number, comment.id, emoji)+ if (response.ok) {+ const added = response.data.added++ setLocalReactionCounts((prevCounts) => {+ const newCounts = [...(prevCounts ?? [])]+ const reactionIndex = newCounts.findIndex((r) => r.emoji === emoji)+ if (reactionIndex !== -1) {+ const newCount = added ? newCounts[reactionIndex].count + 1 : newCounts[reactionIndex].count - 1+ if (newCount === 0) {+ newCounts.splice(reactionIndex, 1)+ } else {+ newCounts[reactionIndex] = {+ ...newCounts[reactionIndex],+ count: newCount,+ includesMe: added,+ }+ }+ } else if (added) {+ newCounts.push({ emoji, count: 1, includesMe: true })+ }+ return newCounts+ })+ }+ }+const onActionSelected = (action: string) => () => {if (action === "copylink") {window.location.hash = `#comment-${props.comment.id}`@@ -178,15 +223,7 @@ export const ShowComment = (props: ShowCommentProps) => {<><Markdown text={comment.content} style="full" />{comment.attachments && comment.attachments.map((x) => <ImageViewer key={x} bkey={x} />)}- {comment.reactionCounts !== undefined && (- <div className="mt-2 flex space-x-2">- {Object.entries(comment.reactionCounts).map(([emoji, count]) => (- <span key={emoji} className="inline-flex items-center px-2 py-1 rounded-full text-xs bg-gray-100 mr-2">- {emoji} <span className="ml-1 font-semibold">{count}</span>- </span>- ))}- </div>- )}+ <Reactions reactions={localReactionCounts} emojiSelectorRef={emojiSelectorRef} toggleReaction={toggleReaction} /></>)}</div>diff --git a/public/services/actions/post.ts b/public/services/actions/post.tsindex 0c4d3bdf4..39b382565 100644--- a/public/services/actions/post.ts+++ b/public/services/actions/post.ts@@ -62,6 +62,13 @@ export const updateComment = async (postNumber: number, commentID: number, conteexport const deleteComment = async (postNumber: number, commentID: number): Promise<Result> => {return http.delete(`/api/v1/posts/${postNumber}/comments/${commentID}`).then(http.event("comment", "delete"))}+interface ToggleReactionResponse {+ added: boolean+}++export const toggleCommentReaction = async (postNumber: number, commentID: number, emoji: string): Promise<Result<ToggleReactionResponse>> => {+ return http.post<ToggleReactionResponse>(`/api/v1/posts/${postNumber}/comments/${commentID}/reactions/${emoji}`)+}interface SetResponseInput {status: string