72185aef-7931-4dd9-a377-318054098118
This commit is contained in:
parent
d77000472f
commit
28aebdf552
147 changed files with 18743 additions and 2 deletions
56
.gitignore
vendored
56
.gitignore
vendored
|
|
@ -1,2 +1,54 @@
|
|||
skills/
|
||||
node_modules/
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
local-*
|
||||
.claude
|
||||
.z-ai-config
|
||||
*.log
|
||||
dev.log
|
||||
dev.out.log
|
||||
test
|
||||
prompt
|
||||
|
||||
server.log
|
||||
# Skills directory
|
||||
/skills/
|
||||
175
.zscripts/build.sh
Executable file
175
.zscripts/build.sh
Executable file
|
|
@ -0,0 +1,175 @@
|
|||
#!/bin/bash
|
||||
|
||||
# 将 stderr 重定向到 stdout,避免 execute_command 因为 stderr 输出而报错
|
||||
exec 2>&1
|
||||
|
||||
set -e
|
||||
|
||||
# 获取脚本所在目录(.zscripts 目录,即 workspace-agent/.zscripts)
|
||||
# 使用 $0 获取脚本路径(兼容 sh 和 bash)
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
# Next.js 项目路径
|
||||
NEXTJS_PROJECT_DIR="/home/z/my-project"
|
||||
|
||||
# 检查 Next.js 项目目录是否存在
|
||||
if [ ! -d "$NEXTJS_PROJECT_DIR" ]; then
|
||||
echo "❌ 错误: Next.js 项目目录不存在: $NEXTJS_PROJECT_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🚀 开始构建 Next.js 应用和 mini-services..."
|
||||
echo "📁 Next.js 项目路径: $NEXTJS_PROJECT_DIR"
|
||||
|
||||
# 切换到 Next.js 项目目录
|
||||
cd "$NEXTJS_PROJECT_DIR" || exit 1
|
||||
|
||||
# 设置环境变量
|
||||
export NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
BUILD_DIR="/tmp/build_fullstack_$BUILD_ID"
|
||||
echo "📁 清理并创建构建目录: $BUILD_DIR"
|
||||
mkdir -p "$BUILD_DIR"
|
||||
|
||||
# 安装依赖
|
||||
echo "📦 安装依赖..."
|
||||
bun install
|
||||
|
||||
# 构建 Next.js 应用
|
||||
echo "🔨 构建 Next.js 应用..."
|
||||
bun run build
|
||||
|
||||
# 校验 standalone 服务端入口是否生成(部署成功率守卫)。
|
||||
# Next 仅在 next.config 含 output:"standalone" 时产出 .next/standalone/server.js。
|
||||
# 若用户/AI 编辑项目时改写或删除了该配置,bun run build 仍会成功(static 照常
|
||||
# 产出、退出码 0),但 standalone 缺失——打出的包里没有 server.js,部署到 FC 后
|
||||
# start.sh 找不到 next-service-dist/server.js → 不启动 Next → Caddy:81 反代空的
|
||||
# 3000 → FC 健康检查 120s 超时失败(线上 warmup_412 / FunctionNotStarted 的主因)。
|
||||
# 这里做一次自愈:仅在确实缺失时,给 next.config 补回 output:"standalone" 并重建。
|
||||
# 正常项目(已生成 server.js)整段跳过,不读写任何用户文件。
|
||||
if [ ! -f ".next/standalone/server.js" ]; then
|
||||
echo "⚠️ 构建未产出 .next/standalone/server.js,开始自愈 next.config 的 output 配置..."
|
||||
NEXT_CONFIG_FILE="$(ls next.config.ts next.config.js next.config.mjs next.config.cjs 2>/dev/null | head -1)"
|
||||
|
||||
if [ -z "$NEXT_CONFIG_FILE" ]; then
|
||||
echo "❌ 构建失败:未找到 next.config.*,无法生成 standalone 部署产物。"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if grep -Eq "output\s*:\s*['\"]standalone['\"]" "$NEXT_CONFIG_FILE"; then
|
||||
# 已声明 standalone 却仍没产出 server.js,说明不是配置缺失(可能 build 真
|
||||
# 出错、自定义 distDir 等)。不臆改用户配置,直接失败并暴露原因。
|
||||
echo "❌ 构建失败:$NEXT_CONFIG_FILE 已含 output:\"standalone\",但仍未生成 .next/standalone/server.js。"
|
||||
echo " 请检查上方构建日志中的报错或项目自定义的构建配置。"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if grep -Eq "output\s*:\s*['\"]" "$NEXT_CONFIG_FILE"; then
|
||||
# 已显式声明了其它 output(如 "export" 静态导出 / "standalone" 之外的值)。
|
||||
# "export" 与本部署模型(standalone + 自定义 server)互斥——不能注入第二个
|
||||
# output 覆盖用户意图(JS 对象重复 key 后者生效,注入也无效)。明确失败。
|
||||
echo "❌ 构建失败:$NEXT_CONFIG_FILE 已声明非 standalone 的 output(如 \"export\" 静态导出),与当前部署模型不兼容。"
|
||||
echo " 当前部署需要 output:\"standalone\"。请改为 standalone,或确认该项目是否应走静态托管而非部署沙箱。"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🔧 检测到 $NEXT_CONFIG_FILE 缺少 output:\"standalone\",自动注入后重新构建..."
|
||||
cp "$NEXT_CONFIG_FILE" "${NEXT_CONFIG_FILE}.zbak"
|
||||
# 在第一个配置对象字面量起始的 { 之后插入 output:"standalone",
|
||||
# 覆盖脚手架常见写法:const nextConfig...= { / export default { / module.exports = {
|
||||
perl -0pi -e 's/((?:const\s+\w+[^=]*=|export\s+default|module\.exports\s*=)\s*\{)/$1\n output: "standalone",/' "$NEXT_CONFIG_FILE"
|
||||
|
||||
if ! grep -Eq "output\s*:\s*['\"]standalone['\"]" "$NEXT_CONFIG_FILE"; then
|
||||
echo "❌ 未能匹配到可注入的配置对象,next.config 写法非常规,需人工添加 output:\"standalone\"。"
|
||||
echo " 当前 $NEXT_CONFIG_FILE 内容:"
|
||||
cat "$NEXT_CONFIG_FILE"
|
||||
mv "${NEXT_CONFIG_FILE}.zbak" "$NEXT_CONFIG_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🔨 已注入 output:\"standalone\",重新构建..."
|
||||
bun run build
|
||||
|
||||
if [ ! -f ".next/standalone/server.js" ]; then
|
||||
echo "❌ 注入 output:\"standalone\" 并重建后,仍未生成 .next/standalone/server.js。"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ 自愈成功:standalone 服务端入口已生成。"
|
||||
fi
|
||||
|
||||
# 构建 mini-services
|
||||
# 检查 Next.js 项目目录下是否有 mini-services 目录
|
||||
if [ -d "$NEXTJS_PROJECT_DIR/mini-services" ]; then
|
||||
echo "🔨 构建 mini-services..."
|
||||
# 使用 workspace-agent 目录下的 mini-services 脚本
|
||||
sh "$SCRIPT_DIR/mini-services-install.sh"
|
||||
sh "$SCRIPT_DIR/mini-services-build.sh"
|
||||
|
||||
# 复制 mini-services-start.sh 到 mini-services-dist 目录
|
||||
echo " - 复制 mini-services-start.sh 到 $BUILD_DIR"
|
||||
cp "$SCRIPT_DIR/mini-services-start.sh" "$BUILD_DIR/mini-services-start.sh"
|
||||
chmod +x "$BUILD_DIR/mini-services-start.sh"
|
||||
else
|
||||
echo "ℹ️ mini-services 目录不存在,跳过"
|
||||
fi
|
||||
|
||||
# 将所有构建产物复制到临时构建目录
|
||||
echo "📦 收集构建产物到 $BUILD_DIR..."
|
||||
|
||||
# 复制 Next.js standalone 构建输出
|
||||
if [ -d ".next/standalone" ]; then
|
||||
echo " - 复制 .next/standalone"
|
||||
cp -r .next/standalone "$BUILD_DIR/next-service-dist/"
|
||||
fi
|
||||
|
||||
# 复制 Next.js 静态文件
|
||||
if [ -d ".next/static" ]; then
|
||||
echo " - 复制 .next/static"
|
||||
mkdir -p "$BUILD_DIR/next-service-dist/.next"
|
||||
cp -r .next/static "$BUILD_DIR/next-service-dist/.next/"
|
||||
fi
|
||||
|
||||
# 复制 public 目录
|
||||
if [ -d "public" ]; then
|
||||
echo " - 复制 public"
|
||||
cp -r public "$BUILD_DIR/next-service-dist/"
|
||||
fi
|
||||
|
||||
# Python 不继承 workspace-agent 的 /home/z/.venv。若项目包含 Python 源码或
|
||||
# 依赖清单,在构建期将生产依赖固化到产物,并保持 Python 源码的项目相对路径。
|
||||
PROJECT_DIR="$NEXTJS_PROJECT_DIR" BUILD_DIR="$BUILD_DIR" \
|
||||
bash "$SCRIPT_DIR/python-runtime-build.sh"
|
||||
|
||||
# 有 Preview 数据库时复制现有数据;没有时直接在部署产物中初始化空库。
|
||||
# 模板源码不携带 db/custom.db,不能依赖 dev.sh 必须在 Deploy 前成功运行过。
|
||||
PROJECT_DIR="$NEXTJS_PROJECT_DIR" BUILD_DIR="$BUILD_DIR" \
|
||||
bash "$SCRIPT_DIR/database-runtime-build.sh"
|
||||
|
||||
# 复制 Caddyfile(如果存在)
|
||||
if [ -f "Caddyfile" ]; then
|
||||
echo " - 复制 Caddyfile"
|
||||
cp Caddyfile "$BUILD_DIR/"
|
||||
else
|
||||
echo "ℹ️ Caddyfile 不存在,跳过"
|
||||
fi
|
||||
|
||||
# 复制 start.sh 脚本
|
||||
echo " - 复制 start.sh 到 $BUILD_DIR"
|
||||
cp "$SCRIPT_DIR/start.sh" "$BUILD_DIR/start.sh"
|
||||
chmod +x "$BUILD_DIR/start.sh"
|
||||
|
||||
# 打包到 $BUILD_DIR.tar.gz
|
||||
PACKAGE_FILE="${BUILD_DIR}.tar.gz"
|
||||
echo ""
|
||||
echo "📦 打包构建产物到 $PACKAGE_FILE..."
|
||||
cd "$BUILD_DIR" || exit 1
|
||||
tar -czf "$PACKAGE_FILE" .
|
||||
cd - > /dev/null || exit 1
|
||||
|
||||
# # 清理临时目录
|
||||
# rm -rf "$BUILD_DIR"
|
||||
|
||||
echo ""
|
||||
echo "✅ 构建完成!所有产物已打包到 $PACKAGE_FILE"
|
||||
echo "📊 打包文件大小:"
|
||||
ls -lh "$PACKAGE_FILE"
|
||||
33
.zscripts/database-runtime-build.sh
Executable file
33
.zscripts/database-runtime-build.sh
Executable file
|
|
@ -0,0 +1,33 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_DIR="${PROJECT_DIR:-/home/z/my-project}"
|
||||
BUILD_DIR="${BUILD_DIR:?BUILD_DIR is required}"
|
||||
SOURCE_DB_DIR="$PROJECT_DIR/db"
|
||||
SOURCE_DB_PATH="$SOURCE_DB_DIR/custom.db"
|
||||
TARGET_DB_DIR="$BUILD_DIR/db"
|
||||
TARGET_DB_PATH="$TARGET_DB_DIR/custom.db"
|
||||
|
||||
mkdir -p "$TARGET_DB_DIR"
|
||||
|
||||
if [ -f "$SOURCE_DB_PATH" ]; then
|
||||
echo "🗄️ 复制 Preview 数据库到构建产物..."
|
||||
cp -a "$SOURCE_DB_DIR/." "$TARGET_DB_DIR/"
|
||||
else
|
||||
echo "ℹ️ 未找到 Preview 数据库 db/custom.db,将初始化空的生产数据库"
|
||||
fi
|
||||
|
||||
echo "🗄️ 同步构建产物中的数据库结构..."
|
||||
(
|
||||
cd "$PROJECT_DIR"
|
||||
DATABASE_URL="file:$TARGET_DB_PATH" bun run db:push
|
||||
)
|
||||
|
||||
if [ ! -f "$TARGET_DB_PATH" ]; then
|
||||
echo "❌ 数据库初始化命令执行成功,但未生成 $TARGET_DB_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ 构建产物数据库已准备完成"
|
||||
ls -lah "$TARGET_DB_DIR"
|
||||
1
.zscripts/dev.pid
Normal file
1
.zscripts/dev.pid
Normal file
|
|
@ -0,0 +1 @@
|
|||
2231
|
||||
154
.zscripts/dev.sh
Executable file
154
.zscripts/dev.sh
Executable file
|
|
@ -0,0 +1,154 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# 获取脚本所在目录(.zscripts)
|
||||
# 使用 $0 获取脚本路径(与 build.sh 保持一致)
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
|
||||
log_step_start() {
|
||||
local step_name="$1"
|
||||
echo "=========================================="
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting: $step_name"
|
||||
echo "=========================================="
|
||||
export STEP_START_TIME
|
||||
STEP_START_TIME=$(date +%s)
|
||||
}
|
||||
|
||||
log_step_end() {
|
||||
local step_name="${1:-Unknown step}"
|
||||
local end_time
|
||||
end_time=$(date +%s)
|
||||
local duration=$((end_time - STEP_START_TIME))
|
||||
echo "=========================================="
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Completed: $step_name"
|
||||
echo "[LOG] Step: $step_name | Duration: ${duration}s"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
}
|
||||
|
||||
start_mini_services() {
|
||||
local mini_services_dir="$PROJECT_DIR/mini-services"
|
||||
local started_count=0
|
||||
|
||||
log_step_start "Starting mini-services"
|
||||
if [ ! -d "$mini_services_dir" ]; then
|
||||
echo "Mini-services directory not found, skipping..."
|
||||
log_step_end "Starting mini-services"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Found mini-services directory, scanning for sub-services..."
|
||||
|
||||
for service_dir in "$mini_services_dir"/*; do
|
||||
if [ ! -d "$service_dir" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
local service_name
|
||||
service_name=$(basename "$service_dir")
|
||||
echo "Checking service: $service_name"
|
||||
|
||||
if [ ! -f "$service_dir/package.json" ]; then
|
||||
echo "[$service_name] No package.json found, skipping..."
|
||||
continue
|
||||
fi
|
||||
|
||||
if ! grep -q '"dev"' "$service_dir/package.json"; then
|
||||
echo "[$service_name] No dev script found, skipping..."
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "Starting $service_name in background..."
|
||||
(
|
||||
cd "$service_dir"
|
||||
echo "[$service_name] Installing dependencies..."
|
||||
bun install
|
||||
echo "[$service_name] Running bun run dev..."
|
||||
exec bun run dev
|
||||
) >"$PROJECT_DIR/.zscripts/mini-service-${service_name}.log" 2>&1 &
|
||||
|
||||
local service_pid=$!
|
||||
echo "[$service_name] Started in background (PID: $service_pid)"
|
||||
echo "[$service_name] Log: $PROJECT_DIR/.zscripts/mini-service-${service_name}.log"
|
||||
disown "$service_pid" 2>/dev/null || true
|
||||
started_count=$((started_count + 1))
|
||||
done
|
||||
|
||||
echo "Mini-services startup completed. Started $started_count service(s)."
|
||||
log_step_end "Starting mini-services"
|
||||
}
|
||||
|
||||
wait_for_service() {
|
||||
local host="$1"
|
||||
local port="$2"
|
||||
local service_name="$3"
|
||||
local max_attempts="${4:-60}"
|
||||
local attempt=1
|
||||
|
||||
echo "Waiting for $service_name to be ready on $host:$port..."
|
||||
|
||||
while [ "$attempt" -le "$max_attempts" ]; do
|
||||
if curl -s --connect-timeout 2 --max-time 5 "http://$host:$port" >/dev/null 2>&1; then
|
||||
echo "$service_name is ready!"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Attempt $attempt/$max_attempts: $service_name not ready yet, waiting..."
|
||||
sleep 1
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
|
||||
echo "ERROR: $service_name failed to start within $max_attempts seconds"
|
||||
return 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
if [ -n "${DEV_PID:-}" ] && kill -0 "$DEV_PID" >/dev/null 2>&1; then
|
||||
echo "Stopping Next.js dev server (PID: $DEV_PID)..."
|
||||
kill "$DEV_PID" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
if ! command -v bun >/dev/null 2>&1; then
|
||||
echo "ERROR: bun is not installed or not in PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
log_step_start "bun install"
|
||||
echo "[BUN] Installing dependencies..."
|
||||
bun install
|
||||
log_step_end "bun install"
|
||||
|
||||
log_step_start "bun run db:push"
|
||||
echo "[BUN] Setting up database..."
|
||||
bun run db:push
|
||||
log_step_end "bun run db:push"
|
||||
|
||||
log_step_start "Starting Next.js dev server"
|
||||
echo "[BUN] Starting development server..."
|
||||
bun run dev &
|
||||
DEV_PID=$!
|
||||
log_step_end "Starting Next.js dev server"
|
||||
|
||||
log_step_start "Waiting for Next.js dev server"
|
||||
wait_for_service "localhost" "3000" "Next.js dev server"
|
||||
log_step_end "Waiting for Next.js dev server"
|
||||
|
||||
log_step_start "Health check"
|
||||
echo "[BUN] Performing health check..."
|
||||
curl -fsS localhost:3000 >/dev/null
|
||||
echo "[BUN] Health check passed"
|
||||
log_step_end "Health check"
|
||||
|
||||
start_mini_services
|
||||
|
||||
echo "Next.js dev server is running in background (PID: $DEV_PID)."
|
||||
echo "Use 'kill $DEV_PID' to stop it."
|
||||
disown "$DEV_PID" 2>/dev/null || true
|
||||
unset DEV_PID
|
||||
78
.zscripts/mini-services-build.sh
Executable file
78
.zscripts/mini-services-build.sh
Executable file
|
|
@ -0,0 +1,78 @@
|
|||
#!/bin/bash
|
||||
|
||||
# 配置项
|
||||
ROOT_DIR="/home/z/my-project/mini-services"
|
||||
DIST_DIR="/tmp/build_fullstack_$BUILD_ID/mini-services-dist"
|
||||
|
||||
main() {
|
||||
echo "🚀 开始批量构建..."
|
||||
|
||||
# 检查 rootdir 是否存在
|
||||
if [ ! -d "$ROOT_DIR" ]; then
|
||||
echo "ℹ️ 目录 $ROOT_DIR 不存在,跳过构建"
|
||||
return
|
||||
fi
|
||||
|
||||
# 创建输出目录(如果不存在)
|
||||
mkdir -p "$DIST_DIR"
|
||||
|
||||
# 统计变量
|
||||
success_count=0
|
||||
fail_count=0
|
||||
|
||||
# 遍历 mini-services 目录下的所有文件夹
|
||||
for dir in "$ROOT_DIR"/*; do
|
||||
# 检查是否是目录且包含 package.json
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
|
||||
project_name=$(basename "$dir")
|
||||
|
||||
# 智能查找入口文件 (按优先级查找)
|
||||
entry_path=""
|
||||
for entry in "src/index.ts" "index.ts" "src/index.js" "index.js"; do
|
||||
if [ -f "$dir/$entry" ]; then
|
||||
entry_path="$dir/$entry"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$entry_path" ]; then
|
||||
echo "⚠️ 跳过 $project_name: 未找到入口文件 (index.ts/js)"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📦 正在构建: $project_name..."
|
||||
|
||||
# 使用 bun build CLI 构建
|
||||
output_file="$DIST_DIR/mini-service-$project_name.js"
|
||||
|
||||
if bun build "$entry_path" \
|
||||
--outfile "$output_file" \
|
||||
--target bun \
|
||||
--minify; then
|
||||
echo "✅ $project_name 构建成功 -> $output_file"
|
||||
success_count=$((success_count + 1))
|
||||
else
|
||||
echo "❌ $project_name 构建失败"
|
||||
fail_count=$((fail_count + 1))
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -f ./.zscripts/mini-services-start.sh ]; then
|
||||
cp ./.zscripts/mini-services-start.sh "$DIST_DIR/mini-services-start.sh"
|
||||
chmod +x "$DIST_DIR/mini-services-start.sh"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🎉 所有任务完成!"
|
||||
if [ $success_count -gt 0 ] || [ $fail_count -gt 0 ]; then
|
||||
echo "✅ 成功: $success_count 个"
|
||||
if [ $fail_count -gt 0 ]; then
|
||||
echo "❌ 失败: $fail_count 个"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
main
|
||||
|
||||
65
.zscripts/mini-services-install.sh
Executable file
65
.zscripts/mini-services-install.sh
Executable file
|
|
@ -0,0 +1,65 @@
|
|||
#!/bin/bash
|
||||
|
||||
# 配置项
|
||||
ROOT_DIR="/home/z/my-project/mini-services"
|
||||
|
||||
main() {
|
||||
echo "🚀 开始批量安装依赖..."
|
||||
|
||||
# 检查 rootdir 是否存在
|
||||
if [ ! -d "$ROOT_DIR" ]; then
|
||||
echo "ℹ️ 目录 $ROOT_DIR 不存在,跳过安装"
|
||||
return
|
||||
fi
|
||||
|
||||
# 统计变量
|
||||
success_count=0
|
||||
fail_count=0
|
||||
failed_projects=""
|
||||
|
||||
# 遍历 mini-services 目录下的所有文件夹
|
||||
for dir in "$ROOT_DIR"/*; do
|
||||
# 检查是否是目录且包含 package.json
|
||||
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
|
||||
project_name=$(basename "$dir")
|
||||
echo ""
|
||||
echo "📦 正在安装依赖: $project_name..."
|
||||
|
||||
# 进入项目目录并执行 bun install
|
||||
if (cd "$dir" && bun install); then
|
||||
echo "✅ $project_name 依赖安装成功"
|
||||
success_count=$((success_count + 1))
|
||||
else
|
||||
echo "❌ $project_name 依赖安装失败"
|
||||
fail_count=$((fail_count + 1))
|
||||
if [ -z "$failed_projects" ]; then
|
||||
failed_projects="$project_name"
|
||||
else
|
||||
failed_projects="$failed_projects $project_name"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
# 汇总结果
|
||||
echo ""
|
||||
echo "=================================================="
|
||||
if [ $success_count -gt 0 ] || [ $fail_count -gt 0 ]; then
|
||||
echo "🎉 安装完成!"
|
||||
echo "✅ 成功: $success_count 个"
|
||||
if [ $fail_count -gt 0 ]; then
|
||||
echo "❌ 失败: $fail_count 个"
|
||||
echo ""
|
||||
echo "失败的项目:"
|
||||
for project in $failed_projects; do
|
||||
echo " - $project"
|
||||
done
|
||||
fi
|
||||
else
|
||||
echo "ℹ️ 未找到任何包含 package.json 的项目"
|
||||
fi
|
||||
echo "=================================================="
|
||||
}
|
||||
|
||||
main
|
||||
|
||||
123
.zscripts/mini-services-start.sh
Executable file
123
.zscripts/mini-services-start.sh
Executable file
|
|
@ -0,0 +1,123 @@
|
|||
#!/bin/sh
|
||||
|
||||
# 配置项
|
||||
DIST_DIR="./mini-services-dist"
|
||||
|
||||
# 存储所有子进程的 PID
|
||||
pids=""
|
||||
|
||||
# 清理函数:优雅关闭所有服务
|
||||
cleanup() {
|
||||
echo ""
|
||||
echo "🛑 正在关闭所有服务..."
|
||||
|
||||
# 发送 SIGTERM 信号给所有子进程
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
service_name=$(ps -p "$pid" -o comm= 2>/dev/null || echo "unknown")
|
||||
echo " 关闭进程 $pid ($service_name)..."
|
||||
kill -TERM "$pid" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# 等待所有进程退出(最多等待 5 秒)
|
||||
sleep 1
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
# 如果还在运行,等待最多 4 秒
|
||||
timeout=4
|
||||
while [ $timeout -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
|
||||
sleep 1
|
||||
timeout=$((timeout - 1))
|
||||
done
|
||||
# 如果仍然在运行,强制关闭
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
echo " 强制关闭进程 $pid..."
|
||||
kill -KILL "$pid" 2>/dev/null
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo "✅ 所有服务已关闭"
|
||||
}
|
||||
|
||||
main() {
|
||||
echo "🚀 开始启动所有 mini services..."
|
||||
|
||||
# 检查 dist 目录是否存在
|
||||
if [ ! -d "$DIST_DIR" ]; then
|
||||
echo "ℹ️ 目录 $DIST_DIR 不存在"
|
||||
return
|
||||
fi
|
||||
|
||||
# 查找所有 mini-service-*.js 文件
|
||||
service_files=""
|
||||
for file in "$DIST_DIR"/mini-service-*.js; do
|
||||
if [ -f "$file" ]; then
|
||||
if [ -z "$service_files" ]; then
|
||||
service_files="$file"
|
||||
else
|
||||
service_files="$service_files $file"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
# 计算服务文件数量
|
||||
service_count=0
|
||||
for file in $service_files; do
|
||||
service_count=$((service_count + 1))
|
||||
done
|
||||
|
||||
if [ $service_count -eq 0 ]; then
|
||||
echo "ℹ️ 未找到任何 mini service 文件"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "📦 找到 $service_count 个服务,开始启动..."
|
||||
echo ""
|
||||
|
||||
# 启动每个服务
|
||||
for file in $service_files; do
|
||||
service_name=$(basename "$file" .js | sed 's/mini-service-//')
|
||||
echo "▶️ 启动服务: $service_name..."
|
||||
|
||||
# 使用 bun 运行服务(后台运行)
|
||||
bun "$file" &
|
||||
pid=$!
|
||||
if [ -z "$pids" ]; then
|
||||
pids="$pid"
|
||||
else
|
||||
pids="$pids $pid"
|
||||
fi
|
||||
|
||||
# 等待一小段时间检查进程是否成功启动
|
||||
sleep 0.5
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
echo "❌ $service_name 启动失败"
|
||||
# 从字符串中移除失败的 PID
|
||||
pids=$(echo "$pids" | sed "s/\b$pid\b//" | sed 's/ */ /g' | sed 's/^ *//' | sed 's/ *$//')
|
||||
else
|
||||
echo "✅ $service_name 已启动 (PID: $pid)"
|
||||
fi
|
||||
done
|
||||
|
||||
# 计算运行中的服务数量
|
||||
running_count=0
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
running_count=$((running_count + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "🎉 所有服务已启动!共 $running_count 个服务正在运行"
|
||||
echo ""
|
||||
echo "💡 按 Ctrl+C 停止所有服务"
|
||||
echo ""
|
||||
|
||||
# 等待所有后台进程
|
||||
wait
|
||||
}
|
||||
|
||||
main
|
||||
|
||||
120
.zscripts/python-runtime-build.sh
Executable file
120
.zscripts/python-runtime-build.sh
Executable file
|
|
@ -0,0 +1,120 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_DIR="${PROJECT_DIR:-/home/z/my-project}"
|
||||
BUILD_DIR="${BUILD_DIR:?BUILD_DIR is required}"
|
||||
PYTHON_VERSION="${PYTHON_VERSION:-3.12}"
|
||||
NEXT_DIST_DIR="$BUILD_DIR/next-service-dist"
|
||||
PYTHON_RUNTIME_DIR="$BUILD_DIR/python-runtime"
|
||||
PYTHON_PACKAGES_DIR="$PYTHON_RUNTIME_DIR/site-packages"
|
||||
|
||||
has_python_sources() {
|
||||
find "$PROJECT_DIR" \
|
||||
\( -type d \( -name '.git' \
|
||||
-o -name '.next' \
|
||||
-o -name '.venv' \
|
||||
-o -name 'node_modules' \
|
||||
-o -name '__pycache__' \
|
||||
-o -name 'mini-services' \
|
||||
-o -name 'upload' \
|
||||
-o -name 'download' \
|
||||
\) -prune \) \
|
||||
-o -type f \( -name '*.py' -o -name '*.pyi' \) -print -quit | grep -q .
|
||||
}
|
||||
|
||||
if ! has_python_sources \
|
||||
&& [ ! -f "$PROJECT_DIR/requirements.txt" ] \
|
||||
&& [ ! -f "$PROJECT_DIR/pyproject.toml" ]; then
|
||||
echo "ℹ️ 未检测到 Python 源码或依赖清单,跳过 Python runtime 构建"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! command -v uv >/dev/null 2>&1; then
|
||||
echo "❌ 检测到 Python 项目,但构建环境中没有 uv"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🐍 检测到 Python runtime,目标版本: $PYTHON_VERSION"
|
||||
mkdir -p "$NEXT_DIST_DIR" "$PYTHON_PACKAGES_DIR"
|
||||
|
||||
install_requirements() {
|
||||
local requirements_file="$1"
|
||||
local target_dir="${2:-$PYTHON_PACKAGES_DIR}"
|
||||
if [ ! -s "$requirements_file" ]; then
|
||||
echo "ℹ️ Python 依赖清单为空,跳过依赖安装"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "📦 根据 $(basename "$requirements_file") 固化 Python 生产依赖..."
|
||||
uv pip install \
|
||||
--python "$PYTHON_VERSION" \
|
||||
--target "$target_dir" \
|
||||
--requirements "$requirements_file"
|
||||
|
||||
# --target 生成的 console scripts 会保留构建机 Python 的绝对 shebang。
|
||||
# 改成 Runner 内可解析的 python,并由 start scripts 将该 bin 目录加入 PATH。
|
||||
if [ -d "$target_dir/bin" ]; then
|
||||
for script in "$target_dir"/bin/*; do
|
||||
[ -f "$script" ] || continue
|
||||
perl -0pi -e 's/\A#![^\n]*python[^\n]*\n/#!\/usr\/bin\/env python\n/' "$script"
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
install_pyproject() {
|
||||
local project_dir="$1"
|
||||
local target_dir="$2"
|
||||
local output_name="$3"
|
||||
local requirements_file="$PYTHON_RUNTIME_DIR/$output_name"
|
||||
|
||||
if [ -f "$project_dir/uv.lock" ]; then
|
||||
uv export \
|
||||
--project "$project_dir" \
|
||||
--frozen \
|
||||
--no-dev \
|
||||
--no-emit-project \
|
||||
--format requirements.txt \
|
||||
--output-file "$requirements_file"
|
||||
else
|
||||
uv pip compile \
|
||||
"$project_dir/pyproject.toml" \
|
||||
--python-version "$PYTHON_VERSION" \
|
||||
--output-file "$requirements_file"
|
||||
fi
|
||||
install_requirements "$requirements_file" "$target_dir"
|
||||
}
|
||||
|
||||
if [ -f "$PROJECT_DIR/pyproject.toml" ] && [ -f "$PROJECT_DIR/uv.lock" ]; then
|
||||
echo "🔒 使用 pyproject.toml + uv.lock 导出生产依赖..."
|
||||
install_pyproject "$PROJECT_DIR" "$PYTHON_PACKAGES_DIR" "requirements.lock.txt"
|
||||
elif [ -f "$PROJECT_DIR/requirements.txt" ]; then
|
||||
cp "$PROJECT_DIR/requirements.txt" "$PYTHON_RUNTIME_DIR/requirements.txt"
|
||||
install_requirements "$PYTHON_RUNTIME_DIR/requirements.txt"
|
||||
elif [ -f "$PROJECT_DIR/pyproject.toml" ]; then
|
||||
echo "📦 pyproject.toml 未配套 uv.lock,解析生产依赖..."
|
||||
install_pyproject "$PROJECT_DIR" "$PYTHON_PACKAGES_DIR" "requirements.txt"
|
||||
else
|
||||
echo "⚠️ 检测到 Python 源码,但没有 requirements.txt 或 pyproject.toml;仅支持 Python 标准库"
|
||||
fi
|
||||
|
||||
if has_python_sources; then
|
||||
echo "📄 复制 Python 源码到部署项目,保持相对路径..."
|
||||
(
|
||||
cd "$PROJECT_DIR"
|
||||
find . \
|
||||
\( -type d \( -name '.git' \
|
||||
-o -name '.next' \
|
||||
-o -name '.venv' \
|
||||
-o -name 'node_modules' \
|
||||
-o -name '__pycache__' \
|
||||
-o -name 'mini-services' \
|
||||
-o -name 'upload' \
|
||||
-o -name 'download' \
|
||||
\) -prune \) \
|
||||
-o -type f \( -name '*.py' -o -name '*.pyi' \) -print0 \
|
||||
| tar --null -T - -cf -
|
||||
) | tar -C "$NEXT_DIST_DIR" -xf -
|
||||
fi
|
||||
|
||||
echo "✅ Python runtime 已固化到部署产物"
|
||||
145
.zscripts/start.sh
Executable file
145
.zscripts/start.sh
Executable file
|
|
@ -0,0 +1,145 @@
|
|||
#!/bin/sh
|
||||
|
||||
set -e
|
||||
|
||||
# 获取脚本所在目录
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
BUILD_DIR="$SCRIPT_DIR"
|
||||
|
||||
# 存储所有子进程的 PID
|
||||
pids=""
|
||||
|
||||
# 清理函数:优雅关闭所有服务
|
||||
cleanup() {
|
||||
echo ""
|
||||
echo "🛑 正在关闭所有服务..."
|
||||
|
||||
# 发送 SIGTERM 信号给所有子进程
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
service_name=$(ps -p "$pid" -o comm= 2>/dev/null || echo "unknown")
|
||||
echo " 关闭进程 $pid ($service_name)..."
|
||||
kill -TERM "$pid" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# 等待所有进程退出(最多等待 5 秒)
|
||||
sleep 1
|
||||
for pid in $pids; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
# 如果还在运行,等待最多 4 秒
|
||||
timeout=4
|
||||
while [ $timeout -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
|
||||
sleep 1
|
||||
timeout=$((timeout - 1))
|
||||
done
|
||||
# 如果仍然在运行,强制关闭
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
echo " 强制关闭进程 $pid..."
|
||||
kill -KILL "$pid" 2>/dev/null
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo "✅ 所有服务已关闭"
|
||||
exit 0
|
||||
}
|
||||
|
||||
echo "🚀 开始启动所有服务..."
|
||||
echo ""
|
||||
|
||||
# 切换到构建目录
|
||||
cd "$BUILD_DIR" || exit 1
|
||||
|
||||
ls -lah
|
||||
|
||||
DEFAULT_PACKAGED_DB_PATH="/app/db/custom.db"
|
||||
DEFAULT_PACKAGED_DATABASE_URL="file:$DEFAULT_PACKAGED_DB_PATH"
|
||||
|
||||
# Python 依赖在构建阶段安装进部署产物,不复用 Sandbox 的 /home/z/.venv。
|
||||
# Next.js 及其启动的子进程都会继承这组路径。
|
||||
if [ -d "/app/python-runtime/site-packages" ]; then
|
||||
export PYTHONPATH="/app/python-runtime/site-packages:/app/next-service-dist${PYTHONPATH:+:$PYTHONPATH}"
|
||||
export PATH="/app/python-runtime/site-packages/bin:$PATH"
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export PYTHONUNBUFFERED=1
|
||||
echo "🐍 已启用部署包内 Python runtime: $(python --version 2>&1)"
|
||||
fi
|
||||
|
||||
# 启动 Next.js 服务器
|
||||
if [ -f "./next-service-dist/server.js" ]; then
|
||||
echo "🚀 启动 Next.js 服务器..."
|
||||
cd next-service-dist/ || exit 1
|
||||
|
||||
# 设置环境变量
|
||||
export NODE_ENV=production
|
||||
export PORT="${PORT:-3000}"
|
||||
export HOSTNAME="${HOSTNAME:-0.0.0.0}"
|
||||
export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PACKAGED_DATABASE_URL}"
|
||||
|
||||
if [ "$DATABASE_URL" = "$DEFAULT_PACKAGED_DATABASE_URL" ]; then
|
||||
if [ ! -f "$DEFAULT_PACKAGED_DB_PATH" ]; then
|
||||
echo "❌ 未找到打包后的数据库文件 $DEFAULT_PACKAGED_DB_PATH"
|
||||
echo " 为避免生产环境启动到空数据库,启动已终止"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "🗄️ 当前使用打包数据库: $DEFAULT_PACKAGED_DB_PATH"
|
||||
else
|
||||
echo "🗄️ 当前使用外部指定数据库: $DATABASE_URL"
|
||||
fi
|
||||
|
||||
# 后台启动 Next.js
|
||||
bun server.js &
|
||||
NEXT_PID=$!
|
||||
pids="$NEXT_PID"
|
||||
|
||||
# 等待一小段时间检查进程是否成功启动
|
||||
sleep 1
|
||||
if ! kill -0 "$NEXT_PID" 2>/dev/null; then
|
||||
echo "❌ Next.js 服务器启动失败"
|
||||
exit 1
|
||||
else
|
||||
echo "✅ Next.js 服务器已启动 (PID: $NEXT_PID, Port: $PORT)"
|
||||
fi
|
||||
|
||||
cd ../
|
||||
else
|
||||
echo "⚠️ 未找到 Next.js 服务器文件: ./next-service-dist/server.js"
|
||||
fi
|
||||
|
||||
# 启动 mini-services
|
||||
if [ -f "./mini-services-start.sh" ]; then
|
||||
echo "🚀 启动 mini-services..."
|
||||
|
||||
# 运行启动脚本(从根目录运行,脚本内部会处理 mini-services-dist 目录)
|
||||
sh ./mini-services-start.sh &
|
||||
MINI_PID=$!
|
||||
pids="$pids $MINI_PID"
|
||||
|
||||
# 等待一小段时间检查进程是否成功启动
|
||||
sleep 1
|
||||
if ! kill -0 "$MINI_PID" 2>/dev/null; then
|
||||
echo "⚠️ mini-services 可能启动失败,但继续运行..."
|
||||
else
|
||||
echo "✅ mini-services 已启动 (PID: $MINI_PID)"
|
||||
fi
|
||||
elif [ -d "./mini-services-dist" ]; then
|
||||
echo "⚠️ 未找到 mini-services 启动脚本,但目录存在"
|
||||
else
|
||||
echo "ℹ️ mini-services 目录不存在,跳过"
|
||||
fi
|
||||
|
||||
# 启动 Caddy(如果存在 Caddyfile)
|
||||
echo "🚀 启动 Caddy..."
|
||||
|
||||
# Caddy 作为前台进程运行(主进程)
|
||||
echo "✅ Caddy 已启动(前台运行)"
|
||||
echo ""
|
||||
echo "🎉 所有服务已启动!"
|
||||
echo ""
|
||||
echo "💡 按 Ctrl+C 停止所有服务"
|
||||
echo ""
|
||||
|
||||
# Caddy 作为主进程运行
|
||||
exec caddy run --config Caddyfile --adapter caddyfile
|
||||
23
Caddyfile
Normal file
23
Caddyfile
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
:81 {
|
||||
@transform_port_query {
|
||||
query XTransformPort=*
|
||||
}
|
||||
|
||||
handle @transform_port_query {
|
||||
reverse_proxy localhost:{query.XTransformPort} {
|
||||
header_up Host {host}
|
||||
header_up X-Forwarded-For {remote_host}
|
||||
header_up X-Forwarded-Proto {scheme}
|
||||
header_up X-Real-IP {remote_host}
|
||||
}
|
||||
}
|
||||
|
||||
handle {
|
||||
reverse_proxy localhost:3000 {
|
||||
header_up Host {host}
|
||||
header_up X-Forwarded-For {remote_host}
|
||||
header_up X-Forwarded-Proto {scheme}
|
||||
header_up X-Real-IP {remote_host}
|
||||
}
|
||||
}
|
||||
}
|
||||
21
components.json
Normal file
21
components.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
BIN
db/custom.db
Normal file
BIN
db/custom.db
Normal file
Binary file not shown.
50
eslint.config.mjs
Normal file
50
eslint.config.mjs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTypescript from "eslint-config-next/typescript";
|
||||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const eslintConfig = [...nextCoreWebVitals, ...nextTypescript, {
|
||||
rules: {
|
||||
// TypeScript rules
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"@typescript-eslint/no-non-null-assertion": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/prefer-as-const": "off",
|
||||
"@typescript-eslint/no-unused-disable-directive": "off",
|
||||
|
||||
// React rules
|
||||
"react-hooks/exhaustive-deps": "off",
|
||||
"react-hooks/purity": "off",
|
||||
"react/no-unescaped-entities": "off",
|
||||
"react/display-name": "off",
|
||||
"react/prop-types": "off",
|
||||
"react-compiler/react-compiler": "off",
|
||||
|
||||
// Next.js rules
|
||||
"@next/next/no-img-element": "off",
|
||||
"@next/next/no-html-link-for-pages": "off",
|
||||
|
||||
// General JavaScript rules
|
||||
"prefer-const": "off",
|
||||
"no-unused-vars": "off",
|
||||
"no-console": "off",
|
||||
"no-debugger": "off",
|
||||
"no-empty": "off",
|
||||
"no-irregular-whitespace": "off",
|
||||
"no-case-declarations": "off",
|
||||
"no-fallthrough": "off",
|
||||
"no-mixed-spaces-and-tabs": "off",
|
||||
"no-redeclare": "off",
|
||||
"no-undef": "off",
|
||||
"no-unreachable": "off",
|
||||
"no-useless-escape": "off",
|
||||
},
|
||||
}, {
|
||||
ignores: ["node_modules/**", ".next/**", "out/**", "build/**", "next-env.d.ts", "examples/**", "skills"]
|
||||
}];
|
||||
|
||||
export default eslintConfig;
|
||||
196
examples/websocket/frontend.tsx
Normal file
196
examples/websocket/frontend.tsx
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { io } from 'socket.io-client';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
type Message = {
|
||||
id: string;
|
||||
username: string;
|
||||
content: string;
|
||||
timestamp: Date | string;
|
||||
type: 'user' | 'system';
|
||||
}
|
||||
|
||||
export default function SocketDemo() {
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [inputMessage, setInputMessage] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
const [isUsernameSet, setIsUsernameSet] = useState(false);
|
||||
const [socket, setSocket] = useState<any>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
// Connect to websocket server
|
||||
// Never use PORT in the URL, alyways use XTransformPort
|
||||
// DO NOT change the path, it is used by Caddy to forward the request to the correct port
|
||||
const socketInstance = io('/?XTransformPort=3003', {
|
||||
transports: ['websocket', 'polling'],
|
||||
forceNew: true,
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000,
|
||||
timeout: 10000
|
||||
})
|
||||
|
||||
setSocket(socketInstance);
|
||||
|
||||
socketInstance.on('connect', () => {
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
socketInstance.on('disconnect', () => {
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
socketInstance.on('message', (msg: Message) => {
|
||||
setMessages(prev => [...prev, msg]);
|
||||
});
|
||||
|
||||
socketInstance.on('user-joined', (data: { user: User; message: Message }) => {
|
||||
setMessages(prev => [...prev, data.message]);
|
||||
setUsers(prev => {
|
||||
if (!prev.find(u => u.id === data.user.id)) {
|
||||
return [...prev, data.user];
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
});
|
||||
|
||||
socketInstance.on('user-left', (data: { user: User; message: Message }) => {
|
||||
setMessages(prev => [...prev, data.message]);
|
||||
setUsers(prev => prev.filter(u => u.id !== data.user.id));
|
||||
});
|
||||
|
||||
socketInstance.on('users-list', (data: { users: User[] }) => {
|
||||
setUsers(data.users);
|
||||
});
|
||||
|
||||
return () => {
|
||||
socketInstance.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleJoin = () => {
|
||||
if (socket && username.trim() && isConnected) {
|
||||
socket.emit('join', { username: username.trim() });
|
||||
setIsUsernameSet(true);
|
||||
}
|
||||
};
|
||||
|
||||
const sendMessage = () => {
|
||||
if (socket && inputMessage.trim() && username.trim()) {
|
||||
socket.emit('message', {
|
||||
content: inputMessage.trim(),
|
||||
username: username.trim()
|
||||
});
|
||||
setInputMessage('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
sendMessage();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
WebSocket Demo
|
||||
<span className={`text-sm px-2 py-1 rounded ${isConnected ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
|
||||
{isConnected ? 'Connected' : 'Disconnected'}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{!isUsernameSet ? (
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
onKeyPress={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleJoin();
|
||||
}
|
||||
}}
|
||||
placeholder="Enter your username..."
|
||||
disabled={!isConnected}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleJoin}
|
||||
disabled={!isConnected || !username.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
Join Chat
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<ScrollArea className="h-80 w-full border rounded-md p-4">
|
||||
<div className="space-y-2">
|
||||
{messages.length === 0 ? (
|
||||
<p className="text-gray-500 text-center">No messages yet</p>
|
||||
) : (
|
||||
messages.map((msg) => (
|
||||
<div key={msg.id} className="border-b pb-2 last:border-b-0">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex-1">
|
||||
<p className={`text-sm font-medium ${msg.type === 'system'
|
||||
? 'text-blue-600 italic'
|
||||
: 'text-gray-700'
|
||||
}`}>
|
||||
{msg.username}
|
||||
</p>
|
||||
<p className={`${msg.type === 'system'
|
||||
? 'text-blue-500 italic'
|
||||
: 'text-gray-900'
|
||||
}`}>
|
||||
{msg.content}
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(msg.timestamp).toLocaleTimeString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Input
|
||||
value={inputMessage}
|
||||
onChange={(e) => setInputMessage(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
placeholder="Type a message..."
|
||||
disabled={!isConnected}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={sendMessage}
|
||||
disabled={!isConnected || !inputMessage.trim()}
|
||||
>
|
||||
Send
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
138
examples/websocket/server.ts
Normal file
138
examples/websocket/server.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { createServer } from 'http'
|
||||
import { Server } from 'socket.io'
|
||||
|
||||
const httpServer = createServer()
|
||||
const io = new Server(httpServer, {
|
||||
// DO NOT change the path, it is used by Caddy to forward the request to the correct port
|
||||
path: '/',
|
||||
cors: {
|
||||
origin: "*",
|
||||
methods: ["GET", "POST"]
|
||||
},
|
||||
pingTimeout: 60000,
|
||||
pingInterval: 25000,
|
||||
})
|
||||
|
||||
interface User {
|
||||
id: string
|
||||
username: string
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: string
|
||||
username: string
|
||||
content: string
|
||||
timestamp: Date
|
||||
type: 'user' | 'system'
|
||||
}
|
||||
|
||||
const users = new Map<string, User>()
|
||||
|
||||
const generateMessageId = () => Math.random().toString(36).substr(2, 9)
|
||||
|
||||
const createSystemMessage = (content: string): Message => ({
|
||||
id: generateMessageId(),
|
||||
username: 'System',
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
type: 'system'
|
||||
})
|
||||
|
||||
const createUserMessage = (username: string, content: string): Message => ({
|
||||
id: generateMessageId(),
|
||||
username,
|
||||
content,
|
||||
timestamp: new Date(),
|
||||
type: 'user'
|
||||
})
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
console.log(`User connected: ${socket.id}`)
|
||||
|
||||
// Add test event handler
|
||||
socket.on('test', (data) => {
|
||||
console.log('Received test message:', data)
|
||||
socket.emit('test-response', {
|
||||
message: 'Server received test message',
|
||||
data: data,
|
||||
timestamp: new Date().toISOString()
|
||||
})
|
||||
})
|
||||
|
||||
socket.on('join', (data: { username: string }) => {
|
||||
const { username } = data
|
||||
|
||||
// Create user object
|
||||
const user: User = {
|
||||
id: socket.id,
|
||||
username
|
||||
}
|
||||
|
||||
// Add to user list
|
||||
users.set(socket.id, user)
|
||||
|
||||
// Send join message to all users
|
||||
const joinMessage = createSystemMessage(`${username} joined the chat room`)
|
||||
io.emit('user-joined', { user, message: joinMessage })
|
||||
|
||||
// Send current user list to new user
|
||||
const usersList = Array.from(users.values())
|
||||
socket.emit('users-list', { users: usersList })
|
||||
|
||||
console.log(`${username} joined the chat room, current online users: ${users.size}`)
|
||||
})
|
||||
|
||||
socket.on('message', (data: { content: string; username: string }) => {
|
||||
const { content, username } = data
|
||||
const user = users.get(socket.id)
|
||||
|
||||
if (user && user.username === username) {
|
||||
const message = createUserMessage(username, content)
|
||||
io.emit('message', message)
|
||||
console.log(`${username}: ${content}`)
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
const user = users.get(socket.id)
|
||||
|
||||
if (user) {
|
||||
// Remove from user list
|
||||
users.delete(socket.id)
|
||||
|
||||
// Send leave message to all users
|
||||
const leaveMessage = createSystemMessage(`${user.username} left the chat room`)
|
||||
io.emit('user-left', { user: { id: socket.id, username: user.username }, message: leaveMessage })
|
||||
|
||||
console.log(`${user.username} left the chat room, current online users: ${users.size}`)
|
||||
} else {
|
||||
console.log(`User disconnected: ${socket.id}`)
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('error', (error) => {
|
||||
console.error(`Socket error (${socket.id}):`, error)
|
||||
})
|
||||
})
|
||||
|
||||
const PORT = 3003
|
||||
httpServer.listen(PORT, () => {
|
||||
console.log(`WebSocket server running on port ${PORT}`)
|
||||
})
|
||||
|
||||
// Graceful shutdown
|
||||
process.on('SIGTERM', () => {
|
||||
console.log('Received SIGTERM signal, shutting down server...')
|
||||
httpServer.close(() => {
|
||||
console.log('WebSocket server closed')
|
||||
process.exit(0)
|
||||
})
|
||||
})
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log('Received SIGINT signal, shutting down server...')
|
||||
httpServer.close(() => {
|
||||
console.log('WebSocket server closed')
|
||||
process.exit(0)
|
||||
})
|
||||
})
|
||||
0
mini-services/.gitkeep
Normal file
0
mini-services/.gitkeep
Normal file
12
next.config.ts
Normal file
12
next.config.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
/* config options here */
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
reactStrictMode: false,
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
95
package.json
Normal file
95
package.json
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
{
|
||||
"name": "nextjs_tailwind_shadcn_ts",
|
||||
"version": "0.2.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3000 2>&1 | tee dev.log",
|
||||
"build": "next build && cp -r .next/static .next/standalone/.next/ && cp -r public .next/standalone/",
|
||||
"start": "NODE_ENV=production bun .next/standalone/server.js 2>&1 | tee server.log",
|
||||
"lint": "eslint .",
|
||||
"db:push": "prisma db push --accept-data-loss",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:reset": "prisma migrate reset"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@hookform/resolvers": "^5.1.1",
|
||||
"@mdxeditor/editor": "^3.39.1",
|
||||
"@prisma/client": "^6.11.1",
|
||||
"@radix-ui/react-accordion": "^1.2.11",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.14",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.7",
|
||||
"@radix-ui/react-avatar": "^1.1.10",
|
||||
"@radix-ui/react-checkbox": "^1.3.2",
|
||||
"@radix-ui/react-collapsible": "^1.1.11",
|
||||
"@radix-ui/react-context-menu": "^2.2.15",
|
||||
"@radix-ui/react-dialog": "^1.1.14",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.15",
|
||||
"@radix-ui/react-hover-card": "^1.1.14",
|
||||
"@radix-ui/react-label": "^2.1.7",
|
||||
"@radix-ui/react-menubar": "^1.1.15",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.13",
|
||||
"@radix-ui/react-popover": "^1.1.14",
|
||||
"@radix-ui/react-progress": "^1.1.7",
|
||||
"@radix-ui/react-radio-group": "^1.3.7",
|
||||
"@radix-ui/react-scroll-area": "^1.2.9",
|
||||
"@radix-ui/react-select": "^2.2.5",
|
||||
"@radix-ui/react-separator": "^1.1.7",
|
||||
"@radix-ui/react-slider": "^1.3.5",
|
||||
"@radix-ui/react-slot": "^1.2.3",
|
||||
"@radix-ui/react-switch": "^1.2.5",
|
||||
"@radix-ui/react-tabs": "^1.1.12",
|
||||
"@radix-ui/react-toast": "^1.2.14",
|
||||
"@radix-ui/react-toggle": "^1.1.9",
|
||||
"@radix-ui/react-toggle-group": "^1.1.10",
|
||||
"@radix-ui/react-tooltip": "^1.2.7",
|
||||
"@reactuses/core": "^6.0.5",
|
||||
"@tanstack/react-query": "^5.82.0",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"framer-motion": "^12.23.2",
|
||||
"input-otp": "^1.4.2",
|
||||
"jszip": "^3.10.2",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next": "^16.1.1",
|
||||
"next-auth": "^4.24.11",
|
||||
"next-intl": "^4.3.4",
|
||||
"next-themes": "^0.4.6",
|
||||
"prisma": "^6.11.1",
|
||||
"react": "^19.0.0",
|
||||
"react-day-picker": "^9.8.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hook-form": "^7.60.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-resizable-panels": "^3.0.3",
|
||||
"react-syntax-highlighter": "^15.6.1",
|
||||
"recharts": "^2.15.4",
|
||||
"sharp": "^0.34.3",
|
||||
"sonner": "^2.0.6",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"uuid": "^11.1.0",
|
||||
"vaul": "^1.1.2",
|
||||
"z-ai-web-dev-sdk": "^0.0.18",
|
||||
"zod": "^4.0.2",
|
||||
"zustand": "^5.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"bun-types": "^1.3.4",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "^16.1.1",
|
||||
"tailwindcss": "^4",
|
||||
"tw-animate-css": "^1.3.5",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
5
postcss.config.mjs
Normal file
5
postcss.config.mjs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
const config = {
|
||||
plugins: ["@tailwindcss/postcss"],
|
||||
};
|
||||
|
||||
export default config;
|
||||
27
prisma/schema.prisma
Normal file
27
prisma/schema.prisma
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model Preset {
|
||||
id String @id @default(cuid())
|
||||
name String @unique
|
||||
author String @default("")
|
||||
description String @default("")
|
||||
content String
|
||||
isBuiltIn Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model Settings {
|
||||
id String @id @default("main")
|
||||
defaultScript String?
|
||||
bandConfig String?
|
||||
beatConfig String?
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
BIN
public/avs-originals/Synth-C - Gap The Mind.avs
Normal file
BIN
public/avs-originals/Synth-C - Gap The Mind.avs
Normal file
Binary file not shown.
BIN
public/avs-originals/Synth-C - Quantization.avs
Normal file
BIN
public/avs-originals/Synth-C - Quantization.avs
Normal file
Binary file not shown.
BIN
public/avs-originals/zamuz - keep tryin.avs
Normal file
BIN
public/avs-originals/zamuz - keep tryin.avs
Normal file
Binary file not shown.
BIN
public/avs-originals/zamuz - vorticity brain activity remix.avs
Normal file
BIN
public/avs-originals/zamuz - vorticity brain activity remix.avs
Normal file
Binary file not shown.
BIN
public/avs-originals/zamuz - wonder bout.avs
Normal file
BIN
public/avs-originals/zamuz - wonder bout.avs
Normal file
Binary file not shown.
29
public/logo.svg
Normal file
29
public/logo.svg
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 30 30" style="enable-background:new 0 0 30 30;" xml:space="preserve">
|
||||
<defs>
|
||||
<style type="text/css">
|
||||
.st194{fill:#2D2D2D;stroke:#FFFFFF;stroke-width:0.6317;stroke-miterlimit:10;}
|
||||
.st23{fill:#FFFFFF;}
|
||||
|
||||
.z-breathe {
|
||||
animation: breathe 2.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes breathe {
|
||||
0%, 100% { opacity: 0.7; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
</style>
|
||||
</defs>
|
||||
|
||||
<g>
|
||||
<path class="st194" d="M24.51,28.51H5.49c-2.21,0-4-1.79-4-4V5.49c0-2.21,1.79-4,4-4h19.03c2.21,0,4,1.79,4,4v19.03
|
||||
C28.51,26.72,26.72,28.51,24.51,28.51z"/>
|
||||
<g class="z-breathe">
|
||||
<path class="st23" d="M15.47,7.1l-1.3,1.85c-0.2,0.29-0.54,0.47-0.9,0.47h-7.1V7.09C6.16,7.1,15.47,7.1,15.47,7.1z"/>
|
||||
<polygon class="st23" points="24.3,7.1 13.14,22.91 5.7,22.91 16.86,7.1"/>
|
||||
<path class="st23" d="M14.53,22.91l1.31-1.86c0.2-0.29,0.54-0.47,0.9-0.47h7.09v2.33H14.53z"/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1 KiB |
14
public/robots.txt
Normal file
14
public/robots.txt
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
User-agent: Googlebot
|
||||
Allow: /
|
||||
|
||||
User-agent: Bingbot
|
||||
Allow: /
|
||||
|
||||
User-agent: Twitterbot
|
||||
Allow: /
|
||||
|
||||
User-agent: facebookexternalhit
|
||||
Allow: /
|
||||
|
||||
User-agent: *
|
||||
Allow: /
|
||||
1
rust-agent/.gitignore
vendored
Normal file
1
rust-agent/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/target
|
||||
25
rust-agent/Cargo.toml
Normal file
25
rust-agent/Cargo.toml
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
[package]
|
||||
name = "ava-agent"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "AVA — Advanced Visualization Agent · native (Rust + wgpu) scaffold"
|
||||
license = "MIT"
|
||||
|
||||
# Web reference implementation: ../src/lib/ava/* (Next.js edition).
|
||||
# This crate ports the same engine: band analysis, beat prediction, the
|
||||
# AVS-eel flavored script language and the .ava preset format.
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# Force genuine Vulkan everywhere — on macOS this means Vulkan through
|
||||
# MoltenVK (install the Vulkan SDK first) instead of wgpu's Metal path.
|
||||
vulkan-force = []
|
||||
|
||||
[dependencies]
|
||||
winit = "0.30"
|
||||
wgpu = "22"
|
||||
cpal = "0.15"
|
||||
rustfft = "6.2"
|
||||
anyhow = "1"
|
||||
pollster = "0.3"
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
115
rust-agent/README.md
Normal file
115
rust-agent/README.md
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
# ava-agent — AVA native scaffold (Rust + wgpu)
|
||||
|
||||
Native counterpart of the **AVA — Advanced Visualization Agent** web edition
|
||||
(the Next.js reference implementation lives at the repository root). One cargo
|
||||
crate that runs the *same* `.ava` visualization scripts: cpal audio capture →
|
||||
rustfft band analysis → the ported beat predictor → the AVS-eel expression
|
||||
engine → a wgpu (Vulkan-first) renderer.
|
||||
|
||||
The portability contract: every script under `presets/` runs **unmodified** on
|
||||
both engines.
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
┌──────────────────────────── ava-agent (binary) ───────────────────────────┐
|
||||
│ │
|
||||
│ cpal input thread ──► RingBuffer ──► spectrum.rs (rustfft 8192, Hann) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ audio.rs BandLevels (bass/mid/treb + _att, attack 35 ms / release │
|
||||
│ 220 ms — identical constants to the web engine) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ beat.rs BeatTracker: detect → learn (median+EMA) → predict (PLL) │
|
||||
│ ▲ └── tap tempo (Space) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ script/ .ava parser + expression engine │
|
||||
│ [init] once · [frame] ×1 · [beat] on beats · [point] ×n │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ render/ wgpu: fade → audio-reactive background → additive points │
|
||||
└──────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Web ↔ native module map:
|
||||
|
||||
| web (`src/lib/ava/`) | native (`src/`) |
|
||||
| ------------------------------- | -------------------------------- |
|
||||
| `audio.ts` (WebAudio Analyser) | `audio.rs` + `spectrum.rs` |
|
||||
| `beat.ts` | `beat.rs` (statement-for-statement) |
|
||||
| `expression.ts` / `script.ts` | `script/{lexer,parser,env,mod}.rs` |
|
||||
| `engine.ts` (rAF loop + Canvas2D) | `engine.rs` + `render/{mod.rs,shader.wgsl}` |
|
||||
| `presets.ts` | `presets/*.ava` |
|
||||
|
||||
## Building
|
||||
|
||||
### Linux (Debian / Ubuntu)
|
||||
|
||||
```sh
|
||||
sudo apt install libasound2-dev libvulkan-dev # or: libvulkan1 vulkan-loader
|
||||
cargo run --release -- --preset presets/gap-the-mind.ava
|
||||
```
|
||||
|
||||
wgpu speaks native Vulkan on Linux; if no Vulkan loader is present the agent
|
||||
falls back to other primary backends with a warning.
|
||||
|
||||
### Windows
|
||||
|
||||
1. Install [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/)
|
||||
(C++ workload) and Rust with the `x86_64-pc-windows-msvc` toolchain.
|
||||
2. `cargo run --release -- --preset presets/gap-the-mind.ava`
|
||||
|
||||
wgpu picks the best available backend — Vulkan preferred (per the project's
|
||||
Vulkan requirement), DX12 as the practical fallback on machines without a
|
||||
Vulkan driver.
|
||||
|
||||
### macOS
|
||||
|
||||
```sh
|
||||
cargo run --release -- --preset presets/gap-the-mind.ava
|
||||
```
|
||||
|
||||
By default this uses **Metal** via wgpu's automatic backend selection (macOS
|
||||
has no native Vulkan). For **strict Vulkan** install the
|
||||
[Vulkan SDK](https://vulkan.lunarg.com/sdk/home) (MoltenVK) and build with:
|
||||
|
||||
```sh
|
||||
cargo run --release --features vulkan-force -- --preset presets/gap-the-mind.ava
|
||||
```
|
||||
|
||||
One codebase, three platforms, Vulkan-first.
|
||||
|
||||
## Controls & CLI
|
||||
|
||||
| input | action |
|
||||
| ---------------- | --------------------------------------------------------- |
|
||||
| `Space` | beat tap tempo ("Set Beat") — the planned `--bpm-tap` key |
|
||||
| `Esc` | quit |
|
||||
|
||||
```text
|
||||
ava-agent [--preset <path.ava>] [--input <device-index|default>] [--list-devices]
|
||||
```
|
||||
|
||||
- `--preset path.ava` — load a visualization script (see `presets/`)
|
||||
- `--input <index>` — pick an audio input device by index (`--list-devices`
|
||||
enumerates them); `default` uses the system default input
|
||||
- Audio capture failing? The agent exits with the full device list; feed line-in
|
||||
or a loopback device via `--input`.
|
||||
|
||||
## Port status
|
||||
|
||||
| area | status |
|
||||
| ----------------------------- | ------ |
|
||||
| audio capture (cpal) | ✓ |
|
||||
| FFT / 3-band analysis | ✓ (bass 20–100 Hz · mid 700–2000 Hz · high 7000–16000 Hz, tunable via `BandConfig`) |
|
||||
| beat tracker + predictor | ✓ (1:1 port of `beat.ts`) |
|
||||
| script engine | ✓ (subset: same grammar & function set; no `reg[]` buffers yet) |
|
||||
| renderer | ✓ (basic reactive fullscreen shader + additive point cloud) |
|
||||
| AVS compatibility | partial (the 5 adapted presets run identically; raw Winamp AVS features like Texer sprites are roadmap items) |
|
||||
|
||||
Known v0 simplifications (search `TODO(avb)` in the source): persistence
|
||||
trails use a fade pass instead of an offscreen feedback texture, `solid`
|
||||
render mode falls back to points, and point `size` is not yet honored
|
||||
(wgpu point-list draws single pixels).
|
||||
35
rust-agent/presets/gap-the-mind.ava
Normal file
35
rust-agent/presets/gap-the-mind.ava
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
# Adapted from "Synth-C - Gap The Mind" (Winamp AVS / visbot.net)
|
||||
# Core of the original Superscope preserved:
|
||||
# r = i*2pi; d = snd; x = sin(r)*d; y = cos(r)*d
|
||||
# d = d*(1 - sin((r-pi/2)*7)*.03); r = r + cos(d*12)*.03
|
||||
name: Gap The Mind
|
||||
author: synth-c (adapted)
|
||||
mode: lines
|
||||
blend: additive
|
||||
persist: 0.9
|
||||
linewidth: 2
|
||||
|
||||
[init]
|
||||
n = 480
|
||||
hue = 0
|
||||
rot = 0
|
||||
avg = 0
|
||||
|
||||
[frame]
|
||||
# rolling average of the audio energy (the original used a getosc ring buffer)
|
||||
avg = avg * 0.8 + (bass + vol) * 0.2
|
||||
hue = hue + dt * (0.05 + mid * 0.12) + beat * 0.015
|
||||
rot = rot + dt * (0.1 + mid_att * 0.9)
|
||||
rad = 0.25 + avg * 0.85
|
||||
warp = 1 + treb * 0.5
|
||||
|
||||
[point]
|
||||
r = i * 6.28318
|
||||
d = rad + abs(v) * 0.45
|
||||
d = d * (1 - sin((r - 1.5708) * 7) * 0.03 * warp)
|
||||
r = r + cos(d * 12) * 0.03 * warp + rot
|
||||
x = sin(r) * d / aspect
|
||||
y = cos(r) * d
|
||||
red = 0.5 + 0.5 * sin(hue * 6.28318)
|
||||
green = 0.5 + 0.5 * sin(hue * 6.28318 + 2.094)
|
||||
blue = 0.5 + 0.5 * sin(hue * 6.28318 + 4.188)
|
||||
34
rust-agent/presets/keep-tryin.ava
Normal file
34
rust-agent/presets/keep-tryin.ava
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
# Adapted from "keep tryin'" by zamuz (Winamp AVS / visbot.net)
|
||||
# Original Texer II dots: rs = getspec(.1,.1,0)*3 + .3 on spawn,
|
||||
# swirl movement x = x + .002*sin(y*20); y = y + .002*sin(x*20).
|
||||
name: keep tryin'
|
||||
author: zamuz (adapted)
|
||||
mode: dots
|
||||
blend: additive
|
||||
persist: 0.85
|
||||
linewidth: 3
|
||||
|
||||
[init]
|
||||
n = 900
|
||||
travel = 0
|
||||
hue = 0
|
||||
|
||||
[frame]
|
||||
travel = travel + dt * (0.35 + bass_att * 1.2)
|
||||
swirl = 0.15 + mid * 0.5
|
||||
hue = hue + dt * 0.15
|
||||
|
||||
[point]
|
||||
d = frac(rand(i + 0.13) + travel)
|
||||
ang = rand(i + 0.77) * 6.28318 + d * swirl * 6.28318
|
||||
rad = d * (0.3 + bass * 0.7)
|
||||
x0 = sin(ang) * rad
|
||||
y0 = cos(ang) * rad
|
||||
# the swirl distortion from the original movement
|
||||
x = x0 + 0.05 * sin(y0 * 20) / aspect
|
||||
y = y0 + 0.05 * sin(x0 * 20)
|
||||
fade = sin(d * 3.14159)
|
||||
red = fade * (0.25 + 0.75 * sin(hue * 6.28318))
|
||||
green = fade * (0.25 + 0.75 * sin(hue * 6.28318 + 2.09))
|
||||
blue = fade * (0.25 + 0.75 * sin(hue * 6.28318 + 4.19))
|
||||
size = 1.5 + treb * 3
|
||||
34
rust-agent/presets/quantization.ava
Normal file
34
rust-agent/presets/quantization.ava
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
# Adapted from "Synth-C - Quantization" (Winamp AVS / visbot.net)
|
||||
# Original Superscope: r = i*2pi; d = snd + .5; x = sin(r)*d; y = cos(r)*d
|
||||
# with pixel quantization x = ((x*40)|0)/40 and a dot-fog sound heightmap.
|
||||
name: Quantization
|
||||
author: synth-c (adapted)
|
||||
mode: dots
|
||||
blend: additive
|
||||
persist: 0.82
|
||||
linewidth: 3
|
||||
|
||||
[init]
|
||||
n = 720
|
||||
hue = 0
|
||||
q = 34
|
||||
avg = 0
|
||||
|
||||
[frame]
|
||||
hue = hue + dt * 0.06
|
||||
avg = avg * 0.8 + vol * 0.2
|
||||
rad = 0.28 + avg * 0.75
|
||||
zoom = 0.9 + bass * 0.3
|
||||
|
||||
[point]
|
||||
r = i * 6.28318
|
||||
d = rad + abs(v) * 0.4
|
||||
x0 = sin(r) * d * zoom
|
||||
y0 = cos(r) * d * zoom
|
||||
# snap to the quantization grid (the |0 division from the original)
|
||||
x = floor(x0 * q) / q / aspect
|
||||
y = floor(y0 * q) / q
|
||||
red = 0.5 + 0.5 * sin(hue * 6.28318 + d * 3)
|
||||
green = 0.5 + 0.5 * sin(hue * 6.28318 + d * 3 + 2.09)
|
||||
blue = 0.5 + 0.5 * sin(hue * 6.28318 + d * 3 + 4.19)
|
||||
size = 2 + mid * 5
|
||||
30
rust-agent/presets/starter.ava
Normal file
30
rust-agent/presets/starter.ava
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# AVA visualization script — starter template
|
||||
# Tap "Help" in the editor for the full variable & function reference.
|
||||
name: My Visualization
|
||||
author: you
|
||||
mode: lines
|
||||
blend: additive
|
||||
persist: 0.85
|
||||
linewidth: 2
|
||||
|
||||
[init]
|
||||
n = 400
|
||||
t = 0
|
||||
|
||||
[frame]
|
||||
# t advances faster when the bass hits
|
||||
t = t + dt * (0.5 + bass)
|
||||
hue = hue + dt * 0.05
|
||||
|
||||
[beat]
|
||||
flash = 1
|
||||
|
||||
[point]
|
||||
# a circle whose radius breathes with the bass
|
||||
a = i * 6.28318
|
||||
rad = 0.2 + bass * 0.5 + flash * 0.05
|
||||
x = sin(a + t) * rad / aspect
|
||||
y = cos(a + t) * rad
|
||||
red = 0.2 + bass
|
||||
green = 0.8
|
||||
blue = 0.25 + treb
|
||||
33
rust-agent/presets/vorticity.ava
Normal file
33
rust-agent/presets/vorticity.ava
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
# Adapted from "vorticity (brain activity remix)" — original by synth-c,
|
||||
# remix by zamuz (Winamp AVS / visbot.net). The original ran 3D particle
|
||||
# trails through rotating vector fields at sound-driven speed (sndspd = 10).
|
||||
name: vorticity
|
||||
author: synth-c / zamuz (adapted)
|
||||
mode: lines
|
||||
blend: additive
|
||||
persist: 0.92
|
||||
linewidth: 1.6
|
||||
|
||||
[init]
|
||||
n = 1200
|
||||
t = 0
|
||||
hue = 0
|
||||
|
||||
[frame]
|
||||
t = t + dt * (0.4 + bass_att * 1.6)
|
||||
twist = 1.2 + mid * 2.6
|
||||
zoom = 0.75 + bass * 0.45
|
||||
hue = hue + dt * 0.04 + beat * 0.01
|
||||
|
||||
[point]
|
||||
arm = floor(i * 6)
|
||||
fa = frac(i * 6)
|
||||
d = fa
|
||||
ang = arm * 1.047 + d * twist * 3.14159 + t
|
||||
rad = (0.06 + d * d * 1.1) * zoom
|
||||
x = sin(ang) * rad / aspect
|
||||
y = cos(ang) * rad
|
||||
red = (0.3 + 0.7 * d) * (0.35 + bass)
|
||||
green = (0.3 + 0.7 * d) * (0.25 + mid)
|
||||
blue = (0.3 + 0.7 * d) * (0.2 + treb + hue * 0.25)
|
||||
skip = if(below(fa, 0.03), 1, 0)
|
||||
40
rust-agent/presets/wonder-bout.ava
Normal file
40
rust-agent/presets/wonder-bout.ava
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
# Adapted from "wonder 'bout" by zamuz (Winamp AVS / visbot.net)
|
||||
# The original spawned Texer II ring sprites: ss = ss + .05 per frame,
|
||||
# size = |ss| * min(w,h)*.006, random color & position on wrap,
|
||||
# grow-scale sampled from the bass (getspec(.1,.1,0)).
|
||||
name: wonder 'bout
|
||||
author: zamuz (adapted)
|
||||
mode: lines
|
||||
blend: additive
|
||||
persist: 0.88
|
||||
linewidth: 1.8
|
||||
|
||||
[init]
|
||||
n = 480
|
||||
groups = 12
|
||||
hue = 0
|
||||
|
||||
[frame]
|
||||
# expansion speed rises with the smoothed bass (original: reg01 = .05/frame)
|
||||
speed = 0.25 + bass_att * 0.9
|
||||
hue = hue + dt * 0.1
|
||||
|
||||
[point]
|
||||
g = floor(i * groups)
|
||||
gi = frac(i * groups)
|
||||
# per-ring phase, drifting at its own tempo
|
||||
ph = frac(rand(g * 7.3 + 1) + time * speed * (0.7 + rand(g + 31) * 0.6))
|
||||
px0 = rand(g + 3.7) * 1.7 - 0.85
|
||||
py0 = rand(g + 9.1) * 1.7 - 0.85
|
||||
rad = ph * (0.3 + bass * 0.6)
|
||||
cr = rand(g + 21.7)
|
||||
cg = rand(g + 15.3)
|
||||
cb = rand(g + 27.9)
|
||||
fade = (1 - ph) * (0.25 + ph * 2.2)
|
||||
a = 6.28318 * (gi * 1.05 - 0.025)
|
||||
x = px0 + cos(a) * rad / aspect
|
||||
y = py0 + sin(a) * rad
|
||||
red = cr * fade * (0.7 + 0.3 * sin(hue * 6.28318 + g))
|
||||
green = cg * fade * (0.7 + 0.3 * sin(hue * 6.28318 + g + 2.09))
|
||||
blue = cb * fade * (0.7 + 0.3 * sin(hue * 6.28318 + g + 4.19))
|
||||
skip = if(below(gi, 0.025), 1, 0)
|
||||
328
rust-agent/src/audio.rs
Normal file
328
rust-agent/src/audio.rs
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
//! AVA — native audio capture + band level pipeline (cpal).
|
||||
//!
|
||||
//! Web ↔ native mapping: `src/lib/ava/audio.ts` (Web Audio AnalyserNode) →
|
||||
//! this module + `spectrum.rs`. A cpal input stream runs on its own thread
|
||||
//! and pushes mono frames into a lock-guarded ring buffer;
|
||||
//! [`AudioProcessor::poll`] — called once per frame from the render loop —
|
||||
//! windows the last FFT_SIZE samples, runs the spectrum analysis and applies
|
||||
//! the same fast-attack (tau 35 ms) / slow-release (tau 220 ms) smoothing as
|
||||
//! the web engine.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
|
||||
use crate::spectrum::{band_level, Spectrum, SpectrumAnalyzer, FFT_SIZE};
|
||||
|
||||
/// Ring capacity — twice the FFT window so we always have full history.
|
||||
const RING_CAPACITY: usize = FFT_SIZE * 2;
|
||||
|
||||
/// Attack / release smoothing time constants — identical to audio.ts.
|
||||
const ATTACK_TAU: f32 = 0.035; // seconds
|
||||
const RELEASE_TAU: f32 = 0.22; // seconds
|
||||
|
||||
/// Band ranges + gains — mirrors `BandConfig` in types.ts
|
||||
/// (bass 20–100 Hz · mid 700–2000 Hz · high 7000–16000 Hz, user-tunable).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BandConfig {
|
||||
pub bass_low: f32,
|
||||
pub bass_high: f32,
|
||||
pub mid_low: f32,
|
||||
pub mid_high: f32,
|
||||
pub high_low: f32,
|
||||
pub high_high: f32,
|
||||
pub bass_gain: f32,
|
||||
pub mid_gain: f32,
|
||||
pub high_gain: f32,
|
||||
}
|
||||
|
||||
impl Default for BandConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bass_low: 20.0,
|
||||
bass_high: 100.0,
|
||||
mid_low: 700.0,
|
||||
mid_high: 2000.0,
|
||||
high_low: 7000.0,
|
||||
high_high: 16000.0,
|
||||
bass_gain: 1.0,
|
||||
mid_gain: 1.25,
|
||||
high_gain: 1.6,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Instant + smoothed band levels (0..1+) — mirrors `BandLevels` in types.ts.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct BandLevels {
|
||||
pub bass: f32,
|
||||
pub mid: f32,
|
||||
pub treb: f32,
|
||||
pub bass_att: f32,
|
||||
pub mid_att: f32,
|
||||
pub treb_att: f32,
|
||||
pub vol: f32,
|
||||
pub vol_att: f32,
|
||||
}
|
||||
|
||||
/// Lock-guarded mono ring buffer shared with the cpal callback thread.
|
||||
struct Ring {
|
||||
buf: Vec<f32>,
|
||||
write: usize,
|
||||
filled: usize,
|
||||
channels: u16,
|
||||
}
|
||||
|
||||
impl Ring {
|
||||
fn new(capacity: usize, channels: u16) -> Self {
|
||||
Self {
|
||||
buf: vec![0.0; capacity],
|
||||
write: 0,
|
||||
filled: 0,
|
||||
channels,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_frame(&mut self, sample: f32) {
|
||||
self.buf[self.write] = sample;
|
||||
self.write = (self.write + 1) % self.buf.len();
|
||||
self.filled = (self.filled + 1).min(self.buf.len());
|
||||
}
|
||||
|
||||
/// Copy the last `out.len()` samples into `out` in chronological order,
|
||||
/// zero-padding the front when the buffer has not filled yet.
|
||||
fn snapshot_last(&self, out: &mut [f32]) {
|
||||
let want = out.len();
|
||||
let avail = self.filled.min(want);
|
||||
let pad = want - avail;
|
||||
out[..pad].fill(0.0);
|
||||
for k in 0..avail {
|
||||
let idx = (self.write + self.buf.len() - avail + k) % self.buf.len();
|
||||
out[pad + k] = self.buf[idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Average interleaved input frames (any channel count) into mono samples.
|
||||
fn push_frames(ring: &Arc<Mutex<Ring>>, data: &[f32]) {
|
||||
if let Ok(mut guard) = ring.lock() {
|
||||
let ch = guard.channels as usize;
|
||||
for frame in data.chunks(ch) {
|
||||
let mono = frame.iter().sum::<f32>() / frame.len() as f32;
|
||||
guard.push_frame(mono);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pick_input_device(host: &cpal::Host, index: Option<usize>) -> Result<cpal::Device> {
|
||||
match index {
|
||||
None => host.default_input_device().ok_or_else(|| {
|
||||
anyhow!(
|
||||
"no default audio input device — available inputs:\n{}",
|
||||
list_input_devices(host)
|
||||
)
|
||||
}),
|
||||
Some(idx) => {
|
||||
let mut devices = host
|
||||
.input_devices()
|
||||
.map_err(|err| anyhow!("failed to enumerate input devices: {err}"))?;
|
||||
devices.nth(idx).ok_or_else(|| {
|
||||
anyhow!(
|
||||
"no input device at index {idx} — available inputs:\n{}",
|
||||
list_input_devices(host)
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_input_devices(host: &cpal::Host) -> String {
|
||||
let mut out = String::new();
|
||||
match host.input_devices() {
|
||||
Ok(devices) => {
|
||||
for (idx, d) in devices.enumerate() {
|
||||
let name = d.name().unwrap_or_else(|_| "<unnamed>".into());
|
||||
out.push_str(&format!(" [{idx}] {name}\n"));
|
||||
}
|
||||
}
|
||||
Err(err) => out.push_str(&format!(" (failed to list devices: {err})\n")),
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push_str(" (none found)\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Enumerate the default host's input devices (for `--list-devices`).
|
||||
pub fn list_default_host_input_devices() -> String {
|
||||
list_input_devices(&cpal::default_host())
|
||||
}
|
||||
|
||||
/// Owns the capture stream and produces per-frame [`BandLevels`].
|
||||
pub struct AudioProcessor {
|
||||
config: BandConfig,
|
||||
levels: BandLevels,
|
||||
analyzer: SpectrumAnalyzer,
|
||||
ring: Arc<Mutex<Ring>>,
|
||||
/// Kept alive on purpose: dropping a cpal `Stream` stops capture.
|
||||
_stream: cpal::Stream,
|
||||
sample_rate: f32,
|
||||
device_name: String,
|
||||
analysis_buf: Vec<f32>,
|
||||
last_spectrum: Option<Spectrum>,
|
||||
}
|
||||
|
||||
impl AudioProcessor {
|
||||
/// Open an input device (system default, or `device_index`) and start
|
||||
/// capturing. 48 kHz mono is preferred; if the device refuses we fall
|
||||
/// back to its default configuration.
|
||||
pub fn start(device_index: Option<usize>) -> Result<Self> {
|
||||
let host = cpal::default_host();
|
||||
let device = pick_input_device(&host, device_index)?;
|
||||
let device_name = device.name().unwrap_or_else(|_| "<unnamed>".into());
|
||||
let supported = device.default_input_config().map_err(|err| {
|
||||
anyhow!("input device '{device_name}' reports no default config: {err}")
|
||||
})?;
|
||||
|
||||
// --- attempt 1: f32, mono, 48 kHz (the preferred config) ------------
|
||||
let preferred = cpal::StreamConfig {
|
||||
channels: 1,
|
||||
sample_rate: cpal::SampleRate(48_000),
|
||||
buffer_size: cpal::BufferSize::Default,
|
||||
};
|
||||
let ring = Arc::new(Mutex::new(Ring::new(RING_CAPACITY, 1)));
|
||||
let preferred_stream = {
|
||||
let r = Arc::clone(&ring);
|
||||
device.build_input_stream(
|
||||
&preferred,
|
||||
move |data: &[f32], _info: &cpal::InputCallbackInfo| push_frames(&r, data),
|
||||
|err| eprintln!("[ava] audio stream error: {err}"),
|
||||
None,
|
||||
)
|
||||
};
|
||||
|
||||
// --- attempt 2: the device's own default config + native format -----
|
||||
let (config, ring, stream) = match preferred_stream {
|
||||
Ok(stream) => (preferred, ring, stream),
|
||||
Err(_) => {
|
||||
let default_cfg = supported.config().clone();
|
||||
let ring = Arc::new(Mutex::new(Ring::new(RING_CAPACITY, default_cfg.channels)));
|
||||
let r = Arc::clone(&ring);
|
||||
let stream: cpal::Stream = match supported.sample_format() {
|
||||
cpal::SampleFormat::F32 => device.build_input_stream(
|
||||
&default_cfg,
|
||||
move |data: &[f32], _info: &cpal::InputCallbackInfo| push_frames(&r, data),
|
||||
|err| eprintln!("[ava] audio stream error: {err}"),
|
||||
None,
|
||||
)?,
|
||||
cpal::SampleFormat::I16 => device.build_input_stream(
|
||||
&default_cfg,
|
||||
move |data: &[i16], _info: &cpal::InputCallbackInfo| {
|
||||
// i16 → f32 with the standard 32768 scale
|
||||
let mono: Vec<f32> =
|
||||
data.iter().map(|&s| s as f32 / 32768.0).collect();
|
||||
push_frames(&r, &mono);
|
||||
},
|
||||
|err| eprintln!("[ava] audio stream error: {err}"),
|
||||
None,
|
||||
)?,
|
||||
other => bail!(
|
||||
"input device uses unsupported sample format {other:?} \
|
||||
(TODO(avb): u16/24-bit conversion)"
|
||||
),
|
||||
};
|
||||
(default_cfg, ring, stream)
|
||||
}
|
||||
};
|
||||
|
||||
stream
|
||||
.play()
|
||||
.map_err(|err| anyhow!("failed to start the input stream on '{device_name}': {err}"))?;
|
||||
println!(
|
||||
"[ava] audio: '{device_name}' — {} Hz, {} ch, {:?}",
|
||||
config.sample_rate.0,
|
||||
config.channels,
|
||||
supported.sample_format()
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
config: BandConfig::default(),
|
||||
levels: BandLevels::default(),
|
||||
analyzer: SpectrumAnalyzer::new(),
|
||||
ring,
|
||||
_stream: stream,
|
||||
sample_rate: config.sample_rate.0 as f32,
|
||||
device_name,
|
||||
analysis_buf: vec![0.0; FFT_SIZE],
|
||||
last_spectrum: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn device_name(&self) -> &str {
|
||||
&self.device_name
|
||||
}
|
||||
|
||||
pub fn sample_rate(&self) -> f32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
/// Replace the band config (CLI / UI hook — matches the web edition's
|
||||
/// user-tunable Hz ranges in types.ts).
|
||||
pub fn set_band_config(&mut self, cfg: BandConfig) {
|
||||
self.config = cfg;
|
||||
}
|
||||
|
||||
/// Analyze the current input and update the smoothed levels.
|
||||
/// Call once per rendered frame — the native twin of `getBands()`.
|
||||
pub fn poll(&mut self, dt_sec: f32) -> BandLevels {
|
||||
// window the last FFT_SIZE samples (the web AnalyserNode does the
|
||||
// equivalent internally over the same length)
|
||||
{
|
||||
let mut guard = self.ring.lock().expect("audio ring buffer poisoned");
|
||||
guard.snapshot_last(&mut self.analysis_buf);
|
||||
}
|
||||
let spectrum = self.analyzer.analyze(&self.analysis_buf, self.sample_rate);
|
||||
|
||||
let cfg = self.config;
|
||||
let bass = band_level(&spectrum.mags, cfg.bass_low, cfg.bass_high, self.sample_rate)
|
||||
* cfg.bass_gain;
|
||||
let mid = band_level(&spectrum.mags, cfg.mid_low, cfg.mid_high, self.sample_rate)
|
||||
* cfg.mid_gain;
|
||||
let treb = band_level(&spectrum.mags, cfg.high_low, cfg.high_high, self.sample_rate)
|
||||
* cfg.high_gain;
|
||||
|
||||
// fast attack / slow release — the *_att variables of the web engine
|
||||
let smooth = |target: f32, current: f32| -> f32 {
|
||||
let tau = if target > current { ATTACK_TAU } else { RELEASE_TAU };
|
||||
current + (target - current) * (1.0 - (-dt_sec / tau).exp())
|
||||
};
|
||||
|
||||
self.levels.bass = bass;
|
||||
self.levels.mid = mid;
|
||||
self.levels.treb = treb;
|
||||
self.levels.vol = (bass + mid + treb) / 3.0;
|
||||
self.levels.bass_att = smooth(bass, self.levels.bass_att);
|
||||
self.levels.mid_att = smooth(mid, self.levels.mid_att);
|
||||
self.levels.treb_att = smooth(treb, self.levels.treb_att);
|
||||
self.levels.vol_att = smooth(self.levels.vol, self.levels.vol_att);
|
||||
|
||||
self.last_spectrum = Some(spectrum);
|
||||
self.levels
|
||||
}
|
||||
|
||||
/// Waveform sample for the script `v` variable (0..1 → -1..1).
|
||||
pub fn wave(&self, pos: f64) -> f64 {
|
||||
match &self.last_spectrum {
|
||||
Some(s) => s.wave_at(pos),
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Spectrum sample for the script `sv` variable (0..1 → 0..1).
|
||||
pub fn spectrum(&self, pos: f64) -> f64 {
|
||||
match &self.last_spectrum {
|
||||
Some(s) => s.spectrum_at(pos),
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
328
rust-agent/src/beat.rs
Normal file
328
rust-agent/src/beat.rs
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
//! AVA — beat detection, tempo tracking & prediction.
|
||||
//!
|
||||
//! Faithful port of the web reference implementation (`src/lib/ava/beat.ts`) —
|
||||
//! the logic mirrors the original statement for statement:
|
||||
//!
|
||||
//! 1. DETECT — a beat fires when the smoothed bass energy exceeds
|
||||
//! `threshold ×` the rolling average (last ~60 frames),
|
||||
//! gated by `min_interval` and an absolute floor.
|
||||
//! 2. LEARN — consecutive beat intervals build a BPM estimate; when the
|
||||
//! intervals are consistent (low spread), the period is locked
|
||||
//! with an exponential moving average and confidence rises.
|
||||
//! 3. PREDICT — a phase accumulator advances by dt/period every frame. When
|
||||
//! the bass drops out, the predictor keeps firing beats on the
|
||||
//! learned grid so the visuals never lose the beat.
|
||||
//! 4. TAP — the "Set Beat" control (the Space key): taps lock the
|
||||
//! period + phase from the tap intervals (median), teaching
|
||||
//! the tracker the song's beat.
|
||||
//!
|
||||
//! Web ↔ native mapping: `update()` is called once per rendered frame with
|
||||
//! the smoothed bass level, exactly like the web engine's rAF loop.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
const HISTORY_SIZE: usize = 60;
|
||||
const MAX_INTERVALS: usize = 10;
|
||||
/// Tap-tempo buffer length (exposed for the UI's tap counter readout).
|
||||
pub const MAX_TAPS: usize = 8;
|
||||
const TAP_RESET_MS: f64 = 2500.0;
|
||||
|
||||
/// Beat detector / predictor configuration — mirrors `BeatConfig` in types.ts.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BeatConfig {
|
||||
/// Energy multiplier over the rolling average required to fire a beat.
|
||||
pub threshold: f64,
|
||||
/// Minimum milliseconds between beats.
|
||||
pub min_interval: f64,
|
||||
/// Absolute floor for the smoothed bass level.
|
||||
pub floor_level: f64,
|
||||
/// Keep firing predicted beats when the bass drops out.
|
||||
pub prediction: bool,
|
||||
}
|
||||
|
||||
impl Default for BeatConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
threshold: 1.4,
|
||||
min_interval: 250.0,
|
||||
floor_level: 0.04,
|
||||
prediction: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a beat came from — mirrors `BeatSource` in types.ts.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BeatSource {
|
||||
/// Detected from the audio's bass energy.
|
||||
Audio,
|
||||
/// Fired by the phase-locked predictor while the bass was absent.
|
||||
Predicted,
|
||||
/// User tap ("Set Beat" / Space). Used by the UI layer to label taps.
|
||||
#[allow(dead_code)]
|
||||
Tap,
|
||||
/// No beat this frame.
|
||||
None,
|
||||
}
|
||||
|
||||
/// Per-frame beat state — mirrors `BeatFrame` in types.ts.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BeatFrame {
|
||||
/// True on the frame a beat fired (audio, predicted, or tap).
|
||||
pub beat: bool,
|
||||
pub source: BeatSource,
|
||||
/// Estimated BPM (0 while unknown).
|
||||
pub bpm: f64,
|
||||
/// 0..1 phase within the current beat period (from the predictor).
|
||||
pub phase: f64,
|
||||
/// 0..1 confidence of the tempo lock.
|
||||
pub confidence: f64,
|
||||
}
|
||||
|
||||
/// Result of a user tap — mirrors `TapResult` in beat.ts.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TapResult {
|
||||
pub bpm: f64,
|
||||
pub phase: f64,
|
||||
pub confidence: f64,
|
||||
pub tap_count: usize,
|
||||
/// true when enough taps have accumulated to lock a tempo.
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
/// Median of a slice (does not modify the input) — the TS `median()` helper.
|
||||
fn median(values: &[f64]) -> f64 {
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let mid = sorted.len() >> 1;
|
||||
if sorted.len() % 2 == 1 {
|
||||
sorted[mid]
|
||||
} else {
|
||||
(sorted[mid - 1] + sorted[mid]) / 2.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the period inside 60..200 BPM equivalent — the TS `foldPeriod()`.
|
||||
fn fold_period(ms: f64) -> f64 {
|
||||
let mut p = ms;
|
||||
while p > 1000.0 {
|
||||
p /= 2.0;
|
||||
}
|
||||
while p < 300.0 {
|
||||
p *= 2.0;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
pub struct BeatTracker {
|
||||
pub cfg: BeatConfig,
|
||||
history: VecDeque<f64>,
|
||||
intervals: VecDeque<f64>,
|
||||
taps: VecDeque<f64>,
|
||||
last_tap_at: f64,
|
||||
period_ms: f64,
|
||||
phase: f64,
|
||||
bpm: f64,
|
||||
confidence: f64,
|
||||
last_beat_at: f64,
|
||||
last_real_beat_at: f64,
|
||||
prev_real_beat_at: f64,
|
||||
beat_count: u64,
|
||||
}
|
||||
|
||||
impl BeatTracker {
|
||||
pub fn new(cfg: BeatConfig) -> Self {
|
||||
Self {
|
||||
cfg,
|
||||
history: VecDeque::with_capacity(HISTORY_SIZE + 1),
|
||||
intervals: VecDeque::with_capacity(MAX_INTERVALS + 1),
|
||||
taps: VecDeque::with_capacity(MAX_TAPS + 1),
|
||||
last_tap_at: -1e9,
|
||||
period_ms: 500.0,
|
||||
phase: 0.0,
|
||||
bpm: 0.0,
|
||||
confidence: 0.0,
|
||||
last_beat_at: -1e9,
|
||||
last_real_beat_at: -1e9,
|
||||
prev_real_beat_at: -1e9,
|
||||
beat_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.history.clear();
|
||||
self.intervals.clear();
|
||||
self.taps.clear();
|
||||
self.period_ms = 500.0;
|
||||
self.phase = 0.0;
|
||||
self.bpm = 0.0;
|
||||
self.confidence = 0.0;
|
||||
self.last_beat_at = -1e9;
|
||||
self.last_real_beat_at = -1e9;
|
||||
self.prev_real_beat_at = -1e9;
|
||||
self.beat_count = 0;
|
||||
}
|
||||
|
||||
pub fn beat_count(&self) -> u64 {
|
||||
self.beat_count
|
||||
}
|
||||
|
||||
pub fn bpm(&self) -> f64 {
|
||||
self.bpm
|
||||
}
|
||||
|
||||
/// Current phase (0..1) — for UI indicators.
|
||||
pub fn phase(&self) -> f64 {
|
||||
self.phase
|
||||
}
|
||||
|
||||
/// Advance the tracker one frame.
|
||||
///
|
||||
/// * `bass_att` — smoothed bass level (the detector input)
|
||||
/// * `now_ms` — monotonic clock in milliseconds
|
||||
/// * `dt_sec` — frame delta in seconds
|
||||
/// * `cfg` — optional live config update (the web UI does this)
|
||||
pub fn update(&mut self, bass_att: f64, now_ms: f64, dt_sec: f64, cfg: Option<&BeatConfig>) -> BeatFrame {
|
||||
if let Some(cfg) = cfg {
|
||||
self.cfg = *cfg;
|
||||
}
|
||||
|
||||
// --- rolling energy history -------------------------------------------
|
||||
self.history.push_back(bass_att);
|
||||
while self.history.len() > HISTORY_SIZE {
|
||||
self.history.pop_front();
|
||||
}
|
||||
let avg: f64 = self.history.iter().sum::<f64>() / self.history.len() as f64;
|
||||
|
||||
let mut beat = false;
|
||||
let mut source = BeatSource::None;
|
||||
|
||||
// --- real beat detection ----------------------------------------------
|
||||
if bass_att > self.cfg.floor_level
|
||||
&& bass_att > avg * self.cfg.threshold
|
||||
&& now_ms - self.last_beat_at >= self.cfg.min_interval
|
||||
{
|
||||
beat = true;
|
||||
source = BeatSource::Audio;
|
||||
self.last_beat_at = now_ms;
|
||||
self.last_real_beat_at = now_ms;
|
||||
self.beat_count += 1;
|
||||
|
||||
// interval learning
|
||||
if self.prev_real_beat_at > 0.0 {
|
||||
let interval = now_ms - self.prev_real_beat_at;
|
||||
if (200.0..=2500.0).contains(&interval) {
|
||||
self.intervals.push_back(interval);
|
||||
while self.intervals.len() > MAX_INTERVALS {
|
||||
self.intervals.pop_front();
|
||||
}
|
||||
if self.intervals.len() >= 3 {
|
||||
let med = median(&self.intervals);
|
||||
let mean =
|
||||
self.intervals.iter().sum::<f64>() / self.intervals.len() as f64;
|
||||
let variance = self
|
||||
.intervals
|
||||
.iter()
|
||||
.map(|b| (b - mean) * (b - mean))
|
||||
.sum::<f64>()
|
||||
/ self.intervals.len() as f64;
|
||||
let spread = variance.sqrt() / mean.max(1.0);
|
||||
if spread < 0.3 {
|
||||
// consistent tempo: lock the period (EMA) and gain confidence
|
||||
self.period_ms = self.period_ms * 0.6 + fold_period(med) * 0.4;
|
||||
self.bpm = (60000.0 / self.period_ms * 10.0).round() / 10.0;
|
||||
self.confidence = (self.confidence + 0.2).min(1.0);
|
||||
} else {
|
||||
// irregular — trust it less
|
||||
self.confidence = (self.confidence - 0.05).max(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.prev_real_beat_at = now_ms;
|
||||
self.phase = 0.0;
|
||||
}
|
||||
|
||||
// --- predictor (phase-locked grid) -------------------------------------
|
||||
if self.period_ms > 50.0 {
|
||||
self.phase += (dt_sec * 1000.0) / self.period_ms;
|
||||
}
|
||||
if self.phase >= 1.0 {
|
||||
self.phase -= self.phase.floor();
|
||||
let bass_gone = now_ms - self.last_real_beat_at > self.period_ms * 1.4;
|
||||
if !beat
|
||||
&& self.cfg.prediction
|
||||
&& self.confidence > 0.35
|
||||
&& bass_gone
|
||||
&& now_ms - self.last_beat_at >= self.cfg.min_interval
|
||||
{
|
||||
beat = true;
|
||||
source = BeatSource::Predicted;
|
||||
self.last_beat_at = now_ms;
|
||||
self.beat_count += 1;
|
||||
// predicted beats slowly spend confidence so a stale lock fades out
|
||||
self.confidence = (self.confidence - 0.02).max(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
// --- confidence decay when audio beats disappear -----------------------
|
||||
if now_ms - self.last_real_beat_at > 2000.0 && self.taps.is_empty() {
|
||||
self.confidence = (self.confidence - dt_sec * 0.06).max(0.0);
|
||||
}
|
||||
|
||||
BeatFrame {
|
||||
beat,
|
||||
source,
|
||||
bpm: self.bpm,
|
||||
phase: self.phase,
|
||||
confidence: self.confidence,
|
||||
}
|
||||
}
|
||||
|
||||
/// "Set Beat" — user taps to the music. Two or more taps lock the tempo
|
||||
/// (median of tap intervals) and re-phase the predictor to the taps.
|
||||
pub fn tap(&mut self, now_ms: f64) -> TapResult {
|
||||
if now_ms - self.last_tap_at > TAP_RESET_MS {
|
||||
self.taps.clear();
|
||||
}
|
||||
self.last_tap_at = now_ms;
|
||||
self.taps.push_back(now_ms);
|
||||
while self.taps.len() > MAX_TAPS {
|
||||
self.taps.pop_front();
|
||||
}
|
||||
|
||||
// immediate visual feedback + re-phase
|
||||
self.beat_count += 1;
|
||||
self.last_beat_at = now_ms;
|
||||
self.phase = 0.0;
|
||||
|
||||
if self.taps.len() >= 2 {
|
||||
let gaps: Vec<f64> = self
|
||||
.taps
|
||||
.iter()
|
||||
.zip(self.taps.iter().skip(1))
|
||||
.map(|(a, b)| b - a)
|
||||
.collect();
|
||||
let med = median(&gaps);
|
||||
if (250.0..=1500.0).contains(&med) {
|
||||
self.period_ms = fold_period(med);
|
||||
self.bpm = (60000.0 / self.period_ms * 10.0).round() / 10.0;
|
||||
self.confidence = (0.45 + 0.11 * self.taps.len() as f64).min(1.0);
|
||||
// keep the interval learner in sync with the tapped grid
|
||||
// (gaps ≤ MAX_TAPS-1 ≤ MAX_INTERVALS, so this is the full list)
|
||||
self.intervals = gaps.iter().copied().collect();
|
||||
self.last_real_beat_at = now_ms;
|
||||
}
|
||||
} else {
|
||||
self.confidence = self.confidence.max(0.25);
|
||||
}
|
||||
|
||||
TapResult {
|
||||
bpm: self.bpm,
|
||||
phase: self.phase,
|
||||
confidence: self.confidence,
|
||||
tap_count: self.taps.len(),
|
||||
locked: self.taps.len() >= 2 && self.bpm > 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
231
rust-agent/src/engine.rs
Normal file
231
rust-agent/src/engine.rs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
//! AVA engine — the native twin of `AvaEngine` in `src/lib/ava/engine.ts`.
|
||||
//!
|
||||
//! Owns the audio processor, the beat tracker and the script state, and runs
|
||||
//! the per-frame tick:
|
||||
//!
|
||||
//! ```text
|
||||
//! bands → beat → env update → [frame] (+[beat]) → [point] ×n → render inputs
|
||||
//! ```
|
||||
//!
|
||||
//! The tick is driven by winit's `RedrawRequested` (see main.rs) instead of
|
||||
//! requestAnimationFrame; everything else matches the web engine's loop
|
||||
//! statement for statement, including the environment variable set, the
|
||||
//! per-point output resets and the pen/`skip` line-strip logic.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::audio::{AudioProcessor, BandLevels};
|
||||
use crate::beat::{BeatFrame, BeatTracker};
|
||||
use crate::render::{Point, Renderer, Uniforms};
|
||||
use crate::script::env::{get, set};
|
||||
use crate::script::{AvaScript, Env, RenderMode};
|
||||
|
||||
/// Hard cap on evaluated points per frame — matches engine.ts.
|
||||
pub const MAX_POINTS: usize = 4096;
|
||||
/// Fallback surface size before the renderer exists.
|
||||
pub const DEFAULT_SIZE: (u32, u32) = (1280, 720);
|
||||
|
||||
pub struct Engine {
|
||||
pub audio: Option<AudioProcessor>,
|
||||
pub beat: BeatTracker,
|
||||
pub script: Option<AvaScript>,
|
||||
env: Env,
|
||||
points: Vec<Point>,
|
||||
started: Instant,
|
||||
last_frame: Instant,
|
||||
beat_flash: f32,
|
||||
frames: u64,
|
||||
total_beats: u64,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new(script: Option<AvaScript>, audio: Option<AudioProcessor>) -> Self {
|
||||
// Fresh environment + [init] — mirrors AvaEngine::setScript().
|
||||
let mut env = Env::new();
|
||||
set(&mut env, "n", 400.0);
|
||||
set(&mut env, "t", 0.0);
|
||||
set(&mut env, "time", 0.0);
|
||||
set(&mut env, "frame", 0.0);
|
||||
set(&mut env, "beats", 0.0);
|
||||
if let Some(s) = &script {
|
||||
s.run_init(&mut env);
|
||||
}
|
||||
let now = Instant::now();
|
||||
Self {
|
||||
audio,
|
||||
beat: BeatTracker::new(Default::default()),
|
||||
script,
|
||||
env,
|
||||
points: Vec::with_capacity(MAX_POINTS * 2),
|
||||
started: now,
|
||||
last_frame: now,
|
||||
beat_flash: 0.0,
|
||||
frames: 0,
|
||||
total_beats: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Monotonic milliseconds since engine start (the beat tracker clock).
|
||||
pub fn now_ms(&self) -> f64 {
|
||||
self.started.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// "Set Beat" tap tempo — the Space key handler.
|
||||
pub fn tap(&mut self) {
|
||||
let tap = self.beat.tap(self.now_ms());
|
||||
println!(
|
||||
"[ava] tap {}/{} — {} (confidence {:.2})",
|
||||
tap.tap_count,
|
||||
crate::beat::MAX_TAPS,
|
||||
if tap.bpm > 0.0 {
|
||||
format!("{:.1} BPM", tap.bpm)
|
||||
} else {
|
||||
"…".to_string()
|
||||
},
|
||||
tap.confidence
|
||||
);
|
||||
}
|
||||
|
||||
/// One engine frame: analyze, track, script, then push points +
|
||||
/// uniforms through the renderer (the rAF loop body in engine.ts).
|
||||
pub fn tick(&mut self, renderer: Option<&mut Renderer>) {
|
||||
let now = self.started.elapsed().as_secs_f64();
|
||||
let dt = self.last_frame.elapsed().as_secs_f32().clamp(0.0005, 0.1);
|
||||
self.last_frame = Instant::now();
|
||||
self.frames += 1;
|
||||
|
||||
// ---- audio bands + beat tracking ---------------------------------
|
||||
let levels: BandLevels = match &mut self.audio {
|
||||
Some(a) => a.poll(dt),
|
||||
None => BandLevels::default(),
|
||||
};
|
||||
let beat_frame: BeatFrame =
|
||||
self.beat.update(levels.bass_att as f64, now * 1000.0, dt as f64, None);
|
||||
self.beat_flash *= (-dt * 8.0).exp(); // ~90 ms visual flash decay
|
||||
if beat_frame.beat {
|
||||
self.beat_flash = 1.0;
|
||||
}
|
||||
self.total_beats += u64::from(beat_frame.beat);
|
||||
|
||||
let (w, h) = renderer
|
||||
.as_ref()
|
||||
.map(|r| r.size())
|
||||
.unwrap_or(DEFAULT_SIZE);
|
||||
let base_persist = self.script.as_ref().map(|s| s.meta.persist).unwrap_or(0.85);
|
||||
|
||||
// ---- environment (the same variables as the web engine) -----------
|
||||
{
|
||||
let env = &mut self.env;
|
||||
for (name, value) in [
|
||||
("dt", dt as f64),
|
||||
("time", now),
|
||||
("frame", self.frames as f64),
|
||||
("bass", levels.bass as f64),
|
||||
("mid", levels.mid as f64),
|
||||
("treb", levels.treb as f64),
|
||||
("bass_att", levels.bass_att as f64),
|
||||
("mid_att", levels.mid_att as f64),
|
||||
("treb_att", levels.treb_att as f64),
|
||||
("vol", levels.vol as f64),
|
||||
("vol_att", levels.vol_att as f64),
|
||||
("beat", f64::from(beat_frame.beat)),
|
||||
("bpm", beat_frame.bpm),
|
||||
("beatphase", beat_frame.phase),
|
||||
("beatconf", beat_frame.confidence),
|
||||
("beats", self.total_beats as f64),
|
||||
("w", w as f64),
|
||||
("h", h as f64),
|
||||
("aspect", w as f64 / h.max(1) as f64),
|
||||
("persist", base_persist), // reset so the script can override
|
||||
] {
|
||||
set(env, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- [frame] (+ [beat] on beat frames) -----------------------------
|
||||
if let Some(s) = &self.script {
|
||||
s.run_frame(&mut self.env);
|
||||
if beat_frame.beat {
|
||||
s.run_beat(&mut self.env);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- [point] × n -----------------------------------------------------
|
||||
self.points.clear();
|
||||
if let Some(s) = &self.script {
|
||||
if s.point_prog.is_some() {
|
||||
let mode = s.meta.mode;
|
||||
let linewidth = s.meta.linewidth;
|
||||
let n = get(&self.env, "n").round().clamp(4.0, MAX_POINTS as f64) as usize;
|
||||
let mut pen: Option<Point> = None; // previous unskipped point (lines)
|
||||
for k in 0..n {
|
||||
let i = if n > 1 { k as f64 / (n - 1) as f64 } else { 0.0 };
|
||||
set(&mut self.env, "i", i);
|
||||
set(&mut self.env, "v", self.audio.as_ref().map(|a| a.wave(i)).unwrap_or(0.0));
|
||||
set(&mut self.env, "sv", self.audio.as_ref().map(|a| a.spectrum(i)).unwrap_or(0.0));
|
||||
// reset output variables (custom variables persist, AVS-style)
|
||||
for (name, value) in [
|
||||
("x", 0.0), ("y", 0.0), ("red", 1.0), ("green", 1.0),
|
||||
("blue", 1.0), ("skip", 0.0), ("size", linewidth), ("alpha", 1.0),
|
||||
] {
|
||||
set(&mut self.env, name, value);
|
||||
}
|
||||
s.run_point(&mut self.env);
|
||||
|
||||
if get(&self.env, "skip") > 0.5 {
|
||||
pen = None;
|
||||
continue;
|
||||
}
|
||||
let p = Point {
|
||||
x: get(&self.env, "x") as f32,
|
||||
y: get(&self.env, "y") as f32,
|
||||
r: (get(&self.env, "red") as f32).clamp(0.0, 1.0),
|
||||
g: (get(&self.env, "green") as f32).clamp(0.0, 1.0),
|
||||
b: (get(&self.env, "blue") as f32).clamp(0.0, 1.0),
|
||||
a: (get(&self.env, "alpha") as f32).clamp(0.0, 1.0),
|
||||
};
|
||||
if mode == RenderMode::Lines {
|
||||
// line-list: emit prev→p segments; `skip` breaks the
|
||||
// strip (the pen logic in engine.ts)
|
||||
if let Some(prev) = pen.take() {
|
||||
self.points.push(prev);
|
||||
self.points.push(p);
|
||||
}
|
||||
pen = Some(p);
|
||||
} else {
|
||||
// dots (and solid until a fill pipeline exists — TODO(avb))
|
||||
self.points.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- upload + render --------------------------------------------------
|
||||
let persist = get(&self.env, "persist").clamp(0.0, 0.985) as f32;
|
||||
if let Some(renderer) = renderer {
|
||||
renderer.update_points(&self.points);
|
||||
let uniforms = Uniforms {
|
||||
time: now as f32,
|
||||
dt,
|
||||
bass: levels.bass,
|
||||
mid: levels.mid,
|
||||
treb: levels.treb,
|
||||
bass_att: levels.bass_att,
|
||||
mid_att: levels.mid_att,
|
||||
treb_att: levels.treb_att,
|
||||
vol: levels.vol,
|
||||
vol_att: levels.vol_att,
|
||||
beat: self.beat_flash,
|
||||
bpm: beat_frame.bpm as f32,
|
||||
beatphase: beat_frame.phase as f32,
|
||||
aspect: w as f32 / h.max(1) as f32,
|
||||
resolution: [w as f32, h as f32],
|
||||
persist,
|
||||
..Default::default()
|
||||
};
|
||||
if let Err(err) = renderer.render(&uniforms) {
|
||||
eprintln!("[ava] render error: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
229
rust-agent/src/main.rs
Normal file
229
rust-agent/src/main.rs
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
//! AVA — Advanced Visualization Agent · native scaffold (Rust + wgpu).
|
||||
//!
|
||||
//! This binary wires the modules together (the same engine stages as
|
||||
//! `src/lib/ava/engine.ts`):
|
||||
//!
|
||||
//! ```text
|
||||
//! cpal capture thread → ring buffer → band analysis (spectrum.rs)
|
||||
//! → beat tracker (beat.rs) → script engine (script/, driven by engine.rs)
|
||||
//! → wgpu renderer (render/) → screen
|
||||
//! ```
|
||||
//!
|
||||
//! main.rs stays orchestration-only: CLI, window, wgpu bootstrap, event loop.
|
||||
//! The event loop uses winit 0.30's `ApplicationHandler` trait with
|
||||
//! continuous rendering (`about_to_wait` → `request_redraw` →
|
||||
//! `RedrawRequested` → `Engine::tick`).
|
||||
|
||||
mod audio;
|
||||
mod beat;
|
||||
mod engine;
|
||||
mod render;
|
||||
mod script;
|
||||
mod spectrum;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::{ElementState, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::keyboard::{KeyCode, PhysicalKey};
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
use engine::Engine;
|
||||
use render::Renderer;
|
||||
|
||||
// ------------------------------------------------------------ CLI parsing
|
||||
|
||||
struct Options {
|
||||
/// Path to a .ava preset script (optional).
|
||||
preset: Option<PathBuf>,
|
||||
/// Input device index (`--input 2`); None = system default.
|
||||
input: Option<usize>,
|
||||
}
|
||||
|
||||
fn print_usage() {
|
||||
println!("AVA — Advanced Visualization Agent (native scaffold)");
|
||||
println!();
|
||||
println!("USAGE:");
|
||||
println!(" ava-agent [--preset <path.ava>] [--input <device-index|default>]");
|
||||
println!();
|
||||
println!("OPTIONS:");
|
||||
println!(" --preset <path> load a .ava visualization script");
|
||||
println!(" --input <index> audio input device (default: system default)");
|
||||
println!(" --list-devices list audio input devices and exit");
|
||||
println!();
|
||||
println!("CONTROLS:");
|
||||
println!(" Space — beat tap tempo (the planned --bpm-tap key)");
|
||||
println!(" Esc — quit");
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Options> {
|
||||
let mut opts = Options { preset: None, input: None };
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"-h" | "--help" => {
|
||||
print_usage();
|
||||
std::process::exit(0);
|
||||
}
|
||||
"--list-devices" => {
|
||||
println!("audio input devices:\n{}", audio::list_default_host_input_devices());
|
||||
std::process::exit(0);
|
||||
}
|
||||
"--preset" => {
|
||||
let v = args.next().context("--preset expects a path to a .ava script")?;
|
||||
opts.preset = Some(PathBuf::from(v));
|
||||
}
|
||||
"--input" => {
|
||||
let v = args.next().context("--input expects <device-index|default>")?;
|
||||
if v != "default" {
|
||||
opts.input =
|
||||
Some(v.parse().with_context(|| format!("bad device index '{v}'"))?);
|
||||
}
|
||||
}
|
||||
other => bail!("unknown argument '{other}' — see --help"),
|
||||
}
|
||||
}
|
||||
Ok(opts)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- app
|
||||
|
||||
/// Window + renderer + engine state. The native twin of the web app's
|
||||
/// `AvaEngine` singleton attached to its canvas.
|
||||
struct App {
|
||||
window: Option<Window>,
|
||||
renderer: Option<Renderer>,
|
||||
engine: Engine,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return; // already initialized (resumed can re-fire on some platforms)
|
||||
}
|
||||
let attrs = Window::default_attributes()
|
||||
.with_title("AVA — Advanced Visualization Agent")
|
||||
.with_inner_size(winit::dpi::PhysicalSize::new(1280u32, 720u32));
|
||||
let window = match event_loop.create_window(attrs) {
|
||||
Ok(w) => w,
|
||||
Err(err) => {
|
||||
eprintln!("[ava] window creation failed: {err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let size = window.inner_size();
|
||||
let mut renderer =
|
||||
match pollster::block_on(Renderer::init(&window, size.width, size.height)) {
|
||||
Ok(r) => r,
|
||||
Err(err) => {
|
||||
eprintln!("[ava] renderer init failed: {err:#}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(s) = &self.engine.script {
|
||||
renderer.set_mode(s.meta.mode);
|
||||
}
|
||||
self.renderer = Some(renderer);
|
||||
self.window = Some(window);
|
||||
}
|
||||
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::Resized(size) => {
|
||||
if let Some(r) = &mut self.renderer {
|
||||
r.resize(size.width, size.height);
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
if event.state == ElementState::Pressed {
|
||||
if let PhysicalKey::Code(code) = event.physical_key {
|
||||
match code {
|
||||
// "Set Beat" tap tempo (the planned --bpm-tap key)
|
||||
KeyCode::Space => self.engine.tap(),
|
||||
KeyCode::Escape => event_loop.exit(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
let renderer = self.renderer.as_mut();
|
||||
self.engine.tick(renderer);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
// continuous render loop: keep the redraw requests flowing
|
||||
if let Some(window) = &self.window {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let opts = parse_args()?;
|
||||
|
||||
// ---- preset script (optional) ------------------------------------------
|
||||
let script = match &opts.preset {
|
||||
Some(path) => {
|
||||
let text = std::fs::read_to_string(path)
|
||||
.with_context(|| format!("failed to read preset {}", path.display()))?;
|
||||
match script::parse_script(&text) {
|
||||
Ok(s) => {
|
||||
println!(
|
||||
"[ava] preset '{}' by {} — mode {:?}, blend {:?}, {} point statement(s)",
|
||||
s.meta.name,
|
||||
s.meta.author,
|
||||
s.meta.mode,
|
||||
s.meta.blend,
|
||||
s.point_prog.as_ref().map(|p| p.statement_count()).unwrap_or(0)
|
||||
);
|
||||
Some(s)
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("[ava] preset error: {err}");
|
||||
bail!("failed to parse {}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
println!(
|
||||
"[ava] no --preset given — rendering the background only \
|
||||
(try --preset presets/starter.ava)"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// ---- audio input ---------------------------------------------------------
|
||||
let audio = match audio::AudioProcessor::start(opts.input) {
|
||||
Ok(a) => Some(a),
|
||||
Err(err) => {
|
||||
eprintln!("[ava] audio capture failed: {err:#}");
|
||||
eprintln!(
|
||||
"[ava] available input devices:\n{}",
|
||||
audio::list_default_host_input_devices()
|
||||
);
|
||||
return Err(err.context("no usable audio input — pick one with --input <index>"));
|
||||
}
|
||||
};
|
||||
|
||||
println!("[ava] starting window (Space = tap tempo, Esc = quit)");
|
||||
let event_loop = EventLoop::new().context("failed to create the winit event loop")?;
|
||||
let mut app = App {
|
||||
window: None,
|
||||
renderer: None,
|
||||
engine: Engine::new(script, audio),
|
||||
};
|
||||
event_loop
|
||||
.run_app(&mut app)
|
||||
.map_err(|err| anyhow::anyhow!("event loop terminated with error: {err}"))?;
|
||||
Ok(())
|
||||
}
|
||||
458
rust-agent/src/render/mod.rs
Normal file
458
rust-agent/src/render/mod.rs
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
//! wgpu renderer — the native counterpart of the Canvas2D renderer in
|
||||
//! `src/lib/ava/engine.ts`.
|
||||
//!
|
||||
//! Pass order per frame:
|
||||
//! 1. **fade** — fullscreen black quad at alpha `1 - persist`
|
||||
//! (v0 persistence; TODO(avb): offscreen feedback
|
||||
//! texture for true motion trails)
|
||||
//! 2. **background** — audio-reactive radial gradient (WGSL, dark base
|
||||
//! with neon-green / amber accents)
|
||||
//! 3. **content** — line-list or point-list point cloud with
|
||||
//! per-vertex color and additive blending (the
|
||||
//! equivalent of the web engine's `'lighter'`
|
||||
//! composite mode)
|
||||
//!
|
||||
//! Backend selection honors the `vulkan-force` cargo feature (strict Vulkan,
|
||||
//! i.e. MoltenVK on macOS); otherwise Linux/Windows try Vulkan first and fall
|
||||
//! back to other primary backends with a warning, and macOS uses Metal.
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
|
||||
use crate::script::RenderMode;
|
||||
|
||||
/// Hard cap on evaluated points — matches `MAX_POINTS` in engine.ts.
|
||||
pub const MAX_POINTS: usize = 4096;
|
||||
/// Line-list needs two vertices per segment.
|
||||
const MAX_VERTICES: usize = MAX_POINTS * 2;
|
||||
|
||||
/// One visible point in NDC-ish script space (-1..1, +y up) with linear RGBA.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Point {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub r: f32,
|
||||
pub g: f32,
|
||||
pub b: f32,
|
||||
pub a: f32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
|
||||
struct Vertex {
|
||||
pos: [f32; 2],
|
||||
color: [f32; 4],
|
||||
}
|
||||
|
||||
impl Vertex {
|
||||
const ATTRIBUTES: [wgpu::VertexAttribute; 2] =
|
||||
wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x4];
|
||||
|
||||
fn layout() -> wgpu::VertexBufferLayout<'static> {
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &Vertex::ATTRIBUTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-frame uniforms shared by every pipeline (mirrors the WGSL `Uniforms`).
|
||||
///
|
||||
/// NOTE: `beat` is a decaying flash envelope (set to 1 on a beat frame,
|
||||
/// decays exponentially in the engine tick) rather than the raw 0/1 script
|
||||
/// variable — shaders are stateless, so the decay happens on the CPU.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
|
||||
pub struct Uniforms {
|
||||
pub time: f32,
|
||||
pub dt: f32,
|
||||
pub bass: f32,
|
||||
pub mid: f32,
|
||||
pub treb: f32,
|
||||
pub bass_att: f32,
|
||||
pub mid_att: f32,
|
||||
pub treb_att: f32,
|
||||
pub vol: f32,
|
||||
pub vol_att: f32,
|
||||
pub beat: f32,
|
||||
pub bpm: f32,
|
||||
pub beatphase: f32,
|
||||
pub aspect: f32,
|
||||
pub resolution: [f32; 2],
|
||||
pub persist: f32,
|
||||
pad0: f32,
|
||||
pad1: f32,
|
||||
pad2: f32,
|
||||
}
|
||||
|
||||
/// Additive blending — the native equivalent of the web engine's
|
||||
/// `globalCompositeOperation = 'lighter'`.
|
||||
const ADDITIVE: wgpu::BlendState = wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::One,
|
||||
dst_factor: wgpu::BlendFactor::One,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::One,
|
||||
dst_factor: wgpu::BlendFactor::One,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
};
|
||||
|
||||
/// Backend strategy: Vulkan-first per the project requirements.
|
||||
fn backend_attempts() -> &'static [(&'static str, wgpu::Backends)] {
|
||||
if cfg!(feature = "vulkan-force") {
|
||||
&[
|
||||
("Vulkan (vulkan-force)", wgpu::Backends::VULKAN),
|
||||
("primary fallback", wgpu::Backends::PRIMARY),
|
||||
]
|
||||
} else if cfg!(any(target_os = "linux", target_os = "windows")) {
|
||||
&[
|
||||
("Vulkan", wgpu::Backends::VULKAN),
|
||||
("primary fallback", wgpu::Backends::PRIMARY),
|
||||
]
|
||||
} else if cfg!(target_os = "macos") {
|
||||
println!(
|
||||
"[ava] macOS: using Metal through wgpu (strict Vulkan: install the \
|
||||
Vulkan SDK and build with --features vulkan-force)"
|
||||
);
|
||||
&[("Metal", wgpu::Backends::METAL)]
|
||||
} else {
|
||||
&[("primary", wgpu::Backends::PRIMARY)]
|
||||
}
|
||||
}
|
||||
|
||||
async fn surface_and_adapter(
|
||||
window: &winit::window::Window,
|
||||
) -> Result<(wgpu::Instance, wgpu::Surface<'static>, wgpu::Adapter)> {
|
||||
let mut notes: Vec<String> = Vec::new();
|
||||
for (label, backends) in backend_attempts() {
|
||||
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
|
||||
backends: *backends,
|
||||
..Default::default()
|
||||
});
|
||||
let surface = match instance.create_surface(window.clone()) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
notes.push(format!("{label}: surface creation failed ({err})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
})
|
||||
.await;
|
||||
if let Some(adapter) = adapter {
|
||||
let info = adapter.get_info();
|
||||
println!(
|
||||
"[ava] GPU: {} ({:?} backend, {:?})",
|
||||
info.name, info.backend, info.device_type
|
||||
);
|
||||
return Ok((instance, surface, adapter));
|
||||
}
|
||||
notes.push(format!("{label}: no adapter with a compatible surface"));
|
||||
}
|
||||
Err(anyhow!(
|
||||
"no usable GPU adapter found — tried:{}",
|
||||
notes.iter().map(|n| format!("\n {n}")).collect::<String>()
|
||||
))
|
||||
}
|
||||
|
||||
fn create_pipeline(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::PipelineLayout,
|
||||
module: &wgpu::ShaderModule,
|
||||
label: &str,
|
||||
vs_entry: &str,
|
||||
fs_entry: &str,
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
vertex_buffers: &[wgpu::VertexBufferLayout<'_>],
|
||||
blend: wgpu::BlendState,
|
||||
format: wgpu::TextureFormat,
|
||||
) -> wgpu::RenderPipeline {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some(vs_entry),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
buffers: vertex_buffers,
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some(fs_entry),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
cache: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub struct Renderer {
|
||||
surface: wgpu::Surface<'static>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
config: wgpu::SurfaceConfiguration,
|
||||
uniform_buf: wgpu::Buffer,
|
||||
uniform_bg: wgpu::BindGroup,
|
||||
fade_pipeline: wgpu::RenderPipeline,
|
||||
bg_pipeline: wgpu::RenderPipeline,
|
||||
line_pipeline: wgpu::RenderPipeline,
|
||||
point_pipeline: wgpu::RenderPipeline,
|
||||
vertex_buf: wgpu::Buffer,
|
||||
staging: Vec<Vertex>,
|
||||
vertex_count: u32,
|
||||
mode: RenderMode,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
/// Create surface + device + pipelines. Async (wgpu adapter/device
|
||||
/// requests are futures in wgpu 22) — call via `pollster::block_on`.
|
||||
pub async fn init(
|
||||
window: &winit::window::Window,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Result<Self> {
|
||||
let (instance, surface, adapter) = surface_and_adapter(window).await?;
|
||||
|
||||
let (device, queue) = adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: Some("ava-device"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::default(),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| anyhow!("failed to request a wgpu device: {err}"))?;
|
||||
|
||||
let caps = surface.get_capabilities(&adapter);
|
||||
let format = caps
|
||||
.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|f| f.is_srgb())
|
||||
.or_else(|| caps.formats.first().copied())
|
||||
.unwrap_or(wgpu::TextureFormat::Bgra8UnormSrgb);
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format,
|
||||
width: width.max(1),
|
||||
height: height.max(1),
|
||||
present_mode: wgpu::PresentMode::Fifo, // vsync
|
||||
alpha_mode: wgpu::CompositeAlphaMode::Auto,
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
};
|
||||
surface.configure(&device, &config);
|
||||
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("ava-shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
|
||||
});
|
||||
|
||||
// one uniform buffer shared by all pipelines
|
||||
let uniform_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("ava-uniform-bgl"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu::BufferSize::new(
|
||||
std::mem::size_of::<Uniforms>() as u64
|
||||
),
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("ava-uniforms"),
|
||||
size: std::mem::size_of::<Uniforms>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let uniform_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("ava-uniform-bg"),
|
||||
layout: &uniform_bgl,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: uniform_buf.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("ava-pipeline-layout"),
|
||||
bind_group_layouts: &[&uniform_bgl],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let fade_pipeline = create_pipeline(
|
||||
&device, &pipeline_layout, &shader, "ava-fade", "vs_fade", "fs_fade",
|
||||
wgpu::PrimitiveTopology::TriangleList, &[], wgpu::BlendState::ALPHA, format,
|
||||
);
|
||||
let bg_pipeline = create_pipeline(
|
||||
&device, &pipeline_layout, &shader, "ava-bg", "vs_bg", "fs_bg",
|
||||
wgpu::PrimitiveTopology::TriangleList, &[], wgpu::BlendState::ALPHA, format,
|
||||
);
|
||||
let line_pipeline = create_pipeline(
|
||||
&device, &pipeline_layout, &shader, "ava-lines", "vs_line", "fs_line",
|
||||
wgpu::PrimitiveTopology::LineList, &[Vertex::layout()], ADDITIVE, format,
|
||||
);
|
||||
let point_pipeline = create_pipeline(
|
||||
&device, &pipeline_layout, &shader, "ava-points", "vs_point", "fs_point",
|
||||
wgpu::PrimitiveTopology::PointList, &[Vertex::layout()], ADDITIVE, format,
|
||||
);
|
||||
|
||||
let vertex_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("ava-vertices"),
|
||||
size: (MAX_VERTICES * std::mem::size_of::<Vertex>()) as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
surface,
|
||||
device,
|
||||
queue,
|
||||
config,
|
||||
uniform_buf,
|
||||
uniform_bg,
|
||||
fade_pipeline,
|
||||
bg_pipeline,
|
||||
line_pipeline,
|
||||
point_pipeline,
|
||||
vertex_buf,
|
||||
staging: Vec::with_capacity(MAX_VERTICES),
|
||||
vertex_count: 0,
|
||||
mode: RenderMode::Lines,
|
||||
})
|
||||
}
|
||||
|
||||
/// Current surface size in physical pixels.
|
||||
pub fn size(&self) -> (u32, u32) {
|
||||
(self.config.width, self.config.height)
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
if width > 0 && height > 0 && (self.config.width != width || self.config.height != height) {
|
||||
self.config.width = width;
|
||||
self.config.height = height;
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the content pipeline (from the script's `mode:` header).
|
||||
pub fn set_mode(&mut self, mode: RenderMode) {
|
||||
self.mode = mode;
|
||||
}
|
||||
|
||||
/// Upload the visible point cloud.
|
||||
///
|
||||
/// For `lines` mode the caller passes pre-paired segment endpoints
|
||||
/// (2 vertices per segment — the `skip` handling lives in the engine
|
||||
/// tick, mirroring the pen logic in engine.ts); for `dots`/`solid` one
|
||||
/// vertex per point. `solid` currently renders as points — TODO(avb):
|
||||
/// triangle-strip fill pipeline.
|
||||
pub fn update_points(&mut self, points: &[Point]) {
|
||||
self.staging.clear();
|
||||
for p in points {
|
||||
self.staging.push(Vertex {
|
||||
pos: [p.x, p.y],
|
||||
color: [p.r, p.g, p.b, p.a],
|
||||
});
|
||||
}
|
||||
self.staging.truncate(MAX_VERTICES);
|
||||
if self.staging.is_empty() {
|
||||
self.vertex_count = 0;
|
||||
return;
|
||||
}
|
||||
self.queue
|
||||
.write_buffer(&self.vertex_buf, 0, bytemuck::cast_slice(&self.staging));
|
||||
self.vertex_count = self.staging.len() as u32;
|
||||
}
|
||||
|
||||
/// Render one frame: fade → background → additive point cloud.
|
||||
pub fn render(&mut self, uniforms: &Uniforms) -> Result<()> {
|
||||
self.queue
|
||||
.write_buffer(&self.uniform_buf, 0, bytemuck::bytes_of(uniforms));
|
||||
|
||||
let frame = match self.surface.get_current_texture() {
|
||||
Ok(f) => f,
|
||||
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
|
||||
// reconfigure and try once more
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
self.surface
|
||||
.get_current_texture()
|
||||
.map_err(|err| anyhow!("surface texture lost twice: {err}"))?
|
||||
}
|
||||
Err(err) => return Err(anyhow!("surface error: {err}")),
|
||||
};
|
||||
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("ava-encoder"),
|
||||
});
|
||||
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("ava-pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
// Load (not Clear): the fade pass reads the previous
|
||||
// frame — that is the whole persistence mechanism.
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
});
|
||||
|
||||
// 1. persistence fade toward black (alpha blend)
|
||||
pass.set_pipeline(&self.fade_pipeline);
|
||||
pass.set_bind_group(0, &self.uniform_bg, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
|
||||
// 2. audio-reactive background gradient
|
||||
pass.set_pipeline(&self.bg_pipeline);
|
||||
pass.draw(0..3, 0..1);
|
||||
|
||||
// 3. point cloud (additive, per-vertex color)
|
||||
if self.vertex_count > 0 {
|
||||
pass.set_pipeline(match self.mode {
|
||||
RenderMode::Lines => &self.line_pipeline,
|
||||
_ => &self.point_pipeline,
|
||||
});
|
||||
pass.set_bind_group(0, &self.uniform_bg, &[]);
|
||||
pass.set_vertex_buffer(0, self.vertex_buf.slice(..));
|
||||
pass.draw(0..self.vertex_count, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
self.queue.submit(Some(encoder.finish()));
|
||||
frame.present();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
134
rust-agent/src/render/shader.wgsl
Normal file
134
rust-agent/src/render/shader.wgsl
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// AVA — native renderer shaders (WGSL)
|
||||
//
|
||||
// Four entry points share one uniform block:
|
||||
// vs_fade / fs_fade — fullscreen persistence fade toward black
|
||||
// vs_bg / fs_bg — audio-reactive radial gradient background
|
||||
// vs_line / fs_line — point cloud, line-list topology
|
||||
// vs_point/ fs_point — point cloud, point-list topology
|
||||
//
|
||||
// Color language: dark base with neon-green / amber accents (no blue),
|
||||
// matching the web edition's look. The point cloud uses additive blending.
|
||||
|
||||
struct Uniforms {
|
||||
time: f32,
|
||||
dt: f32,
|
||||
bass: f32,
|
||||
mid: f32,
|
||||
treb: f32,
|
||||
bass_att: f32,
|
||||
mid_att: f32,
|
||||
treb_att: f32,
|
||||
vol: f32,
|
||||
vol_att: f32,
|
||||
beat: f32, // decaying beat-flash envelope 0..1
|
||||
bpm: f32,
|
||||
beatphase: f32,
|
||||
aspect: f32,
|
||||
resolution: vec2<f32>,
|
||||
persist: f32,
|
||||
pad0: f32,
|
||||
pad1: f32,
|
||||
pad2: f32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> u: Uniforms;
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
/// One large triangle covering the viewport — no vertex buffer needed.
|
||||
fn fullscreen_triangle(vi: u32) -> vec4<f32> {
|
||||
var p = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0),
|
||||
vec2<f32>( 3.0, -1.0),
|
||||
vec2<f32>(-1.0, 3.0),
|
||||
);
|
||||
return vec4<f32>(p[vi], 0.0, 1.0);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- fade pass
|
||||
// Higher `persist` -> less fade -> longer motion trails. This is the v0
|
||||
// stand-in for the web engine's per-frame `rgba(0,0,0,1-persist)` fillRect.
|
||||
|
||||
@vertex
|
||||
fn vs_fade(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
|
||||
return fullscreen_triangle(vi);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_fade() -> @location(0) vec4<f32> {
|
||||
let a = clamp(1.0 - u.persist, 0.01, 1.0);
|
||||
return vec4<f32>(0.0, 0.0, 0.0, a);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------- background pass
|
||||
|
||||
@vertex
|
||||
fn vs_bg(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
|
||||
return fullscreen_triangle(vi);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_bg(@builtin(position) frag: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let uv = frag.xy / u.resolution; // 0..1
|
||||
let p = (uv - 0.5) * vec2<f32>(u.aspect, 1.0); // aspect-corrected
|
||||
let r = length(p);
|
||||
|
||||
// slow breathing shimmer for the edge glow
|
||||
let pulse = 0.5 + 0.5 * cos(u.time * 1.7 + r * 6.0);
|
||||
|
||||
// bass -> warm amber glow at the center
|
||||
let warm = vec3<f32>(1.0, 0.62, 0.16);
|
||||
let glow = u.bass_att * exp(-r * 3.2) * 0.9;
|
||||
|
||||
// treble -> thin neon-green shimmer toward the edges
|
||||
let neon = vec3<f32>(0.25, 1.0, 0.45);
|
||||
let shimmer = u.treb_att * smoothstep(0.25, 0.9, r) * (0.35 + 0.3 * pulse) * 0.55;
|
||||
|
||||
// beat -> brief bright flash (the envelope decays on the CPU side)
|
||||
let flash = u.beat * exp(-r * 2.0) * 0.35;
|
||||
|
||||
let color = warm * glow + neon * shimmer + warm * flash;
|
||||
return vec4<f32>(color, 0.85);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ point cloud
|
||||
|
||||
struct PointIn {
|
||||
@location(0) pos: vec2<f32>,
|
||||
@location(1) color: vec4<f32>,
|
||||
};
|
||||
|
||||
struct PointOut {
|
||||
@builtin(position) pos: vec4<f32>,
|
||||
@location(0) color: vec4<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_line(in: PointIn) -> PointOut {
|
||||
var out: PointOut;
|
||||
// script space is NDC-shaped already (-1..1, +y up — the web engine maps
|
||||
// (0.5 - y*0.5) * height to the same orientation)
|
||||
out.pos = vec4<f32>(in.pos, 0.0, 1.0);
|
||||
out.color = in.color;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_line(in: PointOut) -> @location(0) vec4<f32> {
|
||||
return in.color;
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_point(in: PointIn) -> PointOut {
|
||||
var out: PointOut;
|
||||
out.pos = vec4<f32>(in.pos, 0.0, 1.0);
|
||||
out.color = in.color;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_point(in: PointOut) -> @location(0) vec4<f32> {
|
||||
// wgpu point-list draws single pixels — TODO(avb): instanced quad
|
||||
// sprites honoring the script `size` variable (see render/mod.rs).
|
||||
return in.color;
|
||||
}
|
||||
25
rust-agent/src/script/env.rs
Normal file
25
rust-agent/src/script/env.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
//! Script variable environment.
|
||||
//!
|
||||
//! Web ↔ native mapping: the web engine uses a plain JS object
|
||||
//! (`Record<string, number>`); here we use a `HashMap<String, f64>`. Unknown
|
||||
//! variables read as 0 and assignment inserts/overwrites — the same semantics
|
||||
//! as JS object property access, which the AVS-style scripts rely on
|
||||
//! (custom variables persist across [point] iterations).
|
||||
//!
|
||||
//! TODO(avb): performance — a flat `Vec<f64>` with name→slot interning at
|
||||
//! parse time would remove per-lookup hashing in the 4096-point loop.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Mutable variable environment shared by all sections of a script.
|
||||
pub type Env = HashMap<String, f64>;
|
||||
|
||||
/// Read a variable; missing variables are 0 (JS `undefined → 0` semantics).
|
||||
pub fn get(env: &Env, name: &str) -> f64 {
|
||||
env.get(name).copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Insert/overwrite a variable.
|
||||
pub fn set(env: &mut Env, name: &str, value: f64) {
|
||||
env.insert(name.to_string(), value);
|
||||
}
|
||||
140
rust-agent/src/script/lexer.rs
Normal file
140
rust-agent/src/script/lexer.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
//! Tokenizer — port of `tokenize()` in `src/lib/ava/expression.ts`.
|
||||
//!
|
||||
//! Rules (behavior-identical to the web engine):
|
||||
//! - newlines are statement separators (`;`) at paren depth 0; newlines
|
||||
//! inside parentheses are ignored
|
||||
//! - comments run from `#` or `//` to the end of the line
|
||||
//! - numbers: `1`, `1.5`, `.5`, `1e-3`
|
||||
//! - identifiers: `[A-Za-z_][A-Za-z0-9_]*`
|
||||
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TokenKind {
|
||||
Num,
|
||||
Ident,
|
||||
Op,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Token {
|
||||
pub kind: TokenKind,
|
||||
pub value: String,
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// Compile-time error carrying the source line — mirrors `ExpressionError`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExpressionError {
|
||||
pub message: String,
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExpressionError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{} (line {})", self.message, self.line)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ExpressionError {}
|
||||
|
||||
const TWO_CHAR_OPS: [&str; 6] = ["<=", ">=", "==", "!=", "&&", "||"];
|
||||
const ONE_CHAR_OPS: [char; 15] = [
|
||||
'+', '-', '*', '/', '%', '^', '<', '>', '=', '!', '?', ':', '(', ')', ',', ';',
|
||||
];
|
||||
|
||||
/// Tokenize script source. `base_line` is the 1-based line of the first
|
||||
/// character (sections pass their header line so errors line up with the
|
||||
/// original file).
|
||||
pub fn tokenize(src: &str, base_line: usize) -> Result<Vec<Token>, ExpressionError> {
|
||||
let chars: Vec<char> = src.chars().collect();
|
||||
let n = chars.len();
|
||||
let mut tokens = Vec::new();
|
||||
let mut i = 0usize;
|
||||
let mut line = base_line;
|
||||
let mut depth = 0usize; // paren depth — newlines inside parens are not separators
|
||||
|
||||
while i < n {
|
||||
let c = chars[i];
|
||||
match c {
|
||||
'\n' => {
|
||||
line += 1;
|
||||
i += 1;
|
||||
if depth == 0 {
|
||||
tokens.push(Token { kind: TokenKind::Op, value: ";".into(), line });
|
||||
}
|
||||
}
|
||||
'\r' | ' ' | '\t' => i += 1,
|
||||
// comments: '#' or '//'
|
||||
'#' => {
|
||||
while i < n && chars[i] != '\n' {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'/' if i + 1 < n && chars[i + 1] == '/' => {
|
||||
while i < n && chars[i] != '\n' {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
c if c.is_ascii_digit() || (c == '.' && i + 1 < n && chars[i + 1].is_ascii_digit()) => {
|
||||
let mut j = i;
|
||||
while j < n && (chars[j].is_ascii_digit() || chars[j] == '.') {
|
||||
j += 1;
|
||||
}
|
||||
if j < n && (chars[j] == 'e' || chars[j] == 'E')
|
||||
&& j + 1 < n
|
||||
&& (chars[j + 1].is_ascii_digit()
|
||||
|| chars[j + 1] == '+'
|
||||
|| chars[j + 1] == '-')
|
||||
{
|
||||
j += 2;
|
||||
while j < n && chars[j].is_ascii_digit() {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
tokens.push(Token {
|
||||
kind: TokenKind::Num,
|
||||
value: chars[i..j].iter().collect(),
|
||||
line,
|
||||
});
|
||||
i = j;
|
||||
}
|
||||
c if c.is_ascii_alphabetic() || c == '_' => {
|
||||
let mut j = i;
|
||||
while j < n && (chars[j].is_ascii_alphanumeric() || chars[j] == '_') {
|
||||
j += 1;
|
||||
}
|
||||
tokens.push(Token {
|
||||
kind: TokenKind::Ident,
|
||||
value: chars[i..j].iter().collect(),
|
||||
line,
|
||||
});
|
||||
i = j;
|
||||
}
|
||||
_ => {
|
||||
let two: String = chars[i..(i + 2).min(n)].iter().collect();
|
||||
if TWO_CHAR_OPS.contains(&two.as_str()) {
|
||||
tokens.push(Token { kind: TokenKind::Op, value: two, line });
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c == '(' {
|
||||
depth += 1;
|
||||
}
|
||||
if c == ')' {
|
||||
depth = depth.saturating_sub(1);
|
||||
}
|
||||
if ONE_CHAR_OPS.contains(&c) {
|
||||
tokens.push(Token { kind: TokenKind::Op, value: c.to_string(), line });
|
||||
i += 1;
|
||||
} else {
|
||||
return Err(ExpressionError {
|
||||
message: format!("Unexpected character '{c}'"),
|
||||
line,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(tokens)
|
||||
}
|
||||
349
rust-agent/src/script/mod.rs
Normal file
349
rust-agent/src/script/mod.rs
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
//! AVA visualization script (`.ava`) format parser — port of
|
||||
//! `src/lib/ava/script.ts`.
|
||||
//!
|
||||
//! A script is a plain-text file:
|
||||
//!
|
||||
//! ```text
|
||||
//! # comment lines start with '#' or '//'
|
||||
//! name: Gap The Mind <- header keys before the first [section]
|
||||
//! author: synth-c (adapted)
|
||||
//! mode: lines <- lines | dots | solid
|
||||
//! blend: additive <- additive | alpha
|
||||
//! persist: 0.9 <- motion trail persistence 0..0.98
|
||||
//! linewidth: 2
|
||||
//!
|
||||
//! [init] runs once when the script loads
|
||||
//! [frame] runs once per frame
|
||||
//! [beat] runs on frames where a beat fired (after [frame])
|
||||
//! [point] runs once per point (n times per frame)
|
||||
//! ```
|
||||
//!
|
||||
//! Errors carry the section + 1-based line, exactly like the web engine's
|
||||
//! `ScriptError` / `AvaScriptError`.
|
||||
|
||||
pub mod env;
|
||||
pub mod lexer;
|
||||
pub mod parser;
|
||||
|
||||
pub use env::Env;
|
||||
pub use parser::{hash_rand, Program};
|
||||
|
||||
use crate::script::lexer::ExpressionError;
|
||||
|
||||
// ---------------------------------------------------------------- meta
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RenderMode {
|
||||
Lines,
|
||||
Dots,
|
||||
Solid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BlendMode {
|
||||
Additive,
|
||||
Alpha,
|
||||
}
|
||||
|
||||
/// Header metadata — mirrors `ScriptMeta` in script.ts.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ScriptMeta {
|
||||
pub name: String,
|
||||
pub author: String,
|
||||
pub description: String,
|
||||
pub mode: RenderMode,
|
||||
pub blend: BlendMode,
|
||||
pub persist: f64,
|
||||
pub linewidth: f64,
|
||||
}
|
||||
|
||||
impl Default for ScriptMeta {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: "Untitled".into(),
|
||||
author: String::new(),
|
||||
description: String::new(),
|
||||
mode: RenderMode::Lines,
|
||||
blend: BlendMode::Additive,
|
||||
persist: 0.85,
|
||||
linewidth: 2.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- errors
|
||||
|
||||
/// Parse/compile error with section + line — mirrors `ScriptError`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ScriptError {
|
||||
pub message: String,
|
||||
pub section: String,
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ScriptError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "[{}] line {}: {}", self.section, self.line, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ScriptError {}
|
||||
|
||||
// --------------------------------------------------------------- script
|
||||
|
||||
/// A parsed + compiled script (sections compile once, run per frame).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AvaScript {
|
||||
pub meta: ScriptMeta,
|
||||
pub init_prog: Option<Program>,
|
||||
pub frame_prog: Option<Program>,
|
||||
pub beat_prog: Option<Program>,
|
||||
pub point_prog: Option<Program>,
|
||||
}
|
||||
|
||||
impl AvaScript {
|
||||
/// Run helpers — all safely no-op when a section is absent (mirrors the
|
||||
/// execInit/execFrame/execBeat/execPoint helpers in script.ts).
|
||||
pub fn run_init(&self, env: &mut Env) -> f64 {
|
||||
self.init_prog.as_ref().map(|p| p.exec(env)).unwrap_or(0.0)
|
||||
}
|
||||
pub fn run_frame(&self, env: &mut Env) -> f64 {
|
||||
self.frame_prog.as_ref().map(|p| p.exec(env)).unwrap_or(0.0)
|
||||
}
|
||||
pub fn run_beat(&self, env: &mut Env) -> f64 {
|
||||
self.beat_prog.as_ref().map(|p| p.exec(env)).unwrap_or(0.0)
|
||||
}
|
||||
pub fn run_point(&self, env: &mut Env) -> f64 {
|
||||
self.point_prog.as_ref().map(|p| p.exec(env)).unwrap_or(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-throwing validation result — mirrors `validateScript()` in script.ts.
|
||||
pub struct ValidationResult {
|
||||
pub ok: bool,
|
||||
pub script: Option<AvaScript>,
|
||||
pub error: Option<ScriptError>,
|
||||
pub meta: Option<ScriptMeta>,
|
||||
}
|
||||
|
||||
/// Parse + compile a script. `Err` on the first problem found.
|
||||
pub fn parse_script(text: &str) -> Result<AvaScript, ScriptError> {
|
||||
match try_parse(text) {
|
||||
TryParse::Ok(script) => Ok(script),
|
||||
TryParse::Err { error, .. } => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Never fails — returns the error (first only) instead.
|
||||
pub fn validate_script(text: &str) -> ValidationResult {
|
||||
match try_parse(text) {
|
||||
TryParse::Ok(script) => ValidationResult {
|
||||
ok: true,
|
||||
meta: Some(script.meta.clone()),
|
||||
script: Some(script),
|
||||
error: None,
|
||||
},
|
||||
TryParse::Err { meta, error } => ValidationResult {
|
||||
ok: false,
|
||||
meta: Some(meta),
|
||||
script: None,
|
||||
error: Some(error),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
enum TryParse {
|
||||
Ok(AvaScript),
|
||||
Err { meta: ScriptMeta, error: ScriptError },
|
||||
}
|
||||
|
||||
struct SectionSource {
|
||||
text: String,
|
||||
start_line: usize,
|
||||
}
|
||||
|
||||
/// `[section]` line — name must be ascii-alphabetic (TS regex `^\[([a-zA-Z]+)\]$`).
|
||||
fn parse_section_header(trimmed: &str) -> Option<&str> {
|
||||
let inner = trimmed.strip_prefix('[')?.strip_suffix(']')?;
|
||||
if !inner.is_empty() && inner.chars().all(|c| c.is_ascii_alphabetic()) {
|
||||
Some(inner)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// `Key: value` header line — key is ascii-alphabetic, value runs to EOL
|
||||
/// (TS regex `^([a-zA-Z]+)\s*:\s*(.*)$`).
|
||||
fn parse_header(trimmed: &str) -> Option<(String, String)> {
|
||||
let colon = trimmed.find(':')?;
|
||||
let key = trimmed[..colon].trim_end();
|
||||
if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
Some((key.to_ascii_lowercase(), trimmed[colon + 1..].trim().to_string()))
|
||||
}
|
||||
|
||||
fn try_parse(text: &str) -> TryParse {
|
||||
let mut meta = ScriptMeta::default();
|
||||
let mut sections: Vec<(&'static str, SectionSource)> = Vec::new();
|
||||
let mut current: Option<(&'static str, SectionSource)> = None;
|
||||
|
||||
let header_error = |meta: ScriptMeta, message: String, line: usize| TryParse::Err {
|
||||
meta,
|
||||
error: ScriptError { message, section: "header".into(), line },
|
||||
};
|
||||
|
||||
for (idx, raw) in text.lines().enumerate() {
|
||||
let line_no = idx + 1;
|
||||
let trimmed = raw.trim();
|
||||
|
||||
// section headers
|
||||
if let Some(name) = parse_section_header(trimmed) {
|
||||
if let Some((prev, src)) = current.take() {
|
||||
sections.push((prev, src));
|
||||
}
|
||||
let canonical: &str = match name.to_ascii_lowercase().as_str() {
|
||||
"init" => "init",
|
||||
"frame" => "frame",
|
||||
"beat" => "beat",
|
||||
"point" => "point",
|
||||
_ => {
|
||||
return TryParse::Err {
|
||||
meta,
|
||||
error: ScriptError {
|
||||
message: format!(
|
||||
"Unknown section '[{name}]' — valid sections: init, frame, beat, point"
|
||||
),
|
||||
section: name.to_string(),
|
||||
line: line_no,
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
if sections.iter().any(|(n, _)| *n == canonical) {
|
||||
return TryParse::Err {
|
||||
meta,
|
||||
error: ScriptError {
|
||||
message: format!("Duplicate section '[{canonical}]'"),
|
||||
section: canonical.into(),
|
||||
line: line_no,
|
||||
},
|
||||
};
|
||||
}
|
||||
current = Some((canonical, SectionSource { text: String::new(), start_line: line_no + 1 }));
|
||||
continue;
|
||||
}
|
||||
|
||||
// inside a section: keep raw lines (trimming happens in the tokenizer)
|
||||
if let Some((_, src)) = &mut current {
|
||||
src.text.push_str(raw);
|
||||
src.text.push('\n');
|
||||
continue;
|
||||
}
|
||||
|
||||
// header area
|
||||
if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") {
|
||||
continue;
|
||||
}
|
||||
let Some((key, value)) = parse_header(trimmed) else {
|
||||
return header_error(
|
||||
meta,
|
||||
format!("Expected 'key: value' header or a [section] — got '{trimmed}'"),
|
||||
line_no,
|
||||
);
|
||||
};
|
||||
match key.as_str() {
|
||||
"name" => meta.name = if value.is_empty() { "Untitled".into() } else { value },
|
||||
"author" => meta.author = value,
|
||||
"description" => meta.description = value,
|
||||
"mode" => {
|
||||
meta.mode = match value.as_str() {
|
||||
"lines" => RenderMode::Lines,
|
||||
"dots" => RenderMode::Dots,
|
||||
"solid" => RenderMode::Solid,
|
||||
_ => {
|
||||
return header_error(
|
||||
meta,
|
||||
format!("mode must be one of: lines, dots, solid (got '{value}')"),
|
||||
line_no,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
"blend" => {
|
||||
meta.blend = match value.as_str() {
|
||||
"additive" => BlendMode::Additive,
|
||||
"alpha" => BlendMode::Alpha,
|
||||
_ => {
|
||||
return header_error(
|
||||
meta,
|
||||
format!("blend must be 'additive' or 'alpha' (got '{value}')"),
|
||||
line_no,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
"persist" => match value.parse::<f64>() {
|
||||
Ok(v) => meta.persist = v.clamp(0.0, 0.98),
|
||||
Err(_) => {
|
||||
return header_error(
|
||||
meta,
|
||||
format!("persist must be a number 0..0.98 (got '{value}')"),
|
||||
line_no,
|
||||
)
|
||||
}
|
||||
},
|
||||
"linewidth" => match value.parse::<f64>() {
|
||||
Ok(v) => meta.linewidth = v.clamp(0.5, 16.0),
|
||||
Err(_) => {
|
||||
return header_error(
|
||||
meta,
|
||||
format!("linewidth must be a number (got '{value}')"),
|
||||
line_no,
|
||||
)
|
||||
}
|
||||
},
|
||||
other => {
|
||||
return header_error(
|
||||
meta,
|
||||
format!(
|
||||
"Unknown header key '{other}' — valid keys: name, author, description, \
|
||||
mode, blend, persist, linewidth"
|
||||
),
|
||||
line_no,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((prev, src)) = current.take() {
|
||||
sections.push((prev, src));
|
||||
}
|
||||
|
||||
// compile sections (fixed order, mirroring script.ts)
|
||||
let mut progs: [Option<Program>; 4] = [None, None, None, None];
|
||||
for (slot, name) in [(0usize, "init"), (1, "frame"), (2, "beat"), (3, "point")] {
|
||||
let Some((_, src)) = sections.iter().find(|(n, _)| *n == name) else {
|
||||
continue;
|
||||
};
|
||||
if src.text.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
match parser::compile_program(&src.text, src.start_line) {
|
||||
Ok(prog) => progs[slot] = Some(prog),
|
||||
Err(ExpressionError { message, line }) => {
|
||||
return TryParse::Err {
|
||||
meta,
|
||||
error: ScriptError { message, section: name.into(), line },
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TryParse::Ok(AvaScript {
|
||||
meta,
|
||||
init_prog: progs[0].take(),
|
||||
frame_prog: progs[1].take(),
|
||||
beat_prog: progs[2].take(),
|
||||
point_prog: progs[3].take(),
|
||||
})
|
||||
}
|
||||
494
rust-agent/src/script/parser.rs
Normal file
494
rust-agent/src/script/parser.rs
Normal file
|
|
@ -0,0 +1,494 @@
|
|||
//! Recursive-descent parser + evaluator — port of the `Parser` class and the
|
||||
//! function table in `src/lib/ava/expression.ts`.
|
||||
//!
|
||||
//! This is a clean-room recursive-descent implementation rather than a
|
||||
//! transliteration, but BEHAVIOR PARITY is the contract:
|
||||
//! - assignment is an expression and is valid inside call args and ternary
|
||||
//! branches: `if(cond, x = 1, x = 2)` (right-associative)
|
||||
//! - `if(c, a, b)` and the ternary evaluate only the taken branch (lazy)
|
||||
//! - `&&` / `||` short-circuit
|
||||
//! - `^` is right-associative power (`2 ^ -3` parses via unary exponent)
|
||||
//! - `rand(seed)` is the same deterministic hash as the web engine
|
||||
//! - comparisons / boolean ops return 1 or 0
|
||||
|
||||
use super::env::Env;
|
||||
use super::lexer::{tokenize, ExpressionError, Token, TokenKind};
|
||||
|
||||
/// Deterministic hash-based rand in [0,1) — the identical formula to
|
||||
/// expression.ts, so per-point randomness is stable across web and native.
|
||||
pub fn hash_rand(x: f64) -> f64 {
|
||||
let s = (x * 127.1 + 311.7).sin() * 43758.5453;
|
||||
s - s.floor()
|
||||
}
|
||||
|
||||
/// Built-in functions — the full web engine set.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Func {
|
||||
Sin, Cos, Tan, Asin, Acos, Atan, Atan2,
|
||||
Abs, Sqrt, Sqr, Pow, Exp, Log, Log10,
|
||||
Floor, Ceil, Round, Int, Frac, Sign,
|
||||
Min, Max, Rand,
|
||||
Lerp, Clamp, InRange, Above, Below, Equal,
|
||||
Band, Bor, Bnot, Sigmoid, If,
|
||||
}
|
||||
|
||||
impl Func {
|
||||
pub fn lookup(name: &str) -> Option<Func> {
|
||||
Some(match name {
|
||||
"sin" => Func::Sin, "cos" => Func::Cos, "tan" => Func::Tan,
|
||||
"asin" => Func::Asin, "acos" => Func::Acos, "atan" => Func::Atan,
|
||||
"atan2" => Func::Atan2, "abs" => Func::Abs, "sqrt" => Func::Sqrt,
|
||||
"sqr" => Func::Sqr, "pow" => Func::Pow, "exp" => Func::Exp,
|
||||
"log" => Func::Log, "log10" => Func::Log10, "floor" => Func::Floor,
|
||||
"ceil" => Func::Ceil, "round" => Func::Round, "int" => Func::Int,
|
||||
"frac" => Func::Frac, "sign" => Func::Sign, "min" => Func::Min,
|
||||
"max" => Func::Max, "rand" => Func::Rand, "lerp" => Func::Lerp,
|
||||
"clamp" => Func::Clamp, "inrange" => Func::InRange,
|
||||
"above" => Func::Above, "below" => Func::Below, "equal" => Func::Equal,
|
||||
"band" => Func::Band, "bor" => Func::Bor, "bnot" => Func::Bnot,
|
||||
"sigmoid" => Func::Sigmoid, "if" => Func::If,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// (min, max) argument count — mirrors the web engine's fn1/fn2/fn3.
|
||||
pub fn arity(self) -> (usize, usize) {
|
||||
match self {
|
||||
Func::Atan2 | Func::Pow | Func::Min | Func::Max | Func::Above
|
||||
| Func::Below | Func::Equal | Func::Band | Func::Bor | Func::Sigmoid => (2, 2),
|
||||
Func::Lerp | Func::Clamp | Func::InRange | Func::If => (3, 3),
|
||||
_ => (1, 1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Named constants (expression.ts `CONSTANTS`).
|
||||
pub fn constant(name: &str) -> Option<f64> {
|
||||
Some(match name {
|
||||
"pi" => std::f64::consts::PI,
|
||||
"tau" => std::f64::consts::TAU,
|
||||
"e" => std::f64::consts::E,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UnOp {
|
||||
Neg,
|
||||
Not,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BinOp {
|
||||
Add, Sub, Mul, Div, Mod, Pow,
|
||||
Eq, Ne, Lt, Le, Gt, Ge,
|
||||
And, Or,
|
||||
}
|
||||
|
||||
/// Expression AST — the compiled form of the web engine's closure tree.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Expr {
|
||||
Num(f64),
|
||||
Var(String),
|
||||
Assign(String, Box<Expr>),
|
||||
Unary(UnOp, Box<Expr>),
|
||||
Binary(BinOp, Box<Expr>, Box<Expr>),
|
||||
Ternary(Box<Expr>, Box<Expr>, Box<Expr>),
|
||||
Call(Func, Vec<Expr>),
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
/// Evaluate against the environment, mirroring the closure tree of
|
||||
/// expression.ts (including the laziness of if/ternary/&&/||).
|
||||
pub fn eval(&self, env: &mut Env) -> f64 {
|
||||
match self {
|
||||
Expr::Num(v) => *v,
|
||||
Expr::Var(name) => super::env::get(env, name),
|
||||
Expr::Assign(name, value) => {
|
||||
let v = value.eval(env);
|
||||
env.insert(name.clone(), v);
|
||||
v
|
||||
}
|
||||
Expr::Unary(UnOp::Neg, u) => -u.eval(env),
|
||||
Expr::Unary(UnOp::Not, u) => if u.eval(env) == 0.0 { 1.0 } else { 0.0 },
|
||||
Expr::Binary(op, l, r) => match op {
|
||||
// short-circuit: the right side is only evaluated when needed
|
||||
BinOp::And => {
|
||||
if l.eval(env) == 0.0 { 0.0 } else if r.eval(env) != 0.0 { 1.0 } else { 0.0 }
|
||||
}
|
||||
BinOp::Or => {
|
||||
if l.eval(env) != 0.0 { 1.0 } else if r.eval(env) != 0.0 { 1.0 } else { 0.0 }
|
||||
}
|
||||
BinOp::Add => l.eval(env) + r.eval(env),
|
||||
BinOp::Sub => l.eval(env) - r.eval(env),
|
||||
BinOp::Mul => l.eval(env) * r.eval(env),
|
||||
BinOp::Div => l.eval(env) / r.eval(env),
|
||||
BinOp::Mod => l.eval(env) % r.eval(env),
|
||||
BinOp::Pow => l.eval(env).powf(r.eval(env)),
|
||||
BinOp::Eq => if l.eval(env) == r.eval(env) { 1.0 } else { 0.0 },
|
||||
BinOp::Ne => if l.eval(env) != r.eval(env) { 1.0 } else { 0.0 },
|
||||
BinOp::Lt => if l.eval(env) < r.eval(env) { 1.0 } else { 0.0 },
|
||||
BinOp::Le => if l.eval(env) <= r.eval(env) { 1.0 } else { 0.0 },
|
||||
BinOp::Gt => if l.eval(env) > r.eval(env) { 1.0 } else { 0.0 },
|
||||
BinOp::Ge => if l.eval(env) >= r.eval(env) { 1.0 } else { 0.0 },
|
||||
},
|
||||
// lazy: only the taken branch is evaluated (AVS semantics)
|
||||
Expr::Ternary(c, a, b) => {
|
||||
if c.eval(env) != 0.0 { a.eval(env) } else { b.eval(env) }
|
||||
}
|
||||
Expr::Call(func, args) => call(*func, args, env),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn call(func: Func, args: &[Expr], env: &mut Env) -> f64 {
|
||||
use Func::*;
|
||||
match func {
|
||||
// lazy — only the taken branch
|
||||
If => if args[0].eval(env) != 0.0 { args[1].eval(env) } else { args[2].eval(env) },
|
||||
Sin => args[0].eval(env).sin(),
|
||||
Cos => args[0].eval(env).cos(),
|
||||
Tan => args[0].eval(env).tan(),
|
||||
Asin => args[0].eval(env).asin(),
|
||||
Acos => args[0].eval(env).acos(),
|
||||
Atan => args[0].eval(env).atan(),
|
||||
Atan2 => args[0].eval(env).atan2(args[1].eval(env)),
|
||||
Abs => args[0].eval(env).abs(),
|
||||
Sqrt => args[0].eval(env).sqrt(),
|
||||
Sqr => args[0].eval(env) * args[0].eval(env),
|
||||
Pow => args[0].eval(env).powf(args[1].eval(env)),
|
||||
Exp => args[0].eval(env).exp(),
|
||||
Log => args[0].eval(env).ln(),
|
||||
Log10 => args[0].eval(env).log10(),
|
||||
Floor => args[0].eval(env).floor(),
|
||||
Ceil => args[0].eval(env).ceil(),
|
||||
Round => args[0].eval(env).round(),
|
||||
Int => args[0].eval(env).trunc(),
|
||||
Frac => { let x = args[0].eval(env); x - x.floor() }
|
||||
Sign => args[0].eval(env).signum(),
|
||||
Min => args[0].eval(env).min(args[1].eval(env)),
|
||||
Max => args[0].eval(env).max(args[1].eval(env)),
|
||||
Rand => hash_rand(args[0].eval(env)),
|
||||
Lerp => { let (a, b) = (args[0].eval(env), args[1].eval(env)); a + (b - a) * args[2].eval(env) }
|
||||
Clamp => { let (x, lo) = (args[0].eval(env), args[1].eval(env)); x.max(lo).min(args[2].eval(env)) }
|
||||
InRange => {
|
||||
let (x, lo) = (args[0].eval(env), args[1].eval(env));
|
||||
let hi = args[2].eval(env);
|
||||
if x >= lo && x <= hi { 1.0 } else { 0.0 }
|
||||
}
|
||||
Above => if args[0].eval(env) > args[1].eval(env) { 1.0 } else { 0.0 },
|
||||
Below => if args[0].eval(env) < args[1].eval(env) { 1.0 } else { 0.0 },
|
||||
Equal => if args[0].eval(env) == args[1].eval(env) { 1.0 } else { 0.0 },
|
||||
Band => if args[0].eval(env) != 0.0 && args[1].eval(env) != 0.0 { 1.0 } else { 0.0 },
|
||||
Bor => if args[0].eval(env) != 0.0 || args[1].eval(env) != 0.0 { 1.0 } else { 0.0 },
|
||||
Bnot => if args[0].eval(env) == 0.0 { 1.0 } else { 0.0 },
|
||||
Sigmoid => { let (x, y) = (args[0].eval(env), args[1].eval(env)); 1.0 / (1.0 + (-x * y).exp()) }
|
||||
}
|
||||
}
|
||||
|
||||
struct Parser {
|
||||
tokens: Vec<Token>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn new(tokens: Vec<Token>) -> Self {
|
||||
Self { tokens, pos: 0 }
|
||||
}
|
||||
|
||||
fn peek(&self, offset: usize) -> Option<&Token> {
|
||||
self.tokens.get(self.pos + offset)
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<&Token> {
|
||||
let t = self.tokens.get(self.pos);
|
||||
self.pos += 1;
|
||||
t
|
||||
}
|
||||
|
||||
fn last_line(&self) -> usize {
|
||||
self.tokens.last().map(|t| t.line).unwrap_or(1)
|
||||
}
|
||||
|
||||
fn at_op(&self, v: &str) -> bool {
|
||||
match self.peek(0) {
|
||||
Some(t) => t.kind == TokenKind::Op && t.value == v,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_op(&mut self, v: &str) -> Result<(), ExpressionError> {
|
||||
let line = self.peek(0).map(|t| t.line).unwrap_or_else(|| self.last_line());
|
||||
match self.next() {
|
||||
Some(t) if t.kind == TokenKind::Op && t.value == v => Ok(()),
|
||||
Some(t) => Err(ExpressionError {
|
||||
message: format!("Expected '{}' but found '{}'", v, t.value),
|
||||
line: t.line,
|
||||
}),
|
||||
None => Err(ExpressionError {
|
||||
message: format!("Expected '{v}' but found end of line"),
|
||||
line,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Statement list: expressions separated by `;` (newlines become `;` in
|
||||
/// the lexer).
|
||||
fn parse_statements(&mut self) -> Result<Vec<Expr>, ExpressionError> {
|
||||
let mut stmts = Vec::new();
|
||||
loop {
|
||||
while self.at_op(";") {
|
||||
self.next();
|
||||
}
|
||||
if self.peek(0).is_none() {
|
||||
break;
|
||||
}
|
||||
stmts.push(self.parse_assign_expr()?);
|
||||
match self.peek(0) {
|
||||
None => break,
|
||||
Some(t) if t.kind == TokenKind::Op && t.value == ";" => {}
|
||||
Some(t) => {
|
||||
return Err(ExpressionError {
|
||||
message: format!(
|
||||
"Unexpected '{}' — separate statements with ';' or a newline",
|
||||
t.value
|
||||
),
|
||||
line: t.line,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(stmts)
|
||||
}
|
||||
|
||||
/// Assignment expression — also valid inside function args and ternary
|
||||
/// branches (AVS-style `if(cond, x = 1, x = 2)`). Right-associative.
|
||||
fn parse_assign_expr(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let is_assign = match (self.peek(0), self.peek(1)) {
|
||||
(Some(a), Some(b)) => a.kind == TokenKind::Ident && b.kind == TokenKind::Op && b.value == "=",
|
||||
_ => false,
|
||||
};
|
||||
if is_assign {
|
||||
let name = self.next().unwrap().value.clone();
|
||||
self.next(); // consume '='
|
||||
let value = self.parse_assign_expr()?;
|
||||
return Ok(Expr::Assign(name, Box::new(value)));
|
||||
}
|
||||
self.parse_expr()
|
||||
}
|
||||
|
||||
fn parse_expr(&mut self) -> Result<Expr, ExpressionError> {
|
||||
self.parse_ternary()
|
||||
}
|
||||
|
||||
fn parse_ternary(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let cond = self.parse_or()?;
|
||||
if self.at_op("?") {
|
||||
self.next();
|
||||
let a = self.parse_assign_expr()?;
|
||||
self.expect_op(":")?;
|
||||
let b = self.parse_assign_expr()?;
|
||||
return Ok(Expr::Ternary(Box::new(cond), Box::new(a), Box::new(b)));
|
||||
}
|
||||
Ok(cond)
|
||||
}
|
||||
|
||||
fn parse_or(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let mut l = self.parse_and()?;
|
||||
while self.at_op("||") {
|
||||
self.next();
|
||||
let r = self.parse_and()?;
|
||||
l = Expr::Binary(BinOp::Or, Box::new(l), Box::new(r));
|
||||
}
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
fn parse_and(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let mut l = self.parse_cmp()?;
|
||||
while self.at_op("&&") {
|
||||
self.next();
|
||||
let r = self.parse_cmp()?;
|
||||
l = Expr::Binary(BinOp::And, Box::new(l), Box::new(r));
|
||||
}
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
fn parse_cmp(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let mut l = self.parse_add()?;
|
||||
loop {
|
||||
let op = match self.peek(0) {
|
||||
Some(t) if t.kind == TokenKind::Op => match t.value.as_str() {
|
||||
"==" => BinOp::Eq, "!=" => BinOp::Ne, "<" => BinOp::Lt,
|
||||
"<=" => BinOp::Le, ">" => BinOp::Gt, ">=" => BinOp::Ge,
|
||||
_ => break,
|
||||
},
|
||||
_ => break,
|
||||
};
|
||||
self.next();
|
||||
let r = self.parse_add()?;
|
||||
l = Expr::Binary(op, Box::new(l), Box::new(r));
|
||||
}
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
fn parse_add(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let mut l = self.parse_mul()?;
|
||||
loop {
|
||||
let op = match self.peek(0) {
|
||||
Some(t) if t.kind == TokenKind::Op && t.value == "+" => BinOp::Add,
|
||||
Some(t) if t.kind == TokenKind::Op && t.value == "-" => BinOp::Sub,
|
||||
_ => break,
|
||||
};
|
||||
self.next();
|
||||
let r = self.parse_mul()?;
|
||||
l = Expr::Binary(op, Box::new(l), Box::new(r));
|
||||
}
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
fn parse_mul(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let mut l = self.parse_unary()?;
|
||||
loop {
|
||||
let op = match self.peek(0) {
|
||||
Some(t) if t.kind == TokenKind::Op && t.value == "*" => BinOp::Mul,
|
||||
Some(t) if t.kind == TokenKind::Op && t.value == "/" => BinOp::Div,
|
||||
Some(t) if t.kind == TokenKind::Op && t.value == "%" => BinOp::Mod,
|
||||
_ => break,
|
||||
};
|
||||
self.next();
|
||||
let r = self.parse_unary()?;
|
||||
l = Expr::Binary(op, Box::new(l), Box::new(r));
|
||||
}
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
fn parse_unary(&mut self) -> Result<Expr, ExpressionError> {
|
||||
if self.at_op("-") {
|
||||
self.next();
|
||||
return Ok(Expr::Unary(UnOp::Neg, Box::new(self.parse_unary()?)));
|
||||
}
|
||||
if self.at_op("+") {
|
||||
self.next();
|
||||
return self.parse_unary();
|
||||
}
|
||||
if self.at_op("!") {
|
||||
self.next();
|
||||
return Ok(Expr::Unary(UnOp::Not, Box::new(self.parse_unary()?)));
|
||||
}
|
||||
self.parse_pow()
|
||||
}
|
||||
|
||||
/// `^` binds tighter than unary minus on the left and looser on the
|
||||
/// right: `2 ^ -3` works, `-2^2` is `-(2^2)` (right-associative).
|
||||
fn parse_pow(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let base = self.parse_primary()?;
|
||||
if self.at_op("^") {
|
||||
self.next();
|
||||
let exp = self.parse_unary();
|
||||
return Ok(Expr::Binary(BinOp::Pow, Box::new(base), Box::new(exp?)));
|
||||
}
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
fn parse_primary(&mut self) -> Result<Expr, ExpressionError> {
|
||||
let line = self.peek(0).map(|t| t.line).unwrap_or_else(|| self.last_line());
|
||||
let t = match self.next() {
|
||||
Some(t) => t.clone(),
|
||||
None => {
|
||||
return Err(ExpressionError {
|
||||
message: "Unexpected end of expression".into(),
|
||||
line,
|
||||
})
|
||||
}
|
||||
};
|
||||
match t.kind {
|
||||
TokenKind::Num => {
|
||||
// (JS parseFloat silently truncates junk like "1.2.3"; we
|
||||
// surface it as a compile error — presets are clean.)
|
||||
let v: f64 = t.value.parse().map_err(|_| ExpressionError {
|
||||
message: format!("Bad number '{}'", t.value),
|
||||
line: t.line,
|
||||
})?;
|
||||
Ok(Expr::Num(v))
|
||||
}
|
||||
TokenKind::Ident => {
|
||||
if self.at_op("(") {
|
||||
self.next();
|
||||
let mut args = Vec::new();
|
||||
if !self.at_op(")") {
|
||||
args.push(self.parse_assign_expr()?);
|
||||
while self.at_op(",") {
|
||||
self.next();
|
||||
args.push(self.parse_assign_expr()?);
|
||||
}
|
||||
}
|
||||
self.expect_op(")")?;
|
||||
let func = Func::lookup(&t.value).ok_or_else(|| ExpressionError {
|
||||
message: format!("Unknown function '{}'", t.value),
|
||||
line: t.line,
|
||||
})?;
|
||||
let (min_args, max_args) = func.arity();
|
||||
if args.len() < min_args || args.len() > max_args {
|
||||
let expected = if min_args == max_args {
|
||||
format!("{min_args}")
|
||||
} else {
|
||||
format!("{min_args}-{max_args}")
|
||||
};
|
||||
return Err(ExpressionError {
|
||||
message: format!(
|
||||
"{}() expects {} argument(s), got {}",
|
||||
t.value, expected, args.len()
|
||||
),
|
||||
line: t.line,
|
||||
});
|
||||
}
|
||||
Ok(Expr::Call(func, args))
|
||||
} else if let Some(v) = constant(&t.value) {
|
||||
Ok(Expr::Num(v))
|
||||
} else {
|
||||
Ok(Expr::Var(t.value))
|
||||
}
|
||||
}
|
||||
TokenKind::Op if t.value == "(" => {
|
||||
let inner = self.parse_expr()?;
|
||||
self.expect_op(")")?;
|
||||
Ok(inner)
|
||||
}
|
||||
_ => Err(ExpressionError {
|
||||
message: format!("Unexpected token '{}'", t.value),
|
||||
line: t.line,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A compiled statement list — one per script section (compile once, execute
|
||||
/// per frame / per point).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Program {
|
||||
statements: Vec<Expr>,
|
||||
}
|
||||
|
||||
impl Program {
|
||||
pub fn statement_count(&self) -> usize {
|
||||
self.statements.len()
|
||||
}
|
||||
|
||||
/// Execute in order against the env; returns the last statement's value.
|
||||
/// (No runtime errors are possible: all fallible work happened at parse
|
||||
/// time and f64 math mirrors JS — div-by-zero → ±inf, not a trap.)
|
||||
pub fn exec(&self, env: &mut Env) -> f64 {
|
||||
let mut last = 0.0;
|
||||
for stmt in &self.statements {
|
||||
last = stmt.eval(env);
|
||||
}
|
||||
last
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile a statement list (mirrors `compileProgram` in expression.ts).
|
||||
pub fn compile_program(src: &str, base_line: usize) -> Result<Program, ExpressionError> {
|
||||
let tokens = tokenize(src, base_line)?;
|
||||
let mut parser = Parser::new(tokens);
|
||||
Ok(Program { statements: parser.parse_statements()? })
|
||||
}
|
||||
133
rust-agent/src/spectrum.rs
Normal file
133
rust-agent/src/spectrum.rs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
//! AVA — FFT / band-level spectrum analysis (rustfft wrapper).
|
||||
//!
|
||||
//! Native counterpart of the band math inside `src/lib/ava/audio.ts`
|
||||
//! (`getBands` / `getSpectrum`). The web engine reads a Web Audio
|
||||
//! `AnalyserNode`'s byte-spectrum; here we run our own 8192-point real FFT
|
||||
//! over the most recent window of input samples and average the magnitudes
|
||||
//! over the same Hz ranges.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rustfft::num_complex::Complex;
|
||||
use rustfft::{Fft, FftPlanner};
|
||||
|
||||
/// FFT length — 8192 samples (~5.4 Hz bins at 44.1/48 kHz), same as the web
|
||||
/// engine's AnalyserNode.
|
||||
pub const FFT_SIZE: usize = 8192;
|
||||
|
||||
/// Waveform history kept for the script `v` variable (matches the web
|
||||
/// engine's "most recent 2048 samples" window).
|
||||
pub const WAVE_SIZE: usize = 2048;
|
||||
|
||||
/// Calibration: a full-scale sinusoid through the Hann window lands at a
|
||||
/// magnitude of ≈ FFT_SIZE/4 (≈ 2048). Dividing by this constant maps it to
|
||||
/// 1.0 — the same 0..1 range the web engine gets from the AnalyserNode's
|
||||
/// byte spectrum (`value / 255`), so band gains, attack/release smoothing and
|
||||
/// beat thresholds transfer unchanged between the two engines.
|
||||
const MAG_TO_UNIT: f32 = 1.0 / (FFT_SIZE as f32 / 4.0);
|
||||
|
||||
/// Result of one analysis pass.
|
||||
pub struct Spectrum {
|
||||
/// Per-bin unit-normalized magnitudes (len = FFT_SIZE/2, DC..Nyquist).
|
||||
pub mags: Vec<f32>,
|
||||
/// Raw (un-windowed) waveform snapshot, most recent sample last.
|
||||
pub wave: Vec<f32>,
|
||||
/// Sample rate the analysis ran at.
|
||||
pub sample_rate: f32,
|
||||
}
|
||||
|
||||
impl Spectrum {
|
||||
/// Waveform sample at position 0..1 → -1..1 (the script `v` variable).
|
||||
/// Mirrors `AudioEngine.getWave()` in audio.ts.
|
||||
pub fn wave_at(&self, pos: f64) -> f64 {
|
||||
if self.wave.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let idx = (pos.clamp(0.0, 1.0) * (self.wave.len() as f64 - 1.0)).floor() as usize;
|
||||
self.wave[idx.min(self.wave.len() - 1)] as f64
|
||||
}
|
||||
|
||||
/// Spectrum magnitude at position 0..1 → 0..1 with the web engine's
|
||||
/// log-ish frequency mapping. Mirrors `AudioEngine.getSpectrum()`.
|
||||
pub fn spectrum_at(&self, pos: f64) -> f64 {
|
||||
if self.mags.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let p = pos.clamp(0.0, 1.0);
|
||||
let bin = 2.0 + (p.powf(1.6) * (self.mags.len() as f64 - 3.0)).floor();
|
||||
self.mags[(bin as usize).min(self.mags.len() - 1)] as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// Hz per FFT bin (web: `sampleRate / 2 / frequencyBinCount` — identical).
|
||||
pub fn bin_hz(sample_rate: f32, fft_size: usize) -> f32 {
|
||||
sample_rate / fft_size as f32
|
||||
}
|
||||
|
||||
/// Average unit-magnitude over an inclusive Hz range — the `levelOf()`
|
||||
/// closure inside `getBands()` in audio.ts.
|
||||
pub fn band_level(mags: &[f32], lo_hz: f32, hi_hz: f32, sample_rate: f32) -> f32 {
|
||||
let bh = bin_hz(sample_rate, mags.len() * 2);
|
||||
let lo = ((lo_hz / bh) as usize).max(1);
|
||||
let hi = ((hi_hz / bh).ceil() as usize).min(mags.len() - 1);
|
||||
if hi <= lo {
|
||||
return 0.0;
|
||||
}
|
||||
mags[lo..=hi].iter().sum::<f32>() / (hi - lo + 1) as f32
|
||||
}
|
||||
|
||||
/// Reusable FFT machinery (the plan is cached — one per AudioProcessor).
|
||||
pub struct SpectrumAnalyzer {
|
||||
fft: Arc<dyn Fft<f32>>,
|
||||
window: Vec<f32>,
|
||||
buffer: Vec<Complex<f32>>,
|
||||
}
|
||||
|
||||
impl SpectrumAnalyzer {
|
||||
pub fn new() -> Self {
|
||||
let mut planner = FftPlanner::<f32>::new();
|
||||
let fft = planner.plan_fft_forward(FFT_SIZE);
|
||||
// Hann window. (The web AnalyserNode uses Blackman internally; both
|
||||
// have ~0.5 coherent gain, so the MAG_TO_UNIT calibration holds.)
|
||||
let window: Vec<f32> = (0..FFT_SIZE)
|
||||
.map(|k| {
|
||||
let t = k as f32 / (FFT_SIZE - 1) as f32;
|
||||
0.5 * (1.0 - (std::f32::consts::TAU * t).cos())
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
fft,
|
||||
window,
|
||||
buffer: vec![Complex::new(0.0, 0.0); FFT_SIZE],
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyze the most recent `FFT_SIZE` mono samples (chronological order;
|
||||
/// zero-padded at the front by the caller when the stream just started).
|
||||
pub fn analyze(&mut self, samples: &[f32], sample_rate: f32) -> Spectrum {
|
||||
let n = samples.len().min(FFT_SIZE);
|
||||
for k in 0..FFT_SIZE {
|
||||
let s = if k < n { samples[k] } else { 0.0 };
|
||||
self.buffer[k] = Complex::new(s * self.window[k], 0.0);
|
||||
}
|
||||
self.fft.process(&mut self.buffer);
|
||||
|
||||
let half = FFT_SIZE / 2;
|
||||
let mags: Vec<f32> = self.buffer[..half]
|
||||
.iter()
|
||||
.map(|c| (c.re * c.re + c.im * c.im).sqrt() * MAG_TO_UNIT)
|
||||
.collect();
|
||||
let wave = samples[(samples.len() - WAVE_SIZE.min(samples.len()))..].to_vec();
|
||||
Spectrum {
|
||||
mags,
|
||||
wave,
|
||||
sample_rate,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SpectrumAnalyzer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
46
src/app/api/presets/[id]/route.ts
Normal file
46
src/app/api/presets/[id]/route.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { db } from '@/lib/db'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const body = await req.json()
|
||||
const preset = await db.preset.findUnique({ where: { id } })
|
||||
if (!preset) {
|
||||
return NextResponse.json({ error: 'Preset not found' }, { status: 404 })
|
||||
}
|
||||
if (preset.isBuiltIn) {
|
||||
return NextResponse.json({ error: 'Built-in presets cannot be modified' }, { status: 403 })
|
||||
}
|
||||
const data: Record<string, string> = {}
|
||||
if (typeof body.name === 'string' && body.name.trim()) data.name = body.name.trim()
|
||||
if (typeof body.content === 'string') data.content = body.content
|
||||
if (typeof body.author === 'string') data.author = body.author.trim()
|
||||
if (typeof body.description === 'string') data.description = body.description.trim()
|
||||
const updated = await db.preset.update({ where: { id }, data })
|
||||
return NextResponse.json({ preset: updated })
|
||||
} catch (err) {
|
||||
console.error('PUT /api/presets/[id] failed:', err)
|
||||
return NextResponse.json({ error: 'Failed to update preset' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const preset = await db.preset.findUnique({ where: { id } })
|
||||
if (!preset) {
|
||||
return NextResponse.json({ error: 'Preset not found' }, { status: 404 })
|
||||
}
|
||||
if (preset.isBuiltIn) {
|
||||
return NextResponse.json({ error: 'Built-in presets cannot be deleted' }, { status: 403 })
|
||||
}
|
||||
await db.preset.delete({ where: { id } })
|
||||
return NextResponse.json({ deleted: true })
|
||||
} catch (err) {
|
||||
console.error('DELETE /api/presets/[id] failed:', err)
|
||||
return NextResponse.json({ error: 'Failed to delete preset' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
79
src/app/api/presets/route.ts
Normal file
79
src/app/api/presets/route.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { db } from '@/lib/db'
|
||||
import { BUILTIN_PRESETS } from '@/lib/ava/presets'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/** Seed the built-in presets on first run. */
|
||||
async function ensureSeeded(): Promise<void> {
|
||||
const count = await db.preset.count()
|
||||
if (count > 0) return
|
||||
for (const p of BUILTIN_PRESETS) {
|
||||
await db.preset.create({
|
||||
data: {
|
||||
name: p.name,
|
||||
author: p.author,
|
||||
description: p.description,
|
||||
content: p.content,
|
||||
isBuiltIn: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
await ensureSeeded()
|
||||
const presets = await db.preset.findMany({
|
||||
orderBy: [{ isBuiltIn: 'desc' }, { createdAt: 'asc' }],
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
author: true,
|
||||
description: true,
|
||||
content: true,
|
||||
isBuiltIn: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
})
|
||||
return NextResponse.json({ presets })
|
||||
} catch (err) {
|
||||
console.error('GET /api/presets failed:', err)
|
||||
return NextResponse.json({ error: 'Failed to load presets' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json()
|
||||
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
||||
const content = typeof body.content === 'string' ? body.content : ''
|
||||
const author = typeof body.author === 'string' ? body.author.trim() : ''
|
||||
const description = typeof body.description === 'string' ? body.description.trim() : ''
|
||||
if (!name || !content) {
|
||||
return NextResponse.json({ error: 'name and content are required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const existing = await db.preset.findUnique({ where: { name } })
|
||||
if (existing?.isBuiltIn) {
|
||||
return NextResponse.json(
|
||||
{ error: `'${name}' is a built-in preset — save under a different name` },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
if (existing) {
|
||||
const updated = await db.preset.update({
|
||||
where: { id: existing.id },
|
||||
data: { content, author, description },
|
||||
})
|
||||
return NextResponse.json({ preset: updated, updated: true })
|
||||
}
|
||||
const preset = await db.preset.create({
|
||||
data: { name, content, author, description, isBuiltIn: false },
|
||||
})
|
||||
return NextResponse.json({ preset, created: true })
|
||||
} catch (err) {
|
||||
console.error('POST /api/presets failed:', err)
|
||||
return NextResponse.json({ error: 'Failed to save preset' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
5
src/app/api/route.ts
Normal file
5
src/app/api/route.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({ message: "Hello, world!" });
|
||||
}
|
||||
70
src/app/api/rust-scaffold/route.ts
Normal file
70
src/app/api/rust-scaffold/route.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { NextResponse } from 'next/server'
|
||||
import JSZip from 'jszip'
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/** Directories that must never end up in the scaffold zip. */
|
||||
const SKIP_DIRS = new Set(['target', '.git', 'node_modules'])
|
||||
|
||||
/** Recursively add every file under `dir` to the zip under `prefix`. */
|
||||
async function collectFiles(dir: string, zip: JSZip, prefix: string): Promise<number> {
|
||||
let count = 0
|
||||
const entries = await fs.readdir(dir, { withFileTypes: true })
|
||||
for (const entry of entries) {
|
||||
if (entry.isDirectory() && SKIP_DIRS.has(entry.name)) continue
|
||||
const full = path.join(dir, entry.name)
|
||||
const rel = prefix ? `${prefix}/${entry.name}` : entry.name
|
||||
if (entry.isDirectory()) {
|
||||
count += await collectFiles(full, zip, rel)
|
||||
} else if (entry.isFile()) {
|
||||
zip.file(rel, await fs.readFile(full))
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/** GET /api/rust-scaffold — zip the rust-agent/ cargo project for download. */
|
||||
export async function GET() {
|
||||
const root = path.join(process.cwd(), 'rust-agent')
|
||||
try {
|
||||
const stat = await fs.stat(root)
|
||||
if (!stat.isDirectory()) throw new Error('rust-agent is not a directory')
|
||||
} catch (err) {
|
||||
console.error('GET /api/rust-scaffold: scaffold folder missing:', err)
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
'rust-agent scaffold folder not found on the server (expected at the project root)',
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const zip = new JSZip()
|
||||
const files = await collectFiles(root, zip, 'rust-agent')
|
||||
if (files === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'rust-agent scaffold is empty — nothing to zip' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
const data = await zip.generateAsync({ type: 'uint8array' })
|
||||
return new NextResponse(data, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Disposition': 'attachment; filename="ava-rust-scaffold.zip"',
|
||||
'Content-Length': String(data.length),
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('GET /api/rust-scaffold failed:', err)
|
||||
return NextResponse.json({ error: 'Failed to build the scaffold zip' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
48
src/app/api/settings/route.ts
Normal file
48
src/app/api/settings/route.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { db } from '@/lib/db'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
let settings = await db.settings.findUnique({ where: { id: 'main' } })
|
||||
if (!settings) {
|
||||
settings = await db.settings.create({ data: { id: 'main' } })
|
||||
}
|
||||
return NextResponse.json({
|
||||
defaultScript: settings.defaultScript ?? null,
|
||||
bandConfig: settings.bandConfig ? JSON.parse(settings.bandConfig) : null,
|
||||
beatConfig: settings.beatConfig ? JSON.parse(settings.beatConfig) : null,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('GET /api/settings failed:', err)
|
||||
return NextResponse.json({ error: 'Failed to load settings' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json()
|
||||
const data: Record<string, string> = {}
|
||||
if (typeof body.defaultScript === 'string') data.defaultScript = body.defaultScript
|
||||
if (body.bandConfig && typeof body.bandConfig === 'object') {
|
||||
data.bandConfig = JSON.stringify(body.bandConfig)
|
||||
}
|
||||
if (body.beatConfig && typeof body.beatConfig === 'object') {
|
||||
data.beatConfig = JSON.stringify(body.beatConfig)
|
||||
}
|
||||
const settings = await db.settings.upsert({
|
||||
where: { id: 'main' },
|
||||
update: data,
|
||||
create: { id: 'main', ...data },
|
||||
})
|
||||
return NextResponse.json({
|
||||
defaultScript: settings.defaultScript ?? null,
|
||||
bandConfig: settings.bandConfig ? JSON.parse(settings.bandConfig) : null,
|
||||
beatConfig: settings.beatConfig ? JSON.parse(settings.beatConfig) : null,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('PUT /api/settings failed:', err)
|
||||
return NextResponse.json({ error: 'Failed to save settings' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
122
src/app/globals.css
Normal file
122
src/app/globals.css
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
41
src/app/layout.tsx
Normal file
41
src/app/layout.tsx
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "AVA — Advanced Visualization Agent",
|
||||
description:
|
||||
"Audio-reactive visualization agent for clubs: 3-band spectrum detection, predictive beat tracking and AVS-style visualization scripting.",
|
||||
keywords: ["AVA", "visualization", "VJ", "audio-reactive", "beat detection", "AVS", "Winamp"],
|
||||
icons: {
|
||||
icon: "/logo.svg",
|
||||
},
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" className="dark" suppressHydrationWarning>
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-zinc-950 text-zinc-100 font-sans`}
|
||||
>
|
||||
{children}
|
||||
<Toaster />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
154
src/app/page.tsx
Normal file
154
src/app/page.tsx
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
// AVA — Advanced Visualization Agent · main page.
|
||||
//
|
||||
// Assembles the whole app: header (source controls + beat pairing), the
|
||||
// visual stage (canvas + engine loop), the control panel (Presets / Script /
|
||||
// Detect / Beat / Native) and the sticky footer status bar.
|
||||
//
|
||||
// Engine lifecycle lives in <VisualStage> (the canvas owner); this page owns
|
||||
// initial data loading (presets + settings), the beat-flash watcher and the
|
||||
// Space-to-tap shortcut.
|
||||
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { AppHeader } from '@/components/ava/header'
|
||||
import { VisualStage } from '@/components/ava/visual-stage'
|
||||
import { ControlPanel } from '@/components/ava/control-panel'
|
||||
import { FooterBar } from '@/components/ava/footer-bar'
|
||||
import { applyScriptText, tapBeat } from '@/components/ava/audio-source'
|
||||
import { STARTER_TEMPLATE } from '@/lib/ava/presets'
|
||||
import {
|
||||
isBandConfig,
|
||||
isBeatConfig,
|
||||
lsGetString,
|
||||
readStoredBandConfig,
|
||||
readStoredBeatConfig,
|
||||
useAvaStore,
|
||||
} from '@/lib/store'
|
||||
|
||||
/**
|
||||
* Watch the throttled stats stream and fire the dot-flash for beats the
|
||||
* sampler happened to miss: engine stats arrive ~8 Hz, but a beat flag is
|
||||
* only true on its single frame — so also detect the phase running backwards
|
||||
* (a real beat resets it to 0, the predictor grid wraps it at 1).
|
||||
*/
|
||||
function useBeatWatcher() {
|
||||
const stats = useAvaStore((s) => s.stats)
|
||||
const prevPhaseRef = useRef<number | null>(null)
|
||||
const lastFlashAtRef = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (!stats) return
|
||||
const b = stats.beat
|
||||
const prev = prevPhaseRef.current
|
||||
prevPhaseRef.current = b.phase
|
||||
|
||||
const store = useAvaStore.getState()
|
||||
const now = performance.now()
|
||||
if (now - lastFlashAtRef.current < 100) return
|
||||
|
||||
const flash = (source: Parameters<typeof store.flashBeat>[0]) => {
|
||||
lastFlashAtRef.current = now
|
||||
store.flashBeat(source)
|
||||
}
|
||||
|
||||
if (b.beat) {
|
||||
flash(b.source)
|
||||
return
|
||||
}
|
||||
|
||||
if (prev !== null && b.phase < prev - 0.002) {
|
||||
// ignore the sample immediately after a manual tap — it already flashed
|
||||
const recentTap = store.beatFlash?.source === 'tap' && now - store.beatFlash.at < 300
|
||||
if (recentTap) return
|
||||
// silent + locked tempo → the predictor is carrying the beat
|
||||
const predicted = store.beatConfig.prediction && b.confidence > 0.35 && stats.levels.bassAtt < 0.06
|
||||
if (predicted) {
|
||||
flash('predicted')
|
||||
} else if (stats.levels.bassAtt > 0.05) {
|
||||
// audio is live — a real beat reset the phase
|
||||
flash('audio')
|
||||
}
|
||||
}
|
||||
}, [stats])
|
||||
}
|
||||
|
||||
/** First load: presets + settings (server first, localStorage fallback). */
|
||||
function useInitialLoad() {
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
const [presetsRes, settingsRes] = await Promise.all([
|
||||
fetch('/api/presets')
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.catch(() => null),
|
||||
fetch('/api/settings')
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.catch(() => null),
|
||||
])
|
||||
if (cancelled) return
|
||||
|
||||
const store = useAvaStore.getState()
|
||||
const presetsList = (presetsRes?.presets ?? []) as { content?: string }[]
|
||||
if (presetsRes?.presets) store.setPresets(presetsRes.presets)
|
||||
|
||||
const settings = (settingsRes ?? {}) as {
|
||||
defaultScript?: string | null
|
||||
bandConfig?: unknown
|
||||
beatConfig?: unknown
|
||||
}
|
||||
|
||||
const band = isBandConfig(settings.bandConfig) ? settings.bandConfig : readStoredBandConfig()
|
||||
if (band) store.applyBandConfig(band)
|
||||
const beat = isBeatConfig(settings.beatConfig) ? settings.beatConfig : readStoredBeatConfig()
|
||||
if (beat) store.applyBeatConfig(beat)
|
||||
|
||||
// startup script: saved default → localStorage backup → first preset → template
|
||||
let text: string | null = typeof settings.defaultScript === 'string' ? settings.defaultScript : null
|
||||
if (!text) text = lsGetString('ava.defaultScript')
|
||||
if (!text) text = presetsList[0]?.content ?? null
|
||||
if (!text) text = STARTER_TEMPLATE
|
||||
applyScriptText(text)
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
|
||||
/** Space anywhere outside inputs/buttons taps the beat. */
|
||||
function useSpaceToTap() {
|
||||
useEffect(() => {
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.code !== 'Space' || e.repeat) return
|
||||
const el = e.target as HTMLElement | null
|
||||
const tag = el?.tagName
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || tag === 'BUTTON' || el?.isContentEditable) {
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
tapBeat()
|
||||
}
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
return () => window.removeEventListener('keydown', onKeyDown)
|
||||
}, [])
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
useInitialLoad()
|
||||
useBeatWatcher()
|
||||
useSpaceToTap()
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-zinc-950 text-zinc-100 lg:h-screen lg:overflow-hidden">
|
||||
<AppHeader />
|
||||
<main className="flex min-h-0 flex-1 flex-col gap-4 p-4 lg:flex-row">
|
||||
<VisualStage className="min-h-[45vh] lg:min-h-0 lg:flex-1" />
|
||||
<aside className="flex w-full min-h-0 shrink-0 flex-col lg:w-[420px] xl:w-[440px]">
|
||||
<ControlPanel />
|
||||
</aside>
|
||||
</main>
|
||||
<FooterBar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
124
src/components/ava/audio-source.ts
Normal file
124
src/components/ava/audio-source.ts
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
// AVA — audio source control + "Set Beat" tap helpers
|
||||
//
|
||||
// All engine.audio.* calls are async and require a user gesture; these helpers
|
||||
// centralize error handling, store sync and toasts so every button in the UI
|
||||
// behaves identically.
|
||||
|
||||
'use client'
|
||||
|
||||
import { useCallback } from 'react'
|
||||
import { getEngine } from '@/lib/ava/engine'
|
||||
import type { TapResult } from '@/lib/ava/beat'
|
||||
import { validateScript } from '@/lib/ava/script'
|
||||
import type { ScriptError } from '@/lib/ava/script'
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { useToast } from '@/hooks/use-toast'
|
||||
|
||||
/** "Set Beat" — tap tempo. Flashes the dot immediately with source "tap". */
|
||||
export function tapBeat(): TapResult {
|
||||
const engine = getEngine()
|
||||
const result = engine.beat.tap(performance.now())
|
||||
const store = useAvaStore.getState()
|
||||
store.setLastTap(result)
|
||||
store.flashBeat('tap')
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the editor content and (when it compiles) apply it to the engine.
|
||||
* Returns the validation outcome so callers can toast / show errors.
|
||||
*/
|
||||
export function applyScriptText(text: string): { ok: boolean; error: ScriptError | null } {
|
||||
const v = validateScript(text)
|
||||
const store = useAvaStore.getState()
|
||||
store.setScriptText(text)
|
||||
if (v.ok && v.script) {
|
||||
getEngine().setScript(v.script)
|
||||
return { ok: true, error: null }
|
||||
}
|
||||
return { ok: false, error: v.error }
|
||||
}
|
||||
|
||||
function micErrorMessage(err: unknown): string {
|
||||
const name = (err as DOMException | null)?.name ?? ''
|
||||
if (name === 'NotAllowedError' || name === 'PermissionDeniedError') {
|
||||
return 'Microphone permission denied. Allow mic access in your browser settings and try again.'
|
||||
}
|
||||
if (name === 'NotFoundError' || name === 'DevicesNotFoundError') {
|
||||
return 'No microphone found. Connect an input device and try again.'
|
||||
}
|
||||
return 'Could not start the microphone.'
|
||||
}
|
||||
|
||||
function fileErrorMessage(err: unknown): string {
|
||||
const name = (err as DOMException | null)?.name ?? ''
|
||||
if (name === 'NotSupportedError') {
|
||||
return 'This browser cannot decode that file — try a WAV or MP3.'
|
||||
}
|
||||
return 'Could not play that audio file.'
|
||||
}
|
||||
|
||||
/**
|
||||
* Source lifecycle hook. Every method catches errors (mic permission, decode
|
||||
* failures) → destructive toast, and syncs the store with the engine's
|
||||
* authoritative audio.kind afterwards.
|
||||
*/
|
||||
export function useAudioSource() {
|
||||
const { toast } = useToast()
|
||||
|
||||
const syncSource = useCallback(() => {
|
||||
const engine = getEngine()
|
||||
const kind = engine.audio.kind
|
||||
useAvaStore.getState().setSource(kind === 'idle' ? 'idle' : (kind as 'demo' | 'mic' | 'file'))
|
||||
}, [])
|
||||
|
||||
const startDemo = useCallback(async () => {
|
||||
const engine = getEngine()
|
||||
try {
|
||||
await engine.audio.startDemo()
|
||||
syncSource()
|
||||
} catch (err) {
|
||||
syncSource()
|
||||
toast({
|
||||
title: 'Demo track failed',
|
||||
description: `Could not start the built-in synth (${String(err)}).`,
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}, [syncSource, toast])
|
||||
|
||||
const startMic = useCallback(async () => {
|
||||
const engine = getEngine()
|
||||
try {
|
||||
await engine.audio.startMic()
|
||||
syncSource()
|
||||
toast({ title: 'Microphone live', description: 'Analyzing the mic input — it is never routed to the speakers.' })
|
||||
} catch (err) {
|
||||
syncSource()
|
||||
toast({ title: 'Microphone unavailable', description: micErrorMessage(err), variant: 'destructive' })
|
||||
}
|
||||
}, [syncSource, toast])
|
||||
|
||||
const startFile = useCallback(
|
||||
async (file: File) => {
|
||||
const engine = getEngine()
|
||||
try {
|
||||
await engine.audio.startFile(file)
|
||||
syncSource()
|
||||
toast({ title: 'Playing file', description: file.name })
|
||||
} catch (err) {
|
||||
syncSource()
|
||||
toast({ title: 'File playback failed', description: fileErrorMessage(err), variant: 'destructive' })
|
||||
}
|
||||
},
|
||||
[syncSource, toast],
|
||||
)
|
||||
|
||||
const stop = useCallback(() => {
|
||||
const engine = getEngine()
|
||||
engine.audio.stop()
|
||||
syncSource()
|
||||
}, [syncSource])
|
||||
|
||||
return { startDemo, startMic, startFile, stop }
|
||||
}
|
||||
114
src/components/ava/beat-dot.tsx
Normal file
114
src/components/ava/beat-dot.tsx
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
// AVA — the green beat indicator.
|
||||
//
|
||||
// A circular component: emerald center dot + thin SVG phase ring that fills
|
||||
// with beat.phase over each beat period. On every beat pulse the dot scales up
|
||||
// and glows (~180 ms). When the pulse came from the *predictor* the flash is
|
||||
// rendered as an expanding outline ring + "PRED" badge instead of a filled
|
||||
// dot, so prediction is visible at a glance.
|
||||
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { motion } from 'framer-motion'
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface BeatDotProps {
|
||||
size?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function BeatDot({ size = 44, className }: BeatDotProps) {
|
||||
const phase = useAvaStore((s) => s.stats?.beat.phase ?? 0)
|
||||
const beatFlash = useAvaStore((s) => s.beatFlash)
|
||||
const bpm = useAvaStore((s) => s.stats?.beat.bpm ?? 0)
|
||||
|
||||
// flash state is derived: a flash is "on" until its seq is cleared by the
|
||||
// hold timeout (setState only ever happens inside the timeout callback)
|
||||
const [clearedSeq, setClearedSeq] = useState(-1)
|
||||
|
||||
useEffect(() => {
|
||||
if (!beatFlash) return
|
||||
const hold = beatFlash.source === 'predicted' ? 450 : 180
|
||||
const t = setTimeout(() => setClearedSeq(beatFlash.seq), hold)
|
||||
return () => clearTimeout(t)
|
||||
}, [beatFlash])
|
||||
|
||||
const flashing = beatFlash !== null && beatFlash.seq > clearedSeq
|
||||
const flashSource = flashing ? beatFlash.source : 'none'
|
||||
|
||||
const r = size / 2 - 3
|
||||
const c = 2 * Math.PI * r
|
||||
const predicted = flashing && flashSource === 'predicted'
|
||||
const dotBase = Math.max(8, size * 0.3)
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn('relative shrink-0 select-none', className)}
|
||||
style={{ width: size, height: size }}
|
||||
role="img"
|
||||
aria-label={`Beat indicator — ${bpm > 0 ? `${bpm.toFixed(1)} BPM` : 'no tempo'}${flashSource === 'predicted' ? ', predicted' : ''}`}
|
||||
>
|
||||
{/* phase progress ring */}
|
||||
<svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="absolute inset-0 -rotate-90">
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={r}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={Math.max(2, size / 22)}
|
||||
className="text-zinc-800"
|
||||
/>
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={r}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={Math.max(2, size / 22)}
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={c}
|
||||
strokeDashoffset={c * (1 - Math.min(1, Math.max(0, phase)))}
|
||||
className="text-emerald-400 transition-[stroke-dashoffset] duration-150 ease-linear"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
{/* filled pulse dot (audio / tap beats) */}
|
||||
<div
|
||||
className={cn(
|
||||
'absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-emerald-400 transition-all duration-150 ease-out',
|
||||
flashing && !predicted
|
||||
? 'opacity-100 shadow-[0_0_18px_4px_rgba(52,211,153,0.65)]'
|
||||
: 'opacity-80 shadow-[0_0_8px_1px_rgba(52,211,153,0.3)]',
|
||||
)}
|
||||
style={{
|
||||
width: dotBase,
|
||||
height: dotBase,
|
||||
transform: `translate(-50%, -50%) scale(${flashing && !predicted ? 1.9 : 1})`,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* predicted beats: expanding outline ring instead of the filled dot */}
|
||||
{predicted && (
|
||||
<motion.span
|
||||
initial={{ scale: 0.45, opacity: 0.9 }}
|
||||
animate={{ scale: 1.3, opacity: 0 }}
|
||||
transition={{ duration: 0.45, ease: 'easeOut' }}
|
||||
className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-emerald-300"
|
||||
style={{ width: size * 0.62, height: size * 0.62 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* PRED badge — visible while a predicted pulse is showing */}
|
||||
{predicted && (
|
||||
<span
|
||||
className="absolute left-1/2 -translate-x-1/2 rounded border border-emerald-400/40 bg-zinc-950/90 px-1 py-px font-mono text-emerald-300"
|
||||
style={{ bottom: size >= 64 ? -18 : -13, fontSize: size >= 64 ? 9 : 7, letterSpacing: '0.08em' }}
|
||||
>
|
||||
PRED
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
170
src/components/ava/beat-tab.tsx
Normal file
170
src/components/ava/beat-tab.tsx
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
// AVA — Beat tab: the beat detection & prediction lab.
|
||||
//
|
||||
// Large beat indicator + SET BEAT tap-tempo button, live confidence meter,
|
||||
// sensitivity / min-interval sliders and the prediction switch (all persisted).
|
||||
|
||||
'use client'
|
||||
|
||||
import { motion } from 'framer-motion'
|
||||
import { Timer } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Slider } from '@/components/ui/slider'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { BeatDot } from '@/components/ava/beat-dot'
|
||||
import { tapBeat } from '@/components/ava/audio-source'
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const SOURCE_LABELS: Record<string, string> = {
|
||||
audio: 'AUDIO',
|
||||
predicted: 'PRED',
|
||||
tap: 'TAP',
|
||||
none: 'NONE',
|
||||
}
|
||||
|
||||
export function BeatTab() {
|
||||
const stats = useAvaStore((s) => s.stats)
|
||||
const lastTap = useAvaStore((s) => s.lastTap)
|
||||
const beatFlash = useAvaStore((s) => s.beatFlash)
|
||||
const beatConfig = useAvaStore((s) => s.beatConfig)
|
||||
const setBeatValue = useAvaStore((s) => s.setBeatValue)
|
||||
|
||||
const beat = stats?.beat
|
||||
const bpm = beat?.bpm ?? 0
|
||||
const confidence = beat?.confidence ?? 0
|
||||
const beatCount = stats?.beatCount ?? 0
|
||||
const lastSource = beatFlash?.source ?? 'none'
|
||||
|
||||
const tapFeedback = lastTap
|
||||
? lastTap.locked
|
||||
? `Locked: ${lastTap.bpm.toFixed(1)} BPM`
|
||||
: `Tap ${lastTap.tapCount}… keep tapping`
|
||||
: 'Tap along with the music — Space works too'
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* big dot + readouts */}
|
||||
<div className="flex items-center gap-5">
|
||||
<BeatDot size={80} />
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-4xl font-bold leading-none tabular-nums text-emerald-400">
|
||||
{bpm > 0 ? bpm.toFixed(1) : '—'}
|
||||
<span className="ml-1.5 align-baseline font-sans text-sm font-medium text-zinc-500">BPM</span>
|
||||
</div>
|
||||
<div className="mt-2.5 flex flex-wrap items-center gap-2">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'border-zinc-700 font-mono text-[10px] tracking-wider',
|
||||
lastSource === 'predicted' && 'border-emerald-400/40 text-emerald-300',
|
||||
lastSource === 'tap' && 'border-amber-300/40 text-amber-200',
|
||||
)}
|
||||
>
|
||||
{SOURCE_LABELS[lastSource] ?? lastSource.toUpperCase()}
|
||||
</Badge>
|
||||
<span className="font-mono text-[11px] tabular-nums text-zinc-500">{beatCount} beats</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SET BEAT */}
|
||||
<motion.button
|
||||
type="button"
|
||||
whileTap={{ scale: 0.965 }}
|
||||
onClick={tapBeat}
|
||||
className="flex h-14 w-full flex-col items-center justify-center gap-0.5 rounded-xl bg-emerald-400 font-bold text-zinc-950 shadow-[0_0_24px_rgba(52,211,153,0.28)] transition-colors hover:bg-emerald-300"
|
||||
title="Tap to set the tempo (or press Space)"
|
||||
>
|
||||
<span className="flex items-center gap-2 text-sm font-bold tracking-[0.12em]">
|
||||
<Timer className="size-4" /> SET BEAT
|
||||
</span>
|
||||
<span className="text-[10px] font-medium tracking-wide opacity-70">tap to the music · space works too</span>
|
||||
</motion.button>
|
||||
<p className="min-h-4 text-center font-mono text-xs text-zinc-400" role="status">
|
||||
{tapFeedback}
|
||||
</p>
|
||||
|
||||
{/* confidence */}
|
||||
<div>
|
||||
<div className="mb-1.5 flex items-center justify-between text-xs">
|
||||
<span className="text-zinc-400">Tempo lock confidence</span>
|
||||
<span className="font-mono tabular-nums text-zinc-300">{Math.round(confidence * 100)}%</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-zinc-800">
|
||||
<div
|
||||
className="h-full rounded-full bg-emerald-400 transition-[width] duration-200 ease-linear"
|
||||
style={{ width: `${Math.round(confidence * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator className="bg-zinc-800" />
|
||||
|
||||
{/* detector controls */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="mb-1.5 flex items-center justify-between">
|
||||
<Label className="text-xs text-zinc-400">Sensitivity</Label>
|
||||
<span className="font-mono text-xs tabular-nums text-zinc-200">×{beatConfig.threshold.toFixed(2)}</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[beatConfig.threshold]}
|
||||
min={1.1}
|
||||
max={2.5}
|
||||
step={0.05}
|
||||
onValueChange={([v]) => setBeatValue('threshold', v)}
|
||||
aria-label="Beat sensitivity (threshold)"
|
||||
className="py-1.5"
|
||||
/>
|
||||
<p className="mt-1.5 text-[11px] leading-relaxed text-zinc-500">
|
||||
A beat fires when the bass energy exceeds this multiple of the recent average — lower = more sensitive.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-1.5 flex items-center justify-between">
|
||||
<Label className="text-xs text-zinc-400">Min beat interval</Label>
|
||||
<span className="font-mono text-xs tabular-nums text-zinc-200">{beatConfig.minInterval} ms</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[beatConfig.minInterval]}
|
||||
min={150}
|
||||
max={600}
|
||||
step={10}
|
||||
onValueChange={([v]) => setBeatValue('minInterval', v)}
|
||||
aria-label="Minimum beat interval"
|
||||
className="py-1.5"
|
||||
/>
|
||||
<p className="mt-1.5 text-[11px] leading-relaxed text-zinc-500">
|
||||
Fastest allowed beat rate — raise it to ignore double-hits and rolls.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border border-zinc-800/80 bg-zinc-950/40 p-3">
|
||||
<div>
|
||||
<Label className="text-xs text-zinc-300">Beat prediction</Label>
|
||||
<p className="mt-0.5 text-[11px] text-zinc-500">Keeps the beat alive when the bass drops out.</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={beatConfig.prediction}
|
||||
onCheckedChange={(v) => setBeatValue('prediction', v)}
|
||||
aria-label="Beat prediction"
|
||||
className="data-[state=checked]:bg-emerald-400"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator className="bg-zinc-800" />
|
||||
|
||||
<p className="text-[11px] leading-relaxed text-zinc-500">
|
||||
<span className="font-semibold text-zinc-400">How it works:</span> beats are detected from the smoothed bass
|
||||
energy crossing the sensitivity threshold. Consistent intervals lock a tempo (the confidence meter), and a
|
||||
phase-locked predictor then keeps firing beats on the learned grid — shown as a hollow ring with a PRED badge —
|
||||
whenever the bass disappears. <span className="font-semibold text-zinc-400">Set Beat</span> teaches the tempo
|
||||
directly: tap along and two or more taps lock the period and phase to your rhythm.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
85
src/components/ava/control-panel.tsx
Normal file
85
src/components/ava/control-panel.tsx
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
// AVA — right-hand control panel: the five tabs.
|
||||
//
|
||||
// Desktop: fixed width, content scrolls inside the panel. Mobile: natural
|
||||
// height (the page scrolls and the footer is pushed down naturally).
|
||||
|
||||
'use client'
|
||||
|
||||
import { motion } from 'framer-motion'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { PresetsTab } from '@/components/ava/presets-tab'
|
||||
import { ScriptTab } from '@/components/ava/script-tab'
|
||||
import { DetectTab } from '@/components/ava/detect-tab'
|
||||
import { BeatTab } from '@/components/ava/beat-tab'
|
||||
import { NativeTab } from '@/components/ava/native-tab'
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { thinScrollbar } from '@/components/ava/shared'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
function TabBody({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 4 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.16, ease: 'easeOut' }}
|
||||
className={cn(thinScrollbar, 'min-h-0 flex-1 overflow-y-auto pr-1 lg:h-full')}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ControlPanel() {
|
||||
const tab = useAvaStore((s) => s.tab)
|
||||
const setTab = useAvaStore((s) => s.setTab)
|
||||
|
||||
return (
|
||||
<Tabs value={tab} onValueChange={setTab} className="flex min-h-0 flex-1 flex-col gap-3">
|
||||
<TabsList className="grid h-11 w-full shrink-0 grid-cols-5 bg-zinc-900/80">
|
||||
<TabsTrigger value="presets" className="text-xs">
|
||||
Presets
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="script" className="text-xs">
|
||||
Script
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="detect" className="text-xs">
|
||||
Detect
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="beat" className="text-xs">
|
||||
Beat
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="native" className="text-xs">
|
||||
Native
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col rounded-xl border border-zinc-800/80 bg-zinc-900/60 p-4 lg:overflow-hidden">
|
||||
<TabsContent value="presets" className="flex min-h-0 flex-1 flex-col outline-none">
|
||||
<TabBody>
|
||||
<PresetsTab />
|
||||
</TabBody>
|
||||
</TabsContent>
|
||||
<TabsContent value="script" className="flex min-h-0 flex-1 flex-col outline-none">
|
||||
<TabBody>
|
||||
<ScriptTab />
|
||||
</TabBody>
|
||||
</TabsContent>
|
||||
<TabsContent value="detect" className="flex min-h-0 flex-1 flex-col outline-none">
|
||||
<TabBody>
|
||||
<DetectTab />
|
||||
</TabBody>
|
||||
</TabsContent>
|
||||
<TabsContent value="beat" className="flex min-h-0 flex-1 flex-col outline-none">
|
||||
<TabBody>
|
||||
<BeatTab />
|
||||
</TabBody>
|
||||
</TabsContent>
|
||||
<TabsContent value="native" className="flex min-h-0 flex-1 flex-col outline-none">
|
||||
<TabBody>
|
||||
<NativeTab />
|
||||
</TabBody>
|
||||
</TabsContent>
|
||||
</div>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
215
src/components/ava/detect-tab.tsx
Normal file
215
src/components/ava/detect-tab.tsx
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
// AVA — Detect tab: fine-tune the three analysis bands (Hz ranges + gains)
|
||||
// with live VU meters. Changes apply to the engine immediately and persist
|
||||
// (localStorage instantly, /api/settings debounced).
|
||||
|
||||
'use client'
|
||||
|
||||
import { RotateCcw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Slider } from '@/components/ui/slider'
|
||||
import { DEFAULT_BAND_CONFIG } from '@/lib/ava/types'
|
||||
import type { BandConfig, BandLevels } from '@/lib/ava/types'
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { clamp01, fmtHz } from '@/components/ava/shared'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type BandKey = 'bass' | 'mid' | 'high'
|
||||
|
||||
type LevelKey = 'bass' | 'mid' | 'treb'
|
||||
|
||||
interface BandSpec {
|
||||
key: BandKey
|
||||
title: string
|
||||
levelKey: LevelKey
|
||||
attKey: `${LevelKey}Att`
|
||||
lowKey: keyof BandConfig
|
||||
highKey: keyof BandConfig
|
||||
gainKey: keyof BandConfig
|
||||
lowRange: { min: number; max: number; step: number }
|
||||
highRange: { min: number; max: number; step: number }
|
||||
barClass: string
|
||||
textClass: string
|
||||
}
|
||||
|
||||
const BANDS: BandSpec[] = [
|
||||
{
|
||||
key: 'bass',
|
||||
title: 'Bass',
|
||||
levelKey: 'bass',
|
||||
attKey: 'bassAtt',
|
||||
lowKey: 'bassLow',
|
||||
highKey: 'bassHigh',
|
||||
gainKey: 'bassGain',
|
||||
lowRange: { min: 10, max: 300, step: 5 },
|
||||
highRange: { min: 20, max: 500, step: 5 },
|
||||
barClass: 'bg-emerald-400',
|
||||
textClass: 'text-emerald-400',
|
||||
},
|
||||
{
|
||||
key: 'mid',
|
||||
title: 'Mid',
|
||||
levelKey: 'mid',
|
||||
attKey: 'midAtt',
|
||||
lowKey: 'midLow',
|
||||
highKey: 'midHigh',
|
||||
gainKey: 'midGain',
|
||||
lowRange: { min: 100, max: 5000, step: 25 },
|
||||
highRange: { min: 300, max: 8000, step: 50 },
|
||||
barClass: 'bg-amber-300',
|
||||
textClass: 'text-amber-300',
|
||||
},
|
||||
{
|
||||
key: 'high',
|
||||
title: 'High',
|
||||
levelKey: 'treb',
|
||||
attKey: 'trebAtt',
|
||||
lowKey: 'highLow',
|
||||
highKey: 'highHigh',
|
||||
gainKey: 'highGain',
|
||||
lowRange: { min: 1000, max: 12000, step: 100 },
|
||||
highRange: { min: 4000, max: 20000, step: 250 },
|
||||
barClass: 'bg-rose-400',
|
||||
textClass: 'text-rose-400',
|
||||
},
|
||||
]
|
||||
|
||||
function SliderRow({
|
||||
label,
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
readout,
|
||||
onChange,
|
||||
}: {
|
||||
label: string
|
||||
value: number
|
||||
min: number
|
||||
max: number
|
||||
step: number
|
||||
readout: string
|
||||
onChange: (v: number) => void
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-1.5 flex items-center justify-between">
|
||||
<Label className="text-xs text-zinc-400">{label}</Label>
|
||||
<span className="font-mono text-xs tabular-nums text-zinc-200">{readout}</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[value]}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
onValueChange={([v]) => onChange(v)}
|
||||
aria-label={label}
|
||||
className="py-1.5"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BandCard({ spec, levels }: { spec: BandSpec; levels: BandLevels | null }) {
|
||||
const bandConfig = useAvaStore((s) => s.bandConfig)
|
||||
const setBandValue = useAvaStore((s) => s.setBandValue)
|
||||
|
||||
const level = levels ? levels[spec.levelKey] : 0
|
||||
const levelAtt = levels ? levels[spec.attKey] : 0
|
||||
|
||||
const resetBand = () => {
|
||||
// restore defaults for just this band, keeping the other two bands untouched
|
||||
setBandValue(spec.lowKey, DEFAULT_BAND_CONFIG[spec.lowKey])
|
||||
setBandValue(spec.highKey, DEFAULT_BAND_CONFIG[spec.highKey])
|
||||
setBandValue(spec.gainKey, DEFAULT_BAND_CONFIG[spec.gainKey])
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-zinc-800/80 bg-zinc-950/40 p-4">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h4 className="text-sm font-semibold">
|
||||
<span className={cn('mr-2', spec.textClass)}>●</span>
|
||||
{spec.title}
|
||||
<span className="ml-2 font-mono text-xs font-normal tabular-nums text-zinc-500">
|
||||
{fmtHz(bandConfig[spec.lowKey])} – {fmtHz(bandConfig[spec.highKey])}
|
||||
</span>
|
||||
</h4>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={resetBand}
|
||||
aria-label={`Reset ${spec.title} band to defaults`}
|
||||
className="size-8 text-zinc-500 hover:bg-zinc-800 hover:text-zinc-200"
|
||||
>
|
||||
<RotateCcw className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<SliderRow
|
||||
label="Low cut"
|
||||
value={bandConfig[spec.lowKey] as number}
|
||||
min={spec.lowRange.min}
|
||||
max={spec.lowRange.max}
|
||||
step={spec.lowRange.step}
|
||||
readout={fmtHz(bandConfig[spec.lowKey] as number)}
|
||||
onChange={(v) => setBandValue(spec.lowKey, v)}
|
||||
/>
|
||||
<SliderRow
|
||||
label="High cut"
|
||||
value={bandConfig[spec.highKey] as number}
|
||||
min={spec.highRange.min}
|
||||
max={spec.highRange.max}
|
||||
step={spec.highRange.step}
|
||||
readout={fmtHz(bandConfig[spec.highKey] as number)}
|
||||
onChange={(v) => setBandValue(spec.highKey, v)}
|
||||
/>
|
||||
<SliderRow
|
||||
label="Gain"
|
||||
value={bandConfig[spec.gainKey] as number}
|
||||
min={0.1}
|
||||
max={4}
|
||||
step={0.05}
|
||||
readout={`×${(bandConfig[spec.gainKey] as number).toFixed(2)}`}
|
||||
onChange={(v) => setBandValue(spec.gainKey, v)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* live VU meter — instant fill + smoothed peak-hold tick */}
|
||||
<div className="mt-4">
|
||||
<div className="relative h-2 overflow-hidden rounded-full bg-zinc-800/80">
|
||||
<div
|
||||
className={cn('h-full rounded-full transition-[width] duration-100 ease-linear', spec.barClass)}
|
||||
style={{ width: `${clamp01(level) * 100}%` }}
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-y-0 w-[2px] bg-zinc-100/80"
|
||||
style={{ left: `${clamp01(levelAtt) * 100}%` }}
|
||||
aria-hidden
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-1 flex justify-between font-mono text-[9px] tabular-nums text-zinc-600">
|
||||
<span>level {level.toFixed(2)}</span>
|
||||
<span>peak {levelAtt.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DetectTab() {
|
||||
const levels = useAvaStore((s) => s.stats?.levels ?? null)
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<p className="text-xs leading-relaxed text-zinc-500">
|
||||
Tune which frequency ranges feed <span className="font-mono text-zinc-400">bass</span>,{' '}
|
||||
<span className="font-mono text-zinc-400">mid</span> and <span className="font-mono text-zinc-400">treb</span>.
|
||||
Changes apply live and are saved automatically. Defaults: Bass 20–100 Hz, Mid 700–2000 Hz, High 7k–16k Hz.
|
||||
</p>
|
||||
{BANDS.map((spec) => (
|
||||
<BandCard key={spec.key} spec={spec} levels={levels} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
50
src/components/ava/footer-bar.tsx
Normal file
50
src/components/ava/footer-bar.tsx
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// AVA — sticky footer status bar: micro-stats + engine health.
|
||||
|
||||
'use client'
|
||||
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function FooterBar() {
|
||||
const stats = useAvaStore((s) => s.stats)
|
||||
const source = useAvaStore((s) => s.source)
|
||||
|
||||
const fps = stats?.fps ?? 0
|
||||
const points = stats?.points ?? 0
|
||||
const bpm = stats?.beat.bpm ?? 0
|
||||
const scriptName = stats?.scriptName ?? '—'
|
||||
const error = stats?.error ?? null
|
||||
|
||||
return (
|
||||
<footer className="mt-auto border-t border-zinc-800/80 bg-zinc-950/90 backdrop-blur">
|
||||
<div className="mx-auto flex max-w-[1800px] items-center gap-3 overflow-hidden px-4 py-2 font-mono text-[11px] tabular-nums text-zinc-500 sm:gap-4">
|
||||
<span className="hidden sm:inline">
|
||||
SRC: <span className="text-zinc-300">{source.toUpperCase()}</span>
|
||||
</span>
|
||||
<span>
|
||||
FPS: <span className="text-zinc-300">{fps}</span>
|
||||
</span>
|
||||
<span className="hidden sm:inline">
|
||||
PTS: <span className="text-zinc-300">{points}</span>
|
||||
</span>
|
||||
<span>
|
||||
BPM: <span className="text-zinc-300">{bpm > 0 ? bpm.toFixed(1) : '—'}</span>
|
||||
</span>
|
||||
<span className="hidden min-w-0 items-center md:flex">
|
||||
SCRIPT: <span className="ml-1 truncate text-zinc-300">{scriptName}</span>
|
||||
</span>
|
||||
|
||||
<span className={cn('ml-auto flex shrink-0 items-center gap-1.5', error ? 'text-rose-400' : 'text-emerald-400')}>
|
||||
<span
|
||||
className={cn(
|
||||
'size-1.5 rounded-full',
|
||||
error ? 'animate-pulse bg-rose-400 shadow-[0_0_8px_rgba(251,113,133,0.8)]' : 'bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.8)]',
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="text-zinc-400">{error ? 'script error' : 'engine ok'}</span>
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
172
src/components/ava/header.tsx
Normal file
172
src/components/ava/header.tsx
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// AVA — sticky app header: logo, audio source controls (segmented), demo BPM
|
||||
// slider, BPM readout, and the beat indicator + "Set Beat" button side by side
|
||||
// (hard requirement: that pairing is always visible in the header).
|
||||
|
||||
'use client'
|
||||
|
||||
import { useRef } from 'react'
|
||||
import { AudioWaveform, Disc3, FileAudio, Mic, Square, Timer } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Slider } from '@/components/ui/slider'
|
||||
import { BeatDot } from '@/components/ava/beat-dot'
|
||||
import { tapBeat, useAudioSource } from '@/components/ava/audio-source'
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
function SourceSegmentButton({
|
||||
active,
|
||||
onClick,
|
||||
icon: Icon,
|
||||
label,
|
||||
title,
|
||||
tone = 'default',
|
||||
}: {
|
||||
active: boolean
|
||||
onClick: () => void
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
title: string
|
||||
tone?: 'default' | 'stop'
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-pressed={active}
|
||||
title={title}
|
||||
className={cn(
|
||||
'flex h-11 items-center gap-1.5 rounded-md px-3 text-xs font-medium transition-colors',
|
||||
active
|
||||
? 'bg-emerald-400/15 text-emerald-300 shadow-[inset_0_0_0_1px_rgba(52,211,153,0.35)]'
|
||||
: tone === 'stop'
|
||||
? 'text-rose-300/70 hover:bg-zinc-800 hover:text-rose-300'
|
||||
: 'text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-3.5" />
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function SourceControls() {
|
||||
const source = useAvaStore((s) => s.source)
|
||||
const setDemoBpm = useAvaStore((s) => s.setDemoBpm)
|
||||
const demoBpm = useAvaStore((s) => s.demoBpm)
|
||||
const { startDemo, startMic, startFile, stop } = useAudioSource()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Audio source"
|
||||
className="flex items-center gap-0.5 rounded-lg border border-zinc-800 bg-zinc-900/60 p-0.5"
|
||||
>
|
||||
<SourceSegmentButton
|
||||
active={source === 'demo'}
|
||||
onClick={() => void startDemo()}
|
||||
icon={Disc3}
|
||||
label="Demo"
|
||||
title="Built-in demo track (synthesized techno)"
|
||||
/>
|
||||
<SourceSegmentButton
|
||||
active={source === 'mic'}
|
||||
onClick={() => void startMic()}
|
||||
icon={Mic}
|
||||
label="Mic"
|
||||
title="Live microphone / line-in"
|
||||
/>
|
||||
<SourceSegmentButton
|
||||
active={source === 'file'}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
icon={FileAudio}
|
||||
label="File"
|
||||
title="Play an audio file (loops)"
|
||||
/>
|
||||
<SourceSegmentButton active={false} onClick={stop} icon={Square} label="Stop" title="Stop audio" tone="stop" />
|
||||
</div>
|
||||
|
||||
{source === 'demo' && (
|
||||
<div className="flex h-11 items-center gap-2 rounded-lg border border-zinc-800 bg-zinc-900/60 px-3">
|
||||
<span className="font-mono text-[10px] tracking-widest text-emerald-400/80">DEMO</span>
|
||||
<Slider
|
||||
value={[demoBpm]}
|
||||
min={60}
|
||||
max={200}
|
||||
step={1}
|
||||
onValueChange={([v]) => setDemoBpm(v)}
|
||||
className="w-24"
|
||||
aria-label="Demo track tempo"
|
||||
/>
|
||||
<span className="w-8 text-right font-mono text-xs tabular-nums text-zinc-300">{demoBpm}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="audio/*"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) void startFile(file)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BpmReadout() {
|
||||
const bpm = useAvaStore((s) => s.stats?.beat.bpm ?? 0)
|
||||
return (
|
||||
<div className="text-right leading-none">
|
||||
<div className="font-mono text-xl font-bold tabular-nums text-emerald-400 sm:text-2xl">
|
||||
{bpm > 0 ? bpm.toFixed(1) : '—'}
|
||||
</div>
|
||||
<div className="mt-0.5 font-mono text-[9px] tracking-[0.2em] text-zinc-500">BPM</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function AppHeader() {
|
||||
return (
|
||||
<header className="sticky top-0 z-40 border-b border-zinc-800/80 bg-zinc-950/80 backdrop-blur supports-[backdrop-filter]:bg-zinc-950/60">
|
||||
<div className="mx-auto flex max-w-[1800px] flex-wrap items-center gap-x-3 gap-y-2 px-3 py-2 sm:px-4">
|
||||
{/* logo */}
|
||||
<div className="order-1 flex items-center gap-2.5">
|
||||
<div className="grid size-9 place-items-center rounded-lg bg-emerald-400 shadow-[0_0_16px_rgba(52,211,153,0.35)]">
|
||||
<AudioWaveform className="size-5 text-zinc-950" aria-hidden />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-base font-bold leading-none tracking-wide">AVA</h1>
|
||||
<p className="mt-1 hidden text-[10px] leading-none tracking-[0.14em] text-zinc-500 sm:block">
|
||||
ADVANCED VISUALIZATION AGENT
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* source controls — full row on mobile, after logo on desktop */}
|
||||
<div className="order-3 basis-full md:order-2 md:basis-auto">
|
||||
<SourceControls />
|
||||
</div>
|
||||
|
||||
{/* BPM readout + beat indicator + Set Beat — always paired, always visible */}
|
||||
<div className="order-2 ml-auto flex items-center gap-2.5 md:order-3 sm:gap-3">
|
||||
<BpmReadout />
|
||||
<BeatDot size={44} />
|
||||
<Button
|
||||
onClick={tapBeat}
|
||||
className="h-11 gap-1.5 bg-emerald-400 px-3 font-semibold text-zinc-950 hover:bg-emerald-300 sm:px-4"
|
||||
title="Tap to set the tempo (or press Space)"
|
||||
>
|
||||
<Timer className="size-4" />
|
||||
<span className="hidden sm:inline">Set Beat</span>
|
||||
<span className="sm:hidden">Beat</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
170
src/components/ava/help-panel.tsx
Normal file
170
src/components/ava/help-panel.tsx
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
// AVA — script editor help panel: variables, functions, operators, examples
|
||||
// and the .ava file format. Collapsible, opened from the editor toolbar.
|
||||
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
const FRAME_VARS: [string, string][] = [
|
||||
['n', 'point count (4–4096, default 400 — set in [init] or [frame])'],
|
||||
['t', 'your own counter (do with it whatever you want)'],
|
||||
['time', 'seconds since the script started'],
|
||||
['dt', 'frame delta in seconds'],
|
||||
['frame', 'frame number'],
|
||||
['bass / mid / treb', 'instant band levels, 0..1 and above'],
|
||||
['bass_att / mid_att / treb_att', 'smoothed bands (fast attack, slow release) — use these for beat detection logic'],
|
||||
['vol / vol_att', 'overall level, instant + smoothed'],
|
||||
['beat', '1 on the frame a beat fired, else 0'],
|
||||
['bpm', 'detected tempo'],
|
||||
['beatphase', '0..1 position within the beat period'],
|
||||
['beatconf', '0..1 confidence of the tempo lock'],
|
||||
['beats', 'total beat count since load'],
|
||||
['w / h', 'canvas size in pixels'],
|
||||
['aspect', 'canvas width / height — divide x by it for perfect circles'],
|
||||
['persist', 'motion-trail persistence 0..0.98 (writable per frame)'],
|
||||
]
|
||||
|
||||
const POINT_VARS: [string, string][] = [
|
||||
['i', '0..1 point index'],
|
||||
['v', 'waveform sample −1..1'],
|
||||
['sv', 'spectrum magnitude 0..1'],
|
||||
['x / y', 'position −1..1 (x = sin(a)*rad / aspect keeps circles round)'],
|
||||
['red / green / blue', 'point color 0..1'],
|
||||
['skip', '> 0.5 hides the point / breaks the line'],
|
||||
['size', 'dot radius in pixels (dots mode)'],
|
||||
['alpha', 'opacity 0..1'],
|
||||
]
|
||||
|
||||
const FUNCS: [string, string][] = [
|
||||
['sin cos tan asin acos atan', 'trigonometry (radians)'],
|
||||
['atan2(x, y)', 'arctangent of y/x keeping quadrant'],
|
||||
['abs sqrt sqr pow(x, y) exp log log10', 'powers, roots & logs'],
|
||||
['floor ceil round int frac sign', 'rounding & sign'],
|
||||
['min max', 'pairwise extrema'],
|
||||
['rand(seed)', 'deterministic per-seed random 0..1 — rand(i) is stable per point'],
|
||||
['lerp(a, b, t) clamp(x, lo, hi)', 'interpolate & constrain'],
|
||||
['inrange(x, lo, hi)', '1 when lo ≤ x ≤ hi'],
|
||||
['above(a, b) below(a, b) equal(a, b)', 'comparisons returning 1/0'],
|
||||
['band(a, b) bor(a, b) bnot(a)', 'logical and / or / not (also && || !)'],
|
||||
['sigmoid(x, y)', '1 / (1 + exp(-x·y))'],
|
||||
['if(cond, a, b)', 'lazy conditional — only the taken branch runs, so if(beat, flash=1, 0) works'],
|
||||
]
|
||||
|
||||
const EXAMPLES: [string, string][] = [
|
||||
['rad = 0.2 + bass * 0.6', 'bass pulse'],
|
||||
['rot = rot + dt * 1.2 + beat * 0.4', 'beat kick'],
|
||||
['ang = rand(i) * 6.28318', 'stable per-point random'],
|
||||
['size = if(above(bass, 0.5), 6, 2)', 'conditional dot size'],
|
||||
['x = sin(i * 6.28318 + t) * rad / aspect', 'circle'],
|
||||
]
|
||||
|
||||
function HelpTable({ rows, mono = true }: { rows: [string, string][]; mono?: boolean }) {
|
||||
return (
|
||||
<table className="w-full border-collapse text-left">
|
||||
<tbody>
|
||||
{rows.map(([name, desc]) => (
|
||||
<tr key={name} className="border-b border-zinc-800/60 last:border-0 align-top">
|
||||
<td
|
||||
className={`py-1 pr-3 whitespace-nowrap text-emerald-300/90 ${mono ? 'font-mono text-[11px]' : 'text-xs'}`}
|
||||
>
|
||||
{name}
|
||||
</td>
|
||||
<td className="py-1 text-[11px] leading-relaxed text-zinc-400">{desc}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
|
||||
function HelpSection({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<section>
|
||||
<h4 className="mb-2 text-[11px] font-semibold uppercase tracking-[0.15em] text-zinc-400">{title}</h4>
|
||||
{children}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export function HelpPanel() {
|
||||
return (
|
||||
<div className="space-y-5 rounded-lg border border-zinc-800/80 bg-zinc-950/60 p-4">
|
||||
<HelpSection title="Quick start">
|
||||
<ol className="list-inside list-decimal space-y-1 text-[11px] leading-relaxed text-zinc-400">
|
||||
<li>Write header keys (name, mode, blend, persist, linewidth) at the top.</li>
|
||||
<li>
|
||||
Put setup code in <span className="font-mono text-emerald-300/90">[init]</span>, per-frame code in{' '}
|
||||
<span className="font-mono text-emerald-300/90">[frame]</span>, reactions in{' '}
|
||||
<span className="font-mono text-emerald-300/90">[beat]</span>, and the geometry in{' '}
|
||||
<span className="font-mono text-emerald-300/90">[point]</span>.
|
||||
</li>
|
||||
<li>
|
||||
Set <span className="font-mono text-emerald-300/90">n</span> (point count) in [init], drive it with{' '}
|
||||
<span className="font-mono text-emerald-300/90">bass</span>,{' '}
|
||||
<span className="font-mono text-emerald-300/90">beat</span> and <span className="font-mono text-emerald-300/90">v</span>.
|
||||
</li>
|
||||
<li>Hit Apply ▶ — errors are flagged next to the exact line.</li>
|
||||
</ol>
|
||||
</HelpSection>
|
||||
|
||||
<HelpSection title="Variables — everywhere">
|
||||
<HelpTable rows={FRAME_VARS} />
|
||||
</HelpSection>
|
||||
|
||||
<HelpSection title="Variables — [point] only">
|
||||
<HelpTable rows={POINT_VARS} />
|
||||
</HelpSection>
|
||||
|
||||
<HelpSection title="Functions">
|
||||
<HelpTable rows={FUNCS} />
|
||||
<p className="mt-2 text-[11px] text-zinc-500">
|
||||
Constants: <span className="font-mono text-emerald-300/90">pi tau e</span>
|
||||
</p>
|
||||
</HelpSection>
|
||||
|
||||
<HelpSection title="Operators">
|
||||
<p className="font-mono text-[11px] leading-relaxed text-zinc-400">
|
||||
+ - * / % ^ (power) · == != < <= > >= · && || ! ·
|
||||
ternary <span className="text-emerald-300/90">c ? a : b</span> · assignment{' '}
|
||||
<span className="text-emerald-300/90">=</span> (works inside if() and ternary branches)
|
||||
</p>
|
||||
<p className="mt-1.5 text-[11px] leading-relaxed text-zinc-500">
|
||||
Statements are separated by newlines or semicolons. Comments start with <span className="font-mono">{'#'}</span> or{' '}
|
||||
<span className="font-mono">{'//'}</span>.
|
||||
</p>
|
||||
</HelpSection>
|
||||
|
||||
<HelpSection title="Example formulas">
|
||||
<div className="space-y-1.5">
|
||||
{EXAMPLES.map(([code, note]) => (
|
||||
<div key={code} className="flex flex-col gap-0.5 rounded border border-zinc-800/70 bg-black/40 px-2.5 py-1.5">
|
||||
<code className="font-mono text-[11px] text-zinc-200">{code}</code>
|
||||
<span className="text-[10px] text-zinc-500">{note}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</HelpSection>
|
||||
|
||||
<HelpSection title="File format (.ava)">
|
||||
<p className="mb-2 text-[11px] leading-relaxed text-zinc-400">
|
||||
A plain-text file: optional header keys before the first section, then any of the four sections in any order.
|
||||
</p>
|
||||
<pre className="overflow-x-auto rounded border border-zinc-800/70 bg-black/40 p-2.5 font-mono text-[11px] leading-relaxed text-zinc-300">
|
||||
{`# header keys
|
||||
name: My Visualization
|
||||
author: you
|
||||
description: shown in the preset list
|
||||
mode: lines # lines | dots | solid
|
||||
blend: additive # additive | alpha
|
||||
persist: 0.85 # trail persistence 0..0.98
|
||||
linewidth: 2
|
||||
|
||||
[init] # runs once on load
|
||||
[frame] # runs every frame
|
||||
[beat] # runs on beat frames (after [frame])
|
||||
[point] # runs n times per frame`}
|
||||
</pre>
|
||||
</HelpSection>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
78
src/components/ava/native-tab.tsx
Normal file
78
src/components/ava/native-tab.tsx
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
// AVA — Native tab: renders the Rust/Vulkan blueprint from
|
||||
// @/lib/ava/blueprint.ts and links the scaffold zip download.
|
||||
|
||||
'use client'
|
||||
|
||||
import { Download, Package } from 'lucide-react'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { BLUEPRINT } from '@/lib/ava/blueprint'
|
||||
|
||||
export function NativeTab() {
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<h3 className="flex items-center gap-2 text-base font-semibold">
|
||||
<Package className="size-4 text-emerald-400" aria-hidden />
|
||||
{BLUEPRINT.title}
|
||||
</h3>
|
||||
<p className="mt-2 text-xs leading-relaxed text-zinc-400">{BLUEPRINT.intro}</p>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href="/api/rust-scaffold"
|
||||
download
|
||||
className="flex h-12 items-center justify-center gap-2 rounded-xl bg-emerald-400 font-semibold text-zinc-950 shadow-[0_0_20px_rgba(52,211,153,0.25)] transition-colors hover:bg-emerald-300"
|
||||
>
|
||||
<Download className="size-4" />
|
||||
Download Rust Scaffold (.zip)
|
||||
</a>
|
||||
<p className="text-[11px] text-zinc-500">{BLUEPRINT.downloadNote}</p>
|
||||
|
||||
<blockquote className="rounded-lg border border-emerald-400/20 bg-emerald-400/5 p-3 text-[11px] leading-relaxed text-emerald-200/80">
|
||||
The <span className="font-mono">.ava</span> scripts you write here run on both the web edition and the native
|
||||
Rust engine — the script language is identical.
|
||||
</blockquote>
|
||||
|
||||
<Separator className="bg-zinc-800" />
|
||||
|
||||
<div className="space-y-6">
|
||||
{BLUEPRINT.sections.map((section) => (
|
||||
<section key={section.title}>
|
||||
<h4 className="mb-2 text-sm font-semibold text-zinc-200">{section.title}</h4>
|
||||
<div className="space-y-2">
|
||||
{section.body.map((para, i) => (
|
||||
<p key={i} className="text-xs leading-relaxed text-zinc-400">
|
||||
{para}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
{section.bullets && section.bullets.length > 0 && (
|
||||
<ul className="mt-3 space-y-1.5">
|
||||
{section.bullets.map((bullet, i) => (
|
||||
<li key={i} className="flex gap-2 text-xs leading-relaxed text-zinc-400">
|
||||
<span className="mt-1.5 size-1 shrink-0 rounded-full bg-emerald-400/70" aria-hidden />
|
||||
<span>{bullet}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{section.code && section.code.length > 0 && (
|
||||
<div className="mt-3 space-y-3">
|
||||
{section.code.map((block, i) => (
|
||||
<div key={i}>
|
||||
<div className="mb-1 font-mono text-[10px] uppercase tracking-wider text-zinc-600">
|
||||
{block.label} · {block.language}
|
||||
</div>
|
||||
<pre className="overflow-x-auto rounded-lg border border-zinc-800 bg-zinc-950 p-3 font-mono text-[11px] leading-relaxed text-zinc-300">
|
||||
{block.content}
|
||||
</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
245
src/components/ava/presets-tab.tsx
Normal file
245
src/components/ava/presets-tab.tsx
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
// AVA — Presets tab: load/delete preset scripts, download the original .avs
|
||||
// binaries for the built-ins, save the current editor script as a preset.
|
||||
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Download, FilePlus2, Play, Save, Trash2 } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { originalFileUrl, STARTER_TEMPLATE } from '@/lib/ava/presets'
|
||||
import { validateScript } from '@/lib/ava/script'
|
||||
import { refreshPresets, useAvaStore, type PresetItem } from '@/lib/store'
|
||||
import { applyScriptText } from '@/components/ava/audio-source'
|
||||
import { modeOfScript, thinScrollbar } from '@/components/ava/shared'
|
||||
import { useToast } from '@/hooks/use-toast'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
function PresetCard({ preset }: { preset: PresetItem }) {
|
||||
const { toast } = useToast()
|
||||
const setTab = useAvaStore((s) => s.setTab)
|
||||
const [confirmingDelete, setConfirmingDelete] = useState(false)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!confirmingDelete) return
|
||||
const t = setTimeout(() => setConfirmingDelete(false), 3000)
|
||||
return () => clearTimeout(t)
|
||||
}, [confirmingDelete])
|
||||
|
||||
const load = () => {
|
||||
const result = applyScriptText(preset.content)
|
||||
if (result.ok) {
|
||||
toast({ title: 'Preset loaded', description: `"${preset.name}" is now running.` })
|
||||
} else if (result.error) {
|
||||
toast({
|
||||
title: 'Preset failed to compile',
|
||||
description: `[${result.error.section}] line ${result.error.line}: ${result.error.message}`,
|
||||
variant: 'destructive',
|
||||
})
|
||||
setTab('script')
|
||||
}
|
||||
}
|
||||
|
||||
const remove = async () => {
|
||||
setDeleting(true)
|
||||
try {
|
||||
const res = await fetch(`/api/presets/${preset.id}`, { method: 'DELETE' })
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
await refreshPresets()
|
||||
toast({ title: 'Preset deleted', description: `"${preset.name}" removed.` })
|
||||
} catch {
|
||||
toast({ title: 'Delete failed', description: 'Could not remove that preset.', variant: 'destructive' })
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
setConfirmingDelete(false)
|
||||
}
|
||||
}
|
||||
|
||||
const original = preset.isBuiltIn ? originalFileUrl(preset.name) : undefined
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800/80 bg-zinc-950/40 p-3.5">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<h4 className="truncate text-sm font-medium text-zinc-100">{preset.name}</h4>
|
||||
<p className="truncate text-[11px] text-zinc-500">by {preset.author || 'unknown'}</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<Badge variant="outline" className="border-zinc-700 font-mono text-[10px] text-zinc-400">
|
||||
{modeOfScript(preset.content)}
|
||||
</Badge>
|
||||
<Badge
|
||||
className={cn(
|
||||
'border-transparent font-mono text-[10px]',
|
||||
preset.isBuiltIn ? 'bg-emerald-400/15 text-emerald-300' : 'bg-amber-300/15 text-amber-200',
|
||||
)}
|
||||
variant="outline"
|
||||
>
|
||||
{preset.isBuiltIn ? 'built-in' : 'custom'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 line-clamp-3 text-xs leading-relaxed text-zinc-400">{preset.description}</p>
|
||||
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<Button size="sm" onClick={load} className="h-9 gap-1.5 bg-emerald-400 text-zinc-950 hover:bg-emerald-300">
|
||||
<Play className="size-3.5" /> Load
|
||||
</Button>
|
||||
{original && (
|
||||
<Button size="sm" variant="outline" className="h-9 gap-1.5 border-zinc-700" asChild>
|
||||
<a href={original} download>
|
||||
<Download className="size-3.5" /> .avs original
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
{!preset.isBuiltIn && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={confirmingDelete ? 'destructive' : 'outline'}
|
||||
className="ml-auto h-9 gap-1.5 border-zinc-700"
|
||||
disabled={deleting}
|
||||
onClick={() => (confirmingDelete ? void remove() : setConfirmingDelete(true))}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
{confirmingDelete ? 'Confirm?' : 'Delete'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SavePresetSection() {
|
||||
const { toast } = useToast()
|
||||
const scriptText = useAvaStore((s) => s.scriptText)
|
||||
const [name, setName] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
const save = async () => {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) {
|
||||
toast({ title: 'Name required', description: 'Give the preset a name before saving.', variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
const v = validateScript(scriptText)
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/presets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: trimmed,
|
||||
content: scriptText,
|
||||
author: v.meta?.author || 'you',
|
||||
description: v.meta?.description || '',
|
||||
}),
|
||||
})
|
||||
const data = (await res.json().catch(() => null)) as { error?: string; updated?: boolean } | null
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: 'Save failed',
|
||||
description: data?.error ?? `Server responded ${res.status}.`,
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
await refreshPresets()
|
||||
toast({
|
||||
title: data?.updated ? 'Preset updated' : 'Preset saved',
|
||||
description: `"${trimmed}" is available in the list above.`,
|
||||
})
|
||||
setName('')
|
||||
} catch {
|
||||
toast({ title: 'Save failed', description: 'Network error while saving the preset.', variant: 'destructive' })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800/80 bg-zinc-950/40 p-3.5">
|
||||
<h4 className="text-sm font-medium text-zinc-200">Save current editor script as preset</h4>
|
||||
<p className="mt-0.5 text-[11px] text-zinc-500">
|
||||
Saved under the script's editor content — reuse it any time from this list.
|
||||
</p>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Preset name"
|
||||
className="h-9 border-zinc-700 bg-zinc-900 font-mono text-xs"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void save()
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => void save()}
|
||||
disabled={saving}
|
||||
className="h-9 gap-1.5 bg-emerald-400 text-zinc-950 hover:bg-emerald-300"
|
||||
>
|
||||
<Save className="size-3.5" /> Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PresetsTab() {
|
||||
const presets = useAvaStore((s) => s.presets)
|
||||
const setScriptText = useAvaStore((s) => s.setScriptText)
|
||||
const setTab = useAvaStore((s) => s.setTab)
|
||||
|
||||
// freshness refresh whenever the tab mounts (initial seed happens on app load)
|
||||
useEffect(() => {
|
||||
void refreshPresets()
|
||||
}, [])
|
||||
|
||||
const builtIns = presets.filter((p) => p.isBuiltIn)
|
||||
const customs = presets.filter((p) => !p.isBuiltIn)
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-xs text-zinc-500">
|
||||
{presets.length} preset{presets.length === 1 ? '' : 's'} — classics adapted from the original Winamp AVS
|
||||
files.
|
||||
</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-9 gap-1.5 border-zinc-700"
|
||||
onClick={() => {
|
||||
setScriptText(STARTER_TEMPLATE)
|
||||
setTab('script')
|
||||
}}
|
||||
>
|
||||
<FilePlus2 className="size-3.5" /> New Script
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* long-list handling: capped height + styled scrollbar */}
|
||||
<div className={cn('space-y-2.5 pr-1', thinScrollbar, 'max-h-96 overflow-y-auto')}>
|
||||
{builtIns.map((p) => (
|
||||
<PresetCard key={p.id} preset={p} />
|
||||
))}
|
||||
{customs.length > 0 && (
|
||||
<div className="pt-1 text-[10px] font-semibold uppercase tracking-widest text-zinc-600">Custom</div>
|
||||
)}
|
||||
{customs.map((p) => (
|
||||
<PresetCard key={p.id} preset={p} />
|
||||
))}
|
||||
{presets.length === 0 && (
|
||||
<div className="rounded-lg border border-dashed border-zinc-800 p-6 text-center text-xs text-zinc-600">
|
||||
Loading presets…
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SavePresetSection />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
268
src/components/ava/script-tab.tsx
Normal file
268
src/components/ava/script-tab.tsx
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
// AVA — Script tab: the custom visualization script editor.
|
||||
//
|
||||
// Toolbar: Apply, Save as Default, Save to File, Load from File, New, Help.
|
||||
// Editor: line-number gutter + monospace textarea (synced scroll, Tab inserts
|
||||
// two spaces), error lines flagged in the gutter. Status line under the editor
|
||||
// shows compile status or runtime errors.
|
||||
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Check, CircleHelp, Download, FilePlus2, FolderOpen, Play, Save, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { STARTER_TEMPLATE } from '@/lib/ava/presets'
|
||||
import { validateScript } from '@/lib/ava/script'
|
||||
import { useAvaStore, persistDefaultScript } from '@/lib/store'
|
||||
import { applyScriptText } from '@/components/ava/audio-source'
|
||||
import { HelpPanel } from '@/components/ava/help-panel'
|
||||
import { sanitizeFileName } from '@/components/ava/shared'
|
||||
import { useToast } from '@/hooks/use-toast'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function ScriptTab() {
|
||||
const { toast } = useToast()
|
||||
const scriptText = useAvaStore((s) => s.scriptText)
|
||||
const setScriptText = useAvaStore((s) => s.setScriptText)
|
||||
const runtimeError = useAvaStore((s) => s.stats?.error ?? null)
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const gutterRef = useRef<HTMLDivElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const [validation, setValidation] = useState<ReturnType<typeof validateScript> | null>(null)
|
||||
const [helpOpen, setHelpOpen] = useState(false)
|
||||
|
||||
// debounced live validation (compile is cheap, scripts are small)
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setValidation(validateScript(scriptText)), 250)
|
||||
return () => clearTimeout(t)
|
||||
}, [scriptText])
|
||||
|
||||
const errorLine = validation && !validation.ok ? validation.error?.line ?? null : null
|
||||
const lineCount = useMemo(() => scriptText.split('\n').length, [scriptText])
|
||||
|
||||
// evaluate [init] on a scratch env to report the effective point count
|
||||
const initN = useMemo(() => {
|
||||
if (!validation?.ok || !validation.script) return null
|
||||
try {
|
||||
const env: Record<string, number> = { n: 400 }
|
||||
validation.script.initProg?.exec(env)
|
||||
return Math.min(4096, Math.max(4, Math.round(env.n ?? 400)))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}, [validation])
|
||||
|
||||
const apply = () => {
|
||||
const result = applyScriptText(scriptText)
|
||||
if (result.ok) {
|
||||
const v = validateScript(scriptText)
|
||||
toast({
|
||||
title: 'Script applied',
|
||||
description: `mode: ${v.meta?.mode ?? '?'}, n=${initN ?? '?'} — running "${v.meta?.name ?? 'Untitled'}".`,
|
||||
})
|
||||
} else if (result.error) {
|
||||
toast({
|
||||
title: 'Compile error',
|
||||
description: `[${result.error.section}] line ${result.error.line}: ${result.error.message}`,
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const saveAsDefault = () => {
|
||||
persistDefaultScript(scriptText)
|
||||
toast({
|
||||
title: 'Saved as default',
|
||||
description: 'This script loads automatically on your next visit.',
|
||||
})
|
||||
}
|
||||
|
||||
const saveToFile = () => {
|
||||
const meta = validateScript(scriptText).meta
|
||||
const base = sanitizeFileName(meta?.name && meta.name !== 'Untitled' ? meta.name : 'untitled')
|
||||
try {
|
||||
const blob = new Blob([scriptText], { type: 'text/plain;charset=utf-8' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `${base}.ava`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
toast({ title: 'Script exported', description: `${base}.ava downloaded.` })
|
||||
} catch {
|
||||
toast({ title: 'Export failed', description: 'Could not create the download.', variant: 'destructive' })
|
||||
}
|
||||
}
|
||||
|
||||
const loadFromFile = async (file: File) => {
|
||||
try {
|
||||
const text = await file.text()
|
||||
const result = applyScriptText(text)
|
||||
if (result.ok) {
|
||||
const meta = validateScript(text).meta
|
||||
toast({ title: 'Script loaded', description: `"${meta?.name || file.name}" applied to the engine.` })
|
||||
} else if (result.error) {
|
||||
toast({
|
||||
title: 'Loaded with errors',
|
||||
description: `[${result.error.section}] line ${result.error.line}: ${result.error.message} — fix and Apply.`,
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
toast({ title: 'Could not read file', variant: 'destructive' })
|
||||
}
|
||||
}
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key !== 'Tab') return
|
||||
e.preventDefault()
|
||||
const ta = e.currentTarget
|
||||
const start = ta.selectionStart
|
||||
const end = ta.selectionEnd
|
||||
const next = scriptText.slice(0, start) + ' ' + scriptText.slice(end)
|
||||
setScriptText(next)
|
||||
requestAnimationFrame(() => {
|
||||
ta.selectionStart = ta.selectionEnd = start + 2
|
||||
})
|
||||
}
|
||||
|
||||
const syncScroll = (e: React.UIEvent<HTMLTextAreaElement>) => {
|
||||
if (gutterRef.current) gutterRef.current.scrollTop = e.currentTarget.scrollTop
|
||||
}
|
||||
|
||||
const status = (() => {
|
||||
if (validation && !validation.ok && validation.error) {
|
||||
return { ok: false, text: `✘ [${validation.error.section}] line ${validation.error.line}: ${validation.error.message}` }
|
||||
}
|
||||
if (runtimeError) {
|
||||
return { ok: false, text: `✘ runtime: ${runtimeError}` }
|
||||
}
|
||||
if (validation?.ok) {
|
||||
return { ok: true, text: `✔ Compiled OK — mode: ${validation.meta?.mode}, n=${initN ?? 400}` }
|
||||
}
|
||||
return { ok: null, text: '…' }
|
||||
})()
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* toolbar */}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={apply}
|
||||
className="h-9 gap-1.5 bg-emerald-400 px-3 text-zinc-950 hover:bg-emerald-300"
|
||||
title="Validate and apply to the engine"
|
||||
>
|
||||
<Play className="size-3.5" /> Apply
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={saveAsDefault}
|
||||
className="h-9 gap-1.5 border-zinc-700"
|
||||
title="Persist as your default startup script"
|
||||
>
|
||||
<Save className="size-3.5" /> <span className="hidden sm:inline">Save as</span> Default
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={saveToFile}
|
||||
className="h-9 gap-1.5 border-zinc-700"
|
||||
title="Download the script as a .ava file"
|
||||
>
|
||||
<Download className="size-3.5" /> <span className="hidden sm:inline">Save to</span> File
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="h-9 gap-1.5 border-zinc-700"
|
||||
title="Load a .ava script from disk"
|
||||
>
|
||||
<FolderOpen className="size-3.5" /> <span className="hidden sm:inline">Load from</span> File
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setScriptText(STARTER_TEMPLATE)}
|
||||
className="h-9 gap-1.5 border-zinc-700"
|
||||
title="Start over from the template"
|
||||
>
|
||||
<FilePlus2 className="size-3.5" /> New
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={helpOpen ? 'secondary' : 'outline'}
|
||||
onClick={() => setHelpOpen((v) => !v)}
|
||||
className={cn('h-9 gap-1.5 border-zinc-700', helpOpen && 'border-emerald-400/40 text-emerald-300')}
|
||||
title="Variables, functions & file format reference"
|
||||
>
|
||||
<CircleHelp className="size-3.5" /> Help
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* editor with gutter */}
|
||||
<div className="flex overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950 font-mono text-xs">
|
||||
<div
|
||||
ref={gutterRef}
|
||||
aria-hidden
|
||||
className="w-11 shrink-0 select-none overflow-hidden border-r border-zinc-800/70 bg-zinc-900/50 py-2 text-right"
|
||||
>
|
||||
{Array.from({ length: lineCount }, (_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'px-2 leading-5',
|
||||
errorLine === i + 1 ? 'bg-rose-500/15 font-bold text-rose-400' : 'text-zinc-600',
|
||||
)}
|
||||
>
|
||||
{i + 1}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={scriptText}
|
||||
onChange={(e) => setScriptText(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
onScroll={syncScroll}
|
||||
spellCheck={false}
|
||||
wrap="off"
|
||||
aria-label="Visualization script editor"
|
||||
className="min-h-[320px] flex-1 resize-none bg-transparent p-2 font-mono leading-5 text-zinc-200 caret-emerald-400 outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* status line */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-start gap-2 font-mono text-[11px] leading-relaxed',
|
||||
status.ok === false ? 'text-rose-400' : status.ok ? 'text-emerald-400' : 'text-zinc-600',
|
||||
)}
|
||||
role="status"
|
||||
>
|
||||
{status.ok === false ? <X className="mt-0.5 size-3.5 shrink-0" /> : status.ok ? <Check className="mt-0.5 size-3.5 shrink-0" /> : null}
|
||||
<span className="break-all">{status.text}</span>
|
||||
</div>
|
||||
|
||||
{/* help panel */}
|
||||
{helpOpen && <HelpPanel />}
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".ava,.avs,.txt"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) void loadFromFile(file)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
23
src/components/ava/shared.ts
Normal file
23
src/components/ava/shared.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
// AVA — shared UI constants & tiny helpers for the components
|
||||
|
||||
export const thinScrollbar =
|
||||
'[scrollbar-width:thin] [scrollbar-color:#52525b_transparent] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-zinc-700'
|
||||
|
||||
/** 1000 → "1.0 kHz", 100 → "100 Hz" */
|
||||
export function fmtHz(v: number): string {
|
||||
return v >= 1000 ? `${(v / 1000).toFixed(v % 1000 === 0 ? 0 : 1)} kHz` : `${Math.round(v)} Hz`
|
||||
}
|
||||
|
||||
export function clamp01(v: number): number {
|
||||
return Math.min(1, Math.max(0, v))
|
||||
}
|
||||
|
||||
/** Extract the render mode ("lines" | "dots" | "solid") from a script body. */
|
||||
export function modeOfScript(content: string): string {
|
||||
return /^mode:\s*(\w+)/m.exec(content)?.[1] ?? '?'
|
||||
}
|
||||
|
||||
export function sanitizeFileName(name: string): string {
|
||||
const cleaned = name.replace(/[^\w\-. ]+/g, '').trim()
|
||||
return cleaned.length ? cleaned : 'untitled'
|
||||
}
|
||||
139
src/components/ava/visual-stage.tsx
Normal file
139
src/components/ava/visual-stage.tsx
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// AVA — the visualization stage.
|
||||
//
|
||||
// Owns the canvas + the engine render loop (start on mount, stop on unmount),
|
||||
// the idle "select a source" overlay, the tiny FPS/points readout and the
|
||||
// fullscreen toggle. The engine handles DPR + resize via its ResizeObserver on
|
||||
// the canvas parent.
|
||||
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { AudioWaveform, Disc3, FileAudio, Maximize, Mic, Minimize } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { getEngine } from '@/lib/ava/engine'
|
||||
import { useAvaStore } from '@/lib/store'
|
||||
import { useAudioSource } from '@/components/ava/audio-source'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function VisualStage({ className }: { className?: string }) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const source = useAvaStore((s) => s.source)
|
||||
const fps = useAvaStore((s) => s.stats?.fps ?? 0)
|
||||
const points = useAvaStore((s) => s.stats?.points ?? 0)
|
||||
const [isFullscreen, setIsFullscreen] = useState(false)
|
||||
const { startDemo, startMic, startFile } = useAudioSource()
|
||||
|
||||
// engine lifecycle — the one place the render loop is owned
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
const engine = getEngine()
|
||||
engine.start(canvas)
|
||||
engine.onStats = (s) => {
|
||||
useAvaStore.getState().setStats({ ...s, beatCount: engine.beat.getBeatCount() })
|
||||
}
|
||||
return () => {
|
||||
engine.onStats = null
|
||||
engine.stop()
|
||||
}
|
||||
}, [])
|
||||
|
||||
// fullscreen tracking
|
||||
useEffect(() => {
|
||||
const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement))
|
||||
document.addEventListener('fullscreenchange', onChange)
|
||||
return () => document.removeEventListener('fullscreenchange', onChange)
|
||||
}, [])
|
||||
|
||||
const toggleFullscreen = () => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
if (document.fullscreenElement) {
|
||||
void document.exitFullscreen()
|
||||
} else {
|
||||
void el.requestFullscreen().catch(() => {
|
||||
/* denied — ignore */
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn('relative overflow-hidden rounded-xl border border-zinc-800 bg-black', className)}
|
||||
>
|
||||
<canvas ref={canvasRef} className="absolute inset-0 h-full w-full" aria-label="Audio-reactive visualization" />
|
||||
|
||||
{/* top-left micro readout */}
|
||||
<div className="pointer-events-none absolute left-3 top-2.5 z-10 select-none font-mono text-[10px] tabular-nums text-zinc-600">
|
||||
{fps} FPS · {points} PTS
|
||||
</div>
|
||||
|
||||
{/* fullscreen toggle */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleFullscreen}
|
||||
aria-label={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
|
||||
className="absolute right-2 top-2 z-10 size-9 text-zinc-500 hover:bg-zinc-800/70 hover:text-zinc-200"
|
||||
>
|
||||
{isFullscreen ? <Minimize className="size-4" /> : <Maximize className="size-4" />}
|
||||
</Button>
|
||||
|
||||
{/* idle overlay — pick a source */}
|
||||
<AnimatePresence>
|
||||
{source === 'idle' && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.25 }}
|
||||
className="absolute inset-0 z-20 grid place-items-center bg-zinc-950/60 backdrop-blur-sm"
|
||||
>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.96, y: 8 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
transition={{ duration: 0.3, ease: 'easeOut' }}
|
||||
className="mx-4 max-w-sm rounded-2xl border border-zinc-800 bg-zinc-900/70 p-6 text-center shadow-2xl backdrop-blur-md sm:p-8"
|
||||
>
|
||||
<AudioWaveform className="mx-auto mb-3 size-8 text-emerald-400" aria-hidden />
|
||||
<h2 className="text-lg font-semibold">Select an audio source to begin</h2>
|
||||
<p className="mb-5 mt-1 text-xs text-zinc-500">
|
||||
Demo track, live microphone, or your own audio file.
|
||||
</p>
|
||||
<div className="grid gap-2.5">
|
||||
<Button
|
||||
onClick={() => void startDemo()}
|
||||
className="h-12 gap-2 bg-emerald-400 text-zinc-950 hover:bg-emerald-300"
|
||||
>
|
||||
<Disc3 className="size-4" /> Demo Track
|
||||
</Button>
|
||||
<Button onClick={() => void startMic()} variant="secondary" className="h-12 gap-2">
|
||||
<Mic className="size-4" /> Microphone
|
||||
</Button>
|
||||
<Button onClick={() => fileInputRef.current?.click()} variant="secondary" className="h-12 gap-2">
|
||||
<FileAudio className="size-4" /> Audio File
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="audio/*"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) void startFile(file)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
66
src/components/ui/accordion.tsx
Normal file
66
src/components/ui/accordion.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Accordion({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
|
||||
}
|
||||
|
||||
function AccordionItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||
return (
|
||||
<AccordionPrimitive.Item
|
||||
data-slot="accordion-item"
|
||||
className={cn("border-b last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||
return (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
data-slot="accordion-trigger"
|
||||
className={cn(
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||
return (
|
||||
<AccordionPrimitive.Content
|
||||
data-slot="accordion-content"
|
||||
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||
{...props}
|
||||
>
|
||||
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
)
|
||||
}
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||
157
src/components/ui/alert-dialog.tsx
Normal file
157
src/components/ui/alert-dialog.tsx
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function AlertDialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
data-slot="alert-dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Title
|
||||
data-slot="alert-dialog-title"
|
||||
className={cn("text-lg font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Description
|
||||
data-slot="alert-dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogAction({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Action
|
||||
className={cn(buttonVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDialogCancel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
className={cn(buttonVariants({ variant: "outline" }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
}
|
||||
66
src/components/ui/alert.tsx
Normal file
66
src/components/ui/alert.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const alertVariants = cva(
|
||||
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-card text-card-foreground",
|
||||
destructive:
|
||||
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Alert({
|
||||
className,
|
||||
variant,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert"
|
||||
role="alert"
|
||||
className={cn(alertVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-title"
|
||||
className={cn(
|
||||
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-description"
|
||||
className={cn(
|
||||
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription }
|
||||
11
src/components/ui/aspect-ratio.tsx
Normal file
11
src/components/ui/aspect-ratio.tsx
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
"use client"
|
||||
|
||||
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
|
||||
|
||||
function AspectRatio({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
||||
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
|
||||
}
|
||||
|
||||
export { AspectRatio }
|
||||
53
src/components/ui/avatar.tsx
Normal file
53
src/components/ui/avatar.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback }
|
||||
46
src/components/ui/badge.tsx
Normal file
46
src/components/ui/badge.tsx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
109
src/components/ui/breadcrumb.tsx
Normal file
109
src/components/ui/breadcrumb.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
|
||||
}
|
||||
|
||||
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||
return (
|
||||
<ol
|
||||
data-slot="breadcrumb-list"
|
||||
className={cn(
|
||||
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-item"
|
||||
className={cn("inline-flex items-center gap-1.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbLink({
|
||||
asChild,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="breadcrumb-link"
|
||||
className={cn("hover:text-foreground transition-colors", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-page"
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("text-foreground font-normal", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbSeparator({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li
|
||||
data-slot="breadcrumb-separator"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:size-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function BreadcrumbEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-ellipsis"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
}
|
||||
59
src/components/ui/button.tsx
Normal file
59
src/components/ui/button.tsx
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
213
src/components/ui/calendar.tsx
Normal file
213
src/components/ui/calendar.tsx
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString("default", { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"flex gap-4 flex-col md:flex-row relative",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute bg-popover inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"select-none w-(--cell-size)",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] select-none text-muted-foreground",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"rounded-l-md bg-accent",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString()}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
92
src/components/ui/card.tsx
Normal file
92
src/components/ui/card.tsx
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
241
src/components/ui/carousel.tsx
Normal file
241
src/components/ui/carousel.tsx
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import useEmblaCarousel, {
|
||||
type UseEmblaCarouselType,
|
||||
} from "embla-carousel-react"
|
||||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
type CarouselApi = UseEmblaCarouselType[1]
|
||||
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||
type CarouselOptions = UseCarouselParameters[0]
|
||||
type CarouselPlugin = UseCarouselParameters[1]
|
||||
|
||||
type CarouselProps = {
|
||||
opts?: CarouselOptions
|
||||
plugins?: CarouselPlugin
|
||||
orientation?: "horizontal" | "vertical"
|
||||
setApi?: (api: CarouselApi) => void
|
||||
}
|
||||
|
||||
type CarouselContextProps = {
|
||||
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||
scrollPrev: () => void
|
||||
scrollNext: () => void
|
||||
canScrollPrev: boolean
|
||||
canScrollNext: boolean
|
||||
} & CarouselProps
|
||||
|
||||
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||
|
||||
function useCarousel() {
|
||||
const context = React.useContext(CarouselContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useCarousel must be used within a <Carousel />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function Carousel({
|
||||
orientation = "horizontal",
|
||||
opts,
|
||||
setApi,
|
||||
plugins,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & CarouselProps) {
|
||||
const [carouselRef, api] = useEmblaCarousel(
|
||||
{
|
||||
...opts,
|
||||
axis: orientation === "horizontal" ? "x" : "y",
|
||||
},
|
||||
plugins
|
||||
)
|
||||
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||
|
||||
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||
if (!api) return
|
||||
setCanScrollPrev(api.canScrollPrev())
|
||||
setCanScrollNext(api.canScrollNext())
|
||||
}, [])
|
||||
|
||||
const scrollPrev = React.useCallback(() => {
|
||||
api?.scrollPrev()
|
||||
}, [api])
|
||||
|
||||
const scrollNext = React.useCallback(() => {
|
||||
api?.scrollNext()
|
||||
}, [api])
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
scrollPrev()
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
scrollNext()
|
||||
}
|
||||
},
|
||||
[scrollPrev, scrollNext]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api || !setApi) return
|
||||
setApi(api)
|
||||
}, [api, setApi])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
return (
|
||||
<CarouselContext.Provider
|
||||
value={{
|
||||
carouselRef,
|
||||
api: api,
|
||||
opts,
|
||||
orientation:
|
||||
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||
scrollPrev,
|
||||
scrollNext,
|
||||
canScrollPrev,
|
||||
canScrollNext,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onKeyDownCapture={handleKeyDown}
|
||||
className={cn("relative", className)}
|
||||
role="region"
|
||||
aria-roledescription="carousel"
|
||||
data-slot="carousel"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CarouselContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { carouselRef, orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={carouselRef}
|
||||
className="overflow-hidden"
|
||||
data-slot="carousel-content"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex",
|
||||
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
data-slot="carousel-item"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 grow-0 basis-full",
|
||||
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselPrevious({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-previous"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -left-12 -translate-y-1/2"
|
||||
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollPrev}
|
||||
onClick={scrollPrev}
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeft />
|
||||
<span className="sr-only">Previous slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselNext({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-next"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -right-12 -translate-y-1/2"
|
||||
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollNext}
|
||||
onClick={scrollNext}
|
||||
{...props}
|
||||
>
|
||||
<ArrowRight />
|
||||
<span className="sr-only">Next slide</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
type CarouselApi,
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselPrevious,
|
||||
CarouselNext,
|
||||
}
|
||||
353
src/components/ui/chart.tsx
Normal file
353
src/components/ui/chart.tsx
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as RechartsPrimitive from "recharts"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||
const THEMES = { light: "", dark: ".dark" } as const
|
||||
|
||||
export type ChartConfig = {
|
||||
[k in string]: {
|
||||
label?: React.ReactNode
|
||||
icon?: React.ComponentType
|
||||
} & (
|
||||
| { color?: string; theme?: never }
|
||||
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||
)
|
||||
}
|
||||
|
||||
type ChartContextProps = {
|
||||
config: ChartConfig
|
||||
}
|
||||
|
||||
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
||||
|
||||
function useChart() {
|
||||
const context = React.useContext(ChartContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useChart must be used within a <ChartContainer />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function ChartContainer({
|
||||
id,
|
||||
className,
|
||||
children,
|
||||
config,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
config: ChartConfig
|
||||
children: React.ComponentProps<
|
||||
typeof RechartsPrimitive.ResponsiveContainer
|
||||
>["children"]
|
||||
}) {
|
||||
const uniqueId = React.useId()
|
||||
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
|
||||
|
||||
return (
|
||||
<ChartContext.Provider value={{ config }}>
|
||||
<div
|
||||
data-slot="chart"
|
||||
data-chart={chartId}
|
||||
className={cn(
|
||||
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChartStyle id={chartId} config={config} />
|
||||
<RechartsPrimitive.ResponsiveContainer>
|
||||
{children}
|
||||
</RechartsPrimitive.ResponsiveContainer>
|
||||
</div>
|
||||
</ChartContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||
const colorConfig = Object.entries(config).filter(
|
||||
([, config]) => config.theme || config.color
|
||||
)
|
||||
|
||||
if (!colorConfig.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<style
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: Object.entries(THEMES)
|
||||
.map(
|
||||
([theme, prefix]) => `
|
||||
${prefix} [data-chart=${id}] {
|
||||
${colorConfig
|
||||
.map(([key, itemConfig]) => {
|
||||
const color =
|
||||
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
|
||||
itemConfig.color
|
||||
return color ? ` --color-${key}: ${color};` : null
|
||||
})
|
||||
.join("\n")}
|
||||
}
|
||||
`
|
||||
)
|
||||
.join("\n"),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartTooltip = RechartsPrimitive.Tooltip
|
||||
|
||||
function ChartTooltipContent({
|
||||
active,
|
||||
payload,
|
||||
className,
|
||||
indicator = "dot",
|
||||
hideLabel = false,
|
||||
hideIndicator = false,
|
||||
label,
|
||||
labelFormatter,
|
||||
labelClassName,
|
||||
formatter,
|
||||
color,
|
||||
nameKey,
|
||||
labelKey,
|
||||
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||
React.ComponentProps<"div"> & {
|
||||
hideLabel?: boolean
|
||||
hideIndicator?: boolean
|
||||
indicator?: "line" | "dot" | "dashed"
|
||||
nameKey?: string
|
||||
labelKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
const tooltipLabel = React.useMemo(() => {
|
||||
if (hideLabel || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [item] = payload
|
||||
const key = `${labelKey || item?.dataKey || item?.name || "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const value =
|
||||
!labelKey && typeof label === "string"
|
||||
? config[label as keyof typeof config]?.label || label
|
||||
: itemConfig?.label
|
||||
|
||||
if (labelFormatter) {
|
||||
return (
|
||||
<div className={cn("font-medium", labelClassName)}>
|
||||
{labelFormatter(value, payload)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <div className={cn("font-medium", labelClassName)}>{value}</div>
|
||||
}, [
|
||||
label,
|
||||
labelFormatter,
|
||||
payload,
|
||||
hideLabel,
|
||||
labelClassName,
|
||||
config,
|
||||
labelKey,
|
||||
])
|
||||
|
||||
if (!active || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const nestLabel = payload.length === 1 && indicator !== "dot"
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{!nestLabel ? tooltipLabel : null}
|
||||
<div className="grid gap-1.5">
|
||||
{payload.map((item, index) => {
|
||||
const key = `${nameKey || item.name || item.dataKey || "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const indicatorColor = color || item.payload.fill || item.color
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.dataKey}
|
||||
className={cn(
|
||||
"[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
|
||||
indicator === "dot" && "items-center"
|
||||
)}
|
||||
>
|
||||
{formatter && item?.value !== undefined && item.name ? (
|
||||
formatter(item.value, item.name, item, index, item.payload)
|
||||
) : (
|
||||
<>
|
||||
{itemConfig?.icon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
!hideIndicator && (
|
||||
<div
|
||||
className={cn(
|
||||
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
|
||||
{
|
||||
"h-2.5 w-2.5": indicator === "dot",
|
||||
"w-1": indicator === "line",
|
||||
"w-0 border-[1.5px] border-dashed bg-transparent":
|
||||
indicator === "dashed",
|
||||
"my-0.5": nestLabel && indicator === "dashed",
|
||||
}
|
||||
)}
|
||||
style={
|
||||
{
|
||||
"--color-bg": indicatorColor,
|
||||
"--color-border": indicatorColor,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-1 justify-between leading-none",
|
||||
nestLabel ? "items-end" : "items-center"
|
||||
)}
|
||||
>
|
||||
<div className="grid gap-1.5">
|
||||
{nestLabel ? tooltipLabel : null}
|
||||
<span className="text-muted-foreground">
|
||||
{itemConfig?.label || item.name}
|
||||
</span>
|
||||
</div>
|
||||
{item.value && (
|
||||
<span className="text-foreground font-mono font-medium tabular-nums">
|
||||
{item.value.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartLegend = RechartsPrimitive.Legend
|
||||
|
||||
function ChartLegendContent({
|
||||
className,
|
||||
hideIcon = false,
|
||||
payload,
|
||||
verticalAlign = "bottom",
|
||||
nameKey,
|
||||
}: React.ComponentProps<"div"> &
|
||||
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
|
||||
hideIcon?: boolean
|
||||
nameKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
if (!payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-4",
|
||||
verticalAlign === "top" ? "pb-3" : "pt-3",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{payload.map((item) => {
|
||||
const key = `${nameKey || item.dataKey || "value"}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.value}
|
||||
className={cn(
|
||||
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
|
||||
)}
|
||||
>
|
||||
{itemConfig?.icon && !hideIcon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
<div
|
||||
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||
style={{
|
||||
backgroundColor: item.color,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{itemConfig?.label}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to extract item config from a payload.
|
||||
function getPayloadConfigFromPayload(
|
||||
config: ChartConfig,
|
||||
payload: unknown,
|
||||
key: string
|
||||
) {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const payloadPayload =
|
||||
"payload" in payload &&
|
||||
typeof payload.payload === "object" &&
|
||||
payload.payload !== null
|
||||
? payload.payload
|
||||
: undefined
|
||||
|
||||
let configLabelKey: string = key
|
||||
|
||||
if (
|
||||
key in payload &&
|
||||
typeof payload[key as keyof typeof payload] === "string"
|
||||
) {
|
||||
configLabelKey = payload[key as keyof typeof payload] as string
|
||||
} else if (
|
||||
payloadPayload &&
|
||||
key in payloadPayload &&
|
||||
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
|
||||
) {
|
||||
configLabelKey = payloadPayload[
|
||||
key as keyof typeof payloadPayload
|
||||
] as string
|
||||
}
|
||||
|
||||
return configLabelKey in config
|
||||
? config[configLabelKey]
|
||||
: config[key as keyof typeof config]
|
||||
}
|
||||
|
||||
export {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
ChartLegend,
|
||||
ChartLegendContent,
|
||||
ChartStyle,
|
||||
}
|
||||
32
src/components/ui/checkbox.tsx
Normal file
32
src/components/ui/checkbox.tsx
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
33
src/components/ui/collapsible.tsx
Normal file
33
src/components/ui/collapsible.tsx
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
"use client"
|
||||
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
184
src/components/ui/command.tsx
Normal file
184
src/components/ui/command.tsx
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
import { SearchIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
function Command({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
return (
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = "Command Palette",
|
||||
description = "Search for a command to run...",
|
||||
children,
|
||||
className,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string
|
||||
description?: string
|
||||
className?: string
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogContent
|
||||
className={cn("overflow-hidden p-0", className)}
|
||||
showCloseButton={showCloseButton}
|
||||
>
|
||||
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandInput({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="command-input-wrapper"
|
||||
className="flex h-9 items-center gap-2 border-b px-3"
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
data-slot="command-input"
|
||||
className={cn(
|
||||
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.List>) {
|
||||
return (
|
||||
<CommandPrimitive.List
|
||||
data-slot="command-list"
|
||||
className={cn(
|
||||
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandEmpty({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return (
|
||||
<CommandPrimitive.Empty
|
||||
data-slot="command-empty"
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
return (
|
||||
<CommandPrimitive.Group
|
||||
data-slot="command-group"
|
||||
className={cn(
|
||||
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return (
|
||||
<CommandPrimitive.Separator
|
||||
data-slot="command-separator"
|
||||
className={cn("bg-border -mx-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<CommandPrimitive.Item
|
||||
data-slot="command-item"
|
||||
className={cn(
|
||||
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="command-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
252
src/components/ui/context-menu.tsx
Normal file
252
src/components/ui/context-menu.tsx
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
143
src/components/ui/dialog.tsx
Normal file
143
src/components/ui/dialog.tsx
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
135
src/components/ui/drawer.tsx
Normal file
135
src/components/ui/drawer.tsx
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Drawer as DrawerPrimitive } from "vaul"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Drawer({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
|
||||
}
|
||||
|
||||
function DrawerTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DrawerPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
||||
}
|
||||
|
||||
function DrawerClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
||||
}
|
||||
|
||||
function DrawerOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||
return (
|
||||
<DrawerPrimitive.Overlay
|
||||
data-slot="drawer-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
||||
return (
|
||||
<DrawerPortal data-slot="drawer-portal">
|
||||
<DrawerOverlay />
|
||||
<DrawerPrimitive.Content
|
||||
data-slot="drawer-content"
|
||||
className={cn(
|
||||
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
|
||||
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
||||
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
||||
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-header"
|
||||
className={cn(
|
||||
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
||||
return (
|
||||
<DrawerPrimitive.Title
|
||||
data-slot="drawer-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
||||
return (
|
||||
<DrawerPrimitive.Description
|
||||
data-slot="drawer-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Drawer,
|
||||
DrawerPortal,
|
||||
DrawerOverlay,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerFooter,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
}
|
||||
257
src/components/ui/dropdown-menu.tsx
Normal file
257
src/components/ui/dropdown-menu.tsx
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
167
src/components/ui/form.tsx
Normal file
167
src/components/ui/form.tsx
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
44
src/components/ui/hover-card.tsx
Normal file
44
src/components/ui/hover-card.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function HoverCard({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
|
||||
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
|
||||
}
|
||||
|
||||
function HoverCardTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
|
||||
return (
|
||||
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function HoverCardContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
|
||||
return (
|
||||
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
|
||||
<HoverCardPrimitive.Content
|
||||
data-slot="hover-card-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</HoverCardPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { HoverCard, HoverCardTrigger, HoverCardContent }
|
||||
77
src/components/ui/input-otp.tsx
Normal file
77
src/components/ui/input-otp.tsx
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { OTPInput, OTPInputContext } from "input-otp"
|
||||
import { MinusIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function InputOTP({
|
||||
className,
|
||||
containerClassName,
|
||||
...props
|
||||
}: React.ComponentProps<typeof OTPInput> & {
|
||||
containerClassName?: string
|
||||
}) {
|
||||
return (
|
||||
<OTPInput
|
||||
data-slot="input-otp"
|
||||
containerClassName={cn(
|
||||
"flex items-center gap-2 has-disabled:opacity-50",
|
||||
containerClassName
|
||||
)}
|
||||
className={cn("disabled:cursor-not-allowed", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="input-otp-group"
|
||||
className={cn("flex items-center", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPSlot({
|
||||
index,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
index: number
|
||||
}) {
|
||||
const inputOTPContext = React.useContext(OTPInputContext)
|
||||
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="input-otp-slot"
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{char}
|
||||
{hasFakeCaret && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div data-slot="input-otp-separator" role="separator" {...props}>
|
||||
<MinusIcon />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
|
||||
21
src/components/ui/input.tsx
Normal file
21
src/components/ui/input.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
24
src/components/ui/label.tsx
Normal file
24
src/components/ui/label.tsx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
276
src/components/ui/menubar.tsx
Normal file
276
src/components/ui/menubar.tsx
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as MenubarPrimitive from "@radix-ui/react-menubar"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Menubar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
|
||||
return (
|
||||
<MenubarPrimitive.Root
|
||||
data-slot="menubar"
|
||||
className={cn(
|
||||
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
|
||||
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
|
||||
}
|
||||
|
||||
function MenubarGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
|
||||
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
|
||||
}
|
||||
|
||||
function MenubarPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
|
||||
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
|
||||
}
|
||||
|
||||
function MenubarRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
|
||||
return (
|
||||
<MenubarPrimitive.Trigger
|
||||
data-slot="menubar-trigger"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarContent({
|
||||
className,
|
||||
align = "start",
|
||||
alignOffset = -4,
|
||||
sideOffset = 8,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
|
||||
return (
|
||||
<MenubarPortal>
|
||||
<MenubarPrimitive.Content
|
||||
data-slot="menubar-content"
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</MenubarPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Item
|
||||
data-slot="menubar-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.CheckboxItem
|
||||
data-slot="menubar-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioItem
|
||||
data-slot="menubar-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Label
|
||||
data-slot="menubar-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
|
||||
return (
|
||||
<MenubarPrimitive.Separator
|
||||
data-slot="menubar-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="menubar-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
|
||||
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
|
||||
}
|
||||
|
||||
function MenubarSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.SubTrigger
|
||||
data-slot="menubar-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto h-4 w-4" />
|
||||
</MenubarPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function MenubarSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
|
||||
return (
|
||||
<MenubarPrimitive.SubContent
|
||||
data-slot="menubar-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Menubar,
|
||||
MenubarPortal,
|
||||
MenubarMenu,
|
||||
MenubarTrigger,
|
||||
MenubarContent,
|
||||
MenubarGroup,
|
||||
MenubarSeparator,
|
||||
MenubarLabel,
|
||||
MenubarItem,
|
||||
MenubarShortcut,
|
||||
MenubarCheckboxItem,
|
||||
MenubarRadioGroup,
|
||||
MenubarRadioItem,
|
||||
MenubarSub,
|
||||
MenubarSubTrigger,
|
||||
MenubarSubContent,
|
||||
}
|
||||
168
src/components/ui/navigation-menu.tsx
Normal file
168
src/components/ui/navigation-menu.tsx
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import * as React from "react"
|
||||
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { ChevronDownIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function NavigationMenu({
|
||||
className,
|
||||
children,
|
||||
viewport = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
|
||||
viewport?: boolean
|
||||
}) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Root
|
||||
data-slot="navigation-menu"
|
||||
data-viewport={viewport}
|
||||
className={cn(
|
||||
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{viewport && <NavigationMenuViewport />}
|
||||
</NavigationMenuPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.List
|
||||
data-slot="navigation-menu-list"
|
||||
className={cn(
|
||||
"group flex flex-1 list-none items-center justify-center gap-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Item
|
||||
data-slot="navigation-menu-item"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const navigationMenuTriggerStyle = cva(
|
||||
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
)
|
||||
|
||||
function NavigationMenuTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Trigger
|
||||
data-slot="navigation-menu-trigger"
|
||||
className={cn(navigationMenuTriggerStyle(), "group", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}{" "}
|
||||
<ChevronDownIcon
|
||||
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</NavigationMenuPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Content
|
||||
data-slot="navigation-menu-content"
|
||||
className={cn(
|
||||
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
|
||||
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuViewport({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute top-full left-0 isolate z-50 flex justify-center"
|
||||
)}
|
||||
>
|
||||
<NavigationMenuPrimitive.Viewport
|
||||
data-slot="navigation-menu-viewport"
|
||||
className={cn(
|
||||
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuLink({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Link
|
||||
data-slot="navigation-menu-link"
|
||||
className={cn(
|
||||
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NavigationMenuIndicator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
|
||||
return (
|
||||
<NavigationMenuPrimitive.Indicator
|
||||
data-slot="navigation-menu-indicator"
|
||||
className={cn(
|
||||
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
|
||||
</NavigationMenuPrimitive.Indicator>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
NavigationMenu,
|
||||
NavigationMenuList,
|
||||
NavigationMenuItem,
|
||||
NavigationMenuContent,
|
||||
NavigationMenuTrigger,
|
||||
NavigationMenuLink,
|
||||
NavigationMenuIndicator,
|
||||
NavigationMenuViewport,
|
||||
navigationMenuTriggerStyle,
|
||||
}
|
||||
127
src/components/ui/pagination.tsx
Normal file
127
src/components/ui/pagination.tsx
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import * as React from "react"
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
MoreHorizontalIcon,
|
||||
} from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
|
||||
return (
|
||||
<nav
|
||||
role="navigation"
|
||||
aria-label="pagination"
|
||||
data-slot="pagination"
|
||||
className={cn("mx-auto flex w-full justify-center", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"ul">) {
|
||||
return (
|
||||
<ul
|
||||
data-slot="pagination-content"
|
||||
className={cn("flex flex-row items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
|
||||
return <li data-slot="pagination-item" {...props} />
|
||||
}
|
||||
|
||||
type PaginationLinkProps = {
|
||||
isActive?: boolean
|
||||
} & Pick<React.ComponentProps<typeof Button>, "size"> &
|
||||
React.ComponentProps<"a">
|
||||
|
||||
function PaginationLink({
|
||||
className,
|
||||
isActive,
|
||||
size = "icon",
|
||||
...props
|
||||
}: PaginationLinkProps) {
|
||||
return (
|
||||
<a
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
data-slot="pagination-link"
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
buttonVariants({
|
||||
variant: isActive ? "outline" : "ghost",
|
||||
size,
|
||||
}),
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationPrevious({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PaginationLink>) {
|
||||
return (
|
||||
<PaginationLink
|
||||
aria-label="Go to previous page"
|
||||
size="default"
|
||||
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
<span className="hidden sm:block">Previous</span>
|
||||
</PaginationLink>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationNext({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PaginationLink>) {
|
||||
return (
|
||||
<PaginationLink
|
||||
aria-label="Go to next page"
|
||||
size="default"
|
||||
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
|
||||
{...props}
|
||||
>
|
||||
<span className="hidden sm:block">Next</span>
|
||||
<ChevronRightIcon />
|
||||
</PaginationLink>
|
||||
)
|
||||
}
|
||||
|
||||
function PaginationEllipsis({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
data-slot="pagination-ellipsis"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontalIcon className="size-4" />
|
||||
<span className="sr-only">More pages</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationLink,
|
||||
PaginationItem,
|
||||
PaginationPrevious,
|
||||
PaginationNext,
|
||||
PaginationEllipsis,
|
||||
}
|
||||
48
src/components/ui/popover.tsx
Normal file
48
src/components/ui/popover.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
31
src/components/ui/progress.tsx
Normal file
31
src/components/ui/progress.tsx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ProgressPrimitive from "@radix-ui/react-progress"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
value,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
data-slot="progress"
|
||||
className={cn(
|
||||
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className="bg-primary h-full w-full flex-1 transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Progress }
|
||||
45
src/components/ui/radio-group.tsx
Normal file
45
src/components/ui/radio-group.tsx
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
|
||||
import { CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function RadioGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Root
|
||||
data-slot="radio-group"
|
||||
className={cn("grid gap-3", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function RadioGroupItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Item
|
||||
data-slot="radio-group-item"
|
||||
className={cn(
|
||||
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<RadioGroupPrimitive.Indicator
|
||||
data-slot="radio-group-indicator"
|
||||
className="relative flex items-center justify-center"
|
||||
>
|
||||
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
|
||||
</RadioGroupPrimitive.Indicator>
|
||||
</RadioGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { RadioGroup, RadioGroupItem }
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue