Merge origin/master

This commit is contained in:
2026-01-25 19:39:57 +01:00
374 changed files with 68385 additions and 36750 deletions
+348
View File
@@ -0,0 +1,348 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useAsync } from './useAsync';
import * as errorHandling from '../utils/errorHandling';
// Mock the errorHandling module
vi.mock('../utils/errorHandling', async () => {
const actual = await vi.importActual('../utils/errorHandling');
return {
...actual,
handleError: vi.fn((error: unknown) => {
if (error instanceof Error) {
return error;
}
return new Error('Handled error');
})
};
});
describe('useAsync', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('initial state', () => {
it('should initialize with null data, null error, and loading false', () => {
const { result } = renderHook(() => useAsync<string>());
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(false);
});
it('should provide an execute function', () => {
const { result } = renderHook(() => useAsync<string>());
expect(result.current.execute).toBeInstanceOf(Function);
});
});
describe('loading states', () => {
it('should set loading to true when executing', async () => {
const { result } = renderHook(() => useAsync<string>());
const asyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('test data'), 100);
}));
result.current.execute(asyncFn);
// Loading should be true immediately after execute is called
expect(result.current.loading).toBe(true);
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
});
it('should set loading to false after successful execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const asyncFn = vi.fn(async () => 'test data');
await result.current.execute(asyncFn);
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe('test data');
expect(result.current.error).toBeNull();
});
it('should set loading to false after failed execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const error = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw error;
});
try {
await result.current.execute(asyncFn);
} catch (e) {
// Expected to throw
}
expect(result.current.loading).toBe(false);
expect(result.current.data).toBeNull();
expect(result.current.error).toBe(error);
});
it('should reset data and error when starting new execution', async () => {
const { result } = renderHook(() => useAsync<string>());
// First execution with data
await result.current.execute(async () => 'first data');
expect(result.current.data).toBe('first data');
expect(result.current.error).toBeNull();
// Second execution that will take some time
const slowAsyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('second data'), 100);
}));
result.current.execute(slowAsyncFn);
// Immediately after calling execute, state should be reset
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(true);
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
});
});
describe('data flow', () => {
it('should set data on successful execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const testData = 'success data';
const asyncFn = vi.fn(async () => testData);
await result.current.execute(asyncFn);
expect(result.current.data).toBe(testData);
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(false);
expect(asyncFn).toHaveBeenCalledTimes(1);
});
it('should handle different data types', async () => {
// Test with number
const { result: numberResult } = renderHook(() => useAsync<number>());
await numberResult.current.execute(async () => 42);
expect(numberResult.current.data).toBe(42);
// Test with object
const { result: objectResult } = renderHook(() => useAsync<{ id: number; name: string }>());
const testObject = { id: 1, name: 'test' };
await objectResult.current.execute(async () => testObject);
expect(objectResult.current.data).toEqual(testObject);
// Test with array
const { result: arrayResult } = renderHook(() => useAsync<string[]>());
const testArray = ['a', 'b', 'c'];
await arrayResult.current.execute(async () => testArray);
expect(arrayResult.current.data).toEqual(testArray);
});
it('should return data from execute function', async () => {
const { result } = renderHook(() => useAsync<string>());
const testData = 'returned data';
const asyncFn = vi.fn(async () => testData);
const returnedData = await result.current.execute(asyncFn);
expect(returnedData).toBe(testData);
});
it('should handle null data', async () => {
const { result } = renderHook(() => useAsync<string | null>());
const asyncFn = vi.fn(async () => null);
await result.current.execute(asyncFn);
expect(result.current.data).toBeNull();
expect(result.current.error).toBeNull();
expect(result.current.loading).toBe(false);
});
it('should replace previous data with new data', async () => {
const { result } = renderHook(() => useAsync<string>());
await result.current.execute(async () => 'first');
expect(result.current.data).toBe('first');
await result.current.execute(async () => 'second');
expect(result.current.data).toBe('second');
await result.current.execute(async () => 'third');
expect(result.current.data).toBe('third');
});
});
describe('error handling', () => {
it('should set error on failed execution', async () => {
const { result } = renderHook(() => useAsync<string>());
const error = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw error;
});
try {
await result.current.execute(asyncFn);
} catch (e) {
// Expected to throw
}
expect(result.current.data).toBeNull();
expect(result.current.error).toBe(error);
expect(result.current.loading).toBe(false);
});
it('should call handleError with error and context', async () => {
const { result } = renderHook(() => useAsync<string>());
const error = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw error;
});
try {
await result.current.execute(asyncFn);
} catch (e) {
// Expected to throw
}
expect(errorHandling.handleError).toHaveBeenCalledWith(error, 'Async Operation');
});
it('should re-throw the handled error', async () => {
const { result } = renderHook(() => useAsync<string>());
const originalError = new Error('Test error');
const asyncFn = vi.fn(async () => {
throw originalError;
});
await expect(result.current.execute(asyncFn)).rejects.toThrow();
});
it('should handle errors of different types', async () => {
const { result } = renderHook(() => useAsync<string>());
// Test with Error object
const error1 = new Error('Error object');
await expect(result.current.execute(async () => {
throw error1;
})).rejects.toThrow();
// Test with string error
await expect(result.current.execute(async () => {
throw 'String error';
})).rejects.toThrow();
// Test with number error
await expect(result.current.execute(async () => {
throw 404;
})).rejects.toThrow();
});
it('should clear error on successful subsequent execution', async () => {
const { result } = renderHook(() => useAsync<string>());
// First execution fails
try {
await result.current.execute(async () => {
throw new Error('First error');
});
} catch (e) {
// Expected to throw
}
expect(result.current.error).not.toBeNull();
// Second execution succeeds
await result.current.execute(async () => 'success');
expect(result.current.error).toBeNull();
expect(result.current.data).toBe('success');
});
it('should replace previous error with new error', async () => {
const { result } = renderHook(() => useAsync<string>());
const error1 = new Error('First error');
const error2 = new Error('Second error');
// First execution fails
try {
await result.current.execute(async () => {
throw error1;
});
} catch (e) {
// Expected to throw
}
expect(result.current.error).toBe(error1);
// Second execution also fails
try {
await result.current.execute(async () => {
throw error2;
});
} catch (e) {
// Expected to throw
}
expect(result.current.error).toBe(error2);
});
});
describe('execute function stability', () => {
it('should maintain the same execute function reference', () => {
const { result, rerender } = renderHook(() => useAsync<string>());
const firstExecute = result.current.execute;
rerender();
const secondExecute = result.current.execute;
expect(firstExecute).toBe(secondExecute);
});
});
describe('concurrent executions', () => {
it('should handle multiple concurrent executions', async () => {
const { result } = renderHook(() => useAsync<string>());
const slowAsyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('slow result'), 100);
}));
const fastAsyncFn = vi.fn(() => new Promise<string>((resolve) => {
setTimeout(() => resolve('fast result'), 10);
}));
// Start slow execution
const slowPromise = result.current.execute(slowAsyncFn);
// Start fast execution (will reset state)
const fastPromise = result.current.execute(fastAsyncFn);
// Fast one should complete
await fastPromise;
expect(result.current.data).toBe('fast result');
// Slow one should also complete, but will override the fast result
await slowPromise;
// Note: In the current implementation, the last executed function will set the final state
});
});
});
+47
View File
@@ -0,0 +1,47 @@
import { useState, useEffect, useRef, RefObject } from 'react';
interface UseIntersectionObserverOptions {
threshold?: number | number[];
root?: Element | null;
rootMargin?: string;
}
/**
* Hook to detect when an element is visible in the viewport using IntersectionObserver
* @param options - IntersectionObserver options (threshold, root, rootMargin)
* @returns Object containing ref to attach to element and isIntersecting state
*/
export const useIntersectionObserver = <T extends HTMLElement = HTMLDivElement>(
options: UseIntersectionObserverOptions = {}
): { ref: RefObject<T>; isIntersecting: boolean } => {
const { threshold = 0.5, root = null, rootMargin = '0px' } = options;
const [isIntersecting, setIsIntersecting] = useState<boolean>(false);
const ref = useRef<T>(null);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setIsIntersecting(entry.isIntersecting);
},
{
threshold,
root,
rootMargin,
}
);
const element = ref.current;
if (element) {
observer.observe(element);
}
return () => {
if (element) {
observer.unobserve(element);
}
observer.disconnect();
};
}, [threshold, root, rootMargin]);
return { ref, isIntersecting };
};
+235
View File
@@ -0,0 +1,235 @@
import { renderHook, act } from '@testing-library/react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { useLocalStorage } from './useLocalStorage';
// Mock the error handling utility
vi.mock('../utils/errorHandling', () => ({
handleError: vi.fn()
}));
// Mock localStorage
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: (key: string) => store[key] || null,
setItem: (key: string, value: string) => {
store[key] = value.toString();
},
removeItem: (key: string) => {
delete store[key];
},
clear: () => {
store = {};
}
};
})();
describe('useLocalStorage', () => {
beforeEach(() => {
// Setup localStorage mock
Object.defineProperty(window, 'localStorage', {
value: localStorageMock,
writable: true
});
localStorageMock.clear();
});
afterEach(() => {
vi.clearAllMocks();
});
it('should return initial value when localStorage is empty', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 'initial-value'));
const [value] = result.current;
expect(value).toBe('initial-value');
});
it('should return initial value from function when localStorage is empty', () => {
const initializer = vi.fn(() => 'computed-value');
const { result } = renderHook(() => useLocalStorage('test-key', initializer));
const [value] = result.current;
expect(value).toBe('computed-value');
expect(initializer).toHaveBeenCalled();
});
it('should set value in localStorage', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 'initial'));
act(() => {
const [, setValue] = result.current;
setValue('new-value');
});
const [value] = result.current;
expect(value).toBe('new-value');
expect(JSON.parse(localStorage.getItem('test-key')!)).toBe('new-value');
});
it('should handle updater function in setValue', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 10));
act(() => {
const [, setValue] = result.current;
setValue((prev) => prev + 5);
});
const [value] = result.current;
expect(value).toBe(15);
});
it('should read existing value from localStorage', () => {
localStorage.setItem('test-key', JSON.stringify('existing-value'));
const { result } = renderHook(() => useLocalStorage('test-key', 'initial-value'));
const [value] = result.current;
expect(value).toBe('existing-value');
});
it('should handle complex objects', () => {
const complexObject = { name: 'John', age: 30, hobbies: ['reading', 'coding'] };
const { result } = renderHook(() => useLocalStorage('test-key', complexObject));
act(() => {
const [, setValue] = result.current;
setValue({ ...complexObject, age: 31 });
});
const [value] = result.current;
expect(value).toEqual({ name: 'John', age: 31, hobbies: ['reading', 'coding'] });
});
it('should remove value from localStorage', () => {
localStorage.setItem('test-key', JSON.stringify('existing-value'));
const { result } = renderHook(() => useLocalStorage('test-key', 'initial-value'));
act(() => {
const [, , removeValue] = result.current;
removeValue();
});
const [value] = result.current;
expect(value).toBe('initial-value');
expect(localStorage.getItem('test-key')).toBeNull();
});
it('should handle invalid JSON in localStorage', () => {
localStorage.setItem('test-key', 'invalid-json{');
const { result } = renderHook(() => useLocalStorage('test-key', 'fallback-value'));
const [value] = result.current;
expect(value).toBe('fallback-value');
});
it('should be SSR-safe (no window)', () => {
const originalWindow = global.window;
// @ts-ignore - Temporarily remove window for SSR test
delete global.window;
const { result } = renderHook(() => useLocalStorage('test-key', 'ssr-value'));
const [value] = result.current;
expect(value).toBe('ssr-value');
// Restore window
global.window = originalWindow;
});
it('should handle localStorage quota exceeded', () => {
const { handleError } = require('../utils/errorHandling');
// Mock setItem to throw quota exceeded error
const originalSetItem = localStorage.setItem;
localStorage.setItem = vi.fn(() => {
throw new DOMException('QuotaExceededError');
});
const { result } = renderHook(() => useLocalStorage('test-key', 'initial'));
act(() => {
const [, setValue] = result.current;
setValue('new-value');
});
expect(handleError).toHaveBeenCalled();
// Restore original setItem
localStorage.setItem = originalSetItem;
});
it('should serialize and deserialize arrays', () => {
const initialArray = [1, 2, 3, 4, 5];
const { result } = renderHook(() => useLocalStorage('test-key', initialArray));
act(() => {
const [, setValue] = result.current;
setValue([...initialArray, 6]);
});
const [value] = result.current;
expect(value).toEqual([1, 2, 3, 4, 5, 6]);
expect(JSON.parse(localStorage.getItem('test-key')!)).toEqual([1, 2, 3, 4, 5, 6]);
});
it('should handle boolean values', () => {
const { result } = renderHook(() => useLocalStorage('test-key', false));
act(() => {
const [, setValue] = result.current;
setValue(true);
});
const [value] = result.current;
expect(value).toBe(true);
expect(JSON.parse(localStorage.getItem('test-key')!)).toBe(true);
});
it('should handle number values', () => {
const { result } = renderHook(() => useLocalStorage('test-key', 0));
act(() => {
const [, setValue] = result.current;
setValue(42);
});
const [value] = result.current;
expect(value).toBe(42);
expect(JSON.parse(localStorage.getItem('test-key')!)).toBe(42);
});
it('should handle null values', () => {
const { result } = renderHook(() => useLocalStorage<string | null>('test-key', null));
const [value] = result.current;
expect(value).toBe(null);
});
it('should update localStorage when key changes', () => {
const { result, rerender } = renderHook(
({ key, value }) => useLocalStorage(key, value),
{ initialProps: { key: 'key1', value: 'value1' } }
);
act(() => {
const [, setValue] = result.current;
setValue('updated-value1');
});
expect(localStorage.getItem('key1')).toBe(JSON.stringify('updated-value1'));
// Change the key
rerender({ key: 'key2', value: 'value2' });
act(() => {
const [, setValue] = result.current;
setValue('updated-value2');
});
expect(localStorage.getItem('key2')).toBe(JSON.stringify('updated-value2'));
});
});
+99
View File
@@ -0,0 +1,99 @@
import { useState, useEffect, useCallback } from 'react';
import { handleError } from '../utils/errorHandling';
/**
* Function type for updating the stored value
* @template T - The type of the stored value
* @param value - Either a new value of type T or an updater function that takes the current value and returns a new value
*/
type SetValue<T> = (value: T | ((val: T) => T)) => void;
/**
* Custom hook for managing state in localStorage with automatic serialization
*
* @template T - The type of the stored value
* @param {string} key - The localStorage key to use
* @param {T | (() => T)} initialValue - The initial value or a function that returns the initial value
* @returns {[T, SetValue<T>, () => void]} A tuple containing:
* - The current stored value
* - A function to update the stored value
* - A function to remove the value from storage
*
* @example
* ```tsx
* const [theme, setTheme, removeTheme] = useLocalStorage('theme', 'light');
* setTheme('dark'); // Updates both state and localStorage
* removeTheme(); // Removes from localStorage and resets to initial value
* ```
*
* @remarks
* - SSR-safe: Returns initial value during server-side rendering
* - Automatically serializes/deserializes JSON
* - Handles localStorage quota exceeded errors
* - Handles invalid JSON gracefully
*/
export function useLocalStorage<T>(
key: string,
initialValue: T | (() => T)
): [T, SetValue<T>, () => void] {
// Get initial value - SSR safe
const getInitialValue = useCallback((): T => {
// Check if we're in a browser environment
if (typeof window === 'undefined') {
return initialValue instanceof Function ? initialValue() : initialValue;
}
try {
const item = window.localStorage.getItem(key);
if (item) {
return JSON.parse(item) as T;
}
} catch (error) {
handleError(error, `LocalStorage Read (key: ${key})`);
}
return initialValue instanceof Function ? initialValue() : initialValue;
}, [key, initialValue]);
const [storedValue, setStoredValue] = useState<T>(getInitialValue);
// Update localStorage whenever storedValue changes
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
try {
window.localStorage.setItem(key, JSON.stringify(storedValue));
} catch (error) {
handleError(error, `LocalStorage Write (key: ${key})`);
}
}, [key, storedValue]);
// Set value function that supports both direct values and updater functions
const setValue: SetValue<T> = useCallback((value) => {
try {
setStoredValue((prevValue) => {
const newValue = value instanceof Function ? value(prevValue) : value;
return newValue;
});
} catch (error) {
handleError(error, `LocalStorage Update (key: ${key})`);
}
}, [key]);
// Remove value from localStorage and reset to initial value
const removeValue = useCallback(() => {
try {
if (typeof window !== 'undefined') {
window.localStorage.removeItem(key);
}
const resetValue = initialValue instanceof Function ? initialValue() : initialValue;
setStoredValue(resetValue);
} catch (error) {
handleError(error, `LocalStorage Remove (key: ${key})`);
}
}, [key, initialValue]);
return [storedValue, setValue, removeValue];
}
+25
View File
@@ -0,0 +1,25 @@
import { useState, useEffect } from 'react';
/**
* Hook to detect tab visibility using the Page Visibility API
* @returns boolean - true when page is visible, false when hidden
*/
export const usePageVisibility = (): boolean => {
const [isVisible, setIsVisible] = useState<boolean>(() =>
typeof document !== 'undefined' ? !document.hidden : true
);
useEffect(() => {
const handleVisibilityChange = () => {
setIsVisible(!document.hidden);
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
return isVisible;
};