Merge branch 'main' into bolt/route-lazy-loading-17202030222576625568
This commit is contained in:
@@ -176,17 +176,11 @@ describe('GradientBlinds', () => {
|
||||
unmount();
|
||||
expect(removeEventListenerSpy).toHaveBeenCalledWith('pointermove', expect.any(Function));
|
||||
});
|
||||
|
||||
it('minimizes getBoundingClientRect calls during pointer move', () => {
|
||||
const { unmount } = render(<GradientBlinds />);
|
||||
|
||||
// Spy on getBoundingClientRect
|
||||
// Note: In jsdom, canvas is an HTMLCanvasElement which inherits from HTMLElement
|
||||
const spy = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
|
||||
|
||||
// Trigger pointer move to clear any initial calls or verify baseline
|
||||
// The initial render calls resize(), which calls getBoundingClientRect on container
|
||||
|
||||
// Clear spy history from initial render
|
||||
spy.mockClear();
|
||||
|
||||
act(() => {
|
||||
@@ -198,9 +192,37 @@ describe('GradientBlinds', () => {
|
||||
window.dispatchEvent(event);
|
||||
});
|
||||
|
||||
// EXPECTATION: It should NOT be called because the listener shouldn't be attached (not visible)
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
|
||||
unmount();
|
||||
});
|
||||
|
||||
it('avoids expensive DOM reads (scrollX/Y) in pointermove handler when visible', () => {
|
||||
const { unmount } = render(<GradientBlinds />);
|
||||
|
||||
// Spy on scrollX/scrollY getters
|
||||
// Note: In jsdom, these are properties on window.
|
||||
const scrollSpy = vi.spyOn(window, 'scrollX', 'get');
|
||||
|
||||
// Make visible to attach listener
|
||||
act(() => {
|
||||
if (ioCallback) {
|
||||
ioCallback([{ isIntersecting: true } as IntersectionObserverEntry]);
|
||||
}
|
||||
});
|
||||
|
||||
scrollSpy.mockClear();
|
||||
|
||||
// Trigger pointer move
|
||||
act(() => {
|
||||
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 100, clientY: 100 }));
|
||||
});
|
||||
|
||||
// With the optimization (moving to RAF loop), this should be 0.
|
||||
// Without optimization, this will be > 0.
|
||||
// Since we are mocking RAF and not running the loop, if it's in the loop, it won't be called.
|
||||
expect(scrollSpy).not.toHaveBeenCalled();
|
||||
|
||||
unmount();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,6 +64,8 @@ const GradientBlinds: React.FC<GradientBlindsProps> = ({
|
||||
const geometryRef = useRef<Geometry | null>(null);
|
||||
const rendererRef = useRef<Renderer | null>(null);
|
||||
const mouseTargetRef = useRef<[number, number]>([0, 0]);
|
||||
// Optimization: store raw pointer position (viewport coords) to decouple event handling from calculation
|
||||
const pointerPosRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const lastTimeRef = useRef<number>(0);
|
||||
const firstResizeRef = useRef<boolean>(true);
|
||||
const rectRef = useRef<DOMRect | null>(null);
|
||||
@@ -309,31 +311,34 @@ void main() {
|
||||
ro.observe(container);
|
||||
|
||||
const onPointerMove = (e: PointerEvent) => {
|
||||
const scale = (renderer as unknown as { dpr?: number }).dpr || 1;
|
||||
let x, y;
|
||||
|
||||
if (rectRef.current) {
|
||||
const dx = window.scrollX - scrollPosRef.current.x;
|
||||
const dy = window.scrollY - scrollPosRef.current.y;
|
||||
const rectLeft = rectRef.current.left - dx;
|
||||
const rectTop = rectRef.current.top - dy;
|
||||
x = (e.clientX - rectLeft) * scale;
|
||||
y = (rectRef.current.height - (e.clientY - rectTop)) * scale;
|
||||
} else {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
x = (e.clientX - rect.left) * scale;
|
||||
y = (rect.height - (e.clientY - rect.top)) * scale;
|
||||
}
|
||||
|
||||
mouseTargetRef.current = [x, y];
|
||||
if (mouseDampening <= 0) {
|
||||
uniforms.iMouse.value = [x, y];
|
||||
}
|
||||
pointerPosRef.current = { x: e.clientX, y: e.clientY };
|
||||
};
|
||||
|
||||
const loop = (t: number) => {
|
||||
rafRef.current = requestAnimationFrame(loop);
|
||||
uniforms.iTime.value = t * 0.001;
|
||||
|
||||
// Update target based on pointer position and scroll offset
|
||||
if (pointerPosRef.current) {
|
||||
const scale = (renderer as unknown as { dpr?: number }).dpr || 1;
|
||||
let x, y;
|
||||
|
||||
if (rectRef.current) {
|
||||
const dx = window.scrollX - scrollPosRef.current.x;
|
||||
const dy = window.scrollY - scrollPosRef.current.y;
|
||||
const rectLeft = rectRef.current.left - dx;
|
||||
const rectTop = rectRef.current.top - dy;
|
||||
x = (pointerPosRef.current.x - rectLeft) * scale;
|
||||
y = (rectRef.current.height - (pointerPosRef.current.y - rectTop)) * scale;
|
||||
} else {
|
||||
// Fallback if rectRef missing
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
x = (pointerPosRef.current.x - rect.left) * scale;
|
||||
y = (rect.height - (pointerPosRef.current.y - rect.top)) * scale;
|
||||
}
|
||||
mouseTargetRef.current = [x, y];
|
||||
}
|
||||
|
||||
if (mouseDampening > 0) {
|
||||
if (!lastTimeRef.current) lastTimeRef.current = t;
|
||||
const dt = (t - lastTimeRef.current) / 1000;
|
||||
@@ -346,6 +351,9 @@ void main() {
|
||||
cur[0] += (target[0] - cur[0]) * factor;
|
||||
cur[1] += (target[1] - cur[1]) * factor;
|
||||
} else {
|
||||
if (pointerPosRef.current) {
|
||||
uniforms.iMouse.value = mouseTargetRef.current;
|
||||
}
|
||||
lastTimeRef.current = t;
|
||||
}
|
||||
if (!paused && programRef.current && meshRef.current) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useState, useEffect, useRef, memo } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { motion } from "motion/react";
|
||||
import { useTranslation } from "../../i18n";
|
||||
@@ -9,6 +9,21 @@ import styles from "./Hero.module.css";
|
||||
|
||||
const GRADIENT_COLORS = ["#26a269", "#8ff0a4"];
|
||||
|
||||
interface TypedTextProps {
|
||||
words: string[];
|
||||
}
|
||||
|
||||
const TypedText = memo(({ words }: TypedTextProps) => {
|
||||
const { text } = useTypingEffect({
|
||||
words,
|
||||
typingSpeed: 80,
|
||||
deletingSpeed: 40,
|
||||
pauseDuration: 2500,
|
||||
});
|
||||
|
||||
return <>{text}</>;
|
||||
});
|
||||
|
||||
export function Hero() {
|
||||
const { t } = useTranslation();
|
||||
const [showScrollIndicator, setShowScrollIndicator] = useState(true);
|
||||
@@ -29,13 +44,6 @@ export function Hero() {
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const { text } = useTypingEffect({
|
||||
words: t.hero.rotatingWords,
|
||||
typingSpeed: 80,
|
||||
deletingSpeed: 40,
|
||||
pauseDuration: 2500,
|
||||
});
|
||||
|
||||
return (
|
||||
<section className={styles.hero}>
|
||||
<div
|
||||
@@ -100,7 +108,7 @@ export function Hero() {
|
||||
>
|
||||
<span>{t.hero.tagline}</span>
|
||||
<span className={styles.typed}>
|
||||
{text}
|
||||
<TypedText words={t.hero.rotatingWords} />
|
||||
<span className={styles.cursor}>|</span>
|
||||
</span>
|
||||
</motion.div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
.button {
|
||||
display: inline-flex;
|
||||
position: relative;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-sm);
|
||||
@@ -80,3 +81,23 @@
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.content {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-sm);
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.contentHidden {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.loaderWrapper {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { type ReactNode, type ButtonHTMLAttributes } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import styles from './Button.module.css';
|
||||
|
||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
interface ButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onAnimationStart' | 'onDragStart' | 'onDragEnd' | 'onDrag'> {
|
||||
variant?: 'primary' | 'secondary' | 'outline';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
children: ReactNode;
|
||||
@@ -24,14 +24,18 @@ export function Button({
|
||||
type={type}
|
||||
className={`${styles.button} ${styles[variant]} ${styles[size]} ${className || ''}`}
|
||||
disabled={disabled || isLoading}
|
||||
aria-busy={isLoading}
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
{...props}
|
||||
>
|
||||
{isLoading ? (
|
||||
<span className={styles.loader} />
|
||||
) : (
|
||||
children
|
||||
<span className={`${styles.content} ${isLoading ? styles.contentHidden : ''}`}>
|
||||
{children}
|
||||
</span>
|
||||
{isLoading && (
|
||||
<span className={styles.loaderWrapper} aria-hidden="true">
|
||||
<span className={styles.loader} />
|
||||
</span>
|
||||
)}
|
||||
</motion.button>
|
||||
);
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
color: var(--md-sys-color-on-surface);
|
||||
}
|
||||
|
||||
.required {
|
||||
color: var(--md-sys-color-error);
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
|
||||
.input {
|
||||
padding: var(--space-md);
|
||||
font-family: var(--md-sys-typescale-body-font);
|
||||
|
||||
@@ -15,6 +15,11 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
<div className={`${styles.field} ${error ? styles.hasError : ''} ${className || ''}`}>
|
||||
<label htmlFor={inputId} className={styles.label}>
|
||||
{label}
|
||||
{props.required && (
|
||||
<span className={styles.required} aria-hidden="true">
|
||||
*
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<input
|
||||
ref={ref}
|
||||
@@ -46,6 +51,11 @@ export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
<div className={`${styles.field} ${error ? styles.hasError : ''} ${className || ''}`}>
|
||||
<label htmlFor={inputId} className={styles.label}>
|
||||
{label}
|
||||
{props.required && (
|
||||
<span className={styles.required} aria-hidden="true">
|
||||
*
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<textarea
|
||||
ref={ref}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import { render, screen, cleanup } from '@testing-library/react';
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import { Button } from '../Button';
|
||||
import React from 'react';
|
||||
|
||||
describe('Button', () => {
|
||||
afterEach(() => {
|
||||
@@ -20,4 +19,13 @@ describe('Button', () => {
|
||||
const button = screen.getByTestId('custom-button');
|
||||
expect(button).toBeTruthy();
|
||||
});
|
||||
|
||||
it('renders loading state correctly', () => {
|
||||
render(<Button isLoading>Submit</Button>);
|
||||
const button = screen.getByRole('button', { name: /submit/i }) as HTMLButtonElement;
|
||||
expect(button.getAttribute('aria-busy')).toBe('true');
|
||||
expect(button.disabled).toBe(true);
|
||||
// Verify text is present (opacity: 0 doesn't remove from DOM)
|
||||
expect(screen.getByText('Submit')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,6 +32,19 @@ describe('Input', () => {
|
||||
expect(input.getAttribute('aria-invalid')).toBe('false');
|
||||
expect(input.hasAttribute('aria-describedby')).toBe(false);
|
||||
});
|
||||
|
||||
it('renders required asterisk when required prop is passed', () => {
|
||||
render(<Input label="Required Input" required />);
|
||||
|
||||
// We search for the asterisk specifically
|
||||
// Note: getByText('*') matches the content of the span
|
||||
const asterisk = screen.getByText('*');
|
||||
expect(asterisk).toBeTruthy();
|
||||
expect(asterisk.getAttribute('aria-hidden')).toBe('true');
|
||||
|
||||
const input = screen.getByRole('textbox', { name: /Required Input/i });
|
||||
expect(input.hasAttribute('required')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Textarea', () => {
|
||||
@@ -49,4 +62,15 @@ describe('Textarea', () => {
|
||||
expect(error.id).toBeDefined();
|
||||
expect(error.id).not.toBe('');
|
||||
});
|
||||
|
||||
it('renders required asterisk when required prop is passed', () => {
|
||||
render(<Textarea label="Required Textarea" required />);
|
||||
|
||||
const asterisk = screen.getByText('*');
|
||||
expect(asterisk).toBeTruthy();
|
||||
expect(asterisk.getAttribute('aria-hidden')).toBe('true');
|
||||
|
||||
const textarea = screen.getByRole('textbox', { name: /Required Textarea/i });
|
||||
expect(textarea.hasAttribute('required')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export { useTypingEffect } from './useTypingEffect';
|
||||
export { useRateLimit } from './useRateLimit';
|
||||
|
||||
64
src/hooks/useRateLimit.test.ts
Normal file
64
src/hooks/useRateLimit.test.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
// @vitest-environment jsdom
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
|
||||
import { useRateLimit } from './useRateLimit';
|
||||
|
||||
describe('useRateLimit', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('should allow first attempt', () => {
|
||||
const { result } = renderHook(() => useRateLimit('test-key', 1000));
|
||||
|
||||
let allowed: boolean = false;
|
||||
act(() => {
|
||||
allowed = result.current.checkRateLimit();
|
||||
});
|
||||
|
||||
expect(allowed).toBe(true);
|
||||
expect(result.current.remainingTime).toBe(0);
|
||||
});
|
||||
|
||||
it('should block immediate second attempt', () => {
|
||||
const { result } = renderHook(() => useRateLimit('test-key', 1000));
|
||||
|
||||
act(() => {
|
||||
result.current.checkRateLimit();
|
||||
});
|
||||
|
||||
let allowed: boolean = true;
|
||||
act(() => {
|
||||
allowed = result.current.checkRateLimit();
|
||||
});
|
||||
|
||||
expect(allowed).toBe(false);
|
||||
expect(result.current.remainingTime).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should allow attempt after cooldown', () => {
|
||||
const { result } = renderHook(() => useRateLimit('test-key', 1000));
|
||||
|
||||
act(() => {
|
||||
result.current.checkRateLimit();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1100);
|
||||
});
|
||||
|
||||
let allowed: boolean = false;
|
||||
act(() => {
|
||||
allowed = result.current.checkRateLimit();
|
||||
});
|
||||
|
||||
expect(allowed).toBe(true);
|
||||
expect(result.current.remainingTime).toBe(0);
|
||||
});
|
||||
});
|
||||
38
src/hooks/useRateLimit.ts
Normal file
38
src/hooks/useRateLimit.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
interface UseRateLimitReturn {
|
||||
checkRateLimit: () => boolean;
|
||||
remainingTime: number;
|
||||
}
|
||||
|
||||
export function useRateLimit(key: string, cooldownMs: number): UseRateLimitReturn {
|
||||
const [remainingTime, setRemainingTime] = useState(0);
|
||||
|
||||
const checkRateLimit = useCallback(() => {
|
||||
try {
|
||||
const now = Date.now();
|
||||
const lastAttempt = localStorage.getItem(key);
|
||||
|
||||
if (lastAttempt) {
|
||||
const lastTime = parseInt(lastAttempt, 10);
|
||||
const timePassed = now - lastTime;
|
||||
|
||||
if (timePassed < cooldownMs) {
|
||||
const remaining = Math.ceil((cooldownMs - timePassed) / 1000);
|
||||
setRemainingTime(remaining);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
localStorage.setItem(key, now.toString());
|
||||
setRemainingTime(0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('LocalStorage not available:', error);
|
||||
// Fail safe: allow action if storage fails
|
||||
return true;
|
||||
}
|
||||
}, [key, cooldownMs]);
|
||||
|
||||
return { checkRateLimit, remainingTime };
|
||||
}
|
||||
@@ -96,6 +96,7 @@ export const de = {
|
||||
sending: 'Wird gesendet...',
|
||||
success: 'Nachricht erfolgreich gesendet! Ich melde mich bald bei Ihnen.',
|
||||
error: 'Fehler beim Senden. Bitte versuchen Sie es erneut oder kontaktieren Sie mich direkt.',
|
||||
rateLimit: 'Zu viele Anfragen. Bitte warten Sie einen Moment.',
|
||||
},
|
||||
info: {
|
||||
title: 'Kontaktdaten',
|
||||
|
||||
@@ -98,6 +98,7 @@ export const en: Translations = {
|
||||
sending: 'Sending...',
|
||||
success: 'Message sent successfully! I\'ll get back to you soon.',
|
||||
error: 'Error sending message. Please try again or contact me directly.',
|
||||
rateLimit: 'Too many requests. Please wait a moment.',
|
||||
},
|
||||
info: {
|
||||
title: 'Contact Info',
|
||||
|
||||
@@ -2,12 +2,14 @@ import { useState, type FormEvent } from "react";
|
||||
import { motion } from "motion/react";
|
||||
import emailjs from "@emailjs/browser";
|
||||
import { useTranslation } from "../i18n";
|
||||
import { useRateLimit } from "../hooks";
|
||||
import { config } from "../config";
|
||||
import { Button, Input, Textarea } from "../components/ui";
|
||||
import { sanitizeInput } from "../utils/security";
|
||||
import { sanitizeInput, isValidEmail } from "../utils/security";
|
||||
import styles from "./Contact.module.css";
|
||||
|
||||
const NAME_MAX_LENGTH = 100;
|
||||
const EMAIL_MAX_LENGTH = 254;
|
||||
const SUBJECT_MAX_LENGTH = 200;
|
||||
const MESSAGE_MAX_LENGTH = 5000;
|
||||
|
||||
@@ -38,6 +40,8 @@ export function Contact() {
|
||||
const [submitStatus, setSubmitStatus] = useState<
|
||||
"idle" | "success" | "error"
|
||||
>("idle");
|
||||
const [rateLimitError, setRateLimitError] = useState(false);
|
||||
const { checkRateLimit } = useRateLimit("contact-form", 60000); // 1 minute cooldown
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
@@ -50,7 +54,9 @@ export function Contact() {
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
newErrors.email = "Required";
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
||||
} else if (formData.email.length > EMAIL_MAX_LENGTH) {
|
||||
newErrors.email = `Max ${EMAIL_MAX_LENGTH} characters`;
|
||||
} else if (!isValidEmail(formData.email)) {
|
||||
newErrors.email = "Invalid email";
|
||||
}
|
||||
|
||||
@@ -73,8 +79,14 @@ export function Contact() {
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
setRateLimitError(false);
|
||||
if (!validateForm()) return;
|
||||
|
||||
if (!checkRateLimit()) {
|
||||
setRateLimitError(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
setSubmitStatus("idle");
|
||||
|
||||
@@ -149,39 +161,51 @@ export function Contact() {
|
||||
>
|
||||
<p className={styles.intro}>{t.contact.intro}</p>
|
||||
|
||||
<form onSubmit={handleSubmit} className={styles.form}>
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className={styles.form}
|
||||
noValidate
|
||||
>
|
||||
<Input
|
||||
label={t.contact.form.name}
|
||||
required
|
||||
placeholder={t.contact.form.namePlaceholder}
|
||||
value={formData.name}
|
||||
onChange={(e) => handleChange("name", e.target.value)}
|
||||
error={errors.name}
|
||||
maxLength={NAME_MAX_LENGTH}
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={t.contact.form.email}
|
||||
type="email"
|
||||
required
|
||||
placeholder={t.contact.form.emailPlaceholder}
|
||||
value={formData.email}
|
||||
onChange={(e) => handleChange("email", e.target.value)}
|
||||
error={errors.email}
|
||||
maxLength={EMAIL_MAX_LENGTH}
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={t.contact.form.subject}
|
||||
required
|
||||
placeholder={t.contact.form.subjectPlaceholder}
|
||||
value={formData.subject}
|
||||
onChange={(e) => handleChange("subject", e.target.value)}
|
||||
error={errors.subject}
|
||||
maxLength={SUBJECT_MAX_LENGTH}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label={t.contact.form.message}
|
||||
required
|
||||
placeholder={t.contact.form.messagePlaceholder}
|
||||
value={formData.message}
|
||||
onChange={(e) => handleChange("message", e.target.value)}
|
||||
error={errors.message}
|
||||
rows={6}
|
||||
maxLength={MESSAGE_MAX_LENGTH}
|
||||
/>
|
||||
|
||||
<Button
|
||||
@@ -201,6 +225,8 @@ export function Contact() {
|
||||
className={styles.success}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
>
|
||||
{t.contact.form.success}
|
||||
</motion.p>
|
||||
@@ -211,10 +237,24 @@ export function Contact() {
|
||||
className={styles.error}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
>
|
||||
{t.contact.form.error}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
{rateLimitError && (
|
||||
<motion.p
|
||||
className={styles.error}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
>
|
||||
{t.contact.form.rateLimit}
|
||||
</motion.p>
|
||||
)}
|
||||
</form>
|
||||
</motion.div>
|
||||
|
||||
@@ -235,6 +275,7 @@ export function Contact() {
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
|
||||
<polyline points="22,6 12,13 2,6" />
|
||||
@@ -250,7 +291,7 @@ export function Contact() {
|
||||
|
||||
<div className={styles.infoItem}>
|
||||
<div className={styles.infoIcon}>
|
||||
<svg viewBox="0 0 24 24" fill="currentColor">
|
||||
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
@@ -63,6 +63,7 @@ describe('Contact Page', () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
document.body.innerHTML = '';
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('submits the form with correct parameters', async () => {
|
||||
@@ -115,6 +116,8 @@ describe('Contact Page', () => {
|
||||
// Verify success message
|
||||
const successMessage = await screen.findByText('Message sent successfully!');
|
||||
expect(successMessage).toBeTruthy();
|
||||
expect(successMessage.getAttribute('role')).toBe('alert');
|
||||
expect(successMessage.getAttribute('aria-live')).toBe('polite');
|
||||
});
|
||||
|
||||
it('sanitizes input before sending', async () => {
|
||||
@@ -170,4 +173,54 @@ describe('Contact Page', () => {
|
||||
// EmailJS should NOT be called
|
||||
expect(emailjs.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows error when email contains invalid characters', async () => {
|
||||
const { container } = render(<Contact />);
|
||||
|
||||
// Fill out the form with invalid email (XSS vector)
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'John Doe' } });
|
||||
fireEvent.change(screen.getByLabelText('Email'), { target: { value: '<script>@example.com' } });
|
||||
fireEvent.change(screen.getByLabelText('Subject'), { target: { value: 'Test Subject' } });
|
||||
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Hello world' } });
|
||||
|
||||
// Submit via form submit event to bypass browser validation (jsdom/browser would block this otherwise)
|
||||
// This ensures our application-level validation logic (isValidEmail) is tested
|
||||
const form = container.querySelector('form');
|
||||
if (form) fireEvent.submit(form);
|
||||
|
||||
// Validation error should appear
|
||||
const errorMessage = await screen.findByText('Invalid email');
|
||||
expect(errorMessage).toBeTruthy();
|
||||
|
||||
// EmailJS should NOT be called
|
||||
expect(emailjs.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows error message with alert role when submission fails', async () => {
|
||||
// Mock failure
|
||||
const sendMock = vi.mocked(emailjs.send);
|
||||
sendMock.mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
render(<Contact />);
|
||||
|
||||
// Fill out the form
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'John Doe' } });
|
||||
fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'john@example.com' } });
|
||||
fireEvent.change(screen.getByLabelText('Subject'), { target: { value: 'Test Subject' } });
|
||||
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Hello world' } });
|
||||
|
||||
// Submit
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Send Message' }));
|
||||
|
||||
// Wait for submission attempt
|
||||
await waitFor(() => {
|
||||
expect(emailjs.send).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Verify error message
|
||||
const errorMessage = await screen.findByText('Failed to send message.');
|
||||
expect(errorMessage).toBeTruthy();
|
||||
expect(errorMessage.getAttribute('role')).toBe('alert');
|
||||
expect(errorMessage.getAttribute('aria-live')).toBe('polite');
|
||||
});
|
||||
});
|
||||
|
||||
56
src/utils/security.test.ts
Normal file
56
src/utils/security.test.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { sanitizeInput, isValidEmail } from './security';
|
||||
|
||||
describe('Security Utils', () => {
|
||||
describe('sanitizeInput', () => {
|
||||
it('escapes special HTML characters', () => {
|
||||
expect(sanitizeInput('<script>')).toBe('<script>');
|
||||
expect(sanitizeInput('foo & bar')).toBe('foo & bar');
|
||||
expect(sanitizeInput('"quotes"')).toBe('"quotes"');
|
||||
expect(sanitizeInput("'single quotes'")).toBe(''single quotes'');
|
||||
expect(sanitizeInput('>')).toBe('>');
|
||||
});
|
||||
|
||||
it('returns non-string input as is', () => {
|
||||
// @ts-ignore
|
||||
expect(sanitizeInput(123)).toBe(123);
|
||||
// @ts-ignore
|
||||
expect(sanitizeInput(null)).toBe(null);
|
||||
});
|
||||
|
||||
it('handles mixed content correctly', () => {
|
||||
const input = '<script>alert("XSS")</script>';
|
||||
const expected = '<script>alert("XSS")</script>';
|
||||
expect(sanitizeInput(input)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isValidEmail', () => {
|
||||
it('accepts valid email addresses', () => {
|
||||
expect(isValidEmail('test@example.com')).toBe(true);
|
||||
expect(isValidEmail('john.doe@sub.domain.co.uk')).toBe(true);
|
||||
expect(isValidEmail('user+tag@example.com')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects invalid email formats', () => {
|
||||
expect(isValidEmail('plainaddress')).toBe(false);
|
||||
expect(isValidEmail('@example.com')).toBe(false);
|
||||
expect(isValidEmail('user@')).toBe(false);
|
||||
expect(isValidEmail('user@.com')).toBe(false);
|
||||
expect(isValidEmail('user@com')).toBe(false); // Missing dot in domain part (simple regex might allow, but strict one requires dot)
|
||||
});
|
||||
|
||||
it('rejects emails with dangerous characters (<, >)', () => {
|
||||
expect(isValidEmail('<script>@example.com')).toBe(false);
|
||||
expect(isValidEmail('user@<script>.com')).toBe(false);
|
||||
expect(isValidEmail('user<name>@example.com')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects emails with whitespace', () => {
|
||||
expect(isValidEmail('user @example.com')).toBe(false);
|
||||
expect(isValidEmail('user@ example.com')).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -16,3 +16,21 @@ export function sanitizeInput(input: string): string {
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an email address format securely.
|
||||
* Rejects inputs containing dangerous characters like <, >, or whitespace.
|
||||
*
|
||||
* @param email - The email string to validate.
|
||||
* @returns True if the email is valid and safe, false otherwise.
|
||||
*/
|
||||
export function isValidEmail(email: string): boolean {
|
||||
// Basic format check + rejection of XSS vectors (<, >)
|
||||
// [^\s@<>]+ : Local part - no whitespace, @, <, or >
|
||||
// @ : Literal @
|
||||
// [^\s@<>]+ : Domain part - no whitespace, @, <, or >
|
||||
// \. : Literal .
|
||||
// [^\s@<>]+ : TLD part - no whitespace, @, <, or >
|
||||
const emailRegex = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user