feat(ui): style sidebar and landing page (#27)

This commit is contained in:
Dominic Elm
2024-08-01 16:54:59 +02:00
committed by GitHub
parent 41f3f202ec
commit 5bbcdcca2c
13 changed files with 275 additions and 248 deletions

View File

@@ -1,15 +1,15 @@
import type { Message } from 'ai';
import React, { type LegacyRef, type RefCallback } from 'react';
import React, { type RefCallback } from 'react';
import { ClientOnly } from 'remix-utils/client-only';
import { Menu } from '~/components/sidebar/Menu.client';
import { IconButton } from '~/components/ui/IconButton';
import { Workbench } from '~/components/workbench/Workbench.client';
import { classNames } from '~/utils/classNames';
import { Messages } from './Messages.client';
import { Menu } from '~/components/sidemenu/Menu.client';
import { SendButton } from './SendButton.client';
interface BaseChatProps {
textareaRef?: LegacyRef<HTMLTextAreaElement> | undefined;
textareaRef?: React.RefObject<HTMLTextAreaElement> | undefined;
messageRef?: RefCallback<HTMLDivElement> | undefined;
scrollRef?: RefCallback<HTMLDivElement> | undefined;
chatStarted?: boolean;
@@ -19,12 +19,18 @@ interface BaseChatProps {
promptEnhanced?: boolean;
input?: string;
handleStop?: () => void;
sendMessage?: (event: React.UIEvent) => void;
sendMessage?: (event: React.UIEvent, messageInput?: string) => void;
handleInputChange?: (event: React.ChangeEvent<HTMLTextAreaElement>) => void;
enhancePrompt?: () => void;
}
const EXAMPLES = [{ text: 'Example' }, { text: 'Example' }, { text: 'Example' }, { text: 'Example' }];
const EXAMPLE_PROMPTS = [
{ text: 'Build a todo app in React using Tailwind' },
{ text: 'Build a simple blog using Astro' },
{ text: 'Create a cookie consent form using Material UI' },
{ text: 'Make a space invaders game' },
{ text: 'How do I can center a div?' },
];
const TEXTAREA_MIN_HEIGHT = 72;
@@ -53,22 +59,15 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
<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 id="chat" className="flex flex-col w-full h-full px-6">
<div className="flex flex-col w-full h-full px-6">
{!chatStarted && (
<div id="intro" className="mt-[20vh] mb-14 max-w-3xl mx-auto">
<h2 className="text-4xl text-center font-bold text-slate-800 mb-2">Where ideas begin.</h2>
<p className="mb-14 text-center">Bring ideas to life in seconds or get help on existing projects.</p>
<div className="grid max-md:grid-cols-[repeat(1,1fr)] md:grid-cols-[repeat(2,minmax(300px,1fr))] gap-4">
{EXAMPLES.map((suggestion, index) => (
<button key={index} className="p-4 rounded-lg shadow-xs bg-white border border-gray-200 text-left">
{suggestion.text}
</button>
))}
</div>
<div id="intro" className="mt-[26vh] max-w-2xl mx-auto">
<h1 className="text-5xl text-center font-bold text-slate-800 mb-2">Where ideas begin</h1>
<p className="mb-4 text-center">Bring ideas to life in seconds or get help on existing projects.</p>
</div>
)}
<div
className={classNames('pt-10', {
className={classNames('pt-6', {
'h-full flex flex-col': chatStarted,
})}
>
@@ -77,7 +76,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
return chatStarted ? (
<Messages
ref={messageRef}
className="flex flex-col w-full flex-1 max-w-3xl px-4 pb-10 mx-auto z-1"
className="flex flex-col w-full flex-1 max-w-2xl px-4 pb-10 mx-auto z-1"
messages={messages}
isStreaming={isStreaming}
/>
@@ -85,7 +84,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
}}
</ClientOnly>
<div
className={classNames('relative w-full max-w-3xl md:mx-auto z-2', {
className={classNames('relative w-full max-w-2xl md:mx-auto z-2', {
'sticky bottom-0': chatStarted,
})}
>
@@ -172,6 +171,26 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
<div className="bg-white pb-6">{/* Ghost Element */}</div>
</div>
</div>
{!chatStarted && (
<div id="examples" className="relative w-full max-w-2xl mx-auto text-center mt-8 flex justify-center">
<div className="flex flex-col items-center space-y-2 [mask-image:linear-gradient(to_bottom,black_0%,transparent_180%)] hover:[mask-image:none]">
{EXAMPLE_PROMPTS.map((examplePrompt, index) => {
return (
<button
key={index}
onClick={(event) => {
sendMessage?.(event, examplePrompt.text);
}}
className="group flex items-center gap-2 bg-transparent text-gray-500 hover:text-gray-1000"
>
{examplePrompt.text}
<div className="i-ph:arrow-bend-down-left" />
</button>
);
})}
</div>
</div>
)}
</div>
<ClientOnly>{() => <Workbench chatStarted={chatStarted} isStreaming={isStreaming} />}</ClientOnly>
</div>

View File

@@ -44,7 +44,7 @@ export function ChatImpl({ initialMessages, storeMessageHistory }: ChatProps) {
const [animationScope, animate] = useAnimate();
const { messages, isLoading, input, handleInputChange, setInput, handleSubmit, stop, append } = useChat({
const { messages, isLoading, input, handleInputChange, setInput, stop, append } = useChat({
api: '/api/chat',
onError: (error) => {
logger.error('Request failed\n\n', error);
@@ -61,6 +61,10 @@ export function ChatImpl({ initialMessages, storeMessageHistory }: ChatProps) {
const TEXTAREA_MAX_HEIGHT = chatStarted ? 400 : 200;
useEffect(() => {
chatStore.setKey('started', initialMessages.length > 0);
}, []);
useEffect(() => {
parseMessages(messages, isLoading);
@@ -101,13 +105,20 @@ export function ChatImpl({ initialMessages, storeMessageHistory }: ChatProps) {
return;
}
await animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn });
await Promise.all([
animate('#examples', { opacity: 0, display: 'none' }, { duration: 0.1 }),
animate('#intro', { opacity: 0, flex: 1 }, { duration: 0.2, ease: cubicEasingFn }),
]);
chatStore.setKey('started', true);
setChatStarted(true);
};
const sendMessage = async (event: React.UIEvent) => {
if (input.length === 0 || isLoading) {
const sendMessage = async (_event: React.UIEvent, messageInput?: string) => {
const _input = messageInput || input;
if (_input.length === 0 || isLoading) {
return;
}
@@ -136,9 +147,7 @@ export function ChatImpl({ initialMessages, storeMessageHistory }: ChatProps) {
* manually reset the input and we'd have to manually pass in file attachments. However, those
* aren't relevant here.
*/
append({ role: 'user', content: `${diff}\n\n${input}` });
setInput('');
append({ role: 'user', content: `${diff}\n\n${_input}` });
/**
* After sending a new message we reset all modifications since the model
@@ -146,9 +155,11 @@ export function ChatImpl({ initialMessages, storeMessageHistory }: ChatProps) {
*/
workbenchStore.resetAllFileModifications();
} else {
handleSubmit(event);
append({ role: 'user', content: _input });
}
setInput('');
resetEnhancer();
textareaRef.current?.blur();

View File

@@ -1,20 +1,26 @@
import { useStore } from '@nanostores/react';
import { ClientOnly } from 'remix-utils/client-only';
import { IconButton } from '~/components/ui/IconButton';
import { chatStore } from '~/lib/stores/chat';
import { classNames } from '~/utils/classNames';
import { OpenStackBlitz } from './OpenStackBlitz.client';
export function Header() {
const chat = useStore(chatStore);
return (
<header className="flex items-center bg-white p-4 border-b border-gray-200 h-[var(--header-height)]">
<header
className={classNames('flex items-center bg-white p-5 border-b h-[var(--header-height)]', {
'border-transparent': !chat.started,
'border-gray-200': chat.started,
})}
>
<div className="flex items-center gap-2">
<a href="/" className="text-2xl font-semibold text-accent">
Bolt
<img src="/logo_text.svg" width="60px" alt="Bolt Logo" />
</a>
</div>
<div className="ml-auto flex gap-2">
<ClientOnly>{() => <OpenStackBlitz />}</ClientOnly>
<a href="/logout">
<IconButton icon="i-ph:sign-out" />
</a>
</div>
</header>
);

View File

@@ -0,0 +1,80 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'react-toastify';
import { db, deleteId, type ChatHistory } from '~/lib/persistence';
import { logger } from '~/utils/logger';
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((event: React.UIEvent) => {
event.preventDefault();
if (db) {
deleteId(db, item.id)
.then(() => loadEntries())
.catch((error) => {
toast.error('Failed to delete conversation');
logger.error(error);
});
}
}, []);
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
ref={hoverRef}
className="group rounded-md hover:bg-gray-100 overflow-hidden flex justify-between items-center px-2 py-1"
>
<a href={`/chat/${item.urlId}`} className="flex w-full relative truncate block">
{item.description}
<div className="absolute right-0 z-1 top-0 bottom-0 bg-gradient-to-l from-white group-hover:from-gray-100 to-transparent w-10 flex justify-end group-hover:w-15 group-hover:from-45%">
{hovering && (
<div className="flex items-center p-1">
{requestingDelete ? (
<button className="i-ph:check text-gray-600 hover:text-gray-1000 scale-110" onClick={deleteItem} />
) : (
<button
className="i-ph:trash text-gray-600 hover:text-gray-1000 scale-110"
onClick={(event) => {
event.preventDefault();
setRequestingDelete(true);
}}
/>
)}
</div>
)}
</div>
</a>
</div>
);
}

View File

@@ -0,0 +1,114 @@
import { motion, type Variants } from 'framer-motion';
import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'react-toastify';
import { IconButton } from '~/components/ui/IconButton';
import { db, getAll, type ChatHistory } from '~/lib/persistence';
import { cubicEasingFn } from '~/utils/easings';
import { HistoryItem } from './HistoryItem';
import { binDates } from './date-binning';
const menuVariants = {
closed: {
opacity: 0,
left: '-150px',
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
open: {
opacity: 1,
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 top-0 w-[350px] h-full bg-white border-r rounded-r-3xl border-gray-200 z-max shadow-xl text-sm"
>
<div className="flex items-center p-4 h-[var(--header-height)]">
<img src="/logo_text.svg" width="60px" alt="Bolt Logo" />
</div>
<div className="flex-1 flex flex-col h-full w-full overflow-hidden">
<div className="p-4">
<a
href="/"
className="flex gap-2 items-center text-accent-600 rounded-md bg-accent-600/12 hover:bg-accent-600/15 p-2 font-medium"
>
<span className="inline-block i-blitz:chat scale-110" />
Start new chat
</a>
</div>
<div className="font-semibold pl-6 pr-5 my-2">Your Chats</div>
<div className="flex-1 overflow-scroll pl-4 pr-5 pb-5">
{list.length === 0 && <div className="pl-2 text-gray">No previous conversations</div>}
{binDates(list).map(({ category, items }) => (
<div key={category} className="mt-4 first:mt-0 space-y-1">
<div className="text-gray sticky top-0 z-20 bg-white pl-2 pt-2 pb-1">{category}</div>
{items.map((item) => (
<HistoryItem key={item.id} item={item} loadEntries={loadEntries} />
))}
</div>
))}
</div>
<div className="flex items-center border-t p-4">
<a href="/logout">
<IconButton className="p-1.5 gap-1.5">
<>
Logout <span className="i-ph:sign-out text-lg" />
</>
</IconButton>
</a>
</div>
</div>
</motion.div>
);
}

View File

@@ -1,5 +1,5 @@
import { format, isAfter, isThisWeek, isThisYear, isToday, isYesterday, subDays } from 'date-fns';
import type { ChatHistory } from '~/lib/persistence';
import { format, isToday, isYesterday, isThisWeek, isThisYear, subDays, isAfter } from 'date-fns';
type Bin = { category: string; items: ChatHistory[] };
@@ -19,6 +19,7 @@ export function binDates(_list: ChatHistory[]) {
};
binLookup[category] = bin;
bins.push(bin);
} else {
binLookup[category].items.push(item);
@@ -38,7 +39,8 @@ function dateCategory(date: Date) {
}
if (isThisWeek(date)) {
return format(date, 'eeee'); // e.g. "Monday"
// e.g., "Monday"
return format(date, 'eeee');
}
const thirtyDaysAgo = subDays(new Date(), 30);
@@ -48,8 +50,10 @@ function dateCategory(date: Date) {
}
if (isThisYear(date)) {
return format(date, 'MMMM'); // e.g., "July"
// e.g., "July"
return format(date, 'MMMM');
}
return format(date, 'MMMM yyyy'); // e.g. "July 2023"
// e.g., "July 2023"
return format(date, 'MMMM yyyy');
}

View File

@@ -1,88 +0,0 @@
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

@@ -1,99 +0,0 @@
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

@@ -1,5 +1,6 @@
import { map } from 'nanostores';
export const chatStore = map({
started: false,
aborted: false,
});

View File

@@ -4,30 +4,6 @@
@import './components/terminal.scss';
@import './components/resize-handle.scss';
body {
--at-apply: bg-bolt-elements-app-backgroundColor;
font-family: 'Inter', sans-serif;
&:before {
--line: color-mix(in lch, canvasText, transparent 93%);
--size: 50px;
content: '';
height: 100vh;
mask: linear-gradient(-25deg, transparent 60%, white);
pointer-events: none;
position: fixed;
top: -8px;
transform-style: flat;
width: 100vw;
z-index: -1;
background:
linear-gradient(90deg, var(--line) 1px, transparent 1px var(--size)) 50% 50% / var(--size) var(--size),
linear-gradient(var(--line) 1px, transparent 1px var(--size)) 50% 50% / var(--size) var(--size);
}
}
html,
body {
height: 100%;