Spaces:
Sleeping
Sleeping
add: doc for iframe integration
Browse filesFiles changed (5)
- README.md+372
- app/Http/Controllers/Controller.phpAdded+5
- pnpm-lock.yamlAdded
- resources/css/app.css+63-12
- resources/js/pages/embed.tsx+174-69
8 unmodified lines910118 unmodified lines---# CAPS04 FE REFACTOR8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823838 unmodified lines---# CAPS04 FE REFACTOR---## Embed Widget — Integration GuideRAG Hub menyediakan widget chat berbasis `<iframe>` yang dapat diintegrasikan ke situs web pihak ketiga manapun. Widget ini mendukung autentikasi berbasis API Key, kustomisasi tampilan penuh melalui query string, serta komunikasi dua arah dengan halaman induk melalui `postMessage`.---### Table of Contents1. [Quick Start](#1-quick-start)2. [Authentication](#2-authentication)3. [URL Parameters Reference](#3-url-parameters-reference)4. [Theming & Customization](#4-theming--customization)5. [Chat Mode](#5-chat-mode)6. [postMessage Events](#6-postmessage-events)7. [Session Persistence](#7-session-persistence)8. [Full Integration Examples](#8-full-integration-examples)9. [Troubleshooting](#9-troubleshooting)---### 1. Quick StartTambahkan `<iframe>` berikut ke halaman HTML Anda:```html<iframesrc="https://your-raghub-domain.com/embed?api_key=YOUR_API_KEY"width="420"height="680"style="border: none; border-radius: 16px;"allow="clipboard-write"></iframe>```Ganti `YOUR_API_KEY` dengan API Key yang digenerate dari halaman **Admin → API Keys**.---### 2. AuthenticationWidget mendukung dua metode autentikasi. Pilih salah satu sesuai kebutuhan.#### 2.1 API Key (Direkomendasikan)Gunakan parameter `api_key`. Widget akan secara otomatis menukar API Key dengan bearer token melalui endpoint `/auth/login/api-key` saat pertama kali dimuat.```/embed?api_key=sk-xxxxxxxxxxxxxxxx```Token hasil login disimpan di `sessionStorage` browser sehingga tidak perlu login ulang selama sesi tab masih aktif.> **Keamanan:** API Key sebaiknya tidak di-hardcode langsung di HTML publik. Untuk lingkungan produksi, generate token di sisi server lalu teruskan lewat metode **Direct Token** (lihat 2.2).#### 2.2 Direct TokenJika server Anda sudah memiliki bearer token yang valid, teruskan langsung melalui parameter `token`:```/embed?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...```Token akan langsung disimpan ke `sessionStorage` dan digunakan untuk semua request selanjutnya.#### Token Resolution PriorityWidget menyelesaikan autentikasi dengan urutan berikut:1. Cek `sessionStorage` — jika token sudah tersimpan dari sesi sebelumnya, langsung digunakan.2. Cek parameter `?token` di URL.3. Cek parameter `?api_key` di URL, lalu tukar dengan token via API.4. Jika tidak ada ketiganya → widget menampilkan pesan error autentikasi.---### 3. URL Parameters ReferenceSemua konfigurasi dilakukan melalui query string pada URL `src` iframe.#### 3.1 Authentication| Parameter | Tipe | Keterangan ||-----------|----------|------------|| `api_key` | `string` | API Key dari Admin Panel. Widget otomatis login dan menyimpan token. || `token` | `string` | Bearer token langsung. Digunakan jika server sudah generate token sendiri. |#### 3.2 Behavior| Parameter | Tipe | Default | Keterangan ||--------------|----------|---------|------------|| `course_id` | `string` | — | Pra-pilih mata kuliah tertentu. Widget langsung menggunakan course ini tanpa perlu user memilih. || `session_id` | `string` | — | Buka riwayat sesi chat tertentu langsung saat widget dimuat. || `user_name` | `string` | `User` | Nama yang ditampilkan di greeting ("Good Morning, ..."). Jika tidak diisi, diambil dari data user saat login via `api_key`. |#### 3.3 Appearance| Parameter | Tipe | Default | Keterangan ||--------------|----------|---------|------------|| `title` | `string` | `RAG Hub` | Judul widget (tab browser & empty state). || `subtitle` | `string` | *(default text)* | Teks deskripsi di bawah judul pada empty state. |---### 4. Theming & CustomizationSemua warna dikustomisasi via query string. Format nilai warna: hex 3-digit (`#fff`) atau 6-digit (`#ffffff`), dengan atau tanpa `#` di depan.Format radius: nilai numerik diikuti unit `px` atau `rem` (maks. 2 digit), contoh: `20px`, `1rem`.| Parameter | Default | Keterangan ||----------------------|-------------|------------|| `primary` | `#2764eb` | Warna utama — tombol kirim, avatar asisten, border composer. || `primary_gradient` | `#ccdcff` | Warna lembut primary — background avatar user & aksen gradient. || `background` | `#ffffff` | Background utama widget. || `background_profile` | `#ffffff` | Background bubble chat asisten dan composer. || `text_primary` | `#0a0a0a` | Warna teks utama. || `text_secondary` | `#737373` | Warna teks sekunder / placeholder. || `border` | `#739af1` | Warna border composer dan bubble. || `logout` | `#ef4444` | Warna aksi destruktif (tombol hapus sesi). || `radius` | `20px` | Border radius bubble chat dan composer. |**Contoh URL dengan tema gelap:**```/embed?api_key=YOUR_KEY&background=1a1a2e&background_profile=16213e&text_primary=e0e0e0&text_secondary=8892b0&primary=4f8ef7&primary_gradient=1e3a6e&border=2a3f6f&logout=ff6b6b&radius=16px```---### 5. Chat ModeChat mode dikonfigurasi di sisi **server** (bukan via URL), melalui environment variable `RAG_CHAT_MODE`.| Mode | Keterangan ||------------|------------|| `standard` | *(default)* Chat berbasis sesi. Riwayat percakapan tersimpan dan bisa diakses kembali via tab Riwayat. || `direct` | Setiap pesan dikirim langsung ke endpoint `/ai/query` tanpa membuat sesi. Cocok untuk one-shot Q&A tanpa history. |Atur di file `.env`:```envRAG_CHAT_MODE=direct```---### 6. postMessage EventsWidget berkomunikasi dengan halaman induk melalui `window.postMessage`. Dengarkan event ini di halaman yang meng-embed iframe untuk mendapat notifikasi dari widget.#### 6.1 Events yang Dikirim Widget (Outbound)| Event type | Kapan dikirim ||-----------------------------|---------------|| `sevima-raghub:close` | User menekan tombol **✕** di sudut kanan atas widget. |**Contoh listener di halaman induk:**```javascriptwindow.addEventListener('message', (event) => {// Selalu validasi origin di produksiif (event.origin !== 'https://your-raghub-domain.com') return;if (event.data?.type === 'sevima-raghub:close') {// Sembunyikan atau hancurkan iframedocument.getElementById('raghub-iframe').style.display = 'none';}});```---### 7. Session PersistenceWidget menyimpan data sesi di `sessionStorage` browser (bukan `localStorage`), sehingga **otomatis terhapus saat tab ditutup**.| Key | Isi ||------------------------------|-----|| `sevima_raghub_embed_token` | Bearer token aktif. || `sevima_raghub_embed_user` | Objek user JSON (`id`, `name`, `email`, `role`). |Karena berbasis `sessionStorage` pada iframe, data ini terisolasi dan tidak dapat diakses oleh halaman induk.Untuk memaksa sesi baru (logout), reload iframe atau hapus `sessionStorage` dari dalam iframe.---### 8. Full Integration Examples#### 8.1 Embed Sederhana (API Key)```html<!DOCTYPE html><html lang="id"><head><meta charset="UTF-8" /><title>My App</title></head><body><iframeid="raghub-widget"src="https://your-raghub-domain.com/embed?api_key=sk-xxxx&user_name=Budi&title=Asisten+Akademik"width="420"height="680"style="border: none; border-radius: 20px; box-shadow: 0 8px 32px rgba(0,0,0,0.15);"allow="clipboard-write"></iframe><script>window.addEventListener('message', (event) => {if (event.origin !== 'https://your-raghub-domain.com') return;if (event.data?.type === 'sevima-raghub:close') {document.getElementById('raghub-widget').style.display = 'none';}});</script></body></html>```#### 8.2 Floating Chat Button```html<style>#raghub-fab {position: fixed;bottom: 24px;right: 24px;width: 56px;height: 56px;border-radius: 50%;background: #2764eb;border: none;cursor: pointer;color: #fff;font-size: 24px;box-shadow: 0 4px 16px rgba(39,100,235,0.4);z-index: 1000;}#raghub-container {display: none;position: fixed;bottom: 96px;right: 24px;width: 420px;height: 680px;z-index: 1000;border-radius: 20px;overflow: hidden;box-shadow: 0 12px 48px rgba(0,0,0,0.2);}#raghub-container iframe {width: 100%;height: 100%;border: none;}</style><button id="raghub-fab" onclick="toggleWidget()">💬</button><div id="raghub-container"><iframeid="raghub-iframe"src="https://your-raghub-domain.com/embed?api_key=sk-xxxx&primary=2764eb&radius=16px"allow="clipboard-write"></iframe></div><script>function toggleWidget() {const container = document.getElementById('raghub-container');container.style.display = container.style.display === 'none' ? 'block' : 'none';}window.addEventListener('message', (event) => {if (event.origin !== 'https://your-raghub-domain.com') return;if (event.data?.type === 'sevima-raghub:close') {document.getElementById('raghub-container').style.display = 'none';}});</script>```#### 8.3 Pra-pilih Mata Kuliah & Langsung ke Sesi Tertentu```html<iframesrc="https://your-raghub-domain.com/embed?api_key=sk-xxxx&course_id=COURSE_UUID&session_id=SESSION_UUID&user_name=Mahasiswa+A"width="420"height="680"style="border: none; border-radius: 20px;"></iframe>```#### 8.4 Token dari Server (Lebih Aman untuk Produksi)Alur yang direkomendasikan untuk produksi: server Anda meminta token ke RAG Hub API menggunakan API Key, lalu meneruskan token tersebut ke frontend.```javascript// server-side (Node.js / PHP / Python, dll.)const response = await fetch('https://your-raghub-domain.com/api/auth/login/api-key', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ api_key: process.env.RAG_API_KEY }),});const { token } = await response.json();// Render ke template HTMLconst iframeSrc = `https://your-raghub-domain.com/embed?token=${token}&user_name=${userName}`;``````html<!-- HTML yang dirender server --><iframe src="{{ iframeSrc }}" width="420" height="680" style="border:none;"></iframe>```---### 9. Troubleshooting#### Widget menampilkan "Token iframe tidak tersedia"Pastikan salah satu dari berikut ada di URL:- `?api_key=` — API Key valid dari Admin Panel.- `?token=` — Bearer token yang belum expired.Jika menggunakan `api_key`, pastikan key tersebut masih aktif dan belum direvoke.#### Mata kuliah tidak muncul di dropdownPastikan akun yang terkait dengan `api_key` memiliki akses ke setidaknya satu course. Periksa di Admin Panel bahwa course sudah berstatus **active**.#### Widget tidak merespons tombol ✕ di halaman indukPastikan listener `message` event sudah terpasang sebelum iframe dimuat, dan validasi `event.origin` sesuai domain RAG Hub.#### Token expired di tengah sesiWidget tidak melakukan refresh token otomatis. Jika token expired, reload iframe dengan token baru:```javascriptconst iframe = document.getElementById('raghub-iframe');iframe.src = `https://your-raghub-domain.com/embed?token=${newToken}`;```Reload iframe akan menghapus `sessionStorage`-nya dan memulai sesi baru.#### Warna tidak berubah setelah mengubah query stringPastikan nilai warna dalam format hex yang valid: 3 atau 6 digit, dengan atau tanpa `#`. Karakter selain `0-9` dan `a-f` akan diabaikan dan diganti nilai default.---
12345<?php
namespace App\Http\Controllers;
abstract class Controller {}1213 unmodified lines121412151216121712181219122012 unmodified lines123312341235123612371238123956 unmodified lines1296129712981299130013011302130313041305130613071308130913101311131224 unmodified lines133713381339134013411342134314 unmodified lines135813591360136113621363136424 unmodified lines13891390139113921393139413953 unmodified lines139914001401140214031404140517 unmodified lines14231424142514261427142814298 unmodified lines14381439144014411442144314441445144614471448144910 unmodified lines14601461146214631464146518 unmodified lines1484148514861487148814891213 unmodified lines}.embed-shell {@apply relative flex min-h-svh flex-col overflow-hidden px-6 py-5;background-color: var(--embed-bg);color: var(--embed-text);}12 unmodified lines}.embed-tabs button {@apply h-6 rounded-full px-6 text-xs font-medium transition;color: var(--embed-text);}56 unmodified lines}.embed-empty-state p {@apply mt-2 text-xs;color: var(--embed-muted);}.embed-status {@apply mt-4 text-center text-xs font-medium;color: var(--embed-danger);}.embed-thread {@apply min-h-0 flex-1 space-y-5 overflow-y-auto px-0 pt-10;padding-bottom: 11rem;}24 unmodified lines}.embed-message-bubble {@apply max-w-[min(290px,75%)] rounded-[10px] border px-4 py-3 text-xs shadow-none;background-color: var(--embed-surface);border-color: var(--embed-border);color: var(--embed-text);14 unmodified lines}.embed-message-time {@apply mt-2 block text-[10px];color: color-mix(in oklab, currentColor 68%, transparent);}24 unmodified lines}.embed-course-row {@apply flex flex-wrap items-center gap-2 text-[11px] font-bold;color: var(--embed-text);}3 unmodified lines}.embed-course-row select {@apply h-6 max-w-[210px] rounded-[5px] border px-2 text-[10px] outline-none;background-color: var(--embed-surface);border-color: var(--embed-border);color: var(--embed-text);17 unmodified lines}.embed-question-row textarea {@apply min-h-[72px] flex-1 resize-none bg-transparent text-xs outline-none;color: var(--embed-text);}8 unmodified lines}.embed-updated-at {@apply mt-2 text-center text-[10px];color: var(--embed-muted);}.embed-history {@apply flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto pt-7;}.embed-history-item {10 unmodified lines);}.embed-history-item strong {@apply block text-base font-semibold;}18 unmodified linescolor: var(--embed-muted);}.lecturer-dashboard-shell {@apply min-h-svh;background-color: var(--lecturer-bg);1213 unmodified lines121412151216121712181219122012 unmodified lines123312341235123612371238123956 unmodified lines129612971298129913001301130213031304130513061307130813091310131113121313131424 unmodified lines133913401341134213431344134514 unmodified lines136013611362136313641365136624 unmodified lines13911392139313941395139613973 unmodified lines140114021403140414051406140717 unmodified lines14251426142714281429143014318 unmodified lines1440144114421443144414451446144714481449145014511452145310 unmodified lines146414651466146714681469147018 unmodified lines14891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401213 unmodified lines}.embed-shell {@apply relative flex h-svh flex-col overflow-hidden px-6 py-5;background-color: var(--embed-bg);color: var(--embed-text);}12 unmodified lines}.embed-tabs button {@apply h-6 rounded-full px-6 text-sm font-medium transition;color: var(--embed-text);}56 unmodified lines}.embed-empty-state p {@apply mt-2 text-sm;color: var(--embed-muted);}.embed-status {@apply mt-4 text-center text-sm font-medium;color: var(--embed-danger);}.embed-thread {@apply min-h-0 flex-1 space-y-5 overflow-y-auto overscroll-contain px-0 pt-10;margin-right: -1.5rem;padding-right: 1.5rem;padding-bottom: 11rem;}24 unmodified lines}.embed-message-bubble {@apply max-w-[min(290px,75%)] rounded-[10px] border px-4 py-3 text-sm shadow-none;background-color: var(--embed-surface);border-color: var(--embed-border);color: var(--embed-text);14 unmodified lines}.embed-message-time {@apply mt-2 block text-xs;color: color-mix(in oklab, currentColor 68%, transparent);}24 unmodified lines}.embed-course-row {@apply flex flex-wrap items-center gap-2 text-sm font-bold;color: var(--embed-text);}3 unmodified lines}.embed-course-row select {@apply h-6 max-w-[210px] rounded-[5px] border px-2 text-xs outline-none;background-color: var(--embed-surface);border-color: var(--embed-border);color: var(--embed-text);17 unmodified lines}.embed-question-row textarea {@apply min-h-[72px] flex-1 resize-none bg-transparent text-sm outline-none;color: var(--embed-text);}8 unmodified lines}.embed-updated-at {@apply mt-2 text-center text-xs;color: var(--embed-muted);}.embed-history {@apply flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto overscroll-contain pt-7;margin-right: -1.5rem;padding-right: 1.5rem;}.embed-history-item {10 unmodified lines);}.embed-history-item strong {@apply block text-base font-semibold;}18 unmodified linescolor: var(--embed-muted);}.embed-modal-backdrop {@apply absolute inset-0 z-50 flex items-center justify-center p-6;background-color: color-mix(in oklab, var(--embed-text) 30%, transparent);}.embed-modal {@apply w-full max-w-xs rounded-2xl p-5 shadow-xl;background-color: var(--embed-surface);color: var(--embed-text);}.embed-modal-title {@apply mb-1 text-sm font-semibold;}.embed-modal-body {@apply mb-4 text-sm;color: var(--embed-muted);}.embed-modal-actions {@apply flex justify-end gap-2;}.embed-modal-btn {@apply rounded-full px-4 py-1.5 text-xs font-medium transition;}.embed-modal-btn--cancel {background-color: color-mix(in oklab, var(--embed-muted) 15%, transparent);color: var(--embed-text);}.embed-modal-btn--cancel:hover {background-color: color-mix(in oklab, var(--embed-muted) 25%, transparent);}.embed-modal-btn--danger {background-color: var(--embed-danger);color: #fff;}.embed-modal-btn--danger:hover {opacity: 0.88;}.lecturer-dashboard-shell {@apply min-h-svh;background-color: var(--lecturer-bg);
34 unmodified lines353637383940414243444546474849504 unmodified lines5556575859606162636465666768697018 unmodified lines89909192939495969798991001011021031047 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146200 unmodified lines34734834935035135273 unmodified lines4264274284294304318 unmodified lines4404414424434444454464474484494504514525 unmodified lines45845946046146246346446546646746846947047147247347447547647747847910 unmodified lines4904914924934944954961 unmodified line49849950050150250396 unmodified lines6006016026036046052 unmodified lines60860961061161261361461561661761861962062162262362462562662762812 unmodified lines64164264364464564634 unmodified lines68168268368468568668729 unmodified lines71771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774834 unmodified linestype EmbedConfig = {background: string;border: string;courseId?: string | null;danger: string;muted: string;primary: string;primarySoft: string;radius: string;subtitle: string;surface: string;text: string;title: string;userName: string;};4 unmodified linesconst COLOR_DEFAULTS = {background: '#ffffff',border: '#739af1',danger: '#ef4444',muted: '#737373',primary: '#2764eb',primarySoft: '#ccdcff',surface: '#ffffff',text: '#0a0a0a',} as const;const EMBED_TOKEN_KEY = 'sevima_raghub_embed_token';function parseColor(value: string | null, fallback: string): string {if (!value) {18 unmodified linesfunction parseEmbedConfig(params: URLSearchParams): EmbedConfig {return {background: parseColor(params.get('background'), COLOR_DEFAULTS.background),border: parseColor(params.get('border'), COLOR_DEFAULTS.border),courseId: params.get('course_id') ?? params.get('courseId') ?? undefined,danger: parseColor(params.get('danger'), COLOR_DEFAULTS.danger),muted: parseColor(params.get('muted'), COLOR_DEFAULTS.muted),primary: parseColor(params.get('primary'), COLOR_DEFAULTS.primary),primarySoft: parseColor(params.get('primary_soft'), COLOR_DEFAULTS.primarySoft),radius: parseRadius(params.get('radius')),subtitle: params.get('subtitle') ?? 'Pilih mata kuliah, lalu kirim pertanyaan pertama untuk membuat sesi baru',surface: parseColor(params.get('surface'), COLOR_DEFAULTS.surface),text: parseColor(params.get('text'), COLOR_DEFAULTS.text),title: params.get('title') ?? 'RAG Hub',userName: params.get('user_name') ?? 'User',};7 unmodified lines}}function storeEmbedToken(token: string): void {try {sessionStorage.setItem(EMBED_TOKEN_KEY, token);} catch {}}async function resolveEmbedToken(params: URLSearchParams): Promise<string | null> {const stored = getStoredEmbedToken();if (stored) {return stored;}const tokenParam = params.get('token');if (tokenParam) {storeEmbedToken(tokenParam);return tokenParam;}const apiKey = params.get('api_key');if (apiKey) {try {const { token } = await loginWithEmbedApiKey(apiKey);storeEmbedToken(token);return token;} catch {return null;}200 unmodified lines);}function EmbedHistory({activeSessionId,chatSessions,73 unmodified lines);const [question, setQuestion] = useState('');const [isProcessing, setIsProcessing] = useState(false);const [backendMessage, setBackendMessage] = useState<string | undefined>();const [activeTab, setActiveTab] = useState<'chat' | 'history'>('chat');const [animatedAssistantMessageId, setAnimatedAssistantMessageId] =8 unmodified linesconst rootStyle = {'--embed-bg': config.background,'--embed-border': config.border,'--embed-danger': config.danger,'--embed-muted': config.muted,'--embed-primary': config.primary,'--embed-primary-soft': config.primarySoft,'--embed-radius': config.radius,'--embed-surface': config.surface,'--embed-text': config.text,} as CSSProperties;useEffect(() => {5 unmodified linessetSelectedCourseId(parsedConfig.courseId ?? '');void (async () => {const resolvedToken = await resolveEmbedToken(params);if (!resolvedToken) {setBackendMessage('Token iframe tidak tersedia.');return;}setToken(resolvedToken);setIsAuthorized(true);try {const [coursesResult, sessionsResult] = await Promise.all([listCoursesEmbed(resolvedToken),listChatSessionsEmbed(resolvedToken,parsedConfig.courseId ?? undefined,),]);10 unmodified linessetSessionId(parsedSessionId);const historyResult = await getChatHistoryEmbed(parsedSessionId,resolvedToken,);setMessages(historyResult.data);}1 unmodified linesetBackendMessage(err instanceof Error ? err.message : 'Gagal memuat data.',);}})();}, []);96 unmodified linessetSessionId(targetSessionId);setMessages([]);setOptimisticMessages([]);try {const result = await getChatHistoryEmbed(targetSessionId, token);2 unmodified linessetBackendMessage(err instanceof Error ? err.message : 'Gagal memuat riwayat.',);}}async function handleDeleteSession(targetSessionId: string): Promise<void> {if (!token || !window.confirm('Hapus riwayat chat ini?')) {return;}try {await deleteChatSessionEmbed(targetSessionId, token);setChatSessions((prev) =>prev.filter((s) => s.uuid_id !== targetSessionId),);if (targetSessionId === sessionId) {handleNewSession();}} catch (err) {12 unmodified lines<Head title={config.title} /><main className="embed-shell" style={rootStyle}><header className="embed-toolbar"><div className="embed-tabs" role="tablist"><button34 unmodified lines</div></header>{activeTab === 'history' ? (<EmbedHistoryactiveSessionId={sessionId}chatSessions={chatSessions}29 unmodified lines</p>)}{allMessages.map((message) => (<EmbedMessagekey={message.uuid_id}message={message}shouldAnimateTyping={message.uuid_id ===animatedAssistantMessageId}/>))}{isProcessing && (<article className="embed-message embed-message--assistant"><span className="embed-message-avatar embed-message-avatar--assistant"><Bot className="size-4" /></span><div className="embed-message-bubble embed-message-bubble--typing"><LoadingIndicatorlabel="Thinking"showSpinner={false}/></div></article>)}<div ref={messagesEndRef} /></div>) : (<div className="embed-empty-state">34 unmodified lines353637383940414243444546474849504 unmodified lines5556575859606162636465666768697071727374757618 unmodified lines95969798991001011021031041051061071081091107 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167200 unmodified lines36836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041173 unmodified lines4854864874884894904914924938 unmodified lines5025035045055065075085095105115125135145 unmodified lines52052152252352452552652752852953053153253353453553653753853954054154254354454554654710 unmodified lines5585595605615625635641 unmodified line56656756856957057157257396 unmodified lines6706716726736746756762 unmodified lines67968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171212 unmodified lines72572672772872973073173273373473573673734 unmodified lines77277377477577677777877978078178278378429 unmodified lines81481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285334 unmodified linestype EmbedConfig = {background: string;backgroundProfile: string;border: string;courseId?: string | null;logout: string;primary: string;primaryGradient: string;radius: string;subtitle: string;textPrimary: string;textSecondary: string;title: string;userName: string;};4 unmodified linesconst COLOR_DEFAULTS = {background: '#ffffff',backgroundProfile: '#ffffff',border: '#739af1',logout: '#ef4444',primary: '#2764eb',primaryGradient: '#ccdcff',textPrimary: '#0a0a0a',textSecondary: '#737373',} as const;const EMBED_TOKEN_KEY = 'sevima_raghub_embed_token';const EMBED_USER_KEY = 'sevima_raghub_embed_user';type EmbedTokenResult = {token: string;user?: AuthUser;};function parseColor(value: string | null, fallback: string): string {if (!value) {18 unmodified linesfunction parseEmbedConfig(params: URLSearchParams): EmbedConfig {return {background: parseColor(params.get('background'), COLOR_DEFAULTS.background),backgroundProfile: parseColor(params.get('background_profile'), COLOR_DEFAULTS.backgroundProfile),border: parseColor(params.get('border'), COLOR_DEFAULTS.border),courseId: params.get('course_id') ?? params.get('courseId') ?? undefined,logout: parseColor(params.get('logout'), COLOR_DEFAULTS.logout),primary: parseColor(params.get('primary'), COLOR_DEFAULTS.primary),primaryGradient: parseColor(params.get('primary_gradient'), COLOR_DEFAULTS.primaryGradient),radius: parseRadius(params.get('radius')),subtitle: params.get('subtitle') ?? 'Pilih mata kuliah, lalu kirim pertanyaan pertama untuk membuat sesi baru',textPrimary: parseColor(params.get('text_primary'), COLOR_DEFAULTS.textPrimary),textSecondary: parseColor(params.get('text_secondary'), COLOR_DEFAULTS.textSecondary),title: params.get('title') ?? 'RAG Hub',userName: params.get('user_name') ?? 'User',};7 unmodified lines}}function getStoredEmbedUser(): AuthUser | null {try {const raw = sessionStorage.getItem(EMBED_USER_KEY);return raw ? (JSON.parse(raw) as AuthUser) : null;} catch {return null;}}function storeEmbedSession(token: string, user?: AuthUser): void {try {sessionStorage.setItem(EMBED_TOKEN_KEY, token);if (user) {sessionStorage.setItem(EMBED_USER_KEY, JSON.stringify(user));}} catch {}}async function resolveEmbedToken(params: URLSearchParams,): Promise<EmbedTokenResult | null> {const stored = getStoredEmbedToken();if (stored) {return { token: stored, user: getStoredEmbedUser() ?? undefined };}const tokenParam = params.get('token');if (tokenParam) {storeEmbedSession(tokenParam);return { token: tokenParam };}const apiKey = params.get('api_key');if (apiKey) {try {const { token, user } = await loginWithEmbedApiKey(apiKey);storeEmbedSession(token, user);return { token, user };} catch {return null;}200 unmodified lines);}function EmbedConfirmModal({message,onCancel,onConfirm,}: {message: string;onCancel: () => void;onConfirm: () => void;}) {return (<div className="embed-modal-backdrop" onClick={onCancel} role="dialog"><divclassName="embed-modal"onClick={(e) => e.stopPropagation()}><p className="embed-modal-title">Konfirmasi</p><p className="embed-modal-body">{message}</p><div className="embed-modal-actions"><buttonclassName="embed-modal-btn embed-modal-btn--cancel"onClick={onCancel}type="button">Batal</button><buttonclassName="embed-modal-btn embed-modal-btn--danger"onClick={onConfirm}type="button">Hapus</button></div></div></div>);}function EmbedHistory({activeSessionId,chatSessions,73 unmodified lines);const [question, setQuestion] = useState('');const [isProcessing, setIsProcessing] = useState(false);const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);const [isLoading, setIsLoading] = useState(true);const [isLoadingHistory, setIsLoadingHistory] = useState(false);const [backendMessage, setBackendMessage] = useState<string | undefined>();const [activeTab, setActiveTab] = useState<'chat' | 'history'>('chat');const [animatedAssistantMessageId, setAnimatedAssistantMessageId] =8 unmodified linesconst rootStyle = {'--embed-bg': config.background,'--embed-border': config.border,'--embed-danger': config.logout,'--embed-muted': config.textSecondary,'--embed-primary': config.primary,'--embed-primary-soft': config.primaryGradient,'--embed-radius': config.radius,'--embed-surface': config.backgroundProfile,'--embed-text': config.textPrimary,} as CSSProperties;useEffect(() => {5 unmodified linessetSelectedCourseId(parsedConfig.courseId ?? '');void (async () => {try {const resolvedToken = await resolveEmbedToken(params);if (!resolvedToken) {setBackendMessage('Token iframe tidak tersedia.');return;}const { token, user } = resolvedToken;setToken(token);setIsAuthorized(true);if (user?.name && !params.get('user_name')) {setConfig((prev: EmbedConfig) => ({ ...prev, userName: user.name as string }));}const [coursesResult, sessionsResult] = await Promise.all([listCoursesEmbed(token),listChatSessionsEmbed(token,parsedConfig.courseId ?? undefined,),]);10 unmodified linessetSessionId(parsedSessionId);const historyResult = await getChatHistoryEmbed(parsedSessionId,token,);setMessages(historyResult.data);}1 unmodified linesetBackendMessage(err instanceof Error ? err.message : 'Gagal memuat data.',);} finally {setIsLoading(false);}})();}, []);96 unmodified linessetSessionId(targetSessionId);setMessages([]);setOptimisticMessages([]);setIsLoadingHistory(true);try {const result = await getChatHistoryEmbed(targetSessionId, token);2 unmodified linessetBackendMessage(err instanceof Error ? err.message : 'Gagal memuat riwayat.',);} finally {setIsLoadingHistory(false);}}function handleDeleteSession(targetSessionId: string): void {if (!token) {return;}setPendingDeleteId(targetSessionId);}async function handleConfirmDelete(): Promise<void> {if (!token || !pendingDeleteId) {return;}const targetId = pendingDeleteId;setPendingDeleteId(null);try {await deleteChatSessionEmbed(targetId, token);setChatSessions((prev) =>prev.filter((s) => s.uuid_id !== targetId),);if (targetId === sessionId) {handleNewSession();}} catch (err) {12 unmodified lines<Head title={config.title} /><main className="embed-shell" style={rootStyle}>{pendingDeleteId && (<EmbedConfirmModalmessage="Sesi chat ini akan dihapus permanen."onCancel={() => setPendingDeleteId(null)}onConfirm={() => { void handleConfirmDelete(); }}/>)}<header className="embed-toolbar"><div className="embed-tabs" role="tablist"><button34 unmodified lines</div></header>{isLoading ? (<section className="embed-chat"><div className="embed-empty-state"><Spinner className="size-6" /></div></section>) : activeTab === 'history' ? (<EmbedHistoryactiveSessionId={sessionId}chatSessions={chatSessions}29 unmodified lines</p>)}{isLoadingHistory ? (<div className="embed-empty-state"><Spinner className="size-6" /></div>) : (<>{allMessages.map((message) => (<EmbedMessagekey={message.uuid_id}message={message}shouldAnimateTyping={message.uuid_id ===animatedAssistantMessageId}/>))}{isProcessing && (<article className="embed-message embed-message--assistant"><span className="embed-message-avatar embed-message-avatar--assistant"><Bot className="size-4" /></span><div className="embed-message-bubble embed-message-bubble--typing"><LoadingIndicatorlabel="Thinking"showSpinner={false}/></div></article>)}<div ref={messagesEndRef} /></>)}</div>) : (<div className="embed-empty-state">
README.md+372
app/Http/Controllers/Controller.phpAdded+5
pnpm-lock.yamlAdded
resources/css/app.css+63-12
resources/js/pages/embed.tsx+174-69