1- import { filter , get , indexOf , last , map , max , min , values } from 'lodash-es' ;
1+ import { get , indexOf , last , max , min , values } from 'lodash-es' ;
22import { useCallback } from 'react' ;
33import {
44 History as ChatHistory ,
@@ -40,12 +40,7 @@ export function useManageMessageSiblings(chatId: string, history?: ChatHistory):
4040 if ( ! history ?. messages ) return ;
4141
4242 const isPrev = direction === 'prev' ;
43- const siblings : Array < string > = message . parentId
44- ? get ( history . messages [ message . parentId ] , 'childrenIds' , [ ] )
45- : map (
46- filter ( values ( history . messages ) , ( msg ) => msg . parentId === null ) ,
47- 'id' ,
48- ) ;
43+ const siblings = getOrderedSiblingIds ( message . parentId ?? null ) ;
4944
5045 const currentIndex = indexOf ( siblings , message . id ) ;
5146 const targetIndex = isPrev ? max ( [ currentIndex - 1 , 0 ] ) : min ( [ currentIndex + 1 , siblings . length - 1 ] ) ;
@@ -64,12 +59,7 @@ export function useManageMessageSiblings(chatId: string, history?: ChatHistory):
6459 ( message : Message ) => {
6560 if ( ! history ?. messages ) return { siblings : [ ] , currentIndex : - 1 , hasSiblings : false } ;
6661
67- const siblings = message . parentId
68- ? get ( history . messages [ message . parentId ] , 'childrenIds' , [ ] )
69- : map (
70- filter ( values ( history . messages ) , ( msg ) => msg . parentId === null ) ,
71- 'id' ,
72- ) ;
62+ const siblings = getOrderedSiblingIds ( message . parentId ?? null ) ;
7363
7464 const currentIndex = indexOf ( siblings , message . id ) ;
7565
@@ -82,6 +72,20 @@ export function useManageMessageSiblings(chatId: string, history?: ChatHistory):
8272 [ history ] ,
8373 ) ;
8474
75+ const getOrderedSiblingIds = useCallback (
76+ ( parentId : string | null ) : Array < string > => {
77+ if ( ! history ?. messages ) return [ ] ;
78+
79+ return values ( history . messages )
80+ . filter ( ( msg ) => msg . parentId === parentId )
81+ . sort (
82+ ( a , b ) => ( a . timestamp !== b . timestamp ? a . timestamp - b . timestamp : a . id . localeCompare ( b . id ) ) , // safety fallback
83+ )
84+ . map ( ( msg ) => msg . id ) ;
85+ } ,
86+ [ history ] ,
87+ ) ;
88+
8589 return {
8690 showPreviousSibling : ( msg ) => navigateSibling ( msg , 'prev' ) ,
8791 showNextSibling : ( msg ) => navigateSibling ( msg , 'next' ) ,
0 commit comments