update prettier
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2026-02-23 14:23:46 +01:00
parent 33d1425fbb
commit cbabf43584
25 changed files with 1373 additions and 1363 deletions

View File

@@ -4,34 +4,34 @@ type: docker
name: web-core-ci name: web-core-ci
trigger: trigger:
branch: branch:
- main - main
- develop - develop
event: event:
- push - push
- pull_request - pull_request
steps: steps:
- name: install - name: install
image: node:22 image: node:22
commands: commands:
- corepack enable - corepack enable
- corepack prepare yarn@1.22.22 --activate - corepack prepare yarn@1.22.22 --activate
- yarn install --frozen-lockfile - yarn install --frozen-lockfile
- name: lint - name: lint
image: node:22 image: node:22
commands: commands:
- corepack enable - corepack enable
- corepack prepare yarn@1.22.22 --activate - corepack prepare yarn@1.22.22 --activate
- yarn lint - yarn lint
- name: build - name: build
image: node:22 image: node:22
commands: commands:
- corepack enable - corepack enable
- corepack prepare yarn@1.22.22 --activate - corepack prepare yarn@1.22.22 --activate
- yarn build - yarn build
--- ---
kind: pipeline kind: pipeline
@@ -39,22 +39,22 @@ type: docker
name: web-core-publish name: web-core-publish
trigger: trigger:
branch: branch:
- main - main
event: event:
- promote - promote
target: target:
- production - production
steps: steps:
- name: publish-npm - name: publish-npm
image: node:22 image: node:22
environment: environment:
NEXUS_NPM_TOKEN: NEXUS_NPM_TOKEN:
from_secret: nexus_npm_token from_secret: nexus_npm_token
commands: commands:
- corepack enable - corepack enable
- corepack prepare yarn@1.22.22 --activate - corepack prepare yarn@1.22.22 --activate
- yarn install --frozen-lockfile - yarn install --frozen-lockfile
- npm config set //nexus.beatrice.wtf/repository/npm-hosted/:_authToken "$NEXUS_NPM_TOKEN" - npm config set //nexus.beatrice.wtf/repository/npm-hosted/:_authToken "$NEXUS_NPM_TOKEN"
- yarn publish:nexus - yarn publish:nexus

View File

@@ -1,7 +1,7 @@
{ {
"$schema": "https://json.schemastore.org/prettierrc", "$schema": "https://json.schemastore.org/prettierrc",
"singleQuote": true, "singleQuote": true,
"semi": true, "semi": true,
"printWidth": 100, "printWidth": 100,
"tabWidth": 2 "tabWidth": 4
} }

View File

@@ -5,47 +5,47 @@ import globals from 'globals';
import tseslint from 'typescript-eslint'; import tseslint from 'typescript-eslint';
export default tseslint.config( export default tseslint.config(
{ {
ignores: [ ignores: [
'dist', 'dist',
'coverage', 'coverage',
'node_modules', 'node_modules',
'*.config.cjs', '*.config.cjs',
'vite.config.js', 'vite.config.js',
'vite.config.d.ts', 'vite.config.d.ts',
], ],
},
js.configs.recommended,
...tseslint.configs.recommended,
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: {
...globals.browser,
...globals.node,
},
}, },
rules: { js.configs.recommended,
'no-empty': ['error', { allowEmptyCatch: true }], ...tseslint.configs.recommended,
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: {
...globals.browser,
...globals.node,
},
},
rules: {
'no-empty': ['error', { allowEmptyCatch: true }],
},
}, },
}, {
{ files: ['src/**/*.{ts,tsx}'],
files: ['src/**/*.{ts,tsx}'], plugins: {
plugins: { 'react-hooks': reactHooks,
'react-hooks': reactHooks, 'react-refresh': reactRefresh,
'react-refresh': reactRefresh, },
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
},
}, },
rules: { {
...reactHooks.configs.recommended.rules, files: ['src/contexts/**/*.{ts,tsx}'],
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }], rules: {
'react-refresh/only-export-components': 'off',
},
}, },
},
{
files: ['src/contexts/**/*.{ts,tsx}'],
rules: {
'react-refresh/only-export-components': 'off',
},
},
); );

View File

@@ -1,51 +1,51 @@
{ {
"name": "@panic/web-core", "name": "@panic/web-core",
"version": "0.1.3", "version": "0.1.3",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"description": "Core auth and utilities for panic.haus web applications", "description": "Core auth and utilities for panic.haus web applications",
"type": "module", "type": "module",
"main": "./dist/index.js", "main": "./dist/index.js",
"module": "./dist/index.js", "module": "./dist/index.js",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"exports": { "exports": {
".": { ".": {
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"import": "./dist/index.js" "import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"clean": "rm -rf dist",
"build": "yarn clean && vite build && tsc -p tsconfig.build.json",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier . --write",
"format:check": "prettier . --check",
"prepublishOnly": "yarn build",
"publish:nexus": "npm publish --registry ${NEXUS_NPM_REGISTRY:-https://nexus.beatrice.wtf/repository/npm-hosted/}"
},
"publishConfig": {
"registry": "https://nexus.beatrice.wtf/repository/npm-hosted/",
"access": "restricted"
},
"peerDependencies": {
"react": "^19.0.0"
},
"devDependencies": {
"@eslint/js": "^9",
"@types/react": "^19.0.0",
"@vitejs/plugin-react": "^5.0.0",
"eslint": "^9",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.1",
"globals": "^17.3.0",
"prettier": "^3.8.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"typescript": "^5.6.2",
"typescript-eslint": "^8.56.0",
"vite": "^7.0.0"
} }
},
"files": [
"dist"
],
"scripts": {
"clean": "rm -rf dist",
"build": "yarn clean && vite build && tsc -p tsconfig.build.json",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier . --write",
"format:check": "prettier . --check",
"prepublishOnly": "yarn build",
"publish:nexus": "npm publish --registry ${NEXUS_NPM_REGISTRY:-https://nexus.beatrice.wtf/repository/npm-hosted/}"
},
"publishConfig": {
"registry": "https://nexus.beatrice.wtf/repository/npm-hosted/",
"access": "restricted"
},
"peerDependencies": {
"react": "^19.0.0"
},
"devDependencies": {
"@eslint/js": "^9",
"@types/react": "^19.0.0",
"@vitejs/plugin-react": "^5.0.0",
"eslint": "^9",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.1",
"globals": "^17.3.0",
"prettier": "^3.8.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"typescript": "^5.6.2",
"typescript-eslint": "^8.56.0",
"vite": "^7.0.0"
}
} }

View File

@@ -1,3 +1,3 @@
{ {
"$schema": "https://docs.renovatebot.com/renovate-schema.json" "$schema": "https://docs.renovatebot.com/renovate-schema.json"
} }

View File

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

View File

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

View File

@@ -6,91 +6,91 @@ const DEFAULT_REFRESH_TOKEN_KEY = 'refreshToken';
const DEFAULT_LEGACY_KEYS = ['auth_token', 'auth_user', 'token']; const DEFAULT_LEGACY_KEYS = ['auth_token', 'auth_user', 'token'];
export type AuthState<TUser> = { export type AuthState<TUser> = {
authToken: string | null; authToken: string | null;
refreshToken: string | null; refreshToken: string | null;
currentUser: TUser | null; currentUser: TUser | null;
}; };
export type AuthContextValue<TUser> = AuthState<TUser> & { export type AuthContextValue<TUser> = AuthState<TUser> & {
setSession: (authToken: string, refreshToken: string, currentUser: TUser) => void; setSession: (authToken: string, refreshToken: string, currentUser: TUser) => void;
setCurrentUser: (currentUser: TUser | null) => void; setCurrentUser: (currentUser: TUser | null) => void;
clearSession: () => void; clearSession: () => void;
}; };
export type CreateAuthContextOptions = { export type CreateAuthContextOptions = {
authTokenKey?: string; authTokenKey?: string;
refreshTokenKey?: string; refreshTokenKey?: string;
legacyKeys?: string[]; legacyKeys?: string[];
}; };
export function createAuthContext<TUser>(options: CreateAuthContextOptions = {}) { export function createAuthContext<TUser>(options: CreateAuthContextOptions = {}) {
const authTokenKey = options.authTokenKey ?? DEFAULT_AUTH_TOKEN_KEY; const authTokenKey = options.authTokenKey ?? DEFAULT_AUTH_TOKEN_KEY;
const refreshTokenKey = options.refreshTokenKey ?? DEFAULT_REFRESH_TOKEN_KEY; const refreshTokenKey = options.refreshTokenKey ?? DEFAULT_REFRESH_TOKEN_KEY;
const legacyKeys = options.legacyKeys ?? DEFAULT_LEGACY_KEYS; const legacyKeys = options.legacyKeys ?? DEFAULT_LEGACY_KEYS;
const AuthContext = createContext<AuthContextValue<TUser> | undefined>(undefined); const AuthContext = createContext<AuthContextValue<TUser> | undefined>(undefined);
function readStoredSession(): AuthState<TUser> { function readStoredSession(): AuthState<TUser> {
for (const key of legacyKeys) { for (const key of legacyKeys) {
localStorage.removeItem(key); localStorage.removeItem(key);
}
const authToken = localStorage.getItem(authTokenKey);
const refreshToken = localStorage.getItem(refreshTokenKey);
return {
authToken,
refreshToken,
currentUser: null,
};
} }
const authToken = localStorage.getItem(authTokenKey); function AuthProvider({ children }: Readonly<{ children: ReactNode }>) {
const refreshToken = localStorage.getItem(refreshTokenKey); 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 { return {
authToken, AuthProvider,
refreshToken, useAuth,
currentUser: null, AuthContext,
}; };
}
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,
};
} }

View File

@@ -1,35 +1,35 @@
const MILLISECONDS_PER_SECOND = 1000; const MILLISECONDS_PER_SECOND = 1000;
export function decodeJwtPayload(token: string): Record<string, unknown> | null { export function decodeJwtPayload(token: string): Record<string, unknown> | null {
const parts = token.split('.'); const parts = token.split('.');
if (parts.length !== 3) { if (parts.length !== 3) {
return null; 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; 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) { export function isJwtExpired(token: string, skewSeconds = 0) {
const payload = decodeJwtPayload(token); const payload = decodeJwtPayload(token);
const exp = payload?.exp; const exp = payload?.exp;
if (typeof exp !== 'number' || !Number.isFinite(exp)) { if (typeof exp !== 'number' || !Number.isFinite(exp)) {
return false; return false;
} }
const expiresAt = exp * MILLISECONDS_PER_SECOND; const expiresAt = exp * MILLISECONDS_PER_SECOND;
const now = Date.now(); const now = Date.now();
return expiresAt <= now + skewSeconds * MILLISECONDS_PER_SECOND; return expiresAt <= now + skewSeconds * MILLISECONDS_PER_SECOND;
} }

View File

@@ -1,13 +1,13 @@
import { import {
createContext, createContext,
useCallback, useCallback,
useContext, useContext,
useEffect, useEffect,
useMemo, useMemo,
useRef, useRef,
useState, useState,
type CSSProperties, type CSSProperties,
type ReactNode, type ReactNode,
} from 'react'; } from 'react';
import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine'; import { isDesktopViewport, useSidePanelMachine } from '../panels/useSidePanelMachine';
@@ -19,207 +19,207 @@ const SIDEBAR_MAX_WIDTH = 420;
const SIDEBAR_COLLAPSED_WIDTH = 56; const SIDEBAR_COLLAPSED_WIDTH = 56;
export type LeftMenuRenderState = { export type LeftMenuRenderState = {
collapsed: boolean; collapsed: boolean;
mobileOpen: boolean; mobileOpen: boolean;
isDesktop: boolean; isDesktop: boolean;
closeMenu: () => void; closeMenu: () => void;
}; };
export type LeftMenuContent = { export type LeftMenuContent = {
ariaLabel?: string; ariaLabel?: string;
render: (state: LeftMenuRenderState) => ReactNode; render: (state: LeftMenuRenderState) => ReactNode;
}; };
export type LeftMenuStyle = CSSProperties & { export type LeftMenuStyle = CSSProperties & {
'--auth-sidebar-width': string; '--auth-sidebar-width': string;
}; };
type LeftMenuContextValue = { type LeftMenuContextValue = {
collapsed: boolean; collapsed: boolean;
mobileOpen: boolean; mobileOpen: boolean;
content: LeftMenuContent; content: LeftMenuContent;
desktopMenuStyle: LeftMenuStyle; desktopMenuStyle: LeftMenuStyle;
openMenu: (content?: LeftMenuContent) => void; openMenu: (content?: LeftMenuContent) => void;
closeMenu: () => void; closeMenu: () => void;
toggleMenu: (content?: LeftMenuContent) => void; toggleMenu: (content?: LeftMenuContent) => void;
expandMenu: () => void; expandMenu: () => void;
collapseMenu: () => void; collapseMenu: () => void;
toggleCollapsed: () => void; toggleCollapsed: () => void;
setMenuContent: (content: LeftMenuContent | null) => void; setMenuContent: (content: LeftMenuContent | null) => void;
startResize: ReturnType<typeof useSidePanelMachine>['startResize']; startResize: ReturnType<typeof useSidePanelMachine>['startResize'];
}; };
type LeftMenuProviderProps = { type LeftMenuProviderProps = {
children: ReactNode; children: ReactNode;
defaultContent: LeftMenuContent; defaultContent: LeftMenuContent;
closeOnPathname?: string; closeOnPathname?: string;
}; };
const LeftMenuContext = createContext<LeftMenuContextValue | undefined>(undefined); const LeftMenuContext = createContext<LeftMenuContextValue | undefined>(undefined);
function readStoredCollapsed(): boolean { function readStoredCollapsed(): boolean {
if (!globalThis.window) { if (!globalThis.window) {
return false; return false;
} }
return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1'; return localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === '1';
} }
export function LeftMenuProvider({ export function LeftMenuProvider({
children, children,
defaultContent, 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, closeOnPathname,
onCloseOnPathname: handleCloseOnPathname, }: Readonly<LeftMenuProviderProps>) {
onEscape: closeMobile, const [collapsed, setCollapsed] = useState<boolean>(() => readStoredCollapsed());
}); const [mobileOpen, setMobileOpen] = useState(false);
const [content, setContent] = useState<LeftMenuContent>(defaultContent);
const defaultContentRef = useRef(defaultContent);
const desktopMenuStyle = useMemo<LeftMenuStyle>( useEffect(() => {
() => ({ const previousDefaultContent = defaultContentRef.current;
'--auth-sidebar-width': `${collapsed ? SIDEBAR_COLLAPSED_WIDTH : width}px`, defaultContentRef.current = defaultContent;
}), setContent((currentContent) => {
[collapsed, width], if (currentContent === previousDefaultContent) {
); return defaultContent;
}
return currentContent;
});
}, [defaultContent]);
const value = useMemo<LeftMenuContextValue>( useEffect(() => {
() => ({ if (!globalThis.window) {
collapsed, return;
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>; 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() { export function useLeftMenu() {
const ctx = useContext(LeftMenuContext); const ctx = useContext(LeftMenuContext);
if (!ctx) { if (!ctx) {
throw new Error('useLeftMenu must be used within LeftMenuProvider'); throw new Error('useLeftMenu must be used within LeftMenuProvider');
} }
return ctx; return ctx;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,26 +1,26 @@
export { createAuthContext } from './auth/createAuthContext'; export { createAuthContext } from './auth/createAuthContext';
export type { export type {
AuthContextValue, AuthContextValue,
AuthState, AuthState,
CreateAuthContextOptions, CreateAuthContextOptions,
} from './auth/createAuthContext'; } from './auth/createAuthContext';
export { decodeJwtPayload, isJwtExpired } from './auth/jwt'; export { decodeJwtPayload, isJwtExpired } from './auth/jwt';
export { createApiClient, ApiError } from './api/createApiClient'; export { createApiClient, ApiError } from './api/createApiClient';
export type { export type {
CreateApiClientConfig, CreateApiClientConfig,
RequestOptions, RequestOptions,
ResolveErrorInput, ResolveErrorInput,
} from './api/createApiClient'; } from './api/createApiClient';
export { buildListQuery } from './api/query'; export { buildListQuery } from './api/query';
export { createErrorResolver } from './errors/createErrorResolver'; export { createErrorResolver } from './errors/createErrorResolver';
export type { export type {
CreateErrorResolverConfig, CreateErrorResolverConfig,
ErrorCatalog, ErrorCatalog,
ResolveErrorMessageOptions, ResolveErrorMessageOptions,
} from './errors/createErrorResolver'; } from './errors/createErrorResolver';
export { useValidatedFields } from './hooks/useValidatedFields'; export { useValidatedFields } from './hooks/useValidatedFields';
@@ -33,9 +33,9 @@ export { useCooldownTimer } from './hooks/useCooldownTimer';
export { LeftMenuProvider, useLeftMenu } from './contexts/LeftMenuContext'; export { LeftMenuProvider, useLeftMenu } from './contexts/LeftMenuContext';
export type { export type {
LeftMenuContent, LeftMenuContent,
LeftMenuRenderState, LeftMenuRenderState,
LeftMenuStyle, LeftMenuStyle,
} from './contexts/LeftMenuContext'; } from './contexts/LeftMenuContext';
export { RightSidebarProvider, useRightSidebar } from './contexts/RightSidebarContext'; export { RightSidebarProvider, useRightSidebar } from './contexts/RightSidebarContext';
export type { RightSidebarContent, RightSidebarStyle } from './contexts/RightSidebarContext'; export type { RightSidebarContent, RightSidebarStyle } from './contexts/RightSidebarContext';

View File

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

View File

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

View File

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

View File

@@ -1,12 +1,12 @@
{ {
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"compilerOptions": { "compilerOptions": {
"noEmit": false, "noEmit": false,
"declaration": true, "declaration": true,
"emitDeclarationOnly": true, "emitDeclarationOnly": true,
"rootDir": "src", "rootDir": "src",
"outDir": "dist", "outDir": "dist",
"declarationMap": true "declarationMap": true
}, },
"include": ["src"] "include": ["src"]
} }

View File

@@ -1,17 +1,17 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2022", "target": "ES2022",
"module": "ESNext", "module": "ESNext",
"moduleResolution": "Bundler", "moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"], "lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx", "jsx": "react-jsx",
"strict": true, "strict": true,
"skipLibCheck": true, "skipLibCheck": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"allowImportingTsExtensions": false, "allowImportingTsExtensions": false,
"noEmit": true, "noEmit": true,
"types": ["react"] "types": ["react"]
}, },
"include": ["src"] "include": ["src"]
} }

View File

@@ -3,16 +3,16 @@ import react from '@vitejs/plugin-react';
import { resolve } from 'node:path'; import { resolve } from 'node:path';
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
build: { build: {
lib: { lib: {
entry: resolve(__dirname, 'src/index.ts'), entry: resolve(__dirname, 'src/index.ts'),
name: 'PanicCore', name: 'PanicCore',
formats: ['es'], formats: ['es'],
fileName: () => 'index.js', fileName: () => 'index.js',
},
rollupOptions: {
external: ['react'],
},
}, },
rollupOptions: {
external: ['react'],
},
},
}); });