()
| 31 | * updating items, and clearing the history. |
| 32 | */ |
| 33 | export function useHistory(): UseHistoryManagerReturn { |
| 34 | const [history, setHistory] = useState<HistoryItem[]>([]); |
| 35 | const messageIdCounterRef = useRef(0); |
| 36 | |
| 37 | // Generates a unique message ID based on a timestamp and a counter. |
| 38 | const getNextMessageId = useCallback((baseTimestamp: number): number => { |
| 39 | messageIdCounterRef.current += 1; |
| 40 | return baseTimestamp + messageIdCounterRef.current; |
| 41 | }, []); |
| 42 | |
| 43 | const loadHistory = useCallback((newHistory: HistoryItem[]) => { |
| 44 | setHistory(newHistory); |
| 45 | }, []); |
| 46 | |
| 47 | // Adds a new item to the history state with a unique ID. |
| 48 | const addItem = useCallback( |
| 49 | (itemData: Omit<HistoryItem, 'id'>, baseTimestamp: number): number => { |
| 50 | const id = getNextMessageId(baseTimestamp); |
| 51 | const newItem: HistoryItem = { ...itemData, id } as HistoryItem; |
| 52 | |
| 53 | setHistory((prevHistory) => { |
| 54 | if (prevHistory.length > 0) { |
| 55 | const lastItem = prevHistory[prevHistory.length - 1]; |
| 56 | // Prevent adding duplicate consecutive user messages |
| 57 | if ( |
| 58 | lastItem.type === 'user' && |
| 59 | newItem.type === 'user' && |
| 60 | lastItem.text === newItem.text |
| 61 | ) { |
| 62 | return prevHistory; // Don't add the duplicate |
| 63 | } |
| 64 | } |
| 65 | return [...prevHistory, newItem]; |
| 66 | }); |
| 67 | return id; // Return the generated ID (even if not added, to keep signature) |
| 68 | }, |
| 69 | [getNextMessageId], |
| 70 | ); |
| 71 | |
| 72 | /** |
| 73 | * Updates an existing history item identified by its ID. |
| 74 | * @deprecated Prefer not to update history item directly as we are currently |
| 75 | * rendering all history items in <Static /> for performance reasons. Only use |
| 76 | * if ABSOLUTELY NECESSARY |
| 77 | */ |
| 78 | // |
| 79 | const updateItem = useCallback( |
| 80 | ( |
| 81 | id: number, |
| 82 | updates: Partial<Omit<HistoryItem, 'id'>> | HistoryItemUpdater, |
| 83 | ) => { |
| 84 | setHistory((prevHistory) => |
| 85 | prevHistory.map((item) => { |
| 86 | if (item.id === id) { |
| 87 | // Apply updates based on whether it's an object or a function |
| 88 | const newUpdates = |
| 89 | typeof updates === 'function' ? updates(item) : updates; |
| 90 | return { ...item, ...newUpdates } as HistoryItem; |
no outgoing calls
no test coverage detected