|
| 1 | +import { differenceInMilliseconds } from 'date-fns'; |
| 2 | + |
1 | 3 | import { logError } from '../../shared/logger'; |
2 | 4 | import type { Link } from '../types'; |
3 | 5 | import type { |
@@ -162,7 +164,8 @@ async function getGitifySubjectForDiscussion( |
162 | 164 | } |
163 | 165 | } |
164 | 166 |
|
165 | | - const latestDiscussionComment = getLatestDiscussionComment( |
| 167 | + const latestDiscussionComment = getClosestDiscussionCommentOrReply( |
| 168 | + notification, |
166 | 169 | discussion.comments.nodes, |
167 | 170 | ); |
168 | 171 |
|
@@ -190,20 +193,33 @@ async function getGitifySubjectForDiscussion( |
190 | 193 | }; |
191 | 194 | } |
192 | 195 |
|
193 | | -export function getLatestDiscussionComment( |
| 196 | +export function getClosestDiscussionCommentOrReply( |
| 197 | + notification: Notification, |
194 | 198 | comments: DiscussionComment[], |
195 | 199 | ): DiscussionComment | null { |
196 | 200 | if (!comments || comments.length === 0) { |
197 | 201 | return null; |
198 | 202 | } |
199 | 203 |
|
200 | | - // Return latest reply if available |
201 | | - if (comments[0].replies.nodes.length === 1) { |
202 | | - return comments[0].replies.nodes[0]; |
203 | | - } |
| 204 | + const targetTimestamp = notification.updated_at; |
| 205 | + |
| 206 | + const allCommentsAndReplies = comments.flatMap((comment) => [ |
| 207 | + comment, |
| 208 | + ...comment.replies.nodes, |
| 209 | + ]); |
| 210 | + |
| 211 | + // Find the closest match using the target timestamp |
| 212 | + const closestComment = allCommentsAndReplies.reduce((prev, curr) => { |
| 213 | + const prevDiff = Math.abs( |
| 214 | + differenceInMilliseconds(prev.createdAt, targetTimestamp), |
| 215 | + ); |
| 216 | + const currDiff = Math.abs( |
| 217 | + differenceInMilliseconds(curr.createdAt, targetTimestamp), |
| 218 | + ); |
| 219 | + return currDiff < prevDiff ? curr : prev; |
| 220 | + }); |
204 | 221 |
|
205 | | - // Return latest comment if no replies |
206 | | - return comments[0]; |
| 222 | + return closestComment; |
207 | 223 | } |
208 | 224 |
|
209 | 225 | async function getGitifySubjectForIssue( |
|
0 commit comments