[feat]: Implement chat description editing in sidebar and header, add visual cue for active chat in sidebar
This commit is contained in:
@@ -2,4 +2,5 @@ export * from './useMessageParser';
|
||||
export * from './usePromptEnhancer';
|
||||
export * from './useShortcuts';
|
||||
export * from './useSnapScroll';
|
||||
export * from './useEditChatDescription';
|
||||
export { default } from './useViewport';
|
||||
|
||||
152
app/lib/hooks/useEditChatDescription.ts
Normal file
152
app/lib/hooks/useEditChatDescription.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
import {
|
||||
chatId as chatIdStore,
|
||||
description as descriptionStore,
|
||||
db,
|
||||
updateChatDescription,
|
||||
getMessages,
|
||||
} from '~/lib/persistence';
|
||||
|
||||
interface EditChatDescriptionOptions {
|
||||
initialDescription?: string;
|
||||
customChatId?: string;
|
||||
syncWithGlobalStore?: boolean;
|
||||
}
|
||||
|
||||
type EditChatDescriptionHook = {
|
||||
editing: boolean;
|
||||
handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
handleBlur: () => Promise<void>;
|
||||
handleSubmit: (event: React.FormEvent) => Promise<void>;
|
||||
handleKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => Promise<void>;
|
||||
currentDescription: string;
|
||||
toggleEditMode: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to manage the state and behavior for editing chat descriptions.
|
||||
*
|
||||
* Offers functions to:
|
||||
* - Switch between edit and view modes.
|
||||
* - Manage input changes, blur, and form submission events.
|
||||
* - Save updates to IndexedDB and optionally to the global application state.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {string} options.initialDescription - The current chat description.
|
||||
* @param {string} options.customChatId - Optional ID for updating the description via the sidebar.
|
||||
* @param {boolean} options.syncWithGlobalStore - Flag to indicate global description store synchronization.
|
||||
* @returns {EditChatDescriptionHook} Methods and state for managing description edits.
|
||||
*/
|
||||
export function useEditChatDescription({
|
||||
initialDescription = descriptionStore.get()!,
|
||||
customChatId,
|
||||
syncWithGlobalStore,
|
||||
}: EditChatDescriptionOptions): EditChatDescriptionHook {
|
||||
const chatId = (customChatId || chatIdStore.get()) as string;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [currentDescription, setCurrentDescription] = useState(initialDescription);
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentDescription(initialDescription);
|
||||
}, [initialDescription]);
|
||||
|
||||
const toggleEditMode = useCallback(() => setEditing((prev) => !prev), []);
|
||||
|
||||
const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setCurrentDescription(e.target.value);
|
||||
}, []);
|
||||
|
||||
const fetchLatestDescription = useCallback(async () => {
|
||||
if (!db || !chatId) {
|
||||
return initialDescription;
|
||||
}
|
||||
|
||||
try {
|
||||
const chat = await getMessages(db, chatId);
|
||||
return chat?.description || initialDescription;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch latest description:', error);
|
||||
return initialDescription;
|
||||
}
|
||||
}, [db, chatId, initialDescription]);
|
||||
|
||||
const handleBlur = useCallback(async () => {
|
||||
const latestDescription = await fetchLatestDescription();
|
||||
setCurrentDescription(latestDescription);
|
||||
toggleEditMode();
|
||||
}, [fetchLatestDescription, toggleEditMode]);
|
||||
|
||||
const isValidDescription = useCallback((desc: string): boolean => {
|
||||
const trimmedDesc = desc.trim();
|
||||
|
||||
if (trimmedDesc === initialDescription) {
|
||||
toggleEditMode();
|
||||
return false; // No change, skip validation
|
||||
}
|
||||
|
||||
const lengthValid = trimmedDesc.length > 0 && trimmedDesc.length <= 100;
|
||||
const characterValid = /^[a-zA-Z0-9\s]+$/.test(trimmedDesc);
|
||||
|
||||
if (!lengthValid) {
|
||||
toast.error('Description must be between 1 and 100 characters.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!characterValid) {
|
||||
toast.error('Description can only contain alphanumeric characters and spaces.');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!isValidDescription(currentDescription)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!db) {
|
||||
toast.error('Chat persistence is not available');
|
||||
return;
|
||||
}
|
||||
|
||||
await updateChatDescription(db, chatId, currentDescription);
|
||||
|
||||
if (syncWithGlobalStore) {
|
||||
descriptionStore.set(currentDescription);
|
||||
}
|
||||
|
||||
toast.success('Chat description updated successfully');
|
||||
} catch (error) {
|
||||
toast.error('Failed to update chat description: ' + (error as Error).message);
|
||||
}
|
||||
|
||||
toggleEditMode();
|
||||
},
|
||||
[currentDescription, db, chatId, initialDescription, customChatId],
|
||||
);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
async (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Escape') {
|
||||
await handleBlur();
|
||||
}
|
||||
},
|
||||
[handleBlur],
|
||||
);
|
||||
|
||||
return {
|
||||
editing,
|
||||
handleChange,
|
||||
handleBlur,
|
||||
handleSubmit,
|
||||
handleKeyDown,
|
||||
currentDescription,
|
||||
toggleEditMode,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,68 @@
|
||||
import { useStore } from '@nanostores/react';
|
||||
import { description } from './useChatHistory';
|
||||
import { TooltipProvider } from '@radix-ui/react-tooltip';
|
||||
import WithTooltip from '~/components/ui/Tooltip';
|
||||
import { useEditChatDescription } from '~/lib/hooks';
|
||||
import { description as descriptionStore } from '~/lib/persistence';
|
||||
|
||||
export function ChatDescription() {
|
||||
return useStore(description);
|
||||
const initialDescription = useStore(descriptionStore)!;
|
||||
|
||||
const { editing, handleChange, handleBlur, handleSubmit, handleKeyDown, currentDescription, toggleEditMode } =
|
||||
useEditChatDescription({
|
||||
initialDescription,
|
||||
syncWithGlobalStore: true,
|
||||
});
|
||||
|
||||
if (!initialDescription) {
|
||||
// doing this to prevent showing edit button until chat description is set
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center">
|
||||
{editing ? (
|
||||
<form onSubmit={handleSubmit} className="flex items-center justify-center">
|
||||
<input
|
||||
type="text"
|
||||
className="bg-bolt-elements-background-depth-1 text-bolt-elements-textPrimary rounded px-2 mr-2 w-fit"
|
||||
autoFocus
|
||||
value={currentDescription}
|
||||
onChange={handleChange}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
style={{ width: `${Math.max(currentDescription.length * 8, 100)}px` }}
|
||||
/>
|
||||
<TooltipProvider>
|
||||
<WithTooltip tooltip="Save title">
|
||||
<div className="flex justify-between items-center p-2 rounded-md bg-bolt-elements-background-depth-3">
|
||||
<button
|
||||
type="submit"
|
||||
className="i-ph:check-bold scale-110 hover:text-bolt-elements-item-contentAccent"
|
||||
onMouseDown={handleSubmit}
|
||||
/>
|
||||
</div>
|
||||
</WithTooltip>
|
||||
</TooltipProvider>
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
{currentDescription}
|
||||
<TooltipProvider>
|
||||
<WithTooltip tooltip="Rename chat">
|
||||
<div className="flex justify-between items-center p-2 rounded-md bg-bolt-elements-background-depth-3 ml-2">
|
||||
<button
|
||||
type="button"
|
||||
className="i-ph:pencil-fill scale-110 hover:text-bolt-elements-item-contentAccent"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
toggleEditMode();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</WithTooltip>
|
||||
</TooltipProvider>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -52,17 +52,23 @@ export async function setMessages(
|
||||
messages: Message[],
|
||||
urlId?: string,
|
||||
description?: string,
|
||||
timestamp?: string,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction('chats', 'readwrite');
|
||||
const store = transaction.objectStore('chats');
|
||||
|
||||
if (timestamp && isNaN(Date.parse(timestamp))) {
|
||||
reject(new Error('Invalid timestamp'));
|
||||
return;
|
||||
}
|
||||
|
||||
const request = store.put({
|
||||
id,
|
||||
messages,
|
||||
urlId,
|
||||
description,
|
||||
timestamp: new Date().toISOString(),
|
||||
timestamp: timestamp ?? new Date().toISOString(),
|
||||
});
|
||||
|
||||
request.onsuccess = () => resolve();
|
||||
@@ -212,3 +218,17 @@ export async function createChatFromMessages(
|
||||
|
||||
return newUrlId; // Return the urlId instead of id for navigation
|
||||
}
|
||||
|
||||
export async function updateChatDescription(db: IDBDatabase, id: string, description: string): Promise<void> {
|
||||
const chat = await getMessages(db, id);
|
||||
|
||||
if (!chat) {
|
||||
throw new Error('Chat not found');
|
||||
}
|
||||
|
||||
if (!description.trim()) {
|
||||
throw new Error('Description cannot be empty');
|
||||
}
|
||||
|
||||
await setMessages(db, id, chat.messages, chat.urlId, description, chat.timestamp);
|
||||
}
|
||||
|
||||
@@ -100,6 +100,9 @@ export class ActionRunner {
|
||||
.catch((error) => {
|
||||
console.error('Action failed:', error);
|
||||
});
|
||||
|
||||
// eslint-disable-next-line consistent-return -- TODO: fix this consistent-return error
|
||||
return this.#currentExecutionPromise;
|
||||
}
|
||||
|
||||
async #executeAction(actionId: string, isStreaming: boolean = false) {
|
||||
|
||||
Reference in New Issue
Block a user