File size: 8,987 Bytes
4e1096a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
'use client';

import clsx from 'clsx';
import dayjs from 'dayjs';
import React, { useEffect, useState, useCallback } from 'react';
import { LuMessageSquare, LuTrash2, LuPencil, LuCheck, LuX, LuPlus } from 'react-icons/lu';

import { useTranslation } from '@/hooks/useTranslation';
import { useBookDataStore } from '@/store/bookDataStore';
import { useAIChatStore } from '@/store/aiChatStore';
import { useNotebookStore } from '@/store/notebookStore';
import type { AIConversation } from '@/services/ai/types';
import { useEnv } from '@/context/EnvContext';

interface ChatHistoryViewProps {
  bookKey: string;
}

const ChatHistoryView: React.FC<ChatHistoryViewProps> = ({ bookKey }) => {
  const _ = useTranslation();
  const { appService } = useEnv();
  const { getBookData } = useBookDataStore();
  const {
    conversations,
    isLoadingHistory,
    loadConversations,
    setActiveConversation,
    deleteConversation,
    renameConversation,
    createConversation,
  } = useAIChatStore();
  const { setNotebookVisible, setNotebookActiveTab } = useNotebookStore();

  const [editingId, setEditingId] = useState<string | null>(null);
  const [editTitle, setEditTitle] = useState('');

  const bookData = getBookData(bookKey);
  const bookHash = bookKey.split('-')[0] || '';
  const bookTitle = bookData?.book?.title || 'Unknown';

  // Load conversations for this book
  useEffect(() => {
    if (bookHash) {
      loadConversations(bookHash);
    }
  }, [bookHash, loadConversations]);

  const handleSelectConversation = useCallback(
    async (conversation: AIConversation) => {
      await setActiveConversation(conversation.id);
      setNotebookVisible(true);
      setNotebookActiveTab('ai');
    },
    [setActiveConversation, setNotebookVisible, setNotebookActiveTab],
  );

  const handleNewConversation = useCallback(async () => {
    await createConversation(bookHash, `Chat about ${bookTitle}`);
    setNotebookVisible(true);
    setNotebookActiveTab('ai');
  }, [bookHash, bookTitle, createConversation, setNotebookVisible, setNotebookActiveTab]);

  const handleDeleteConversation = useCallback(
    async (e: React.MouseEvent, id: string) => {
      e.stopPropagation();
      if (!appService) return;
      if (await appService.ask(_('Delete this conversation?'))) {
        await deleteConversation(id);
      }
    },
    [deleteConversation, _, appService],
  );

  const handleStartRename = useCallback((e: React.MouseEvent, conversation: AIConversation) => {
    e.stopPropagation();
    setEditingId(conversation.id);
    setEditTitle(conversation.title);
  }, []);

  const handleSaveRename = useCallback(
    async (e: React.MouseEvent | React.KeyboardEvent) => {
      e.stopPropagation();
      if (editingId && editTitle.trim()) {
        await renameConversation(editingId, editTitle.trim());
      }
      setEditingId(null);
      setEditTitle('');
    },
    [editingId, editTitle, renameConversation],
  );

  const handleCancelRename = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    setEditingId(null);
    setEditTitle('');
  }, []);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        handleSaveRename(e);
      } else if (e.key === 'Escape') {
        setEditingId(null);
        setEditTitle('');
      }
    },
    [handleSaveRename],
  );

  if (isLoadingHistory) {
    return (
      <div className='flex h-full items-center justify-center p-4'>
        <div className='border-primary size-5 animate-spin rounded-full border-2 border-t-transparent' />
      </div>
    );
  }

  return (
    <div className='relative flex h-full flex-col'>
      {/* Conversation list */}
      <div className='flex-1 overflow-y-auto'>
        {conversations.length === 0 ? (
          <div className='flex h-full flex-col items-center justify-center gap-3 p-4 text-center'>
            <div className='bg-base-300/50 rounded-full p-3'>
              <LuMessageSquare className='text-base-content/50 size-6' />
            </div>
            <div>
              <p className='text-base-content/70 text-sm'>{_('No conversations yet')}</p>
              <p className='text-base-content/50 text-xs'>
                {_('Start a new chat to ask questions about this book')}
              </p>
            </div>
          </div>
        ) : (
          <ul className='divide-base-300/30 divide-y pb-16'>
            {conversations.map((conversation) => (
              <li
                key={conversation.id}
                className={clsx(
                  'group flex cursor-pointer items-start gap-2 px-3 py-2.5',
                  'hover:bg-base-300/50 transition-colors duration-150',
                )}
              >
                <div
                  className='flex flex-1 items-start gap-2'
                  tabIndex={0}
                  role='button'
                  onClick={() => handleSelectConversation(conversation)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                      e.preventDefault();
                      handleSelectConversation(conversation);
                    }
                  }}
                >
                  <div className='min-w-0 flex-1'>
                    {editingId === conversation.id ? (
                      <div
                        className='flex items-center gap-1'
                        role='presentation'
                        onClick={(e) => e.stopPropagation()}
                        onKeyDown={(e) => e.stopPropagation()}
                      >
                        <input
                          type='text'
                          value={editTitle}
                          onChange={(e) => setEditTitle(e.target.value)}
                          onKeyDown={handleKeyDown}
                          className={clsx(
                            'input input-xs input-bordered w-full',
                            'bg-base-100 text-base-content',
                          )}
                          // eslint-disable-next-line jsx-a11y/no-autofocus
                          autoFocus
                        />
                        <button
                          onClick={handleSaveRename}
                          className='btn btn-ghost btn-xs text-success'
                          aria-label={_('Save')}
                        >
                          <LuCheck size={14} />
                        </button>
                        <button
                          onClick={handleCancelRename}
                          className='btn btn-ghost btn-xs text-error'
                          aria-label={_('Cancel')}
                        >
                          <LuX size={14} />
                        </button>
                      </div>
                    ) : (
                      <>
                        <p className='text-base-content line-clamp-1 text-sm font-medium'>
                          {conversation.title}
                        </p>
                        <p className='text-base-content/50 text-xs'>
                          {dayjs(conversation.updatedAt).format('MMM D, YYYY h:mm A')}
                        </p>
                      </>
                    )}
                  </div>
                </div>

                {editingId !== conversation.id && (
                  <div className='flex flex-shrink-0 gap-0.5 opacity-0 transition-opacity group-hover:opacity-100'>
                    <button
                      onClick={(e) => handleStartRename(e, conversation)}
                      className='btn btn-ghost btn-xs'
                      aria-label={_('Rename')}
                    >
                      <LuPencil size={12} />
                    </button>
                    <button
                      onClick={(e) => handleDeleteConversation(e, conversation.id)}
                      className='btn btn-ghost btn-xs text-error'
                      aria-label={_('Delete')}
                    >
                      <LuTrash2 size={12} />
                    </button>
                  </div>
                )}
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* Floating New Chat button at bottom right */}
      <div className='absolute bottom-4 right-4'>
        <button
          onClick={handleNewConversation}
          className={clsx(
            'flex items-center gap-2 rounded-full px-4 py-2',
            'bg-base-300 text-base-content',
            'hover:bg-base-content/10',
            'border-base-content/10 border',
            'shadow-sm',
            'transition-all duration-200 ease-out',
            'active:scale-[0.97]',
          )}
          aria-label={_('New Chat')}
        >
          <LuPlus size={16} />
          <span className='text-sm font-medium'>{_('New Chat')}</span>
        </button>
      </div>
    </div>
  );
};

export default ChatHistoryView;