browser / src /hooks /useBrowserState.ts
no-name-here's picture
Upload 86 files
9b63060 verified
import { useState, useCallback } from 'react';
export const useBrowserState = () => {
const [historyStack, setHistoryStack] = useState<string[]>([]);
const [currentIndex, setCurrentIndex] = useState(-1);
const [bookmarks, setBookmarks] = useState<string[]>([]);
const [summary, setSummary] = useState('');
const [isSummaryVisible, setIsSummaryVisible] = useState(false);
const loadUrl = useCallback(async (url: string, pushToHistory = true) => {
try {
console.log('Loading URL:', url);
if (pushToHistory) {
setHistoryStack(prev => {
const newStack = prev.slice(0, currentIndex + 1);
newStack.push(url);
return newStack;
});
setCurrentIndex(prev => prev + 1);
}
return url;
} catch (error) {
console.error('Error loading URL:', error);
throw error;
}
}, [currentIndex]);
const goBack = useCallback(() => {
if (currentIndex > 0) {
const newIndex = currentIndex - 1;
setCurrentIndex(newIndex);
return historyStack[newIndex];
}
return null;
}, [currentIndex, historyStack]);
const goForward = useCallback(() => {
if (currentIndex < historyStack.length - 1) {
const newIndex = currentIndex + 1;
setCurrentIndex(newIndex);
return historyStack[newIndex];
}
return null;
}, [currentIndex, historyStack]);
const addBookmark = useCallback(() => {
if (currentIndex >= 0) {
const currentUrl = historyStack[currentIndex];
if (currentUrl && !bookmarks.includes(currentUrl)) {
setBookmarks(prev => [...prev, currentUrl]);
console.log('Bookmark added:', currentUrl);
}
}
}, [currentIndex, historyStack, bookmarks]);
const setSummaryAndShow = useCallback((summaryText: string) => {
setSummary(summaryText);
setIsSummaryVisible(true);
}, []);
const hideSummary = useCallback(() => {
setIsSummaryVisible(false);
}, []);
return {
historyStack,
currentIndex,
bookmarks,
summary,
isSummaryVisible,
canGoBack: currentIndex > 0,
canGoForward: currentIndex < historyStack.length - 1,
loadUrl,
goBack,
goForward,
addBookmark,
setSummaryAndShow,
hideSummary
};
};