add chat function

#
This commit is contained in:
Bartal Læarsson
2026-06-12 17:47:14 +01:00
commit 385727b09d
12 changed files with 2776 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
target
Generated
+1579
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "chat-service"
version = "0.0.1"
edition = "2024"
[dependencies]
axum = { version = "=0.6.20", features = ["ws"] }
tokio = { version = "=1.35.1", features = ["full"] }
tower-http = { version = "=0.4.4", features = ["fs"] }
tower = { version = "=0.4.13", features = ["util"] }
serde = { version = "=1.0.197", features = ["derive"] }
serde_json = "=1.0.115"
uuid = { version = "=1.7.0", features = ["v4"] }
dashmap = "=5.5.3"
tracing = "=0.1.40"
tracing-subscriber = { version = "=0.3.18", features = ["env-filter"] }
chrono = { version = "=0.4.35", features = ["serde"] }
url = "=2.4.1"
idna = "=0.5.0"
[profile.release]
opt-level = 3 # Max optimization (default for release)
lto = true # Link-Time Optimization — smaller, faster binary
codegen-units = 1 # Single codegen unit — slower compile, better optimization
panic = "abort" # Remove panic unwinding overhead
strip = true # Strip debug symbols (requires Rust 1.59+)
+208
View File
@@ -0,0 +1,208 @@
use axum::{
extract::{Path, State, Form},
response::Html,
};
use chrono::Utc;
use std::sync::Arc;
use uuid::Uuid;
use crate::{
models::{ChatSession, Message, MessageSender, SendMessageForm, NewSessionForm, SessionStatus},
state::AppState,
};
fn render_message(msg: &Message) -> String {
let (bubble_class, label) = match msg.sender {
MessageSender::Customer => ("msg-customer", "You"),
MessageSender::Agent => ("msg-agent", "Support"),
MessageSender::System => ("msg-system", ""),
};
if msg.sender == MessageSender::System {
format!(
"<div class=\"msg-system-wrap\"><span class=\"msg-system-text\">{}</span></div>",
html_escape(&msg.content)
)
} else {
let time = msg.timestamp.format("%H:%M").to_string();
format!(
"<div class=\"msg-wrap {bclass}-wrap\">\
<div class=\"{bclass}\">\
<span class=\"msg-label\">{label}</span>\
<p class=\"msg-text\">{content}</p>\
<span class=\"msg-time\">{time}</span>\
</div>\
</div>",
bclass = bubble_class,
content = html_escape(&msg.content),
)
}
}
fn html_escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}
/// GET /messages/:session_id
pub async fn get_messages(
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
) -> Html<String> {
let Some(session) = state.sessions.get(&session_id) else {
return Html("<p class='error'>Session not found.</p>".to_string());
};
let html: String = session.messages.iter().map(render_message).collect();
Html(html)
}
/// POST /send/:session_id — customer sends a message
pub async fn send_message(
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
Form(form): Form<SendMessageForm>,
) -> Html<String> {
let content = form.content.trim().to_string();
if content.is_empty() {
return Html(String::new());
}
let msg = Message {
id: Uuid::new_v4().to_string(),
session_id: session_id.clone(),
sender: MessageSender::Customer,
content,
timestamp: Utc::now(),
};
let rendered = render_message(&msg);
if let Some(mut session) = state.sessions.get_mut(&session_id) {
session.messages.push(msg);
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
let _ = state.agent_notifier.send(session_id.clone());
}
Html(rendered)
}
/// POST /agent/send/:session_id — agent sends a message
pub async fn agent_send_message(
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
Form(form): Form<SendMessageForm>,
) -> Html<String> {
let content = form.content.trim().to_string();
if content.is_empty() {
return Html(String::new());
}
let msg = Message {
id: Uuid::new_v4().to_string(),
session_id: session_id.clone(),
sender: MessageSender::Agent,
content,
timestamp: Utc::now(),
};
let rendered = render_message(&msg);
if let Some(mut session) = state.sessions.get_mut(&session_id) {
session.messages.push(msg);
session.status = SessionStatus::Active;
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
}
Html(rendered)
}
/// GET /sessions — session list for agent dashboard
pub async fn get_sessions(
State(state): State<Arc<AppState>>,
) -> Html<String> {
let mut sessions: Vec<_> = state.sessions
.iter()
.filter(|s| s.status != SessionStatus::Closed)
.map(|s| (s.id.clone(), s.customer_name.clone(), s.status.clone(), s.messages.len()))
.collect();
sessions.sort_by(|a, b| a.0.cmp(&b.0));
if sessions.is_empty() {
return Html("<p class=\"no-sessions\">No active conversations yet.</p>".to_string());
}
let mut html = String::new();
for (id, name, status, count) in &sessions {
let status_class = match status {
SessionStatus::Waiting => "status-waiting",
SessionStatus::Active => "status-active",
SessionStatus::Closed => "status-closed",
};
let status_label = match status {
SessionStatus::Waiting => "Waiting",
SessionStatus::Active => "Active",
SessionStatus::Closed => "Closed",
};
let short_id = &id[..8];
let escaped_name = html_escape(name);
html.push_str(&format!(
"<button class=\"session-item\" \
hx-get=\"/messages/{id}\" \
hx-target=\"#agent-messages\" \
hx-swap=\"innerHTML\" \
onclick=\"document.querySelectorAll('.session-item').forEach(function(b){{b.classList.remove('selected')}}); this.classList.add('selected'); setActiveSession('{id}', '{escaped_name}')\">\
<span class=\"session-name\">{escaped_name}</span>\
<span class=\"session-meta\">\
<span class=\"session-badge {status_class}\">{status_label}</span>\
<span class=\"session-count\">{count} msgs</span>\
</span>\
<span class=\"session-id\">#{short_id}</span>\
</button>"
));
}
Html(html)
}
/// POST /sessions/new — start a new customer session
pub async fn new_session(
State(state): State<Arc<AppState>>,
Form(form): Form<NewSessionForm>,
) -> Html<String> {
let name = form.name.trim().to_string();
let name = if name.is_empty() { "Anonymous".to_string() } else { name };
let session_id = Uuid::new_v4().to_string();
let short = session_id[..8].to_string();
let session = ChatSession::new(session_id.clone(), name.clone());
state.sessions.insert(session_id.clone(), session);
state.get_or_create_notifier(&session_id);
let _ = state.agent_notifier.send(session_id.clone());
// The response swaps out #start-form and fills #chat-container via OOB
let html = format!(
"<div id=\"chat-container\" style=\"display:flex;flex-direction:column\" hx-swap-oob=\"true\">\
<div id=\"chat-header\">\
<span class=\"chat-status-dot active\"></span>\
<span>Support Chat</span>\
<span class=\"chat-session-id\">Session #{short}</span>\
</div>\
<div id=\"messages\" \
hx-get=\"/messages/{session_id}\" \
hx-trigger=\"load, every 2s\" \
hx-swap=\"innerHTML\">\
</div>\
<div id=\"typing-indicator\" class=\"htmx-indicator\">\
<span class=\"typing-dot\"></span><span class=\"typing-dot\"></span><span class=\"typing-dot\"></span>\
</div>\
<form id=\"chat-form\" \
hx-post=\"/send/{session_id}\" \
hx-target=\"#messages\" \
hx-swap=\"beforeend\" \
hx-on=\"htmx:afterRequest: this.reset(); scrollMessages()\">\
<input type=\"text\" name=\"content\" placeholder=\"Type your message...\" autocomplete=\"off\" required />\
<button type=\"submit\">Send</button>\
</form>\
</div>\
<script>document.getElementById('start-form').style.display='none'; window.__sessionId='{session_id}';</script>"
);
Html(html)
}
+3
View File
@@ -0,0 +1,3 @@
pub mod pages;
pub mod chat;
pub mod ws;
+9
View File
@@ -0,0 +1,9 @@
use axum::response::Html;
pub async fn customer_page() -> Html<&'static str> {
Html(include_str!("../../templates/customer.html"))
}
pub async fn agent_page() -> Html<&'static str> {
Html(include_str!("../../templates/agent.html"))
}
+74
View File
@@ -0,0 +1,74 @@
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
Path, State,
},
response::IntoResponse,
};
use std::sync::Arc;
use crate::state::AppState;
/// WebSocket for customer — pushes notifications when agent replies
pub async fn customer_ws(
ws: WebSocketUpgrade,
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(move |socket| handle_customer_socket(socket, session_id, state))
}
async fn handle_customer_socket(mut socket: WebSocket, session_id: String, state: Arc<AppState>) {
let tx = state.get_or_create_notifier(&session_id);
let mut rx = tx.subscribe();
loop {
tokio::select! {
// Forward broadcast events to the customer browser
Ok(sid) = rx.recv() => {
if sid == session_id {
// Signal HTMX to re-poll messages
if socket.send(Message::Text("refresh".into())).await.is_err() {
break;
}
}
}
// Handle ping/close from client
msg = socket.recv() => {
match msg {
Some(Ok(Message::Close(_))) | None => break,
_ => {}
}
}
}
}
}
/// WebSocket for agent dashboard — pushes notifications when any session updates
pub async fn agent_ws(
ws: WebSocketUpgrade,
Path(_agent_id): Path<String>,
State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
ws.on_upgrade(move |socket| handle_agent_socket(socket, state))
}
async fn handle_agent_socket(mut socket: WebSocket, state: Arc<AppState>) {
let mut rx = state.agent_notifier.subscribe();
loop {
tokio::select! {
Ok(session_id) = rx.recv() => {
if socket.send(Message::Text(session_id.into())).await.is_err() {
break;
}
}
msg = socket.recv() => {
match msg {
Some(Ok(Message::Close(_))) | None => break,
_ => {}
}
}
}
}
}
+46
View File
@@ -0,0 +1,46 @@
mod state;
mod handlers;
mod models;
use axum::{
routing::{get, post},
Router,
};
use std::sync::Arc;
use tower_http::services::ServeDir;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use state::AppState;
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| "chat_service=debug,info".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();
let state = Arc::new(AppState::new());
let app = Router::new()
.route("/", get(handlers::pages::customer_page))
.route("/agent", get(handlers::pages::agent_page))
.route("/ws/customer/:session_id", get(handlers::ws::customer_ws))
.route("/ws/agent/:agent_id", get(handlers::ws::agent_ws))
.route("/messages/:session_id", get(handlers::chat::get_messages))
.route("/send/:session_id", post(handlers::chat::send_message))
.route("/agent/send/:session_id", post(handlers::chat::agent_send_message))
.route("/sessions", get(handlers::chat::get_sessions))
.route("/sessions/new", post(handlers::chat::new_session))
.nest_service("/static", ServeDir::new("static"))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
tracing::info!("Chat service running — http://0.0.0.0:3000");
axum::Server::from_tcp(listener.into_std().unwrap())
.unwrap()
.serve(app.into_make_service())
.await
.unwrap();
}
+66
View File
@@ -0,0 +1,66 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MessageSender {
Customer,
Agent,
System,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub id: String,
pub session_id: String,
pub sender: MessageSender,
pub content: String,
pub timestamp: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SessionStatus {
Waiting,
Active,
Closed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatSession {
pub id: String,
pub customer_name: String,
pub status: SessionStatus,
pub created_at: DateTime<Utc>,
pub messages: Vec<Message>,
}
impl ChatSession {
pub fn new(id: String, customer_name: String) -> Self {
let now = Utc::now();
let welcome = Message {
id: uuid::Uuid::new_v4().to_string(),
session_id: id.clone(),
sender: MessageSender::System,
content: "Welcome! A support agent will be with you shortly.".to_string(),
timestamp: now,
};
Self {
id,
customer_name,
status: SessionStatus::Waiting,
created_at: now,
messages: vec![welcome],
}
}
}
#[derive(Debug, Deserialize)]
pub struct SendMessageForm {
pub content: String,
}
#[derive(Debug, Deserialize)]
pub struct NewSessionForm {
pub name: String,
}
+32
View File
@@ -0,0 +1,32 @@
use dashmap::DashMap;
use tokio::sync::broadcast;
use crate::models::ChatSession;
pub struct AppState {
pub sessions: DashMap<String, ChatSession>,
// broadcast channel: session_id -> sender
pub notifiers: DashMap<String, broadcast::Sender<String>>,
// agent broadcast for new sessions
pub agent_notifier: broadcast::Sender<String>,
}
impl AppState {
pub fn new() -> Self {
let (agent_tx, _) = broadcast::channel(64);
Self {
sessions: DashMap::new(),
notifiers: DashMap::new(),
agent_notifier: agent_tx,
}
}
pub fn get_or_create_notifier(&self, session_id: &str) -> broadcast::Sender<String> {
if let Some(tx) = self.notifiers.get(session_id) {
tx.clone()
} else {
let (tx, _) = broadcast::channel(64);
self.notifiers.insert(session_id.to_string(), tx.clone());
tx
}
}
}
+411
View File
@@ -0,0 +1,411 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Support Dashboard</title>
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0f1117;
--surface: #1a1d27;
--surface2: #20243a;
--border: #2a2d3a;
--accent: #6c63ff;
--accent-dim:#4a44b5;
--text: #e8e8f0;
--muted: #6b6e80;
--customer: #6c63ff;
--agent: #22c55e;
--radius: 10px;
}
html, body {
height: 100%;
background: var(--bg);
font-family: 'Inter', system-ui, sans-serif;
color: var(--text);
overflow: hidden;
}
/* --- Layout --- */
.layout {
display: grid;
grid-template-columns: 280px 1fr;
grid-template-rows: 56px 1fr;
height: 100vh;
}
/* --- Top bar --- */
.topbar {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0 1.5rem;
border-bottom: 1px solid var(--border);
background: var(--surface);
}
.topbar-logo { font-size: 1.2rem; }
.topbar h1 {
font-size: 1rem;
font-weight: 700;
letter-spacing: -0.01em;
}
.topbar-badge {
margin-left: auto;
font-size: 0.75rem;
color: var(--muted);
background: var(--bg);
padding: 0.2rem 0.6rem;
border-radius: 20px;
border: 1px solid var(--border);
}
/* --- Sidebar --- */
.sidebar {
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
overflow: hidden;
}
.sidebar-header {
padding: 1rem;
border-bottom: 1px solid var(--border);
font-size: 0.78rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--muted);
}
#session-list {
flex: 1;
overflow-y: auto;
padding: 0.5rem;
display: flex;
flex-direction: column;
gap: 0.3rem;
}
#session-list::-webkit-scrollbar { width: 4px; }
#session-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
.session-item {
width: 100%;
text-align: left;
background: transparent;
border: 1px solid transparent;
border-radius: var(--radius);
padding: 0.7rem 0.8rem;
cursor: pointer;
color: var(--text);
font-size: 0.88rem;
transition: background 0.15s, border-color 0.15s;
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.session-item:hover { background: var(--surface2); border-color: var(--border); }
.session-item.selected { background: var(--surface2); border-color: var(--accent); }
.session-name { font-weight: 600; }
.session-meta {
display: flex;
align-items: center;
gap: 0.5rem;
}
.session-badge {
font-size: 0.68rem;
padding: 0.15rem 0.5rem;
border-radius: 20px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.status-waiting { background: rgba(234, 179, 8, 0.15); color: #eab308; }
.status-active { background: rgba(34, 197, 94, 0.15); color: #22c55e; }
.status-closed { background: rgba(107, 110, 128, 0.15); color: var(--muted); }
.session-count { font-size: 0.75rem; color: var(--muted); }
.session-id { font-size: 0.7rem; color: var(--muted); font-family: monospace; }
.no-sessions {
padding: 1.5rem 1rem;
font-size: 0.85rem;
color: var(--muted);
text-align: center;
}
/* --- Main panel --- */
.main-panel {
display: flex;
flex-direction: column;
overflow: hidden;
}
.main-header {
padding: 0.9rem 1.5rem;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
gap: 0.5rem;
min-height: 56px;
}
#active-session-name {
font-weight: 700;
font-size: 1rem;
}
#active-session-meta {
font-size: 0.8rem;
color: var(--muted);
}
#agent-messages {
flex: 1;
overflow-y: auto;
padding: 1.2rem 1.5rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
scroll-behavior: smooth;
}
#agent-messages::-webkit-scrollbar { width: 4px; }
#agent-messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--muted);
gap: 0.5rem;
}
.empty-state .icon { font-size: 2rem; }
.empty-state p { font-size: 0.9rem; }
/* Message bubbles (same as customer page) */
.msg-wrap { display: flex; }
.msg-customer-wrap { justify-content: flex-end; }
.msg-agent-wrap { justify-content: flex-start; }
.msg-customer, .msg-agent {
max-width: 65%;
padding: 0.6rem 0.9rem;
border-radius: 16px;
font-size: 0.88rem;
line-height: 1.5;
}
.msg-customer { background: var(--customer); color: #fff; border-bottom-right-radius: 4px; }
.msg-agent { background: var(--border); color: var(--text); border-bottom-left-radius: 4px; }
.msg-label {
display: block;
font-size: 0.7rem;
font-weight: 600;
opacity: 0.7;
margin-bottom: 2px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.msg-text { margin: 0; }
.msg-time {
display: block;
font-size: 0.68rem;
opacity: 0.5;
margin-top: 4px;
text-align: right;
}
.msg-system-wrap { display: flex; justify-content: center; margin: 0.25rem 0; }
.msg-system-text {
font-size: 0.75rem;
color: var(--muted);
background: var(--bg);
padding: 0.25rem 0.75rem;
border-radius: 20px;
}
/* --- Reply form --- */
#reply-area {
border-top: 1px solid var(--border);
padding: 0.75rem 1.5rem;
display: none;
}
#reply-area.visible { display: flex; gap: 0.6rem; }
#reply-area input[type="text"] {
flex: 1;
padding: 0.65rem 1rem;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
color: var(--text);
font-size: 0.9rem;
outline: none;
transition: border-color 0.2s;
}
#reply-area input[type="text"]:focus { border-color: var(--accent); }
#reply-area button {
padding: 0.65rem 1.2rem;
background: var(--agent);
color: #0f1117;
border: none;
border-radius: var(--radius);
font-weight: 700;
font-size: 0.88rem;
cursor: pointer;
transition: opacity 0.2s;
}
#reply-area button:hover { opacity: 0.85; }
</style>
</head>
<body>
<div class="layout">
<!-- Top bar -->
<header class="topbar">
<span class="topbar-logo">🎧</span>
<h1>Support Dashboard</h1>
<span class="topbar-badge" id="ws-status">● Connecting…</span>
</header>
<!-- Sidebar: session list -->
<aside class="sidebar">
<div class="sidebar-header">Conversations</div>
<div id="session-list"
hx-get="/sessions"
hx-trigger="load, every 5s"
hx-swap="innerHTML">
<p class="no-sessions">Loading…</p>
</div>
</aside>
<!-- Main: message view + reply -->
<section class="main-panel">
<div class="main-header">
<span id="active-session-name" style="color: var(--muted)">Select a conversation</span>
<span id="active-session-meta"></span>
</div>
<div id="agent-messages">
<div class="empty-state">
<span class="icon">💬</span>
<p>No conversation selected</p>
</div>
</div>
<div id="reply-area">
<input type="text" id="reply-input" placeholder="Reply to customer…" autocomplete="off" />
<button id="reply-btn">Send</button>
</div>
</section>
</div>
<script>
let activeSessionId = null;
function setActiveSession(sessionId, name) {
activeSessionId = sessionId;
document.getElementById('active-session-name').textContent = name;
document.getElementById('active-session-meta').textContent = '#' + sessionId.slice(0, 8);
document.getElementById('reply-area').classList.add('visible');
scrollAgentMessages();
}
function scrollAgentMessages() {
const el = document.getElementById('agent-messages');
if (el) el.scrollTop = el.scrollHeight;
}
document.addEventListener('htmx:afterSwap', (e) => {
if (e.detail.target.id === 'agent-messages') scrollAgentMessages();
});
// Send reply on button click
document.getElementById('reply-btn').addEventListener('click', () => {
if (!activeSessionId) return;
const input = document.getElementById('reply-input');
const content = input.value.trim();
if (!content) return;
fetch(`/agent/send/${activeSessionId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `content=${encodeURIComponent(content)}`
})
.then(r => r.text())
.then(html => {
const msgs = document.getElementById('agent-messages');
msgs.insertAdjacentHTML('beforeend', html);
scrollAgentMessages();
input.value = '';
});
});
// Also send on Enter
document.getElementById('reply-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter') document.getElementById('reply-btn').click();
});
// WebSocket: get push notifications for new messages / sessions
function connectAgentWS() {
const ws = new WebSocket(`ws://${location.host}/ws/agent/dashboard`);
ws.onopen = () => {
document.getElementById('ws-status').textContent = '● Live';
document.getElementById('ws-status').style.color = '#22c55e';
};
ws.onmessage = (e) => {
const updatedSessionId = e.data;
// Refresh session list
htmx.trigger('#session-list', 'refresh');
// If this session is currently open, refresh its messages
if (updatedSessionId === activeSessionId) {
fetch(`/messages/${activeSessionId}`)
.then(r => r.text())
.then(html => {
document.getElementById('agent-messages').innerHTML = html;
scrollAgentMessages();
});
}
};
ws.onclose = () => {
document.getElementById('ws-status').textContent = '● Reconnecting…';
document.getElementById('ws-status').style.color = '#eab308';
setTimeout(connectAgentWS, 2000);
};
}
connectAgentWS();
</script>
</body>
</html>
+321
View File
@@ -0,0 +1,321 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Support Chat</title>
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0f1117;
--surface: #1a1d27;
--border: #2a2d3a;
--accent: #6c63ff;
--accent-dim:#4a44b5;
--text: #e8e8f0;
--muted: #6b6e80;
--customer: #6c63ff;
--agent: #22c55e;
--radius: 12px;
}
body {
background: var(--bg);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-family: 'Inter', system-ui, sans-serif;
color: var(--text);
}
/* --- Start form --- */
#start-form {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 20px;
padding: 2.5rem;
width: 360px;
text-align: center;
}
#start-form .icon {
font-size: 2.5rem;
margin-bottom: 1rem;
}
#start-form h1 {
font-size: 1.4rem;
font-weight: 700;
margin-bottom: 0.4rem;
letter-spacing: -0.02em;
}
#start-form p {
font-size: 0.9rem;
color: var(--muted);
margin-bottom: 1.8rem;
}
#start-form input[type="text"] {
width: 100%;
padding: 0.75rem 1rem;
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius);
color: var(--text);
font-size: 0.95rem;
margin-bottom: 1rem;
outline: none;
transition: border-color 0.2s;
}
#start-form input[type="text"]:focus {
border-color: var(--accent);
}
#start-form button {
width: 100%;
padding: 0.75rem;
background: var(--accent);
color: #fff;
border: none;
border-radius: var(--radius);
font-size: 0.95rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
}
#start-form button:hover { background: var(--accent-dim); }
/* --- Chat container --- */
#chat-container {
display: none;
flex-direction: column;
width: 380px;
height: 580px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 20px;
overflow: hidden;
}
#chat-header {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 1rem 1.2rem;
border-bottom: 1px solid var(--border);
font-weight: 600;
font-size: 0.95rem;
}
.chat-status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--muted);
}
.chat-status-dot.active { background: var(--agent); }
.chat-session-id {
margin-left: auto;
font-size: 0.75rem;
color: var(--muted);
font-weight: 400;
}
#messages {
flex: 1;
overflow-y: auto;
padding: 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
scroll-behavior: smooth;
}
#messages::-webkit-scrollbar { width: 4px; }
#messages::-webkit-scrollbar-track { background: transparent; }
#messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
/* --- Message bubbles --- */
.msg-wrap { display: flex; }
.msg-customer-wrap { justify-content: flex-end; }
.msg-agent-wrap { justify-content: flex-start; }
.msg-customer, .msg-agent {
max-width: 75%;
padding: 0.6rem 0.9rem;
border-radius: 16px;
font-size: 0.88rem;
line-height: 1.5;
}
.msg-customer {
background: var(--customer);
color: #fff;
border-bottom-right-radius: 4px;
}
.msg-agent {
background: var(--border);
color: var(--text);
border-bottom-left-radius: 4px;
}
.msg-label {
display: block;
font-size: 0.7rem;
font-weight: 600;
opacity: 0.7;
margin-bottom: 2px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.msg-text { margin: 0; }
.msg-time {
display: block;
font-size: 0.68rem;
opacity: 0.5;
margin-top: 4px;
text-align: right;
}
.msg-system-wrap {
display: flex;
justify-content: center;
margin: 0.25rem 0;
}
.msg-system-text {
font-size: 0.75rem;
color: var(--muted);
background: var(--bg);
padding: 0.25rem 0.75rem;
border-radius: 20px;
}
/* --- Typing indicator --- */
#typing-indicator {
display: none;
padding: 0 1rem 0.5rem;
gap: 4px;
align-items: center;
}
#typing-indicator.htmx-request { display: flex; }
.typing-dot {
width: 6px; height: 6px;
border-radius: 50%;
background: var(--muted);
animation: bounce 1.2s infinite;
}
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes bounce {
0%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-6px); }
}
/* --- Input form --- */
#chat-form {
display: flex;
gap: 0.5rem;
padding: 0.75rem 1rem;
border-top: 1px solid var(--border);
}
#chat-form input[type="text"] {
flex: 1;
padding: 0.6rem 0.9rem;
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius);
color: var(--text);
font-size: 0.9rem;
outline: none;
transition: border-color 0.2s;
}
#chat-form input[type="text"]:focus { border-color: var(--accent); }
#chat-form button {
padding: 0.6rem 1.1rem;
background: var(--accent);
color: #fff;
border: none;
border-radius: var(--radius);
font-weight: 600;
font-size: 0.88rem;
cursor: pointer;
transition: background 0.2s;
}
#chat-form button:hover { background: var(--accent-dim); }
</style>
</head>
<body>
<!-- Step 1: Start form -->
<div id="start-form">
<div class="icon">💬</div>
<h1>Talk to Support</h1>
<p>We're here to help. Start a conversation and we'll get back to you right away.</p>
<form hx-post="/sessions/new"
hx-target="body"
hx-swap="beforeend">
<input type="text" name="name" placeholder="Your name (optional)" maxlength="40" />
<button type="submit">Start Chat</button>
</form>
</div>
<!-- Step 2: Chat UI (injected by server after session creation) -->
<div id="chat-container"></div>
<script>
function scrollMessages() {
const el = document.getElementById('messages');
if (el) el.scrollTop = el.scrollHeight;
}
// Auto-scroll when HTMX adds new messages
document.addEventListener('htmx:afterSwap', (e) => {
if (e.detail.target.id === 'messages') scrollMessages();
});
// WebSocket for instant push (agent replies trigger a refresh)
// Session ID is injected after session creation
let ws = null;
document.addEventListener('htmx:afterRequest', (e) => {
if (e.detail.requestConfig?.path === '/sessions/new' && !ws) {
// Extract session id from the returned HTML
const container = document.getElementById('chat-container');
if (!container) return;
const match = container.innerHTML.match(/\/messages\/([a-f0-9-]+)/);
if (!match) return;
const sessionId = match[1];
ws = new WebSocket(`ws://${location.host}/ws/customer/${sessionId}`);
ws.onmessage = () => {
// Trigger an out-of-band refresh of the messages div
htmx.trigger('#messages', 'refresh');
};
ws.onerror = () => console.warn('WS error, falling back to polling');
}
});
</script>
</body>
</html>