| |
| |
| |
| |
| |
|
|
| import { useState, useRef, useCallback } from 'react'; |
| import type { HistoryItem } from '../types.js'; |
|
|
| |
| type HistoryItemUpdater = ( |
| prevItem: HistoryItem, |
| ) => Partial<Omit<HistoryItem, 'id'>>; |
|
|
| export interface UseHistoryManagerReturn { |
| history: HistoryItem[]; |
| addItem: (itemData: Omit<HistoryItem, 'id'>, baseTimestamp: number) => number; |
| updateItem: ( |
| id: number, |
| updates: Partial<Omit<HistoryItem, 'id'>> | HistoryItemUpdater, |
| ) => void; |
| clearItems: () => void; |
| loadHistory: (newHistory: HistoryItem[]) => void; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| export function useHistory(): UseHistoryManagerReturn { |
| const [history, setHistory] = useState<HistoryItem[]>([]); |
| const messageIdCounterRef = useRef(0); |
|
|
| |
| const getNextMessageId = useCallback((baseTimestamp: number): number => { |
| messageIdCounterRef.current += 1; |
| return baseTimestamp + messageIdCounterRef.current; |
| }, []); |
|
|
| const loadHistory = useCallback((newHistory: HistoryItem[]) => { |
| setHistory(newHistory); |
| }, []); |
|
|
| |
| const addItem = useCallback( |
| (itemData: Omit<HistoryItem, 'id'>, baseTimestamp: number): number => { |
| const id = getNextMessageId(baseTimestamp); |
| const newItem: HistoryItem = { ...itemData, id } as HistoryItem; |
|
|
| setHistory((prevHistory) => { |
| if (prevHistory.length > 0) { |
| const lastItem = prevHistory[prevHistory.length - 1]; |
| |
| if ( |
| lastItem.type === 'user' && |
| newItem.type === 'user' && |
| lastItem.text === newItem.text |
| ) { |
| return prevHistory; |
| } |
| } |
| return [...prevHistory, newItem]; |
| }); |
| return id; |
| }, |
| [getNextMessageId], |
| ); |
|
|
| |
| |
| |
| |
| |
| |
| |
| const updateItem = useCallback( |
| ( |
| id: number, |
| updates: Partial<Omit<HistoryItem, 'id'>> | HistoryItemUpdater, |
| ) => { |
| setHistory((prevHistory) => |
| prevHistory.map((item) => { |
| if (item.id === id) { |
| |
| const newUpdates = |
| typeof updates === 'function' ? updates(item) : updates; |
| return { ...item, ...newUpdates } as HistoryItem; |
| } |
| return item; |
| }), |
| ); |
| }, |
| [], |
| ); |
|
|
| |
| const clearItems = useCallback(() => { |
| setHistory([]); |
| messageIdCounterRef.current = 0; |
| }, []); |
|
|
| return { |
| history, |
| addItem, |
| updateItem, |
| clearItems, |
| loadHistory, |
| }; |
| } |
|
|