better md

This commit is contained in:
Yash 2024-04-10 15:17:37 +00:00
parent 457ab9dbda
commit 6b7be692c5
3 changed files with 100 additions and 69 deletions

View file

@ -55,4 +55,16 @@ body {
.main-hidden {
padding-bottom: 20vh;
padding-bottom: 15dvh;
}
.chat-answer pre {
@apply bg-rgray-3 rounded-md border border-rgray-5 p-3 text-sm my-5;
}
.chat-answer h1 {
@apply text-rgray-11 text-xl font-medium my-5;
}
.chat-answer img {
@apply rounded-md font-medium my-5;
}

View file

@ -1,9 +1,9 @@
import React, { useEffect } from 'react';
import { motion } from 'framer-motion';
import { ArrowUpRight, Globe } from 'lucide-react';
import { convertRemToPixels } from '@/lib/utils';
import { SpaceIcon } from '@/assets/Memories';
import Markdown from 'react-markdown';
import React, { useEffect } from "react";
import { motion } from "framer-motion";
import { ArrowUpRight, Globe } from "lucide-react";
import { convertRemToPixels } from "@/lib/utils";
import { SpaceIcon } from "@/assets/Memories";
import Markdown from "react-markdown";
export function ChatAnswer({
children: message,
@ -15,11 +15,11 @@ export function ChatAnswer({
loading?: boolean;
}) {
return (
<div className="flex w-full flex-col items-start gap-5">
<div className="flex h-max w-full flex-col items-start gap-5">
{loading ? (
<MessageSkeleton />
) : (
<div className="w-full text-lg text-white/60">
<div className="chat-answer h-full w-full text-lg text-white/60">
<Markdown>{message}</Markdown>
</div>
)}
@ -50,7 +50,7 @@ export function ChatAnswer({
export function ChatQuestion({ children }: { children: string }) {
return (
<div
className={`text-rgray-12 w-full text-left ${children.length > 200 ? 'text-xl' : 'text-2xl'}`}
className={`text-rgray-12 h-max w-full text-left ${children.length > 200 ? "text-xl" : "text-2xl"}`}
>
{children}
</div>
@ -70,14 +70,9 @@ export function ChatMessage({
useEffect(() => {
if (!isLast) return;
console.log(
'last',
messageRef.current?.offsetTop,
messageRef.current?.parentElement,
);
messageRef.current?.parentElement?.scrollTo({
top: messageRef.current?.offsetTop,
behavior: 'smooth',
behavior: "smooth",
});
}, []);
@ -86,11 +81,11 @@ export function ChatMessage({
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{
type: 'tween',
type: "tween",
duration: 0.5,
}}
ref={messageRef}
className={`${index === 0 ? 'pt-16' : 'pt-28'} flex w-full flex-col items-start justify-start gap-5 transition-[height] ${isLast ? 'min-h-screen' : 'h-auto'}`}
className={`${index === 0 ? "pt-16" : "pt-28"} flex h-max w-full resize-y flex-col items-start justify-start gap-5 transition-[height] ${isLast ? "min-h-screen pb-[40vh]" : "h-max"}`}
>
{children}
</motion.div>

View file

@ -1,32 +1,56 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { FilterCombobox } from './Sidebar/FilterCombobox';
import { Textarea2 } from './ui/textarea';
import { ArrowRight, ArrowUp } from 'lucide-react';
import { MemoryDrawer } from './MemoryDrawer';
import useViewport from '@/hooks/useViewport';
import { AnimatePresence, motion } from 'framer-motion';
import { cn, countLines } from '@/lib/utils';
import { ChatHistory } from '../../types/memory';
import { ChatAnswer, ChatMessage, ChatQuestion } from './ChatMessage';
import { useRouter, useSearchParams } from 'next/navigation';
import { useMemory } from '@/contexts/MemoryContext';
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { FilterCombobox } from "./Sidebar/FilterCombobox";
import { Textarea2 } from "./ui/textarea";
import { ArrowRight, ArrowUp } from "lucide-react";
import { MemoryDrawer } from "./MemoryDrawer";
import useViewport from "@/hooks/useViewport";
import { AnimatePresence, motion } from "framer-motion";
import { cn, countLines } from "@/lib/utils";
import { ChatHistory } from "../../types/memory";
import { ChatAnswer, ChatMessage, ChatQuestion } from "./ChatMessage";
import { useRouter, useSearchParams } from "next/navigation";
import { useMemory } from "@/contexts/MemoryContext";
function supportsDVH() {
try {
return CSS.supports('height: 100dvh');
return CSS.supports("height: 100dvh");
} catch {
return false;
}
}
const failResponse = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In volutpat bibendum ligula, nec consectetur purus iaculis eu. Sed venenatis magna at lacus efficitur, vel faucibus sem lobortis. Sed sit amet imperdiet eros, nec vestibulum ante. Integer ut eros pulvinar, tempus augue a, blandit nisl. Nulla ut ligula molestie, tincidunt ligula vitae, rhoncus tellus. Vestibulum molestie, orci nec scelerisque finibus, mauris eros convallis urna, vitae vehicula metus nisi id urna. Phasellus non metus et lectus sollicitudin convallis a sit amet turpis. Donec id lacinia sapien.
Donec eget eros diam. Ut enim nunc, placerat vitae augue vel, rutrum dapibus felis. Nulla et ultrices ex. In sed arcu eget lectus scelerisque semper. Nullam aliquam luctus ultrices. Morbi finibus nec dolor vitae mattis. Quisque ligula dui, ullamcorper sed blandit et, maximus vel quam. Nunc id eros id sapien tempor feugiat sit amet sed mi. Quisque feugiat hendrerit libero non cursus. Praesent convallis, diam eget ullamcorper bibendum, est tellus blandit velit, vel cursus diam turpis sed nisi.
Cras dictum tortor ex, id ullamcorper nibh mollis quis. Fusce mollis, massa vel sodales consectetur, lorem mi vehicula erat, id tincidunt lorem libero at augue. Suspendisse vitae enim varius, molestie augue ut, lobortis ipsum. Nam lobortis leo eget velit auctor, ac consequat nisl malesuada. Donec sed dapibus nunc. Curabitur euismod erat a erat viverra vestibulum lacinia quis nisl. Aenean rhoncus suscipit maximus. Aliquam vitae lectus est.
Sed rhoncus sem sapien, at posuere libero imperdiet eget. Maecenas in egestas quam. Duis non faucibus eros, nec sodales sem. Proin felis urna, dapibus eget ante vitae, porttitor bibendum nunc. Integer nec augue eget diam pulvinar vestibulum. Nulla lobortis libero tellus, eu commodo elit ullamcorper in. Sed semper ultricies turpis ac dignissim. Morbi at ligula non urna mollis interdum vitae sed nisi. Quisque mattis arcu eu nisl placerat ullamcorper. Cras aliquet risus sed hendrerit faucibus. Donec vitae ex quis magna cursus ultricies ut nec urna.
Integer molestie nulla interdum enim suscipit malesuada. Nullam eget ipsum et elit sagittis imperdiet sed dignissim sem. Fusce vitae tellus ligula. Donec eget mi varius, consequat eros sed, consectetur urna. Suspendisse potenti. Praesent posuere ullamcorper tincidunt. Donec bibendum, magna nec mollis posuere, nisi risus dictum mauris, sed gravida metus sapien vel ipsum. Etiam ultrices nulla tincidunt erat lacinia, sit amet bibendum libero posuere. Vestibulum vehicula lectus dolor, sit amet vehicula arcu ultricies nec. Proin blandit risus diam, vel finibus erat efficitur in. Suspendisse lacinia eros luctus posuere fermentum. Etiam sed lacus aliquam, vulputate est sed, venenatis ex. Aenean at nulla rhoncus, sollicitudin elit quis, auctor tortor. Donec semper, augue lacinia pharetra imperdiet, metus purus bibendum ex, et venenatis enim purus vitae nulla. Duis eu felis porta ligula laoreet viverra.
Answer
It seems like you've used placeholder text commonly known as "Lorem Ipsum," which is often used in design and publishing to simulate the appearance of written text. If you have any specific questions or need assistance with something related to this text, feel free to ask!
what is its purpose?
Sources
solopress.com favicon
typingpal.com favicon
View 2 more
Answer
The purpose of Lorem Ipsum, a commonly used placeholder text in design and publishing, is to create a natural-looking block of text that doesn't distract from the layout. It allows designers to visualize how text will appear in a design without the need for actual content to be written and approved. Lorem Ipsum helps in planning out where the content will sit on a page, focusing on the design rather than the specific content. This practice is particularly useful when the main emphasis is on the visual layout, allowing designers and clients to review templates without being distracted by the actual copy on the page
4
5
.
hello
`;
export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
const searchParams = useSearchParams();
const router = useRouter();
const [hide, setHide] = useState(false);
const [layout, setLayout] = useState<'chat' | 'initial'>('initial');
const [value, setValue] = useState('');
const [layout, setLayout] = useState<"chat" | "initial">("initial");
const [value, setValue] = useState("");
const { width } = useViewport();
const [isAiLoading, setIsAiLoading] = useState(false);
@ -35,7 +59,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
// Variable to keep track of the chat history in this session
const [chatHistory, setChatHistory] = useState<ChatHistory[]>([]);
const [toBeParsed, setToBeParsed] = useState('');
const [toBeParsed, setToBeParsed] = useState("");
const textArea = useRef<HTMLDivElement>(null);
const main = useRef<HTMLDivElement>(null);
@ -43,11 +67,11 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
const [selectedSpaces, setSelectedSpaces] = useState<number[]>([]);
useEffect(() => {
const search = searchParams.get('q');
const search = searchParams.get("q");
if (search && search.trim().length > 0) {
setValue(search);
onSend();
router.push('/');
router.push("/");
}
}, []);
@ -66,9 +90,9 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
}
}
window.visualViewport?.addEventListener('resize', onResize);
window.visualViewport?.addEventListener("resize", onResize);
return () => {
window.visualViewport?.removeEventListener('resize', onResize);
window.visualViewport?.removeEventListener("resize", onResize);
};
}, []);
@ -78,13 +102,13 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
// Attempt to parse the "toBeParsed" state as JSON
try {
// Split the accumulated data by the known delimiter "\n\n"
const parts = toBeParsed.split('\n\n');
let remainingData = '';
const parts = toBeParsed.split("\n\n");
let remainingData = "";
// Process each part to extract JSON objects
parts.forEach((part, index) => {
try {
const parsedPart = JSON.parse(part.replace('data: ', '')); // Try to parse the part as JSON
const parsedPart = JSON.parse(part.replace("data: ", "")); // Try to parse the part as JSON
// If the part is the last one and couldn't be parsed, keep it to accumulate more data
if (index === parts.length - 1 && !parsedPart) {
@ -117,7 +141,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
} catch (error) {
// If parsing fails and it's not the last part, it's a malformed JSON
if (index !== parts.length - 1) {
console.error('Malformed JSON part: ', part);
console.error("Malformed JSON part: ", part);
} else {
// If it's the last part, it may be incomplete, so keep it
remainingData = part;
@ -130,7 +154,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
setToBeParsed(remainingData);
}
} catch (error) {
console.error('Error parsing accumulated data: ', error);
console.error("Error parsing accumulated data: ", error);
}
};
@ -141,14 +165,14 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
}, [toBeParsed]);
const modifyChatHistory = useCallback((old: ChatHistory[]) => {
const final: { role: 'user' | 'model'; parts: { text: string }[] }[] = [];
const final: { role: "user" | "model"; parts: { text: string }[] }[] = [];
old.forEach((chat) => {
final.push({
role: 'user',
role: "user",
parts: [{ text: chat.question }],
});
final.push({
role: 'model',
role: "model",
parts: chat.answer.parts.map((part) => ({ text: part.text })),
});
});
@ -160,7 +184,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
setIsAiLoading(true);
const _value = value.trim();
setValue('');
setValue("");
setChatHistory((prev) => [
...prev,
@ -176,7 +200,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
const sourcesResponse = await fetch(
`/api/chat?sourcesOnly=true&q=${_value}`,
{
method: 'POST',
method: "POST",
body: JSON.stringify({
chatHistory: modifyChatHistory(chatHistory),
}),
@ -203,13 +227,13 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
});
const actualSelectedSpaces = selectedSpaces.map(
(space) => spaces.find((s) => s.id === space)?.title ?? '',
(space) => spaces.find((s) => s.id === space)?.title ?? "",
);
const response = await fetch(
`/api/chat?q=${_value}&spaces=${actualSelectedSpaces.join(',')}`,
`/api/chat?q=${_value}&spaces=${actualSelectedSpaces.join(",")}`,
{
method: 'POST',
method: "POST",
body: JSON.stringify({
chatHistory: modifyChatHistory(chatHistory),
}),
@ -223,15 +247,15 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
if (response.body) {
let reader = response.body?.getReader();
let decoder = new TextDecoder('utf-8');
let result = '';
let decoder = new TextDecoder("utf-8");
let result = "";
// @ts-ignore
reader.read().then(function processText({ done, value }) {
if (done) {
setIsAiLoading(false);
setToBeParsed('');
setValue('');
setToBeParsed("");
setValue("");
return;
}
@ -243,14 +267,14 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
};
const onSend = async () => {
setLayout('chat');
setLayout("chat");
await getSearchResults();
};
return (
<>
<AnimatePresence mode="wait">
{layout === 'chat' ? (
{layout === "chat" ? (
<Chat
key="chat"
isLoading={isAiLoading}
@ -266,7 +290,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
ref={main}
className={cn(
"sidebar flex w-full flex-col items-end justify-center gap-5 px-5 pt-5 transition-[padding-left,padding-top,padding-right] delay-200 duration-200 md:items-center md:gap-10 md:px-72 [&[data-sidebar-open='true']]:pr-10 [&[data-sidebar-open='true']]:delay-0 md:[&[data-sidebar-open='true']]:pl-[calc(2.5rem+30vw)]",
hide ? '' : 'main-hidden',
hide ? "" : "main-hidden",
)}
>
<h1 className="text-rgray-11 mt-auto w-full text-center text-3xl md:mt-0">
@ -280,19 +304,19 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
y: 50,
}}
transition={{
type: 'tween',
type: "tween",
duration: 0.2,
}}
textAreaProps={{
placeholder: 'Ask your SuperMemory...',
placeholder: "Ask your SuperMemory...",
className:
'h-auto overflow-auto md:h-full md:resize-none text-lg py-0 px-2 pt-2 md:py-0 md:p-5 resize-y text-rgray-11 w-full min-h-[1em]',
"h-auto overflow-auto md:h-full md:resize-none text-lg py-0 px-2 pt-2 md:py-0 md:p-5 resize-y text-rgray-11 w-full min-h-[1em]",
value,
autoFocus: true,
onChange: (e) => setValue(e.target.value),
onKeyDown: (e) => {
console.log(e.key, e.ctrlKey, e.metaKey);
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
onSend();
}
},
@ -301,7 +325,7 @@ export default function Main({ sidebarOpen }: { sidebarOpen: boolean }) {
<div className="text-rgray-11/70 flex h-full w-fit items-center justify-center pl-0 md:w-full md:p-2">
<FilterCombobox
onClose={() => {
textArea.current?.querySelector('textarea')?.focus();
textArea.current?.querySelector("textarea")?.focus();
}}
className="hidden md:flex"
selectedSpaces={selectedSpaces}
@ -355,7 +379,7 @@ export function Chat({
"sidebar relative flex w-full flex-col items-end gap-5 px-5 pt-5 transition-[padding-left,padding-top,padding-right] delay-200 duration-200 md:items-center md:gap-10 md:px-72 [&[data-sidebar-open='true']]:pr-10 [&[data-sidebar-open='true']]:delay-0 md:[&[data-sidebar-open='true']]:pl-[calc(2.5rem+30vw)]",
)}
>
<div className="scrollbar-none flex max-h-screen w-full flex-col overflow-y-auto px-5">
<div className="scrollbar-none h-screen w-full overflow-y-auto px-5">
{chatHistory.map((msg, i) => (
<ChatMessage index={i} key={i} isLast={i === chatHistory.length - 1}>
<ChatQuestion>{msg.question}</ChatQuestion>
@ -363,7 +387,7 @@ export function Chat({
loading={i === chatHistory.length - 1 ? isLoading : false}
sources={msg.answer.sources}
>
{msg.answer.parts.map((part) => part.text).join(' ')}
{msg.answer.parts.map((part) => part.text).join(" ")}
</ChatAnswer>
</ChatMessage>
))}
@ -376,7 +400,7 @@ export function Chat({
<div className="animate-from-top fixed bottom-10 mt-auto flex w-[50%] flex-col items-start justify-center gap-2">
<FilterCombobox
onClose={() => {
textArea.current?.querySelector('textarea')?.focus();
textArea.current?.querySelector("textarea")?.focus();
}}
side="top"
align="start"
@ -389,15 +413,15 @@ export function Chat({
ref={textArea}
className="bg-rgray-2 h-auto w-full flex-row items-start justify-center overflow-auto px-3 md:items-center md:justify-center"
textAreaProps={{
placeholder: 'Ask your SuperMemory...',
placeholder: "Ask your SuperMemory...",
className:
'overflow-auto h-auto p-3 md:resize-none text-lg w-auto resize-y text-rgray-11 w-full',
"overflow-auto h-auto p-3 md:resize-none text-lg w-auto resize-y text-rgray-11 w-full",
value,
rows: 1,
autoFocus: true,
onChange: onValueChange,
onKeyDown: (e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
askQuestion();
}
},