backend / frontend /src /components /chat /ChatMain.jsx
muhammadhasnain100's picture
add code
49f22ac
Raw History Blame Contribute Delete
25 kB
import { forwardRef, useEffect, useRef, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import ComsatsLogo from '../ComsatsLogo'
import { MessageRoleSticker } from './MessageRoleSticker'
function AssistantAvatarIcon({ className = '' }) {
return (
<svg
className={className}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
aria-hidden
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
/>
</svg>
)
}
function SendIcon({ className = '' }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
<path d="M3.478 2.404a.75.75 0 00-.926.941l2.432 7.905H13.5a.75.75 0 010 1.5H4.984l-2.432 7.905a.75.75 0 00.926.94 60.519 60.519 0 0018.445-8.986.75.75 0 000-1.218A60.517 60.517 0 003.478 2.404z" />
</svg>
)
}
function DotsVerticalIcon({ className = '' }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
<circle cx="12" cy="6" r="1.75" />
<circle cx="12" cy="12" r="1.75" />
<circle cx="12" cy="18" r="1.75" />
</svg>
)
}
function CheckMiniIcon({ className = '' }) {
return (
<svg className={className} viewBox="0 0 20 20" fill="currentColor" aria-hidden>
<path
fillRule="evenodd"
d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
clipRule="evenodd"
/>
</svg>
)
}
function SparklesIcon({ className = '' }) {
return (
<svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
<path d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z" />
</svg>
)
}
function MarkdownText({ content, tone = 'assistant' }) {
const linkClass =
tone === 'user'
? 'underline decoration-white/60 hover:decoration-white'
: 'font-medium text-comsats-blue underline decoration-comsats-blue/25 underline-offset-2 hover:text-comsats-purple'
const codeBg =
tone === 'user' ? 'bg-white/20 text-white' : 'bg-slate-100 text-slate-900 ring-1 ring-slate-200/80'
const codeBlockBg =
tone === 'user' ? 'bg-black/25 text-white' : 'bg-slate-50 text-slate-900 ring-1 ring-slate-200/90'
return (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
p: ({ children }) => (
<p className="m-0 whitespace-pre-wrap text-[15px] leading-[1.65] [&:not(:first-child)]:mt-3">
{children}
</p>
),
ul: ({ children }) => <ul className="my-3 list-disc space-y-1.5 pl-5 text-[15px] leading-relaxed">{children}</ul>,
ol: ({ children }) => <ol className="my-3 list-decimal space-y-1.5 pl-5 text-[15px] leading-relaxed">{children}</ol>,
li: ({ children }) => <li className="leading-relaxed">{children}</li>,
a: ({ href, children }) => (
<a href={href} target="_blank" rel="noopener noreferrer" className={linkClass}>
{children}
</a>
),
strong: ({ children }) => (
<strong
className={
tone === 'user' ? 'font-semibold text-white' : 'font-semibold text-slate-900'
}
>
{children}
</strong>
),
code: ({ inline, children }) =>
inline ? (
<code className={`rounded-md px-1.5 py-0.5 text-[0.88em] ${codeBg}`}>{children}</code>
) : (
<code className={`block overflow-x-auto rounded-xl p-4 text-[13px] leading-relaxed ${codeBlockBg}`}>
{children}
</code>
),
}}
>
{content ?? ''}
</ReactMarkdown>
)
}
const EMPTY_THREAD_STARTERS = [
'What programs are offered at CUI Attock?',
'How do I apply for admissions?',
'Tell me about campus facilities and fees.',
]
const ChatMain = forwardRef(function ChatMain(
{
chatId,
chatTitle = 'Conversation',
turns,
loadingChat,
loadingOlder,
hasOlder,
onLoadOlder,
sending,
tailBump,
error,
question,
setQuestion,
onSend,
followUpSuggestions = [],
suggestionsEnabled = true,
onSuggestionsEnabledChange,
webSearchEnabled = false,
onWebSearchEnabledChange,
onPickFollowUp,
sidebarExpanded = true,
collapsedSidebarRail = false,
onOpenSidebar = () => {},
},
scrollRef,
) {
const [sourceMenuOpen, setSourceMenuOpen] = useState(false)
const sourceMenuWrapRef = useRef(null)
useEffect(() => {
if (!sourceMenuOpen) return
function handlePointerDown(e) {
const el = sourceMenuWrapRef.current
if (el && !el.contains(e.target)) setSourceMenuOpen(false)
}
function handleKey(e) {
if (e.key === 'Escape') setSourceMenuOpen(false)
}
document.addEventListener('mousedown', handlePointerDown)
window.addEventListener('keydown', handleKey)
return () => {
document.removeEventListener('mousedown', handlePointerDown)
window.removeEventListener('keydown', handleKey)
}
}, [sourceMenuOpen])
useEffect(() => {
if (!chatId || loadingChat) return
const el = scrollRef?.current
if (!el) return
const scrollToEnd = () => {
el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' })
}
requestAnimationFrame(() => {
requestAnimationFrame(scrollToEnd)
})
}, [chatId, loadingChat, tailBump])
const showHeaderOpenSidebar =
!sidebarExpanded && !collapsedSidebarRail
const headerTools = (
<div className="flex w-full shrink-0 flex-wrap items-center justify-end gap-2 sm:w-auto sm:gap-3">
<div className="flex items-center gap-2 rounded-full bg-slate-50 px-2 py-1 ring-1 ring-slate-200/70">
<span className="hidden text-[11px] font-medium text-slate-500 sm:inline">Follow-ups</span>
<button
type="button"
role="switch"
aria-checked={suggestionsEnabled}
title={suggestionsEnabled ? 'Follow-up ideas on' : 'Follow-up ideas off'}
onClick={() => onSuggestionsEnabledChange?.(!suggestionsEnabled)}
className={`relative h-7 w-11 shrink-0 rounded-full transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-2 ${
suggestionsEnabled ? 'bg-comsats-purple' : 'bg-slate-300'
}`}
>
<span
className={`absolute top-0.5 left-0.5 h-6 w-6 rounded-full bg-white shadow transition-transform duration-200 ease-out ${
suggestionsEnabled ? 'translate-x-[1.125rem]' : 'translate-x-0'
}`}
/>
</button>
</div>
</div>
)
if (!chatId) {
return (
<main className="relative flex min-h-0 flex-1 flex-col bg-gradient-to-b from-slate-50 via-chat-canvas to-slate-100/80">
<header className="flex h-14 shrink-0 items-center gap-3 border-b border-slate-200/60 bg-white/80 px-3 backdrop-blur-md md:hidden">
{showHeaderOpenSidebar ? (
<button
type="button"
onClick={() => onOpenSidebar()}
className="flex shrink-0 rounded-xl bg-white p-0.5 shadow-sm ring-1 ring-slate-200/80 transition-shadow hover:ring-comsats-purple/25"
aria-label="Open sidebar"
>
<ComsatsLogo className="h-9 w-9" />
</button>
) : null}
<span className="min-w-0 truncate text-sm font-semibold text-slate-800">CUI Connect</span>
</header>
<div className="flex flex-1 flex-col items-center justify-center px-4 py-12 text-center">
<div className="mx-auto max-w-md rounded-3xl border border-white/80 bg-white/90 p-8 shadow-[0_20px_60px_-24px_rgba(75,46,131,0.35)] ring-1 ring-slate-200/60 backdrop-blur-sm">
<div
className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-comsats-purple/12 to-comsats-blue/15 text-comsats-purple shadow-inner"
aria-hidden
>
<AssistantAvatarIcon className="h-8 w-8" />
</div>
<h1 className="text-2xl font-semibold tracking-tight text-slate-900">CUI Connect</h1>
<p className="mt-3 text-[15px] leading-relaxed text-slate-600">
Open the sidebar to pick a chat or start fresh — admissions, programs, and campus questions
welcome.
</p>
</div>
</div>
</main>
)
}
const showEmptyWelcome = !loadingChat && turns.length === 0 && !sending
return (
<main className="flex min-h-0 flex-1 flex-col overflow-hidden bg-gradient-to-b from-slate-50/95 via-chat-canvas to-slate-100/70">
<header
className="flex min-h-[3.25rem] shrink-0 flex-col gap-2 border-b border-slate-200/60 bg-white/85 px-3 py-2 shadow-[0_1px_0_rgba(0,0,0,0.03)] backdrop-blur-md sm:min-h-14 sm:flex-row sm:items-center sm:gap-x-3 md:flex-wrap md:px-6 md:py-2.5"
title={chatId ? `Technical ID (support): ${chatId}` : undefined}
>
{showHeaderOpenSidebar ? (
<button
type="button"
onClick={() => onOpenSidebar()}
className="flex shrink-0 rounded-xl bg-white p-0.5 shadow-md shadow-slate-900/5 ring-1 ring-slate-200/90 transition-all hover:ring-comsats-purple/30 hover:shadow-comsats-purple/10"
aria-label="Open sidebar"
>
<ComsatsLogo className="h-9 w-9 md:h-10 md:w-10" />
</button>
) : null}
<div className="flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
<div className="min-w-0 flex-1">
<h2 className="line-clamp-2 text-[15px] font-semibold leading-snug text-slate-900 sm:line-clamp-2 md:line-clamp-1">
{chatTitle}
</h2>
<p className="mt-0.5 text-[11px] text-slate-500 sm:text-[12px]">
<span className="font-medium text-comsats-purple/90">CUI Connect</span>
<span className="mx-1.5 text-slate-300">·</span>
Knowledge assistant
</p>
</div>
{headerTools}
</div>
</header>
<div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto">
{loadingChat ? (
<div className="flex flex-col items-center justify-center gap-3 py-24">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-comsats-purple/20 border-t-comsats-purple" />
<p className="text-[14px] font-medium text-slate-500">Loading messages…</p>
</div>
) : (
<div className="mx-auto w-full max-w-[min(100%,56rem)] pb-4 pt-2 sm:pb-5 md:pb-6 md:pt-4">
{hasOlder ? (
<div className="mb-6 flex justify-center px-4">
<button
type="button"
disabled={loadingOlder}
onClick={onLoadOlder}
className="rounded-full border border-slate-200/90 bg-white px-5 py-2 text-[13px] font-medium text-comsats-purple shadow-sm transition-all hover:border-comsats-purple/25 hover:bg-comsats-purple/[0.04] hover:shadow disabled:opacity-50"
>
{loadingOlder ? 'Loading older…' : 'Load older messages'}
</button>
</div>
) : null}
{showEmptyWelcome ? (
<div className="flex flex-col items-center px-3 py-10 text-center sm:px-5 sm:py-14 md:py-20">
<div className="mb-6 flex h-[4.5rem] w-[4.5rem] items-center justify-center rounded-3xl bg-white shadow-[0_12px_40px_-16px_rgba(0,94,184,0.35)] ring-1 ring-comsats-blue/15">
<SparklesIcon className="h-9 w-9 text-comsats-blue" />
</div>
<p className="max-w-xl text-2xl font-semibold tracking-tight text-slate-900 md:text-[1.65rem]">
What would you like to know?
</p>
<p className="mt-3 max-w-lg text-[15px] leading-relaxed text-slate-600">
I can help with programs, admissions, fees, and campus life. After you open a chat,
use the <span className="font-semibold text-slate-700">⋯</span> menu next to the
message box to choose{' '}
<span className="font-semibold text-comsats-purple">RAG</span> (knowledge base) or{' '}
<span className="font-semibold text-comsats-blue">Web search</span>.
</p>
<p className="mt-10 text-[12px] font-semibold uppercase tracking-[0.12em] text-slate-400">
Try one of these
</p>
<div className="mt-4 grid w-full max-w-xl gap-3">
{EMPTY_THREAD_STARTERS.map((s) => (
<button
key={s}
type="button"
onClick={() => onPickFollowUp?.(s)}
className="group rounded-2xl border border-slate-200/90 bg-white px-5 py-4 text-left text-[15px] font-medium text-slate-800 shadow-[0_2px_8px_rgba(0,0,0,0.04)] ring-1 ring-white transition-all hover:-translate-y-0.5 hover:border-comsats-purple/30 hover:shadow-[0_12px_28px_-12px_rgba(75,46,131,0.25)]"
dir="auto"
>
<span className="flex items-start gap-3">
<span className="mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-comsats-purple/10 text-comsats-purple transition-colors group-hover:bg-comsats-purple group-hover:text-white">
<SparklesIcon className="h-3.5 w-3.5" />
</span>
<span className="leading-snug">{s}</span>
</span>
</button>
))}
</div>
</div>
) : null}
<div className="flex flex-col divide-y divide-slate-200/50">
{turns.map((turn) => {
const key =
turn.clientKey != null ? turn.clientKey : `pair-${turn.pairIndex ?? 'x'}`
return (
<article key={key} className="first:pt-0">
<div className="space-y-4 px-3 py-5 sm:space-y-5 sm:px-5 md:space-y-6 md:px-8 md:py-8">
<div className="flex justify-end">
<div className="flex max-w-[min(100%,min(92vw,36rem))] items-end gap-2 sm:gap-3">
<div
className="min-w-0 rounded-[1.35rem] rounded-br-lg bg-gradient-to-br from-comsats-purple to-[#3d2469] px-4 py-3 text-[14px] leading-relaxed text-white shadow-lg shadow-comsats-purple/25 ring-1 ring-white/15 sm:px-[18px] sm:py-3.5 sm:text-[15px]"
dir="auto"
>
<span className="sr-only">You: </span>
<MarkdownText content={turn.question} tone="user" />
</div>
<MessageRoleSticker role="user" />
</div>
</div>
<div className="flex items-start gap-2 sm:gap-3 md:gap-4">
<MessageRoleSticker role="assistant" />
<div
className="min-w-0 flex-1 rounded-2xl bg-white px-4 py-4 shadow-[0_2px_12px_rgba(0,0,0,0.05)] ring-1 ring-slate-200/70 md:rounded-[1.35rem] md:px-6 md:py-5"
dir="auto"
>
<span className="sr-only">Assistant: </span>
{turn.pending ? (
<span className="inline-flex items-center gap-2.5 text-[15px] text-slate-500">
<span className="inline-flex gap-1">
<span className="h-2 w-2 animate-bounce rounded-full bg-comsats-blue [animation-delay:-0.3s]" />
<span className="h-2 w-2 animate-bounce rounded-full bg-comsats-blue [animation-delay:-0.15s]" />
<span className="h-2 w-2 animate-bounce rounded-full bg-comsats-blue" />
</span>
Thinking…
</span>
) : (
<div className="text-slate-800">
<MarkdownText content={turn.answer} tone="assistant" />
</div>
)}
</div>
</div>
</div>
</article>
)
})}
</div>
</div>
)}
</div>
{error ? (
<div className="border-t border-red-200/80 bg-red-50 px-4 py-2.5 text-center text-[13px] font-medium text-red-800">
{error}
</div>
) : null}
<footer className="relative shrink-0 border-t border-slate-200/60 bg-gradient-to-t from-white via-white to-slate-50/90 pb-[max(0.5rem,env(safe-area-inset-bottom))] shadow-[0_-8px_30px_rgba(0,0,0,0.04)]">
{suggestionsEnabled && followUpSuggestions.length > 0 && !sending ? (
<div className="border-b border-slate-100/90 bg-white/60 px-2 py-2 sm:px-4 md:px-6">
<div className="mx-auto flex max-w-[min(100%,56rem)] items-center gap-2">
<span className="flex shrink-0 items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-slate-400">
<SparklesIcon className="h-3.5 w-3.5 text-comsats-purple" aria-hidden />
Ideas
</span>
<div className="no-scrollbar flex min-w-0 flex-1 gap-2 overflow-x-auto py-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{followUpSuggestions.map((s, i) => (
<button
key={`${i}-${s.slice(0, 24)}`}
type="button"
onClick={() => onPickFollowUp?.(s)}
className="max-w-[min(85vw,20rem)] shrink-0 rounded-full border border-slate-200/90 bg-white px-3 py-1.5 text-left text-[11px] font-medium leading-snug text-slate-800 shadow-sm ring-slate-900/[0.02] transition-colors hover:border-comsats-purple/35 hover:bg-comsats-purple/[0.04] sm:max-w-xs sm:text-xs md:text-[13px]"
dir="auto"
title={s}
>
<span className="line-clamp-2">{s}</span>
</button>
))}
</div>
</div>
<p className="sr-only">Suggested follow-up questions; swipe sideways or tap one.</p>
</div>
) : null}
<div className="mx-auto max-w-[min(100%,56rem)] px-3 pb-4 pt-3 sm:px-5 sm:pb-5 sm:pt-4 md:px-8 md:pb-6 md:pt-5">
<div className="mb-2 flex flex-wrap items-center gap-2 px-0.5">
<span className="text-[11px] font-medium text-slate-500">Answer source</span>
<span
className={`inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold uppercase tracking-wide ring-1 ${
webSearchEnabled
? 'bg-comsats-blue/12 text-comsats-blue ring-comsats-blue/25'
: 'bg-comsats-purple/12 text-comsats-purple ring-comsats-purple/25'
}`}
>
{webSearchEnabled ? 'Web search' : 'RAG'}
</span>
</div>
<form
onSubmit={(e) => {
e.preventDefault()
onSend()
}}
className="relative flex items-end gap-1 rounded-[28px] border border-slate-200/90 bg-white px-2 py-2 shadow-[0_4px_24px_rgba(0,0,0,0.06)] ring-slate-900/[0.02] transition-[border-color,box-shadow] focus-within:border-comsats-blue/40 focus-within:shadow-[0_8px_32px_-8px_rgba(0,94,184,0.22)] focus-within:ring-2 focus-within:ring-comsats-blue/18 sm:gap-2 sm:px-3 sm:py-2.5"
>
<label htmlFor="chat-composer" className="sr-only">
Message
</label>
<div ref={sourceMenuWrapRef} className="relative shrink-0 self-end pb-1">
<button
type="button"
aria-expanded={sourceMenuOpen}
aria-haspopup="menu"
aria-label="Choose answer source: RAG or Web search"
onClick={() => setSourceMenuOpen((o) => !o)}
className="flex h-10 w-10 items-center justify-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-comsats-purple focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-1"
>
<DotsVerticalIcon className="h-5 w-5" />
</button>
{sourceMenuOpen ? (
<div
role="menu"
className="absolute bottom-[calc(100%+6px)] left-0 z-40 w-[min(calc(100vw-2rem),14rem)] rounded-xl border border-slate-200/90 bg-white py-1 shadow-[0_12px_40px_-12px_rgba(0,0,0,0.25)] ring-1 ring-slate-900/5"
>
<button
type="button"
role="menuitemradio"
aria-checked={!webSearchEnabled}
className="flex w-full items-center gap-2 px-3 py-2.5 text-left text-[13px] font-medium text-slate-800 hover:bg-slate-50"
onClick={() => {
onWebSearchEnabledChange?.(false)
setSourceMenuOpen(false)
}}
>
<span className="flex w-5 shrink-0 justify-center text-comsats-purple">
{!webSearchEnabled ? <CheckMiniIcon className="h-4 w-4" /> : null}
</span>
Knowledge base (RAG)
</button>
<button
type="button"
role="menuitemradio"
aria-checked={webSearchEnabled}
className="flex w-full items-center gap-2 px-3 py-2.5 text-left text-[13px] font-medium text-slate-800 hover:bg-slate-50"
onClick={() => {
onWebSearchEnabledChange?.(true)
setSourceMenuOpen(false)
}}
>
<span className="flex w-5 shrink-0 justify-center text-comsats-blue">
{webSearchEnabled ? <CheckMiniIcon className="h-4 w-4" /> : null}
</span>
Web search
</button>
</div>
) : null}
</div>
<textarea
id="chat-composer"
rows={1}
value={question}
onChange={(e) => setQuestion(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
if (!sending && question.trim()) onSend()
}
}}
placeholder="Ask anything about CUI Attock…"
disabled={sending}
className="max-h-44 min-h-[48px] min-w-0 flex-1 resize-none bg-transparent py-2.5 pr-1 text-[15px] leading-snug text-slate-900 outline-none placeholder:text-slate-400 disabled:opacity-60"
dir="auto"
/>
<button
type="submit"
disabled={sending || !question.trim()}
className="mb-0.5 flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-comsats-blue to-[#004a94] text-white shadow-md shadow-comsats-blue/25 transition-all hover:from-comsats-purple hover:to-comsats-purple hover:shadow-lg hover:shadow-comsats-purple/25 disabled:opacity-35 disabled:shadow-none"
aria-label="Send message"
>
<SendIcon className="h-[19px] w-[19px] -translate-y-px translate-x-px" />
</button>
</form>
<p className="mt-3 text-center text-[11px] leading-relaxed text-slate-400">
Answers are generated by AI — double-check important details with official CUI sources.
</p>
</div>
</footer>
</main>
)
})
export default ChatMain