add initial crates and apps

This commit is contained in:
Evan Carroll 2026-01-12 15:34:40 -06:00
parent 5c87ba3519
commit 1ca300098f
113 changed files with 28169 additions and 0 deletions

View file

@ -0,0 +1,90 @@
[package]
name = "chattyness-app"
version.workspace = true
edition.workspace = true
[lib]
crate-type = ["cdylib", "rlib"]
[[bin]]
name = "chattyness-app"
path = "src/main.rs"
[dependencies]
chattyness-admin-ui.workspace = true
chattyness-user-ui.workspace = true
chattyness-db.workspace = true
chattyness-error.workspace = true
leptos.workspace = true
leptos_meta.workspace = true
leptos_router.workspace = true
leptos_axum = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
tower = { workspace = true, optional = true }
tower-http = { workspace = true, optional = true }
tower-sessions = { workspace = true, optional = true }
tower-sessions-sqlx-store = { workspace = true, optional = true }
sqlx = { workspace = true, optional = true }
clap = { workspace = true, optional = true }
tokio = { workspace = true, optional = true }
dotenvy = { workspace = true, optional = true }
tracing = { workspace = true, optional = true }
tracing-subscriber = { workspace = true, optional = true }
serde.workspace = true
uuid.workspace = true
# WASM dependencies
console_error_panic_hook = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
[features]
default = ["ssr"]
ssr = [
"leptos/ssr",
"leptos_axum",
"axum",
"tower",
"tower-http",
"tower-sessions",
"tower-sessions-sqlx-store",
"sqlx",
"clap",
"tokio",
"dotenvy",
"tracing",
"tracing-subscriber",
"chattyness-admin-ui/ssr",
"chattyness-user-ui/ssr",
"chattyness-db/ssr",
"chattyness-error/ssr",
]
# Unified hydrate feature - admin routes are lazy-loaded via #[lazy] macro
hydrate = [
"leptos/hydrate",
"chattyness-user-ui/hydrate",
"chattyness-admin-ui/hydrate",
"console_error_panic_hook",
"wasm-bindgen",
]
[package.metadata.leptos]
# Project name used for output artifacts
output-name = "chattyness-app"
# Site configuration (paths relative to workspace root)
site-root = "target/site"
site-pkg-dir = "pkg"
site-addr = "127.0.0.1:3000"
reload-port = 3003
# Tailwind CSS (path relative to this Cargo.toml)
tailwind-input-file = "style/tailwind.css"
# Build settings
bin-features = ["ssr"]
bin-default-features = false
lib-features = ["hydrate"]
lib-default-features = false
# Environment
env = "DEV"

View file

@ -0,0 +1 @@
../../../target/site-owner/static/chattyness-owner.css

View file

View file

@ -0,0 +1,326 @@
//! Combined application for lazy-loading admin interface.
//!
//! This module provides a unified app that serves both user and admin interfaces,
//! with the admin interface lazy-loaded to reduce initial WASM bundle size.
use leptos::prelude::*;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::{
components::{Route, Router, Routes},
ParamSegment, StaticSegment,
};
// Re-export user pages for inline route definitions
use chattyness_user_ui::pages::{
HomePage, LoginPage, PasswordResetPage, RealmPage, SignupPage,
};
// Lazy-load admin pages to split WASM bundle
// Each lazy function includes the admin CSS stylesheet for on-demand loading
#[lazy]
fn lazy_dashboard() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="dashboard" base_path="/admin">
<chattyness_admin_ui::pages::DashboardPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_login() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::LoginLayout>
<chattyness_admin_ui::pages::LoginPage />
</chattyness_admin_ui::components::LoginLayout>
}.into_any()
}
#[lazy]
fn lazy_config() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="config" base_path="/admin">
<chattyness_admin_ui::pages::ConfigPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_users() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="users" base_path="/admin">
<chattyness_admin_ui::pages::UsersPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_user_new() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="users" base_path="/admin">
<chattyness_admin_ui::pages::UserNewPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_user_detail() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="users" base_path="/admin">
<chattyness_admin_ui::pages::UserDetailPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_staff() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="staff" base_path="/admin">
<chattyness_admin_ui::pages::StaffPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_realms() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="realms" base_path="/admin">
<chattyness_admin_ui::pages::RealmsPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_realm_new() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="realms" base_path="/admin">
<chattyness_admin_ui::pages::RealmNewPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_realm_detail() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="realms" base_path="/admin">
<chattyness_admin_ui::pages::RealmDetailPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_scenes() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="scenes" base_path="/admin">
<chattyness_admin_ui::pages::ScenesPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_scene_new() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="scenes_new" base_path="/admin">
<chattyness_admin_ui::pages::SceneNewPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
#[lazy]
fn lazy_scene_detail() -> AnyView {
view! {
<Stylesheet href="/static/css/admin.css"/>
<chattyness_admin_ui::components::AuthenticatedLayout current_page="scenes" base_path="/admin">
<chattyness_admin_ui::pages::SceneDetailPage />
</chattyness_admin_ui::components::AuthenticatedLayout>
}.into_any()
}
/// Admin loading fallback - shown on both server (SSR) and client until lazy content loads.
#[component]
fn AdminLoading() -> impl IntoView {
view! {
<div class="admin-loading">
<div class="loading-spinner"></div>
<p>"Loading admin panel..."</p>
</div>
}
}
/// Macro to generate lazy admin route view functions.
/// Both SSR and client render the same Suspense structure initially.
/// On SSR: Suspense child is empty, so fallback always shows.
/// On client: Suspense child is the lazy content, which loads after hydration.
macro_rules! lazy_admin_view {
($name:ident, $lazy_fn:ident) => {
fn $name() -> impl IntoView {
view! {
<Suspense fallback=AdminLoading>
{
// On server: empty content, Suspense shows fallback
// On client: lazy content loads after hydration
#[cfg(feature = "ssr")]
{ () }
#[cfg(feature = "hydrate")]
{ Suspend::new(async { $lazy_fn().await }) }
}
</Suspense>
}
}
};
}
// Generate view functions for each admin route
lazy_admin_view!(admin_login_view, lazy_login);
lazy_admin_view!(admin_dashboard_view, lazy_dashboard);
lazy_admin_view!(admin_config_view, lazy_config);
lazy_admin_view!(admin_users_view, lazy_users);
lazy_admin_view!(admin_user_new_view, lazy_user_new);
lazy_admin_view!(admin_user_detail_view, lazy_user_detail);
lazy_admin_view!(admin_staff_view, lazy_staff);
lazy_admin_view!(admin_realms_view, lazy_realms);
lazy_admin_view!(admin_realm_new_view, lazy_realm_new);
lazy_admin_view!(admin_realm_detail_view, lazy_realm_detail);
lazy_admin_view!(admin_scenes_view, lazy_scenes);
lazy_admin_view!(admin_scene_new_view, lazy_scene_new);
lazy_admin_view!(admin_scene_detail_view, lazy_scene_detail);
/// Combined app state for unified SSR.
#[cfg(feature = "ssr")]
#[derive(Clone)]
pub struct CombinedAppState {
pub pool: sqlx::PgPool,
pub leptos_options: LeptosOptions,
}
#[cfg(feature = "ssr")]
impl axum::extract::FromRef<CombinedAppState> for LeptosOptions {
fn from_ref(state: &CombinedAppState) -> Self {
state.leptos_options.clone()
}
}
#[cfg(feature = "ssr")]
impl axum::extract::FromRef<CombinedAppState> for sqlx::PgPool {
fn from_ref(state: &CombinedAppState) -> Self {
state.pool.clone()
}
}
/// Combined shell for SSR.
pub fn combined_shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<AutoReload options=options.clone() />
<HydrationScripts options />
<MetaTags />
</head>
<body class="bg-gray-900 text-white antialiased">
<CombinedApp />
</body>
</html>
}
}
/// Combined application component with lazy-loaded admin routes.
///
/// User routes are eagerly loaded, admin routes are lazy-loaded via LocalResource
/// to ensure consistent SSR/hydration (server renders fallback, client loads lazy content).
#[component]
pub fn CombinedApp() -> impl IntoView {
provide_meta_context();
view! {
<Stylesheet id="leptos" href="/static/chattyness-app.css" />
<Title text="Chattyness - Virtual Community Spaces" />
<Router>
<main>
<Routes fallback=|| "Page not found.".into_view()>
// ==========================================
// User routes (eager loading)
// ==========================================
<Route path=StaticSegment("") view=LoginPage />
<Route path=StaticSegment("signup") view=SignupPage />
<Route path=StaticSegment("home") view=HomePage />
<Route path=StaticSegment("password-reset") view=PasswordResetPage />
<Route path=(StaticSegment("realms"), ParamSegment("slug")) view=RealmPage />
// ==========================================
// Admin routes (lazy loading)
// Server renders fallback, client loads lazy WASM after hydration.
// ==========================================
<Route
path=(StaticSegment("admin"), StaticSegment("login"))
view=admin_login_view
/>
<Route
path=StaticSegment("admin")
view=admin_dashboard_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("config"))
view=admin_config_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("users"))
view=admin_users_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("users"), StaticSegment("new"))
view=admin_user_new_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("users"), ParamSegment("user_id"))
view=admin_user_detail_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("staff"))
view=admin_staff_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("realms"))
view=admin_realms_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("realms"), StaticSegment("new"))
view=admin_realm_new_view
/>
// Scene routes (must come before realm detail to match first)
<Route
path=(StaticSegment("admin"), StaticSegment("realms"), ParamSegment("slug"), StaticSegment("scenes"))
view=admin_scenes_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("realms"), ParamSegment("slug"), StaticSegment("scenes"), StaticSegment("new"))
view=admin_scene_new_view
/>
<Route
path=(StaticSegment("admin"), StaticSegment("realms"), ParamSegment("slug"), StaticSegment("scenes"), ParamSegment("scene_id"))
view=admin_scene_detail_view
/>
// Realm detail (must come after more specific routes)
<Route
path=(StaticSegment("admin"), StaticSegment("realms"), ParamSegment("slug"))
view=admin_realm_detail_view
/>
</Routes>
</main>
</Router>
}
}

View file

@ -0,0 +1,20 @@
#![recursion_limit = "256"]
//! App WASM hydration entry point.
//!
//! This provides unified hydration for the combined app, with lazy-loaded
//! admin routes for optimal bundle size.
mod app;
pub use app::{combined_shell, CombinedApp};
#[cfg(feature = "ssr")]
pub use app::CombinedAppState;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
// Use hydrate_lazy to enable lazy component loading
leptos::mount::hydrate_lazy(CombinedApp);
}

View file

@ -0,0 +1,196 @@
#![recursion_limit = "256"]
//! App server entry point.
//!
//! This server runs on port 3000 and serves both user and admin interfaces
//! using a unified CombinedApp with lazy-loaded admin routes.
//!
//! Both interfaces share the same `chattyness_app` database role with RLS.
#[cfg(feature = "ssr")]
mod server {
use axum::Router;
use clap::Parser;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use sqlx::postgres::PgPoolOptions;
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
use tower_http::services::ServeDir;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use chattyness_app::{combined_shell, CombinedApp, CombinedAppState};
use chattyness_user_ui::api::WebSocketState;
/// CLI arguments.
#[derive(Parser)]
#[command(name = "chattyness-app")]
#[command(about = "Chattyness App Server (User + Admin UI)")]
struct Args {
/// Host to bind to
#[arg(long, env = "HOST", default_value = "127.0.0.1")]
host: String,
/// Port to bind to
#[arg(long, env = "APP_PORT", default_value = "3000")]
port: u16,
/// Database password for chattyness_app role
#[arg(long, env = "DB_CHATTYNESS_APP")]
db_password: String,
/// Use secure cookies
#[arg(long, env = "SECURE_COOKIES", default_value = "false")]
secure_cookies: bool,
}
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load environment variables
dotenvy::dotenv().ok();
// Initialize logging
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "chattyness_app=debug,chattyness_user_ui=debug,tower_http=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// Parse arguments
let args = Args::parse();
tracing::info!("Starting Chattyness App Server");
// Create database pool for app access (fixed connection string, RLS-constrained)
let database_url = format!(
"postgres://chattyness_app:{}@localhost/chattyness",
args.db_password
);
let pool = PgPoolOptions::new()
.max_connections(20)
.connect(&database_url)
.await?;
tracing::info!("Connected to database (app role with RLS)");
// Configure Leptos
let cargo_toml = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
let conf = get_configuration(Some(cargo_toml)).unwrap();
let leptos_options = conf.leptos_options;
let addr = SocketAddr::new(args.host.parse()?, args.port);
// Create session layer (shared between user and admin interfaces)
let session_layer =
chattyness_user_ui::auth::session::create_session_layer(pool.clone(), args.secure_cookies)
.await;
// Create combined app state
let app_state = CombinedAppState {
pool: pool.clone(),
leptos_options: leptos_options.clone(),
};
// Generate routes for the combined app
let routes = generate_route_list(CombinedApp);
// Get site paths from Leptos config
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let workspace_root = manifest_dir.parent().unwrap().parent().unwrap();
let site_root = workspace_root.join(&*leptos_options.site_root);
// site-pkg-dir is now "pkg" to match wasm_split's hardcoded /pkg/ imports
let pkg_dir = site_root.join("pkg");
let public_dir = manifest_dir.join("public");
// --split mode puts WASM/JS in target/site-app/pkg/ instead of configured location
let split_pkg_dir = workspace_root.join("target/site-app/pkg");
tracing::info!("Serving pkg files from: {}", pkg_dir.display());
tracing::info!("Serving split WASM from: {}", split_pkg_dir.display());
// Shared assets directory for uploaded files (realm images, etc.)
let assets_dir = Path::new("/srv/chattyness/assets");
// Create WebSocket state for real-time channel presence
let ws_state = Arc::new(WebSocketState::new());
// Create state types for each API router
let user_api_state = chattyness_user_ui::AppState {
pool: pool.clone(),
leptos_options: leptos_options.clone(),
ws_state: ws_state.clone(),
};
let admin_api_state = chattyness_admin_ui::AdminAppState {
pool: pool.clone(),
leptos_options: leptos_options.clone(),
};
// Build nested API routers with their own state
let user_api_router = chattyness_user_ui::api::api_router()
.with_state(user_api_state);
let admin_api_router = chattyness_admin_ui::api::admin_api_router()
.with_state(admin_api_state);
// Create RLS layer for row-level security
let rls_layer = chattyness_user_ui::auth::RlsLayer::new(pool.clone());
// Build the unified app
// Layer order (outer to inner): session -> rls -> router
// This ensures session is available when RLS middleware runs
let app = Router::new()
// API routes (with their own state)
.nest("/api", user_api_router)
.nest("/api/admin", admin_api_router)
// Leptos routes with unified shell
.leptos_routes_with_context(
&app_state,
routes,
{
let pool = pool.clone();
move || {
provide_context(pool.clone());
}
},
{
let leptos_options = leptos_options.clone();
move || combined_shell(leptos_options.clone())
},
)
.with_state(app_state)
// Serve pkg files at /pkg (wasm_split hardcodes /pkg/ imports)
// Fallback to split_pkg_dir for --split mode output
.nest_service("/pkg", ServeDir::new(&pkg_dir).fallback(ServeDir::new(&split_pkg_dir)))
// Uploaded assets (realm backgrounds, etc.) - must come before /static
.nest_service("/static/realm", ServeDir::new(assets_dir.join("realm")))
// Server-level assets (avatar props, etc.)
.nest_service("/static/server", ServeDir::new(assets_dir.join("server")))
// Also serve at /static for backwards compatibility
.nest_service("/static", ServeDir::new(&pkg_dir).fallback(ServeDir::new(&split_pkg_dir)))
.nest_service("/favicon.ico", tower_http::services::ServeFile::new(public_dir.join("favicon.ico")))
// Serve admin CSS at standardized path (symlinked from owner build)
.nest_service("/static/css/admin.css", tower_http::services::ServeFile::new(public_dir.join("admin.css")))
// Apply middleware layers (order: session outer, rls inner)
.layer(rls_layer)
.layer(session_layer);
tracing::info!("Listening on http://{}", addr);
tracing::info!(" User UI: http://{}/", addr);
tracing::info!(" Admin UI: http://{}/admin", addr);
// Start server
let listener = tokio::net::TcpListener::bind(&addr).await?;
axum::serve(listener, app.into_make_service()).await?;
Ok(())
}
}
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
server::main().await
}
#[cfg(not(feature = "ssr"))]
fn main() {
// This is for WASM build, which is handled by lib.rs
}

View file

@ -0,0 +1,78 @@
@import "tailwindcss";
/* Source paths (relative to this CSS file's location) */
/* Only scan user-ui sources - admin-ui CSS is lazy-loaded from /admin.css */
@source "../src/**/*.rs";
@source "../public/**/*.html";
@source "../../../crates/chattyness-user-ui/src/**/*.rs";
@source not "../../../target";
/* Custom theme extensions */
@theme {
--color-realm-50: #f0f9ff;
--color-realm-100: #e0f2fe;
--color-realm-200: #bae6fd;
--color-realm-300: #7dd3fc;
--color-realm-400: #38bdf8;
--color-realm-500: #0ea5e9;
--color-realm-600: #0284c7;
--color-realm-700: #0369a1;
--color-realm-800: #075985;
--color-realm-900: #0c4a6e;
--color-realm-950: #082f49;
}
/* User-specific styles only */
@import "./user.css";
/* Base styles for accessibility */
@layer base {
/* Focus visible for keyboard navigation */
:focus-visible {
@apply outline-2 outline-offset-2 outline-blue-500;
}
/* Reduce motion for users who prefer it */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
}
/* Component styles used by user-ui */
@layer components {
/* Form input base styles */
.input-base {
@apply w-full px-4 py-3 bg-gray-700 border border-gray-600
rounded-lg text-white placeholder-gray-400
focus:ring-2 focus:ring-blue-500 focus:border-transparent
transition-colors duration-200;
}
/* Button base styles */
.btn-primary {
@apply px-6 py-3 bg-blue-600 hover:bg-blue-700
disabled:bg-gray-600 disabled:cursor-not-allowed
text-white font-semibold rounded-lg
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-800
transition-colors duration-200;
}
.btn-secondary {
@apply px-6 py-3 bg-gray-600 hover:bg-gray-500
disabled:bg-gray-700 disabled:cursor-not-allowed
text-white font-semibold rounded-lg
focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 focus:ring-offset-gray-800
transition-colors duration-200;
}
/* Error message styles */
.error-message {
@apply p-4 bg-red-900/50 border border-red-500 rounded-lg text-red-200;
}
}

View file

@ -0,0 +1,8 @@
/**
* User Interface Styles
*
* CSS custom properties and component styles for the user-facing interface.
* This file is imported after admin.css to allow user-specific overrides.
*/
/* User-specific styles will be added here as needed */

File diff suppressed because it is too large Load diff