feat: initial chat history ui (#25)

This commit is contained in:
Kirjava 2024-07-31 22:21:40 +01:00 committed by GitHub
parent be315f685a
commit 41f3f202ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 285 additions and 5 deletions

View File

@ -5,6 +5,7 @@ import { IconButton } from '~/components/ui/IconButton';
import { Workbench } from '~/components/workbench/Workbench.client'; import { Workbench } from '~/components/workbench/Workbench.client';
import { classNames } from '~/utils/classNames'; import { classNames } from '~/utils/classNames';
import { Messages } from './Messages.client'; import { Messages } from './Messages.client';
import { Menu } from '~/components/sidemenu/Menu.client';
import { SendButton } from './SendButton.client'; import { SendButton } from './SendButton.client';
interface BaseChatProps { interface BaseChatProps {
@ -50,6 +51,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
return ( return (
<div ref={ref} className="relative flex h-full w-full overflow-hidden "> <div ref={ref} className="relative flex h-full w-full overflow-hidden ">
<ClientOnly>{() => <Menu />}</ClientOnly>
<div ref={scrollRef} className="flex overflow-scroll w-full h-full"> <div ref={scrollRef} className="flex overflow-scroll w-full h-full">
<div id="chat" className="flex flex-col w-full h-full px-6"> <div id="chat" className="flex flex-col w-full h-full px-6">
{!chatStarted && ( {!chatStarted && (

View File

@ -6,7 +6,9 @@ export function Header() {
return ( return (
<header className="flex items-center bg-white p-4 border-b border-gray-200 h-[var(--header-height)]"> <header className="flex items-center bg-white p-4 border-b border-gray-200 h-[var(--header-height)]">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="text-2xl font-semibold text-accent">Bolt</div> <a href="/" className="text-2xl font-semibold text-accent">
Bolt
</a>
</div> </div>
<div className="ml-auto flex gap-2"> <div className="ml-auto flex gap-2">
<ClientOnly>{() => <OpenStackBlitz />}</ClientOnly> <ClientOnly>{() => <OpenStackBlitz />}</ClientOnly>

View File

@ -0,0 +1,88 @@
import { toast } from 'react-toastify';
import { useCallback, useEffect, useState, useRef } from 'react';
import { motion, type Variants } from 'framer-motion';
import { cubicEasingFn } from '~/utils/easings';
import { IconButton } from '~/components/ui/IconButton';
import { db, deleteId, type ChatHistory } from '~/lib/persistence';
const iconVariants = {
closed: {
transform: 'translate(40px,0)',
opacity: 0,
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
open: {
transform: 'translate(0,0)',
opacity: 1,
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
} satisfies Variants;
export function HistoryItem({ item, loadEntries }: { item: ChatHistory; loadEntries: () => void }) {
const [requestingDelete, setRequestingDelete] = useState(false);
const [hovering, setHovering] = useState(false);
const hoverRef = useRef<HTMLDivElement>(null);
const deleteItem = useCallback(() => {
if (db) {
deleteId(db, item.id)
.then(() => loadEntries())
.catch((error) => toast.error(error.message));
}
}, []);
useEffect(() => {
let timeout: NodeJS.Timeout | undefined;
function mouseEnter() {
setHovering(true);
if (timeout) {
clearTimeout(timeout);
}
}
function mouseLeave() {
setHovering(false);
// wait for animation to finish before unsetting
timeout = setTimeout(() => {
setRequestingDelete(false);
}, 200);
}
hoverRef.current?.addEventListener('mouseenter', mouseEnter);
hoverRef.current?.addEventListener('mouseleave', mouseLeave);
return () => {
hoverRef.current?.removeEventListener('mouseenter', mouseEnter);
hoverRef.current?.removeEventListener('mouseleave', mouseLeave);
};
}, []);
return (
<div className="ml-3 mr-1">
<div
ref={hoverRef}
className="rounded-md hover:bg-gray-200 p-1 overflow-hidden flex justify-between items-center"
>
<a href={`/chat/${item.urlId}`} className="truncate block pr-1">
{item.description}
</a>
<motion.div initial="closed" animate={hovering ? 'open' : 'closed'} variants={iconVariants}>
{requestingDelete ? (
<IconButton icon="i-ph:check" onClick={deleteItem} />
) : (
<IconButton icon="i-ph:trash" onClick={() => setRequestingDelete(true)} />
)}
</motion.div>
</div>
</div>
);
}

View File

@ -0,0 +1,99 @@
import { Fragment, useEffect, useState, useRef, useCallback } from 'react';
import { toast } from 'react-toastify';
import { motion, type Variants } from 'framer-motion';
import { cubicEasingFn } from '~/utils/easings';
import { db, getAll, type ChatHistory } from '~/lib/persistence';
import { HistoryItem } from './HistoryItem';
import { binDates } from './date-binning';
const menuVariants = {
closed: {
left: '-400px',
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
open: {
left: 0,
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
} satisfies Variants;
export function Menu() {
const menuRef = useRef<HTMLDivElement>(null);
const [list, setList] = useState<ChatHistory[]>([]);
const [open, setOpen] = useState(false);
const loadEntries = useCallback(() => {
if (db) {
getAll(db)
.then((list) => list.filter((item) => item.urlId && item.description))
.then(setList)
.catch((error) => toast.error(error.message));
}
}, []);
useEffect(() => {
if (open) {
loadEntries();
}
}, [open]);
useEffect(() => {
function onMouseMove(event: MouseEvent) {
if (event.pageX < 80) {
setOpen(true);
}
}
function onMouseLeave(_event: MouseEvent) {
setOpen(false);
}
menuRef.current?.addEventListener('mouseleave', onMouseLeave);
window.addEventListener('mousemove', onMouseMove);
return () => {
menuRef.current?.removeEventListener('mouseleave', onMouseLeave);
window.removeEventListener('mousemove', onMouseMove);
};
}, []);
return (
<motion.div
ref={menuRef}
initial="closed"
animate={open ? 'open' : 'closed'}
variants={menuVariants}
className="flex flex-col side-menu fixed left-[-400px] top-0 w-[400px] h-full bg-white border-r border-gray-200 z-max"
>
<div className="flex items-center border-b border-gray-200 bg-white p-4 h-[var(--header-height)]">
<a href="/" className="text-2xl font-semibold">
Bolt
</a>
</div>
<div className="m-4 ml-2 mt-7">
<a href="/" className="text-white rounded-md bg-accent-600 p-2 font-semibold">
Start new chat
</a>
</div>
<div className="font-semibold m-2 ml-4">Your Chats</div>
<div className="overflow-auto pb-2">
{list.length === 0 && <div className="ml-4 text-gray">No previous conversations</div>}
{binDates(list).map(({ category, items }) => (
<Fragment key={category}>
<div className="ml-4 text-gray m-2">{category}</div>
{items.map((item) => (
<HistoryItem key={item.id} item={item} loadEntries={loadEntries} />
))}
</Fragment>
))}
</div>
<div className="border-t border-gray-200 h-[var(--header-height)]" />
</motion.div>
);
}

View File

@ -0,0 +1,55 @@
import type { ChatHistory } from '~/lib/persistence';
import { format, isToday, isYesterday, isThisWeek, isThisYear, subDays, isAfter } from 'date-fns';
type Bin = { category: string; items: ChatHistory[] };
export function binDates(_list: ChatHistory[]) {
const list = _list.toSorted((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
const binLookup: Record<string, Bin> = {};
const bins: Array<Bin> = [];
list.forEach((item) => {
const category = dateCategory(new Date(item.timestamp));
if (!(category in binLookup)) {
const bin = {
category,
items: [item],
};
binLookup[category] = bin;
bins.push(bin);
} else {
binLookup[category].items.push(item);
}
});
return bins;
}
function dateCategory(date: Date) {
if (isToday(date)) {
return 'Today';
}
if (isYesterday(date)) {
return 'Yesterday';
}
if (isThisWeek(date)) {
return format(date, 'eeee'); // e.g. "Monday"
}
const thirtyDaysAgo = subDays(new Date(), 30);
if (isAfter(date, thirtyDaysAgo)) {
return 'Last 30 Days';
}
if (isThisYear(date)) {
return format(date, 'MMMM'); // e.g., "July"
}
return format(date, 'MMMM yyyy'); // e.g. "July 2023"
}

View File

@ -30,6 +30,17 @@ export async function openDatabase(): Promise<IDBDatabase | undefined> {
}); });
} }
export async function getAll(db: IDBDatabase): Promise<ChatHistory[]> {
return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readonly');
const store = transaction.objectStore('chats');
const request = store.getAll();
request.onsuccess = () => resolve(request.result as ChatHistory[]);
request.onerror = () => reject(request.error);
});
}
export async function setMessages( export async function setMessages(
db: IDBDatabase, db: IDBDatabase,
id: string, id: string,
@ -46,6 +57,7 @@ export async function setMessages(
messages, messages,
urlId, urlId,
description, description,
timestamp: new Date().toISOString(),
}); });
request.onsuccess = () => resolve(); request.onsuccess = () => resolve();
@ -80,13 +92,28 @@ export async function getMessagesById(db: IDBDatabase, id: string): Promise<Chat
}); });
} }
export async function deleteId(db: IDBDatabase, id: string): Promise<void> {
return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readwrite');
const store = transaction.objectStore('chats');
const request = store.delete(id);
request.onsuccess = () => resolve(undefined);
request.onerror = () => reject(request.error);
});
}
export async function getNextId(db: IDBDatabase): Promise<string> { export async function getNextId(db: IDBDatabase): Promise<string> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const transaction = db.transaction('chats', 'readonly'); const transaction = db.transaction('chats', 'readonly');
const store = transaction.objectStore('chats'); const store = transaction.objectStore('chats');
const request = store.count(); const request = store.getAllKeys();
request.onsuccess = () => {
const highestId = request.result.reduce((cur, acc) => Math.max(+cur, +acc), 0);
resolve(String(+highestId + 1));
};
request.onsuccess = () => resolve(String(request.result));
request.onerror = () => reject(request.error); request.onerror = () => reject(request.error);
}); });
} }

View File

@ -10,6 +10,7 @@ export interface ChatHistory {
urlId?: string; urlId?: string;
description?: string; description?: string;
messages: Message[]; messages: Message[];
timestamp: string;
} }
const persistenceEnabled = !import.meta.env.VITE_DISABLE_PERSISTENCE; const persistenceEnabled = !import.meta.env.VITE_DISABLE_PERSISTENCE;

View File

@ -96,8 +96,6 @@
:root { :root {
--header-height: 65px; --header-height: 65px;
--z-index-max: 999;
/* App */ /* App */
--bolt-elements-app-backgroundColor: var(--bolt-background-primary); --bolt-elements-app-backgroundColor: var(--bolt-background-primary);
--bolt-elements-app-borderColor: var(--bolt-border-primary); --bolt-elements-app-borderColor: var(--bolt-border-primary);

View File

@ -1 +1,5 @@
$zIndexMax: 999; $zIndexMax: 999;
.z-max {
z-index: $zIndexMax;
}

View File

@ -44,6 +44,7 @@
"@xterm/addon-web-links": "^0.11.0", "@xterm/addon-web-links": "^0.11.0",
"@xterm/xterm": "^5.5.0", "@xterm/xterm": "^5.5.0",
"ai": "^3.2.27", "ai": "^3.2.27",
"date-fns": "^3.6.0",
"diff": "^5.2.0", "diff": "^5.2.0",
"framer-motion": "^11.2.12", "framer-motion": "^11.2.12",
"isbot": "^4.1.0", "isbot": "^4.1.0",

View File

@ -119,6 +119,9 @@ importers:
ai: ai:
specifier: ^3.2.27 specifier: ^3.2.27
version: 3.2.27(react@18.3.1)(svelte@4.2.18)(vue@3.4.30(typescript@5.5.2))(zod@3.23.8) version: 3.2.27(react@18.3.1)(svelte@4.2.18)(vue@3.4.30(typescript@5.5.2))(zod@3.23.8)
date-fns:
specifier: ^3.6.0
version: 3.6.0
diff: diff:
specifier: ^5.2.0 specifier: ^5.2.0
version: 5.2.0 version: 5.2.0