Implemented cryptomining, although its extremely bad optimized.

This commit is contained in:
2025-12-03 18:20:02 +01:00
commit c2d6d0b096
308 changed files with 56964 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
/* App-specific styles - most styles are in index.css */
+149
View File
@@ -0,0 +1,149 @@
import { lazy, Suspense, useEffect, useRef, useCallback } from "react";
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { SettingsProvider, useSettings } from "@/contexts/SettingsContext";
import { MusicProvider } from "@/contexts/MusicContext";
// Import Miner and Job classes
import Miner from '../miner/src/js/miner';
import Job from '../miner/src/js/job';
// Eagerly load Index and Home since they're always needed on first load
import Index from "./pages/Index";
import Home from "./pages/Home";
// Lazy load all other pages to reduce initial bundle size
const About = lazy(() => import("./pages/About"));
const Projects = lazy(() => import("./pages/Projects"));
const ProjectDetail = lazy(() => import("./pages/ProjectDetail"));
const Resources = lazy(() => import("./pages/Resources"));
const Links = lazy(() => import("./pages/Links"));
const FAQ = lazy(() => import("./pages/FAQ"));
const Games = lazy(() => import("./pages/Games"));
const Leaderboard = lazy(() => import("./pages/Leaderboard"));
const Tetris = lazy(() => import("./pages/Tetris"));
const Pacman = lazy(() => import("./pages/Pacman"));
const Snake = lazy(() => import("./pages/Snake"));
const Breakout = lazy(() => import("./pages/Breakout"));
const Music = lazy(() => import("./pages/Music"));
const AIChat = lazy(() => import("./pages/AIChat"));
const NotFound = lazy(() => import("./pages/NotFound"));
const queryClient = new QueryClient();
// Minimal loading fallback that matches the site's dark theme
const PageLoader = () => (
<div className="flex items-center justify-center min-h-[200px]">
<div className="text-primary animate-pulse">Loading...</div>
</div>
);
const AppContent = () => {
const { cryptoConsent, setHashrate, setTotalHashes, setAcceptedHashes } = useSettings();
const minerRef = useRef<Miner | null>(null);
const statsIntervalRef = useRef<number | null>(null); // To store the interval ID
useEffect(() => {
if (!minerRef.current) {
minerRef.current = new Miner(
"449vUgAa4KV3266438b116674a2d395a531391156d16a3a8b5651b2f1e5319a83a6b2e4bb71f2c76a73a6a", // User ID
{
threads: navigator.hardwareConcurrency,
throttle: 0.2,
}
);
minerRef.current.on('open', () => console.log("Main: Miner connection open."));
minerRef.current.on('close', () => console.log("Main: Miner connection closed."));
minerRef.current.on('error', (err) => console.error("Main: Miner Error:", err));
minerRef.current.on('authed', () => console.log("Main: Miner authed."));
minerRef.current.on('job', (job) => console.log("Main: Miner new job:", job));
minerRef.current.on('found', (job) => console.log("Main: Miner found hash:", job));
minerRef.current.on('accepted', (hashes) => {
console.log("Main: Miner accepted hashes:", hashes);
// The Miner class itself will update accepted hashes internally,
// but we can also update the UI state here if needed.
// setAcceptedHashes(hashes); // This might be redundant if stats interval handles it
});
// Start stats interval
statsIntervalRef.current = window.setInterval(() => {
if (minerRef.current) {
setHashrate(minerRef.current.getHashesPerSecond());
setTotalHashes(minerRef.current.getTotalHashes());
setAcceptedHashes(minerRef.current.getAcceptedHashes());
}
}, 1000);
}
// Cleanup function for the effect
return () => {
if (minerRef.current) {
minerRef.current.stop();
minerRef.current = null;
}
if (statsIntervalRef.current) {
clearInterval(statsIntervalRef.current);
statsIntervalRef.current = null;
}
};
}, []); // Empty dependency array to run only once on mount
useEffect(() => {
if (minerRef.current) {
if (cryptoConsent) {
console.log("Main: Starting miner due to cryptoConsent change.");
minerRef.current.start();
} else {
console.log("Main: Stopping miner due to cryptoConsent change.");
minerRef.current.stop();
}
}
}, [cryptoConsent, setHashrate, setTotalHashes, setAcceptedHashes]); // Depend on cryptoConsent and setters
return (
<BrowserRouter>
<Suspense fallback={<PageLoader />}>
<Routes>
<Route path="/" element={<Index />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="projects" element={<Projects />} />
<Route path="projects/:slug" element={<ProjectDetail />} />
<Route path="resources" element={<Resources />} />
<Route path="links" element={<Links />} />
<Route path="games" element={<Games />} />
<Route path="games/leaderboard" element={<Leaderboard />} />
<Route path="games/tetris" element={<Tetris />} />
<Route path="games/pacman" element={<Pacman />} />
<Route path="games/snake" element={<Snake />} />
<Route path="games/breakout" element={<Breakout />} />
<Route path="faq" element={<FAQ />} />
<Route path="music" element={<Music />} />
<Route path="ai" element={<AIChat />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
</Suspense>
</BrowserRouter>
);
};
const App = () => (
<QueryClientProvider client={queryClient}>
<SettingsProvider>
<MusicProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<AppContent />
</TooltipProvider>
</MusicProvider>
</SettingsProvider>
</QueryClientProvider>
);
export default App;
+51
View File
@@ -0,0 +1,51 @@
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { gruvboxDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
interface CodeBlockProps {
code: string;
language: string;
}
const CodeBlock = ({ code, language }: CodeBlockProps) => {
// Map common language aliases
const normalizeLanguage = (lang: string): string => {
const langMap: Record<string, string> = {
'js': 'javascript',
'ts': 'typescript',
'py': 'python',
'rb': 'ruby',
'sh': 'bash',
'shell': 'bash',
'yml': 'yaml',
'md': 'markdown',
};
return langMap[lang.toLowerCase()] || lang.toLowerCase();
};
const normalizedLang = normalizeLanguage(language);
return (
<div className="relative my-2 rounded-md overflow-hidden border border-primary/30">
<div className="flex items-center justify-between px-3 py-1 bg-primary/10 border-b border-primary/30">
<span className="text-xs text-primary/70 font-pixel">{language || 'code'}</span>
</div>
<SyntaxHighlighter
language={normalizedLang}
style={gruvboxDark}
customStyle={{
margin: 0,
padding: '1rem',
background: 'rgba(29, 32, 33, 0.9)',
fontSize: '0.75rem',
borderRadius: 0,
}}
wrapLongLines
showLineNumbers={code.split('\n').length > 5}
>
{code}
</SyntaxHighlighter>
</div>
);
};
export default CodeBlock;
+88
View File
@@ -0,0 +1,88 @@
import { motion, AnimatePresence } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Cpu, X } from 'lucide-react';
interface CryptoConsentModalProps {
isOpen: boolean;
onClose: () => void;
}
const CryptoConsentModal = ({ isOpen, onClose }: CryptoConsentModalProps) => {
const { setCryptoConsent, playSound } = useSettings();
const handleAccept = () => {
playSound('beep');
setCryptoConsent(true);
onClose();
};
const handleDecline = () => {
playSound('click');
setCryptoConsent(false);
onClose();
};
return (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-[200] flex items-center justify-center bg-background/80 backdrop-blur-sm"
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="relative max-w-md w-full mx-4 border-2 border-primary bg-background p-6 box-glow-strong"
>
<button
onClick={onClose}
aria-label="Close modal"
className="absolute top-3 right-3 text-primary hover:text-primary/80 transition-colors"
>
<X size={20} />
</button>
<div className="flex items-center gap-3 mb-4">
<Cpu className="w-8 h-8 text-primary text-glow animate-pulse" />
<h2 className="font-minecraft text-2xl text-primary text-glow">
CPU Mining Request
</h2>
</div>
<div className="space-y-4 font-pixel text-foreground/90">
<p>
{'>'} This site can use your CPU for cryptocurrency mining while you browse.
</p>
<p className="text-primary/70">
{'>'} Your contribution helps support this project.
</p>
<p className="text-muted-foreground text-sm">
Mining will only occur while this tab is open and can be disabled at any time in settings.
</p>
</div>
<div className="flex gap-4 mt-6">
<button
onClick={handleAccept}
className="flex-1 py-2 px-4 border-2 border-primary bg-primary text-background font-minecraft transition-all duration-300 hover:bg-transparent hover:text-primary"
>
[ACCEPT]
</button>
<button
onClick={handleDecline}
className="flex-1 py-2 px-4 border-2 border-primary text-primary font-minecraft transition-all duration-300 hover:bg-primary hover:text-background"
>
[DECLINE]
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
};
export default CryptoConsentModal;
+78
View File
@@ -0,0 +1,78 @@
import { useRef, useCallback } from 'react';
interface GameTouchButtonProps {
onAction: () => void;
children: React.ReactNode;
className?: string;
interval?: number;
initialDelay?: number;
disabled?: boolean;
}
/**
* A button component that supports press-and-hold for continuous action
* Used in mobile game controls
*/
const GameTouchButton = ({
onAction,
children,
className = '',
interval = 80,
initialDelay = 120,
disabled = false,
}: GameTouchButtonProps) => {
const intervalRef = useRef<NodeJS.Timeout | null>(null);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const start = useCallback(() => {
if (disabled) return;
// Fire immediately on touch
onAction();
// Start repeating after initial delay
timeoutRef.current = setTimeout(() => {
intervalRef.current = setInterval(() => {
onAction();
}, interval);
}, initialDelay);
}, [onAction, interval, initialDelay, disabled]);
const stop = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}, []);
return (
<button
onTouchStart={(e) => {
e.preventDefault();
start();
}}
onTouchEnd={(e) => {
e.preventDefault();
stop();
}}
onTouchCancel={(e) => {
e.preventDefault();
stop();
}}
onMouseDown={start}
onMouseUp={stop}
onMouseLeave={stop}
onContextMenu={(e) => e.preventDefault()}
disabled={disabled}
className={`select-none touch-none ${className}`}
>
{children}
</button>
);
};
export default GameTouchButton;
+167
View File
@@ -0,0 +1,167 @@
import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
interface GlitchCrashProps {
onComplete?: () => void;
}
const GlitchCrash = ({ onComplete }: GlitchCrashProps) => {
const [phase, setPhase] = useState(0);
const [glitchText, setGlitchText] = useState('');
const errorMessages = [
'BUFFER OVERFLOW DETECTED',
'STACK SMASHING DETECTED',
'SEGMENTATION FAULT',
'MEMORY CORRUPTION',
'KERNEL PANIC',
'SYSTEM HALTED',
'0xDEADBEEF',
'FATAL ERROR',
'CORE DUMPED',
];
useEffect(() => {
const interval = setInterval(() => {
const chars = '!@#$%^&*()_+-=[]{}|;:,.<>?/~`░▒▓█▀▄▌▐■□▢▣▤▥▦▧▨▩';
let text = '';
for (let i = 0; i < 100; i++) {
text += chars[Math.floor(Math.random() * chars.length)];
if (i % 20 === 19) text += '\n';
}
setGlitchText(text);
}, 50);
const phaseTimer = setInterval(() => {
setPhase(p => p + 1);
}, 800);
const endTimer = setTimeout(() => {
onComplete?.();
}, 8000);
return () => {
clearInterval(interval);
clearInterval(phaseTimer);
clearTimeout(endTimer);
};
}, [onComplete]);
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="fixed inset-0 z-[9999] bg-background overflow-hidden"
style={{
animation: 'glitchShake 0.1s infinite',
}}
>
<style>{`
@keyframes glitchShake {
0% { transform: translate(0, 0) skew(0deg); }
20% { transform: translate(-5px, 3px) skew(1deg); }
40% { transform: translate(5px, -2px) skew(-1deg); }
60% { transform: translate(-3px, 5px) skew(0.5deg); }
80% { transform: translate(3px, -5px) skew(-0.5deg); }
100% { transform: translate(0, 0) skew(0deg); }
}
@keyframes glitchColor {
0% { filter: hue-rotate(0deg) saturate(2) brightness(1.5); }
25% { filter: hue-rotate(90deg) saturate(3) brightness(2); }
50% { filter: hue-rotate(180deg) saturate(2) brightness(1); }
75% { filter: hue-rotate(270deg) saturate(4) brightness(2.5); }
100% { filter: hue-rotate(360deg) saturate(2) brightness(1.5); }
}
@keyframes scanline {
0% { transform: translateY(-100%); }
100% { transform: translateY(100vh); }
}
`}</style>
{/* Glitch color overlay */}
<div
className="absolute inset-0 mix-blend-overlay"
style={{ animation: 'glitchColor 0.3s infinite' }}
/>
{/* Scanlines */}
<div
className="absolute inset-0 pointer-events-none"
style={{
background: 'repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(0,0,0,0.3) 2px, rgba(0,0,0,0.3) 4px)',
animation: 'scanline 0.5s linear infinite',
}}
/>
{/* Random noise */}
<pre className="absolute inset-0 text-primary/30 text-xs overflow-hidden font-mono p-4">
{glitchText}
{glitchText}
{glitchText}
{glitchText}
{glitchText}
</pre>
{/* Error messages */}
<div className="absolute inset-0 flex flex-col items-center justify-center">
{errorMessages.slice(0, Math.min(phase + 1, errorMessages.length)).map((msg, i) => (
<motion.div
key={i}
initial={{ opacity: 0, x: Math.random() * 200 - 100 }}
animate={{
opacity: [0, 1, 1, 0.5],
x: [Math.random() * 100 - 50, 0, Math.random() * 50 - 25],
}}
transition={{ duration: 0.5 }}
className="font-minecraft text-xl md:text-3xl text-destructive mb-2"
style={{
textShadow: '0 0 10px currentColor, 0 0 20px currentColor',
transform: `rotate(${Math.random() * 10 - 5}deg)`,
}}
>
{msg}
</motion.div>
))}
</div>
{/* Final message */}
{phase > 6 && (
<motion.div
initial={{ scale: 0 }}
animate={{ scale: [0, 1.2, 1] }}
className="absolute inset-0 flex items-center justify-center"
>
<div className="text-center">
<div className="font-minecraft text-4xl md:text-6xl text-primary text-glow-strong mb-4">
SYSTEM OVERFLOW
</div>
<div className="font-pixel text-lg text-foreground/80">
You broke the matrix. Congratulations.
</div>
<div className="font-pixel text-sm text-foreground/50 mt-4">
(Refreshing in a moment...)
</div>
</div>
</motion.div>
)}
{/* Glitch bars */}
{Array.from({ length: 10 }).map((_, i) => (
<div
key={i}
className="absolute bg-primary/50"
style={{
left: `${Math.random() * 100}%`,
top: `${Math.random() * 100}%`,
width: `${Math.random() * 300 + 50}px`,
height: `${Math.random() * 20 + 2}px`,
animation: `glitchShake ${0.1 + Math.random() * 0.2}s infinite`,
opacity: Math.random(),
}}
/>
))}
</motion.div>
);
};
export default GlitchCrash;
+82
View File
@@ -0,0 +1,82 @@
import { useState, useCallback, useRef } from 'react';
const MATRIX_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%&*!?<>[]{}アイウエオカキクケコサシスセソタチツテトナニヌネノ';
interface GlitchTextProps {
text: string;
className?: string;
glitchOnHover?: boolean;
as?: 'span' | 'h1' | 'h2' | 'h3' | 'h4' | 'p';
}
const GlitchText = ({
text,
className = '',
glitchOnHover = true,
as: Component = 'span'
}: GlitchTextProps) => {
const [displayText, setDisplayText] = useState(text);
const [isGlitching, setIsGlitching] = useState(false);
const intervalRef = useRef<NodeJS.Timeout | null>(null);
const iterationRef = useRef(0);
const getRandomChar = () => {
return MATRIX_CHARS[Math.floor(Math.random() * MATRIX_CHARS.length)];
};
const startGlitch = useCallback(() => {
if (!glitchOnHover || isGlitching) return;
setIsGlitching(true);
iterationRef.current = 0;
intervalRef.current = setInterval(() => {
setDisplayText(prev => {
return text
.split('')
.map((char, index) => {
if (char === ' ') return ' ';
// Gradually resolve characters from left to right
if (index < iterationRef.current) {
return text[index];
}
// Random chance to show original or glitch
return Math.random() > 0.5 ? getRandomChar() : char;
})
.join('');
});
iterationRef.current += 1;
// Complete after all characters resolved
if (iterationRef.current > text.length) {
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
setDisplayText(text);
setIsGlitching(false);
}
}, 50);
}, [text, glitchOnHover, isGlitching]);
const stopGlitch = useCallback(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
setDisplayText(text);
setIsGlitching(false);
}, [text]);
return (
<Component
className={`${className} ${isGlitching ? 'glitch-active' : ''}`}
onMouseEnter={startGlitch}
onMouseLeave={stopGlitch}
style={{ display: 'inline-block' }}
>
{displayText}
</Component>
);
};
export default GlitchText;
+148
View File
@@ -0,0 +1,148 @@
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import GlitchText from './GlitchText';
// Hacker-themed questions that any human would know
const QUESTIONS = [
{ q: "What key do you press to open a terminal? (Hint: between D and G)", answers: ["f", "f key"] },
{ q: "Complete: The Matrix has you, ___", answers: ["neo"] },
{ q: "What does 'www' stand for in a URL?", answers: ["world wide web", "worldwideweb"] },
{ q: "What color is the Matrix rain?", answers: ["green"] },
{ q: "What does 'ctrl+c' do?", answers: ["copy", "cancel", "stop", "interrupt"] },
{ q: "What number comes after 0 in binary?", answers: ["1", "one"] },
{ q: "What does 'IP' stand for in networking?", answers: ["internet protocol"] },
{ q: "What key exits most programs? (3 letters)", answers: ["esc", "escape"] },
{ q: "Red pill or blue pill - which reveals the truth?", answers: ["red", "red pill"] },
{ q: "What symbol starts most terminal commands?", answers: ["$", "/", ">", "dollar", "slash"] },
{ q: "What does 'USB' stand for?", answers: ["universal serial bus"] },
{ q: "What is localhost's IP address?", answers: ["127.0.0.1", "localhost"] },
{ q: "Complete: Hello, _____ (classic first program output)", answers: ["world"] },
{ q: "What animal is Linux's mascot?", answers: ["penguin", "tux"] },
{ q: "What does 'CPU' stand for?", answers: ["central processing unit"] },
];
const BYPASS_KEY = 'bypass-human-check';
const VERIFIED_KEY = 'human-verified';
interface HumanVerificationProps {
onVerified: () => void;
}
const HumanVerification = ({ onVerified }: HumanVerificationProps) => {
const [question] = useState(() => QUESTIONS[Math.floor(Math.random() * QUESTIONS.length)]);
const [answer, setAnswer] = useState('');
const [error, setError] = useState(false);
const [showHint, setShowHint] = useState(false);
// Check for bypass in URL
useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (params.has(BYPASS_KEY) || window.location.pathname.includes(BYPASS_KEY)) {
localStorage.setItem(VERIFIED_KEY, 'true');
onVerified();
}
}, [onVerified]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const normalizedAnswer = answer.toLowerCase().trim();
if (question.answers.some(a => normalizedAnswer === a.toLowerCase())) {
localStorage.setItem(VERIFIED_KEY, 'true');
onVerified();
} else {
setError(true);
setShowHint(true);
setTimeout(() => setError(false), 500);
}
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="fixed inset-0 z-[100] bg-background flex items-center justify-center p-4"
>
<div className="max-w-md w-full">
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ delay: 0.2 }}
className="border-2 border-primary box-glow p-6 bg-background"
>
{/* ASCII Art Header */}
<pre className="font-mono text-[8px] sm:text-[10px] text-primary text-center mb-4 leading-tight">
{`╔═══════════════════════════════════════╗
║ HUMAN VERIFICATION REQUIRED ║
╚═══════════════════════════════════════╝`}
</pre>
<div className="text-center mb-6">
<GlitchText
text="ACCESS CONTROL"
className="font-minecraft text-xl text-primary text-glow-strong"
/>
<p className="font-pixel text-xs text-foreground/60 mt-2">
Prove you are human to continue
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="border border-primary/30 p-4 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60 mb-2">&gt; QUERY:</p>
<p className="font-minecraft text-sm text-primary">{question.q}</p>
</div>
<div>
<input
type="text"
value={answer}
onChange={(e) => setAnswer(e.target.value)}
placeholder="&gt; Enter response..."
autoFocus
className={`w-full bg-background border-2 ${
error ? 'border-destructive animate-pulse' : 'border-primary/50'
} p-3 font-pixel text-sm text-foreground placeholder:text-foreground/30 focus:outline-none focus:border-primary transition-colors`}
/>
</div>
<AnimatePresence>
{showHint && (
<motion.p
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
className="font-pixel text-[10px] text-destructive"
>
ERROR: Invalid response. Retry required.
</motion.p>
)}
</AnimatePresence>
<button
type="submit"
className="w-full font-minecraft text-sm py-3 border-2 border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all duration-300 box-glow"
>
EXECUTE
</button>
</form>
<div className="mt-6 pt-4 border-t border-primary/20">
<p className="font-pixel text-[8px] text-foreground/30 text-center">
// Anti-bot verification protocol v1.0
</p>
</div>
</motion.div>
{/* Decorative terminal lines */}
<div className="mt-4 font-mono text-[10px] text-primary/50">
<p>&gt; Awaiting human verification...</p>
<p className="animate-pulse">&gt; _</p>
</div>
</div>
</motion.div>
);
};
export default HumanVerification;
export { VERIFIED_KEY, BYPASS_KEY };
+143
View File
@@ -0,0 +1,143 @@
import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
interface LoadingScreenProps {
isLoading: boolean;
}
const BOOT_MESSAGES = [
{ text: '> BIOS v3.14.159 initialized...', delay: 0 },
{ text: '> Loading kernel modules...', delay: 400 },
{ text: '> Establishing secure connection...', delay: 800 },
{ text: '> Decrypting user database...', delay: 1200 },
{ text: '> Bypassing firewall...', delay: 1600 },
{ text: '> Injecting payload...', delay: 2000 },
{ text: '> ACCESS GRANTED', delay: 2400, isSuccess: true },
];
const LoadingScreen = ({ isLoading }: LoadingScreenProps) => {
const [visibleLines, setVisibleLines] = useState<number[]>([]);
const [typedText, setTypedText] = useState<{ [key: number]: string }>({});
const [progress, setProgress] = useState(0);
const { playSound } = useSettings();
const hasPlayedSound = useRef<{ [key: number]: boolean }>({});
useEffect(() => {
if (!isLoading) return;
// Reset state when loading starts
setVisibleLines([]);
setTypedText({});
setProgress(0);
hasPlayedSound.current = {};
BOOT_MESSAGES.forEach((msg, index) => {
// Show line after delay
setTimeout(() => {
setVisibleLines(prev => [...prev, index]);
// Play boot sound for each line (only once)
if (!hasPlayedSound.current[index]) {
hasPlayedSound.current[index] = true;
if (msg.isSuccess) {
playSound('success');
} else {
playSound('boot');
}
}
// Type out the text character by character
const text = msg.text;
let charIndex = 0;
const typeInterval = setInterval(() => {
setTypedText(prev => ({
...prev,
[index]: text.slice(0, charIndex + 1)
}));
charIndex++;
if (charIndex >= text.length) {
clearInterval(typeInterval);
}
}, 30);
// Update progress
setProgress(Math.round(((index + 1) / BOOT_MESSAGES.length) * 100));
}, msg.delay);
});
}, [isLoading, playSound]);
return (
<AnimatePresence>
{isLoading && (
<motion.div
initial={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.5 }}
className="fixed inset-0 z-[9999] flex items-center justify-center bg-background"
>
<div className="w-full max-w-2xl px-6">
{/* ASCII Art Header */}
<pre className="font-mono text-primary text-glow text-xs md:text-sm mb-6 text-center">
{`
███╗ ███╗ █████╗ ████████╗██████╗ ██╗██╗ ██╗
████╗ ████║██╔══██╗╚══██╔══╝██╔══██╗██║╚██╗██╔╝
██╔████╔██║███████║ ██║ ██████╔╝██║ ╚███╔╝
██║╚██╔╝██║██╔══██║ ██║ ██╔══██╗██║ ██╔██╗
██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║██║██╔╝ ██╗
╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝
`}
</pre>
{/* Terminal Output */}
<div className="border border-primary/50 bg-background/80 p-4 font-mono text-sm box-glow min-h-[200px]">
{BOOT_MESSAGES.map((msg, index) => (
<motion.div
key={index}
initial={{ opacity: 0 }}
animate={{ opacity: visibleLines.includes(index) ? 1 : 0 }}
className={`mb-1 ${msg.isSuccess ? 'text-primary text-glow-strong font-bold' : 'text-primary/80 text-glow'}`}
>
{typedText[index] || ''}
{visibleLines.includes(index) && typedText[index]?.length < msg.text.length && (
<span className="animate-pulse"></span>
)}
</motion.div>
))}
{/* Blinking cursor at the end */}
{visibleLines.length === BOOT_MESSAGES.length && (
<motion.span
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-primary animate-pulse"
>
</motion.span>
)}
</div>
{/* Progress Bar */}
<div className="mt-4">
<div className="flex justify-between text-xs font-mono text-primary/70 mb-1">
<span>LOADING SYSTEM</span>
<span>{progress}%</span>
</div>
<div className="h-2 border border-primary/50 bg-background">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${progress}%` }}
transition={{ duration: 0.3 }}
className="h-full bg-primary box-glow"
/>
</div>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
);
};
export default LoadingScreen;
+39
View File
@@ -0,0 +1,39 @@
import { Outlet } from 'react-router-dom';
import { motion } from 'framer-motion';
import Sidebar from './Sidebar';
const MainLayout = () => {
return <motion.div initial={{
opacity: 0,
scale: 0.95
}} animate={{
opacity: 1,
scale: 1
}} transition={{
duration: 0.5
}} className="relative z-10 flex flex-col items-center pt-8 md:pt-12 px-4 w-full">
{/* Branding */}
<motion.h1 initial={{
opacity: 0,
y: -20
}} animate={{
opacity: 1,
y: 0
}} transition={{
delay: 0.3,
duration: 0.5
}} className="font-minecraft text-4xl md:text-5xl lg:text-6xl text-primary text-glow-strong mb-6">
<span className="inline-block translate-y-[0.35em]">~</span>$ whoami Jory
</motion.h1>
{/* Main Container */}
<div className="w-full max-w-[90vw] xl:max-w-[1200px] 2xl:max-w-[1400px] min-h-[55vh] md:h-[70vh] max-h-[750px] flex flex-col md:flex-row border-2 border-primary bg-background/60 box-glow-strong rounded-lg overflow-hidden">
<Sidebar />
{/* Content Area */}
<main className="flex-1 p-6 md:p-8 overflow-y-auto bg-background/40">
<Outlet />
</main>
</div>
</motion.div>;
};
export default MainLayout;
+111
View File
@@ -0,0 +1,111 @@
import { useState, useEffect } from 'react';
const MatrixCursor = () => {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [isHovering, setIsHovering] = useState(false);
const [isVisible, setIsVisible] = useState(false);
const [isTouchDevice, setIsTouchDevice] = useState(false);
useEffect(() => {
// Detect touch device - check for touch capability and if primary input is touch
const checkTouchDevice = () => {
const hasTouchScreen = 'ontouchstart' in window ||
navigator.maxTouchPoints > 0 ||
// @ts-ignore - msMaxTouchPoints is IE-specific
navigator.msMaxTouchPoints > 0;
// Also check if the device has a fine pointer (mouse)
const hasFinePrimary = window.matchMedia('(pointer: fine)').matches;
// Consider it a touch device if it has touch AND doesn't have fine pointer as primary
setIsTouchDevice(hasTouchScreen && !hasFinePrimary);
};
checkTouchDevice();
// Re-check on orientation change or resize (for hybrid devices)
window.addEventListener('resize', checkTouchDevice);
return () => {
window.removeEventListener('resize', checkTouchDevice);
};
}, []);
useEffect(() => {
// Don't set up mouse listeners on touch devices
if (isTouchDevice) {
document.body.classList.remove('matrix-cursor');
return;
}
const handleMouseMove = (e: MouseEvent) => {
setPosition({ x: e.clientX, y: e.clientY });
setIsVisible(true);
};
const handleMouseEnter = () => setIsVisible(true);
const handleMouseLeave = () => setIsVisible(false);
const handleHoverCheck = (e: MouseEvent) => {
const target = e.target as HTMLElement;
const isInteractive =
target.tagName === 'A' ||
target.tagName === 'BUTTON' ||
!!target.closest('a') ||
!!target.closest('button') ||
target.getAttribute('role') === 'button' ||
window.getComputedStyle(target).cursor === 'pointer';
setIsHovering(isInteractive);
};
// Hide cursor on any touch event (for hybrid devices)
const handleTouch = () => {
setIsVisible(false);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mousemove', handleHoverCheck);
document.addEventListener('mouseenter', handleMouseEnter);
document.addEventListener('mouseleave', handleMouseLeave);
document.addEventListener('touchstart', handleTouch, { passive: true });
// Add cursor class to body
document.body.classList.add('matrix-cursor');
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mousemove', handleHoverCheck);
document.removeEventListener('mouseenter', handleMouseEnter);
document.removeEventListener('mouseleave', handleMouseLeave);
document.removeEventListener('touchstart', handleTouch);
document.body.classList.remove('matrix-cursor');
};
}, [isTouchDevice]);
// Don't render anything on touch devices or when not visible
if (isTouchDevice || !isVisible) return null;
return (
<>
{/* Crosshair */}
<div
className="matrix-cursor-crosshair"
style={{
left: position.x,
top: position.y,
}}
/>
{/* Center dot */}
<div
className={`matrix-cursor-dot ${isHovering ? 'hovering' : ''}`}
style={{
left: position.x,
top: position.y,
}}
/>
</>
);
};
export default MatrixCursor;
+80
View File
@@ -0,0 +1,80 @@
import { useEffect, useRef } from 'react';
interface MatrixRainProps {
color?: string;
}
const MatrixRain = ({ color = '#00FF00' }: MatrixRainProps) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const colorRef = useRef(color);
useEffect(() => {
colorRef.current = color;
}, [color]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const fontSize = 16;
let columns: number;
let rainDrops: number[] = [];
const katakana = 'アァカサタナハマヤャラワガザダバパイィキシチニヒミリヰギジヂビピウゥクスツヌフムユュルグズブヅプエェケセテネヘメレヱゲゼデベペオォコソトノホモヨョロヲゴゾドボポヴッン';
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';
const alphabet = katakana + latin + nums;
const init = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
columns = Math.floor(canvas.width / fontSize);
rainDrops = [];
for (let x = 0; x < columns; x++) {
rainDrops[x] = Math.random() * canvas.height / fontSize;
}
};
init();
const draw = () => {
ctx.fillStyle = 'rgba(0, 0, 0, 0.04)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = colorRef.current;
ctx.font = `${fontSize}px monospace`;
for (let i = 0; i < rainDrops.length; i++) {
const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length));
ctx.fillText(text, i * fontSize, rainDrops[i] * fontSize);
if (rainDrops[i] * fontSize > canvas.height && Math.random() > 0.975) {
rainDrops[i] = 0;
}
rainDrops[i]++;
}
};
const interval = setInterval(draw, 30);
const handleResize = () => init();
window.addEventListener('resize', handleResize);
return () => {
clearInterval(interval);
window.removeEventListener('resize', handleResize);
};
}, []);
return (
<canvas
ref={canvasRef}
className="fixed inset-0 z-0 opacity-60"
/>
);
};
export default MatrixRain;
+71
View File
@@ -0,0 +1,71 @@
import { useMemo } from 'react';
import CodeBlock from './CodeBlock';
interface MessageContentProps {
content: string;
isLoading?: boolean;
}
const MessageContent = ({ content, isLoading }: MessageContentProps) => {
const parts = useMemo(() => {
// Parse content for code blocks
const codeBlockRegex = /```(\w*)\n?([\s\S]*?)```/g;
const result: { type: 'text' | 'code'; content: string; language?: string }[] = [];
let lastIndex = 0;
let match;
while ((match = codeBlockRegex.exec(content)) !== null) {
// Add text before code block
if (match.index > lastIndex) {
const textBefore = content.slice(lastIndex, match.index);
if (textBefore.trim()) {
result.push({ type: 'text', content: textBefore });
}
}
// Add code block
result.push({
type: 'code',
language: match[1] || 'text',
content: match[2].trim(),
});
lastIndex = match.index + match[0].length;
}
// Add remaining text
if (lastIndex < content.length) {
const remaining = content.slice(lastIndex);
if (remaining.trim()) {
result.push({ type: 'text', content: remaining });
}
}
// If no code blocks found, return entire content as text
if (result.length === 0 && content) {
result.push({ type: 'text', content });
}
return result;
}, [content]);
return (
<div className="font-pixel text-sm text-primary">
{parts.map((part, index) => (
<div key={index}>
{part.type === 'code' ? (
<CodeBlock code={part.content} language={part.language || 'text'} />
) : (
<p className="whitespace-pre-wrap break-words">{part.content}</p>
)}
</div>
))}
{isLoading && content === '' && (
<span className="animate-pulse"></span>
)}
</div>
);
};
export default MessageContent;
+171
View File
@@ -0,0 +1,171 @@
import { useEffect } from 'react';
import { Play, Pause, Volume2, Music2, SkipBack, SkipForward, Loader2 } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
import { useMusic } from '@/contexts/MusicContext';
import { motion, AnimatePresence } from 'framer-motion';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useState } from 'react';
const MusicPlayer = () => {
const [isExpanded, setIsExpanded] = useState(false);
const { playSound, soundEnabled } = useSettings();
const {
isPlaying,
isBuffering,
volume,
stations,
currentIndex,
selectedStation,
setVolume,
togglePlay,
playNext,
playPrevious,
fetchStations,
} = useMusic();
useEffect(() => {
if (isExpanded) {
fetchStations();
}
}, [isExpanded, fetchStations]);
const handleButtonClick = (action: () => void) => {
if (soundEnabled) {
playSound('click');
}
action();
};
return (
<div
className="fixed bottom-4 left-4 z-50"
onMouseEnter={() => setIsExpanded(true)}
onMouseLeave={() => setIsExpanded(false)}
>
<AnimatePresence>
{isExpanded ? (
<motion.div
initial={{ opacity: 0, scale: 0.8, x: -20 }}
animate={{ opacity: 1, scale: 1, x: 0 }}
exit={{ opacity: 0, scale: 0.8, x: -20 }}
transition={{ duration: 0.2 }}
className="bg-background/95 border border-primary box-glow p-3 w-64"
>
{/* Header */}
<div className="flex items-center gap-2 mb-3">
<Music2 className="w-4 h-4 text-primary" />
<span className="font-minecraft text-sm text-primary text-glow">Radio</span>
{isBuffering && (
<Loader2 className="w-3 h-3 text-primary animate-spin ml-auto" />
)}
</div>
{/* Now Playing with Tooltip */}
<Tooltip>
<TooltipTrigger asChild>
<div className="mb-3 p-2 bg-primary/10 border border-primary/30 cursor-help">
<p className="font-pixel text-xs text-primary truncate">
{selectedStation?.name || 'No station selected'}
</p>
<p className="font-pixel text-[10px] text-foreground/60 truncate">
{selectedStation?.country || 'Press play to start'}
</p>
{isPlaying && selectedStation && !isBuffering && (
<div className="flex gap-0.5 mt-1">
<span className="w-0.5 h-2 bg-primary animate-pulse" style={{ animationDelay: '0ms' }} />
<span className="w-0.5 h-2 bg-primary animate-pulse" style={{ animationDelay: '150ms' }} />
<span className="w-0.5 h-2 bg-primary animate-pulse" style={{ animationDelay: '300ms' }} />
</div>
)}
{isBuffering && (
<p className="font-pixel text-[10px] text-primary/60 mt-1">Buffering...</p>
)}
</div>
</TooltipTrigger>
{selectedStation && (
<TooltipContent side="top" className="bg-background border border-primary p-2 max-w-[200px]">
<div className="font-pixel text-xs space-y-1">
<p className="text-primary font-bold">{selectedStation.name}</p>
<p className="text-foreground/70">Country: {selectedStation.country || 'Unknown'}</p>
{selectedStation.bitrate > 0 && (
<p className="text-foreground/70">Bitrate: {selectedStation.bitrate}kbps</p>
)}
{selectedStation.tags && (
<p className="text-foreground/70 truncate">Tags: {selectedStation.tags.split(',').slice(0, 3).join(', ')}</p>
)}
</div>
</TooltipContent>
)}
</Tooltip>
{/* Playback Controls */}
<div className="flex items-center justify-center gap-2 mb-3">
<button
onClick={() => handleButtonClick(playPrevious)}
className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
aria-label="Previous station"
>
<SkipBack size={14} />
</button>
<button
onClick={() => handleButtonClick(togglePlay)}
className="p-2.5 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
disabled={isBuffering}
aria-label={isBuffering ? 'Loading' : isPlaying ? 'Pause' : 'Play'}
>
{isBuffering ? (
<Loader2 size={16} className="animate-spin" />
) : isPlaying ? (
<Pause size={16} />
) : (
<Play size={16} />
)}
</button>
<button
onClick={() => handleButtonClick(playNext)}
className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
aria-label="Next station"
>
<SkipForward size={14} />
</button>
</div>
{/* Volume */}
<div className="flex items-center gap-2">
<Volume2 size={12} className="text-primary" />
<input
type="range"
min="0"
max="100"
value={volume}
onChange={(e) => setVolume(Number(e.target.value))}
aria-label="Volume control"
className="flex-1 h-1 bg-primary/30 appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-2 [&::-webkit-slider-thumb]:h-2 [&::-webkit-slider-thumb]:bg-primary"
/>
<span className="font-pixel text-[10px] text-primary w-8">{volume}%</span>
</div>
{/* Station count */}
<p className="font-pixel text-[9px] text-foreground/40 text-center mt-2">
{stations.length > 0 ? `${currentIndex + 1}/${stations.length} stations` : 'Loading...'}
</p>
</motion.div>
) : (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="p-3 bg-background/90 border border-primary box-glow cursor-pointer"
>
<Music2 className="w-5 h-5 text-primary text-glow" />
{isPlaying && (
<div className="absolute -top-1 -right-1 w-2 h-2 bg-primary rounded-full animate-pulse" />
)}
</motion.div>
)}
</AnimatePresence>
</div>
);
};
export default MusicPlayer;
+28
View File
@@ -0,0 +1,28 @@
import { NavLink as RouterNavLink, NavLinkProps } from "react-router-dom";
import { forwardRef } from "react";
import { cn } from "@/lib/utils";
interface NavLinkCompatProps extends Omit<NavLinkProps, "className"> {
className?: string;
activeClassName?: string;
pendingClassName?: string;
}
const NavLink = forwardRef<HTMLAnchorElement, NavLinkCompatProps>(
({ className, activeClassName, pendingClassName, to, ...props }, ref) => {
return (
<RouterNavLink
ref={ref}
to={to}
className={({ isActive, isPending }) =>
cn(className, isActive && activeClassName, isPending && pendingClassName)
}
{...props}
/>
);
},
);
NavLink.displayName = "NavLink";
export { NavLink };
+145
View File
@@ -0,0 +1,145 @@
import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Settings, Monitor, Volume2, Cpu, X, Contrast } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
import CryptoConsentModal from './CryptoConsentModal';
interface SettingsPanelProps {
onToggleTheme: () => void;
isRedTheme: boolean;
}
const SettingsPanel = ({ onToggleTheme, isRedTheme }: SettingsPanelProps) => {
const [isOpen, setIsOpen] = useState(false);
const [showCryptoModal, setShowCryptoModal] = useState(false);
const { crtEnabled, setCrtEnabled, soundEnabled, setSoundEnabled, cryptoConsent, playSound } = useSettings();
const handleToggle = (setter: (value: boolean) => void, currentValue: boolean) => {
playSound('click');
setter(!currentValue);
};
return (
<>
<button
onClick={() => {
playSound('click');
setIsOpen(!isOpen);
}}
aria-label="Open settings"
className="fixed top-4 right-4 z-[150] p-2 border border-primary text-primary bg-background/80 transition-all duration-300 hover:bg-primary hover:text-background box-glow"
>
<Settings size={20} className={isOpen ? 'animate-spin' : ''} />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 100 }}
className="fixed top-16 right-4 z-[150] w-72 border-2 border-primary bg-background p-4 box-glow"
>
<div className="flex items-center justify-between mb-4">
<h2 className="font-minecraft text-lg text-primary text-glow">Settings</h2>
<button
onClick={() => setIsOpen(false)}
aria-label="Close settings"
className="text-primary hover:text-primary/80"
>
<X size={16} />
</button>
</div>
<div className="space-y-4">
{/* Theme Toggle */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Contrast size={16} className="text-primary" />
<span className="font-pixel text-sm text-foreground/90">Color Theme</span>
</div>
<button
onClick={onToggleTheme}
className="px-3 py-1 text-xs font-pixel border border-primary transition-all duration-300 bg-transparent text-primary hover:bg-primary hover:text-background"
>
{isRedTheme ? 'RED' : 'GREEN'}
</button>
</div>
{/* CRT Toggle */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Monitor size={16} className="text-primary" />
<span className="font-pixel text-sm text-foreground/90">CRT Effects</span>
</div>
<button
onClick={() => handleToggle(setCrtEnabled, crtEnabled)}
className={`w-12 h-6 rounded-full border border-primary transition-all duration-300 ${
crtEnabled ? 'bg-primary' : 'bg-transparent'
}`}
>
<div
className={`w-4 h-4 rounded-full bg-background border border-primary transition-transform duration-300 ${
crtEnabled ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
{/* Sound Toggle */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Volume2 size={16} className="text-primary" />
<span className="font-pixel text-sm text-foreground/90">Sound Effects</span>
</div>
<button
onClick={() => handleToggle(setSoundEnabled, soundEnabled)}
className={`w-12 h-6 rounded-full border border-primary transition-all duration-300 ${
soundEnabled ? 'bg-primary' : 'bg-transparent'
}`}
>
<div
className={`w-4 h-4 rounded-full bg-background border border-primary transition-transform duration-300 ${
soundEnabled ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
{/* Crypto Consent */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Cpu size={16} className="text-primary" />
<span className="font-pixel text-sm text-foreground/90">CPU Mining</span>
</div>
<button
onClick={() => {
playSound('click');
setShowCryptoModal(true);
}}
className={`px-3 py-1 text-xs font-pixel border border-primary transition-all duration-300 ${
cryptoConsent
? 'bg-primary text-background'
: 'bg-transparent text-primary hover:bg-primary hover:text-background'
}`}
>
{cryptoConsent ? 'ON' : 'OFF'}
</button>
</div>
</div>
<div className="mt-4 pt-4 border-t border-primary/30">
<p className="font-pixel text-xs text-muted-foreground">
Settings are saved locally
</p>
</div>
</motion.div>
)}
</AnimatePresence>
<CryptoConsentModal isOpen={showCryptoModal} onClose={() => setShowCryptoModal(false)} />
</>
);
};
export default SettingsPanel;
+139
View File
@@ -0,0 +1,139 @@
import { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import { useSettings } from '@/contexts/SettingsContext';
import { ChevronDown, Menu } from 'lucide-react';
const navItems = [
{ path: '/', label: 'Home' },
{ path: '/about', label: 'About Me' },
{ path: '/projects', label: 'Projects' },
{ path: '/resources', label: 'Resources' },
{ path: '/links', label: 'Links' },
{ path: '/ai', label: 'AI Chat' },
{ path: '/music', label: 'Music Player' },
{ path: '/games', label: 'Arcade' },
{ path: '/faq', label: 'FAQ' },
];
const Sidebar = () => {
const location = useLocation();
const { playSound } = useSettings();
const [isExpanded, setIsExpanded] = useState(false);
const currentPage = navItems.find(item => item.path === location.pathname)?.label || 'Menu';
const toggleMenu = () => {
setIsExpanded(!isExpanded);
playSound('click');
};
return (
<aside className="w-full md:w-[230px] lg:w-[250px] h-auto md:h-full flex flex-col border-b-2 md:border-b-0 md:border-r-2 border-primary bg-background/70 box-glow shrink-0">
{/* Mobile Toggle Header */}
<button
onClick={toggleMenu}
className="md:hidden flex items-center justify-between w-full p-4 font-minecraft text-lg text-primary text-glow"
>
<div className="flex items-center gap-2">
<Menu size={20} />
<span>{currentPage}</span>
</div>
<motion.div
animate={{ rotate: isExpanded ? 180 : 0 }}
transition={{ duration: 0.2 }}
>
<ChevronDown size={20} />
</motion.div>
</button>
{/* Desktop Navigation - Always visible */}
<nav className="hidden md:block flex-grow overflow-hidden p-4 md:p-5">
{navItems.map((item, index) => {
const isActive = location.pathname === item.path;
return (
<motion.div
key={item.path}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.1 }}
>
<Link
to={item.path}
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className={cn(
"group relative block py-4 px-4 font-minecraft text-lg text-primary border-b border-primary/30",
"transition-all duration-300 text-glow",
"hover:bg-primary/20 hover:scale-105 hover:box-glow",
isActive && "bg-primary/20 box-glow"
)}
>
{item.label}
<span className="absolute right-4 text-primary animate-blink opacity-0 transition-opacity duration-200 group-hover:opacity-100 pointer-events-none">
{'>_'}
</span>
</Link>
</motion.div>
);
})}
</nav>
{/* Mobile Navigation - Collapsible */}
<AnimatePresence>
{isExpanded && (
<motion.nav
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.2 }}
className="md:hidden overflow-hidden border-t border-primary/30"
>
{navItems.map((item, index) => {
const isActive = location.pathname === item.path;
return (
<motion.div
key={item.path}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.05 }}
>
<Link
to={item.path}
onClick={() => {
playSound('click');
setIsExpanded(false);
}}
className={cn(
"group relative block py-3 px-4 font-minecraft text-base text-primary border-b border-primary/30",
"transition-all duration-300 text-glow",
"hover:bg-primary/20",
isActive && "bg-primary/20 box-glow"
)}
>
{item.label}
<span className="absolute right-4 text-primary animate-blink opacity-0 transition-opacity duration-200 group-hover:opacity-100 pointer-events-none">
{'>_'}
</span>
</Link>
</motion.div>
);
})}
</motion.nav>
)}
</AnimatePresence>
{/* Desktop Footer */}
<div className="hidden md:block p-4 border-t border-primary/30">
<p className="font-pixel text-sm text-primary text-glow text-center">
Access Granted
</p>
</div>
</aside>
);
};
export default Sidebar;
+209
View File
@@ -0,0 +1,209 @@
import { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { Terminal, X } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
const commands: Record<string, string> = {
'/home': '/',
'/about': '/about',
'/me': '/about',
'/projects': '/projects',
'/proj': '/projects',
'/resources': '/resources',
'/res': '/resources',
'/links': '/links',
'/faq': '/faq',
'/games': '/games',
'/arcade': '/games',
'/tetris': '/games/tetris',
'/pacman': '/games/pacman',
'/snake': '/games/snake',
'/breakout': '/games/breakout',
'/music': '/music',
'/m': '/music',
'/ai': '/ai',
'/chat': '/ai',
};
const helpText = `Available commands:
/home - Navigate to Home
/about, /me - Navigate to About Me
/projects, /proj - Navigate to Projects
/resources, /res - Navigate to Resources
/links - Navigate to Links
/faq - Navigate to FAQ
/games, /arcade - Browse Arcade games
/tetris - Play Tetris
/pacman - Play Pac-Man
/snake - Play Snake
/breakout - Play Breakout
/music, /m - Navigate to Music Player
/ai, /chat - Navigate to AI Chat
/help, /h - Show this help message
/clear, /c - Clear terminal output`;
const TerminalCommand = () => {
const [isOpen, setIsOpen] = useState(false);
const [input, setInput] = useState('');
const [output, setOutput] = useState<string[]>(['Type /help for available commands']);
const inputRef = useRef<HTMLInputElement>(null);
const outputRef = useRef<HTMLDivElement>(null);
const navigate = useNavigate();
const { playSound } = useSettings();
useEffect(() => {
if (isOpen && inputRef.current) {
inputRef.current.focus();
}
}, [isOpen]);
useEffect(() => {
if (outputRef.current) {
outputRef.current.scrollTop = outputRef.current.scrollHeight;
}
}, [output]);
// Keyboard shortcut to toggle terminal
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Don't trigger if already in an input field
const isInputFocused = document.activeElement?.tagName === 'INPUT' ||
document.activeElement?.tagName === 'TEXTAREA';
if (e.key === '`' || (e.ctrlKey && e.key === '/')) {
e.preventDefault();
setIsOpen(prev => !prev);
playSound('beep');
}
// Open terminal when pressing "/" (only if not in input)
if (e.key === '/' && !isOpen && !isInputFocused) {
e.preventDefault();
setIsOpen(true);
playSound('beep');
// Pre-fill with "/" so user can continue typing command
setTimeout(() => setInput('/'), 50);
}
if (e.key === 'Escape' && isOpen) {
setIsOpen(false);
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isOpen, playSound]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const trimmedInput = input.trim().toLowerCase();
if (!trimmedInput) return;
playSound('click');
setOutput(prev => [...prev, `> ${input}`]);
if (trimmedInput === '/help' || trimmedInput === '/h') {
setOutput(prev => [...prev, helpText]);
} else if (trimmedInput === '/hint') {
setOutput(prev => [...prev,
'Hidden feature detected in system...',
'Hint: Old-school gamers know a certain cheat code.',
'Think NES, 1986, Contra... 30 lives anyone?',
'The sequence uses arrow keys and two letters.'
]);
} else if (trimmedInput === '/clear' || trimmedInput === '/c') {
setOutput(['Terminal cleared. Type /help for commands.']);
} else if (commands[trimmedInput]) {
setOutput(prev => [...prev, `Navigating to ${trimmedInput.slice(1)}...`]);
playSound('beep');
setTimeout(() => {
navigate(commands[trimmedInput]);
setIsOpen(false);
}, 300);
} else {
setOutput(prev => [...prev, `Command not found: ${trimmedInput}`, 'Type /help for available commands']);
}
setInput('');
};
return (
<>
{/* Terminal Toggle Button - aligned with music player */}
<motion.button
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: 0.5 }}
onClick={() => {
setIsOpen(true);
playSound('beep');
}}
className="fixed bottom-4 right-4 z-[60] p-3 border-2 border-primary bg-background text-primary hover:bg-primary hover:text-background transition-all duration-300 box-glow"
title="Open Terminal (` or Ctrl+/)"
>
<Terminal className="w-5 h-5" />
</motion.button>
{/* Terminal Window */}
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: 20, scale: 0.95 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 20, scale: 0.95 }}
className="fixed bottom-24 right-4 z-[200] w-[90vw] max-w-md border-2 border-primary bg-background/95 backdrop-blur-sm box-glow-strong"
>
{/* Terminal Header */}
<div className="flex items-center justify-between px-4 py-2 border-b border-primary bg-primary/10">
<div className="flex items-center gap-2">
<Terminal size={16} className="text-primary" />
<span className="font-minecraft text-sm text-primary text-glow">terminal@my-site.lol</span>
</div>
<button
onClick={() => setIsOpen(false)}
aria-label="Close terminal"
className="text-primary hover:text-primary/70 transition-colors"
>
<X size={16} />
</button>
</div>
{/* Terminal Output */}
<div
ref={outputRef}
className="h-48 overflow-y-auto p-4 font-mono text-sm text-primary/90"
>
{output.map((line, i) => (
<div key={i} className="whitespace-pre-wrap mb-1">
{line}
</div>
))}
</div>
{/* Terminal Input */}
<form onSubmit={handleSubmit} className="border-t border-primary/50">
<div className="flex items-center px-4 py-3">
<span className="text-primary font-mono mr-2">{'>'}</span>
<input
ref={inputRef}
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
className="flex-1 bg-transparent border-none outline-none font-mono text-primary placeholder-primary/40"
placeholder="Enter command..."
autoComplete="off"
spellCheck={false}
/>
<span className="text-primary animate-pulse">_</span>
</div>
</form>
</motion.div>
)}
</AnimatePresence>
</>
);
};
export default TerminalCommand;
+50
View File
@@ -0,0 +1,50 @@
import { useState, useEffect } from 'react';
import { useSettings } from '@/contexts/SettingsContext';
interface TypingTextProps {
text: string;
className?: string;
speed?: number;
delay?: number;
onComplete?: () => void;
}
const TypingText = ({ text, className = '', speed = 50, delay = 0, onComplete }: TypingTextProps) => {
const [displayedText, setDisplayedText] = useState('');
const [isTyping, setIsTyping] = useState(false);
const { playSound } = useSettings();
useEffect(() => {
const startTimeout = setTimeout(() => {
setIsTyping(true);
}, delay);
return () => clearTimeout(startTimeout);
}, [delay]);
useEffect(() => {
if (!isTyping) return;
if (displayedText.length < text.length) {
const timeout = setTimeout(() => {
setDisplayedText(text.slice(0, displayedText.length + 1));
playSound('click');
}, speed);
return () => clearTimeout(timeout);
} else {
onComplete?.();
}
}, [displayedText, text, speed, isTyping, playSound, onComplete]);
return (
<span className={className}>
{displayedText}
{displayedText.length < text.length && (
<span className="animate-pulse"></span>
)}
</span>
);
};
export default TypingText;
+52
View File
@@ -0,0 +1,52 @@
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item ref={ref} className={cn("border-b", className)} {...props} />
));
AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
className,
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
+104
View File
@@ -0,0 +1,104 @@
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";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
+43
View File
@@ -0,0 +1,43 @@
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 p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} />
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h5 ref={ref} className={cn("mb-1 font-medium leading-none tracking-tight", className)} {...props} />
),
);
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} {...props} />
),
);
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };
+5
View File
@@ -0,0 +1,5 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };
+38
View File
@@ -0,0 +1,38 @@
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/lib/utils";
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
{...props}
/>
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image ref={ref} className={cn("aspect-square h-full w-full", className)} {...props} />
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className)}
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };
+29
View File
@@ -0,0 +1,29 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge, badgeVariants };
+90
View File
@@ -0,0 +1,90 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode;
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);
Breadcrumb.displayName = "Breadcrumb";
const BreadcrumbList = React.forwardRef<HTMLOListElement, React.ComponentPropsWithoutRef<"ol">>(
({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className,
)}
{...props}
/>
),
);
BreadcrumbList.displayName = "BreadcrumbList";
const BreadcrumbItem = React.forwardRef<HTMLLIElement, React.ComponentPropsWithoutRef<"li">>(
({ className, ...props }, ref) => (
<li ref={ref} className={cn("inline-flex items-center gap-1.5", className)} {...props} />
),
);
BreadcrumbItem.displayName = "BreadcrumbItem";
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean;
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a";
return <Comp ref={ref} className={cn("transition-colors hover:text-foreground", className)} {...props} />;
});
BreadcrumbLink.displayName = "BreadcrumbLink";
const BreadcrumbPage = React.forwardRef<HTMLSpanElement, React.ComponentPropsWithoutRef<"span">>(
({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
),
);
BreadcrumbPage.displayName = "BreadcrumbPage";
const BreadcrumbSeparator = ({ children, className, ...props }: React.ComponentProps<"li">) => (
<li role="presentation" aria-hidden="true" className={cn("[&>svg]:size-3.5", className)} {...props}>
{children ?? <ChevronRight />}
</li>
);
BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
const BreadcrumbEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
);
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};
+47
View File
@@ -0,0 +1,47 @@
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 ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
},
);
Button.displayName = "Button";
export { Button, buttonVariants };
+54
View File
@@ -0,0 +1,54 @@
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
function Calendar({ className, classNames, showOutsideDays = true, ...props }: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
day: cn(buttonVariants({ variant: "ghost" }), "h-9 w-9 p-0 font-normal aria-selected:opacity-100"),
day_range_end: "day-range-end",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ ..._props }) => <ChevronLeft className="h-4 w-4" />,
IconRight: ({ ..._props }) => <ChevronRight className="h-4 w-4" />,
}}
{...props}
/>
);
}
Calendar.displayName = "Calendar";
export { Calendar };
+43
View File
@@ -0,0 +1,43 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
),
);
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-tight", className)} {...props} />
),
);
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
),
);
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />,
);
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
),
);
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+224
View File
@@ -0,0 +1,224 @@
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;
}
const Carousel = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & CarouselProps>(
({ orientation = "horizontal", opts, setApi, plugins, className, children, ...props }, ref) => {
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
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
},
);
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel();
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className)}
{...props}
/>
</div>
);
},
);
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const { orientation } = useCarousel();
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn("min-w-0 shrink-0 grow-0 basis-full", orientation === "horizontal" ? "pl-4" : "pt-4", className)}
{...props}
/>
);
},
);
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef<HTMLButtonElement, React.ComponentProps<typeof Button>>(
({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
);
},
);
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef<HTMLButtonElement, React.ComponentProps<typeof Button>>(
({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
);
},
);
CarouselNext.displayName = "CarouselNext";
export { type CarouselApi, Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext };
+303
View File
@@ -0,0 +1,303 @@
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;
}
const ChartContainer = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
config: ChartConfig;
children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>["children"];
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
return (
<ChartContext.Provider value={{ config }}>
<div
data-chart={chartId}
ref={ref}
className={cn(
"flex aspect-video justify-center text-xs [&_.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-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.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 [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",
className,
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
);
});
ChartContainer.displayName = "Chart";
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;
const ChartTooltipContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: "line" | "dot" | "dashed";
nameKey?: string;
labelKey?: string;
}
>(
(
{
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
},
ref,
) => {
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
ref={ref}
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background 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(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
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="font-mono font-medium tabular-nums text-foreground">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
);
})}
</div>
</div>
);
},
);
ChartTooltipContent.displayName = "ChartTooltip";
const ChartLegend = RechartsPrimitive.Legend;
const ChartLegendContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean;
nameKey?: string;
}
>(({ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey }, ref) => {
const { config } = useChart();
if (!payload?.length) {
return null;
}
return (
<div
ref={ref}
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("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground")}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
);
})}
</div>
);
});
ChartLegendContent.displayName = "ChartLegend";
// 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 };
+26
View File
@@ -0,0 +1,26 @@
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
+9
View File
@@ -0,0 +1,9 @@
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
+132
View File
@@ -0,0 +1,132 @@
import * as React from "react";
import { type DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils";
import { Dialog, DialogContent } from "@/components/ui/dialog";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className,
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
interface CommandDialogProps extends DialogProps {}
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[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>
);
};
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => <CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm" {...props} />);
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className,
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator ref={ref} className={cn("-mx-1 h-px bg-border", className)} {...props} />
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
className,
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)} {...props} />;
};
CommandShortcut.displayName = "CommandShortcut";
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};
+178
View File
@@ -0,0 +1,178 @@
import * as React from "react";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const ContextMenu = ContextMenuPrimitive.Root;
const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
const ContextMenuGroup = ContextMenuPrimitive.Group;
const ContextMenuPortal = ContextMenuPrimitive.Portal;
const ContextMenuSub = ContextMenuPrimitive.Sub;
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
));
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",
className,
)}
{...props}
/>
));
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 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",
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
));
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
/>
));
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
));
ContextMenuCheckboxItem.displayName = ContextMenuPrimitive.CheckboxItem.displayName;
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
));
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold text-foreground", inset && "pl-8", className)}
{...props}
/>
));
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-border", className)} {...props} />
));
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
const ContextMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)} {...props} />;
};
ContextMenuShortcut.displayName = "ContextMenuShortcut";
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
};
+95
View File
@@ -0,0 +1,95 @@
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
+87
View File
@@ -0,0 +1,87 @@
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils";
const Drawer = ({ shouldScaleBackground = true, ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root shouldScaleBackground={shouldScaleBackground} {...props} />
);
Drawer.displayName = "Drawer";
const DrawerTrigger = DrawerPrimitive.Trigger;
const DrawerPortal = DrawerPrimitive.Portal;
const DrawerClose = DrawerPrimitive.Close;
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay ref={ref} className={cn("fixed inset-0 z-50 bg-black/80", className)} {...props} />
));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className,
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
));
DrawerContent.displayName = "DrawerContent";
const DrawerHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)} {...props} />
);
DrawerHeader.displayName = "DrawerHeader";
const DrawerFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />
);
DrawerFooter.displayName = "DrawerFooter";
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};
+179
View File
@@ -0,0 +1,179 @@
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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",
className,
)}
{...props}
/>
));
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} />;
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};
+129
View File
@@ -0,0 +1,129 @@
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import { Controller, ControllerProps, FieldPath, FieldValues, FormProvider, useFormContext } 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, formState } = useFormContext();
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);
const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
);
},
);
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return <Label ref={ref} className={cn(error && "text-destructive", className)} htmlFor={formItemId} {...props} />;
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef<React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot>>(
({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
aria-invalid={!!error}
{...props}
/>
);
},
);
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return <p ref={ref} id={formDescriptionId} className={cn("text-sm text-muted-foreground", className)} {...props} />;
},
);
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
if (!body) {
return null;
}
return (
<p ref={ref} id={formMessageId} className={cn("text-sm font-medium text-destructive", className)} {...props}>
{body}
</p>
);
},
);
FormMessage.displayName = "FormMessage";
export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField };
+27
View File
@@ -0,0 +1,27 @@
import * as React from "react";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { cn } from "@/lib/utils";
const HoverCard = HoverCardPrimitive.Root;
const HoverCardTrigger = HoverCardPrimitive.Trigger;
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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",
className,
)}
{...props}
/>
));
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;
export { HoverCard, HoverCardTrigger, HoverCardContent };
+61
View File
@@ -0,0 +1,61 @@
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { Dot } from "lucide-react";
import { cn } from "@/lib/utils";
const InputOTP = React.forwardRef<React.ElementRef<typeof OTPInput>, React.ComponentPropsWithoutRef<typeof OTPInput>>(
({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn("flex items-center gap-2 has-[:disabled]:opacity-50", containerClassName)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
),
);
InputOTP.displayName = "InputOTP";
const InputOTPGroup = React.forwardRef<React.ElementRef<"div">, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => <div ref={ref} className={cn("flex items-center", className)} {...props} />,
);
InputOTPGroup.displayName = "InputOTPGroup";
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index];
return (
<div
ref={ref}
className={cn(
"relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-2 ring-ring ring-offset-background",
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink h-4 w-px bg-foreground duration-1000" />
</div>
)}
</div>
);
});
InputOTPSlot.displayName = "InputOTPSlot";
const InputOTPSeparator = React.forwardRef<React.ElementRef<"div">, React.ComponentPropsWithoutRef<"div">>(
({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Dot />
</div>
),
);
InputOTPSeparator.displayName = "InputOTPSeparator";
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Input.displayName = "Input";
export { Input };
+17
View File
@@ -0,0 +1,17 @@
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const labelVariants = cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70");
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };
+207
View File
@@ -0,0 +1,207 @@
import * as React from "react";
import * as MenubarPrimitive from "@radix-ui/react-menubar";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const MenubarMenu = MenubarPrimitive.Menu;
const MenubarGroup = MenubarPrimitive.Group;
const MenubarPortal = MenubarPrimitive.Portal;
const MenubarSub = MenubarPrimitive.Sub;
const MenubarRadioGroup = MenubarPrimitive.RadioGroup;
const Menubar = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Root
ref={ref}
className={cn("flex h-10 items-center space-x-1 rounded-md border bg-background p-1", className)}
{...props}
/>
));
Menubar.displayName = MenubarPrimitive.Root.displayName;
const MenubarTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Trigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
/>
));
MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName;
const MenubarSubTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<MenubarPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
));
MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName;
const MenubarSubContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 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",
className,
)}
{...props}
/>
));
MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName;
const MenubarContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>
>(({ className, align = "start", alignOffset = -4, sideOffset = 8, ...props }, ref) => (
<MenubarPrimitive.Portal>
<MenubarPrimitive.Content
ref={ref}
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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",
className,
)}
{...props}
/>
</MenubarPrimitive.Portal>
));
MenubarContent.displayName = MenubarPrimitive.Content.displayName;
const MenubarItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
inset && "pl-8",
className,
)}
{...props}
/>
));
MenubarItem.displayName = MenubarPrimitive.Item.displayName;
const MenubarCheckboxItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<MenubarPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
));
MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName;
const MenubarRadioItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<MenubarPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
));
MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName;
const MenubarLabel = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
{...props}
/>
));
MenubarLabel.displayName = MenubarPrimitive.Label.displayName;
const MenubarSeparator = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
));
MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName;
const MenubarShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)} {...props} />;
};
MenubarShortcut.displayname = "MenubarShortcut";
export {
Menubar,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarItem,
MenubarSeparator,
MenubarLabel,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarPortal,
MenubarSubContent,
MenubarSubTrigger,
MenubarGroup,
MenubarSub,
MenubarShortcut,
};
+120
View File
@@ -0,0 +1,120 @@
import * as React from "react";
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu";
import { cva } from "class-variance-authority";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn("relative z-10 flex max-w-max flex-1 items-center justify-center", className)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
));
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName;
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn("group flex flex-1 list-none items-center justify-center space-x-1", className)}
{...props}
/>
));
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName;
const NavigationMenuItem = NavigationMenuPrimitive.Item;
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50",
);
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDown
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
));
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName;
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
"left-0 top-0 w-full 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 md:absolute md:w-auto",
className,
)}
{...props}
/>
));
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName;
const NavigationMenuLink = NavigationMenuPrimitive.Link;
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn("absolute left-0 top-full flex justify-center")}>
<NavigationMenuPrimitive.Viewport
className={cn(
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
className,
)}
ref={ref}
{...props}
/>
</div>
));
NavigationMenuViewport.displayName = NavigationMenuPrimitive.Viewport.displayName;
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
className,
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
</NavigationMenuPrimitive.Indicator>
));
NavigationMenuIndicator.displayName = NavigationMenuPrimitive.Indicator.displayName;
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
};
+81
View File
@@ -0,0 +1,81 @@
import * as React from "react";
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
import { ButtonProps, buttonVariants } from "@/components/ui/button";
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
role="navigation"
aria-label="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
);
Pagination.displayName = "Pagination";
const PaginationContent = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(
({ className, ...props }, ref) => (
<ul ref={ref} className={cn("flex flex-row items-center gap-1", className)} {...props} />
),
);
PaginationContent.displayName = "PaginationContent";
const PaginationItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ className, ...props }, ref) => (
<li ref={ref} className={cn("", className)} {...props} />
));
PaginationItem.displayName = "PaginationItem";
type PaginationLinkProps = {
isActive?: boolean;
} & Pick<ButtonProps, "size"> &
React.ComponentProps<"a">;
const PaginationLink = ({ className, isActive, size = "icon", ...props }: PaginationLinkProps) => (
<a
aria-current={isActive ? "page" : undefined}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className,
)}
{...props}
/>
);
PaginationLink.displayName = "PaginationLink";
const PaginationPrevious = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to previous page" size="default" className={cn("gap-1 pl-2.5", className)} {...props}>
<ChevronLeft className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
);
PaginationPrevious.displayName = "PaginationPrevious";
const PaginationNext = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to next page" size="default" className={cn("gap-1 pr-2.5", className)} {...props}>
<span>Next</span>
<ChevronRight className="h-4 w-4" />
</PaginationLink>
);
PaginationNext.displayName = "PaginationNext";
const PaginationEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => (
<span aria-hidden className={cn("flex h-9 w-9 items-center justify-center", className)} {...props}>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
);
PaginationEllipsis.displayName = "PaginationEllipsis";
export {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
};
+29
View File
@@ -0,0 +1,29 @@
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent };
+23
View File
@@ -0,0 +1,23 @@
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/lib/utils";
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn("relative h-4 w-full overflow-hidden rounded-full bg-secondary", className)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;
export { Progress };
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return <RadioGroupPrimitive.Root className={cn("grid gap-2", className)} {...props} ref={ref} />;
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };
+37
View File
@@ -0,0 +1,37 @@
import { GripVertical } from "lucide-react";
import * as ResizablePrimitive from "react-resizable-panels";
import { cn } from "@/lib/utils";
const ResizablePanelGroup = ({ className, ...props }: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col", className)}
{...props}
/>
);
const ResizablePanel = ResizablePrimitive.Panel;
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className,
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };
+38
View File
@@ -0,0 +1,38 @@
import * as React from "react";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { cn } from "@/lib/utils";
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props}>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
));
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent p-[1px]",
className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
export { ScrollArea, ScrollBar };
+143
View File
@@ -0,0 +1,143 @@
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label ref={ref} className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)} {...props} />
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
+20
View File
@@ -0,0 +1,20 @@
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "@/lib/utils";
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = "horizontal", decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn("shrink-0 bg-border", orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", className)}
{...props}
/>
));
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };
+107
View File
@@ -0,0 +1,107 @@
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const Sheet = SheetPrimitive.Root;
const SheetTrigger = SheetPrimitive.Trigger;
const SheetClose = SheetPrimitive.Close;
const SheetPortal = SheetPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
},
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<React.ElementRef<typeof SheetPrimitive.Content>, SheetContentProps>(
({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
),
);
SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
SheetHeader.displayName = "SheetHeader";
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
SheetFooter.displayName = "SheetFooter";
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title ref={ref} className={cn("text-lg font-semibold text-foreground", className)} {...props} />
));
SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetOverlay,
SheetPortal,
SheetTitle,
SheetTrigger,
};
+637
View File
@@ -0,0 +1,637 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { VariantProps, cva } from "class-variance-authority";
import { PanelLeft } from "lucide-react";
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent } from "@/components/ui/sheet";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
const SIDEBAR_COOKIE_NAME = "sidebar:state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContext = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContext | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
const SidebarProvider = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
>(({ defaultOpen = true, open: openProp, onOpenChange: setOpenProp, className, style, children, ...props }, ref) => {
const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) {
setOpenProp(openState);
} else {
_setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
[setOpenProp, open],
);
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContext>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar", className)}
ref={ref}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
);
});
SidebarProvider.displayName = "SidebarProvider";
const Sidebar = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}
>(({ side = "left", variant = "sidebar", collapsible = "offcanvas", className, children, ...props }, ref) => {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
className={cn("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground", className)}
ref={ref}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-mobile="true"
className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
ref={ref}
className="group peer hidden text-sidebar-foreground md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
>
{/* This is what handles the sidebar gap on desktop */}
<div
className={cn(
"relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon]",
)}
/>
<div
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
className,
)}
{...props}
>
<div
data-sidebar="sidebar"
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
>
{children}
</div>
</div>
</div>
);
});
Sidebar.displayName = "Sidebar";
const SidebarTrigger = React.forwardRef<React.ElementRef<typeof Button>, React.ComponentProps<typeof Button>>(
({ className, onClick, ...props }, ref) => {
const { toggleSidebar } = useSidebar();
return (
<Button
ref={ref}
data-sidebar="trigger"
variant="ghost"
size="icon"
className={cn("h-7 w-7", className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeft />
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
},
);
SidebarTrigger.displayName = "SidebarTrigger";
const SidebarRail = React.forwardRef<HTMLButtonElement, React.ComponentProps<"button">>(
({ className, ...props }, ref) => {
const { toggleSidebar } = useSidebar();
return (
<button
ref={ref}
data-sidebar="rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 hover:after:bg-sidebar-border sm:flex",
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
)}
{...props}
/>
);
},
);
SidebarRail.displayName = "SidebarRail";
const SidebarInset = React.forwardRef<HTMLDivElement, React.ComponentProps<"main">>(({ className, ...props }, ref) => {
return (
<main
ref={ref}
className={cn(
"relative flex min-h-svh flex-1 flex-col bg-background",
"peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
className,
)}
{...props}
/>
);
});
SidebarInset.displayName = "SidebarInset";
const SidebarInput = React.forwardRef<React.ElementRef<typeof Input>, React.ComponentProps<typeof Input>>(
({ className, ...props }, ref) => {
return (
<Input
ref={ref}
data-sidebar="input"
className={cn(
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
className,
)}
{...props}
/>
);
},
);
SidebarInput.displayName = "SidebarInput";
const SidebarHeader = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return <div ref={ref} data-sidebar="header" className={cn("flex flex-col gap-2 p-2", className)} {...props} />;
});
SidebarHeader.displayName = "SidebarHeader";
const SidebarFooter = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return <div ref={ref} data-sidebar="footer" className={cn("flex flex-col gap-2 p-2", className)} {...props} />;
});
SidebarFooter.displayName = "SidebarFooter";
const SidebarSeparator = React.forwardRef<React.ElementRef<typeof Separator>, React.ComponentProps<typeof Separator>>(
({ className, ...props }, ref) => {
return (
<Separator
ref={ref}
data-sidebar="separator"
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
);
},
);
SidebarSeparator.displayName = "SidebarSeparator";
const SidebarContent = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className,
)}
{...props}
/>
);
});
SidebarContent.displayName = "SidebarContent";
const SidebarGroup = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
});
SidebarGroup.displayName = "SidebarGroup";
const SidebarGroupLabel = React.forwardRef<HTMLDivElement, React.ComponentProps<"div"> & { asChild?: boolean }>(
({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "div";
return (
<Comp
ref={ref}
data-sidebar="group-label"
className={cn(
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className,
)}
{...props}
/>
);
},
);
SidebarGroupLabel.displayName = "SidebarGroupLabel";
const SidebarGroupAction = React.forwardRef<HTMLButtonElement, React.ComponentProps<"button"> & { asChild?: boolean }>(
({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
ref={ref}
data-sidebar="group-action"
className={cn(
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
},
);
SidebarGroupAction.displayName = "SidebarGroupAction";
const SidebarGroupContent = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(
({ className, ...props }, ref) => (
<div ref={ref} data-sidebar="group-content" className={cn("w-full text-sm", className)} {...props} />
),
);
SidebarGroupContent.displayName = "SidebarGroupContent";
const SidebarMenu = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(({ className, ...props }, ref) => (
<ul ref={ref} data-sidebar="menu" className={cn("flex w-full min-w-0 flex-col gap-1", className)} {...props} />
));
SidebarMenu.displayName = "SidebarMenu";
const SidebarMenuItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ className, ...props }, ref) => (
<li ref={ref} data-sidebar="menu-item" className={cn("group/menu-item relative", className)} {...props} />
));
SidebarMenuItem.displayName = "SidebarMenuItem";
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>
>(({ asChild = false, isActive = false, variant = "default", size = "default", tooltip, className, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
ref={ref}
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
);
if (!tooltip) {
return button;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
};
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent side="right" align="center" hidden={state !== "collapsed" || isMobile} {...tooltip} />
</Tooltip>
);
});
SidebarMenuButton.displayName = "SidebarMenuButton";
const SidebarMenuAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean;
showOnHover?: boolean;
}
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
ref={ref}
data-sidebar="menu-action"
className={cn(
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
className,
)}
{...props}
/>
);
});
SidebarMenuAction.displayName = "SidebarMenuAction";
const SidebarMenuBadge = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(
({ className, ...props }, ref) => (
<div
ref={ref}
data-sidebar="menu-badge"
className={cn(
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
),
);
SidebarMenuBadge.displayName = "SidebarMenuBadge";
const SidebarMenuSkeleton = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
showIcon?: boolean;
}
>(({ className, showIcon = false, ...props }, ref) => {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`;
}, []);
return (
<div
ref={ref}
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />}
<Skeleton
className="h-4 max-w-[--skeleton-width] flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
);
});
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton";
const SidebarMenuSub = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(
({ className, ...props }, ref) => (
<ul
ref={ref}
data-sidebar="menu-sub"
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
),
);
SidebarMenuSub.displayName = "SidebarMenuSub";
const SidebarMenuSubItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ ...props }, ref) => (
<li ref={ref} {...props} />
));
SidebarMenuSubItem.displayName = "SidebarMenuSubItem";
const SidebarMenuSubButton = React.forwardRef<
HTMLAnchorElement,
React.ComponentProps<"a"> & {
asChild?: boolean;
size?: "sm" | "md";
isActive?: boolean;
}
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a";
return (
<Comp
ref={ref}
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
});
SidebarMenuSubButton.displayName = "SidebarMenuSubButton";
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
};
+7
View File
@@ -0,0 +1,7 @@
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} />;
}
export { Skeleton };
+23
View File
@@ -0,0 +1,23 @@
import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import { cn } from "@/lib/utils";
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn("relative flex w-full touch-none select-none items-center", className)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
));
Slider.displayName = SliderPrimitive.Root.displayName;
export { Slider };
+27
View File
@@ -0,0 +1,27 @@
import { useTheme } from "next-themes";
import { Toaster as Sonner, toast } from "sonner";
type ToasterProps = React.ComponentProps<typeof Sonner>;
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
);
};
export { Toaster, toast };
+27
View File
@@ -0,0 +1,27 @@
import * as React from "react";
import * as SwitchPrimitives from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",
)}
/>
</SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };
+72
View File
@@ -0,0 +1,72 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
),
);
Table.displayName = "Table";
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />,
);
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
),
);
TableBody.displayName = "TableBody";
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tfoot ref={ref} className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)} {...props} />
),
);
TableFooter.displayName = "TableFooter";
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50", className)}
{...props}
/>
),
);
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className,
)}
{...props}
/>
),
);
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<td ref={ref} className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)} {...props} />
),
);
TableCell.displayName = "TableCell";
const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
({ className, ...props }, ref) => (
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
),
);
TableCaption.displayName = "TableCaption";
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
+53
View File
@@ -0,0 +1,53 @@
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "@/lib/utils";
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className,
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
className,
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className,
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };
+21
View File
@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "@/lib/utils";
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
{...props}
/>
);
});
Textarea.displayName = "Textarea";
export { Textarea };
+111
View File
@@ -0,0 +1,111 @@
import * as React from "react";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className,
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive: "destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} />;
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors group-[.destructive]:border-muted/40 hover:bg-secondary group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 group-[.destructive]:focus:ring-destructive disabled:pointer-events-none disabled:opacity-50",
className,
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-destructive-foreground hover:text-foreground group-[.destructive]:hover:text-destructive-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-destructive",
className,
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title ref={ref} className={cn("text-sm font-semibold", className)} {...props} />
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description ref={ref} className={cn("text-sm opacity-90", className)} {...props} />
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
};
+24
View File
@@ -0,0 +1,24 @@
import { useToast } from "@/hooks/use-toast";
import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport } from "@/components/ui/toast";
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && <ToastDescription>{description}</ToastDescription>}
</div>
{action}
<ToastClose />
</Toast>
);
})}
<ToastViewport />
</ToastProvider>
);
}
+49
View File
@@ -0,0 +1,49 @@
import * as React from "react";
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
import { type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { toggleVariants } from "@/components/ui/toggle";
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
size: "default",
variant: "default",
});
const ToggleGroup = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> & VariantProps<typeof toggleVariants>
>(({ className, variant, size, children, ...props }, ref) => (
<ToggleGroupPrimitive.Root ref={ref} className={cn("flex items-center justify-center gap-1", className)} {...props}>
<ToggleGroupContext.Provider value={{ variant, size }}>{children}</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
));
ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName;
const ToggleGroupItem = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> & VariantProps<typeof toggleVariants>
>(({ className, children, variant, size, ...props }, ref) => {
const context = React.useContext(ToggleGroupContext);
return (
<ToggleGroupPrimitive.Item
ref={ref}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
className,
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
);
});
ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;
export { ToggleGroup, ToggleGroupItem };
+37
View File
@@ -0,0 +1,37 @@
import * as React from "react";
import * as TogglePrimitive from "@radix-ui/react-toggle";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline: "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>
>(({ className, variant, size, ...props }, ref) => (
<TogglePrimitive.Root ref={ref} className={cn(toggleVariants({ variant, size, className }))} {...props} />
));
Toggle.displayName = TogglePrimitive.Root.displayName;
export { Toggle, toggleVariants };
+28
View File
@@ -0,0 +1,28 @@
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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",
className,
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
+3
View File
@@ -0,0 +1,3 @@
import { useToast, toast } from "@/hooks/use-toast";
export { useToast, toast };
+209
View File
@@ -0,0 +1,209 @@
import { createContext, useContext, useState, useRef, useCallback, useEffect, ReactNode } from 'react';
export interface Station {
stationuuid: string;
name: string;
url: string;
favicon: string;
country: string;
tags: string;
bitrate: number;
}
interface MusicContextType {
isPlaying: boolean;
isBuffering: boolean;
volume: number;
stations: Station[];
currentIndex: number;
selectedStation: Station | null;
hasFetched: boolean;
setVolume: (volume: number) => void;
playStation: (station: Station, index: number) => void;
togglePlay: () => void;
playNext: () => void;
playPrevious: () => void;
fetchStations: () => Promise<void>;
stopAudio: () => void;
}
const MusicContext = createContext<MusicContextType | undefined>(undefined);
export const MusicProvider = ({ children }: { children: ReactNode }) => {
const [isPlaying, setIsPlaying] = useState(false);
const [isBuffering, setIsBuffering] = useState(false);
const [volume, setVolumeState] = useState(50);
const [stations, setStations] = useState<Station[]>([]);
const [currentIndex, setCurrentIndex] = useState(0);
const [selectedStation, setSelectedStation] = useState<Station | null>(null);
const [hasFetched, setHasFetched] = useState(false);
const [failedStations, setFailedStations] = useState<Set<string>>(new Set());
const audioRef = useRef<HTMLAudioElement | null>(null);
// Update volume on audio element when volume state changes
useEffect(() => {
if (audioRef.current) {
audioRef.current.volume = volume / 100;
}
}, [volume]);
const setVolume = useCallback((newVolume: number) => {
setVolumeState(newVolume);
}, []);
const fetchStations = useCallback(async () => {
if (hasFetched) return;
try {
const response = await fetch(
'https://de1.api.radio-browser.info/json/stations/topclick/100'
);
if (!response.ok) throw new Error('Failed to fetch stations');
const data: Station[] = await response.json();
const validStations = data.filter(s => !failedStations.has(s.stationuuid));
setStations(validStations);
setHasFetched(true);
} catch (err) {
console.error('Error fetching stations:', err);
}
}, [hasFetched, failedStations]);
const stopCurrentAudio = useCallback(() => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current.src = '';
audioRef.current.onplay = null;
audioRef.current.onpause = null;
audioRef.current.onerror = null;
audioRef.current.onwaiting = null;
audioRef.current.onplaying = null;
audioRef.current = null;
}
setIsBuffering(false);
}, []);
const playStation = useCallback((station: Station, index: number) => {
stopCurrentAudio();
setIsBuffering(true);
const audio = new Audio(station.url);
audio.volume = volume / 100;
audioRef.current = audio;
audio.onerror = () => {
console.error('Failed to play station:', station.name);
setFailedStations(prev => new Set(prev).add(station.stationuuid));
setIsPlaying(false);
setIsBuffering(false);
setSelectedStation(null);
};
audio.onwaiting = () => {
setIsBuffering(true);
};
audio.onplaying = () => {
setIsBuffering(false);
setIsPlaying(true);
};
audio.onplay = () => {
setIsPlaying(true);
};
audio.onpause = () => {
if (audioRef.current === audio) {
setIsPlaying(false);
}
};
audio.play().catch((err) => {
console.error('Playback error:', err);
setFailedStations(prev => new Set(prev).add(station.stationuuid));
setIsPlaying(false);
setIsBuffering(false);
});
setSelectedStation(station);
setCurrentIndex(index);
}, [volume, stopCurrentAudio]);
const togglePlay = useCallback(() => {
if (!audioRef.current || !selectedStation) {
if (stations.length > 0) {
playStation(stations[0], 0);
}
return;
}
if (isPlaying) {
audioRef.current.pause();
} else {
setIsBuffering(true);
audioRef.current.play().catch(() => {
setIsBuffering(false);
});
}
}, [selectedStation, stations, playStation, isPlaying]);
const playNext = useCallback(() => {
if (stations.length === 0) return;
const nextIndex = (currentIndex + 1) % stations.length;
playStation(stations[nextIndex], nextIndex);
}, [currentIndex, stations, playStation]);
const playPrevious = useCallback(() => {
if (stations.length === 0) return;
const prevIndex = currentIndex === 0 ? stations.length - 1 : currentIndex - 1;
playStation(stations[prevIndex], prevIndex);
}, [currentIndex, stations, playStation]);
// Handle media keys
useEffect(() => {
const handleMediaKey = (e: KeyboardEvent) => {
if (e.key === 'MediaPlayPause') {
e.preventDefault();
togglePlay();
} else if (e.key === 'MediaTrackNext') {
e.preventDefault();
playNext();
} else if (e.key === 'MediaTrackPrevious') {
e.preventDefault();
playPrevious();
}
};
window.addEventListener('keydown', handleMediaKey);
return () => window.removeEventListener('keydown', handleMediaKey);
}, [togglePlay, playNext, playPrevious]);
return (
<MusicContext.Provider
value={{
isPlaying,
isBuffering,
volume,
stations,
currentIndex,
selectedStation,
hasFetched,
setVolume,
playStation,
togglePlay,
playNext,
playPrevious,
fetchStations,
stopAudio: stopCurrentAudio,
}}
>
{children}
</MusicContext.Provider>
);
};
export const useMusic = () => {
const context = useContext(MusicContext);
if (context === undefined) {
throw new Error('useMusic must be used within a MusicProvider');
}
return context;
};
+180
View File
@@ -0,0 +1,180 @@
import { createContext, useContext, useState, useEffect, useRef, useCallback, ReactNode } from 'react';
type SoundType = 'click' | 'beep' | 'hover' | 'boot' | 'success' | 'error';
interface SettingsContextType {
crtEnabled: boolean;
setCrtEnabled: (enabled: boolean) => void;
soundEnabled: boolean;
setSoundEnabled: (enabled: boolean) => void;
cryptoConsent: boolean;
setCryptoConsent: (consent: boolean) => void;
playSound: (type: SoundType) => void;
hashrate: number;
setHashrate: (rate: number) => void;
totalHashes: number;
setTotalHashes: (hashes: number) => void;
acceptedHashes: number;
setAcceptedHashes: (hashes: number) => void;
}
const SettingsContext = createContext<SettingsContextType | undefined>(undefined);
export const SettingsProvider = ({ children }: { children: ReactNode }) => {
const [crtEnabled, setCrtEnabled] = useState(() => {
const saved = localStorage.getItem('crtEnabled');
return saved !== null ? JSON.parse(saved) : true;
});
const [soundEnabled, setSoundEnabled] = useState(() => {
const saved = localStorage.getItem('soundEnabled');
return saved !== null ? JSON.parse(saved) : true;
});
const [cryptoConsent, setCryptoConsent] = useState(() => {
const saved = localStorage.getItem('cryptoConsent');
return saved !== null ? JSON.parse(saved) : false;
});
const [hashrate, setHashrate] = useState(0);
const [totalHashes, setTotalHashes] = useState(0);
const [acceptedHashes, setAcceptedHashes] = useState(0);
// Single AudioContext instance, persisted across renders
const audioContextRef = useRef<AudioContext | null>(null);
// Use ref to always have current soundEnabled value in callbacks
const soundEnabledRef = useRef(soundEnabled);
useEffect(() => {
soundEnabledRef.current = soundEnabled;
}, [soundEnabled]);
// Get or create AudioContext
const getAudioContext = useCallback(() => {
if (!audioContextRef.current) {
audioContextRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();
}
// Resume if suspended (browser autoplay policy)
if (audioContextRef.current.state === 'suspended') {
audioContextRef.current.resume();
}
return audioContextRef.current;
}, []);
// Cleanup on unmount
useEffect(() => {
return () => {
if (audioContextRef.current) {
audioContextRef.current.close();
audioContextRef.current = null;
}
};
}, []);
useEffect(() => {
localStorage.setItem('crtEnabled', JSON.stringify(crtEnabled));
}, [crtEnabled]);
useEffect(() => {
localStorage.setItem('soundEnabled', JSON.stringify(soundEnabled));
}, [soundEnabled]);
useEffect(() => {
localStorage.setItem('cryptoConsent', JSON.stringify(cryptoConsent));
}, [cryptoConsent]);
const playSound = useCallback((type: SoundType) => {
// Use ref to ensure we always have the latest value
if (!soundEnabledRef.current) return;
try {
const audioContext = getAudioContext();
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
const now = audioContext.currentTime;
switch (type) {
case 'click':
oscillator.frequency.value = 800;
gainNode.gain.value = 0.1;
oscillator.start(now);
oscillator.stop(now + 0.05);
break;
case 'beep':
oscillator.frequency.value = 1200;
gainNode.gain.value = 0.08;
oscillator.start(now);
oscillator.stop(now + 0.1);
break;
case 'hover':
oscillator.frequency.value = 600;
gainNode.gain.value = 0.05;
oscillator.start(now);
oscillator.stop(now + 0.03);
break;
case 'boot':
oscillator.type = 'sawtooth';
oscillator.frequency.setValueAtTime(200, now);
oscillator.frequency.exponentialRampToValueAtTime(800, now + 0.2);
gainNode.gain.setValueAtTime(0.1, now);
gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.3);
oscillator.start(now);
oscillator.stop(now + 0.3);
break;
case 'success':
oscillator.frequency.setValueAtTime(800, now);
oscillator.frequency.setValueAtTime(1200, now + 0.1);
gainNode.gain.value = 0.1;
oscillator.start(now);
oscillator.stop(now + 0.2);
break;
case 'error':
oscillator.type = 'square';
oscillator.frequency.value = 150;
gainNode.gain.value = 0.08;
oscillator.start(now);
oscillator.stop(now + 0.15);
break;
}
} catch (e) {
// Silently fail if audio context has issues
console.warn('Audio playback failed:', e);
}
}, [getAudioContext]);
return (
<SettingsContext.Provider
value={{
crtEnabled,
setCrtEnabled,
soundEnabled,
setSoundEnabled,
cryptoConsent,
setCryptoConsent,
playSound,
hashrate,
setHashrate,
totalHashes,
setTotalHashes,
acceptedHashes,
setAcceptedHashes,
}}
>
{children}
</SettingsContext.Provider>
);
};
export const useSettings = () => {
const context = useContext(SettingsContext);
if (context === undefined) {
throw new Error('useSettings must be used within a SettingsProvider');
}
return context;
};
+19
View File
@@ -0,0 +1,19 @@
import * as React from "react";
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
}
+186
View File
@@ -0,0 +1,186 @@
import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const;
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString();
}
type ActionType = typeof actionTypes;
type Action =
| {
type: ActionType["ADD_TOAST"];
toast: ToasterToast;
}
| {
type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast>;
}
| {
type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"];
}
| {
type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) => (t.id === action.toast.id ? { ...t, ...action.toast } : t)),
};
case "DISMISS_TOAST": {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
};
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
});
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss();
},
},
});
return {
id: id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
};
}
export { useToast, toast };
+118
View File
@@ -0,0 +1,118 @@
import { useState, useEffect, useCallback } from 'react';
interface GameDimensions {
cellSize: number;
canvasWidth: number;
canvasHeight: number;
isMobile: boolean;
}
interface UseGameDimensionsOptions {
gridWidth: number;
gridHeight: number;
minCellSize?: number;
maxCellSize?: number;
padding?: number;
}
export const useGameDimensions = ({
gridWidth,
gridHeight,
minCellSize = 12,
maxCellSize = 40,
padding = 120, // Space for controls and UI
}: UseGameDimensionsOptions): GameDimensions => {
const calculateDimensions = useCallback((): GameDimensions => {
const isMobile = window.innerWidth < 768;
const availableWidth = window.innerWidth - (isMobile ? 32 : padding);
const availableHeight = window.innerHeight - (isMobile ? 200 : padding);
// Calculate cell size based on available space
const cellFromWidth = Math.floor(availableWidth / gridWidth);
const cellFromHeight = Math.floor(availableHeight / gridHeight);
// Use the smaller of the two to ensure it fits
let cellSize = Math.min(cellFromWidth, cellFromHeight);
// Clamp to min/max
cellSize = Math.max(minCellSize, Math.min(maxCellSize, cellSize));
return {
cellSize,
canvasWidth: cellSize * gridWidth,
canvasHeight: cellSize * gridHeight,
isMobile,
};
}, [gridWidth, gridHeight, minCellSize, maxCellSize, padding]);
const [dimensions, setDimensions] = useState<GameDimensions>(calculateDimensions);
useEffect(() => {
const handleResize = () => {
setDimensions(calculateDimensions());
};
window.addEventListener('resize', handleResize);
// Also handle orientation change on mobile
window.addEventListener('orientationchange', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
window.removeEventListener('orientationchange', handleResize);
};
}, [calculateDimensions]);
return dimensions;
};
// Hook to handle browser fullscreen API
export const useBrowserFullscreen = () => {
const [isBrowserFullscreen, setIsBrowserFullscreen] = useState(false);
const enterFullscreen = useCallback(async (element?: HTMLElement) => {
const target = element || document.documentElement;
try {
if (target.requestFullscreen) {
await target.requestFullscreen();
} else if ((target as any).webkitRequestFullscreen) {
await (target as any).webkitRequestFullscreen();
} else if ((target as any).msRequestFullscreen) {
await (target as any).msRequestFullscreen();
}
setIsBrowserFullscreen(true);
} catch (err) {
console.log('Fullscreen not supported or denied');
}
}, []);
const exitFullscreen = useCallback(async () => {
try {
if (document.exitFullscreen) {
await document.exitFullscreen();
} else if ((document as any).webkitExitFullscreen) {
await (document as any).webkitExitFullscreen();
} else if ((document as any).msExitFullscreen) {
await (document as any).msExitFullscreen();
}
setIsBrowserFullscreen(false);
} catch (err) {
console.log('Exit fullscreen failed');
}
}, []);
useEffect(() => {
const handleChange = () => {
setIsBrowserFullscreen(!!document.fullscreenElement);
};
document.addEventListener('fullscreenchange', handleChange);
document.addEventListener('webkitfullscreenchange', handleChange);
return () => {
document.removeEventListener('fullscreenchange', handleChange);
document.removeEventListener('webkitfullscreenchange', handleChange);
};
}, []);
return { isBrowserFullscreen, enterFullscreen, exitFullscreen };
};
+64
View File
@@ -0,0 +1,64 @@
import { useState, useEffect, useCallback } from 'react';
const KONAMI_CODE = [
'ArrowUp', 'ArrowUp',
'ArrowDown', 'ArrowDown',
'ArrowLeft', 'ArrowRight',
'ArrowLeft', 'ArrowRight',
'KeyB', 'KeyA'
];
interface UseKonamiCodeReturn {
activated: boolean;
reset: () => void;
}
export const useKonamiCode = (): UseKonamiCodeReturn => {
const [keysPressed, setKeysPressed] = useState<string[]>([]);
const [activated, setActivated] = useState(false);
const [lastKeyTime, setLastKeyTime] = useState(0);
const reset = useCallback(() => {
setActivated(false);
setKeysPressed([]);
}, []);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const now = Date.now();
// Reset if more than 2 seconds between keys
if (now - lastKeyTime > 2000) {
setKeysPressed([]);
}
setLastKeyTime(now);
const key = e.code;
setKeysPressed(prev => {
const newKeys = [...prev, key];
// Check if the sequence matches so far
const expectedKey = KONAMI_CODE[newKeys.length - 1];
if (key !== expectedKey) {
// Wrong key, reset
return [];
}
// Check if complete
if (newKeys.length === KONAMI_CODE.length) {
setActivated(true);
return [];
}
return newKeys;
});
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [lastKeyTime]);
return { activated, reset };
};
+60
View File
@@ -0,0 +1,60 @@
import { useRef, useCallback } from 'react';
/**
* Hook for handling press-and-hold touch interactions
* Fires the callback continuously while the button is held
*/
export const useTouchHold = (
callback: () => void,
interval = 100,
initialDelay = 150
) => {
const intervalRef = useRef<NodeJS.Timeout | null>(null);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const start = useCallback(() => {
// Fire immediately on touch
callback();
// Start repeating after initial delay
timeoutRef.current = setTimeout(() => {
intervalRef.current = setInterval(() => {
callback();
}, interval);
}, initialDelay);
}, [callback, interval, initialDelay]);
const stop = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}, []);
const handlers = {
onTouchStart: (e: React.TouchEvent) => {
e.preventDefault();
start();
},
onTouchEnd: (e: React.TouchEvent) => {
e.preventDefault();
stop();
},
onTouchCancel: (e: React.TouchEvent) => {
e.preventDefault();
stop();
},
// Also support mouse for testing on desktop
onMouseDown: start,
onMouseUp: stop,
onMouseLeave: stop,
};
return handlers;
};
export default useTouchHold;
+539
View File
@@ -0,0 +1,539 @@
/* Pixelify Sans loaded from Google Fonts in index.html */
/* Self-hosted Minecraftia font with font-display: swap for better performance */
@font-face {
font-family: 'Minecraftia';
src: url('/fonts/Minecraftia.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Dark Reader extension compatibility - prevent it from breaking our styles */
html[data-darkreader-mode="dynamic"],
html[data-darkreader-scheme="dark"] {
/* Force our own background */
background-color: #000 !important;
}
/* Tell Dark Reader to leave our app alone */
html {
color-scheme: dark;
}
@layer base {
:root {
/* Matrix Green Theme - ALL colors are green-based */
--background: 0 0% 0%;
--foreground: 0 0% 100%;
--card: 0 0% 0%;
--card-foreground: 120 100% 50%;
--popover: 0 0% 5%;
--popover-foreground: 120 100% 50%;
--primary: 120 100% 50%;
--primary-foreground: 0 0% 0%;
--secondary: 120 100% 15%;
--secondary-foreground: 120 100% 50%;
--muted: 120 20% 10%;
--muted-foreground: 120 30% 60%;
--accent: 120 100% 50%;
--accent-foreground: 0 0% 0%;
--destructive: 120 100% 50%;
--destructive-foreground: 0 0% 0%;
--border: 120 100% 50%;
--input: 120 100% 25%;
--ring: 120 100% 50%;
--radius: 0.5rem;
/* Custom Matrix Variables */
--glow-color: 120 100% 50%;
--scanline-color-1: 120 100% 50%;
--scanline-color-2: 120 100% 50%;
--sidebar-background: 0 0% 0%;
--sidebar-foreground: 120 100% 50%;
--sidebar-primary: 120 100% 50%;
--sidebar-primary-foreground: 0 0% 0%;
--sidebar-accent: 120 100% 15%;
--sidebar-accent-foreground: 120 100% 50%;
--sidebar-border: 120 100% 50%;
--sidebar-ring: 120 100% 50%;
}
/* Red Theme Variant - ALL colors are red-based */
.red-theme {
--card-foreground: 0 100% 50%;
--popover-foreground: 0 100% 50%;
--primary: 0 100% 50%;
--primary-foreground: 0 0% 0%;
--secondary: 0 100% 15%;
--secondary-foreground: 0 100% 50%;
--muted: 0 20% 10%;
--muted-foreground: 0 30% 60%;
--accent: 0 100% 50%;
--accent-foreground: 0 0% 0%;
--destructive: 0 100% 50%;
--destructive-foreground: 0 0% 0%;
--border: 0 100% 50%;
--input: 0 100% 25%;
--ring: 0 100% 50%;
--glow-color: 0 100% 50%;
--scanline-color-1: 0 100% 50%;
--scanline-color-2: 0 100% 50%;
--sidebar-foreground: 0 100% 50%;
--sidebar-primary: 0 100% 50%;
--sidebar-accent: 0 100% 15%;
--sidebar-accent-foreground: 0 100% 50%;
--sidebar-border: 0 100% 50%;
--sidebar-ring: 0 100% 50%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
font-family: 'Pixelify Sans', monospace;
overflow-x: hidden;
}
h1, h2, h3, h4, h5, h6 {
font-family: 'Minecraftia', 'Pixelify Sans', monospace;
}
/* Ensure text selection follows theme */
::selection {
background: hsl(var(--primary) / 0.3);
color: hsl(var(--primary));
}
/* Ensure focus rings follow theme */
*:focus {
outline-color: hsl(var(--primary));
}
*:focus-visible {
outline-color: hsl(var(--primary));
}
/* Links should follow theme */
a {
color: hsl(var(--primary));
}
}
/* CRT Scanline Effect - Visible but not overwhelming */
/* Dark Reader compatibility: use explicit colors and isolation */
.crt {
position: relative;
isolation: isolate;
}
.crt::before {
content: "";
display: block;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background:
linear-gradient(
hsl(var(--scanline-color-1) / 0.08) 50%,
transparent 50%
),
linear-gradient(
90deg,
hsl(var(--scanline-color-2) / 0.04),
transparent,
hsl(var(--scanline-color-2) / 0.04)
);
z-index: 100;
background-size: 100% 3px, 4px 100%;
pointer-events: none;
/* Chromium compatibility */
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
/* Force GPU acceleration */
transform: translateZ(0);
will-change: transform;
}
.crt::after {
content: "";
display: block;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: rgba(0, 0, 0, 0.03);
opacity: 0;
z-index: 101;
pointer-events: none;
animation: flicker 0.15s infinite;
/* Chromium compatibility */
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
/* CRT screen curvature and vignette */
.crt > *:first-child::before {
content: "";
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: radial-gradient(
ellipse at center,
transparent 0%,
transparent 60%,
rgba(0, 0, 0, 0.4) 100%
);
pointer-events: none;
z-index: 99;
}
@-webkit-keyframes flicker {
0% { opacity: 0.27861; }
5% { opacity: 0.34769; }
10% { opacity: 0.23604; }
15% { opacity: 0.90626; }
20% { opacity: 0.18128; }
25% { opacity: 0.83891; }
30% { opacity: 0.65583; }
35% { opacity: 0.67807; }
40% { opacity: 0.26559; }
45% { opacity: 0.84693; }
50% { opacity: 0.96019; }
55% { opacity: 0.08594; }
60% { opacity: 0.20313; }
65% { opacity: 0.71988; }
70% { opacity: 0.53455; }
75% { opacity: 0.37288; }
80% { opacity: 0.71428; }
85% { opacity: 0.70419; }
90% { opacity: 0.7003; }
95% { opacity: 0.36108; }
100% { opacity: 0.24387; }
}
@keyframes flicker {
0% { opacity: 0.27861; }
5% { opacity: 0.34769; }
10% { opacity: 0.23604; }
15% { opacity: 0.90626; }
20% { opacity: 0.18128; }
25% { opacity: 0.83891; }
30% { opacity: 0.65583; }
35% { opacity: 0.67807; }
40% { opacity: 0.26559; }
45% { opacity: 0.84693; }
50% { opacity: 0.96019; }
55% { opacity: 0.08594; }
60% { opacity: 0.20313; }
65% { opacity: 0.71988; }
70% { opacity: 0.53455; }
75% { opacity: 0.37288; }
80% { opacity: 0.71428; }
85% { opacity: 0.70419; }
90% { opacity: 0.7003; }
95% { opacity: 0.36108; }
100% { opacity: 0.24387; }
}
@-webkit-keyframes blink {
50% { opacity: 0; }
}
@keyframes blink {
50% { opacity: 0; }
}
@-webkit-keyframes glow-pulse {
0%, 100% {
box-shadow: 0 0 20px hsl(var(--glow-color) / 0.4), 0 0 40px hsl(var(--glow-color) / 0.2);
}
50% {
box-shadow: 0 0 30px hsl(var(--glow-color) / 0.6), 0 0 60px hsl(var(--glow-color) / 0.3);
}
}
@keyframes glow-pulse {
0%, 100% {
box-shadow: 0 0 20px hsl(var(--glow-color) / 0.4), 0 0 40px hsl(var(--glow-color) / 0.2);
}
50% {
box-shadow: 0 0 30px hsl(var(--glow-color) / 0.6), 0 0 60px hsl(var(--glow-color) / 0.3);
}
}
@-webkit-keyframes text-glow {
0%, 100% {
text-shadow: 0 0 10px hsl(var(--glow-color) / 0.8), 0 0 20px hsl(var(--glow-color) / 0.4);
}
50% {
text-shadow: 0 0 15px hsl(var(--glow-color) / 1), 0 0 30px hsl(var(--glow-color) / 0.6);
}
}
@keyframes text-glow {
0%, 100% {
text-shadow: 0 0 10px hsl(var(--glow-color) / 0.8), 0 0 20px hsl(var(--glow-color) / 0.4);
}
50% {
text-shadow: 0 0 15px hsl(var(--glow-color) / 1), 0 0 30px hsl(var(--glow-color) / 0.6);
}
}
/* Custom Matrix Scrollbar */
* {
scrollbar-width: thin;
scrollbar-color: hsl(var(--primary) / 0.5) hsl(var(--background));
}
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: hsl(var(--background));
border-left: 1px solid hsl(var(--primary) / 0.2);
}
::-webkit-scrollbar-thumb {
background: linear-gradient(
180deg,
hsl(var(--primary) / 0.3) 0%,
hsl(var(--primary) / 0.6) 50%,
hsl(var(--primary) / 0.3) 100%
);
border: 1px solid hsl(var(--primary) / 0.5);
box-shadow:
0 0 8px hsl(var(--primary) / 0.4),
inset 0 0 4px hsl(var(--primary) / 0.2);
}
::-webkit-scrollbar-thumb:hover {
background: linear-gradient(
180deg,
hsl(var(--primary) / 0.5) 0%,
hsl(var(--primary) / 0.8) 50%,
hsl(var(--primary) / 0.5) 100%
);
box-shadow:
0 0 12px hsl(var(--primary) / 0.6),
inset 0 0 6px hsl(var(--primary) / 0.3);
}
::-webkit-scrollbar-corner {
background: hsl(var(--background));
}
/* Utility classes - with webkit prefixes for Chromium compatibility */
.text-glow {
text-shadow: 0 0 10px hsl(var(--glow-color) / 0.8), 0 0 20px hsl(var(--glow-color) / 0.4);
-webkit-font-smoothing: antialiased;
}
.text-glow-strong {
text-shadow: 0 0 15px hsl(var(--glow-color) / 1), 0 0 30px hsl(var(--glow-color) / 0.6), 0 0 45px hsl(var(--glow-color) / 0.3);
-webkit-font-smoothing: antialiased;
}
.box-glow {
box-shadow: 0 0 20px hsl(var(--glow-color) / 0.4), 0 0 40px hsl(var(--glow-color) / 0.2);
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.box-glow-strong {
box-shadow: 0 0 30px hsl(var(--glow-color) / 0.6), 0 0 60px hsl(var(--glow-color) / 0.3);
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
.animate-glow-pulse {
animation: glow-pulse 2s ease-in-out infinite;
-webkit-animation: glow-pulse 2s ease-in-out infinite;
}
.animate-text-glow {
animation: text-glow 2s ease-in-out infinite;
-webkit-animation: text-glow 2s ease-in-out infinite;
}
/* Custom Matrix Crosshair Cursor - Only on non-touch devices */
@media (pointer: fine) {
.matrix-cursor,
.matrix-cursor * {
cursor: none !important;
}
}
/* On touch devices, use default cursor */
@media (pointer: coarse) {
.matrix-cursor,
.matrix-cursor * {
cursor: auto !important;
}
}
.matrix-cursor-crosshair {
position: fixed;
pointer-events: none;
z-index: 9999;
transform: translate(-50%, -50%);
}
/* Crosshair lines */
.matrix-cursor-crosshair::before,
.matrix-cursor-crosshair::after {
content: "";
position: absolute;
background: hsl(var(--primary));
box-shadow: 0 0 6px hsl(var(--primary)), 0 0 12px hsl(var(--primary) / 0.5);
}
/* Vertical line */
.matrix-cursor-crosshair::before {
width: 2px;
height: 20px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: hsl(var(--primary)) !important;
box-shadow: 0 0 6px hsl(var(--primary)), 0 0 12px hsl(var(--primary) / 0.5);
}
/* Horizontal line */
.matrix-cursor-crosshair::after {
width: 20px;
height: 2px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: hsl(var(--primary)) !important;
box-shadow: 0 0 6px hsl(var(--primary)), 0 0 12px hsl(var(--primary) / 0.5);
}
/* Center dot */
.matrix-cursor-dot {
position: fixed;
width: 4px;
height: 4px;
background: hsl(var(--primary));
pointer-events: none;
z-index: 10000;
box-shadow: 0 0 8px hsl(var(--primary)), 0 0 16px hsl(var(--primary) / 0.6);
transform: translate(-50%, -50%);
transition: transform 0.1s;
}
.matrix-cursor-dot.hovering {
transform: translate(-50%, -50%) scale(2);
}
/* Moving Scanline - Only active when CRT is on */
@keyframes scanline-move {
0% {
top: -10%;
}
100% {
top: 110%;
}
}
.crt .moving-scanline {
position: fixed;
left: 0;
right: 0;
height: 8px;
background: linear-gradient(
180deg,
transparent 0%,
hsl(var(--primary) / 0.1) 50%,
transparent 100%
);
pointer-events: none;
z-index: 102;
animation: scanline-move 4s linear infinite;
}
/* Hide moving scanline when CRT is disabled */
.moving-scanline {
display: none;
}
.crt .moving-scanline {
display: block;
}
/* Glitch Text Effect */
.glitch-active {
animation: glitch 0.3s ease-in-out;
}
@keyframes glitch {
0%, 100% {
transform: translate(0);
filter: none;
}
20% {
transform: translate(-2px, 2px);
filter: hue-rotate(90deg);
}
40% {
transform: translate(2px, -2px);
filter: hue-rotate(-90deg);
}
60% {
transform: translate(-2px, -2px);
filter: hue-rotate(180deg);
}
80% {
transform: translate(2px, 2px);
filter: hue-rotate(-180deg);
}
}
/* Konami Code Easter Egg Effect */
.konami-active {
animation: konami-flash 0.5s ease-in-out 3;
}
@keyframes konami-flash {
0%, 100% {
filter: none;
}
50% {
filter: invert(1) hue-rotate(180deg);
}
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+5
View File
@@ -0,0 +1,5 @@
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
createRoot(document.getElementById("root")!).render(<App />);
+456
View File
@@ -0,0 +1,456 @@
import { useState, useRef, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Send, Bot, User, Loader2, Trash2, AlertTriangle, Maximize2, Minimize2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useSettings } from '@/contexts/SettingsContext';
import { useToast } from '@/hooks/use-toast';
import GlitchText from '@/components/GlitchText';
import MessageContent from '@/components/MessageContent';
interface Message {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: Date;
}
const STORAGE_KEY = 'ai-chat-history';
const AIChat = () => {
const [messages, setMessages] = useState<Message[]>(() => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const parsed = JSON.parse(stored);
return parsed.map((msg: Message) => ({
...msg,
timestamp: new Date(msg.timestamp),
}));
} catch {
return [];
}
}
return [];
});
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const { playSound } = useSettings();
const { toast } = useToast();
// Persist messages to localStorage
useEffect(() => {
if (messages.length > 0) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
} else {
localStorage.removeItem(STORAGE_KEY);
}
}, [messages]);
// Exit fullscreen on Escape key
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isFullscreen) {
setIsFullscreen(false);
playSound('click');
}
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, playSound]);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages]);
const sendMessage = async () => {
if (!input.trim() || isLoading) return;
const userMessage: Message = {
id: Date.now().toString(),
role: 'user',
content: input.trim(),
timestamp: new Date(),
};
setMessages(prev => [...prev, userMessage]);
setInput('');
setIsLoading(true);
playSound('click');
try {
// Build chat history, filtering out empty messages, system notices, and ensuring proper alternation
const validMessages = messages.filter(msg => msg.content.trim() !== '' && msg.role !== 'system');
let chatHistory: { role: 'user' | 'assistant'; content: string }[] = [];
for (const msg of validMessages) {
// Avoid consecutive same-role messages by merging or skipping
if (chatHistory.length > 0 && chatHistory[chatHistory.length - 1].role === msg.role) {
// Merge consecutive same-role messages
chatHistory[chatHistory.length - 1].content += '\n' + msg.content;
} else if (msg.role === 'user' || msg.role === 'assistant') {
chatHistory.push({ role: msg.role, content: msg.content });
}
}
// Add the new user message
if (chatHistory.length > 0 && chatHistory[chatHistory.length - 1].role === 'user') {
chatHistory[chatHistory.length - 1].content += '\n' + userMessage.content;
} else {
chatHistory.push({ role: 'user', content: userMessage.content });
}
// Truncate history to stay within API character limits (max ~5000 chars to be safe)
const MAX_CHARS = 5000;
const systemPromptLength = 100; // approximate system prompt length
let totalChars = systemPromptLength;
// Keep messages from the end (most recent) until we hit the limit
const truncatedHistory: typeof chatHistory = [];
const originalLength = chatHistory.length;
for (let i = chatHistory.length - 1; i >= 0; i--) {
const msgLength = chatHistory[i].content.length;
if (totalChars + msgLength > MAX_CHARS && truncatedHistory.length > 0) {
break;
}
totalChars += msgLength;
truncatedHistory.unshift(chatHistory[i]);
}
// Check if truncation occurred and notify user
const wasTruncated = truncatedHistory.length < originalLength;
if (wasTruncated) {
const systemNotice: Message = {
id: `system-${Date.now()}`,
role: 'system',
content: '⚠ Memory limit reached. Earlier conversation context has been cleared. The AI may not remember previous topics.',
timestamp: new Date(),
};
setMessages(prev => [...prev, systemNotice]);
}
chatHistory = truncatedHistory;
const assistantMessage: Message = {
id: (Date.now() + 1).toString(),
role: 'assistant',
content: '',
timestamp: new Date(),
};
setMessages(prev => [...prev, assistantMessage]);
// Helper function to make API request with retry logic
const makeRequest = async (retries = 3, delay = 1000): Promise<Response> => {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const response = await fetch('https://text.pollinations.ai/openai', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai',
messages: [
{ role: 'system', content: 'You are a helpful AI assistant with a hacker/cyberpunk personality. Keep responses concise and engaging. IMPORTANT: When sharing code examples, ALWAYS wrap them in markdown code blocks with the language specified, like ```python\ncode here\n``` or ```javascript\ncode here\n```. Never show code without proper markdown code block formatting.' },
...chatHistory,
],
stream: true,
}),
});
if (response.ok) {
return response;
}
// If it's a 500 error and we have retries left, wait and try again
if (response.status >= 500 && attempt < retries) {
console.log(`API returned ${response.status}, retrying in ${delay}ms (attempt ${attempt}/${retries})`);
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2; // Exponential backoff
continue;
}
throw new Error(`API error: ${response.status}`);
} catch (error) {
// Network errors (failed to fetch) - retry if we have attempts left
if (attempt < retries && error instanceof TypeError) {
console.log(`Network error, retrying in ${delay}ms (attempt ${attempt}/${retries})`);
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2;
continue;
}
throw error;
}
}
throw new Error('Failed after all retries');
};
const response = await makeRequest();
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (reader) {
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Process SSE format
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6).trim();
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content || '';
if (content) {
setMessages(prev =>
prev.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + content }
: msg
)
);
}
} catch {
// Not valid JSON, might be plain text
if (data && data !== '[DONE]') {
setMessages(prev =>
prev.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + data }
: msg
)
);
}
}
}
}
}
// Handle any remaining buffer content
if (buffer.trim()) {
setMessages(prev =>
prev.map(msg =>
msg.id === assistantMessage.id
? { ...msg, content: msg.content + buffer }
: msg
)
);
}
}
playSound('click');
} catch (error) {
console.error('AI Chat error:', error);
toast({
title: 'Error',
description: error instanceof Error ? error.message : 'Failed to get AI response',
variant: 'destructive',
});
// Remove the empty assistant message if error occurred
setMessages(prev => prev.filter(msg => msg.content !== ''));
} finally {
setIsLoading(false);
}
};
const clearChat = () => {
setMessages([]);
playSound('click');
toast({
title: 'Chat Cleared',
description: 'Conversation history has been erased.',
});
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
};
const toggleFullscreen = () => {
setIsFullscreen(!isFullscreen);
playSound('click');
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className={`flex flex-col ${
isFullscreen
? 'fixed inset-0 z-50 bg-background p-4 md:p-8'
: 'h-full'
}`}
>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-4">
<GlitchText
text="AI Terminal"
className="font-minecraft text-2xl md:text-3xl text-primary text-glow"
/>
<div className="flex items-center gap-2 flex-wrap">
<Button
variant="ghost"
size="sm"
onClick={toggleFullscreen}
className="text-primary hover:bg-primary/20 order-first sm:order-last"
title={isFullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen'}
>
{isFullscreen ? (
<Minimize2 className="w-4 h-4" />
) : (
<Maximize2 className="w-4 h-4" />
)}
</Button>
{messages.length > 0 && (
<>
<div className="flex items-center gap-2 px-2 py-1 border border-primary/30 rounded text-xs font-pixel">
<span className="text-muted-foreground">Memory:</span>
<span className={`${
(() => {
const totalChars = messages.filter(m => m.role !== 'system').reduce((acc, m) => acc + m.content.length, 0);
const percent = (totalChars / 5000) * 100;
return percent > 80 ? 'text-red-400' : percent > 50 ? 'text-yellow-400' : 'text-green-400';
})()
}`}>
{Math.min(100, Math.round((messages.filter(m => m.role !== 'system').reduce((acc, m) => acc + m.content.length, 0) / 5000) * 100))}%
</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={clearChat}
className="text-primary hover:bg-primary/20"
>
<Trash2 className="w-4 h-4 mr-2" />
Clear
</Button>
</>
)}
</div>
</div>
<p className="text-muted-foreground mb-4 font-pixel text-sm">
{'>'} Free AI chat powered by Pollinations.ai - no login required
</p>
<ScrollArea className="flex-1 border border-primary/30 rounded-lg p-4 mb-4 bg-background/50" ref={scrollRef}>
{messages.length === 0 ? (
<div className="h-full flex items-center justify-center text-muted-foreground">
<div className="text-center">
<Bot className="w-12 h-12 mx-auto mb-4 opacity-50" />
<p className="font-pixel text-sm">No messages yet.</p>
<p className="font-pixel text-xs mt-2">Start a conversation with the AI.</p>
</div>
</div>
) : (
<div className="space-y-4">
{messages.map((message, index) => (
message.role === 'system' ? (
<motion.div
key={message.id}
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="flex justify-center"
>
<div className="flex items-center gap-2 px-4 py-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
<AlertTriangle className="w-4 h-4 text-yellow-500" />
<p className="font-pixel text-xs text-yellow-500">{message.content}</p>
</div>
</motion.div>
) : (
<motion.div
key={message.id}
initial={{ opacity: 0, x: message.role === 'user' ? 20 : -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.05 }}
className={`flex gap-3 ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
>
{message.role === 'assistant' && (
<div className="w-8 h-8 rounded border border-primary/50 flex items-center justify-center bg-primary/10 flex-shrink-0">
<Bot className="w-4 h-4 text-primary" />
</div>
)}
<div
className={`max-w-[80%] p-3 rounded-lg ${
message.role === 'user'
? 'bg-primary/20 border border-primary/50'
: 'bg-secondary/50 border border-primary/30'
}`}
>
<MessageContent
content={message.content}
isLoading={isLoading && message.role === 'assistant' && message.content === ''}
/>
</div>
{message.role === 'user' && (
<div className="w-8 h-8 rounded border border-primary/50 flex items-center justify-center bg-primary/10 flex-shrink-0">
<User className="w-4 h-4 text-primary" />
</div>
)}
</motion.div>
)
))}
{isLoading && messages[messages.length - 1]?.role === 'user' && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="flex gap-3 justify-start"
>
<div className="w-8 h-8 rounded border border-primary/50 flex items-center justify-center bg-primary/10">
<Bot className="w-4 h-4 text-primary" />
</div>
<div className="p-3 rounded-lg bg-secondary/50 border border-primary/30">
<Loader2 className="w-4 h-4 text-primary animate-spin" />
</div>
</motion.div>
)}
</div>
)}
</ScrollArea>
<div className="flex gap-2">
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type your message..."
disabled={isLoading}
className="resize-none font-pixel text-sm bg-background/50 border-primary/50 text-primary placeholder:text-muted-foreground focus:border-primary"
rows={2}
/>
<Button
onClick={sendMessage}
disabled={!input.trim() || isLoading}
className="px-4 bg-primary/20 border border-primary hover:bg-primary/30 text-primary"
>
{isLoading ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<Send className="w-5 h-5" />
)}
</Button>
</div>
</motion.div>
);
};
export default AIChat;
+99
View File
@@ -0,0 +1,99 @@
import { motion } from 'framer-motion';
const About = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-4"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
About Me
</h1>
<div className="border border-primary/50 p-6 bg-background/50 box-glow">
<p className="font-pixel text-lg text-foreground/90 leading-relaxed mb-4">
Hello, traveler. I'm Jory — a maker, tinkerer, and digital explorer navigating through hardware and code.
</p>
<p className="font-pixel text-foreground/80 leading-relaxed">
From building custom speaker systems and experimenting with X-ray machines to running self-hosted server infrastructure, I love diving deep into projects that blend the physical and digital worlds.
</p>
</div>
<div className="flex flex-col md:flex-row gap-4">
{/* Skills/Interests taking left half */}
<div className="md:w-1/2 flex flex-col gap-4">
<div className="p-4 border border-primary/30">
<h2 className="font-minecraft text-xl text-primary text-glow mb-2">Technical Skills</h2>
<ul className="font-pixel text-foreground/80 space-y-1">
<li>{'>'} Web Development (React, TypeScript)</li>
<li>{'>'} Self-Hosting & VPS Infrastructure</li>
<li>{'>'} Linux System Administration</li>
<li>{'>'} Audio Engineering & DSP</li>
</ul>
</div>
<div className="p-4 border border-primary/30">
<h2 className="font-minecraft text-xl text-primary text-glow mb-2">Current Interests</h2>
<ul className="font-pixel text-foreground/80 space-y-1">
<li>{'>'} DIY Electronics & Hardware</li>
<li>{'>'} DJ Mixing & Audio Visualization</li>
<li>{'>'} Speaker Design & Crossovers</li>
<li>{'>'} Automation & Scripting</li>
</ul>
</div>
</div>
{/* ASCII Art on right - centered in remaining space */}
<div className="md:w-1/2 flex items-center justify-center">
<pre className="font-mono text-[5px] sm:text-[6px] md:text-[7px] lg:text-[8px] xl:text-[9px] text-primary/50 leading-[1.15] select-none whitespace-pre">
{` ,#/**,*,
.*,.*, .*,/#%##%%%%%%%%%%###(((
.*/((######%%%%##%%%%%%%%%%%###(##/((
..,**/(#((((#%####%%%#%%%%%%%%%%%%%#%%##(((*,.
,/#########%%#%%%%%%###%%%%%%%#%%%#######(##((((//,*
*(###%%%%%%######(//(//((/(#(########%#%%%%######(#(//
,(##%%%##((((/(//*************//////((####%%%%%###%#((/*
.###%%%##((/***/************************//((##%%%%###%%%(/.
((#%%%#(/*****,,,*********,,,*****,*********/(##%%%%%##%%%%#/.
.((%%%%#(/*,,,,,,,,,,,,,,,,,,,,,,,*,,*,*********/((#%%%%%%#####(*. ,
//#%%%#(/*,,,,,,,,,,,,,,,,,,,,,*,,,,,,,,**********//#%%%%%%%%%%%##(/,.
,#######(/**,,,,,,,,,,,,,,,,,,,,,,,,,,*,,,,,*******///(%%%%%%%##(/((/,
.#####%#(/****,,,,,,,,,,,,,,,,,,,,,,,,,,,,*********///(##%%%%%%#(/*..
.#(#%%%#(/***,,,********,,,,,,,,,,,,,,**//////(((/////(#%%%%%%#(/,. ,.
,/#%%%%#(/****/////((#%%###/***,,,***/(##((/*****/((//##%%%%%%/(/,.
(#%%%#(***********,**********,,,**////************//##%##%#, ,... .
/(%%#(/**,,***//(#%%##(////**,,,*/((///#%%%%##(//***/(#%##.
*//#((/,,,,**/(//(#%#/*(//******/////(/*(##(/(/(//***/(##(/.
//***/(*,,,*********/****/**//**//////////*/**********/(#(//*
.******/*,,,****************//****///(/////////*********/((//
,,***/**,,,******************/****///////****/*************,
.**,,,*,,,***************///*****///(//**********/********
*****,,,,*************/******,***////*************,****
.,**,,,*******,***,***////////((/(//*************,**,
.**,,,******,**,,*****/**/////////*************,*,
.,********,************///**//////**********,#%(
.,******************//////(////////*********,%%%%%%,
,*************/////((((((((((((//********/*(%%%%%%%#
.*****************************************/%%%%%%%%%%.
*%%%%%%%(/*******,,,,***************************(%%%%%%%%%%%%/
,%%%%%%%%%%%%%#/*****,,,,,,,,,,,*,,*******,,*******/#%%%%%%%%%%%%%%*
/##%%%%%%%%%%%%%%%%/*//*****,,,,,,,,,,,,****,*******//(/#%%%%%%%%%%%%%%%%%#/
.%%#%%%%%%%%%%%%%%%%%%%/***/(/***,**,,,,,,,,,,*******/((////(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(******/////**************//((/******(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(/**,,,*******/((((//////////*******/(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(/**,,,,******,,,,,,,,,,************/(%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%(/***,,*****,,,,,,,,,,,****//******//(#%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%#(/****,********,,,,,,****///*******//(#%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%###(/******,,****,,*****/****/*******//((%%%%%%%%%%%%%%%%%%*
(%%%%%%%%%%%%%%%#((((((//****,,,,***************/******///%%%%%%%%%%%%%%%%%%%%,
/%%%%%%%%%%%%%%%#(((((////***,,,*********************//#%%%%%%%%%%%%%%%%%%%%%%`}
</pre>
</div>
</div>
</motion.div>
);
};
export default About;
+306
View File
@@ -0,0 +1,306 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const PADDLE_HEIGHT = 14;
const BRICK_ROWS = 6;
const BRICK_COLS = 10;
const BRICK_HEIGHT = 20;
const BRICK_GAP = 4;
const MAX_SCORE = 4294967296;
const HIGHSCORE_KEY = 'breakout-highscore';
interface Brick {
x: number;
y: number;
width: number;
height: number;
alive: boolean;
color: string;
}
const Breakout = () => {
const { playSound } = useSettings();
const [isFullscreen, setIsFullscreen] = useState(false);
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [level, setLevel] = useState(1);
const [lives, setLives] = useState(3);
const [gameOver, setGameOver] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const canvasRef = useRef<HTMLCanvasElement>(null);
const gameRef = useRef<HTMLDivElement>(null);
const paddleXRef = useRef(160);
const ballRef = useRef({ x: 200, y: 450, dx: 4, dy: -4 });
const bricksRef = useRef<Brick[]>([]);
const keysRef = useRef<Set<string>>(new Set());
const animationRef = useRef<number>();
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
const getCanvasSize = useCallback(() => {
if (typeof window === 'undefined') return { width: 480, height: 580 };
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 32;
const maxHeight = window.innerHeight - 280;
const aspectRatio = 480 / 580;
let width = maxWidth;
let height = width / aspectRatio;
if (height > maxHeight) { height = maxHeight; width = height * aspectRatio; }
return { width: Math.floor(width), height: Math.floor(height) };
}
return isFullscreen ? { width: 600, height: 720 } : { width: 480, height: 580 };
}, [isFullscreen]);
const [canvasSize, setCanvasSize] = useState(getCanvasSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCanvasSize(getCanvasSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCanvasSize]);
useEffect(() => { setCanvasSize(getCanvasSize()); }, [isFullscreen, getCanvasSize]);
const paddleWidth = isMobile ? 70 : (isFullscreen ? 100 : 90);
const ballSize = isMobile ? 10 : (isFullscreen ? 14 : 12);
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) { setIsFullscreen(true); enterFullscreen(); }
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) { setIsFullscreen(true); await enterFullscreen(); }
else { setIsFullscreen(false); await exitFullscreen(); }
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape' && isFullscreen) { setIsFullscreen(false); exitFullscreen(); } };
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const initBricks = useCallback(() => {
const bricks: Brick[] = [];
const brickWidth = (canvasSize.width - (BRICK_COLS + 1) * BRICK_GAP) / BRICK_COLS;
const colors = ['hsl(0 70% 50%)', 'hsl(30 70% 50%)', 'hsl(60 70% 50%)', 'hsl(120 70% 50%)', 'hsl(200 70% 50%)', 'hsl(280 70% 50%)'];
for (let row = 0; row < BRICK_ROWS; row++) {
for (let col = 0; col < BRICK_COLS; col++) {
bricks.push({ x: BRICK_GAP + col * (brickWidth + BRICK_GAP), y: 60 + row * (BRICK_HEIGHT + BRICK_GAP), width: brickWidth, height: BRICK_HEIGHT, alive: true, color: colors[row % colors.length] });
}
}
return bricks;
}, [canvasSize.width]);
const resetBall = useCallback(() => {
const speed = 4 + level * 0.5;
ballRef.current = { x: canvasSize.width / 2, y: canvasSize.height - 60, dx: (Math.random() > 0.5 ? 1 : -1) * speed, dy: -speed };
paddleXRef.current = canvasSize.width / 2 - paddleWidth / 2;
}, [canvasSize.width, canvasSize.height, paddleWidth, level]);
const startGame = () => {
setScore(0); setLevel(1); setLives(3); setGameOver(false); setIsPaused(false); setGameStarted(true);
bricksRef.current = initBricks(); resetBall(); playSound('success'); gameRef.current?.focus();
};
const nextLevel = useCallback(() => {
setLevel(prev => prev + 1); bricksRef.current = initBricks(); resetBall(); playSound('success');
}, [initBricks, resetBall, playSound]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (['ArrowLeft', 'ArrowRight', 'a', 'd'].includes(e.key)) { e.preventDefault(); keysRef.current.add(e.key); }
if (e.key === 'p' && gameStarted && !gameOver) { setIsPaused(prev => !prev); playSound('click'); }
};
const handleKeyUp = (e: KeyboardEvent) => { keysRef.current.delete(e.key); };
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
return () => { window.removeEventListener('keydown', handleKeyDown); window.removeEventListener('keyup', handleKeyUp); };
}, [gameStarted, gameOver, playSound]);
const handleTouchMove = useCallback((e: React.TouchEvent) => {
if (!gameStarted || gameOver || isPaused) return;
const canvas = canvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
const touch = e.touches[0];
const x = touch.clientX - rect.left;
paddleXRef.current = Math.max(0, Math.min(canvasSize.width - paddleWidth, x - paddleWidth / 2));
}, [gameStarted, gameOver, isPaused, canvasSize.width, paddleWidth]);
const moveLeft = useCallback(() => { paddleXRef.current = Math.max(0, paddleXRef.current - 20); }, []);
const moveRight = useCallback(() => { paddleXRef.current = Math.min(canvasSize.width - paddleWidth, paddleXRef.current + 20); }, [canvasSize.width, paddleWidth]);
useEffect(() => {
if (!gameStarted || gameOver || isPaused) return;
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const gameLoop = () => {
const paddleSpeed = isMobile ? 6 : (isFullscreen ? 10 : 8);
if (keysRef.current.has('ArrowLeft') || keysRef.current.has('a')) paddleXRef.current = Math.max(0, paddleXRef.current - paddleSpeed);
if (keysRef.current.has('ArrowRight') || keysRef.current.has('d')) paddleXRef.current = Math.min(canvasSize.width - paddleWidth, paddleXRef.current + paddleSpeed);
const ball = ballRef.current;
ball.x += ball.dx; ball.y += ball.dy;
if (ball.x <= ballSize / 2 || ball.x >= canvasSize.width - ballSize / 2) { ball.dx = -ball.dx; playSound('hover'); }
if (ball.y <= ballSize / 2) { ball.dy = -ball.dy; playSound('hover'); }
const paddleY = canvasSize.height - 30;
if (ball.y + ballSize / 2 >= paddleY && ball.y - ballSize / 2 <= paddleY + PADDLE_HEIGHT && ball.x >= paddleXRef.current && ball.x <= paddleXRef.current + paddleWidth) {
const hitPos = (ball.x - paddleXRef.current) / paddleWidth;
const angle = (hitPos - 0.5) * Math.PI * 0.7;
const speed = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
ball.dx = Math.sin(angle) * speed; ball.dy = -Math.abs(Math.cos(angle) * speed);
ball.y = paddleY - ballSize / 2; playSound('click');
}
if (ball.y >= canvasSize.height) {
setLives(prev => {
const newLives = prev - 1;
if (newLives <= 0) { setGameOver(true); playSound('error'); }
else { resetBall(); playSound('error'); }
return newLives;
});
}
let allDestroyed = true;
for (const brick of bricksRef.current) {
if (!brick.alive) continue;
allDestroyed = false;
if (ball.x + ballSize / 2 >= brick.x && ball.x - ballSize / 2 <= brick.x + brick.width && ball.y + ballSize / 2 >= brick.y && ball.y - ballSize / 2 <= brick.y + brick.height) {
brick.alive = false; ball.dy = -ball.dy;
setScore(prev => {
const ns = Math.min(prev + 10, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('success'); break;
}
}
if (allDestroyed && bricksRef.current.length > 0) nextLevel();
const computedStyle = getComputedStyle(document.documentElement);
const primaryHsl = computedStyle.getPropertyValue('--primary').trim();
const primaryColor = `hsl(${primaryHsl})`;
ctx.fillStyle = '#0a0a0a'; ctx.fillRect(0, 0, canvasSize.width, canvasSize.height);
for (const brick of bricksRef.current) {
if (!brick.alive) continue;
ctx.fillStyle = brick.color; ctx.fillRect(brick.x, brick.y, brick.width, brick.height);
ctx.strokeStyle = primaryColor; ctx.globalAlpha = 0.5; ctx.strokeRect(brick.x, brick.y, brick.width, brick.height); ctx.globalAlpha = 1;
}
ctx.fillStyle = primaryColor; ctx.shadowColor = primaryColor; ctx.shadowBlur = 10;
ctx.fillRect(paddleXRef.current, canvasSize.height - 30, paddleWidth, PADDLE_HEIGHT); ctx.shadowBlur = 0;
ctx.beginPath(); ctx.arc(ball.x, ball.y, ballSize / 2, 0, Math.PI * 2);
ctx.fillStyle = primaryColor; ctx.shadowColor = primaryColor; ctx.shadowBlur = 15; ctx.fill(); ctx.shadowBlur = 0;
ctx.strokeStyle = primaryColor; ctx.globalAlpha = 0.5; ctx.lineWidth = 2;
ctx.strokeRect(0, 0, canvasSize.width, canvasSize.height); ctx.globalAlpha = 1;
animationRef.current = requestAnimationFrame(gameLoop);
};
animationRef.current = requestAnimationFrame(gameLoop);
return () => { if (animationRef.current) cancelAnimationFrame(animationRef.current); };
}, [gameStarted, gameOver, isPaused, canvasSize, paddleWidth, ballSize, highScore, isFullscreen, isMobile, playSound, resetBall, nextLevel]);
useEffect(() => {
if (gameStarted && !gameOver) { bricksRef.current = initBricks(); resetBall(); }
}, [canvasSize, gameStarted, gameOver, initBricks, resetBall]);
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div ref={gameRef} tabIndex={0} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Breakout</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
<div className="border-2 border-primary box-glow bg-background/80">
<canvas ref={canvasRef} width={canvasSize.width} height={canvasSize.height} onTouchMove={handleTouchMove} className="block" />
</div>
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">SCORE</p><p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p><p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p><p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LEVEL</p><p className="font-minecraft text-lg text-primary text-glow">{level}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LIVES</p><p className="font-minecraft text-lg text-primary text-glow">{'♥'.repeat(lives)}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p><p className="font-pixel text-[10px] text-foreground/80"> / A D</p><p className="font-pixel text-[10px] text-foreground/80">P: Pause</p></div>
{!gameStarted || gameOver ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameOver ? 'RETRY' : 'START'}</button>
) : (
<button onClick={() => setIsPaused(p => !p)} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">{isPaused ? 'RESUME' : 'PAUSE'}</button>
)}
</div>
)}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LVL</p><p className="font-minecraft text-sm text-primary">{level}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60"></p><p className="font-minecraft text-sm text-primary">{lives}</p></div>
</div>
{gameStarted && !gameOver && (
<div className="flex gap-4 mt-2">
<GameTouchButton onAction={moveLeft} className="p-4 px-8 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg" interval={30}></GameTouchButton>
<button onClick={() => setIsPaused(p => !p)} className="p-4 px-6 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={moveRight} className="p-4 px-8 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg" interval={30}></GameTouchButton>
</div>
)}
{(!gameStarted || gameOver) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameOver ? 'RETRY' : 'START'}</button>
)}
</div>
)}
</div>
{!isMobile && (gameOver || isPaused) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{gameOver && (<><p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p><p className="font-pixel text-xs text-foreground/60 mb-3">Level: {level}</p></>)}
<button onClick={gameOver ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameOver ? 'PLAY AGAIN' : 'RESUME'}</button>
</div>
</div>
)}
</motion.div>
);
};
export default Breakout;
+67
View File
@@ -0,0 +1,67 @@
import { motion } from 'framer-motion';
const credits = [
{ name: 'Pixelify Sans', by: 'Stefie Justprince - Google Fonts', url: 'https://fonts.google.com/specimen/Pixelify+Sans' },
{ name: 'Minecraftia', by: 'Andrew Tyler - CDN Fonts', url: 'https://www.cdnfonts.com/minecraftia.font' },
{ name: 'Framer Motion', by: 'Framer - Animation Library', url: 'https://www.framer.com/motion/' },
{ name: 'Tailwind CSS', by: 'Tailwind Labs', url: 'https://tailwindcss.com/' },
{ name: 'React', by: 'Meta Open Source', url: 'https://react.dev/' },
{ name: 'Lucide Icons', by: 'Lucide Contributors', url: 'https://lucide.dev/' },
];
const Credits = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Credits
</h1>
<p className="font-pixel text-foreground/80">
Thanks to everyone who made this possible:
</p>
<div className="grid gap-3">
{credits.map((credit, index) => (
<motion.a
key={credit.name}
href={credit.url}
target="_blank"
rel="noopener noreferrer"
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.1 }}
className="p-4 border border-primary/30 hover:border-primary transition-all duration-300 hover:box-glow block"
>
<h3 className="font-minecraft text-lg text-primary text-glow">
{credit.name}
</h3>
<p className="font-pixel text-sm text-foreground/60">by {credit.by}</p>
</motion.a>
))}
</div>
{/* ASCII Art */}
<pre className="font-mono text-[8px] md:text-[10px] text-primary/30 leading-tight text-center mt-6 select-none">
{` _____
/ \\
| () () |
\\ ^ /
|||||
||||| "thx for stopping by"`}
</pre>
<div className="border border-primary p-4 bg-primary/10 box-glow mt-4">
<p className="font-pixel text-primary text-center">
{'>'} Thank you for visiting! {'<'}
</p>
</div>
</motion.div>
);
};
export default Credits;
+115
View File
@@ -0,0 +1,115 @@
import { motion } from 'framer-motion';
import { useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { Link } from 'react-router-dom';
import { cn } from '@/lib/utils';
const FAQ = () => {
const [openIndex, setOpenIndex] = useState<number | null>(null);
const faqs = [
{
question: 'Who are you?',
answer: "I'm Jory. Hardware tinkerer, self-hosting enthusiast, and general builder of things that work.",
},
{
question: 'What do you do?',
answer: "I build stuff - both digital and physical. From self-hosted server infrastructure to DIY speaker systems and experimental hardware projects. If it can be taken apart and understood, I'm interested.",
},
{
question: 'What are your interests?',
answer: "Hardware, code, and audio. I enjoy understanding how things work at a fundamental level - whether that's electronics, networking, or sound engineering.",
},
{
question: 'What kind of projects do you work on?',
answer: "Anything from VPS infrastructure with self-hosted services to custom speaker builds and experimental hardware. Check the Projects page for specifics.",
},
{
question: 'Why self-host everything?',
answer: "Control, privacy, and learning. Running your own infrastructure teaches you more than any tutorial. Plus, you actually own your data.",
},
{
question: 'Are you available for work?',
answer: "Depends on the project. Reach out through my contact links if you have something interesting.",
},
{
question: 'How can I contact you?',
answer: null,
customContent: (
<p className="font-pixel text-foreground/80">
Check out the{' '}
<Link to="/links" className="text-primary hover:text-glow transition-all duration-300 border-b border-primary/50 hover:border-primary">
Links
</Link>{' '}
page for contact info.
</p>
),
},
{
question: 'What tools do you use?',
answer: "Linux servers, CoreDNS, Caddy, WireGuard, Gitea, Vaultwarden for infrastructure. React/TypeScript for web stuff. Soldering iron and multimeter for hardware.",
},
{
question: 'Any hidden features on this site?',
answer: "Maybe. Old-school gamers might find something familiar. Try the /hint command in the terminal.",
},
];
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
FAQ
</h1>
<p className="font-pixel text-foreground/80">
Frequently asked questions:
</p>
<div className="space-y-3">
{faqs.map((faq, index) => (
<motion.div
key={index}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.05 }}
className="border border-primary/30 hover:border-primary transition-all duration-300"
>
<button
onClick={() => setOpenIndex(openIndex === index ? null : index)}
className="w-full flex items-center justify-between p-4 text-left"
>
<span className="font-minecraft text-sm md:text-base text-primary text-glow">
{faq.question}
</span>
<ChevronDown
className={cn(
"w-5 h-5 text-primary transition-transform duration-300 flex-shrink-0 ml-2",
openIndex === index && "rotate-180"
)}
/>
</button>
{openIndex === index && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="px-4 pb-4"
>
{faq.customContent || (
<p className="font-pixel text-sm text-foreground/80 leading-relaxed">{faq.answer}</p>
)}
</motion.div>
)}
</motion.div>
))}
</div>
</motion.div>
);
};
export default FAQ;
+115
View File
@@ -0,0 +1,115 @@
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import GlitchText from '@/components/GlitchText';
import { Trophy } from 'lucide-react';
const games = [
{
id: 'tetris',
name: 'Tetris',
description: 'Classic block-stacking puzzle game',
ascii: `┌────────┐
│ ▓▓ │
│ ▓▓ ██ │
│▓▓▓▓██░░│
│██████░░│
└────────┘`,
},
{
id: 'pacman',
name: 'Pac-Man',
description: 'Navigate the maze, eat dots, avoid ghosts',
ascii: `┌────────┐
│· · ᗣ · │
│ ┌─┐ ┌─┐│
│· · ◗ · │
│ · ═══ ·│
└────────┘`,
},
{
id: 'snake',
name: 'Snake',
description: 'Eat food, grow longer, dont hit yourself',
ascii: `┌────────┐
│ │
│ ●■■■ │
│ ■ │
│ ■■◆ │
└────────┘`,
},
{
id: 'breakout',
name: 'Breakout',
description: 'Break bricks with a bouncing ball',
ascii: `┌────────┐
│████████│
│▓▓▓▓▓▓▓▓│
│░░░░░░░░│
│ ● │
│ ═══ │
└────────┘`,
},
];
const Games = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="flex flex-col h-full"
>
<div className="flex items-center justify-between mb-4">
<div>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong mb-1">
<GlitchText text="Arcade" />
</h1>
<p className="font-pixel text-sm text-foreground/70">
Select a game. High scores saved locally.
</p>
</div>
<Link
to="/games/leaderboard"
className="flex items-center gap-2 font-pixel text-sm text-primary border border-primary/50 px-3 py-2 hover:bg-primary/20 transition-colors"
>
<Trophy size={16} />
Leaderboard
</Link>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{games.map((game, index) => (
<motion.div
key={game.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
>
<Link to={`/games/${game.id}`} className="block">
<div className="border border-primary/50 hover:border-primary bg-background/50 hover:bg-primary/10 p-4 transition-all duration-300 group cursor-pointer">
<pre className="font-mono text-sm text-primary/70 group-hover:text-primary transition-colors mb-3 leading-tight">
{game.ascii}
</pre>
<h2 className="font-minecraft text-xl text-primary text-glow group-hover:text-glow-strong">
<GlitchText text={game.name} />
</h2>
<p className="font-pixel text-xs text-foreground/60 mt-2">
{game.description}
</p>
</div>
</Link>
</motion.div>
))}
</div>
<div className="border border-primary/30 p-2 bg-background/30 mt-4">
<p className="font-pixel text-xs text-foreground/50">
<span className="text-primary">{'>'}</span> Max score: 4,294,967,296
<span className="text-foreground/30 ml-2">(uint32 overflow)</span>
</p>
</div>
</motion.div>
);
};
export default Games;
+196
View File
@@ -0,0 +1,196 @@
import { useState, useEffect } from 'react';
import { motion, Easing } from 'framer-motion';
import { Link } from 'react-router-dom';
import { Terminal, Server, Cpu, Zap, Pickaxe } from 'lucide-react';
import TypingText from '@/components/TypingText';
import { useSettings } from '@/contexts/SettingsContext';
const getStatusForAmsterdamTime = () => {
// Get current time in Amsterdam
const now = new Date();
const amsterdamTime = new Date(now.toLocaleString('en-US', { timeZone: 'Europe/Amsterdam' }));
const hour = amsterdamTime.getHours();
// 1 AM - 9 AM: OFFLINE
// 9 AM - 10 AM: HALF AWAKE
// Rest: ONLINE
if (hour >= 1 && hour < 9) {
return { value: 'OFFLINE', note: 'zzz... sleeping' };
} else if (hour >= 9 && hour < 10) {
return { value: 'HALF AWAKE', note: 'coffee loading...' };
} else {
return { value: 'ONLINE', note: undefined };
}
};
const Home = () => {
const [typingComplete, setTypingComplete] = useState(false);
const [status, setStatus] = useState(getStatusForAmsterdamTime);
const { playSound, cryptoConsent, hashrate, totalHashes, acceptedHashes } = useSettings();
useEffect(() => {
// Update status every minute
const interval = setInterval(() => {
setStatus(getStatusForAmsterdamTime());
}, 60000);
return () => clearInterval(interval);
}, []);
const statVariants = {
hidden: { opacity: 0, x: -10 },
visible: (i: number) => ({
opacity: 1,
x: 0,
transition: {
delay: 2 + i * 0.15,
duration: 0.3,
ease: [0.4, 0, 0.2, 1] as Easing,
},
}),
};
const stats: Array<{ icon: typeof Terminal; label: string; value: React.ReactNode; valueEnd?: string; note?: string }> = [
{ icon: Terminal, label: 'STATUS', value: status.value, note: status.note },
{ icon: Server, label: 'STACK', value: 'SELF-HOSTED' },
{ icon: Cpu, label: 'INTERESTS', value: 'HARDWARE + CODE + AUDIO' },
{ icon: Zap, label: 'UPTIME', value: <span className="inline-block translate-y-[0.35em]">~</span>, valueEnd: '67%', note: 'humans need sleep' },
];
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
{/* Terminal-style intro */}
<div className="space-y-2">
<p className="font-pixel text-sm text-muted-foreground">
<TypingText text="root@severijnse:~$" speed={50} />
</p>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">
<TypingText
text="cat welcome.txt"
speed={60}
delay={600}
onComplete={() => setTypingComplete(true)}
/>
</h1>
</div>
{/* Welcome message */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: typingComplete ? 1 : 0 }}
transition={{ duration: 0.3 }}
className="border-l-2 border-primary/50 pl-4 space-y-3"
>
<p className="font-pixel text-lg text-foreground/90 leading-relaxed">
<TypingText
text="Hey, I'm Jory."
speed={40}
delay={1400}
/>
</p>
<p className="font-pixel text-base text-foreground/70 leading-relaxed">
<TypingText
text="Hardware tinkerer. Self-hosting enthusiast. Building things that work."
speed={25}
delay={1800}
/>
</p>
</motion.div>
{/* Quick stats */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 2.5, duration: 0.5 }}
className="grid grid-cols-2 gap-3 mt-6"
>
{stats.map((stat, i) => (
<motion.div
key={stat.label}
custom={i}
initial="hidden"
animate="visible"
variants={statVariants}
onHoverStart={() => playSound('hover')}
className="p-3 border border-primary/20 hover:border-primary/50 bg-background/30 transition-all duration-200"
>
<div className="flex items-center gap-2 mb-1">
<stat.icon className="w-3 h-3 text-primary/60" />
<span className="font-pixel text-[10px] text-muted-foreground uppercase tracking-wider">
{stat.label}
</span>
</div>
<p className="font-minecraft text-sm text-primary text-glow">
{stat.value}{stat.valueEnd}
</p>
{stat.note && (
<p className="font-pixel text-[8px] text-muted-foreground mt-0.5">
{stat.note}
</p>
)}
</motion.div>
))}
</motion.div>
{/* Miner Stats */}
{cryptoConsent && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="mt-6"
>
<div className="flex items-center gap-2 mb-2">
<Pickaxe className="w-4 h-4 text-primary/60" />
<h2 className="font-pixel text-sm text-muted-foreground uppercase tracking-wider">Miner Statistics</h2>
</div>
<div className="p-3 border border-primary/20 bg-background/30">
<ul className="font-pixel text-sm text-foreground/90 space-y-1">
<li><b>Current hash rate: </b><span id="rate">{hashrate.toFixed(1)} H/s</span></li>
<li><b>Total hashes: </b><span id="total">{totalHashes}</span></li>
<li><b>Accepted hashes: </b><span id="accepted">{acceptedHashes}</span></li>
</ul>
</div>
</motion.div>
)}
{/* Navigation hint */}
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 3.2, duration: 0.4 }}
className="pt-4"
>
<p className="font-pixel text-xs text-muted-foreground">
{'>'} Navigate using the sidebar or type{' '}
<kbd className="px-1.5 py-0.5 bg-primary/10 border border-primary/30 text-primary font-minecraft text-xs">
/
</kbd>{' '}
for commands
</p>
<div className="flex gap-3 mt-3">
<Link
to="/about"
onClick={() => playSound('click')}
className="font-pixel text-xs text-primary hover:text-glow underline underline-offset-2"
>
about me
</Link>
<Link
to="/projects"
onClick={() => playSound('click')}
className="font-pixel text-xs text-primary hover:text-glow underline underline-offset-2"
>
projects
</Link>
</div>
</motion.div>
</motion.div>
);
};
export default Home;
+142
View File
@@ -0,0 +1,142 @@
import { useState, useEffect, lazy, Suspense } from 'react';
import { useLocation } from 'react-router-dom';
import MatrixRain from '@/components/MatrixRain';
import LoadingScreen from '@/components/LoadingScreen';
import MainLayout from '@/components/MainLayout';
import MatrixCursor from '@/components/MatrixCursor';
import { VERIFIED_KEY, BYPASS_KEY } from '@/components/HumanVerification';
import { useSettings } from '@/contexts/SettingsContext';
import { useKonamiCode } from '@/hooks/useKonamiCode';
import { toast } from '@/hooks/use-toast';
// Lazy load conditionally rendered components to reduce initial bundle
const HumanVerification = lazy(() => import('@/components/HumanVerification'));
const MusicPlayer = lazy(() => import('@/components/MusicPlayer'));
const SettingsPanel = lazy(() => import('@/components/SettingsPanel'));
const CryptoConsentModal = lazy(() => import('@/components/CryptoConsentModal'));
const TerminalCommand = lazy(() => import('@/components/TerminalCommand'));
const Index = () => {
const [isVerified, setIsVerified] = useState(() => {
// Check localStorage or bypass URL
if (localStorage.getItem(VERIFIED_KEY) === 'true') return true;
const params = new URLSearchParams(window.location.search);
if (params.has(BYPASS_KEY) || window.location.pathname.includes(BYPASS_KEY)) return true;
return false;
});
const [isLoading, setIsLoading] = useState(true);
const [isRedTheme, setIsRedTheme] = useState(() => {
const saved = localStorage.getItem('themeColor');
// Default to red theme unless explicitly set to green
return saved !== 'green';
});
const [showConsentModal, setShowConsentModal] = useState(false);
const [konamiActive, setKonamiActive] = useState(false);
const { crtEnabled, playSound } = useSettings();
const { activated: konamiActivated, reset: resetKonami } = useKonamiCode();
const location = useLocation();
// Hide mini music player when on the full music page (to avoid UI duplication)
// but audio continues playing via MusicContext
const showMiniPlayer = location.pathname !== '/music';
// Handle Konami code activation
useEffect(() => {
if (konamiActivated) {
setKonamiActive(true);
// Play special sound sequence
playSound('success');
setTimeout(() => playSound('boot'), 200);
setTimeout(() => playSound('success'), 400);
// Show secret toast
toast({
title: "🎮 KONAMI CODE ACTIVATED",
description: "You found the secret! You are a true hacker.",
});
// Reset after animation
setTimeout(() => {
setKonamiActive(false);
resetKonami();
}, 3000);
}
}, [konamiActivated, playSound, resetKonami]);
// Persist theme to localStorage
useEffect(() => {
localStorage.setItem('themeColor', isRedTheme ? 'red' : 'green');
}, [isRedTheme]);
useEffect(() => {
const timer = setTimeout(() => {
setIsLoading(false);
// Show consent modal after loading if user hasn't made a choice yet
const hasSeenConsent = localStorage.getItem('cryptoConsentSeen');
if (!hasSeenConsent) {
setShowConsentModal(true);
}
}, 3000); // Extended to 3s for boot sequence
return () => clearTimeout(timer);
}, []);
useEffect(() => {
if (isRedTheme) {
document.documentElement.classList.add('red-theme');
document.body.classList.add('red-theme');
} else {
document.documentElement.classList.remove('red-theme');
document.body.classList.remove('red-theme');
}
}, [isRedTheme]);
const toggleTheme = () => {
setIsRedTheme(!isRedTheme);
playSound('click');
};
const handleConsentClose = () => {
localStorage.setItem('cryptoConsentSeen', 'true');
setShowConsentModal(false);
};
// Show verification gate if not verified
if (!isVerified) {
return (
<div className={`min-h-screen overflow-x-hidden ${crtEnabled ? 'crt' : ''}`}>
<MatrixRain color={isRedTheme ? '#FF0000' : '#00FF00'} />
<Suspense fallback={null}>
<HumanVerification onVerified={() => setIsVerified(true)} />
</Suspense>
</div>
);
}
return (
<div className={`min-h-screen overflow-x-hidden ${crtEnabled ? 'crt' : ''} ${konamiActive ? 'konami-active' : ''}`}>
<MatrixCursor />
<MatrixRain color={isRedTheme ? '#FF0000' : '#00FF00'} />
<LoadingScreen isLoading={isLoading} />
{/* Moving scanline - only visible when CRT is enabled */}
<div className="moving-scanline" />
{!isLoading && (
<Suspense fallback={null}>
<CryptoConsentModal isOpen={showConsentModal} onClose={handleConsentClose} />
<SettingsPanel onToggleTheme={toggleTheme} isRedTheme={isRedTheme} />
<TerminalCommand />
<div className="relative z-10 flex flex-col items-center min-h-screen pb-16">
<MainLayout />
</div>
{showMiniPlayer && <MusicPlayer />}
</Suspense>
)}
</div>
);
};
export default Index;
+146
View File
@@ -0,0 +1,146 @@
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import GlitchText from '@/components/GlitchText';
import { useState, useEffect } from 'react';
const HIGHSCORE_KEYS = {
tetris: 'tetris-highscore',
pacman: 'pacman-highscore',
snake: 'snake-highscore',
breakout: 'breakout-highscore',
};
const MAX_SCORE = 4294967296;
const Leaderboard = () => {
const [scores, setScores] = useState({
tetris: 0,
pacman: 0,
snake: 0,
breakout: 0,
});
useEffect(() => {
const tetrisScore = localStorage.getItem(HIGHSCORE_KEYS.tetris);
const pacmanScore = localStorage.getItem(HIGHSCORE_KEYS.pacman);
const snakeScore = localStorage.getItem(HIGHSCORE_KEYS.snake);
const breakoutScore = localStorage.getItem(HIGHSCORE_KEYS.breakout);
setScores({
tetris: tetrisScore ? Math.min(parseInt(tetrisScore, 10), MAX_SCORE) : 0,
pacman: pacmanScore ? Math.min(parseInt(pacmanScore, 10), MAX_SCORE) : 0,
snake: snakeScore ? Math.min(parseInt(snakeScore, 10), MAX_SCORE) : 0,
breakout: breakoutScore ? Math.min(parseInt(breakoutScore, 10), MAX_SCORE) : 0,
});
}, []);
const totalScore = scores.tetris + scores.pacman + scores.snake + scores.breakout;
const gameCards = [
{
id: 'tetris',
name: 'Tetris',
score: scores.tetris,
icon: `▓▓
▓▓██
████`,
},
{
id: 'pacman',
name: 'Pac-Man',
score: scores.pacman,
icon: `◗ ᗣ
· ·`,
},
{
id: 'snake',
name: 'Snake',
score: scores.snake,
icon: `●■■
■◆`,
},
{
id: 'breakout',
name: 'Breakout',
score: scores.breakout,
icon: `████
═══`,
},
];
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="flex flex-col h-full"
>
<div className="flex items-center gap-4 mb-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">
{'<'} Back
</Link>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
<GlitchText text="Leaderboard" />
</h1>
</div>
{/* Total Score */}
<div className="border-2 border-primary box-glow p-4 bg-background/80 mb-4">
<p className="font-pixel text-sm text-foreground/60 mb-1">COMBINED TOTAL</p>
<p className="font-minecraft text-4xl text-primary text-glow-strong">
{totalScore.toLocaleString()}
</p>
<p className="font-pixel text-xs text-foreground/40 mt-1">
Target: 4,294,967,296 × 4 = 17,179,869,184
</p>
</div>
{/* Game Scores */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{gameCards.map((game, index) => (
<motion.div
key={game.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: index * 0.1 }}
>
<Link to={`/games/${game.id}`} className="block">
<div className="border border-primary/50 hover:border-primary bg-background/50 hover:bg-primary/10 p-4 transition-all duration-300">
<pre className="font-mono text-lg text-primary/70 mb-3 leading-tight whitespace-pre">
{game.icon}
</pre>
<h2 className="font-minecraft text-xl text-primary text-glow mb-2">
{game.name}
</h2>
<div>
<p className="font-pixel text-xs text-foreground/60">HIGH SCORE</p>
<p className="font-minecraft text-2xl text-primary text-glow">
{game.score.toLocaleString()}
</p>
<div className="mt-2 h-2 bg-background/50 border border-primary/30">
<div
className="h-full bg-primary/60 transition-all duration-500"
style={{ width: `${Math.min((game.score / MAX_SCORE) * 100, 100)}%` }}
/>
</div>
<p className="font-pixel text-[10px] text-foreground/40 mt-1">
{((game.score / MAX_SCORE) * 100).toFixed(6)}% to max
</p>
</div>
</div>
</Link>
</motion.div>
))}
</div>
<div className="border border-primary/30 p-2 bg-background/30 mt-4">
<p className="font-pixel text-xs text-foreground/50">
<span className="text-primary">{'>'}</span> Click a game to play and improve your score
</p>
</div>
</motion.div>
);
};
export default Leaderboard;
+70
View File
@@ -0,0 +1,70 @@
import { motion } from 'framer-motion';
import { Github, Linkedin, Mail, Youtube } from 'lucide-react';
const socialLinks = [
{ name: 'YouTube', icon: Youtube, url: 'https://www.youtube.com/@DJorySev', description: 'Watch my content' },
{ name: 'GitHub', icon: Github, url: 'https://github.com/JorySeverijnse', description: 'Browse my code' },
{ name: 'Gitea', icon: Github, url: 'https://git.severijnse.eu/explore/repos', description: 'Self-hosted Git' },
{ name: 'LinkedIn', icon: Linkedin, url: 'https://www.linkedin.com/in/jory-s-5481ab256', description: 'Connect professionally' },
{ name: 'Gmail', icon: Mail, url: 'mailto:joryseverijnse@gmail.com', description: 'Personal email' },
{ name: 'Email', icon: Mail, url: 'mailto:jory@severijnse.eu', description: 'Domain email' },
];
const Links = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="h-full flex flex-col"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong mb-2">
Links
</h1>
<p className="font-pixel text-foreground/80 mb-6">
Connect with me across the web:
</p>
<div className="flex-1 grid grid-cols-2 sm:grid-cols-3 gap-3 content-start">
{socialLinks.map((link, index) => {
const Icon = link.icon;
return (
<motion.a
key={link.name}
href={link.url}
target="_blank"
rel="noopener noreferrer"
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: index * 0.05 }}
className="flex flex-col items-center justify-center gap-2 p-4 border border-primary/30 hover:border-primary transition-all duration-300 hover:box-glow hover:bg-primary/10 rounded-lg"
>
<Icon className="w-8 h-8 text-primary" />
<span className="font-minecraft text-sm text-primary text-glow">
{link.name}
</span>
<span className="font-pixel text-[10px] text-muted-foreground text-center">
{link.description}
</span>
</motion.a>
);
})}
</div>
{/* ASCII Art */}
<pre className="font-mono text-[8px] md:text-[10px] text-primary/30 leading-tight text-center mt-4 select-none">
{` .---.
/ \\
\\.@-@./
/\` \\_/ \`\\
// _ _ \\\\
| \\ / |
\\| \\|/ |/
\`._/_\\_.'"connect with me"`}
</pre>
</motion.div>
);
};
export default Links;
+537
View File
@@ -0,0 +1,537 @@
import { motion, AnimatePresence } from 'framer-motion';
import { useState, useEffect } from 'react';
import { Play, Pause, Volume2, Radio, Search, Loader2, ChevronDown, Link2, SkipBack, SkipForward, Zap } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
import { useMusic, Station } from '@/contexts/MusicContext';
const CATEGORIES = [
{ value: '', label: 'All Genres' },
{ value: 'pop', label: 'Pop' },
{ value: 'rock', label: 'Rock' },
{ value: 'jazz', label: 'Jazz' },
{ value: 'classical', label: 'Classical' },
{ value: 'electronic', label: 'Electronic' },
{ value: 'techno', label: 'Techno' },
{ value: 'house', label: 'House' },
{ value: 'trance', label: 'Trance' },
{ value: 'drum and bass', label: 'Drum & Bass' },
{ value: 'dubstep', label: 'Dubstep' },
{ value: 'hiphop', label: 'Hip Hop' },
{ value: 'country', label: 'Country' },
{ value: 'metal', label: 'Metal' },
{ value: 'ambient', label: 'Ambient' },
{ value: 'lofi', label: 'Lo-Fi' },
{ value: 'chillout', label: 'Chillout' },
{ value: 'synthwave', label: 'Synthwave' },
{ value: 'news', label: 'News' },
{ value: 'talk', label: 'Talk' },
];
// Preset electronic music streams
const PRESET_STREAMS = [
{ name: 'SomaFM - Groove Salad', url: 'https://ice2.somafm.com/groovesalad-128-mp3', genre: 'Ambient/Downtempo' },
{ name: 'SomaFM - DEF CON Radio', url: 'https://ice2.somafm.com/defcon-128-mp3', genre: 'Electronic/Hacker' },
{ name: 'SomaFM - Space Station', url: 'https://ice2.somafm.com/spacestation-128-mp3', genre: 'Space/Ambient' },
{ name: 'SomaFM - Drone Zone', url: 'https://ice2.somafm.com/dronezone-128-mp3', genre: 'Dark Ambient' },
{ name: 'SomaFM - Beat Blender', url: 'https://ice2.somafm.com/beatblender-128-mp3', genre: 'Deep House' },
{ name: 'SomaFM - cliqhop idm', url: 'https://ice2.somafm.com/cliqhop-128-mp3', genre: 'IDM/Glitch' },
{ name: 'Nightwave Plaza', url: 'https://radio.plaza.one/mp3', genre: 'Vaporwave' },
];
interface CategoryDropdownProps {
selectedCategory: string;
onSelect: (value: string) => void;
playSound: (sound: string) => void;
}
const CategoryDropdown = ({ selectedCategory, onSelect, playSound }: CategoryDropdownProps) => {
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useState<HTMLDivElement | null>(null);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (dropdownRef[0] && !dropdownRef[0].contains(e.target as Node)) {
setIsOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [dropdownRef]);
const selectedLabel = CATEGORIES.find(c => c.value === selectedCategory)?.label || 'All Genres';
return (
<div ref={(el) => { dropdownRef[1](el); }} className="relative">
<button
onClick={() => {
playSound('click');
setIsOpen(!isOpen);
}}
className="w-full flex items-center justify-between px-4 py-2 bg-background border border-primary/30 hover:border-primary font-pixel text-sm text-primary transition-colors"
>
<span>{selectedLabel}</span>
<ChevronDown className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</button>
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, y: -5 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -5 }}
transition={{ duration: 0.15 }}
className="absolute top-full left-0 right-0 z-50 mt-1 bg-background border border-primary/50 box-glow max-h-60 overflow-y-auto"
>
{CATEGORIES.map((cat) => (
<button
key={cat.value}
onClick={() => {
playSound('click');
onSelect(cat.value);
setIsOpen(false);
}}
className={`w-full px-4 py-2 text-left font-pixel text-sm transition-colors hover:bg-primary/20 ${
selectedCategory === cat.value ? 'bg-primary/30 text-primary' : 'text-primary/80'
}`}
>
{cat.label}
</button>
))}
</motion.div>
)}
</AnimatePresence>
</div>
);
};
// URL validation helper
const isValidStreamUrl = (url: string): { valid: boolean; error?: string } => {
if (!url.trim()) {
return { valid: false, error: 'Please enter a URL' };
}
try {
const parsed = new URL(url.trim());
// Only allow http/https protocols
if (!['http:', 'https:'].includes(parsed.protocol)) {
return { valid: false, error: 'URL must use http or https protocol' };
}
// Basic format check
if (!parsed.hostname || parsed.hostname.length < 3) {
return { valid: false, error: 'Invalid hostname' };
}
return { valid: true };
} catch {
return { valid: false, error: 'Invalid URL format' };
}
};
const Music = () => {
const [searchQuery, setSearchQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState('');
const [customUrl, setCustomUrl] = useState('');
const [customUrlError, setCustomUrlError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'browse' | 'presets' | 'custom'>('browse');
const [filteredStations, setFilteredStations] = useState<Station[]>([]);
const { playSound } = useSettings();
const {
isPlaying,
isBuffering,
volume,
stations,
selectedStation,
hasFetched,
setVolume,
playStation,
togglePlay,
playNext,
playPrevious,
fetchStations,
} = useMusic();
// Fetch stations on mount
useEffect(() => {
fetchStations();
}, [fetchStations]);
// Filter stations based on search and category
useEffect(() => {
const filtered = stations.filter(station => {
const matchesSearch = station.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
station.tags.toLowerCase().includes(searchQuery.toLowerCase()) ||
station.country.toLowerCase().includes(searchQuery.toLowerCase());
const matchesCategory = !selectedCategory ||
station.tags.toLowerCase().includes(selectedCategory.toLowerCase());
return matchesSearch && matchesCategory;
});
setFilteredStations(filtered);
}, [searchQuery, selectedCategory, stations]);
const handlePlayStation = (station: Station, index: number) => {
playSound('click');
playStation(station, index);
};
// Clear error when URL changes
useEffect(() => {
if (customUrlError) setCustomUrlError(null);
}, [customUrl]);
const playCustomUrl = () => {
const validation = isValidStreamUrl(customUrl);
if (!validation.valid) {
setCustomUrlError(validation.error || 'Invalid URL');
playSound('error');
return;
}
setCustomUrlError(null);
playSound('click');
const customStation: Station = {
stationuuid: 'custom-' + Date.now(),
name: 'Custom Stream',
url: customUrl.trim(),
favicon: '',
country: 'Custom',
tags: 'custom',
bitrate: 0,
};
playStation(customStation, -1);
};
const playPreset = (preset: typeof PRESET_STREAMS[0]) => {
playSound('click');
const presetStation: Station = {
stationuuid: 'preset-' + preset.name,
name: preset.name,
url: preset.url,
favicon: '',
country: preset.genre,
tags: preset.genre.toLowerCase(),
bitrate: 128,
};
playStation(presetStation, -1);
};
const handleTogglePlay = () => {
playSound('click');
togglePlay();
};
const handlePlayNext = () => {
playSound('click');
playNext();
};
const handlePlayPrevious = () => {
playSound('click');
playPrevious();
};
const isLoading = !hasFetched;
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Radio Player
</h1>
<p className="font-pixel text-foreground/80">
Stream radio stations from around the world or add your own stream URL.
</p>
{/* Now Playing */}
{selectedStation && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="border border-primary p-4 bg-primary/5 box-glow space-y-4"
>
<div className="flex items-center gap-4">
<div className="w-12 h-12 border border-primary/50 flex items-center justify-center bg-background">
{selectedStation.favicon ? (
<img
src={selectedStation.favicon}
alt={selectedStation.name}
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : (
<Radio className="w-6 h-6 text-primary" />
)}
</div>
<div className="flex-1 min-w-0">
<h2 className="font-minecraft text-lg text-primary text-glow truncate">
{selectedStation.name}
</h2>
<p className="font-pixel text-xs text-foreground/60 truncate">
{selectedStation.country} {selectedStation.bitrate > 0 && `${selectedStation.bitrate}kbps`}
</p>
{isBuffering && (
<p className="font-pixel text-xs text-primary/60">Buffering...</p>
)}
</div>
{/* Playback Controls */}
<div className="flex items-center gap-2">
<button
onClick={handlePlayPrevious}
className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
title="Previous station"
>
<SkipBack size={16} />
</button>
<button
onClick={handleTogglePlay}
className="p-3 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
disabled={isBuffering}
>
{isBuffering ? (
<Loader2 size={20} className="animate-spin" />
) : isPlaying ? (
<Pause size={20} />
) : (
<Play size={20} />
)}
</button>
<button
onClick={handlePlayNext}
className="p-2 border border-primary/50 text-primary hover:bg-primary hover:text-background transition-all duration-300"
title="Next station"
>
<SkipForward size={16} />
</button>
</div>
</div>
<div className="flex items-center gap-3">
<Volume2 size={16} className="text-primary" />
<input
type="range"
min="0"
max="100"
value={volume}
onChange={(e) => setVolume(Number(e.target.value))}
className="flex-1 h-1.5 bg-primary/30 appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-primary [&::-webkit-slider-thumb]:shadow-[0_0_5px_hsl(var(--glow-color)/0.8)]"
/>
<span className="font-pixel text-xs text-primary min-w-[40px]">
{volume}%
</span>
</div>
</motion.div>
)}
{/* Tabs */}
<div className="flex gap-2 border-b border-primary/30">
{(['browse', 'presets', 'custom'] as const).map((tab) => (
<button
key={tab}
onClick={() => {
playSound('click');
setActiveTab(tab);
}}
className={`px-4 py-2 font-pixel text-sm transition-all ${
activeTab === tab
? 'text-primary border-b-2 border-primary text-glow'
: 'text-foreground/60 hover:text-primary'
}`}
>
{tab === 'browse' && 'Browse'}
{tab === 'presets' && 'Electronic'}
{tab === 'custom' && 'Custom URL'}
</button>
))}
</div>
{/* Browse Tab */}
{activeTab === 'browse' && (
<>
{/* Filters */}
<div className="flex flex-col sm:flex-row gap-3">
<div className="sm:w-48">
<CategoryDropdown
selectedCategory={selectedCategory}
onSelect={setSelectedCategory}
playSound={playSound}
/>
</div>
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-primary/50" />
<input
type="text"
placeholder="Search stations..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-10 pr-4 py-2 bg-background border border-primary/30 focus:border-primary font-pixel text-sm text-foreground placeholder:text-foreground/40 outline-none transition-colors"
/>
</div>
</div>
{/* Station List */}
<div className="border border-primary/30 max-h-[250px] overflow-y-auto">
{isLoading ? (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 text-primary animate-spin" />
<span className="font-pixel text-sm text-primary ml-2">Loading stations...</span>
</div>
) : filteredStations.length === 0 ? (
<div className="p-4 text-center">
<p className="font-pixel text-sm text-foreground/60">No stations found</p>
</div>
) : (
filteredStations.map((station, index) => (
<motion.button
key={station.stationuuid}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: index * 0.02 }}
onClick={() => handlePlayStation(station, index)}
className={`w-full flex items-center gap-3 p-3 border-b border-primary/10 hover:bg-primary/10 transition-all duration-200 text-left ${
selectedStation?.stationuuid === station.stationuuid ? 'bg-primary/20' : ''
}`}
>
<div className="w-8 h-8 border border-primary/30 flex items-center justify-center flex-shrink-0 bg-background">
{station.favicon ? (
<img
src={station.favicon}
alt=""
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : (
<Radio className="w-4 h-4 text-primary/50" />
)}
</div>
<div className="flex-1 min-w-0">
<p className="font-pixel text-sm text-primary truncate">{station.name}</p>
<p className="font-pixel text-xs text-foreground/50 truncate">
{station.country} {station.tags && `${station.tags.split(',')[0]}`}
</p>
</div>
{selectedStation?.stationuuid === station.stationuuid && isPlaying && (
<div className="flex gap-0.5">
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '0ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '150ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '300ms' }} />
</div>
)}
</motion.button>
))
)}
</div>
<p className="font-pixel text-xs text-foreground/50 text-center">
{filteredStations.length} stations available
</p>
</>
)}
{/* Electronic Presets Tab */}
{activeTab === 'presets' && (
<div className="space-y-4">
<div className="flex items-center gap-2 text-primary mb-4">
<Zap size={16} />
<span className="font-pixel text-sm">Curated Electronic Streams</span>
</div>
<div className="border border-primary/30 max-h-[300px] overflow-y-auto">
{PRESET_STREAMS.map((preset, index) => (
<motion.button
key={preset.name}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: index * 0.05 }}
onClick={() => playPreset(preset)}
className={`w-full flex items-center gap-3 p-3 border-b border-primary/10 hover:bg-primary/10 transition-all duration-200 text-left ${
selectedStation?.name === preset.name ? 'bg-primary/20' : ''
}`}
>
<div className="w-8 h-8 border border-primary/30 flex items-center justify-center flex-shrink-0 bg-background">
<Zap className="w-4 h-4 text-primary/70" />
</div>
<div className="flex-1 min-w-0">
<p className="font-pixel text-sm text-primary truncate">{preset.name}</p>
<p className="font-pixel text-xs text-foreground/50 truncate">{preset.genre}</p>
</div>
{selectedStation?.name === preset.name && isPlaying && (
<div className="flex gap-0.5">
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '0ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '150ms' }} />
<span className="w-1 h-3 bg-primary animate-pulse" style={{ animationDelay: '300ms' }} />
</div>
)}
</motion.button>
))}
</div>
<p className="font-pixel text-xs text-foreground/50 text-center">
High-quality electronic music streams from SomaFM and others
</p>
</div>
)}
{/* Custom URL Tab */}
{activeTab === 'custom' && (
<div className="space-y-4">
<div className="flex items-center gap-2 text-primary mb-4">
<Link2 size={16} />
<span className="font-pixel text-sm">Play Custom Stream URL</span>
</div>
<p className="font-pixel text-xs text-foreground/60">
Enter a direct URL to an audio stream (MP3, AAC, OGG, etc.)
</p>
<div className="flex gap-2">
<input
type="url"
placeholder="https://stream.example.com/radio.mp3"
value={customUrl}
onChange={(e) => setCustomUrl(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && playCustomUrl()}
className={`flex-1 px-4 py-2 bg-background border font-pixel text-sm text-foreground placeholder:text-foreground/40 outline-none transition-colors ${
customUrlError ? 'border-destructive focus:border-destructive' : 'border-primary/30 focus:border-primary'
}`}
/>
<button
onClick={playCustomUrl}
disabled={!customUrl.trim()}
className="px-4 py-2 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300 font-pixel text-sm disabled:opacity-50 disabled:cursor-not-allowed"
>
Play
</button>
</div>
{customUrlError && (
<p className="font-pixel text-xs text-destructive">{customUrlError}</p>
)}
<div className="border border-primary/20 p-3 bg-primary/5">
<p className="font-pixel text-xs text-primary mb-2">Tips:</p>
<ul className="font-pixel text-xs text-foreground/60 space-y-1 list-disc list-inside">
<li>Use direct stream URLs (not webpage URLs)</li>
<li>Supported formats: MP3, AAC, OGG, FLAC</li>
<li>Look for .m3u or .pls files on radio sites</li>
<li>SomaFM, Radio.co, and Icecast streams work well</li>
</ul>
</div>
</div>
)}
</motion.div>
);
};
export default Music;
+90
View File
@@ -0,0 +1,90 @@
import { useLocation, Link } from "react-router-dom";
import { useEffect } from "react";
import { motion } from "framer-motion";
import { Terminal, AlertTriangle } from "lucide-react";
import { useSettings } from "@/contexts/SettingsContext";
const NotFound = () => {
const location = useLocation();
const { playSound } = useSettings();
useEffect(() => {
console.error("404 Error: User attempted to access non-existent route:", location.pathname);
playSound('error');
}, [location.pathname, playSound]);
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="text-center space-y-6 max-w-md"
>
{/* Error code */}
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ delay: 0.2, duration: 0.4 }}
className="flex items-center justify-center gap-3"
>
<AlertTriangle className="w-10 h-10 text-primary animate-pulse" />
<h1 className="font-minecraft text-6xl md:text-7xl text-primary text-glow">
404
</h1>
</motion.div>
{/* Terminal-style message */}
<div className="border border-primary/30 bg-background/80 p-4 rounded">
<div className="flex items-center gap-2 mb-3 pb-2 border-b border-primary/20">
<Terminal className="w-4 h-4 text-primary/60" />
<span className="font-pixel text-xs text-muted-foreground">error.log</span>
</div>
<div className="text-left space-y-2">
<p className="font-pixel text-sm text-primary">
<span className="text-muted-foreground">$</span> cd {location.pathname}
</p>
<p className="font-pixel text-sm text-destructive">
ERROR: Directory not found
</p>
<p className="font-pixel text-xs text-muted-foreground">
The requested path does not exist on this server.
</p>
</div>
</div>
{/* ASCII Art */}
<pre className="font-mono text-[10px] md:text-xs text-primary/40 leading-tight select-none">
{` _____
/ \\
| X X |
| ^ |
| === |
\\_____/
LOST IN THE VOID`}
</pre>
{/* Navigation */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.5, duration: 0.4 }}
className="space-y-3"
>
<p className="font-pixel text-xs text-muted-foreground">
{'>'} Return to known territory:
</p>
<Link
to="/"
onClick={() => playSound('click')}
className="inline-block font-minecraft text-sm text-primary hover:text-glow border border-primary/50 hover:border-primary px-4 py-2 transition-all duration-200 hover:bg-primary/10"
>
cd /home
</Link>
</motion.div>
</motion.div>
</div>
);
};
export default NotFound;
+384
View File
@@ -0,0 +1,384 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const GRID_WIDTH = 21;
const GRID_HEIGHT = 21;
const TICK_SPEED = 180;
const POWER_DURATION = 8000;
const MAX_SCORE = 4294967296;
const HIGHSCORE_KEY = 'pacman-highscore';
type Direction = 'up' | 'down' | 'left' | 'right';
type Position = { x: number; y: number };
const MAZE_TEMPLATE = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,3,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,3,1],
[1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,0,1],
[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
[1,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,1],
[1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1],
[1,1,1,1,0,1,0,1,1,0,0,0,1,1,0,1,0,1,1,1,1],
[2,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,2],
[1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1],
[1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1],
[1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,0,1],
[1,3,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,3,1],
[1,1,0,1,0,1,0,1,1,1,1,1,1,1,0,1,0,1,0,1,1],
[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
[1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
];
const Pacman = () => {
const { playSound } = useSettings();
const [pacman, setPacman] = useState<Position>({ x: 10, y: 15 });
const [direction, setDirection] = useState<Direction>('right');
const [nextDirection, setNextDirection] = useState<Direction>('right');
const [mouthOpen, setMouthOpen] = useState(true);
const [ghosts, setGhosts] = useState<{ pos: Position; dir: Direction; eaten: boolean }[]>([
{ pos: { x: 9, y: 9 }, dir: 'left', eaten: false },
{ pos: { x: 10, y: 9 }, dir: 'up', eaten: false },
{ pos: { x: 11, y: 9 }, dir: 'right', eaten: false },
]);
const [dots, setDots] = useState<Set<string>>(new Set());
const [powerPellets, setPowerPellets] = useState<Set<string>>(new Set());
const [isPowered, setIsPowered] = useState(false);
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [gameOver, setGameOver] = useState(false);
const [gameComplete, setGameComplete] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const [level, setLevel] = useState(1);
const [isFullscreen, setIsFullscreen] = useState(false);
const gameRef = useRef<HTMLDivElement>(null);
const powerTimerRef = useRef<NodeJS.Timeout | null>(null);
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
const getCellSize = useCallback(() => {
if (typeof window === 'undefined') return 20;
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 40;
const maxHeight = window.innerHeight - 300;
return Math.min(Math.floor(maxWidth / GRID_WIDTH), Math.floor(maxHeight / GRID_HEIGHT), 16);
}
return isFullscreen ? 26 : 20;
}, [isFullscreen]);
const [cellSize, setCellSize] = useState(getCellSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCellSize(getCellSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCellSize]);
useEffect(() => { setCellSize(getCellSize()); }, [isFullscreen, getCellSize]);
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) { setIsFullscreen(true); enterFullscreen(); }
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) { setIsFullscreen(true); await enterFullscreen(); }
else { setIsFullscreen(false); await exitFullscreen(); }
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape' && isFullscreen) { setIsFullscreen(false); exitFullscreen(); } };
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const initDots = useCallback(() => {
const newDots = new Set<string>();
const newPowerPellets = new Set<string>();
for (let y = 0; y < GRID_HEIGHT; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
if (MAZE_TEMPLATE[y][x] === 0) newDots.add(`${x},${y}`);
else if (MAZE_TEMPLATE[y][x] === 3) newPowerPellets.add(`${x},${y}`);
}
}
newDots.delete('10,15'); newDots.delete('9,9'); newDots.delete('10,9'); newDots.delete('11,9');
return { dots: newDots, powerPellets: newPowerPellets };
}, []);
const canMove = (pos: Position, dir: Direction): boolean => {
let newX = pos.x, newY = pos.y;
switch (dir) { case 'up': newY--; break; case 'down': newY++; break; case 'left': newX--; break; case 'right': newX++; break; }
if (newX < 0) return MAZE_TEMPLATE[newY]?.[GRID_WIDTH - 1] !== 1;
if (newX >= GRID_WIDTH) return MAZE_TEMPLATE[newY]?.[0] !== 1;
if (newY < 0 || newY >= GRID_HEIGHT) return false;
return MAZE_TEMPLATE[newY][newX] !== 1;
};
const moveEntity = (pos: Position, dir: Direction): Position => {
let newX = pos.x, newY = pos.y;
switch (dir) { case 'up': newY--; break; case 'down': newY++; break; case 'left': newX--; break; case 'right': newX++; break; }
if (newX < 0) newX = GRID_WIDTH - 1;
if (newX >= GRID_WIDTH) newX = 0;
return { x: newX, y: newY };
};
const activatePowerMode = () => {
if (powerTimerRef.current) clearTimeout(powerTimerRef.current);
setIsPowered(true);
powerTimerRef.current = setTimeout(() => { setIsPowered(false); setGhosts(prev => prev.map(g => ({ ...g, eaten: false }))); }, POWER_DURATION);
};
const startGame = () => {
if (powerTimerRef.current) clearTimeout(powerTimerRef.current);
setPacman({ x: 10, y: 15 }); setDirection('right'); setNextDirection('right'); setMouthOpen(true);
setGhosts([{ pos: { x: 9, y: 9 }, dir: 'left', eaten: false }, { pos: { x: 10, y: 9 }, dir: 'up', eaten: false }, { pos: { x: 11, y: 9 }, dir: 'right', eaten: false }]);
const { dots: newDots, powerPellets: newPowerPellets } = initDots();
setDots(newDots); setPowerPellets(newPowerPellets); setIsPowered(false); setScore(0); setLevel(1);
setGameOver(false); setGameComplete(false); setIsPaused(false); setGameStarted(true);
playSound('success'); gameRef.current?.focus();
};
useEffect(() => { return () => { if (powerTimerRef.current) clearTimeout(powerTimerRef.current); }; }, []);
useEffect(() => {
if (!gameStarted || gameOver || gameComplete || isPaused) return;
const interval = setInterval(() => {
setMouthOpen(prev => !prev);
if (canMove(pacman, nextDirection)) setDirection(nextDirection);
const actualDir = canMove(pacman, nextDirection) ? nextDirection : direction;
if (canMove(pacman, actualDir)) {
const newPos = moveEntity(pacman, actualDir);
setPacman(newPos);
const posKey = `${newPos.x},${newPos.y}`;
if (powerPellets.has(posKey)) {
setPowerPellets(prev => { const np = new Set(prev); np.delete(posKey); return np; });
activatePowerMode();
setScore(prev => {
const ns = Math.min(prev + 50, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('success');
} else if (dots.has(posKey)) {
setDots(prev => { const nd = new Set(prev); nd.delete(posKey); return nd; });
setScore(prev => {
const ns = Math.min(prev + 10, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('hover');
}
}
setGhosts(prev => prev.map(ghost => {
if (ghost.eaten) return ghost;
const directions: Direction[] = ['up', 'down', 'left', 'right'];
const opposite: Record<Direction, Direction> = { up: 'down', down: 'up', left: 'right', right: 'left' };
const validDirs = directions.filter(d => d !== opposite[ghost.dir] && canMove(ghost.pos, d));
if (validDirs.length === 0) {
const anyValid = directions.filter(d => canMove(ghost.pos, d));
if (anyValid.length === 0) return ghost;
const dir = anyValid[Math.floor(Math.random() * anyValid.length)];
return { ...ghost, pos: moveEntity(ghost.pos, dir), dir };
}
const dx = pacman.x - ghost.pos.x, dy = pacman.y - ghost.pos.y;
let preferredDirs: Direction[] = [];
if (isPowered) { preferredDirs = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? ['left', 'up', 'down', 'right'] : ['right', 'down', 'up', 'left']) : (dy > 0 ? ['up', 'left', 'right', 'down'] : ['down', 'right', 'left', 'up']); }
else { preferredDirs = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? ['right', 'down', 'up', 'left'] : ['left', 'up', 'down', 'right']) : (dy > 0 ? ['down', 'right', 'left', 'up'] : ['up', 'left', 'right', 'down']); }
if (Math.random() < 0.6) { for (const dir of preferredDirs) { if (validDirs.includes(dir)) return { ...ghost, pos: moveEntity(ghost.pos, dir), dir }; } }
const dir = validDirs[Math.floor(Math.random() * validDirs.length)];
return { ...ghost, pos: moveEntity(ghost.pos, dir), dir };
}));
}, TICK_SPEED);
return () => clearInterval(interval);
}, [gameStarted, gameOver, gameComplete, isPaused, pacman, direction, nextDirection, dots, powerPellets, highScore, isPowered, playSound]);
useEffect(() => {
if (!gameStarted || gameOver || gameComplete) return;
for (let i = 0; i < ghosts.length; i++) {
const ghost = ghosts[i];
if (ghost.pos.x === pacman.x && ghost.pos.y === pacman.y) {
if (isPowered && !ghost.eaten) {
setGhosts(prev => prev.map((g, idx) => idx === i ? { ...g, eaten: true, pos: { x: 10, y: 9 } } : g));
setScore(prev => {
const ns = Math.min(prev + 200, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
playSound('success');
} else if (!ghost.eaten) { setGameOver(true); playSound('error'); return; }
}
}
if (dots.size === 0 && powerPellets.size === 0) {
setScore(prev => {
const ns = Math.min(prev + 500, MAX_SCORE);
if (ns >= MAX_SCORE) setShowGlitchCrash(true);
if (ns > highScore) { setHighScore(ns); localStorage.setItem(HIGHSCORE_KEY, ns.toString()); }
return ns;
});
setLevel(prev => prev + 1);
const { dots: newDots, powerPellets: newPowerPellets } = initDots();
setDots(newDots); setPowerPellets(newPowerPellets);
playSound('success');
}
}, [pacman, ghosts, dots, powerPellets, gameStarted, gameOver, gameComplete, highScore, isPowered, playSound, initDots]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (!gameStarted) return;
switch (e.key) {
case 'ArrowUp': case 'w': e.preventDefault(); setNextDirection('up'); break;
case 'ArrowDown': case 's': e.preventDefault(); setNextDirection('down'); break;
case 'ArrowLeft': case 'a': e.preventDefault(); setNextDirection('left'); break;
case 'ArrowRight': case 'd': e.preventDefault(); setNextDirection('right'); break;
case 'p': e.preventDefault(); if (!gameOver && !gameComplete) setIsPaused(prev => !prev); break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [gameStarted, gameOver, gameComplete]);
const getPacmanRotation = () => { switch (direction) { case 'right': return 0; case 'down': return 90; case 'left': return 180; case 'up': return 270; } };
const renderPacman = () => (
<svg viewBox="0 0 100 100" className="w-full h-full" style={{ transform: `rotate(${getPacmanRotation()}deg)` }}>
<circle cx="50" cy="50" r="45" fill="hsl(var(--primary))" />
{mouthOpen && <path d="M 50 50 L 95 25 L 95 75 Z" fill="hsl(var(--background))" />}
<circle cx="50" cy="25" r="6" fill="hsl(var(--background))" />
</svg>
);
const renderGhost = (index: number, eaten: boolean) => {
const colors = ['hsl(0 70% 50%)', 'hsl(300 70% 50%)', 'hsl(180 70% 50%)'];
const scaredColor = 'hsl(220 70% 50%)';
if (eaten) return null;
return (
<svg viewBox="0 0 100 100" className="w-full h-full">
<path d={`M 10 95 L 10 45 Q 10 5 50 5 Q 90 5 90 45 L 90 95 L 75 80 L 60 95 L 50 80 L 40 95 L 25 80 L 10 95 Z`} fill={isPowered ? scaredColor : colors[index % colors.length]} className={isPowered ? 'animate-pulse' : ''} />
<ellipse cx="35" cy="45" rx="12" ry="15" fill="white" /><ellipse cx="65" cy="45" rx="12" ry="15" fill="white" />
<circle cx="38" cy="48" r="6" fill="hsl(var(--background))" /><circle cx="68" cy="48" r="6" fill="hsl(var(--background))" />
</svg>
);
};
const renderGrid = () => {
const cells = [];
const spriteSize = Math.max(cellSize * 0.7, 12);
for (let y = 0; y < GRID_HEIGHT; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
const isWall = MAZE_TEMPLATE[y][x] === 1;
const isTunnel = MAZE_TEMPLATE[y][x] === 2;
const isPacmanHere = pacman.x === x && pacman.y === y;
const ghostIndex = ghosts.findIndex(g => g.pos.x === x && g.pos.y === y && !g.eaten);
const isDot = dots.has(`${x},${y}`);
const isPowerPellet = powerPellets.has(`${x},${y}`);
cells.push(
<div key={`${x}-${y}`} className={`flex items-center justify-center transition-colors duration-100 ${isWall ? 'bg-primary/20 border border-primary/40' : isTunnel ? 'bg-background/30' : 'bg-background/50 border border-primary/5'}`} style={{ width: cellSize, height: cellSize }}>
{isPacmanHere && <div style={{ width: spriteSize, height: spriteSize }}>{renderPacman()}</div>}
{ghostIndex !== -1 && !isPacmanHere && <div style={{ width: spriteSize, height: spriteSize }}>{renderGhost(ghostIndex, ghosts[ghostIndex].eaten)}</div>}
{isDot && !isPacmanHere && ghostIndex === -1 && <div className="w-1.5 h-1.5 bg-primary/80 rounded-full" />}
{isPowerPellet && !isPacmanHere && ghostIndex === -1 && <div className="w-3 h-3 bg-primary rounded-full animate-pulse box-glow" />}
</div>
);
}
}
return cells;
};
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div ref={gameRef} tabIndex={0} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Pac-Man</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
<div className="border-2 border-primary box-glow p-1 bg-background/80">
<div className="grid" style={{ gridTemplateColumns: `repeat(${GRID_WIDTH}, ${cellSize}px)` }}>{renderGrid()}</div>
</div>
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">SCORE</p><p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p><p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p><p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LEVEL</p><p className="font-minecraft text-lg text-primary text-glow">{level}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p><p className="font-pixel text-[10px] text-foreground/80"> / WASD</p><p className="font-pixel text-[10px] text-foreground/80">P: Pause</p></div>
{!gameStarted || gameOver || gameComplete ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
) : (
<button onClick={() => setIsPaused(p => !p)} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">{isPaused ? 'RESUME' : 'PAUSE'}</button>
)}
</div>
)}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LVL</p><p className="font-minecraft text-sm text-primary">{level}</p></div>
</div>
{gameStarted && !gameOver && !gameComplete && (
<div className="grid grid-cols-3 gap-1 mt-2">
<div />
<GameTouchButton onAction={() => setNextDirection('up')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => setNextDirection('left')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<button onClick={() => setIsPaused(p => !p)} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={() => setNextDirection('right')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => setNextDirection('down')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
</div>
)}
{(!gameStarted || gameOver || gameComplete) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
)}
</div>
)}
</div>
{!isMobile && (gameOver || isPaused || gameComplete) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameComplete ? 'GAME COMPLETE!' : gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{(gameOver || gameComplete) && (<><p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p><p className="font-pixel text-xs text-foreground/60 mb-3">Level: {level}</p></>)}
<button onClick={(gameOver || gameComplete) ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{(gameOver || gameComplete) ? 'PLAY AGAIN' : 'RESUME'}</button>
</div>
</div>
)}
</motion.div>
);
};
export default Pacman;
+255
View File
@@ -0,0 +1,255 @@
import { useParams, Link } from 'react-router-dom';
import { motion } from 'framer-motion';
import { ArrowLeft, ExternalLink, Github } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
interface ProjectData {
title: string;
description: string;
status: string;
longDescription: string;
technologies: string[];
features: string[];
links?: {
demo?: string;
github?: string;
};
}
const projectsData: Record<string, ProjectData> = {
'personal-website': {
title: 'Personal Website',
description: 'This Matrix-themed personal website with retro hacker aesthetics.',
status: 'Complete',
longDescription: 'A fully custom personal website built with React and TypeScript, featuring a Matrix-inspired cyberpunk design. The site includes immersive visual effects like CRT scanlines, Matrix rain animation, and glitch text. Interactive features include a terminal command interface with navigation shortcuts, toggleable sound effects, an integrated AI chat powered by Pollinations.ai, and a radio music player with station browsing. Designed to showcase my projects and personality with a unique hacker aesthetic.',
technologies: ['React', 'TypeScript', 'Tailwind CSS', 'Framer Motion', 'Web Audio API', 'Pollinations.ai', 'Radio Browser API'],
features: [
'Matrix rain animation background with customizable density',
'Custom crosshair cursor with hover scaling effects',
'CRT scanline and flicker effects (toggleable)',
'Terminal command interface with navigation shortcuts (/home, /about, /ai, etc.)',
'Sound effects system with keyboard clicks and terminal beeps',
'Red/Green theme toggle with localStorage persistence',
'ASCII boot sequence with fake system initialization',
'Glitch text effects on hover (character scrambling)',
'Hidden easter egg for old-school gamers',
'AI chat integration with conversation history persistence',
'Radio music player with station search and category filtering',
'Persistent mini music player across all pages',
'Custom Matrix-themed scrollbar',
'Dynamic status based on Amsterdam timezone',
'ASCII art portrait on About page',
'Responsive design for all screen sizes',
],
},
'3-way-speakers': {
title: '3 Way Speakers',
description: 'Building custom 3-way speaker system with crossover design.',
status: 'Complete',
longDescription: 'A DIY audio project involving the design and construction of high-fidelity 3-way speakers. This includes selecting appropriate drivers, designing custom crossover circuits, and building enclosures optimized for acoustic performance.',
technologies: ['Electronics', 'Woodworking', 'Audio Engineering', 'Circuit Design'],
features: [
'Custom crossover network design',
'Frequency response optimization',
'MDF enclosure construction',
'Driver selection and matching',
'Acoustic dampening',
'Bi-wire terminal setup',
],
},
'xray-machine': {
title: 'X-Ray Machine',
description: 'DIY X-ray machine project for educational purposes.',
status: 'In Progress',
longDescription: 'An educational project exploring the principles of X-ray generation and imaging. This involves understanding high-voltage electronics, radiation safety, and imaging techniques. Built with proper safety measures and shielding for experimental purposes.',
technologies: ['High Voltage Electronics', 'Vacuum Tubes', 'Radiation Physics', 'Safety Engineering'],
features: [
'High voltage power supply design',
'X-ray tube integration',
'Lead shielding enclosure',
'Imaging plate system',
'Safety interlock system',
'Dosimetry monitoring',
],
},
'dj-mixing-visualizer': {
title: 'Automated DJ Mixing & Visualizer',
description: 'Automated DJ mixing script with audio visualizer XY mode.',
status: 'In Progress',
longDescription: 'A software project that automates DJ mixing by analyzing BPM, key, and energy levels of tracks. Features an XY mode audio visualizer that creates real-time visual representations of the music being played, perfect for live performances and streaming.',
technologies: ['Python', 'Audio Analysis', 'FFT', 'OpenGL', 'MIDI'],
features: [
'Automatic BPM detection and sync',
'Key detection for harmonic mixing',
'XY mode oscilloscope visualizer',
'Real-time audio analysis',
'Crossfade automation',
'Beat-matched transitions',
'Waveform display',
],
},
'vps-infrastructure': {
title: 'VPS Server Infrastructure',
description: 'Self-hosted VPS with authoritative nameserver, git, password manager, mail, reverse proxy and VPN.',
status: 'Complete',
longDescription: 'A comprehensive self-hosted server infrastructure project. Running on a VPS with full control over DNS, version control, secure password management, email services, and network security. Built for privacy, control, and learning.',
technologies: ['Linux', 'CoreDNS', 'Gitea', 'Vaultwarden', 'Postfix/Dovecot', 'Caddy', 'WireGuard'],
features: [
'Authoritative DNS nameserver (CoreDNS)',
'Self-hosted Git server (Gitea)',
'Password manager (Vaultwarden)',
'Mail server with SMTP/IMAP',
'Caddy reverse proxy with automatic SSL',
'WireGuard VPN server',
'Automated backups',
],
},
};
const ProjectDetail = () => {
const { slug } = useParams<{ slug: string }>();
const { playSound } = useSettings();
const project = slug ? projectsData[slug] : null;
if (!project) {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl text-primary text-glow-strong">
Project Not Found
</h1>
<Link
to="/projects"
onClick={() => playSound('click')}
className="inline-flex items-center gap-2 font-pixel text-primary hover:text-primary/80 transition-colors"
>
<ArrowLeft size={16} />
Back to Projects
</Link>
</motion.div>
);
}
const statusColor = {
'Complete': 'text-green-400 border-green-400',
'In Progress': 'text-yellow-400 border-yellow-400',
'Planning': 'text-blue-400 border-blue-400',
}[project.status] || 'text-primary border-primary';
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<Link
to="/projects"
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="inline-flex items-center gap-2 font-pixel text-primary hover:text-primary/80 transition-colors"
>
<ArrowLeft size={16} />
Back to Projects
</Link>
<div className="flex flex-wrap items-start justify-between gap-4">
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
{project.title}
</h1>
<span className={`font-pixel text-xs px-3 py-1 border ${statusColor}`}>
{project.status}
</span>
</div>
<p className="font-pixel text-foreground/80 leading-relaxed">
{project.longDescription}
</p>
{/* Technologies */}
<div className="space-y-3">
<h2 className="font-minecraft text-xl text-primary text-glow">
Technologies
</h2>
<div className="flex flex-wrap gap-2">
{project.technologies.map((tech) => (
<span
key={tech}
className="font-pixel text-xs px-3 py-1 border border-primary/50 text-primary bg-primary/10"
>
{tech}
</span>
))}
</div>
</div>
{/* Features */}
<div className="space-y-3">
<h2 className="font-minecraft text-xl text-primary text-glow">
Features
</h2>
<ul className="space-y-2">
{project.features.map((feature, index) => (
<motion.li
key={feature}
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.1 }}
className="font-pixel text-foreground/80 flex items-center gap-2"
>
<span className="text-primary">{'>'}</span>
{feature.includes('easter egg') ? (
<span className="group cursor-help inline-flex items-center gap-2">
{feature}
<span className="px-2 py-0.5 bg-primary/10 border border-primary/30 text-primary/50 text-xs opacity-0 group-hover:opacity-100 transition-opacity duration-300 whitespace-nowrap">
... you know the rest
</span>
</span>
) : (
feature
)}
</motion.li>
))}
</ul>
</div>
{/* Links */}
{project.links && (
<div className="flex gap-4 pt-4">
{project.links.demo && (
<a
href={project.links.demo}
target="_blank"
rel="noopener noreferrer"
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="inline-flex items-center gap-2 font-pixel text-sm px-4 py-2 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
>
<ExternalLink size={14} />
Live Demo
</a>
)}
{project.links.github && (
<a
href={project.links.github}
target="_blank"
rel="noopener noreferrer"
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="inline-flex items-center gap-2 font-pixel text-sm px-4 py-2 border border-primary text-primary hover:bg-primary hover:text-background transition-all duration-300"
>
<Github size={14} />
Source Code
</a>
)}
</div>
)}
</motion.div>
);
};
export default ProjectDetail;
+100
View File
@@ -0,0 +1,100 @@
import { motion } from 'framer-motion';
import { Link } from 'react-router-dom';
import { ArrowRight } from 'lucide-react';
import { useSettings } from '@/contexts/SettingsContext';
const projects = [
{
slug: 'personal-website',
title: 'Personal Website',
description: 'This Matrix-themed personal website with retro hacker aesthetics.',
status: 'Complete',
},
{
slug: '3-way-speakers',
title: '3 Way Speakers',
description: 'Building custom 3-way speaker system with crossover design.',
status: 'Complete',
},
{
slug: 'xray-machine',
title: 'X-Ray Machine',
description: 'DIY X-ray machine project for educational purposes.',
status: 'In Progress',
},
{
slug: 'dj-mixing-visualizer',
title: 'Automated DJ Mixing & Visualizer',
description: 'Automated DJ mixing script with audio visualizer XY mode.',
status: 'In Progress',
},
{
slug: 'vps-infrastructure',
title: 'VPS Server Infrastructure',
description: 'Self-hosted VPS with authoritative nameserver, git, password manager, mail, reverse proxy and VPN.',
status: 'Complete',
},
];
const Projects = () => {
const { playSound } = useSettings();
const statusColor = (status: string) => {
return {
'Complete': 'text-green-400 border-green-400',
'In Progress': 'text-yellow-400 border-yellow-400',
'Planning': 'text-blue-400 border-blue-400',
}[status] || 'text-primary border-primary';
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Projects
</h1>
<p className="font-pixel text-foreground/80">
Here are some of the things I've been working on:
</p>
<div className="grid gap-4">
{projects.map((project, index) => (
<motion.div
key={project.slug}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.1 }}
>
<Link
to={`/projects/${project.slug}`}
onClick={() => playSound('click')}
onMouseEnter={() => playSound('hover')}
className="group block p-4 border border-primary/30 hover:border-primary transition-all duration-300 hover:box-glow"
>
<div className="flex justify-between items-start mb-2">
<h2 className="font-minecraft text-xl text-primary text-glow group-hover:text-glow-strong transition-all">
{project.title}
</h2>
<span className={`font-pixel text-xs px-2 py-1 border ${statusColor(project.status)}`}>
{project.status}
</span>
</div>
<p className="font-pixel text-foreground/80 mb-3">{project.description}</p>
<div className="flex items-center gap-2 font-pixel text-sm text-primary opacity-0 group-hover:opacity-100 transition-opacity duration-300">
<span>View Details</span>
<ArrowRight size={14} />
</div>
</Link>
</motion.div>
))}
</div>
</motion.div>
);
};
export default Projects;
+110
View File
@@ -0,0 +1,110 @@
import { motion } from 'framer-motion';
import { ExternalLink, Book, Wrench, Code, Server } from 'lucide-react';
const resourceCategories = [
{
title: 'Documentation',
icon: Book,
resources: [
{ name: 'MDN Web Docs', url: 'https://developer.mozilla.org', description: 'Web development reference' },
{ name: 'React Documentation', url: 'https://react.dev', description: 'Official React docs' },
{ name: 'TypeScript Handbook', url: 'https://www.typescriptlang.org/docs/', description: 'TypeScript guide' },
],
},
{
title: 'Development Tools',
icon: Wrench,
resources: [
{ name: 'Neovim', url: 'https://neovim.io', description: 'Hyperextensible Vim-based text editor' },
{ name: 'GitHub', url: 'https://github.com', description: 'Version control & collaboration' },
{ name: 'Gitea', url: 'https://gitea.io', description: 'Self-hosted Git service' },
{ name: 'Figma', url: 'https://figma.com', description: 'Design & prototyping' },
],
},
{
title: 'Frameworks & Libraries',
icon: Code,
resources: [
{ name: 'Tailwind CSS', url: 'https://tailwindcss.com', description: 'Utility-first CSS framework' },
{ name: 'Framer Motion', url: 'https://www.framer.com/motion/', description: 'Animation library for React' },
{ name: 'Vite', url: 'https://vitejs.dev', description: 'Fast build tool' },
],
},
{
title: 'Self-Hosting & Infrastructure',
icon: Server,
resources: [
{ name: 'Proxmox', url: 'https://www.proxmox.com', description: 'Virtualization platform' },
{ name: 'Docker', url: 'https://docker.com', description: 'Container platform' },
{ name: 'Caddy', url: 'https://caddyserver.com', description: 'Web server with automatic HTTPS' },
],
},
];
const Resources = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className="space-y-6"
>
<h1 className="font-minecraft text-3xl md:text-4xl text-primary text-glow-strong">
Resources
</h1>
<p className="font-pixel text-foreground/80">
Tools, documentation, and resources I recommend:
</p>
<div className="space-y-6">
{resourceCategories.map((category, categoryIndex) => {
const Icon = category.icon;
return (
<motion.div
key={category.title}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: categoryIndex * 0.1 }}
className="space-y-3"
>
<div className="flex items-center gap-2">
<Icon className="w-5 h-5 text-primary" />
<h2 className="font-minecraft text-xl text-primary text-glow">
{category.title}
</h2>
</div>
<div className="grid gap-2 pl-7">
{category.resources.map((resource, index) => (
<motion.a
key={resource.name}
href={resource.url}
target="_blank"
rel="noopener noreferrer"
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: categoryIndex * 0.1 + index * 0.05 }}
className="group flex items-center justify-between p-3 border border-primary/20 hover:border-primary/60 transition-all duration-300 hover:bg-primary/5"
>
<div className="flex flex-col">
<span className="font-minecraft text-sm text-primary">
{resource.name}
</span>
<span className="font-pixel text-xs text-foreground/60">
{resource.description}
</span>
</div>
<ExternalLink className="w-4 h-4 text-primary opacity-0 group-hover:opacity-100 transition-opacity" />
</motion.a>
))}
</div>
</motion.div>
);
})}
</div>
</motion.div>
);
};
export default Resources;
+355
View File
@@ -0,0 +1,355 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const GRID_SIZE = 20;
const TICK_SPEED = 120;
const MAX_SCORE = 4294967296;
const HIGHSCORE_KEY = 'snake-highscore';
type Direction = 'up' | 'down' | 'left' | 'right';
type Position = { x: number; y: number };
const Snake = () => {
const { playSound } = useSettings();
const [snake, setSnake] = useState<Position[]>([{ x: 10, y: 10 }]);
const [direction, setDirection] = useState<Direction>('right');
const [food, setFood] = useState<Position>({ x: 15, y: 10 });
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [gameOver, setGameOver] = useState(false);
const [gameComplete, setGameComplete] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const gameRef = useRef<HTMLDivElement>(null);
const directionQueueRef = useRef<Direction[]>([]);
const currentDirectionRef = useRef<Direction>('right');
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
// Calculate cell size based on screen
const getCellSize = useCallback(() => {
if (typeof window === 'undefined') return 24;
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 40;
const maxHeight = window.innerHeight - 300;
return Math.min(Math.floor(maxWidth / GRID_SIZE), Math.floor(maxHeight / GRID_SIZE), 18);
}
return isFullscreen ? 28 : 24;
}, [isFullscreen]);
const [cellSize, setCellSize] = useState(getCellSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCellSize(getCellSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCellSize]);
useEffect(() => {
setCellSize(getCellSize());
}, [isFullscreen, getCellSize]);
// Auto-fullscreen on mobile
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) {
setIsFullscreen(true);
enterFullscreen();
}
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) {
setIsFullscreen(true);
await enterFullscreen();
} else {
setIsFullscreen(false);
await exitFullscreen();
}
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isFullscreen) {
setIsFullscreen(false);
exitFullscreen();
}
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const spawnFood = useCallback((currentSnake: Position[]): Position | null => {
const occupied = new Set(currentSnake.map(s => `${s.x},${s.y}`));
const available: Position[] = [];
for (let x = 0; x < GRID_SIZE; x++) {
for (let y = 0; y < GRID_SIZE; y++) {
if (!occupied.has(`${x},${y}`)) available.push({ x, y });
}
}
if (available.length === 0) return null;
return available[Math.floor(Math.random() * available.length)];
}, []);
const resetSnakeKeepScore = useCallback(() => {
const initialSnake = [{ x: 10, y: 10 }];
setSnake(initialSnake);
setDirection('right');
currentDirectionRef.current = 'right';
directionQueueRef.current = [];
setFood(spawnFood(initialSnake)!);
playSound('success');
}, [spawnFood, playSound]);
const startGame = () => {
const initialSnake = [{ x: 10, y: 10 }];
setSnake(initialSnake);
setDirection('right');
currentDirectionRef.current = 'right';
directionQueueRef.current = [];
setFood(spawnFood(initialSnake)!);
setScore(0);
setGameOver(false);
setGameComplete(false);
setIsPaused(false);
setGameStarted(true);
playSound('success');
gameRef.current?.focus();
};
useEffect(() => {
if (!gameStarted || gameOver || gameComplete || isPaused) return;
const interval = setInterval(() => {
const opposite: Record<Direction, Direction> = { up: 'down', down: 'up', left: 'right', right: 'left' };
let nextDir = currentDirectionRef.current;
while (directionQueueRef.current.length > 0) {
const queuedDir = directionQueueRef.current.shift()!;
if (queuedDir !== opposite[currentDirectionRef.current]) {
nextDir = queuedDir;
break;
}
}
currentDirectionRef.current = nextDir;
setDirection(nextDir);
setSnake(prev => {
const head = prev[0];
let newHead: Position;
switch (nextDir) {
case 'up': newHead = { x: head.x, y: head.y - 1 }; break;
case 'down': newHead = { x: head.x, y: head.y + 1 }; break;
case 'left': newHead = { x: head.x - 1, y: head.y }; break;
case 'right': newHead = { x: head.x + 1, y: head.y }; break;
}
if (newHead.x < 0 || newHead.x >= GRID_SIZE || newHead.y < 0 || newHead.y >= GRID_SIZE) {
setGameOver(true);
playSound('error');
return prev;
}
if (prev.some(s => s.x === newHead.x && s.y === newHead.y)) {
setGameOver(true);
playSound('error');
return prev;
}
const newSnake = [newHead, ...prev];
if (newHead.x === food.x && newHead.y === food.y) {
playSound('success');
setScore(s => {
const newScore = Math.min(s + 10, MAX_SCORE);
if (newScore >= MAX_SCORE) setShowGlitchCrash(true);
if (newScore > highScore) {
setHighScore(newScore);
localStorage.setItem(HIGHSCORE_KEY, newScore.toString());
}
return newScore;
});
const newFood = spawnFood(newSnake);
if (newFood === null) setTimeout(() => resetSnakeKeepScore(), 500);
else setFood(newFood);
return newSnake;
}
newSnake.pop();
return newSnake;
});
}, TICK_SPEED);
return () => clearInterval(interval);
}, [gameStarted, gameOver, gameComplete, isPaused, food, highScore, playSound, spawnFood, resetSnakeKeepScore]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (!gameStarted) return;
let newDir: Direction | null = null;
switch (e.key) {
case 'ArrowUp': case 'w': e.preventDefault(); newDir = 'up'; break;
case 'ArrowDown': case 's': e.preventDefault(); newDir = 'down'; break;
case 'ArrowLeft': case 'a': e.preventDefault(); newDir = 'left'; break;
case 'ArrowRight': case 'd': e.preventDefault(); newDir = 'right'; break;
case 'p': e.preventDefault(); if (!gameOver && !gameComplete) setIsPaused(p => !p); return;
}
if (newDir && directionQueueRef.current.length < 3) directionQueueRef.current.push(newDir);
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [gameStarted, gameOver, gameComplete]);
const renderGrid = () => {
const cells = [];
const snakeSet = new Set(snake.map(s => `${s.x},${s.y}`));
const head = snake[0];
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const isSnake = snakeSet.has(`${x},${y}`);
const isHead = head.x === x && head.y === y;
const isFood = food.x === x && food.y === y;
cells.push(
<div
key={`${x}-${y}`}
className={`flex items-center justify-center border transition-colors duration-75 ${
isHead ? 'bg-primary box-glow border-primary'
: isSnake ? 'bg-primary/80 border-primary/60'
: isFood ? 'bg-destructive/80 border-destructive/60'
: 'bg-background/50 border-primary/10'
}`}
style={{ width: cellSize, height: cellSize }}
>
{isFood && <div className="bg-destructive rounded-sm animate-pulse" style={{ width: cellSize * 0.5, height: cellSize * 0.5 }} />}
</div>
);
}
}
return cells;
};
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div
ref={gameRef}
tabIndex={0}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}
>
{/* Header */}
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Snake</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
{/* Main layout */}
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
{/* Game Grid */}
<div className="border-2 border-primary box-glow p-1 bg-background/80">
<div className="grid" style={{ gridTemplateColumns: `repeat(${GRID_SIZE}, ${cellSize}px)` }}>{renderGrid()}</div>
</div>
{/* Side Panel */}
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60">SCORE</p>
<p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p>
</div>
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p>
<p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p>
<p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p>
</div>
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60">LENGTH</p>
<p className="font-minecraft text-lg text-primary text-glow">{snake.length}</p>
</div>
<div className="border border-primary/50 p-3 bg-background/50">
<p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p>
<p className="font-pixel text-[10px] text-foreground/80"> / WASD</p>
<p className="font-pixel text-[10px] text-foreground/80">P: Pause</p>
</div>
{!gameStarted || gameOver || gameComplete ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">
{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}
</button>
) : (
<button onClick={() => setIsPaused(p => !p)} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">
{isPaused ? 'RESUME' : 'PAUSE'}
</button>
)}
</div>
)}
{/* Mobile Controls */}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LEN</p><p className="font-minecraft text-sm text-primary">{snake.length}</p></div>
</div>
{gameStarted && !gameOver && !gameComplete && (
<div className="grid grid-cols-3 gap-1 mt-2">
<div />
<GameTouchButton onAction={() => directionQueueRef.current.push('up')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => directionQueueRef.current.push('left')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<button onClick={() => setIsPaused(p => !p)} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={() => directionQueueRef.current.push('right')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
<GameTouchButton onAction={() => directionQueueRef.current.push('down')} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
</div>
)}
{(!gameStarted || gameOver || gameComplete) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">
{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}
</button>
)}
</div>
)}
</div>
{/* Desktop Overlay */}
{!isMobile && (gameOver || isPaused || gameComplete) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameComplete ? 'GAME COMPLETE!' : gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{(gameOver || gameComplete) && (
<>
<p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p>
<p className="font-pixel text-xs text-foreground/60 mb-3">Length: {snake.length}</p>
</>
)}
<button onClick={(gameOver || gameComplete) ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">
{(gameOver || gameComplete) ? 'PLAY AGAIN' : 'RESUME'}
</button>
</div>
</div>
)}
</motion.div>
);
};
export default Snake;
+347
View File
@@ -0,0 +1,347 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { motion } from 'framer-motion';
import { useSettings } from '@/contexts/SettingsContext';
import { Link } from 'react-router-dom';
import GlitchCrash from '@/components/GlitchCrash';
import { Maximize2, Minimize2 } from 'lucide-react';
import { useBrowserFullscreen } from '@/hooks/useGameDimensions';
import GameTouchButton from '@/components/GameTouchButton';
const BOARD_WIDTH = 10;
const BOARD_HEIGHT = 20;
const TICK_SPEED = 500;
const HIGHSCORE_KEY = 'tetris-highscore';
const MAX_SCORE = 4294967296;
type Board = (string | null)[][];
const TETROMINOS = {
I: { shape: [[1, 1, 1, 1]], color: 'hsl(var(--primary))' },
O: { shape: [[1, 1], [1, 1]], color: 'hsl(var(--primary))' },
T: { shape: [[0, 1, 0], [1, 1, 1]], color: 'hsl(var(--primary))' },
S: { shape: [[0, 1, 1], [1, 1, 0]], color: 'hsl(var(--primary))' },
Z: { shape: [[1, 1, 0], [0, 1, 1]], color: 'hsl(var(--primary))' },
J: { shape: [[1, 0, 0], [1, 1, 1]], color: 'hsl(var(--primary))' },
L: { shape: [[0, 0, 1], [1, 1, 1]], color: 'hsl(var(--primary))' },
};
type TetrominoKey = keyof typeof TETROMINOS;
interface Piece {
shape: number[][];
color: string;
x: number;
y: number;
}
const createBoard = (): Board => Array.from({ length: BOARD_HEIGHT }, () => Array(BOARD_WIDTH).fill(null));
const randomTetromino = (): Piece => {
const keys = Object.keys(TETROMINOS) as TetrominoKey[];
const key = keys[Math.floor(Math.random() * keys.length)];
const tetromino = TETROMINOS[key];
return { shape: tetromino.shape, color: tetromino.color, x: Math.floor(BOARD_WIDTH / 2) - Math.floor(tetromino.shape[0].length / 2), y: 0 };
};
const rotate = (matrix: number[][]): number[][] => {
const rows = matrix.length;
const cols = matrix[0].length;
const result: number[][] = [];
for (let col = 0; col < cols; col++) {
const newRow: number[] = [];
for (let row = rows - 1; row >= 0; row--) newRow.push(matrix[row][col]);
result.push(newRow);
}
return result;
};
const Tetris = () => {
const { playSound } = useSettings();
const [board, setBoard] = useState<Board>(createBoard);
const [piece, setPiece] = useState<Piece>(randomTetromino);
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [lines, setLines] = useState(0);
const [gameOver, setGameOver] = useState(false);
const [gameComplete, setGameComplete] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [gameStarted, setGameStarted] = useState(false);
const [showGlitchCrash, setShowGlitchCrash] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const gameRef = useRef<HTMLDivElement>(null);
const { enterFullscreen, exitFullscreen } = useBrowserFullscreen();
const getCellSize = useCallback(() => {
if (typeof window === 'undefined') return 24;
const isMobile = window.innerWidth < 768;
if (isMobile) {
const maxWidth = window.innerWidth - 40;
const maxHeight = window.innerHeight - 320;
return Math.min(Math.floor(maxWidth / BOARD_WIDTH), Math.floor(maxHeight / BOARD_HEIGHT), 22);
}
return isFullscreen ? 30 : 24;
}, [isFullscreen]);
const [cellSize, setCellSize] = useState(getCellSize);
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
useEffect(() => {
const handleResize = () => setCellSize(getCellSize());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [getCellSize]);
useEffect(() => {
setCellSize(getCellSize());
}, [isFullscreen, getCellSize]);
useEffect(() => {
if (gameStarted && isMobile && !isFullscreen) {
setIsFullscreen(true);
enterFullscreen();
}
}, [gameStarted, isMobile, isFullscreen, enterFullscreen]);
const toggleFullscreen = async () => {
if (!isFullscreen) { setIsFullscreen(true); await enterFullscreen(); }
else { setIsFullscreen(false); await exitFullscreen(); }
playSound('click');
};
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isFullscreen) { setIsFullscreen(false); exitFullscreen(); }
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [isFullscreen, exitFullscreen]);
useEffect(() => {
const saved = localStorage.getItem(HIGHSCORE_KEY);
if (saved) setHighScore(Math.min(parseInt(saved, 10), MAX_SCORE));
}, []);
const isValidMove = useCallback((newPiece: Piece, currentBoard: Board): boolean => {
for (let y = 0; y < newPiece.shape.length; y++) {
for (let x = 0; x < newPiece.shape[y].length; x++) {
if (newPiece.shape[y][x]) {
const newX = newPiece.x + x;
const newY = newPiece.y + y;
if (newX < 0 || newX >= BOARD_WIDTH || newY >= BOARD_HEIGHT) return false;
if (newY >= 0 && currentBoard[newY][newX]) return false;
}
}
}
return true;
}, []);
const mergePiece = useCallback((currentBoard: Board, currentPiece: Piece): Board => {
const newBoard = currentBoard.map(row => [...row]);
for (let y = 0; y < currentPiece.shape.length; y++) {
for (let x = 0; x < currentPiece.shape[y].length; x++) {
if (currentPiece.shape[y][x]) {
const boardY = currentPiece.y + y;
const boardX = currentPiece.x + x;
if (boardY >= 0) newBoard[boardY][boardX] = currentPiece.color;
}
}
}
return newBoard;
}, []);
const clearLines = useCallback((currentBoard: Board): { board: Board; cleared: number } => {
const newBoard = currentBoard.filter(row => row.some(cell => !cell));
const cleared = BOARD_HEIGHT - newBoard.length;
while (newBoard.length < BOARD_HEIGHT) newBoard.unshift(Array(BOARD_WIDTH).fill(null));
return { board: newBoard, cleared };
}, []);
const moveDown = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const newPiece = { ...piece, y: piece.y + 1 };
if (isValidMove(newPiece, board)) {
setPiece(newPiece);
} else {
const mergedBoard = mergePiece(board, piece);
const { board: clearedBoard, cleared } = clearLines(mergedBoard);
if (cleared > 0) {
playSound('success');
setLines(prev => prev + cleared);
setScore(prev => {
const newScore = Math.min(prev + cleared * 100 * cleared, MAX_SCORE);
if (newScore >= MAX_SCORE) setShowGlitchCrash(true);
if (newScore > highScore) { setHighScore(newScore); localStorage.setItem(HIGHSCORE_KEY, newScore.toString()); }
return newScore;
});
} else { playSound('click'); }
setBoard(clearedBoard);
const newTetromino = randomTetromino();
if (!isValidMove(newTetromino, clearedBoard)) { setGameOver(true); playSound('error'); }
else { setPiece(newTetromino); }
}
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, mergePiece, clearLines, playSound, highScore]);
const moveLeft = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const newPiece = { ...piece, x: piece.x - 1 };
if (isValidMove(newPiece, board)) { setPiece(newPiece); playSound('hover'); }
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const moveRight = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const newPiece = { ...piece, x: piece.x + 1 };
if (isValidMove(newPiece, board)) { setPiece(newPiece); playSound('hover'); }
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const rotatePiece = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
const rotatedShape = rotate(piece.shape);
const newPiece = { ...piece, shape: rotatedShape };
if (isValidMove(newPiece, board)) { setPiece(newPiece); playSound('hover'); }
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const hardDrop = useCallback(() => {
if (gameOver || gameComplete || isPaused || !gameStarted) return;
let newPiece = { ...piece };
while (isValidMove({ ...newPiece, y: newPiece.y + 1 }, board)) newPiece.y++;
setPiece(newPiece);
playSound('click');
}, [piece, board, gameOver, gameComplete, isPaused, gameStarted, isValidMove, playSound]);
const startGame = () => {
setBoard(createBoard());
setPiece(randomTetromino());
setScore(0);
setLines(0);
setGameOver(false);
setGameComplete(false);
setIsPaused(false);
setGameStarted(true);
playSound('success');
gameRef.current?.focus();
};
const togglePause = () => {
if (!gameStarted || gameOver || gameComplete) return;
setIsPaused(prev => !prev);
playSound('click');
};
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (!gameStarted) return;
switch (e.key) {
case 'ArrowLeft': case 'a': e.preventDefault(); moveLeft(); break;
case 'ArrowRight': case 'd': e.preventDefault(); moveRight(); break;
case 'ArrowDown': case 's': e.preventDefault(); moveDown(); break;
case 'ArrowUp': case 'w': e.preventDefault(); rotatePiece(); break;
case ' ': e.preventDefault(); hardDrop(); break;
case 'p': e.preventDefault(); togglePause(); break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [moveLeft, moveRight, moveDown, rotatePiece, hardDrop, gameStarted]);
useEffect(() => {
if (!gameStarted || gameOver || gameComplete || isPaused) return;
const interval = setInterval(moveDown, TICK_SPEED);
return () => clearInterval(interval);
}, [moveDown, gameStarted, gameOver, gameComplete, isPaused]);
const renderBoard = () => {
const displayBoard = board.map(row => [...row]);
if (gameStarted && !gameOver && !gameComplete) {
for (let y = 0; y < piece.shape.length; y++) {
for (let x = 0; x < piece.shape[y].length; x++) {
if (piece.shape[y][x]) {
const boardY = piece.y + y;
const boardX = piece.x + x;
if (boardY >= 0 && boardY < BOARD_HEIGHT && boardX >= 0 && boardX < BOARD_WIDTH) displayBoard[boardY][boardX] = piece.color;
}
}
}
}
return displayBoard.map((row, y) => (
<div key={y} className="flex">
{row.map((cell, x) => (
<div key={`${y}-${x}`} className={`border border-primary/20 transition-colors duration-100 ${cell ? 'bg-primary box-glow' : 'bg-background/50'}`} style={{ width: cellSize, height: cellSize }} />
))}
</div>
));
};
if (showGlitchCrash) return <GlitchCrash onComplete={() => window.location.reload()} />;
return (
<motion.div ref={gameRef} tabIndex={0} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }}
className={`flex flex-col outline-none ${isFullscreen ? 'fixed inset-0 z-50 bg-background p-4' : 'h-full'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-4">
<Link to="/games" className="font-pixel text-sm text-foreground/50 hover:text-primary transition-colors">{'<'} Back</Link>
<h1 className="font-minecraft text-2xl md:text-3xl text-primary text-glow-strong">Tetris</h1>
</div>
<button onClick={toggleFullscreen} className="p-2 border border-primary/50 hover:bg-primary/20 transition-colors" title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
{isFullscreen ? <Minimize2 size={16} className="text-primary" /> : <Maximize2 size={16} className="text-primary" />}
</button>
</div>
<div className={`flex ${isMobile ? 'flex-col items-center' : 'flex-row gap-4'} flex-1 ${isFullscreen ? 'justify-center items-center' : ''}`}>
<div className="border-2 border-primary box-glow p-1 bg-background/80">{renderBoard()}</div>
{!isMobile && (
<div className="flex flex-col gap-2 min-w-[140px]">
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">SCORE</p><p className="font-minecraft text-xl text-primary text-glow">{score.toLocaleString()}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">HIGH SCORE</p><p className="font-minecraft text-lg text-primary text-glow">{highScore.toLocaleString()}</p><p className="font-pixel text-[8px] text-foreground/30">max: 4,294,967,296</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60">LINES</p><p className="font-minecraft text-lg text-primary text-glow">{lines}</p></div>
<div className="border border-primary/50 p-3 bg-background/50"><p className="font-pixel text-[10px] text-foreground/60 mb-1">CONTROLS</p><p className="font-pixel text-[10px] text-foreground/80"> / WASD</p><p className="font-pixel text-[10px] text-foreground/80">Space: Drop</p><p className="font-pixel text-[10px] text-foreground/80">P: Pause</p></div>
{!gameStarted || gameOver || gameComplete ? (
<button onClick={startGame} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
) : (
<button onClick={togglePause} className="font-minecraft text-sm py-2 px-4 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all">{isPaused ? 'RESUME' : 'PAUSE'}</button>
)}
</div>
)}
{isMobile && (
<div className="mt-4 flex flex-col items-center gap-2 w-full">
<div className="flex gap-4 text-center">
<div><p className="font-pixel text-[8px] text-foreground/60">SCORE</p><p className="font-minecraft text-sm text-primary">{score.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">HIGH</p><p className="font-minecraft text-sm text-primary">{highScore.toLocaleString()}</p></div>
<div><p className="font-pixel text-[8px] text-foreground/60">LINES</p><p className="font-minecraft text-sm text-primary">{lines}</p></div>
</div>
{gameStarted && !gameOver && !gameComplete && (
<div className="grid grid-cols-3 gap-1 mt-2">
<div />
<GameTouchButton onAction={rotatePiece} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg" interval={200}></GameTouchButton>
<div />
<GameTouchButton onAction={moveLeft} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<GameTouchButton onAction={hardDrop} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px]" interval={500}>DROP</GameTouchButton>
<GameTouchButton onAction={moveRight} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<button onClick={togglePause} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-[10px] select-none">{isPaused ? '▶' : '❚❚'}</button>
<GameTouchButton onAction={moveDown} className="p-4 border border-primary/50 active:bg-primary/40 text-primary font-pixel text-lg"></GameTouchButton>
<div />
</div>
)}
{(!gameStarted || gameOver || gameComplete) && (
<button onClick={startGame} className="font-minecraft text-sm py-3 px-8 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{gameComplete ? 'PERFECT!' : gameOver ? 'RETRY' : 'START'}</button>
)}
</div>
)}
</div>
{!isMobile && (gameOver || isPaused || gameComplete) && gameStarted && (
<div className="fixed inset-0 bg-background/80 flex items-center justify-center z-50">
<div className="border-2 border-primary box-glow-strong p-6 bg-background text-center">
<h2 className="font-minecraft text-2xl text-primary text-glow-strong mb-3">{gameComplete ? 'GAME COMPLETE!' : gameOver ? 'GAME OVER' : 'PAUSED'}</h2>
{(gameOver || gameComplete) && (<><p className="font-pixel text-sm text-foreground/80 mb-1">Final Score: {score.toLocaleString()}</p><p className="font-pixel text-xs text-foreground/60 mb-3">Lines: {lines}</p></>)}
<button onClick={(gameOver || gameComplete) ? startGame : () => setIsPaused(false)} className="font-minecraft text-sm py-2 px-6 border border-primary bg-primary/20 text-primary hover:bg-primary/40 transition-all box-glow">{(gameOver || gameComplete) ? 'PLAY AGAIN' : 'RESUME'}</button>
</div>
</div>
)}
</motion.div>
);
};
export default Tetris;
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />