import clsx from 'clsx'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useSettingsStore } from '@/store/settingsStore'; import { useBookDataStore } from '@/store/bookDataStore'; import { useReaderStore } from '@/store/readerStore'; import { useSidebarStore } from '@/store/sidebarStore'; import { useNotebookStore } from '@/store/notebookStore'; import { useAIChatStore } from '@/store/aiChatStore'; import { useTranslation } from '@/hooks/useTranslation'; import { useThemeStore } from '@/store/themeStore'; import { useEnv } from '@/context/EnvContext'; import { DragKey, useDrag } from '@/hooks/useDrag'; import { TextSelection } from '@/utils/sel'; import { BookNote } from '@/types/book'; import { uniqueId } from '@/utils/misc'; import { eventDispatcher } from '@/utils/event'; import { getBookDirFromLanguage } from '@/utils/book'; import { Overlay } from '@/components/Overlay'; import { saveSysSettings } from '@/helpers/settings'; import { NOTE_PREFIX } from '@/types/view'; import useShortcuts from '@/hooks/useShortcuts'; import BooknoteItem from '../sidebar/BooknoteItem'; import AIAssistant from './AIAssistant'; import NotebookHeader from './Header'; import NoteEditor from './NoteEditor'; import SearchBar from './SearchBar'; import NotebookTabNavigation from './NotebookTabNavigation'; const MIN_NOTEBOOK_WIDTH = 0.15; const MAX_NOTEBOOK_WIDTH = 0.45; const Notebook: React.FC = ({}) => { const _ = useTranslation(); const { updateAppTheme, safeAreaInsets } = useThemeStore(); const { envConfig, appService } = useEnv(); const { settings } = useSettingsStore(); const { sideBarBookKey } = useSidebarStore(); const { notebookWidth, isNotebookVisible, isNotebookPinned, notebookActiveTab } = useNotebookStore(); const { notebookNewAnnotation, notebookEditAnnotation, setNotebookPin } = useNotebookStore(); const { getBookData, getConfig, saveConfig, updateBooknotes } = useBookDataStore(); const { getView, getViewSettings } = useReaderStore(); const { getNotebookWidth, setNotebookWidth, setNotebookVisible, toggleNotebookPin } = useNotebookStore(); const { setNotebookNewAnnotation, setNotebookEditAnnotation, setNotebookActiveTab } = useNotebookStore(); const { activeConversationId } = useAIChatStore(); const [isSearchBarVisible, setIsSearchBarVisible] = useState(false); const [searchResults, setSearchResults] = useState(null); const [searchTerm, setSearchTerm] = useState(''); const onNavigateEvent = async () => { const pinButton = document.querySelector('.sidebar-pin-btn'); const isPinButtonHidden = !pinButton || window.getComputedStyle(pinButton).display === 'none'; if (isPinButtonHidden) { setNotebookVisible(false); } }; const handleHideNotebook = useCallback(() => { if (!isNotebookPinned) { setNotebookVisible(false); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isNotebookPinned]); useShortcuts({ onEscape: handleHideNotebook }, [handleHideNotebook]); useEffect(() => { if (isNotebookVisible) { updateAppTheme('base-200'); } else { updateAppTheme('base-100'); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isNotebookVisible]); useEffect(() => { setNotebookWidth(settings.globalReadSettings.notebookWidth); setNotebookPin(settings.globalReadSettings.isNotebookPinned); setNotebookVisible(settings.globalReadSettings.isNotebookPinned); if (settings.globalReadSettings.notebookActiveTab) { setNotebookActiveTab(settings.globalReadSettings.notebookActiveTab); } eventDispatcher.on('navigate', onNavigateEvent); return () => { eventDispatcher.off('navigate', onNavigateEvent); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const handleNotebookResize = (newWidth: string) => { setNotebookWidth(newWidth); settings.globalReadSettings.notebookWidth = newWidth; }; const handleTogglePin = () => { toggleNotebookPin(); const globalReadSettings = settings.globalReadSettings; const newGlobalReadSettings = { ...globalReadSettings, isNotebookPinned: !isNotebookPinned }; saveSysSettings(envConfig, 'globalReadSettings', newGlobalReadSettings); }; const handleTabChange = (tab: 'notes' | 'ai') => { setNotebookActiveTab(tab); const globalReadSettings = settings.globalReadSettings; const newGlobalReadSettings = { ...globalReadSettings, notebookActiveTab: tab }; saveSysSettings(envConfig, 'globalReadSettings', newGlobalReadSettings); }; const handleClickOverlay = () => { setNotebookVisible(false); setNotebookNewAnnotation(null); setNotebookEditAnnotation(null); }; const handleSaveNote = (selection: TextSelection, note: string) => { if (!sideBarBookKey) return; const view = getView(sideBarBookKey); const config = getConfig(sideBarBookKey)!; const cfi = view?.getCFI(selection.index, selection.range); if (!cfi) return; const { booknotes: annotations = [] } = config; const annotation: BookNote = { id: uniqueId(), type: 'annotation', cfi, note, text: selection.text, createdAt: Date.now(), updatedAt: Date.now(), }; view?.addAnnotation({ ...annotation, value: `${NOTE_PREFIX}${annotation.cfi}` }); annotations.push(annotation); const updatedConfig = updateBooknotes(sideBarBookKey, annotations); if (updatedConfig) { saveConfig(envConfig, sideBarBookKey, updatedConfig, settings); } setNotebookNewAnnotation(null); }; const handleEditNote = (note: BookNote, isDelete: boolean) => { if (!sideBarBookKey) return; const view = getView(sideBarBookKey); const config = getConfig(sideBarBookKey)!; const { booknotes: annotations = [] } = config; const existingIndex = annotations.findIndex((item) => item.id === note.id); if (existingIndex === -1) return; if (isDelete) { note.deletedAt = Date.now(); } else { note.updatedAt = Date.now(); } annotations[existingIndex] = note; view?.addAnnotation({ ...note, value: `${NOTE_PREFIX}${note.cfi}` }, true); const updatedConfig = updateBooknotes(sideBarBookKey, annotations); if (updatedConfig) { saveConfig(envConfig, sideBarBookKey, updatedConfig, settings); } setNotebookEditAnnotation(null); }; const onDragMove = (data: { clientX: number }) => { const widthFraction = 1 - data.clientX / window.innerWidth; const newWidth = Math.max(MIN_NOTEBOOK_WIDTH, Math.min(MAX_NOTEBOOK_WIDTH, widthFraction)); handleNotebookResize(`${Math.round(newWidth * 10000) / 100}%`); }; const onDragKeyDown = (data: { key: DragKey; step: number }) => { const currentWidth = parseFloat(getNotebookWidth()) / 100; let newWidth = currentWidth; if (data.key === 'ArrowLeft') { newWidth = Math.max(MIN_NOTEBOOK_WIDTH, currentWidth + data.step); } else if (data.key === 'ArrowRight') { newWidth = Math.min(MAX_NOTEBOOK_WIDTH, currentWidth - data.step); } handleNotebookResize(`${Math.round(newWidth * 10000) / 100}%`); }; const { handleDragStart, handleDragKeyDown } = useDrag(onDragMove, onDragKeyDown); const config = getConfig(sideBarBookKey); const { booknotes: allNotes = [] } = config || {}; const annotationNotes = allNotes .filter((note) => note.type === 'annotation' && note.note && !note.deletedAt) .sort((a, b) => b.createdAt - a.createdAt); const excerptNotes = allNotes .filter((note) => note.type === 'excerpt' && note.text && !note.deletedAt) .sort((a, b) => a.createdAt - b.createdAt); const handleToggleSearchBar = () => { setIsSearchBarVisible((prev) => !prev); if (isSearchBarVisible) { setSearchResults(null); setSearchTerm(''); } }; const filteredAnnotationNotes = useMemo( () => isSearchBarVisible && searchResults ? searchResults.filter((note) => note.type === 'annotation' && note.note && !note.deletedAt) : annotationNotes, [annotationNotes, searchResults, isSearchBarVisible], ); const filteredExcerptNotes = useMemo( () => isSearchBarVisible && searchResults ? searchResults.filter((note) => note.type === 'excerpt' && note.text && !note.deletedAt) : excerptNotes, [excerptNotes, searchResults, isSearchBarVisible], ); if (!sideBarBookKey) return null; const bookData = getBookData(sideBarBookKey); const viewSettings = getViewSettings(sideBarBookKey); if (!bookData || !bookData.bookDoc) { return null; } const { bookDoc } = bookData; const languageDir = getBookDirFromLanguage(bookDoc.metadata.language); const hasSearchResults = filteredAnnotationNotes.length > 0 || filteredExcerptNotes.length > 0; const hasAnyNotes = annotationNotes.length > 0 || excerptNotes.length > 0; return isNotebookVisible ? ( <> {!isNotebookPinned && ( )}
setNotebookVisible(false)} handleTogglePin={handleTogglePin} handleToggleSearchBar={handleToggleSearchBar} showSearchButton={notebookActiveTab === 'notes'} /> {notebookActiveTab === 'notes' && (
)}
{notebookActiveTab === 'ai' ? (
) : (
{isSearchBarVisible && searchResults && !hasSearchResults && hasAnyNotes && (

{_('No notes match your search')}

)}
{filteredExcerptNotes.length > 0 && (

{_('Excerpts')} {isSearchBarVisible && searchResults && ( ({filteredExcerptNotes.length}) )}

)}
    {filteredExcerptNotes.map((item, index) => (
  • { if (e.key === 'Backspace' || e.key === 'Delete') { handleEditNote(item, true); } }} className='booknote-item collapse-arrow border-base-300 bg-base-100 collapse border' >

    {item.text || `Excerpt ${index + 1}`}

    {item.text}

    {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions*/}
    {_('Delete')}
  • ))}
{(notebookNewAnnotation || filteredAnnotationNotes.length > 0) && (

{_('Notes')} {isSearchBarVisible && searchResults && filteredAnnotationNotes.length > 0 && ( ({filteredAnnotationNotes.length}) )}

)}
{(notebookNewAnnotation || notebookEditAnnotation) && !isSearchBarVisible && ( handleEditNote(item, false)} /> )}
    {filteredAnnotationNotes.map((item, index) => ( ))}
)}
) : null; }; export default Notebook;