extract auth to lib

This commit is contained in:
2026-02-22 20:37:30 +01:00
parent db6813cab1
commit 9f86fe80d7
24 changed files with 2442 additions and 0 deletions

134
src/api/createApiClient.ts Normal file
View File

@@ -0,0 +1,134 @@
export type RequestOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
token?: string | null;
body?: unknown;
};
export type ResolveErrorInput = {
code?: string;
status?: number;
fallbackMessage?: string;
};
export type CreateApiClientConfig = {
baseUrl: string;
resolveError?: (input: ResolveErrorInput) => string;
inferErrorCodeFromStatus?: (status?: number | null) => string | undefined;
fetchImpl?: typeof fetch;
};
export class ApiError extends Error {
status: number;
code?: string;
requestId?: string;
details?: unknown;
rawMessage?: string;
constructor({
message,
status,
code,
requestId,
details,
rawMessage
}: {
message: string;
status: number;
code?: string;
requestId?: string;
details?: unknown;
rawMessage?: string;
}) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
this.requestId = requestId;
this.details = details;
this.rawMessage = rawMessage;
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value != null;
}
function parseErrorPayload(data: unknown) {
if (!isRecord(data)) {
return {
code: undefined as string | undefined,
rawMessage: undefined as string | undefined,
requestId: undefined as string | undefined,
details: undefined as unknown
};
}
const code = typeof data.code === 'string' ? data.code : undefined;
const rawMessage = typeof data.error === 'string' ? data.error : undefined;
const requestId = typeof data.requestId === 'string' ? data.requestId : undefined;
const details = data.details;
return { code, rawMessage, requestId, details };
}
function defaultResolveError({ status, fallbackMessage }: ResolveErrorInput): string {
if (fallbackMessage) {
return fallbackMessage;
}
if (status != null) {
return `Request failed (${status}).`;
}
return 'Request failed. Please try again.';
}
export function createApiClient(config: CreateApiClientConfig) {
const {
baseUrl,
resolveError = defaultResolveError,
inferErrorCodeFromStatus,
fetchImpl
} = config;
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { method = 'GET', token, body } = options;
const runFetch = fetchImpl ?? fetch;
const response = await runFetch(`${baseUrl}${path}`, {
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {})
},
body: body ? JSON.stringify(body) : undefined
});
const data = await response.json().catch(() => null);
if (!response.ok) {
const parsed = parseErrorPayload(data);
const code = parsed.code ?? inferErrorCodeFromStatus?.(response.status);
const message = resolveError({
code,
status: response.status,
fallbackMessage: parsed.rawMessage
});
throw new ApiError({
message,
status: response.status,
code,
requestId: parsed.requestId,
details: parsed.details,
rawMessage: parsed.rawMessage
});
}
return data as T;
}
return {
request
};
}

29
src/api/query.ts Normal file
View File

@@ -0,0 +1,29 @@
type BuildListQueryOptions = {
q?: string;
page?: number;
pageSize?: number;
sort?: string;
defaultSort: string;
};
export function buildListQuery({
q,
page = 1,
pageSize = 10,
sort,
defaultSort
}: BuildListQueryOptions): string {
const query = new URLSearchParams();
const normalizedQuery = q?.trim();
const normalizedSort = sort?.trim();
if (normalizedQuery) {
query.set('q', normalizedQuery);
}
query.set('page', String(page));
query.set('pageSize', String(pageSize));
query.set('sort', normalizedSort || defaultSort);
return query.toString();
}

View File

@@ -0,0 +1,90 @@
import { createContext, useCallback, useContext, useMemo, useState } from 'react';
import type { ReactNode } from 'react';
const DEFAULT_AUTH_TOKEN_KEY = 'authToken';
const DEFAULT_REFRESH_TOKEN_KEY = 'refreshToken';
const DEFAULT_LEGACY_KEYS = ['auth_token', 'auth_user', 'token'];
export type AuthState<TUser> = {
authToken: string | null;
refreshToken: string | null;
currentUser: TUser | null;
};
export type AuthContextValue<TUser> = AuthState<TUser> & {
setSession: (authToken: string, refreshToken: string, currentUser: TUser) => void;
setCurrentUser: (currentUser: TUser | null) => void;
clearSession: () => void;
};
export type CreateAuthContextOptions = {
authTokenKey?: string;
refreshTokenKey?: string;
legacyKeys?: string[];
};
export function createAuthContext<TUser>(options: CreateAuthContextOptions = {}) {
const authTokenKey = options.authTokenKey ?? DEFAULT_AUTH_TOKEN_KEY;
const refreshTokenKey = options.refreshTokenKey ?? DEFAULT_REFRESH_TOKEN_KEY;
const legacyKeys = options.legacyKeys ?? DEFAULT_LEGACY_KEYS;
const AuthContext = createContext<AuthContextValue<TUser> | undefined>(undefined);
function readStoredSession(): AuthState<TUser> {
for (const key of legacyKeys) {
localStorage.removeItem(key);
}
const authToken = localStorage.getItem(authTokenKey);
const refreshToken = localStorage.getItem(refreshTokenKey);
return {
authToken,
refreshToken,
currentUser: null
};
}
function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
const [state, setState] = useState<AuthState<TUser>>(readStoredSession);
const setSession = useCallback((authToken: string, refreshToken: string, currentUser: TUser) => {
localStorage.setItem(authTokenKey, authToken);
localStorage.setItem(refreshTokenKey, refreshToken);
setState({ authToken, refreshToken, currentUser });
}, []);
const clearSession = useCallback(() => {
localStorage.removeItem(authTokenKey);
localStorage.removeItem(refreshTokenKey);
setState({ authToken: null, refreshToken: null, currentUser: null });
}, []);
const setCurrentUser = useCallback((currentUser: TUser | null) => {
setState((prev) => ({ ...prev, currentUser }));
}, []);
const value = useMemo<AuthContextValue<TUser>>(() => ({
...state,
setSession,
setCurrentUser,
clearSession
}), [state, setSession, setCurrentUser, clearSession]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error('useAuth must be used within AuthProvider');
}
return ctx;
}
return {
AuthProvider,
useAuth,
AuthContext
};
}

35
src/auth/jwt.ts Normal file
View File

@@ -0,0 +1,35 @@
const MILLISECONDS_PER_SECOND = 1000;
export function decodeJwtPayload(token: string): Record<string, unknown> | null {
const parts = token.split('.');
if (parts.length !== 3) {
return null;
}
const base64Url = parts[1];
const base64 = base64Url.replaceAll('-', '+').replaceAll('_', '/');
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=');
try {
const payload = JSON.parse(atob(padded));
if (payload && typeof payload === 'object') {
return payload as Record<string, unknown>;
}
} catch {
return null;
}
return null;
}
export function isJwtExpired(token: string, skewSeconds = 0) {
const payload = decodeJwtPayload(token);
const exp = payload?.exp;
if (typeof exp !== 'number' || !Number.isFinite(exp)) {
return false;
}
const expiresAt = exp * MILLISECONDS_PER_SECOND;
const now = Date.now();
return expiresAt <= now + skewSeconds * MILLISECONDS_PER_SECOND;
}

View File

@@ -0,0 +1,217 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type CSSProperties,
type ReactNode
} from 'react';
import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine';
const SIDEBAR_WIDTH_KEY = 'authSidebarWidth';
const SIDEBAR_COLLAPSED_KEY = 'authSidebarCollapsed';
const SIDEBAR_DEFAULT_WIDTH = 280;
const SIDEBAR_MIN_WIDTH = 220;
const SIDEBAR_MAX_WIDTH = 420;
const SIDEBAR_COLLAPSED_WIDTH = 56;
export type LeftMenuRenderState = {
collapsed: boolean;
mobileOpen: boolean;
isDesktop: boolean;
closeMenu: () => void;
};
export type LeftMenuContent = {
ariaLabel?: string;
render: (state: LeftMenuRenderState) => ReactNode;
};
export type LeftMenuStyle = CSSProperties & {
'--auth-sidebar-width': string;
};
type LeftMenuContextValue = {
collapsed: boolean;
mobileOpen: boolean;
content: LeftMenuContent;
desktopMenuStyle: LeftMenuStyle;
openMenu: (content?: LeftMenuContent) => void;
closeMenu: () => void;
toggleMenu: (content?: LeftMenuContent) => void;
expandMenu: () => void;
collapseMenu: () => void;
toggleCollapsed: () => void;
setMenuContent: (content: LeftMenuContent | null) => void;
startResize: ReturnType<typeof useSidePanelMachine>['startResize'];
};
type LeftMenuProviderProps = {
children: ReactNode;
defaultContent: LeftMenuContent;
closeOnPathname?: string;
};
const LeftMenuContext = createContext<LeftMenuContextValue | undefined>(undefined);
function readStoredCollapsed(): boolean {
if (!globalThis.window) {
return false;
}
return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1';
}
export function LeftMenuProvider({
children,
defaultContent,
closeOnPathname
}: Readonly<LeftMenuProviderProps>) {
const [collapsed, setCollapsed] = useState<boolean>(() => readStoredCollapsed());
const [mobileOpen, setMobileOpen] = useState(false);
const [content, setContent] = useState<LeftMenuContent>(defaultContent);
const defaultContentRef = useRef(defaultContent);
useEffect(() => {
const previousDefaultContent = defaultContentRef.current;
defaultContentRef.current = defaultContent;
setContent((currentContent) => {
if (currentContent === previousDefaultContent) {
return defaultContent;
}
return currentContent;
});
}, [defaultContent]);
useEffect(() => {
if (!globalThis.window) {
return;
}
localStorage.setItem(SIDEBAR_COLLAPSED_KEY, collapsed ? '1' : '0');
}, [collapsed]);
const expandMenu = useCallback(() => {
setCollapsed(false);
}, []);
const collapseMenu = useCallback(() => {
setCollapsed(true);
}, []);
const toggleCollapsed = useCallback(() => {
setCollapsed((previous) => !previous);
}, []);
const closeMobile = useCallback(() => {
setMobileOpen(false);
}, []);
const setMenuContent = useCallback((nextContent: LeftMenuContent | null) => {
setContent(nextContent ?? defaultContentRef.current);
}, []);
const closeMenu = useCallback(() => {
if (isDesktopViewport()) {
collapseMenu();
return;
}
closeMobile();
}, [collapseMenu, closeMobile]);
const openMenu = useCallback((nextContent?: LeftMenuContent) => {
if (nextContent) {
setContent(nextContent);
}
if (isDesktopViewport()) {
expandMenu();
return;
}
setMobileOpen(true);
}, [expandMenu]);
const toggleMenu = useCallback((nextContent?: LeftMenuContent) => {
if (nextContent) {
setContent(nextContent);
}
if (isDesktopViewport()) {
toggleCollapsed();
return;
}
setMobileOpen((previous) => !previous);
}, [toggleCollapsed]);
const handleCloseOnPathname = useCallback(() => {
setMobileOpen(false);
setContent(defaultContentRef.current);
}, []);
const { width, startResize } = useSidePanelMachine({
storageKey: SIDEBAR_WIDTH_KEY,
defaultWidth: SIDEBAR_DEFAULT_WIDTH,
minWidth: SIDEBAR_MIN_WIDTH,
maxWidth: SIDEBAR_MAX_WIDTH,
resizeAxis: 'from-left',
resizingBodyClass: 'auth-sidebar-resizing',
isOpen: mobileOpen,
canResize: !collapsed,
shouldPersistWidth: !collapsed,
closeOnPathname,
onCloseOnPathname: handleCloseOnPathname,
onEscape: closeMobile
});
const desktopMenuStyle = useMemo<LeftMenuStyle>(() => ({
'--auth-sidebar-width': `${collapsed ? SIDEBAR_COLLAPSED_WIDTH : width}px`
}), [collapsed, width]);
const value = useMemo<LeftMenuContextValue>(() => ({
collapsed,
mobileOpen,
content,
desktopMenuStyle,
openMenu,
closeMenu,
toggleMenu,
expandMenu,
collapseMenu,
toggleCollapsed,
setMenuContent,
startResize
}), [
collapsed,
mobileOpen,
content,
desktopMenuStyle,
openMenu,
closeMenu,
toggleMenu,
expandMenu,
collapseMenu,
toggleCollapsed,
setMenuContent,
startResize
]);
return (
<LeftMenuContext.Provider value={value}>
{children}
</LeftMenuContext.Provider>
);
}
export function useLeftMenu() {
const ctx = useContext(LeftMenuContext);
if (!ctx) {
throw new Error('useLeftMenu must be used within LeftMenuProvider');
}
return ctx;
}

View File

@@ -0,0 +1,139 @@
import {
createContext,
useCallback,
useContext,
useMemo,
useState,
type CSSProperties,
type ReactNode
} from 'react';
import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine';
const RIGHT_SIDEBAR_WIDTH_KEY = 'authRightSidebarWidth';
const RIGHT_SIDEBAR_DEFAULT_WIDTH = 320;
const RIGHT_SIDEBAR_MIN_WIDTH = 260;
const RIGHT_SIDEBAR_MAX_WIDTH = 480;
export type RightSidebarContent = {
title: string;
content: ReactNode;
ariaLabel?: string;
};
export type RightSidebarStyle = CSSProperties & {
'--auth-right-sidebar-width': string;
};
type RightSidebarContextValue = {
isOpen: boolean;
content: RightSidebarContent | null;
openSidebar: (content?: RightSidebarContent) => void;
closeSidebar: () => void;
toggleSidebar: (content?: RightSidebarContent) => void;
setSidebarContent: (content: RightSidebarContent | null) => void;
desktopSidebarStyle: RightSidebarStyle;
startResize: ReturnType<typeof useSidePanelMachine>['startResize'];
};
type RightSidebarProviderProps = {
children: ReactNode;
closeOnPathname?: string;
onMobileOpenRequest?: () => void;
};
const RightSidebarContext = createContext<RightSidebarContextValue | undefined>(undefined);
export function RightSidebarProvider({
children,
closeOnPathname,
onMobileOpenRequest
}: Readonly<RightSidebarProviderProps>) {
const [isOpen, setIsOpen] = useState(false);
const [content, setContent] = useState<RightSidebarContent | null>(null);
const closeSidebar = useCallback(() => {
setIsOpen(false);
setContent(null);
}, []);
const setSidebarContent = useCallback((nextContent: RightSidebarContent | null) => {
setContent(nextContent);
}, []);
const openSidebar = useCallback((nextContent?: RightSidebarContent) => {
const resolvedContent = nextContent ?? content;
if (!resolvedContent) {
return;
}
if (nextContent) {
setContent(nextContent);
}
if (!isDesktopViewport()) {
onMobileOpenRequest?.();
}
setIsOpen(true);
}, [content, onMobileOpenRequest]);
const toggleSidebar = useCallback((nextContent?: RightSidebarContent) => {
if (isOpen) {
closeSidebar();
return;
}
openSidebar(nextContent);
}, [isOpen, closeSidebar, openSidebar]);
const { width, startResize } = useSidePanelMachine({
storageKey: RIGHT_SIDEBAR_WIDTH_KEY,
defaultWidth: RIGHT_SIDEBAR_DEFAULT_WIDTH,
minWidth: RIGHT_SIDEBAR_MIN_WIDTH,
maxWidth: RIGHT_SIDEBAR_MAX_WIDTH,
resizeAxis: 'from-right',
resizingBodyClass: 'auth-right-sidebar-resizing',
isOpen,
canResize: isOpen,
shouldPersistWidth: true,
closeOnPathname,
onCloseOnPathname: closeSidebar,
onEscape: closeSidebar
});
const desktopSidebarStyle = useMemo<RightSidebarStyle>(() => ({
'--auth-right-sidebar-width': `${width}px`
}), [width]);
const value = useMemo<RightSidebarContextValue>(() => ({
isOpen,
content,
openSidebar,
closeSidebar,
toggleSidebar,
setSidebarContent,
desktopSidebarStyle,
startResize
}), [
isOpen,
content,
openSidebar,
closeSidebar,
toggleSidebar,
setSidebarContent,
desktopSidebarStyle,
startResize
]);
return (
<RightSidebarContext.Provider value={value}>
{children}
</RightSidebarContext.Provider>
);
}
export function useRightSidebar() {
const ctx = useContext(RightSidebarContext);
if (!ctx) {
throw new Error('useRightSidebar must be used within RightSidebarProvider');
}
return ctx;
}

View File

@@ -0,0 +1,132 @@
export type ErrorCatalog = Record<string, string>;
type ErrorLike = {
code?: unknown;
status?: unknown;
message?: unknown;
rawMessage?: unknown;
};
export type ResolveErrorMessageOptions = {
code?: string | null;
status?: number | null;
context?: string;
fallbackMessage?: string | null;
};
export type CreateErrorResolverConfig = {
catalog: ErrorCatalog;
fallbackCode?: string;
defaultContext?: string;
contextOverrides?: Record<string, Partial<Record<string, string>>>;
inferCodeFromStatus?: (status?: number | null) => string | undefined;
inferCodeFromLegacyMessage?: (message?: string | null) => string | undefined;
};
export function createErrorResolver(config: CreateErrorResolverConfig) {
const {
catalog,
fallbackCode,
defaultContext = 'default',
contextOverrides = {},
inferCodeFromStatus,
inferCodeFromLegacyMessage
} = config;
const knownCodes = new Set(Object.keys(catalog));
function isKnownErrorCode(value: string): boolean {
return knownCodes.has(value);
}
function normalizeErrorCode(code?: string | null): string | undefined {
if (!code) {
return undefined;
}
return isKnownErrorCode(code) ? code : undefined;
}
function inferErrorCodeFromStatus(status?: number | null): string | undefined {
return inferCodeFromStatus?.(status);
}
function resolveErrorMessage(options: ResolveErrorMessageOptions): string {
const {
code,
status,
context = defaultContext,
fallbackMessage
} = options;
const resolvedCode = normalizeErrorCode(code)
?? inferCodeFromLegacyMessage?.(fallbackMessage)
?? inferErrorCodeFromStatus(status);
if (resolvedCode) {
const contextMessage = contextOverrides[context]?.[resolvedCode];
if (contextMessage) {
return contextMessage;
}
const catalogMessage = catalog[resolvedCode];
if (catalogMessage) {
return catalogMessage;
}
}
const statusCode = inferErrorCodeFromStatus(status);
if (statusCode) {
const contextMessage = contextOverrides[context]?.[statusCode];
if (contextMessage) {
return contextMessage;
}
const catalogMessage = catalog[statusCode];
if (catalogMessage) {
return catalogMessage;
}
}
if (fallbackCode && catalog[fallbackCode]) {
return catalog[fallbackCode];
}
if (fallbackMessage) {
return fallbackMessage;
}
return 'Request failed. Please try again.';
}
function resolveOptionalErrorMessage(code?: string | null, context: string = defaultContext): string | undefined {
if (!code) {
return undefined;
}
return resolveErrorMessage({ code, context });
}
function toErrorMessage(err: unknown, context: string = defaultContext): string {
if (err && typeof err === 'object') {
const errorLike = err as ErrorLike;
const code = typeof errorLike.code === 'string' ? errorLike.code : undefined;
const status = typeof errorLike.status === 'number' ? errorLike.status : undefined;
const rawMessage = typeof errorLike.rawMessage === 'string' ? errorLike.rawMessage : undefined;
const message = typeof errorLike.message === 'string' ? errorLike.message : undefined;
return resolveErrorMessage({
code,
status,
context,
fallbackMessage: rawMessage ?? message
});
}
return resolveErrorMessage({ context });
}
return {
isKnownErrorCode,
inferErrorCodeFromStatus,
resolveErrorMessage,
resolveOptionalErrorMessage,
toErrorMessage
};
}

View File

@@ -0,0 +1,28 @@
import { useCallback, useEffect, useState } from 'react';
export function useCooldownTimer(seconds = 0, enabled = true) {
const [cooldown, setCooldown] = useState(seconds);
useEffect(() => {
if (!enabled || cooldown <= 0) {
return;
}
const timer = globalThis.setInterval(() => {
setCooldown((prev) => (prev > 0 ? prev - 1 : 0));
}, 1000);
return () => {
globalThis.clearInterval(timer);
};
}, [enabled, cooldown]);
const startCooldown = useCallback((seconds: number) => {
setCooldown(Math.max(0, Math.floor(seconds)));
}, []);
return {
cooldown,
startCooldown
};
}

View File

@@ -0,0 +1,68 @@
import { useCallback, useState } from 'react';
import { useValidatedFields } from './useValidatedFields';
type FieldErrors<TValues> = Partial<Record<keyof TValues, string | undefined>>;
type UseEditableFormOptions<TValues> = {
initialValues: TValues;
validate: (values: TValues) => FieldErrors<TValues>;
};
export function useEditableForm<TValues extends Record<string, string>>({
initialValues,
validate
}: UseEditableFormOptions<TValues>) {
const [isEditing, setIsEditing] = useState(false);
const {
values,
errors,
isValid,
setValues,
setFieldValue,
validateAll,
setFieldError,
setErrors,
clearErrors
} = useValidatedFields({
initialValues,
validate
});
const startEditing = useCallback((sourceValues: TValues) => {
setValues(sourceValues, { validate: true });
setIsEditing(true);
}, [setValues]);
const discardChanges = useCallback((sourceValues: TValues) => {
setValues(sourceValues, { clearErrors: true });
setIsEditing(false);
}, [setValues]);
const loadFromSource = useCallback((sourceValues: TValues) => {
setValues(sourceValues, { clearErrors: true });
}, [setValues]);
const commitSaved = useCallback((sourceValues: TValues) => {
setValues(sourceValues, { clearErrors: true });
setIsEditing(false);
}, [setValues]);
return {
values,
errors,
isValid,
setValues,
setFieldValue,
validateAll,
setFieldError,
setErrors,
clearErrors,
isEditing,
startEditing,
discardChanges,
loadFromSource,
commitSaved,
setIsEditing
};
}

View File

@@ -0,0 +1,102 @@
import { useCallback, useEffect, useState } from 'react';
type PaginatedResourceResponse<TItem> = {
items: TItem[];
page: number;
pageSize: number;
total: number;
totalPages: number;
};
type UsePaginatedResourceOptions<TItem> = {
load: (params: { q: string; page: number; pageSize: number; sort?: string }) => Promise<PaginatedResourceResponse<TItem>>;
sort?: string;
debounceMs?: number;
initialQuery?: string;
initialPage?: number;
initialPageSize?: number;
};
export function usePaginatedResource<TItem>({
load,
sort,
debounceMs = 250,
initialQuery = '',
initialPage = 1,
initialPageSize = 10
}: UsePaginatedResourceOptions<TItem>) {
const [items, setItems] = useState<TItem[]>([]);
const [q, setQ] = useState(initialQuery);
const [page, setPage] = useState(initialPage);
const [pageSize, setPageSize] = useState(initialPageSize);
const [total, setTotal] = useState(0);
const [totalPages, setTotalPages] = useState(0);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let cancelled = false;
setIsLoading(true);
setError(null);
const timer = setTimeout(() => {
void (async () => {
try {
const response = await load({
q,
page,
pageSize,
sort
});
if (cancelled) {
return;
}
setItems(response.items);
setTotal(response.total);
setTotalPages(response.totalPages);
setPage(response.page);
setPageSize(response.pageSize);
} catch (err) {
if (!cancelled) {
setError(err instanceof Error ? err.message : 'Request failed. Please try again.');
}
} finally {
if (!cancelled) {
setIsLoading(false);
}
}
})();
}, debounceMs);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [q, page, pageSize, sort, load, debounceMs]);
const setQuery = useCallback((value: string) => {
setQ(value);
setPage(1);
}, []);
const setPageSizeAndResetPage = useCallback((value: number) => {
setPageSize(value);
setPage(1);
}, []);
return {
items,
q,
page,
pageSize,
total,
totalPages,
error,
isLoading,
setQuery,
setPage,
setPageSize: setPageSizeAndResetPage
};
}

78
src/hooks/useSorting.ts Normal file
View File

@@ -0,0 +1,78 @@
import { useCallback, useMemo, useState } from 'react';
export type SortDirection = 'asc' | 'desc';
export type SortState = {
field: string;
direction: SortDirection;
};
function invertDirection(direction: SortDirection): SortDirection {
return direction === 'asc' ? 'desc' : 'asc';
}
export function formatSortParam(sort: SortState | null | undefined): string | undefined {
if (!sort) {
return undefined;
}
return sort.direction === 'desc' ? `-${sort.field}` : sort.field;
}
type UseSortingResult = {
activeSort: SortState | null;
sortParam: string | undefined;
toggleSort: (field: string) => void;
setSort: (next: SortState | null) => void;
resetSort: () => void;
};
export function useSorting(defaultSort?: SortState | null): UseSortingResult {
const [overrideSort, setOverrideSort] = useState<SortState | null>(null);
const activeSort = overrideSort ?? defaultSort ?? null;
const toggleSort = useCallback((field: string) => {
setOverrideSort((previousOverride) => {
const baselineSort = defaultSort ?? null;
const currentSort = previousOverride ?? baselineSort;
if (!currentSort || currentSort.field !== field) {
return { field, direction: 'asc' };
}
if (baselineSort && baselineSort.field === field) {
if (previousOverride == null) {
return { field, direction: invertDirection(baselineSort.direction) };
}
if (previousOverride.direction === baselineSort.direction) {
return { field, direction: invertDirection(baselineSort.direction) };
}
return null;
}
if (previousOverride == null || previousOverride.direction === 'desc') {
return null;
}
return { field, direction: 'desc' };
});
}, [defaultSort]);
const setSort = useCallback((next: SortState | null) => {
setOverrideSort(next);
}, []);
const resetSort = useCallback(() => {
setOverrideSort(null);
}, []);
const sortParam = useMemo(() => formatSortParam(activeSort), [activeSort]);
return {
activeSort,
sortParam,
toggleSort,
setSort,
resetSort
};
}

View File

@@ -0,0 +1,31 @@
import { useCallback, useState } from 'react';
export function useSubmitState<TStatus = string | null>(initialStatus: TStatus) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const [status, setStatus] = useState<TStatus>(initialStatus);
const startSubmitting = useCallback(() => {
setIsSubmitting(true);
}, []);
const finishSubmitting = useCallback(() => {
setIsSubmitting(false);
}, []);
const clearFeedback = useCallback(() => {
setSubmitError(null);
setStatus(initialStatus);
}, [initialStatus]);
return {
isSubmitting,
submitError,
status,
startSubmitting,
finishSubmitting,
setSubmitError,
setStatus,
clearFeedback
};
}

View File

@@ -0,0 +1,166 @@
import { useCallback, useMemo, useState } from 'react';
type FieldErrors<TValues> = Partial<Record<keyof TValues, string | undefined>>;
type TouchedFields<TValues> = Partial<Record<keyof TValues, boolean>>;
type SetValuesOptions = {
validate?: boolean;
clearErrors?: boolean;
};
type SetFieldValueOptions = {
validate?: boolean;
touch?: boolean;
};
type ValidateAllOptions = {
touchAll?: boolean;
};
type UseValidatedFieldsOptions<TValues> = {
initialValues: TValues;
validate: (values: TValues) => FieldErrors<TValues>;
};
function hasErrors<TValues>(errors: FieldErrors<TValues>): boolean {
return Object.values(errors).some(Boolean);
}
function pickTouchedErrors<TValues>(
errors: FieldErrors<TValues>,
touched: TouchedFields<TValues>
): FieldErrors<TValues> {
const next: FieldErrors<TValues> = {};
for (const key of Object.keys(errors) as Array<keyof TValues>) {
if (touched[key]) {
next[key] = errors[key];
}
}
return next;
}
function touchAll<TValues extends Record<string, string>>(values: TValues): TouchedFields<TValues> {
const touched: TouchedFields<TValues> = {};
for (const key of Object.keys(values) as Array<keyof TValues>) {
touched[key] = true;
}
return touched;
}
export function useValidatedFields<TValues extends Record<string, string>>({
initialValues,
validate
}: UseValidatedFieldsOptions<TValues>) {
const [values, setValues] = useState<TValues>(initialValues);
const [allErrors, setAllErrors] = useState<FieldErrors<TValues>>(() => validate(initialValues));
const [touched, setTouched] = useState<TouchedFields<TValues>>({});
const updateValues = useCallback((nextValues: TValues, options: SetValuesOptions = {}) => {
const { validate: shouldValidate = false, clearErrors = false } = options;
setValues(nextValues);
if (shouldValidate || clearErrors) {
setAllErrors(validate(nextValues));
}
if (clearErrors) {
setTouched({});
}
}, [validate]);
const setFieldValue = useCallback(<K extends keyof TValues>(
key: K,
value: TValues[K],
options: SetFieldValueOptions = {}
) => {
const { validate: shouldValidate = true, touch = true } = options;
if (touch) {
setTouched((current) => ({
...current,
[key]: true
}));
}
setValues((current) => {
const nextValues = {
...current,
[key]: value
};
if (shouldValidate) {
setAllErrors(validate(nextValues));
}
return nextValues;
});
}, [validate]);
const validateAll = useCallback((options: ValidateAllOptions = {}) => {
const { touchAll: shouldTouchAll = true } = options;
const nextErrors = validate(values);
setAllErrors(nextErrors);
if (shouldTouchAll) {
setTouched(touchAll(values));
}
return nextErrors;
}, [validate, values]);
const setFieldError = useCallback(<K extends keyof TValues>(key: K, message?: string) => {
setTouched((current) => ({
...current,
[key]: true
}));
setAllErrors((current) => ({
...current,
[key]: message
}));
}, []);
const updateErrors = useCallback((nextErrors: FieldErrors<TValues>) => {
const nextTouched: TouchedFields<TValues> = {};
for (const key of Object.keys(nextErrors) as Array<keyof TValues>) {
if (nextErrors[key]) {
nextTouched[key] = true;
}
}
setTouched((current) => ({
...current,
...nextTouched
}));
setAllErrors(nextErrors);
}, []);
const clearErrors = useCallback(() => {
setAllErrors(validate(values));
setTouched({});
}, [validate, values]);
const errors = useMemo(() => pickTouchedErrors(allErrors, touched), [allErrors, touched]);
const isValid = useMemo(() => {
return !hasErrors(validate(values));
}, [validate, values]);
return {
values,
errors,
isValid,
setValues: updateValues,
setFieldValue,
validateAll,
setFieldError,
setErrors: updateErrors,
clearErrors
};
}

29
src/index.ts Normal file
View File

@@ -0,0 +1,29 @@
export { createAuthContext } from './auth/createAuthContext';
export type { AuthContextValue, AuthState, CreateAuthContextOptions } from './auth/createAuthContext';
export { decodeJwtPayload, isJwtExpired } from './auth/jwt';
export { createApiClient, ApiError } from './api/createApiClient';
export type { CreateApiClientConfig, RequestOptions, ResolveErrorInput } from './api/createApiClient';
export { buildListQuery } from './api/query';
export { createErrorResolver } from './errors/createErrorResolver';
export type { CreateErrorResolverConfig, ErrorCatalog, ResolveErrorMessageOptions } from './errors/createErrorResolver';
export { useValidatedFields } from './hooks/useValidatedFields';
export { useEditableForm } from './hooks/useEditableForm';
export { useSubmitState } from './hooks/useSubmitState';
export { usePaginatedResource } from './hooks/usePaginatedResource';
export { useSorting, formatSortParam } from './hooks/useSorting';
export type { SortDirection, SortState } from './hooks/useSorting';
export { useCooldownTimer } from './hooks/useCooldownTimer';
export { LeftMenuProvider, useLeftMenu } from './contexts/LeftMenuContext';
export type { LeftMenuContent, LeftMenuRenderState, LeftMenuStyle } from './contexts/LeftMenuContext';
export { RightSidebarProvider, useRightSidebar } from './contexts/RightSidebarContext';
export type { RightSidebarContent, RightSidebarStyle } from './contexts/RightSidebarContext';
export { formatDate, capitalize, splitAndCapitalize } from './utils/formatting';
export type { SplitMode } from './utils/formatting';
export { shouldShowVerifiedEmailBadge } from './utils/verifiedEmail';

View File

@@ -0,0 +1,174 @@
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react';
const DEFAULT_DESKTOP_BREAKPOINT = 1024;
type ResizeAxis = 'from-left' | 'from-right';
export type SidePanelMachineOptions = {
storageKey: string;
defaultWidth: number;
minWidth: number;
maxWidth: number;
resizeAxis: ResizeAxis;
resizingBodyClass: string;
isOpen: boolean;
canResize: boolean;
shouldPersistWidth: boolean;
closeOnPathname?: string;
onCloseOnPathname?: () => void;
onEscape?: () => void;
desktopBreakpoint?: number;
};
export type SidePanelMachineResult = {
width: number;
isDesktop: boolean;
startResize: (event: ReactPointerEvent<HTMLDivElement>) => void;
};
export function isDesktopViewport(breakpoint = DEFAULT_DESKTOP_BREAKPOINT): boolean {
if (!globalThis.window) {
return true;
}
if (typeof globalThis.window.matchMedia === 'function') {
return globalThis.window.matchMedia(`(min-width: ${breakpoint}px)`).matches;
}
return window.innerWidth >= breakpoint;
}
export function useSidePanelMachine({
storageKey,
defaultWidth,
minWidth,
maxWidth,
resizeAxis,
resizingBodyClass,
isOpen,
canResize,
shouldPersistWidth,
closeOnPathname,
onCloseOnPathname,
onEscape,
desktopBreakpoint = DEFAULT_DESKTOP_BREAKPOINT
}: SidePanelMachineOptions): SidePanelMachineResult {
const isResizingRef = useRef(false);
const resizeStartXRef = useRef(0);
const resizeStartWidthRef = useRef(0);
const clampWidth = useCallback((value: number) => {
return Math.min(maxWidth, Math.max(minWidth, value));
}, [maxWidth, minWidth]);
const readStoredWidth = useCallback(() => {
if (!globalThis.window) {
return defaultWidth;
}
const storedValue = localStorage.getItem(storageKey);
const parsed = Number(storedValue);
if (!Number.isFinite(parsed)) {
return defaultWidth;
}
return clampWidth(parsed);
}, [defaultWidth, storageKey, clampWidth]);
const [width, setWidth] = useState<number>(() => readStoredWidth());
useEffect(() => {
if (closeOnPathname == null || !onCloseOnPathname) {
return;
}
onCloseOnPathname();
}, [closeOnPathname, onCloseOnPathname]);
useEffect(() => {
if (!shouldPersistWidth || !globalThis.window) {
return;
}
localStorage.setItem(storageKey, String(width));
}, [shouldPersistWidth, storageKey, width]);
useEffect(() => {
function handlePointerMove(event: PointerEvent) {
if (!isResizingRef.current || !canResize) {
return;
}
const deltaX = event.clientX - resizeStartXRef.current;
const delta = resizeAxis === 'from-left' ? deltaX : -deltaX;
const nextWidth = clampWidth(resizeStartWidthRef.current + delta);
setWidth(nextWidth);
}
function stopResizing() {
if (!isResizingRef.current) {
return;
}
isResizingRef.current = false;
document.body.classList.remove(resizingBodyClass);
}
globalThis.addEventListener('pointermove', handlePointerMove);
globalThis.addEventListener('pointerup', stopResizing);
return () => {
globalThis.removeEventListener('pointermove', handlePointerMove);
globalThis.removeEventListener('pointerup', stopResizing);
document.body.classList.remove(resizingBodyClass);
};
}, [canResize, clampWidth, resizeAxis, resizingBodyClass]);
useEffect(() => {
if (!isOpen || isDesktopViewport(desktopBreakpoint)) {
return;
}
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = previousOverflow;
};
}, [isOpen, desktopBreakpoint]);
useEffect(() => {
if (!isOpen || !onEscape) {
return;
}
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onEscape();
}
};
globalThis.addEventListener('keydown', handleEscape);
return () => {
globalThis.removeEventListener('keydown', handleEscape);
};
}, [isOpen, onEscape]);
const startResize = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
if (!canResize || !isDesktopViewport(desktopBreakpoint)) {
return;
}
isResizingRef.current = true;
resizeStartXRef.current = event.clientX;
resizeStartWidthRef.current = width;
document.body.classList.add(resizingBodyClass);
event.preventDefault();
}, [canResize, desktopBreakpoint, resizingBodyClass, width]);
return {
width,
isDesktop: isDesktopViewport(desktopBreakpoint),
startResize
};
}

64
src/utils/formatting.ts Normal file
View File

@@ -0,0 +1,64 @@
export function formatDate(value: string, seconds = false): string {
const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
...(seconds ? { second: "2-digit" } : {}),
};
return new Date(value).toLocaleString("it-IT", options);
}
export const capitalize = (str: string) =>
str.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
export type SplitMode = "underscore" | "camel" | "auto";
/** Title-case a string while preserving short all-caps acronyms (e.g., XML) */
const toTitleCase = (s: string) =>
s
.trim()
.toLowerCase()
.split(/\s+/)
.map(w =>
/^[A-Z]{2,4}$/.test(w) ? w : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
)
.join(" ");
const splitUnderscoreHyphen = (s: string) => s.replaceAll(/[_-]+/g, " ");
/** Insert spaces at camelCase boundaries and around digit/letter edges */
const splitCamel = (s: string) =>
s
// fooBar -> foo Bar ; foo2D -> foo 2D
.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2")
// XMLHttp -> XML Http (acronym + word)
.replaceAll(/([A-Z])([A-Z][a-z])/g, "$1 $2")
// letter<->digit boundaries
.replaceAll(/([a-zA-Z])([0-9])/g, "$1 $2")
.replaceAll(/([0-9])([a-zA-Z])/g, "$1 $2");
/**
* Split and capitalize either by underscores/hyphens or camelCase.
* mode:
* - "underscore": split on _ or -
* - "camel": split on camelCase boundaries
* - "auto": pick underscore if present, otherwise camel
*/
export function splitAndCapitalize(str?: string, mode: SplitMode = "auto"): string {
if (!str) return "";
// normalize underscores/hyphens first for auto decision
const hasUnderscoreLike = /[_-]/.test(str);
const chosen: SplitMode =
mode === "auto" ? (hasUnderscoreLike ? "underscore" : "camel") : mode;
const spaced =
chosen === "underscore" ? splitUnderscoreHyphen(str) : splitCamel(str);
// collapse extra spaces, then title-case
return toTitleCase(spaced.replaceAll(/\s+/g, " ").trim());
}

View File

@@ -0,0 +1,20 @@
type VerifiedEmailVisibilityOptions = {
verifiedAt: string | null;
persistedEmail: string;
currentEmail: string;
isEditing: boolean;
};
export function shouldShowVerifiedEmailBadge(options: VerifiedEmailVisibilityOptions): boolean {
const { verifiedAt, persistedEmail, currentEmail, isEditing } = options;
if (!verifiedAt) {
return false;
}
if (!isEditing) {
return true;
}
return persistedEmail.trim() === currentEmail.trim();
}