adding validated services? patching forcad_local.py

This commit is contained in:
Your Name
2026-08-13 08:32:35 +07:00
parent d485f61169
commit e795614e45
1459 changed files with 420036 additions and 436 deletions

View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -0,0 +1,23 @@
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import { globalIgnores } from "eslint/config";
export default tseslint.config([
globalIgnores(["dist"]),
{
files: ["**/*.{ts,tsx}"],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs["recommended-latest"],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
]);

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PolyPhonia - Mix Tones, Create Magic</title>
</head>
<body class="dark">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,42 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --host",
"dev:local": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview --host"
},
"dependencies": {
"@headlessui/react": "^2.2.7",
"@heroicons/react": "^2.2.0",
"@tonejs/midi": "^2.0.28",
"autoprefixer": "^10.4.21",
"axios": "^1.11.0",
"framer-motion": "^12.23.12",
"postcss": "^8.5.6",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-hot-toast": "^2.6.0",
"react-router-dom": "^7.8.1",
"tailwindcss": "^3.4.17",
"tone": "^15.1.22",
"zustand": "^5.0.7"
},
"devDependencies": {
"@eslint/js": "^9.33.0",
"@types/react": "^19.1.10",
"@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^5.0.0",
"eslint": "^9.33.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.39.1",
"vite": "^6.3.5"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,74 @@
import { useEffect, useState } from "react";
import {
BrowserRouter as Router,
Routes,
Route,
Navigate,
} from "react-router-dom";
import { Toaster } from "react-hot-toast";
import { useAuthStore } from "./store/authStore";
import AuthPage from "./pages/AuthPage";
import ToneLibraryPage from "./pages/ToneLibraryPage";
import ToneCreatorPage from "./pages/ToneCreatorPage";
function App() {
const [isLoading, setIsLoading] = useState(true);
const { isAuthenticated, checkAuth } = useAuthStore();
useEffect(() => {
checkAuth().finally(() => setIsLoading(false));
}, []);
if (isLoading) {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="text-white text-xl">Loading PolyPhonia...</div>
</div>
);
}
return (
<Router>
<Toaster
position="top-right"
toastOptions={{
duration: 4000,
style: {
background: "#1f2937",
color: "#fff",
border: "1px solid #374151",
},
success: {
iconTheme: {
primary: "#10b981",
secondary: "#fff",
},
},
error: {
iconTheme: {
primary: "#ef4444",
secondary: "#fff",
},
},
}}
/>
<Routes>
<Route
path="/"
element={isAuthenticated ? <Navigate to="/library" /> : <AuthPage />}
/>
<Route
path="/library"
element={isAuthenticated ? <ToneLibraryPage /> : <Navigate to="/" />}
/>
<Route
path="/tone-creator"
element={isAuthenticated ? <ToneCreatorPage /> : <Navigate to="/" />}
/>
</Routes>
</Router>
);
}
export default App;

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,93 @@
import { useState } from "react";
import { motion } from "framer-motion";
import { LockClosedIcon, UserIcon } from "@heroicons/react/24/outline";
import { useAuthStore } from "../../store/authStore";
import toast from "react-hot-toast";
interface LoginFormProps {
onSuccess?: () => void;
}
export default function LoginForm({ onSuccess }: LoginFormProps) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const { login, isLoading } = useAuthStore();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await login(username, password);
toast.success("Welcome back!");
onSuccess?.();
} catch (error: any) {
toast.error(error.response?.data?.error || "Login failed");
}
};
return (
<motion.form
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
onSubmit={handleSubmit}
className="space-y-6"
>
<div>
<label
htmlFor="username"
className="block text-sm font-medium text-gray-300 mb-2"
>
Username
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<UserIcon className="h-5 w-5 text-gray-400" />
</div>
<input
id="username"
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="block w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all"
placeholder="Enter your username"
/>
</div>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-gray-300 mb-2"
>
Password
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<LockClosedIcon className="h-5 w-5 text-gray-400" />
</div>
<input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="block w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all"
placeholder="Enter your password"
/>
</div>
</div>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
type="submit"
disabled={isLoading}
className="w-full flex justify-center py-3 px-4 rounded-lg text-white bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-600 hover:to-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 font-medium shadow-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
{isLoading ? "Signing in..." : "Sign In"}
</motion.button>
</motion.form>
);
}

View File

@@ -0,0 +1,126 @@
import { useState } from "react";
import { motion } from "framer-motion";
import {
LockClosedIcon,
UserIcon,
ShieldCheckIcon,
} from "@heroicons/react/24/outline";
import { useAuthStore } from "../../store/authStore";
import toast from "react-hot-toast";
interface RegisterFormProps {
onSuccess?: () => void;
}
export default function RegisterForm({ onSuccess }: RegisterFormProps) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const { register, isLoading } = useAuthStore();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (password !== confirmPassword) {
toast.error("Passwords do not match");
return;
}
try {
await register(username, password);
toast.success("Registration successful! Please login.");
onSuccess?.();
} catch (error: any) {
toast.error(error.response?.data?.error || "Registration failed");
}
};
return (
<motion.form
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
onSubmit={handleSubmit}
className="space-y-6"
>
<div>
<label
htmlFor="reg-username"
className="block text-sm font-medium text-gray-300 mb-2"
>
Username
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<UserIcon className="h-5 w-5 text-gray-400" />
</div>
<input
id="reg-username"
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="block w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all"
placeholder="Choose a username"
/>
</div>
</div>
<div>
<label
htmlFor="reg-password"
className="block text-sm font-medium text-gray-300 mb-2"
>
Password
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<LockClosedIcon className="h-5 w-5 text-gray-400" />
</div>
<input
id="reg-password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="block w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all"
placeholder="Create a password"
/>
</div>
</div>
<div>
<label
htmlFor="confirm-password"
className="block text-sm font-medium text-gray-300 mb-2"
>
Confirm Password
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<ShieldCheckIcon className="h-5 w-5 text-gray-400" />
</div>
<input
id="confirm-password"
type="password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="block w-full pl-10 pr-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all"
placeholder="Confirm your password"
/>
</div>
</div>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
type="submit"
disabled={isLoading}
className="w-full flex justify-center py-3 px-4 rounded-lg text-white bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 font-medium shadow-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
{isLoading ? "Creating account..." : "Create Account"}
</motion.button>
</motion.form>
);
}

View File

@@ -0,0 +1,399 @@
import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import {
BookOpenIcon,
TrashIcon,
PlusIcon,
PencilSquareIcon,
} from "@heroicons/react/24/outline";
import { useNavigate } from "react-router-dom";
import { useToneStore, generateNotes } from "../../store/toneStore";
import axios from "axios";
import toast from "react-hot-toast";
interface ToneLibraryProps {
onSavedMelodiesChange?: (hasMelodies: boolean) => void;
}
interface SavedMelody {
id: number;
name: string;
description: string;
toneSequences: {
id: number;
baseNote: number;
intervalType: string;
chordType: string;
tempo: number;
duration: number;
notes: number[];
}[];
createdAt: string;
updatedAt: string;
}
type ApiMelody = Omit<SavedMelody, "toneSequences"> & {
toneSequences?: unknown;
};
const ensureNumber = (value: unknown, fallback = 0): number => {
const parsed =
typeof value === "string" && value.trim() === "" ? NaN : Number(value);
return Number.isFinite(parsed) ? parsed : fallback;
};
const sanitizeNotesArray = (notes: unknown[]): number[] =>
notes
.map((note) => ensureNumber(note, NaN))
.filter((note): note is number => Number.isFinite(note));
const parseNotes = (rawNotes: unknown): number[] => {
if (Array.isArray(rawNotes)) {
return sanitizeNotesArray(rawNotes);
}
if (typeof rawNotes === "string") {
const trimmed = rawNotes.trim();
if (!trimmed) return [];
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
return sanitizeNotesArray(parsed);
}
} catch (error) {
// Ignore JSON parse errors and fall back to manual parsing
}
const normalized = trimmed.replace(/^[\[{]|[\]}]$/g, "");
if (!normalized) return [];
return sanitizeNotesArray(normalized.split(","));
}
return [];
};
const readStringField = (
source: Record<string, unknown>,
keys: string[],
fallback: string,
): string => {
for (const key of keys) {
const value = source[key];
if (typeof value === "string") {
const trimmed = value.trim();
if (trimmed) {
return trimmed;
}
}
}
return fallback;
};
const readNumberField = (
source: Record<string, unknown>,
keys: string[],
): number | null => {
for (const key of keys) {
if (key in source) {
const value = ensureNumber(source[key], NaN);
if (Number.isFinite(value)) {
return value;
}
}
}
return null;
};
const parseToneSequences = (
rawToneSequences: unknown,
): SavedMelody["toneSequences"] => {
let sequencesSource: unknown[] = [];
if (Array.isArray(rawToneSequences)) {
sequencesSource = rawToneSequences;
} else if (
rawToneSequences &&
typeof rawToneSequences === "object" &&
!Array.isArray(rawToneSequences)
) {
sequencesSource = Object.values(
rawToneSequences as Record<string, unknown>,
);
} else if (typeof rawToneSequences === "string") {
const trimmed = rawToneSequences.trim();
if (trimmed) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
sequencesSource = parsed;
} else if (parsed && typeof parsed === "object") {
sequencesSource = Object.values(parsed as Record<string, unknown>);
}
} catch (error) {
sequencesSource = [];
}
}
}
return sequencesSource
.map((sequence) => {
if (!sequence || typeof sequence !== "object") {
return null;
}
const typedSequence = sequence as Record<string, unknown>;
const parsedId =
readNumberField(typedSequence, ["id", "sequenceId", "sequence_id"]) ??
NaN;
const baseNote = readNumberField(typedSequence, [
"baseNote",
"base_note",
"rootNote",
"root_note",
]);
if (baseNote === null) {
return null;
}
const intervalType = readStringField(
typedSequence,
["intervalType", "interval_type"],
"unison",
);
const chordType = readStringField(
typedSequence,
["chordType", "chord_type"],
"none",
);
const tempo = readNumberField(typedSequence, ["tempo", "bpm"]) ?? 120;
const duration =
readNumberField(typedSequence, ["duration", "length", "beats"]) ?? 4;
const rawNotes =
typedSequence.notes ??
typedSequence.noteValues ??
typedSequence.note_values ??
typedSequence.notesArray ??
typedSequence.notes_array;
const parsedNotes = parseNotes(rawNotes);
const notes =
parsedNotes.length > 0
? parsedNotes
: generateNotes(baseNote, intervalType, chordType);
return {
id: Number.isFinite(parsedId) ? parsedId : Date.now() + Math.random(),
baseNote,
intervalType,
chordType,
tempo,
duration,
notes,
};
})
.filter((sequence): sequence is SavedMelody["toneSequences"][number] =>
Boolean(sequence),
);
};
export default function ToneLibrary({
onSavedMelodiesChange,
}: ToneLibraryProps = {}) {
const [savedMelodies, setSavedMelodies] = useState<SavedMelody[]>([]);
const [isLoading, setIsLoading] = useState(false);
const { clearAll, addTone, setCurrentMelody } = useToneStore();
const navigate = useNavigate();
// Load user's melody library
const loadLibrary = async () => {
setIsLoading(true);
try {
const response = await axios.get("/api/melodies", {
withCredentials: true,
});
const rawMelodies: ApiMelody[] = response.data.melodies || [];
const melodies = rawMelodies.map((melody) => ({
...melody,
toneSequences: parseToneSequences(melody.toneSequences),
}));
setSavedMelodies(melodies);
onSavedMelodiesChange?.(melodies.length > 0);
} catch (error) {
console.error("Failed to load melody library:", error);
toast.error("Failed to load melody library");
onSavedMelodiesChange?.(false);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadLibrary();
}, []);
// Load melody from library
const handleLoadMelody = async (savedMelody: SavedMelody) => {
// Clear existing tones and load the saved melody
clearAll();
// Set current melody info for updating
setCurrentMelody({
id: savedMelody.id,
name: savedMelody.name,
description: savedMelody.description,
});
for (const tone of savedMelody.toneSequences) {
if (
!Number.isFinite(tone.baseNote) ||
!Number.isFinite(tone.tempo) ||
!Number.isFinite(tone.duration)
) {
continue;
}
addTone({
baseNote: tone.baseNote,
intervalType: tone.intervalType,
chordType: tone.chordType,
tempo: tone.tempo,
duration: tone.duration,
});
// Small delay to ensure unique IDs
await new Promise((resolve) => setTimeout(resolve, 5));
}
toast.success(`Loaded "${savedMelody.name}"`);
navigate("/tone-creator");
};
// Delete melody from library
const handleDeleteMelody = async (id: number, name: string) => {
if (!confirm(`Are you sure you want to delete "${name}"?`)) return;
try {
const response = await axios.delete(`/api/melodies/${id}`, {
withCredentials: true,
});
if (response.data.success) {
toast.success("Melody deleted");
loadLibrary();
}
} catch (error) {
toast.error("Failed to delete melody");
console.error(error);
}
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay: 0.2 }}
className="bg-gray-800/50 backdrop-blur-lg rounded-xl p-6 border border-gray-700"
>
<div className="flex items-center justify-between mb-4">
<div className="flex items-center">
<BookOpenIcon className="h-6 w-6 text-primary-400 mr-2" />
<h3 className="text-lg font-semibold text-white">Your Melodies</h3>
</div>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={() => {
clearAll();
navigate("/tone-creator");
}}
className="flex items-center px-3 py-1.5 rounded-lg bg-primary-500 hover:bg-primary-600 text-white text-sm font-medium transition-colors"
>
<PlusIcon className="h-4 w-4 mr-1" />
New Melody
</motion.button>
</div>
{/* Saved Melodies List */}
<div className="space-y-2 max-h-96 overflow-y-auto">
{isLoading ? (
<div className="text-center py-8 text-gray-400">
Loading library...
</div>
) : savedMelodies.length === 0 ? (
<div className="text-center py-8 text-gray-400">
<BookOpenIcon className="h-12 w-12 mx-auto mb-2 opacity-50" />
<p>Your melody library is empty</p>
<p className="text-sm mt-1">
Save your musical creations to build your library!
</p>
</div>
) : (
savedMelodies.map((melody) => (
<motion.div
key={melody.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
className="p-3 bg-gray-900/50 rounded-lg border border-gray-700 hover:border-primary-500/50 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex-1">
<h4 className="text-white font-medium">{melody.name}</h4>
{melody.description && (
<p className="text-gray-400 text-sm mt-1">
{melody.description}
</p>
)}
<div className="flex flex-wrap gap-2 mt-2">
<span className="text-xs px-2 py-1 bg-gray-700 rounded text-gray-300">
{melody.toneSequences.length} sequence
{melody.toneSequences.length !== 1 ? "s" : ""}
</span>
<span className="text-xs px-2 py-1 bg-gray-700 rounded text-gray-300">
{melody.toneSequences.reduce(
(acc, t) => acc + t.notes.length,
0,
)}{" "}
notes
</span>
<span className="text-xs px-2 py-1 bg-gray-700 rounded text-gray-300">
{melody.toneSequences.reduce(
(acc, t) => acc + t.duration,
0,
)}{" "}
beats
</span>
</div>
</div>
<div className="flex gap-1 ml-2">
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
onClick={() => handleLoadMelody(melody)}
className="p-2 rounded-lg bg-green-500/20 hover:bg-green-500/30 text-green-400 transition-colors"
title="Edit melody"
>
<PencilSquareIcon className="h-4 w-4" />
</motion.button>
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
onClick={() => handleDeleteMelody(melody.id, melody.name)}
className="p-2 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-red-400 transition-colors"
title="Delete melody"
>
<TrashIcon className="h-4 w-4" />
</motion.button>
</div>
</div>
</motion.div>
))
)}
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,72 @@
import { useState } from "react";
import { motion } from "framer-motion";
import { PlayIcon, StopIcon } from "@heroicons/react/24/outline";
import { useToneStore } from "../../store/toneStore";
import toast from "react-hot-toast";
export default function PlaybackControls() {
const { toneSequences, initAudioContext, playNote } = useToneStore();
const [isPlaying, setIsPlaying] = useState(false);
const handlePlay = () => {
if (toneSequences.length === 0) {
toast.error("Add some tone sequences first!");
return;
}
initAudioContext();
setIsPlaying(true);
let totalDelay = 0;
toneSequences.forEach((tone) => {
setTimeout(() => {
tone.notes.forEach((note) => {
playNote(note, tone.duration);
});
}, totalDelay);
totalDelay += tone.duration * 500; // Convert beats to milliseconds
});
setTimeout(() => {
setIsPlaying(false);
}, totalDelay);
};
const handleStop = () => {
setIsPlaying(false);
// In a real implementation, we'd need to stop the audio context
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay: 0.3 }}
className="bg-gray-800/50 backdrop-blur-lg rounded-xl p-6 border border-gray-700"
>
<h3 className="text-lg font-semibold text-white mb-4">Playback</h3>
<div className="space-y-4">
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={isPlaying ? handleStop : handlePlay}
disabled={toneSequences.length === 0}
className="w-full flex items-center justify-center py-3 px-4 rounded-lg text-white bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 font-medium shadow-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
{isPlaying ? (
<>
<StopIcon className="h-5 w-5 mr-2" />
Stop
</>
) : (
<>
<PlayIcon className="h-5 w-5 mr-2" />
Play
</>
)}
</motion.button>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,169 @@
import { useState } from "react";
import { motion } from "framer-motion";
import { PlusIcon, MusicalNoteIcon } from "@heroicons/react/24/outline";
import { useToneStore } from "../../store/toneStore";
import toast from "react-hot-toast";
const notes = [
{ value: 60, label: "C4 (Middle C)" },
{ value: 62, label: "D4" },
{ value: 64, label: "E4" },
{ value: 65, label: "F4" },
{ value: 67, label: "G4" },
{ value: 69, label: "A4" },
{ value: 71, label: "B4" },
{ value: 72, label: "C5" },
];
const intervals = [
{ value: "unison", label: "Unison" },
{ value: "minor2", label: "Minor 2nd" },
{ value: "major2", label: "Major 2nd" },
{ value: "minor3", label: "Minor 3rd" },
{ value: "major3", label: "Major 3rd" },
{ value: "perfect4", label: "Perfect 4th" },
{ value: "tritone", label: "Tritone" },
{ value: "perfect5", label: "Perfect 5th" },
{ value: "minor6", label: "Minor 6th" },
{ value: "major6", label: "Major 6th" },
{ value: "minor7", label: "Minor 7th" },
{ value: "major7", label: "Major 7th" },
{ value: "octave", label: "Octave" },
];
const chordTypes = [
{ value: "none", label: "None" },
{ value: "major", label: "Major Triad" },
{ value: "minor", label: "Minor Triad" },
{ value: "diminished", label: "Diminished" },
{ value: "augmented", label: "Augmented" },
{ value: "maj7", label: "Major 7th" },
{ value: "min7", label: "Minor 7th" },
{ value: "dom7", label: "Dominant 7th" },
];
export default function ToneControls() {
const [baseNote, setBaseNote] = useState(60);
const [intervalType, setIntervalType] = useState("unison");
const [chordType, setChordType] = useState("none");
const [tempo, setTempo] = useState(120);
const [duration, setDuration] = useState(4);
const addTone = useToneStore((state) => state.addTone);
const handleAddTone = () => {
addTone({
baseNote,
intervalType,
chordType,
tempo,
duration,
});
toast.success("Tone sequence added!");
};
return (
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5 }}
className="bg-gray-800/50 backdrop-blur-lg rounded-xl p-6 border border-gray-700"
>
<div className="flex items-center mb-6">
<MusicalNoteIcon className="h-6 w-6 text-primary-500 mr-2" />
<h2 className="text-xl font-bold text-white">Tone Controls</h2>
</div>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Base Note
</label>
<select
value={baseNote}
onChange={(e) => setBaseNote(Number(e.target.value))}
className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
>
{notes.map((note) => (
<option key={note.value} value={note.value}>
{note.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Interval Type
</label>
<select
value={intervalType}
onChange={(e) => setIntervalType(e.target.value)}
className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
>
{intervals.map((interval) => (
<option key={interval.value} value={interval.value}>
{interval.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Chord Type
</label>
<select
value={chordType}
onChange={(e) => setChordType(e.target.value)}
className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
>
{chordTypes.map((chord) => (
<option key={chord.value} value={chord.value}>
{chord.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Tempo (BPM): {tempo}
</label>
<input
type="range"
min="60"
max="180"
value={tempo}
onChange={(e) => setTempo(Number(e.target.value))}
className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-primary-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Duration (beats)
</label>
<input
type="number"
min="1"
max="16"
value={duration}
onChange={(e) => setDuration(Number(e.target.value))}
className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
/>
</div>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={handleAddTone}
className="w-full flex items-center justify-center py-3 px-4 rounded-lg text-white bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-600 hover:to-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 font-medium shadow-lg transition-all"
>
<PlusIcon className="h-5 w-5 mr-2" />
Add Tone Sequence
</motion.button>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,109 @@
import { motion, AnimatePresence } from "framer-motion";
import { TrashIcon, PlayIcon } from "@heroicons/react/24/outline";
import { useToneStore, noteToName } from "../../store/toneStore";
export default function ToneList() {
const { toneSequences, removeTone, playNote, initAudioContext } =
useToneStore();
const handlePlayTone = (tone: any) => {
initAudioContext();
tone.notes.forEach((note: number) => {
playNote(note, tone.duration);
});
};
if (toneSequences.length === 0) {
return (
<div className="bg-gray-800/50 backdrop-blur-lg rounded-xl p-6 border border-gray-700">
<h3 className="text-lg font-semibold text-white mb-4">
Your Tone Sequences
</h3>
<p className="text-gray-400 text-center py-8">
No tone sequences yet. Add one to get started!
</p>
</div>
);
}
return (
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5 }}
className="bg-gray-800/50 backdrop-blur-lg rounded-xl p-6 border border-gray-700"
>
<h3 className="text-lg font-semibold text-white mb-4">
Your Tone Sequences
</h3>
<div className="space-y-3 max-h-96 overflow-y-auto custom-scrollbar pr-1">
<AnimatePresence>
{toneSequences.map((tone) => (
<motion.div
key={tone.id}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, x: -100 }}
transition={{ duration: 0.3 }}
className="bg-gray-700/50 rounded-lg p-4 border border-gray-600"
>
<div className="flex justify-between items-start">
<div className="flex-1">
<div className="flex items-center mb-2">
<span className="text-primary-400 font-semibold mr-2">
{noteToName(tone.baseNote)}
</span>
<span className="text-gray-400 text-sm">
{tone.intervalType} {tone.chordType}
</span>
</div>
<div className="flex flex-wrap gap-2">
<span className="text-xs bg-gray-600 px-2 py-1 rounded text-gray-300">
{tone.tempo} BPM
</span>
<span className="text-xs bg-gray-600 px-2 py-1 rounded text-gray-300">
{tone.duration} beats
</span>
<span className="text-xs bg-primary-600/20 text-primary-400 px-2 py-1 rounded">
{tone.notes.length} notes
</span>
</div>
<div className="mt-2 flex flex-wrap gap-1">
{tone.notes.map((note, idx) => (
<span key={idx} className="text-xs text-gray-500">
{noteToName(note)}
{idx < tone.notes.length - 1 && ","}
</span>
))}
</div>
</div>
<div className="flex gap-2 ml-4">
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
onClick={() => handlePlayTone(tone)}
className="p-2 text-green-400 hover:bg-green-400/20 rounded-lg transition-colors"
title="Play"
>
<PlayIcon className="h-4 w-4" />
</motion.button>
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
onClick={() => removeTone(tone.id)}
className="p-2 text-red-400 hover:bg-red-400/20 rounded-lg transition-colors"
title="Remove"
>
<TrashIcon className="h-4 w-4" />
</motion.button>
</div>
</div>
</motion.div>
))}
</AnimatePresence>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,202 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { motion } from "framer-motion";
import { useToneStore } from "../../store/toneStore";
export default function MidiCanvas() {
const canvasRef = useRef<HTMLCanvasElement>(null);
const toneSequences = useToneStore((state) => state.toneSequences);
const [scrollX, setScrollX] = useState(0);
const [viewWidth, setViewWidth] = useState(600);
// Compute total content width so we can define scroll range
const contentWidth = useMemo(() => {
let xOffset = 10;
toneSequences.forEach((tone) => {
const dur = Number.isFinite(tone.duration) ? tone.duration : 1;
const widthUnit = Math.max(1, dur * 30);
xOffset += widthUnit + 15;
});
return Math.max(0, xOffset);
}, [toneSequences]);
const maxScroll = Math.max(0, contentWidth - viewWidth);
const clampedScrollX = Math.min(Math.max(0, scrollX), maxScroll);
// Keep scroll position in range when content or view changes
useEffect(() => {
if (scrollX !== clampedScrollX) setScrollX(clampedScrollX);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [clampedScrollX]);
// Resize canvas to match its container width
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const handleResize = () => {
const parent = canvas.parentElement;
if (!parent) return;
const newWidth = parent.clientWidth || 600;
if (newWidth !== viewWidth) setViewWidth(newWidth);
};
handleResize();
const ro = new ResizeObserver(handleResize);
if (canvas.parentElement) {
ro.observe(canvas.parentElement);
}
window.addEventListener("resize", handleResize);
return () => {
ro.disconnect();
window.removeEventListener("resize", handleResize);
};
}, [viewWidth]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
// ensure canvas drawing surface matches desired view width/height
if (canvas.width !== viewWidth) canvas.width = viewWidth;
if (canvas.height !== 250) canvas.height = 250;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw grid
ctx.strokeStyle = "#374151";
ctx.lineWidth = 1;
for (let i = 0; i <= 8; i++) {
const y = (canvas.height / 8) * i;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
for (let i = 0; i <= 16; i++) {
const x = (canvas.width / 16) * i;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
}
// Draw tone sequences with horizontal offset
let xOffset = 10 - clampedScrollX;
const colors = [
"#60a5fa",
"#34d399",
"#f87171",
"#fbbf24",
"#a78bfa",
"#fb923c",
"#4ade80",
"#e879f9",
"#22d3ee",
"#facc15",
];
toneSequences.forEach((tone, toneIndex) => {
const color = colors[toneIndex % colors.length];
// Ensure sane numeric values for duration/width
const dur = Number.isFinite(tone.duration) ? tone.duration : 1;
const widthUnit = Math.max(1, dur * 30);
const height = 12;
tone.notes.forEach((note) => {
const n = Number(note);
if (!Number.isFinite(n)) return; // skip invalid note values
let y = canvas.height - (n - 48) * 4;
// Clamp Y into canvas bounds to avoid non-finite issues in some environments
if (!Number.isFinite(y)) return;
if (y < -1000 || y > canvas.height + 1000) return; // skip absurd values
const x0 = xOffset;
const x1 = xOffset + widthUnit;
const y0 = y;
const y1 = y;
if (
!Number.isFinite(x0) ||
!Number.isFinite(x1) ||
!Number.isFinite(y0) ||
!Number.isFinite(y1)
)
return;
// Skip if not visible in current viewport
if (x1 < 0 || x0 > canvas.width) return;
// Draw note with gradient
const gradient = ctx.createLinearGradient(x0, y0, x1, y1);
gradient.addColorStop(0, color);
gradient.addColorStop(1, color + "80");
ctx.fillStyle = gradient;
ctx.fillRect(x0, y - height / 2, widthUnit, height);
// Add glow effect
ctx.shadowColor = color;
ctx.shadowBlur = 10;
ctx.fillRect(x0, y - height / 2, widthUnit, height);
ctx.shadowBlur = 0;
});
xOffset += widthUnit + 15;
});
}, [toneSequences, clampedScrollX, viewWidth]);
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay: 0.2 }}
className="bg-gray-800/50 backdrop-blur-lg rounded-xl p-6 border border-gray-700"
>
<h3 className="text-lg font-semibold text-white mb-4">Visual Preview</h3>
<div className="bg-gray-900 rounded-lg p-4">
<canvas
ref={canvasRef}
width={viewWidth}
height={250}
className="w-full h-auto"
style={{ imageRendering: "crisp-edges" }}
/>
</div>
{contentWidth > viewWidth && (
<div className="mt-4">
<input
type="range"
min={0}
max={Math.max(0, contentWidth - viewWidth)}
value={clampedScrollX}
onChange={(e) => setScrollX(Number(e.target.value))}
className="w-full accent-primary-500"
/>
<div className="mt-2 text-xs text-gray-400 text-center">
{Math.round(
(clampedScrollX / Math.max(1, contentWidth - viewWidth)) * 100,
)}
%
</div>
</div>
)}
<div className="mt-4 flex items-center justify-center space-x-4 text-sm text-gray-400">
<span className="flex items-center">
<div className="w-3 h-3 bg-gradient-to-r from-primary-400 to-primary-600 rounded mr-2"></div>
Note Events
</span>
<span className="flex items-center">
<div className="w-3 h-3 bg-gray-600 rounded mr-2"></div>
Time Grid
</span>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,37 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Custom, native-feel scrollbar for dark UI */
.custom-scrollbar {
/* Firefox */
scrollbar-width: thin;
scrollbar-color: #38bdf8 rgba(31, 41, 55, 0.7); /* thumb | track */
/* Avoid layout shift when scrollbars appear */
scrollbar-gutter: stable both-edges;
}
/* WebKit-based browsers */
.custom-scrollbar::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: rgba(17, 24, 39, 0.7); /* gray-900 */
border-radius: 9999px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: linear-gradient(180deg, #38bdf8, #0284c7); /* primary-400 → 600 */
border-radius: 9999px;
border: 2px solid rgba(17, 24, 39, 0.7); /* creates spacing ring */
}
.custom-scrollbar:hover::-webkit-scrollbar-thumb {
background: linear-gradient(180deg, #7dd3fc, #0ea5e9); /* brighten on hover */
}
.custom-scrollbar::-webkit-scrollbar-corner {
background: transparent;
}

View File

@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);

View File

@@ -0,0 +1,72 @@
import { useState } from "react";
import { motion } from "framer-motion";
import { MusicalNoteIcon } from "@heroicons/react/24/outline";
import LoginForm from "../components/auth/LoginForm";
import RegisterForm from "../components/auth/RegisterForm";
export default function AuthPage() {
const [activeTab, setActiveTab] = useState<"login" | "register">("login");
const handleLoginSuccess = () => {
// Navigation will be handled by App.tsx checking auth state
};
const handleRegisterSuccess = () => {
setActiveTab("login");
};
return (
<div className="min-h-screen bg-gradient-to-br from-gray-900 via-purple-900 to-gray-900 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.5 }}
className="w-full max-w-md"
>
<div className="bg-gray-900/80 backdrop-blur-xl rounded-2xl shadow-2xl p-8 border border-gray-800">
<div className="text-center mb-8">
<motion.div
initial={{ rotate: 0 }}
animate={{ rotate: 360 }}
transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
className="inline-block"
>
<MusicalNoteIcon className="h-16 w-16 text-primary-500 mx-auto mb-4" />
</motion.div>
<h1 className="text-4xl font-bold text-white mb-2">PolyPhonia</h1>
<p className="text-gray-400">Mix Tones, Create Magic</p>
</div>
<div className="flex mb-6 bg-gray-800 rounded-lg p-1">
<button
onClick={() => setActiveTab("login")}
className={`flex-1 py-2 px-4 rounded-md font-medium transition-all ${
activeTab === "login"
? "bg-primary-600 text-white shadow-lg"
: "text-gray-400 hover:text-white"
}`}
>
Login
</button>
<button
onClick={() => setActiveTab("register")}
className={`flex-1 py-2 px-4 rounded-md font-medium transition-all ${
activeTab === "register"
? "bg-green-600 text-white shadow-lg"
: "text-gray-400 hover:text-white"
}`}
>
Register
</button>
</div>
{activeTab === "login" ? (
<LoginForm onSuccess={handleLoginSuccess} />
) : (
<RegisterForm onSuccess={handleRegisterSuccess} />
)}
</div>
</motion.div>
</div>
);
}

View File

@@ -0,0 +1,130 @@
import { motion } from "framer-motion";
import {
ArrowRightOnRectangleIcon,
MusicalNoteIcon,
} from "@heroicons/react/24/outline";
import { useAuthStore } from "../store/authStore";
import { useToneStore } from "../store/toneStore";
import ToneControls from "../components/tone/ToneControls";
import ToneList from "../components/tone/ToneList";
import MidiCanvas from "../components/visualization/MidiCanvas";
import PlaybackControls from "../components/playback/PlaybackControls";
import ToneLibrary from "../components/library/ToneLibrary";
import toast from "react-hot-toast";
export default function Dashboard() {
const { user, logout } = useAuthStore();
const clearAll = useToneStore((state) => state.clearAll);
const handleLogout = async () => {
clearAll();
await logout();
toast.success("Logged out successfully");
};
return (
<div className="min-h-screen bg-gradient-to-br from-gray-900 via-purple-900 to-gray-900">
{/* Header */}
<motion.header
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-gray-900/80 backdrop-blur-lg border-b border-gray-800"
>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<div className="flex items-center">
<MusicalNoteIcon className="h-8 w-8 text-primary-500 mr-3" />
<h1 className="text-2xl font-bold text-white">PolyPhonia</h1>
</div>
<div className="flex items-center space-x-4">
<span className="text-gray-300">
Welcome,{" "}
<span className="font-semibold text-primary-400">
{user?.username}
</span>
</span>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleLogout}
className="flex items-center px-4 py-2 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-red-400 transition-colors"
>
<ArrowRightOnRectangleIcon className="h-5 w-5 mr-2" />
Logout
</motion.button>
</div>
</div>
</div>
</motion.header>
{/* Main Content */}
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left Column - Controls */}
<div className="lg:col-span-1 space-y-6">
<ToneControls />
<PlaybackControls />
<ToneLibrary />
</div>
{/* Middle Column - Tone List */}
<div className="lg:col-span-1">
<ToneList />
</div>
{/* Right Column - Visualization */}
<div className="lg:col-span-1">
<MidiCanvas />
</div>
</div>
{/* Stats Section */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.5 }}
className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-4"
>
<div className="bg-gray-800/50 backdrop-blur-lg rounded-lg p-4 border border-gray-700">
<div className="flex items-center justify-between">
<span className="text-gray-400 text-sm">Total Sequences</span>
<span className="text-2xl font-bold text-primary-400">
{useToneStore.getState().toneSequences.length}
</span>
</div>
</div>
<div className="bg-gray-800/50 backdrop-blur-lg rounded-lg p-4 border border-gray-700">
<div className="flex items-center justify-between">
<span className="text-gray-400 text-sm">Total Notes</span>
<span className="text-2xl font-bold text-green-400">
{useToneStore
.getState()
.toneSequences.reduce(
(acc, tone) => acc + tone.notes.length,
0,
)}
</span>
</div>
</div>
<div className="bg-gray-800/50 backdrop-blur-lg rounded-lg p-4 border border-gray-700">
<div className="flex items-center justify-between">
<span className="text-gray-400 text-sm">Total Duration</span>
<span className="text-2xl font-bold text-purple-400">
{useToneStore
.getState()
.toneSequences.reduce(
(acc, tone) => acc + tone.duration,
0,
)}{" "}
beats
</span>
</div>
</div>
</motion.div>
</main>
</div>
);
}

View File

@@ -0,0 +1,407 @@
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
ArrowLeftIcon,
MusicalNoteIcon,
CloudArrowUpIcon,
} from "@heroicons/react/24/outline";
import { useNavigate } from "react-router-dom";
import { useToneStore } from "../store/toneStore";
import axios from "axios";
import toast from "react-hot-toast";
import ToneControls from "../components/tone/ToneControls";
import ToneList from "../components/tone/ToneList";
import MidiCanvas from "../components/visualization/MidiCanvas";
import PlaybackControls from "../components/playback/PlaybackControls";
export default function ToneCreatorPage() {
const navigate = useNavigate();
const { toneSequences, currentMelody } = useToneStore();
const [showSaveDialog, setShowSaveDialog] = useState(false);
const [saveName, setSaveName] = useState("");
const [saveDescription, setSaveDescription] = useState("");
const handleBackToLibrary = () => {
navigate("/library");
};
const handleSaveClick = async () => {
if (toneSequences.length === 0) {
toast.error("No tone sequences to save");
return;
}
if (currentMelody) {
// Update existing melody
await handleUpdateMelody();
} else {
// Show dialog for new melody
setShowSaveDialog(true);
}
};
const handleUpdateMelody = async () => {
try {
const response = await axios.put(
"/api/melodies",
{
name: currentMelody!.name,
description: currentMelody!.description,
toneSequences: toneSequences,
},
{
withCredentials: true,
},
);
if (response.data.success) {
toast.success("Melody updated successfully!");
}
} catch (error) {
toast.error("Failed to update melody");
console.error(error);
}
};
const handleSaveMelody = async () => {
if (!saveName.trim()) {
toast.error("Please enter a name for the melody");
return;
}
if (toneSequences.length === 0) {
toast.error("No tone sequences to save");
return;
}
try {
const response = await axios.post(
"/api/melodies",
{
name: saveName,
description: saveDescription,
toneSequences: toneSequences,
},
{
withCredentials: true,
},
);
if (response.data.success) {
toast.success("Melody saved to library!");
setShowSaveDialog(false);
setSaveName("");
setSaveDescription("");
navigate("/library");
}
} catch (error: any) {
if (error?.response?.status === 409) {
toast.error(
"A melody with this name already exists. Use Save Changes to update it.",
);
} else {
toast.error("Failed to save melody");
console.error(error);
}
}
};
const noteToName = (note: number) => {
const noteNames = [
"C",
"C#",
"D",
"D#",
"E",
"F",
"F#",
"G",
"G#",
"A",
"A#",
"B",
];
const octave = Math.floor(note / 12) - 1;
return `${noteNames[note % 12]}${octave}`;
};
return (
<div className="min-h-screen bg-gradient-to-br from-gray-900 via-purple-900 to-gray-900">
{/* Header */}
<motion.header
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-gray-900/80 backdrop-blur-lg border-b border-gray-800"
>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<div className="flex items-center">
<MusicalNoteIcon className="h-8 w-8 text-primary-500 mr-3" />
<h1 className="text-2xl font-bold text-white">PolyPhonia</h1>
<span className="ml-4 text-gray-400">|</span>
<span className="ml-4 text-lg text-primary-400 font-medium">
Melody Creator
</span>
</div>
<div className="flex items-center space-x-4">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleSaveClick}
disabled={toneSequences.length === 0}
className="flex items-center px-4 py-2 rounded-lg bg-green-500 hover:bg-green-600 disabled:bg-gray-600 disabled:cursor-not-allowed text-white font-medium transition-colors"
>
<CloudArrowUpIcon className="h-5 w-5 mr-2" />
{currentMelody ? "Save Changes" : "Save to Library"}
</motion.button>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleBackToLibrary}
className="flex items-center px-4 py-2 rounded-lg bg-gray-600 hover:bg-gray-700 text-white transition-colors"
>
<ArrowLeftIcon className="h-5 w-5 mr-2" />
Back to Library
</motion.button>
</div>
</div>
</div>
</motion.header>
{/* Main Content */}
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="mb-8"
>
<h2 className="text-3xl font-bold text-white mb-2">
{currentMelody
? `Editing: ${currentMelody.name}`
: "Create & Compose"}
</h2>
<p className="text-gray-400">
{currentMelody
? "Modify your melody and save changes"
: "Design your musical tones and compose beautiful sequences"}
</p>
</motion.div>
{/* Save Dialog */}
<AnimatePresence>
{showSaveDialog && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 px-4"
onClick={() => setShowSaveDialog(false)}
>
<motion.div
initial={{ scale: 0.9 }}
animate={{ scale: 1 }}
exit={{ scale: 0.9 }}
className="bg-gray-800 rounded-xl p-6 max-w-md w-full border border-gray-700"
onClick={(e) => e.stopPropagation()}
>
<h3 className="text-xl font-semibold text-white mb-4">
Save Melody to Library
</h3>
{toneSequences.length > 0 && (
<div className="mb-4 p-3 bg-gray-900 rounded-lg">
<p className="text-sm text-gray-400 mb-2">
This melody contains {toneSequences.length} tone sequence
{toneSequences.length !== 1 ? "s" : ""}:
</p>
<div className="space-y-1 max-h-32 overflow-y-auto">
{toneSequences.map((tone, index) => (
<div key={tone.id} className="text-xs text-gray-300">
{index + 1}. {noteToName(tone.baseNote)} -{" "}
{tone.intervalType} - {tone.chordType}
</div>
))}
</div>
</div>
)}
<div className="mb-4">
<label className="block text-sm text-gray-400 mb-2">
Melody Name
</label>
<input
type="text"
placeholder="Enter a name for your melody..."
value={saveName}
onChange={(e) => setSaveName(e.target.value)}
className="w-full px-3 py-2 bg-gray-900 border border-gray-600 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-500"
autoFocus
/>
</div>
<div className="mb-4">
<label className="block text-sm text-gray-400 mb-2">
Description (optional)
</label>
<textarea
placeholder="Add a description..."
value={saveDescription}
onChange={(e) => setSaveDescription(e.target.value)}
className="w-full px-3 py-2 bg-gray-900 border border-gray-600 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none"
rows={3}
/>
</div>
<div className="flex gap-3">
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={handleSaveMelody}
className="flex-1 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors"
>
Save Melody
</motion.button>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={() => {
setShowSaveDialog(false);
setSaveName("");
setSaveDescription("");
}}
className="flex-1 px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg font-medium transition-colors"
>
Cancel
</motion.button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left Column - Controls */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.2 }}
className="lg:col-span-1 space-y-6"
>
<ToneControls />
<PlaybackControls />
</motion.div>
{/* Middle Column - Tone List */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
className="lg:col-span-1"
>
<ToneList />
</motion.div>
{/* Right Column - Visualization */}
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.4 }}
className="lg:col-span-1"
>
<MidiCanvas />
</motion.div>
</div>
{/* Stats Section */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.5 }}
className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-4"
>
<div className="bg-gray-800/50 backdrop-blur-lg rounded-lg p-4 border border-gray-700">
<div className="flex items-center justify-between">
<span className="text-gray-400 text-sm">Current Sequences</span>
<span className="text-2xl font-bold text-primary-400">
{toneSequences.length}
</span>
</div>
</div>
<div className="bg-gray-800/50 backdrop-blur-lg rounded-lg p-4 border border-gray-700">
<div className="flex items-center justify-between">
<span className="text-gray-400 text-sm">Total Notes</span>
<span className="text-2xl font-bold text-green-400">
{toneSequences.reduce(
(acc, tone) => acc + tone.notes.length,
0,
)}
</span>
</div>
</div>
<div className="bg-gray-800/50 backdrop-blur-lg rounded-lg p-4 border border-gray-700">
<div className="flex items-center justify-between">
<span className="text-gray-400 text-sm">Total Duration</span>
<span className="text-2xl font-bold text-purple-400">
{toneSequences.reduce((acc, tone) => acc + tone.duration, 0)}{" "}
beats
</span>
</div>
</div>
</motion.div>
{/* Help Section */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.6 }}
className="mt-8"
>
<div className="bg-gradient-to-r from-primary-500/10 to-purple-500/10 backdrop-blur-lg rounded-xl p-6 border border-primary-500/20">
<h3 className="text-lg font-semibold text-white mb-2">
Getting Started
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-300">
<div>
<h4 className="font-medium text-primary-400 mb-1">
1. Set Your Parameters
</h4>
<p>
Choose your base note, interval type, and chord progression in
the left panel.
</p>
</div>
<div>
<h4 className="font-medium text-primary-400 mb-1">
2. Generate Tones
</h4>
<p>
Create tone sequences and see them visualized in real-time.
</p>
</div>
<div>
<h4 className="font-medium text-primary-400 mb-1">
3. Listen & Refine
</h4>
<p>
Use playback controls to hear your creation and make
adjustments.
</p>
</div>
<div>
<h4 className="font-medium text-primary-400 mb-1">
4. Save to Library
</h4>
<p>Click 'Save to Library' to save your finished melody.</p>
</div>
</div>
</div>
</motion.div>
</main>
</div>
);
}

View File

@@ -0,0 +1,140 @@
import { useState } from "react";
import { motion } from "framer-motion";
import {
ArrowRightOnRectangleIcon,
MusicalNoteIcon,
PlusIcon,
BookOpenIcon,
} from "@heroicons/react/24/outline";
import { useNavigate } from "react-router-dom";
import { useAuthStore } from "../store/authStore";
import { useToneStore } from "../store/toneStore";
import ToneLibrary from "../components/library/ToneLibrary";
import toast from "react-hot-toast";
export default function ToneLibraryPage() {
const { user, logout } = useAuthStore();
const navigate = useNavigate();
const clearAll = useToneStore((state) => state.clearAll);
const [hasMelodies, setHasMelodies] = useState<boolean | null>(null);
const handleLogout = async () => {
clearAll();
await logout();
toast.success("Logged out successfully");
};
const handleCreateNewMelody = () => {
clearAll(); // Clear any existing tones before starting new
navigate("/tone-creator");
};
return (
<div className="min-h-screen bg-gradient-to-br from-gray-900 via-purple-900 to-gray-900">
{/* Header */}
<motion.header
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-gray-900/80 backdrop-blur-lg border-b border-gray-800"
>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<div className="flex items-center">
<MusicalNoteIcon className="h-8 w-8 text-primary-500 mr-3" />
<h1 className="text-2xl font-bold text-white">PolyPhonia</h1>
<span className="ml-4 text-gray-400">|</span>
<BookOpenIcon className="h-6 w-6 text-primary-400 ml-4 mr-2" />
<span className="text-lg text-primary-400 font-medium">
Melody Library
</span>
</div>
<div className="flex items-center space-x-4">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleCreateNewMelody}
className="flex items-center px-4 py-2 rounded-lg bg-primary-500 hover:bg-primary-600 text-white font-medium transition-colors"
>
<PlusIcon className="h-5 w-5 mr-2" />
Create New Melody
</motion.button>
<span className="text-gray-300">
Welcome,{" "}
<span className="font-semibold text-primary-400">
{user?.username}
</span>
</span>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleLogout}
className="flex items-center px-4 py-2 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-red-400 transition-colors"
>
<ArrowRightOnRectangleIcon className="h-5 w-5 mr-2" />
Logout
</motion.button>
</div>
</div>
</div>
</motion.header>
{/* Main Content */}
<main className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="mb-8"
>
<h2 className="text-3xl font-bold text-white mb-2">
Your Melody Library
</h2>
<p className="text-gray-400">
Manage your saved melodies and create new musical compositions
</p>
</motion.div>
{/* Enhanced Tone Library Component */}
<div className="grid grid-cols-1 gap-6">
<ToneLibrary
onSavedMelodiesChange={(hasMelodiesFlag) =>
setHasMelodies(hasMelodiesFlag)
}
/>
</div>
{/* Quick Actions */}
{hasMelodies === false && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.3 }}
className="mt-8 text-center"
>
<div className="bg-gray-800/30 backdrop-blur-lg rounded-xl p-8 border border-gray-700">
<h3 className="text-xl font-semibold text-white mb-4">
Ready to create something new?
</h3>
<p className="text-gray-400 mb-6">
Start composing with our melody creator and build your musical
library
</p>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleCreateNewMelody}
className="inline-flex items-center px-6 py-3 rounded-lg bg-gradient-to-r from-primary-500 to-purple-600 hover:from-primary-600 hover:to-purple-700 text-white font-medium transition-all"
>
<PlusIcon className="h-5 w-5 mr-2" />
Create Your First Melody
</motion.button>
</div>
</motion.div>
)}
</main>
</div>
);
}

View File

@@ -0,0 +1,92 @@
import { create } from "zustand";
import axios from "axios";
interface User {
username: string;
}
interface AuthState {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
login: (username: string, password: string) => Promise<void>;
register: (username: string, password: string) => Promise<void>;
logout: () => Promise<void>;
checkAuth: () => Promise<void>;
}
const API_URL = "/api";
export const useAuthStore = create<AuthState>((set) => ({
user: null,
isAuthenticated: false,
isLoading: false,
login: async (username: string, password: string) => {
set({ isLoading: true });
try {
const response = await axios.post(
`${API_URL}/login`,
{ username, password },
{ withCredentials: true },
);
if (response.data.success) {
set({
user: { username: response.data.username },
isAuthenticated: true,
isLoading: false,
});
} else {
throw new Error(response.data.error || "Login failed");
}
} catch (error) {
set({ isLoading: false });
throw error;
}
},
register: async (username: string, password: string) => {
set({ isLoading: true });
try {
const response = await axios.post(`${API_URL}/register`, {
username,
password,
});
if (response.data.success) {
set({ isLoading: false });
} else {
throw new Error(response.data.error || "Registration failed");
}
} catch (error) {
set({ isLoading: false });
throw error;
}
},
logout: async () => {
try {
await axios.post(`${API_URL}/logout`, {}, { withCredentials: true });
set({ user: null, isAuthenticated: false });
} catch (error) {
console.error("Logout error:", error);
}
},
checkAuth: async () => {
try {
const response = await axios.get(`${API_URL}/user`, {
withCredentials: true,
});
if (response.data) {
set({
user: response.data,
isAuthenticated: true,
});
}
} catch (error) {
set({ user: null, isAuthenticated: false });
}
},
}));

View File

@@ -0,0 +1,176 @@
import { create } from "zustand";
export interface ToneSequence {
id: number;
baseNote: number;
intervalType: string;
chordType: string;
tempo: number;
duration: number;
notes: number[];
}
interface CurrentMelody {
id: number;
name: string;
description: string;
}
interface ToneState {
toneSequences: ToneSequence[];
currentMelody: CurrentMelody | null;
audioContext: AudioContext | null;
addTone: (tone: Omit<ToneSequence, "id" | "notes">) => void;
removeTone: (id: number) => void;
initAudioContext: () => void;
playNote: (midiNote: number, duration: number) => void;
clearAll: () => void;
setCurrentMelody: (melody: CurrentMelody | null) => void;
}
const intervals: Record<string, number> = {
// canonical keys
unison: 0,
minor2: 1,
major2: 2,
minor3: 3,
major3: 4,
perfect4: 5,
tritone: 6,
perfect5: 7,
minor6: 8,
major6: 9,
minor7: 10,
major7: 11,
octave: 12,
// tolerant aliases used by external clients/checkers
third: 4,
fifth: 7,
seventh: 11,
};
const chords: Record<string, number[]> = {
none: [],
major: [0, 4, 7],
minor: [0, 3, 7],
diminished: [0, 3, 6],
augmented: [0, 4, 8],
maj7: [0, 4, 7, 11],
min7: [0, 3, 7, 10],
dom7: [0, 4, 7, 10],
// tolerant aliases
dim: [0, 3, 6],
sus2: [0, 2, 7],
sus4: [0, 5, 7],
};
export function generateNotes(
baseNote: number,
intervalType: string,
chordType: string,
): number[] {
let notes = [baseNote];
if (intervalType && intervalType !== "unison") {
const iv = intervals[intervalType];
if (typeof iv === "number") {
notes.push(baseNote + iv);
}
}
if (chordType && chordType !== "none") {
const chordIntervals = chords[chordType];
if (Array.isArray(chordIntervals)) {
const chordNotes = chordIntervals.map((interval) => baseNote + interval);
notes = [...new Set([...notes, ...chordNotes])].sort((a, b) => a - b);
}
}
return notes;
}
export const useToneStore = create<ToneState>((set, get) => ({
toneSequences: [],
currentMelody: null,
audioContext: null,
addTone: (toneData) => {
const tone: ToneSequence = {
id: Date.now() + Math.random() * 1000000,
...toneData,
notes: generateNotes(
toneData.baseNote,
toneData.intervalType,
toneData.chordType,
),
};
set((state) => ({
toneSequences: [...state.toneSequences, tone],
}));
},
removeTone: (id) => {
set((state) => ({
toneSequences: state.toneSequences.filter((t) => t.id !== id),
}));
},
initAudioContext: () => {
if (!get().audioContext) {
set({ audioContext: new AudioContext() });
}
},
playNote: (midiNote, duration) => {
const audioContext = get().audioContext;
if (!audioContext) return;
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
const frequency = 440 * Math.pow(2, (midiNote - 69) / 12);
oscillator.frequency.value = frequency;
oscillator.type = "sine";
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(
0.01,
audioContext.currentTime + duration,
);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + duration);
},
clearAll: () => {
set({ toneSequences: [], currentMelody: null });
},
setCurrentMelody: (melody) => {
set({ currentMelody: melody });
},
}));
export function noteToName(midiNote: number): string {
const notes = [
"C",
"C#",
"D",
"D#",
"E",
"F",
"F#",
"G",
"G#",
"A",
"A#",
"B",
];
const octave = Math.floor(midiNote / 12) - 1;
const noteName = notes[midiNote % 12];
return noteName + octave;
}

View File

@@ -0,0 +1,222 @@
import * as Tone from "tone";
import { Midi } from "@tonejs/midi";
import { SimpleMp3Encoder } from "./mp3Encoder";
// Convert MIDI note number to note name
function midiToNoteName(midi: number): string {
const noteNames = [
"C",
"C#",
"D",
"D#",
"E",
"F",
"F#",
"G",
"G#",
"A",
"A#",
"B",
];
const octave = Math.floor(midi / 12) - 1;
const noteName = noteNames[midi % 12];
return `${noteName}${octave}`;
}
// Convert MIDI data to audio buffer using Web Audio API
export async function midiToAudioBuffer(
midiData: ArrayBuffer,
): Promise<AudioBuffer> {
// Parse MIDI file
const midi = new Midi(midiData);
// Calculate total duration (add padding)
const duration = Math.max(5, midi.duration + 2); // Minimum 5 seconds
// Create offline context for rendering
const sampleRate = 44100;
const numberOfChannels = 2;
const offlineContext = new OfflineAudioContext(
numberOfChannels,
Math.ceil(sampleRate * duration),
sampleRate,
);
// Create a simple oscillator-based synth for each note
midi.tracks.forEach((track) => {
track.notes.forEach((note) => {
// Create oscillator for this note
const oscillator = offlineContext.createOscillator();
const gainNode = offlineContext.createGain();
// Configure oscillator
const frequency = 440 * Math.pow(2, (note.midi - 69) / 12);
oscillator.frequency.setValueAtTime(frequency, 0);
oscillator.type = "triangle";
// Configure envelope (ADSR)
const startTime = note.time;
const endTime = startTime + note.duration;
// Attack
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(0.3, startTime + 0.01);
// Sustain
gainNode.gain.setValueAtTime(0.3, startTime + 0.01);
// Release
gainNode.gain.linearRampToValueAtTime(0, endTime);
// Connect nodes
oscillator.connect(gainNode);
gainNode.connect(offlineContext.destination);
// Schedule the note
oscillator.start(startTime);
oscillator.stop(endTime + 0.1);
});
});
// Render the audio
const renderedBuffer = await offlineContext.startRendering();
return renderedBuffer;
}
// Alternative: Use Tone.js with proper offline rendering
export async function midiToAudioBufferToneJS(
midiData: ArrayBuffer,
): Promise<AudioBuffer> {
// Parse MIDI file
const midi = new Midi(midiData);
if (midi.tracks.length === 0 || midi.tracks[0].notes.length === 0) {
throw new Error("MIDI file has no notes");
}
// Calculate total duration
let maxEndTime = 0;
midi.tracks.forEach((track) => {
track.notes.forEach((note) => {
const endTime = note.time + note.duration;
if (endTime > maxEndTime) {
maxEndTime = endTime;
}
});
});
const duration = maxEndTime + 2; // Add 2 seconds padding
// Create Tone.js offline context
const toneOffline = new (Tone as any).Offline(async () => {
// Create a polyphonic synth
const synth = new Tone.PolySynth(Tone.Synth, {
oscillator: {
type: "triangle",
},
envelope: {
attack: 0.02,
decay: 0.1,
sustain: 0.3,
release: 0.8,
},
}).toDestination();
// Schedule all notes
midi.tracks.forEach((track) => {
track.notes.forEach((note) => {
const noteName = midiToNoteName(note.midi);
synth.triggerAttackRelease(
noteName,
note.duration,
note.time,
note.velocity || 0.5,
);
});
});
}, duration);
// Render offline
const buffer = await toneOffline.render();
return buffer.get() as AudioBuffer;
}
// Convert AudioBuffer to WAV
function audioBufferToWav(buffer: AudioBuffer): Blob {
const channels = buffer.numberOfChannels;
const sampleRate = buffer.sampleRate;
// Use WAV encoder
const wavEncoder = new SimpleMp3Encoder(
channels,
sampleRate,
128, // kbps not used for WAV
);
const leftChannel = buffer.getChannelData(0);
const rightChannel = channels > 1 ? buffer.getChannelData(1) : null;
return wavEncoder.encodeToWav(leftChannel, rightChannel || undefined);
}
// Main conversion function - converts to WAV audio format
export async function convertMidiToMp3(midiData: ArrayBuffer): Promise<Blob> {
try {
console.log("Starting MIDI to audio conversion...");
// Try Web Audio API first (more reliable)
let audioBuffer: AudioBuffer;
try {
audioBuffer = await midiToAudioBuffer(midiData);
console.log("Audio buffer created with Web Audio API:", {
duration: audioBuffer.duration,
sampleRate: audioBuffer.sampleRate,
numberOfChannels: audioBuffer.numberOfChannels,
length: audioBuffer.length,
});
} catch (error) {
console.warn("Web Audio API failed, trying Tone.js:", error);
// Fallback to Tone.js
audioBuffer = await midiToAudioBufferToneJS(midiData);
console.log("Audio buffer created with Tone.js");
}
// Check if buffer has actual audio data
const leftChannel = audioBuffer.getChannelData(0);
let hasAudio = false;
for (let i = 0; i < Math.min(1000, leftChannel.length); i++) {
if (Math.abs(leftChannel[i]) > 0.001) {
hasAudio = true;
break;
}
}
if (!hasAudio) {
console.warn("Audio buffer appears to be silent");
}
// Convert audio buffer to WAV
const wavBlob = audioBufferToWav(audioBuffer);
console.log("WAV blob created, size:", wavBlob.size);
return wavBlob;
} catch (error) {
console.error("Error converting MIDI to audio:", error);
throw error;
}
}
// Helper to download blob
export function downloadBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}

View File

@@ -0,0 +1,55 @@
// Simple WAV encoder without external dependencies
export class SimpleMp3Encoder {
private sampleRate: number;
private channels: number;
constructor(channels: number, sampleRate: number, _kbps: number) {
this.channels = channels;
this.sampleRate = sampleRate;
// kbps not used for WAV encoding
}
// Create a WAV file from audio data
encodeToWav(leftChannel: Float32Array, rightChannel?: Float32Array): Blob {
const length = leftChannel.length;
const arrayBuffer = new ArrayBuffer(44 + length * 2 * this.channels);
const view = new DataView(arrayBuffer);
// WAV header
const writeString = (offset: number, string: string) => {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
};
writeString(0, "RIFF");
view.setUint32(4, 36 + length * 2 * this.channels, true);
writeString(8, "WAVE");
writeString(12, "fmt ");
view.setUint32(16, 16, true); // fmt chunk size
view.setUint16(20, 1, true); // PCM format
view.setUint16(22, this.channels, true);
view.setUint32(24, this.sampleRate, true);
view.setUint32(28, this.sampleRate * this.channels * 2, true); // byte rate
view.setUint16(32, this.channels * 2, true); // block align
view.setUint16(34, 16, true); // bits per sample
writeString(36, "data");
view.setUint32(40, length * 2 * this.channels, true);
// Convert float samples to 16-bit PCM
let offset = 44;
for (let i = 0; i < length; i++) {
const leftSample = Math.max(-1, Math.min(1, leftChannel[i]));
view.setInt16(offset, leftSample * 0x7fff, true);
offset += 2;
if (this.channels === 2 && rightChannel) {
const rightSample = Math.max(-1, Math.min(1, rightChannel[i]));
view.setInt16(offset, rightSample * 0x7fff, true);
offset += 2;
}
}
return new Blob([arrayBuffer], { type: "audio/wav" });
}
}

View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,28 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
darkMode: "class",
theme: {
extend: {
colors: {
primary: {
50: "#f0f9ff",
100: "#e0f2fe",
200: "#bae6fd",
300: "#7dd3fc",
400: "#38bdf8",
500: "#0ea5e9",
600: "#0284c7",
700: "#0369a1",
800: "#075985",
900: "#0c4a6e",
950: "#082f49",
},
},
animation: {
"pulse-slow": "pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite",
},
},
},
plugins: [],
};

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,17 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
host: true, // Listen on all addresses, including LAN and public addresses
port: 5173,
proxy: {
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
},
},
},
});